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

restore(batch 11/28): 恢复被误删源码与文档

Agnes Agent 3 часов назад
Родитель
Сommit
0015098c94
100 измененных файлов с 20076 добавлено и 0 удалено
  1. 115 0
      cfc-frontend/.superpowers/sdd/task-5-report.md
  2. 18 0
      cfc-frontend/.superpowers/sdd/task-6-brief.md
  3. 144 0
      cfc-frontend/.superpowers/sdd/task-6-report.md
  4. 18 0
      cfc-frontend/.superpowers/sdd/task-7-brief.md
  5. 113 0
      cfc-frontend/.superpowers/sdd/task-7-report.md
  6. 16 0
      cfc-frontend/.superpowers/sdd/task-8-brief.md
  7. 138 0
      cfc-frontend/.superpowers/sdd/task-8-report.md
  8. 285 0
      cfc-frontend/AGENTS.md
  9. 285 0
      cfc-frontend/App.vue
  10. 2588 0
      cfc-frontend/INTERFACE_TEST_MATRIX.md
  11. 16 0
      cfc-frontend/__tests__/AdminPageTasksExcludeTemplate.contract.spec.js
  12. 17 0
      cfc-frontend/__tests__/ChildTaskExpiryReminder.contract.spec.js
  13. 32 0
      cfc-frontend/__tests__/RecipeNoFallback.contract.spec.js
  14. 19 0
      cfc-frontend/__tests__/TaskEarlyVisibility.contract.spec.js
  15. 18 0
      cfc-frontend/__tests__/TaskExcludeTemplate.contract.spec.js
  16. 21 0
      cfc-frontend/__tests__/TaskExpiry.contract.spec.js
  17. 15 0
      cfc-frontend/__tests__/TaskExpiryCrossDayOnly.contract.spec.js
  18. 21 0
      cfc-frontend/__tests__/TaskNoDeadlineVisible.contract.spec.js
  19. 43 0
      cfc-frontend/__tests__/TaskStageReminder.contract.spec.js
  20. 359 0
      cfc-frontend/__tests__/aiyunyi/aiyunyi.videoPage.contract.test.js
  21. 270 0
      cfc-frontend/__tests__/aiyunyi/report-upload.uploadCard.contract.test.js
  22. 75 0
      cfc-frontend/__tests__/api/api.indicator.test.js
  23. 1321 0
      cfc-frontend/__tests__/api/api.test.js
  24. 159 0
      cfc-frontend/__tests__/components/FamilyRelationGraph.test.js
  25. 75 0
      cfc-frontend/__tests__/config/config.test.js
  26. 342 0
      cfc-frontend/__tests__/diet/recommendation.healthAdjustUi.test.js
  27. 316 0
      cfc-frontend/__tests__/family-join/join-form.required-info.test.js
  28. 55 0
      cfc-frontend/__tests__/games/1a2b.test.js
  29. 278 0
      cfc-frontend/__tests__/pages/article-center/articleDetailVideoFullscreen.contract.test.js
  30. 368 0
      cfc-frontend/__tests__/pages/article-center/articleSearch.contract.test.js
  31. 329 0
      cfc-frontend/__tests__/pages/article-center/articleTagFilter.contract.test.js
  32. 291 0
      cfc-frontend/__tests__/pages/diet/recommendation.pagination.test.js
  33. 328 0
      cfc-frontend/__tests__/pages/diet/recommendation.participantSelect.test.js
  34. 466 0
      cfc-frontend/__tests__/pages/diet/recommendation.uiRework.test.js
  35. 494 0
      cfc-frontend/__tests__/pages/diet/recommendation.viewKeyAndDelete.test.js
  36. 105 0
      cfc-frontend/__tests__/pages/family-members.joinRequestCardInfo.test.js
  37. 77 0
      cfc-frontend/__tests__/pages/growth-main/growthGrid.layout.test.js
  38. 329 0
      cfc-frontend/__tests__/pages/growth-main/growthHistory.dayGroupView.test.js
  39. 318 0
      cfc-frontend/__tests__/pages/growth-main/growthHistory.view.test.js
  40. 214 0
      cfc-frontend/__tests__/pages/health-main/healthMain.redesign.contract.test.js
  41. 411 0
      cfc-frontend/__tests__/pages/health/aiyunyi.detectPage.contract.test.js
  42. 403 0
      cfc-frontend/__tests__/pages/health/aiyunyi.reportDetail.contract.test.js
  43. 316 0
      cfc-frontend/__tests__/pages/health/health-guhe-v2-display.contract.test.js
  44. 172 0
      cfc-frontend/__tests__/pages/health/healthPlanSummary.memberIdScope.test.js
  45. 216 0
      cfc-frontend/__tests__/pages/health/healthSurvey.incrementalSave.test.js
  46. 148 0
      cfc-frontend/__tests__/pages/health/healthSurvey.lifestyleSave.test.js
  47. 284 0
      cfc-frontend/__tests__/pages/health/healthSurvey.memberPicker.test.js
  48. 208 0
      cfc-frontend/__tests__/pages/health/healthSurvey.reviewMultiMember.test.js
  49. 53 0
      cfc-frontend/__tests__/pages/index-home.quickCompleteOverdue.test.js
  50. 143 0
      cfc-frontend/__tests__/pages/index-home/task-today-overdue-visible.contract.test.js
  51. 157 0
      cfc-frontend/__tests__/pages/profile-main/assetsEntry.contract.test.js
  52. 116 0
      cfc-frontend/__tests__/pages/profile-main/bottomMenuOverflow.contract.test.js
  53. 231 0
      cfc-frontend/__tests__/pages/shop/cartLayout.contract.test.js
  54. 224 0
      cfc-frontend/__tests__/pages/shop/checkout.couponAfterAddressReturn.spec.js
  55. 33 0
      cfc-frontend/__tests__/pages/shop/checkout.couponAutoSelect.spec.js
  56. 32 0
      cfc-frontend/__tests__/pages/shop/order-detail.refundAndBuyAgain.spec.js
  57. 424 0
      cfc-frontend/__tests__/pages/signature/signature.canvas2d.test.js
  58. 264 0
      cfc-frontend/__tests__/pages/signature/signature.consignee-editor.test.js
  59. 186 0
      cfc-frontend/__tests__/pages/signature/signature.consignee.test.js
  60. 134 0
      cfc-frontend/__tests__/pages/signature/signature.healthPlan.test.js
  61. 137 0
      cfc-frontend/__tests__/pages/signature/signature.healthPlanSummary.test.js
  62. 177 0
      cfc-frontend/__tests__/pages/signature/signature.landscape.contract.test.js
  63. 136 0
      cfc-frontend/__tests__/pages/signature/signature.landscape.superseded.js
  64. 242 0
      cfc-frontend/__tests__/pages/signature/signature.openPage.test.js
  65. 320 0
      cfc-frontend/__tests__/pages/signature/signature.routeIntegrate.test.js
  66. 336 0
      cfc-frontend/__tests__/pages/tasks/taskHistory.view.test.js
  67. 67 0
      cfc-frontend/__tests__/setup.js
  68. 99 0
      cfc-frontend/__tests__/specs/coupon-claimed-actions.test.js
  69. 331 0
      cfc-frontend/__tests__/specs/report-upload-guide-config.test.js
  70. 59 0
      cfc-frontend/__tests__/specs/shop-price-sort.test.js
  71. 52 0
      cfc-frontend/__tests__/specs/team-invite-share.test.js
  72. 201 0
      cfc-frontend/__tests__/store/store.test.js
  73. 44 0
      cfc-frontend/__tests__/utils/bundle-pricing.test.js
  74. 38 0
      cfc-frontend/__tests__/utils/countAvailableCoupons.test.js
  75. 126 0
      cfc-frontend/__tests__/utils/dwellTracker.test.js
  76. 127 0
      cfc-frontend/__tests__/utils/exerciseTypes.test.js
  77. 122 0
      cfc-frontend/__tests__/utils/fontScale.test.js
  78. 213 0
      cfc-frontend/__tests__/utils/format.test.js
  79. 46 0
      cfc-frontend/__tests__/utils/image-picker.test.js
  80. 65 0
      cfc-frontend/__tests__/utils/indicator-change.test.js
  81. 247 0
      cfc-frontend/__tests__/utils/indicator-favorite.test.js
  82. 76 0
      cfc-frontend/__tests__/utils/memberNormalize.resolveCheckin.test.js
  83. 73 0
      cfc-frontend/__tests__/utils/membershipGate.test.js
  84. 63 0
      cfc-frontend/__tests__/utils/signature-bus.test.js
  85. 87 0
      cfc-frontend/__tests__/utils/team-tree.test.js
  86. 79 0
      cfc-frontend/__tests__/utils/wuxing-sandbox.test.js
  87. 57 0
      cfc-frontend/__tests__/vue-transform.js
  88. 5 0
      cfc-frontend/babel.config.js
  89. 4 0
      cfc-frontend/build_err.txt
  90. 58 0
      cfc-frontend/common/uni.css
  91. 9 0
      cfc-frontend/components/AIFloatingAvatar.vue
  92. 162 0
      cfc-frontend/components/ArticleFeed.vue
  93. 56 0
      cfc-frontend/components/BadgeGrid.vue
  94. 68 0
      cfc-frontend/components/BaseBadge.vue
  95. 96 0
      cfc-frontend/components/BaseCard.vue
  96. 89 0
      cfc-frontend/components/BaseEmpty.vue
  97. 76 0
      cfc-frontend/components/BaseLoading.vue
  98. 164 0
      cfc-frontend/components/BasePrimaryButton.vue
  99. 173 0
      cfc-frontend/components/ConfigurableGuide.vue
  100. 850 0
      cfc-frontend/components/ContentSharePoster.vue

+ 115 - 0
cfc-frontend/.superpowers/sdd/task-5-report.md

@@ -0,0 +1,115 @@
+# 任务 5 实现报告:多接口并发页面 FamilyEmptyState 改造
+
+## 改造概览
+
+对 6 个 uni-app (Vue 2) 小程序页面/组件进行改造,当家庭数据区(familyId 为空)时显示 `FamilyEmptyState` 占位组件。
+
+## 改造文件列表
+
+### 1. `pages/home-pages/parent-index.vue`
+- **改动行数**:+60 / -4
+- **家庭数据区**:5 个卡片区,每块独立 v-if/v-else,type="card"
+  1. 家庭健康排行榜(FamilyHealthRanking,getFamilyRanking)
+  2. 家庭挑战区域(getChallengeList)
+  3. 健康圈入口(getCircleRanking)
+  4. 成长数据卡片区(getEnergyOverview)
+  5. 待处理事项卡片区(含 pendingReviewTasks + pendingReviewWishes/getPendingWishes)
+- **grep 验证**:
+  - `FamilyEmptyState`: 5 次
+  - `hasFamily`: 9 次(computed 定义 1 + v-if 使用 5 + v-else 注释等)
+
+### 2. `pages/index-home/index.vue`
+- **改动行数**:+29 / -5
+- **家庭数据区**:2 个卡片区,type="card"
+  1. 能量沙盘(WuxingSandbox/getFamilyEnergySandbox)
+  2. 家庭挑战任务(getChallengeList)
+- **grep 验证**:
+  - `FamilyEmptyState`: 2 次
+  - `hasFamily`: 4 次
+
+### 3. `pages/health/challenge-manage.vue`
+- **改动行数**:+19 / -2
+- **家庭数据区**:2 个区域,type="card"
+  1. 模板推荐区(快速创建)
+  2. 挑战列表(我的挑战)
+- **computed 追加**:新建 computed 对象,追加 `hasFamily` 计算属性
+- **grep 验证**:
+  - `FamilyEmptyState`: 2 次
+  - `hasFamily`: 4 次
+
+### 4. `pages/mind/index.vue`
+- **改动行数**:+116 / -43
+- **家庭数据区**:3 个卡片区,type="card"
+  1. 能量条 + 心理报告卡片(getEnergyOverview)
+  2. EMI 心理测评报告卡片(getEmiReport)
+  3. 肠脑轴情绪卡片(gutIndicators,通过 uni.request 调用)
+- **grep 验证**:
+  - `FamilyEmptyState`: 3 次
+  - `hasFamily`: 5 次
+
+### 5. `components/member-detail-sections/mind-section.vue`
+- **改动行数**:+11 / -3
+- **家庭数据区**:整段 section,type="block"
+  - 亲密关系评分 + 联系人 + 健康告警 + 里程碑
+- **computed 追加**:在现有 computed 对象中追加 `hasFamily`
+- **grep 验证**:
+  - `FamilyEmptyState`: 2 次(1 处 v-else + 1 处注释)
+  - `hasFamily`: 3 次
+
+### 6. `pages/home-pages/child-index.vue`
+- **改动行数**:+48 / -12
+- **家庭数据区**:2 个卡片区,type="card"
+  1. 五维能量沙盘 + 家庭能量横条(getFamilyEnergySandbox / getEnergyOverview)
+  2. 最近能量变动日志(getEnergyLogs)
+- **grep 验证**:
+  - `FamilyEmptyState`: 2 次
+  - `hasFamily`: 4 次
+
+## 验证结果
+
+### grep 验证(每个文件 FamilyEmptyState ≥ 2,hasFamily ≥ 2)
+
+```
+=== pages/home-pages/parent-index.vue ===
+FamilyEmptyState: 5
+hasFamily: 9
+
+=== pages/index-home/index.vue ===
+FamilyEmptyState: 2
+hasFamily: 4
+
+=== pages/health/challenge-manage.vue ===
+FamilyEmptyState: 2
+hasFamily: 4
+
+=== pages/mind/index.vue ===
+FamilyEmptyState: 3
+hasFamily: 5
+
+=== components/member-detail-sections/mind-section.vue ===
+FamilyEmptyState: 2
+hasFamily: 3
+
+=== pages/home-pages/child-index.vue ===
+FamilyEmptyState: 2
+hasFamily: 4
+```
+
+### git diff 验证(仅 6 个目标文件)
+
+```
+.../member-detail-sections/mind-section.vue        |  11 +-
+cfc-frontend/pages/health/challenge-manage.vue     |  19 +++-
+cfc-frontend/pages/home-pages/child-index.vue      |  48 +++++----
+cfc-frontend/pages/home-pages/parent-index.vue     |  60 +++++++----
+cfc-frontend/pages/index-home/index.vue            |  29 ++++--
+cfc-frontend/pages/mind/index.vue                  | 116 ++++++++++++---------
+6 files changed, 181 insertions(+), 102 deletions(-)
+```
+
+## 实现要点
+
+1. **computed.hasFamily**:6 个文件均在现有(或新建)computed 对象中追加 `hasFamily: function() { return this.$store.getters.hasFamily }`
+2. **模板改造**:每块家庭数据区用 `<view v-if="hasFamily">...</view><view v-else><FamilyEmptyState type="card" /></view>` 包裹
+3. **type 参数**:mind-section.vue 使用 type="block",其余均使用 type="card"
+4. **不改动**:页头/导航/非家庭 UI、store/api.js/main.js/FamilyEmptyState 组件、showModal 等业务逻辑

+ 18 - 0
cfc-frontend/.superpowers/sdd/task-6-brief.md

@@ -0,0 +1,18 @@
+### 任务 6:单接口页面(批次 A — 9 个)
+
+| 文件 | 接口 | type |
+|---|---|---|
+| `components/DimensionProducts.vue` | getDimensionProducts | card |
+| `components/FamilyMemberStrip.vue` | getPendingFamilyRequests | card |
+| `pages/action-detail/interaction-log.vue` | addInteraction | card |
+| `pages/action-detail/member-action-detail.vue` | getEnergyOverview | card |
+| `pages/assessment/purchase.vue` | createAssessmentOrder | card |
+| `pages/body-detail/member-body-detail.vue` | getEnergyOverview | card |
+| `pages/body/index.vue` | getEnergyOverview | card |
+| `pages/body/member-body-detail.vue` | getEnergyOverview | card |
+| `pages/energy/detail.vue` | getEnergyLogs | list |
+
+- [ ] **步骤 1-9:逐一改造**(同任务 5 模式)
+
+---
+

+ 144 - 0
cfc-frontend/.superpowers/sdd/task-6-report.md

@@ -0,0 +1,144 @@
+# 任务 6 实现报告 — 单接口页面(批次 A · 9 个)
+
+**基准提交:** 7b4c3eea  
+**完成时间:** 2026-08-06  
+**任务说明:** 为 9 个组件/页面添加 `v-if="hasFamily"` 包裹家庭数据区,无家庭时渲染 `<FamilyEmptyState type="card/list" />`
+
+---
+
+## 改造文件清单
+
+| # | 文件 | 接口 | type | 改动行数 |
+|---|---|---|---|---|
+| 1 | `components/DimensionProducts.vue` | getDimensionProducts | card | 已在任务 4 完成 |
+| 2 | `components/FamilyMemberStrip.vue` | getPendingFamilyRequests | card | +8 |
+| 3 | `pages/action-detail/interaction-log.vue` | addInteraction | card | +11 |
+| 4 | `pages/action-detail/member-action-detail.vue` | getEnergyOverview | card | +8 |
+| 5 | `pages/assessment/purchase.vue` | createAssessmentOrder | card | +11 |
+| 6 | `pages/body-detail/member-body-detail.vue` | getEnergyOverview | card | +8 |
+| 7 | `pages/body/index.vue` | getEnergyOverview | card | +8 |
+| 8 | `pages/body/member-body-detail.vue` | getEnergyOverview | card | +8 |
+| 9 | `pages/energy/detail.vue` | getEnergyLogs | list | +10 |
+
+---
+
+## 每个文件的改动详情
+
+### 1. `components/DimensionProducts.vue`
+- **状态:** 已在任务 4 完成
+- **改动:** 包裹产品数据区 `<view v-if="hasFamily">` + `<FamilyEmptyState type="card" />`
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 2. `components/FamilyMemberStrip.vue`
+- **改动:**
+  - 将外层 `v-if="(members && members.length > 0) || isAdmin"` 替换为 `v-if="hasFamily"`
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 在模板末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+- **保留不动:** showModal 同意/拒绝加入申请的业务逻辑(approveRequest/rejectRequest)
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 3. `pages/action-detail/interaction-log.vue`
+- **改动:**
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 将家庭数据区(4 个 form-section + submit-bar)包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+  - 页头 `<view class="page-header">` 保留不动
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 4. `pages/action-detail/member-action-detail.vue`
+- **改动:**
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 将五维能量条至底部占位之间的所有内容包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+  - 页头导航栏(nav-bar)保留不动
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 5. `pages/assessment/purchase.vue`
+- **改动:**
+  - 在 `data()` 后添加 `computed` 对象含 `hasFamily` 计算属性
+  - 将页面头部标题之后的所有内容(规划师选择、任务模板、费用明细、提交按钮)包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 6. `pages/body-detail/member-body-detail.vue`
+- **改动:**
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 将五维能量条至底部占位之间的所有内容包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+  - 页头导航栏保留不动
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 7. `pages/body/index.vue`
+- **改动:**
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 将五维能量条(FamilyEnergyBar)至底部占位(bottom-spacer)及 AIFloatingAvatar 包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+  - 保留:品牌头部、雷达图、家庭成员选择条、游客专属区块
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 8. `pages/body/member-body-detail.vue`
+- **改动:**
+  - 在 `computed` 中添加 `hasFamily` 计算属性
+  - 将五维能量条至底部占位之间的所有内容包裹在 `<view v-if="hasFamily">...</view>` 中
+  - 末尾添加 `<view v-else><FamilyEmptyState type="card" /></view>`
+  - 页头导航栏保留不动
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+### 9. `pages/energy/detail.vue`
+- **改动:**
+  - 在 `data()` 后添加 `computed` 对象含 `hasFamily` 计算属性
+  - 流水列表区(`.logs-section`)添加 `v-if="hasFamily"` 条件(与原有 `v-if="!loading"` 并存)
+  - 末尾添加 `<view v-else><FamilyEmptyState type="list" /></view>`
+  - 保留:dim-header(维度信息)、BaseLoading
+- **grep 验证:** `FamilyEmptyState` 出现 1 次,`hasFamily` 出现 3 次
+
+---
+
+## Grep 验证输出
+
+```
+=== components/DimensionProducts.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== components/FamilyMemberStrip.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/action-detail/interaction-log.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/action-detail/member-action-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/assessment/purchase.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/body-detail/member-body-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/body/index.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/body/member-body-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+=== pages/energy/detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+```
+
+---
+
+## 注意事项
+
+1. **DimensionProducts.vue** — 已在之前任务中完成,本次验证其正确性
+2. **FamilyMemberStrip.vue** — 保留了 `approveRequest`/`rejectRequest` 的 showModal 业务逻辑,未做任何改动
+3. **energy/detail.vue** — 唯一使用 `type="list"` 的文件,其余 8 个均使用 `type="card"`
+4. **无新增 import/components 注册** — FamilyEmptyState 已在 main.js 全局注册,各文件无需额外引入
+5. **无禁用语法** — 未使用可选链 `?.`、`:key` 表达式、中文 CSS 类名、CSS Grid
+
+---
+
+## 后续任务
+
+- **任务 7:** 单接口页面(批次 B · 9 个)
+- **任务 8:** 单接口页面(批次 C · 5 个)+ 特例(2 个)

+ 18 - 0
cfc-frontend/.superpowers/sdd/task-7-brief.md

@@ -0,0 +1,18 @@
+### 任务 7:单接口页面(批次 B — 9 个)
+
+| 文件 | 接口 | type |
+|---|---|---|
+| `pages/growth/create.vue` | createGrowthRecord | card |
+| `pages/growth/index.vue` | generateInviteCard | card |
+| `pages/health/gut-index.vue` | getLatestHealthReport | card |
+| `pages/mind-detail/member-mind-detail.vue` | getEnergyOverview | card |
+| `pages/mind/member-mind-detail.vue` | getEnergyOverview | card |
+| `pages/parent/child-detail.vue` | getPendingWishes | card |
+| `pages/parent/plans/index.vue` | listFamilyPlans | card |
+| `pages/parent/wishes/index.vue` | getPendingWishes | card |
+| `pages/rewards/badge.vue` | getFamilyBadgeRanking | card |
+
+- [ ] **步骤 1-9:逐一改造**
+
+---
+

+ 113 - 0
cfc-frontend/.superpowers/sdd/task-7-report.md

@@ -0,0 +1,113 @@
+# 任务 7 实现报告 — 单接口页面家庭数据区改造(批次 B)
+
+## 概览
+
+改造 9 个 uni-app(Vue 2)小程序页面,为每个页面的家庭数据区添加 `v-if="hasFamily"` / `v-else` 渲染 `FamilyEmptyState type="card"` 的条件包裹。
+
+- 基准提交:`7b4c3eea`
+- 改动文件:仅上述 9 个页面文件
+- 不动文件:`store/index.js` / `utils/api.js` / `main.js` / `FamilyEmptyState.vue` / 其他页面(均为任务 1-4 遗留改动)
+
+## 改动明细
+
+| 文件 | FamilyEmptyState | hasFamily | 改动说明 |
+|---|---:|---:|---|
+| `pages/growth/create.vue` | 1 | 3 | 已在上游任务改造,本次确认无重复改动 |
+| `pages/growth/index.vue` | 1 | 5 | 新增 `hasFamily` computed;children-list / records-section / footer-btn 加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/health/gut-index.vue` | 1 | 3 | 新增 computed 块含 `hasFamily`;scroll-view 内容加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/mind-detail/member-mind-detail.vue` | 1 | 3 | 在现有 computed 对象中追加 `hasFamily`;能量条至底部占位区域加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/mind/member-mind-detail.vue` | 1 | 3 | 同上 |
+| `pages/parent/child-detail.vue` | 1 | 3 | 在现有 computed 对象中追加 `hasFamily`;加载状态 + template 内容区加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/parent/plans/index.vue` | 1 | 3 | 新增 computed 块含 `hasFamily`;header 至 plan-list 区域加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/parent/wishes/index.vue` | 1 | 3 | 在现有 computed 对象中追加 `hasFamily`;整个 wish-list 内容区加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+| `pages/rewards/badge.vue` | 1 | 3 | 在现有 computed 对象中追加 `hasFamily`;stats-card 至底部弹窗区域加 `v-if="hasFamily"`,v-else 渲染 FamilyEmptyState |
+
+## 验证输出
+
+### grep 验证
+
+```
+=== pages/growth/create.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/growth/index.vue ===
+FamilyEmptyState: 1
+hasFamily: 5
+
+=== pages/health/gut-index.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/mind-detail/member-mind-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/mind/member-mind-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/parent/child-detail.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/parent/plans/index.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/parent/wishes/index.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+
+=== pages/rewards/badge.vue ===
+FamilyEmptyState: 1
+hasFamily: 3
+```
+
+所有文件均满足:`grep -c "FamilyEmptyState" ≥ 1` 且 `grep -c "hasFamily" ≥ 2`。
+
+### git diff --stat(仅任务 7 改动)
+
+```
+ cfc-frontend/pages/growth/create.vue               | 67 +++++++++++++---------
+ cfc-frontend/pages/growth/index.vue                | 12 +++-
+ cfc-frontend/pages/health/gut-index.vue            | 11 +++-
+ .../pages/mind-detail/member-mind-detail.vue       |  8 +++
+ cfc-frontend/pages/mind/member-mind-detail.vue     |  8 +++
+ cfc-frontend/pages/parent/child-detail.vue         |  9 +++
+ cfc-frontend/pages/parent/plans/index.vue          | 11 ++++
+ cfc-frontend/pages/parent/wishes/index.vue         |  8 +++
+ cfc-frontend/pages/rewards/badge.vue               |  8 +++
+ 9 files changed, 110 insertions(+), 32 deletions(-)
+```
+
+## 改造模式
+
+每个文件均按以下模式改造:
+
+1. **computed**:组件已有 computed 对象则在现有对象中追加 `hasFamily`;无 computed 对象则新建:
+   ```js
+   hasFamily: function() {
+     return this.$store.getters.hasFamily
+   }
+   ```
+
+2. **模板**:在接口成功回调渲染的家庭数据区外层加 `v-if="hasFamily"`,末尾补 `v-else` 块:
+   ```html
+   <view v-if="hasFamily">
+     <!-- 原有内容一字不动 -->
+   </view>
+   <view v-else>
+     <FamilyEmptyState type="card" />
+   </view>
+   ```
+
+3. **FamilyEmptyState** 已通过 `main.js` 全局注册,各组件无需 import 或 components 注册。
+
+## 注意事项
+
+- `pages/growth/create.vue` 在本次任务开始前已由上游任务改造完成,本次确认其状态正确,未做额外改动。
+- `pages/growth/index.vue` 的 `hasFamily` 计数为 5(computed 定义 1 + v-if 模板 2 + footer-btn 条件 2),其余文件均为 3(computed 定义 1 + v-if 模板 1 + v-else 模板 1)。
+- 未触碰 `store/index.js`、`utils/api.js`、`main.js`、`FamilyEmptyState.vue` 及其他非目标页面。
+- 未使用 `?.`、`:key` 表达式、中文 CSS 类名、`new Date(string)`、`uni.getSystemInfoSync()`、CSS Grid。
+- 未 commit 任何更改。

+ 16 - 0
cfc-frontend/.superpowers/sdd/task-8-brief.md

@@ -0,0 +1,16 @@
+### 任务 8:单接口页面(批次 C — 5 个)+ 特例(2 个)
+
+| 文件 | 接口 | type |
+|---|---|---|
+| `pages/share/index.vue` | getFamilyFootprint | card |
+| `pages/teacher/teacher-profile.vue` | generateParentInvite | card |
+| `pages/user-edit/user-edit.vue` | requestJoinByCode | card |
+| `pages/wisdom-detail/member-wisdom-detail.vue` | getEnergyOverview | card |
+| `pages/wisdom/member-wisdom-detail.vue` | getEnergyOverview | card |
+| `pages/profile-extra/family-members.vue` | 特例:仅用 `v-if="hasFamily"` 包住邀请二维码区(L207 附近),不套 FamilyEmptyState(页面本身是家庭管理入口) | — |
+| `pages/invite/join.vue` | 特例:**不动**(申请加入页本身是无家庭态唯一可执行动作) | — |
+
+- [ ] **步骤 1-7:逐一处理**
+
+---
+

+ 138 - 0
cfc-frontend/.superpowers/sdd/task-8-report.md

@@ -0,0 +1,138 @@
+# Task 8 实现报告 — 单接口页面接入家庭空态(批次 C)
+
+## 概览
+
+| 文件 | 接口 | 改动类型 | 改动行数(新增/删除) |
+|------|------|----------|----------------------|
+| `pages/share/index.vue` | getFamilyFootprint | 常规(FamilyEmptyState type="card") | +15 / −2 |
+| `pages/teacher/teacher-profile.vue` | generateParentInvite | 常规(FamilyEmptyState type="card") | +8 / −0 |
+| `pages/user-edit/user-edit.vue` | requestJoinByCode | 常规(FamilyEmptyState type="card") | +44 / −28 |
+| `pages/wisdom-detail/member-wisdom-detail.vue` | getEnergyOverview | 常规(FamilyEmptyState type="card") | +11 / −0 |
+| `pages/wisdom/member-wisdom-detail.vue` | getEnergyOverview | 常规(FamilyEmptyState type="card") | +11 / −0 |
+| `pages/profile-extra/family-members.vue` | 特例(不套 FamilyEmptyState) | +6 / −1 |
+| `pages/invite/join.vue` | 特例(零改动) | — | — |
+
+**总计**:6 文件,79 行新增,22 行删除。
+
+---
+
+## 常规改造(5 文件)
+
+每个文件均做了以下两件事:
+
+1. **script 追加 computed**
+   ```js
+   computed: {
+     hasFamily: function() {
+       return this.$store.getters.hasFamily
+     }
+   }
+   ```
+   已有 computed 的对象则追加字段;无 computed 的则新增 computed 块。
+
+2. **模板加 v-if/v-else 包裹**
+   - 原有数据区内容保持一字不动
+   - 外层用 `<view v-if="hasFamily">` 包裹
+   - 对应 `<view v-else><FamilyEmptyState type="card" /></view>`
+   - FamilyEmptyState 已全局注册(main.js),未在任何组件内 import
+
+### 各文件详情
+
+#### 1. `pages/share/index.vue`
+- `sp-header`、`sp-body`、`sp-footer` 三个数据区均改为 `v-if="hasFamily && ..."`(保留原条件组合)
+- `sp-qr`(扫码区)保持不动,作为对外引流入口
+- `v-else` 插在第 24 行(sp-footer 之后、sp-qr 之前)
+- grep 验证:`FamilyEmptyState` = 1,`hasFamily` = 5
+
+#### 2. `pages/teacher/teacher-profile.vue`
+- `switch-out-btn`(切换家长端)保持不动(全局可见)
+- `user-card` + `menu-list` 整体用 `<view v-if="hasFamily">` 包裹
+- `v-else` 紧跟 `</view>` 闭合标签之后
+- `modal-mask` 密码弹窗保持不动
+- grep 验证:`FamilyEmptyState` = 1,`hasFamily` = 3
+
+#### 3. `pages/user-edit/user-edit.vue`
+- 角色选择区(`role-select-section`)保持不动(新用户流程可见)
+- `form-section` 的 `v-if="isEdit"` 改为 `v-if="isEdit && hasFamily"`
+- `v-else-if="isEdit"` 分支插入 `FamilyEmptyState type="card"`
+- computed 中追加 `hasFamily`(原已有 5 个 computed 字段)
+- grep 验证:`FamilyEmptyState` = 1,`hasFamily` = 3
+
+#### 4. `pages/wisdom-detail/member-wisdom-detail.vue`
+- `nav-bar` 保持不动
+- 从 `FamilyEnergyBar` 到 `DimensionProducts` 的整个数据区用 `<view v-if="hasFamily">` 包裹
+- `v-else` 插入在 `</view>` 之后、`bottom-spacer` 之前
+- 新增 computed 块含 `hasFamily`
+- grep 验证:`FamilyEmptyState` = 1,`hasFamily` = 3
+
+#### 5. `pages/wisdom/member-wisdom-detail.vue`
+- 与第 4 文件完全对称(同名结构)
+- grep 验证:`FamilyEmptyState` = 1,`hasFamily` = 3
+
+---
+
+## 特例处理(2 文件)
+
+### 6. `pages/profile-extra/family-members.vue`
+- 仅在 `SharePoster` 上添加 `v-if="hasFamily"`,并补充 `v-else` 渲染简短提示文字:
+  ```vue
+  <SharePoster v-if="hasFamily" ... />
+  <view v-else class="empty-tip">暂无家庭成员,请先创建或加入家庭</view>
+  ```
+- 在 computed 中追加 `hasFamily`
+- 在 `<style>` 末尾添加 `.empty-tip` 样式(居中文字,padding 60rpx 0,字号 28rpx,颜色 #999)
+- **未使用** FamilyEmptyState 组件
+- 保留已有的 `showModal`(同意/拒绝加入申请弹窗)等业务逻辑不动
+- grep 验证:`hasFamily` = 3,`FamilyEmptyState` = 0
+
+### 7. `pages/invite/join.vue`
+- **零改动**。`git diff HEAD -- pages/invite/join.vue` 输出 0 行,确认完全未触碰。
+- 原因:申请加入页本身是无家庭态唯一可执行动作,不套空态。
+
+---
+
+## 验证结果
+
+### Grep 计数验证(全部通过)
+
+```
+pages/share/index.vue           : FamilyEmptyState=1  hasFamily=5   ✓ (≥1, ≥2)
+pages/teacher/teacher-profile.vue: FamilyEmptyState=1  hasFamily=3   ✓ (≥1, ≥2)
+pages/user-edit/user-edit.vue   : FamilyEmptyState=1  hasFamily=3   ✓ (≥1, ≥2)
+pages/wisdom-detail/member-wisdom-detail.vue: FamilyEmptyState=1  hasFamily=3   ✓ (≥1, ≥2)
+pages/wisdom/member-wisdom-detail.vue: FamilyEmptyState=1  hasFamily=3   ✓ (≥1, ≥2)
+pages/profile-extra/family-members.vue: FamilyEmptyState=0  hasFamily=3 ✓ (==0, ≥2)
+```
+
+### Git diff 范围验证
+
+```
+$ git diff --stat HEAD -- \
+    pages/share/index.vue \
+    pages/teacher/teacher-profile.vue \
+    pages/user-edit/user-edit.vue \
+    pages/wisdom-detail/member-wisdom-detail.vue \
+    pages/wisdom/member-wisdom-detail.vue \
+    pages/profile-extra/family-members.vue
+
+6 files changed, 79 insertions(+), 22 deletions(-)
+```
+
+`pages/invite/join.vue` 不在 diff 范围内(0 行改动)。
+
+---
+
+## 严格遵守的约束
+
+- ✅ 未改动 store/index.js、utils/api.js、main.js、FamilyEmptyState 组件
+- ✅ 未改动这 6 个文件之外的任何文件
+- ✅ FamilyEmptyState 未在任何组件内 import/components 注册
+- ✅ 未使用 `?.` 可选链
+- ✅ 未使用 CSS Grid
+- ✅ 未在 `:key` 中使用表达式
+- ✅ 未在模板中调用方法绑定 class
+- ✅ 未删除或重构任何原有逻辑
+- ✅ 未调整任何原有样式(新增 .empty-tip 除外)
+- ✅ 未进行 git commit
+- ✅ family-members.vue 中已有的 showModal 业务逻辑保留不动
+- ✅ 无中文 CSS 类名

+ 285 - 0
cfc-frontend/AGENTS.md

@@ -0,0 +1,285 @@
+# zxyj-frontend
+
+uni-app 微信小程序前端,Vue 2 语法,家庭教育任务管理。
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| 页面组件 | `pages/*/` | login, index, tasks, rewards, profile, guide, games等 |
+| 页面注册 | `pages.json` | TabBar配置和页面路径 |
+| 应用配置 | `manifest.json` | AppID: `wx5ba8038ef16fb245` |
+| 全局样式 | `uni.scss` | SCSS变量和全局样式 |
+| 应用入口 | `App.vue` | 全局生命周期和配置 |
+| 组件库 | `components/` | 地址选择器、任务卡片等可复用组件 |
+| API配置 | `config/` | baseUrl和请求封装 |
+
+## STRUCTURE
+
+### 主包(主包 = `pages.json` 的 `pages` 数组)
+
+仅含 5 个 TabBar 页面,主包大小已压缩至 ~1MB 以下:
+
+| 路径 | 说明 |
+|------|------|
+| `pages/index/index` | 首页(未登录态引流页 + 角色路由跳转) |
+| `pages/mind/index` | 心维度首页 |
+| `pages/body/index` | 身维度首页 |
+| `pages/wisdom/index` | 智维度首页 |
+| `pages/wealth/index` | 富维度首页 |
+
+> **登录用户路由**:`pages/index/index` 中 `parent-index` 和 `child-index` 已从静态组件改为 `redirectTo` 跳转到分包页面,不再计入主包体积。
+
+### 分包(`pages.json` 的 `subPackages` 数组,共 45 个)
+
+主要分包(按 `root`):
+
+| Root | 内容 |
+|------|------|
+| `pages/teacher` | 成长规划师中心(7 页) |
+| `pages/guide` | 任务模板、邀请、绑定等(11 页) |
+| `pages/parent` | 家长端市场、孩子详情(3 页) |
+| `pages/child` | 孩子端任务、心愿(2 页) |
+| `pages/tasks` | 任务列表/创建/审核(4 页) |
+| `pages/wishes` | 心愿管理(3 页) |
+| `pages/rewards` | 心愿单/勋章墙(2 页) |
+| `pages/games` | 小游戏(5 页) |
+| `pages/assessment` | 测评申请/报告(5 页) |
+| `pages/dan-assessment` | DAN 测评报告(1 页) |
+| `pages/growth` | 成长记录(6 页) |
+| `pages/shop` | 商城(15 页) |
+| `pages/vendor` | 服务商入驻/管理(5 页) |
+| `pages/health` | 健康功能(18 页) |
+| `pages/mind-detail` | 心智详情(11 页) |
+| `pages/body-detail` | 身体详情(6 页) |
+| `pages/wisdom-detail` | 智慧详情(4 页) |
+| `pages/action-detail` | 行动详情(4 页) |
+| `pages/tianpan` | 家庭天盘(6 页) |
+| `pages/article-center` | 文章中心(4 页) |
+| `pages/activity` | 活动(3 页) |
+| `pages/promotion` | 财富中心/推广(6 页) |
+| `pages/membership` | 会员(3 页) |
+| `pages/index` | 原主包页面(parent-index, child-index, member-home-detail) |
+| `pages/login` | 登录页 |
+| `pages/share` | 健康足迹 |
+| `pages/profile` | 个人中心(profile + index) |
+| `pages/profile-extra` | 孩子管理/优惠券(6 页) |
+| ... 共 45 个分包 | 详见 `pages.json` |
+
+> **注意**:分包页面在首次访问时异步下载,主包只加载必要的 TabBar 页面,确保主包 < 1.5MB。
+
+## TabBar 配置
+
+pages.json 中定义 5 个 TabBar 页面(TabBar 文案,非五维维度名):
+- 首页: `pages/index/index` - 角色分流入口
+- 身: `pages/body/index` - 身体健康维度
+- 智: `pages/wisdom/index` - 智慧维度(心智测评)
+- 心: `pages/mind/index` - 心理/情感维度
+- 我的: `pages/profile/profile` - 个人设置和积分
+
+## CONVENTIONS
+
+- **Vue 2:** 使用 Options API,生命周期 `onLoad`、`onShow`
+- **页面注册:** 新页面必须在 `pages.json` 中注册
+- **导航:** 使用 `uni.navigateTo`、`uni.redirectTo`
+- **API 调用:** 使用 `uni.request`,统一在 `config.baseUrl`
+- **地址选择:** 使用 `components/address-picker.vue` 四级联动组件
+- **角色切换:** 页面根据用户角色显示不同内容
+- **页面标题:** 所有页面的标题必须在 `pages.json` 的 `navigationBarTitleText` 中配置,禁止在 Vue 模板中手动写 `<text class="nav-title">`。仅动态标题页面(根据数据实时变化)可保留自定义 nav-bar
+- **API 调用去重(强制规范 · 违反者会被 CI 拦截):** 同一个后端 URL 在同一个页面首次加载时只允许发起一次网络请求。这是硬性规则,不是建议。违规会通过 `scripts/audit-duplicate-api-calls.js` 被检出(exit code 1)。
+
+  **为什么是根本性的:** 微信小程序生命周期在页面首次进入时 `onLoad` 和 `onShow` 都会触发,`utils/api.js` 的 3 秒去重是兜底,不是免死金牌——去重只能掩盖重复调用,不能消除它带来的延迟、内存和可维护性问题。
+
+  **规则 1 · 生命周期双发(最常见):** `onLoad` 和 `onShow` 不得同时无条件调用同一个加载方法。必须使用 `_onLoadFired` 标志位让首次 `onShow` 跳过,切 Tab 返回时刷新:
+  ```js
+  // 正确
+  onLoad(options) {
+    this.loadData(options)
+    this._onLoadFired = true
+  },
+  onShow() {
+    if (this._onLoadFired) {
+      this._onLoadFired = false   // 首次进入:onLoad 已加载,跳过避免双发
+    } else {
+      this.loadData()              // 切 Tab 返回:刷新数据
+    }
+  },
+  ```
+  如果 `onShow` 的加载是"从子页面返回后的条件性刷新"(如地址编辑页返回),同样适用该模式——将条件判断放在 `else` 分支内。
+
+  **规则 2 · 同接口多封装(utils/api.js):** `utils/api.js` 中,同一个后端 URL 只能有**一个**包含 `request()` 调用的导出函数作为规范入口;语义相近的别名必须**委托**到规范函数,禁止复制 `request()` 调用:
+  ```js
+  // 规范入口
+  export const getFamilyMemberList = (params) => request('/api/family/member/list', 'POST', params || {})
+  // 别名(委托,不复制 request 调用)
+  export const getChildren = () => getFamilyMemberList({ memberType: 'child' })
+  ```
+  同 URL 不同 HTTP 方法 / 不同 `params` 的变体允许共存(如 `createPackage` POST data vs `getMyPackages` POST {}),但须在代码注释中标明差异。
+
+  **规则 3 · 一个方法只打一次接口:** 同一个方法内不得发起对同一 URL 的两次调用。常见反模式:`loadLoggedInData()` 中同时调用 `loadFamilyMembers()` 和 `loadChildren()`,二者封装了同一个 URL → 合并为一个请求,从响应中派生不同用途的数据:
+  ```js
+  // 错误:同一 URL 打两次
+  loadLoggedInData() { this.loadFamilyMembers(); this.loadChildren() }
+  // 正确:打一次,派生两类数据
+  loadFamilyData() {
+    getFamilyMemberList({ visibleOnly: true }).then(res => {
+      var arr = res.data
+      this.familyMembersVisible = arr
+      this.children = arr.filter(m => m.effectiveRole === 'child')
+    })
+  }
+  ```
+
+  **规则 4 · 禁止 N+1 循环请求:** 不得在 `.map()` / `.forEach()` / `for` 循环体内发起 API 请求。N 个元素 → N 次请求。应改为:(a) 后端提供批量接口一次返回;(b) 如果确实需要多元素多请求,须用 `Promise.all()` 并发执行(减少串行等待),同时确认后端能承受并发量;(c) 在循环前做去重/过滤,减少实际请求数。
+
+  **规则 4a · 循环前过滤成员类型(常见反模式):** 调用 `getTaskHistory` 等按成员 ID 轮询的接口时,**必须先过滤 `effectiveRole === 'child'`**,不得对家庭成员全量列表(含家长)发起请求。示例:
+  ```js
+  // 正确:过滤后轮询
+  var children = members.filter(m => m.effectiveRole === 'child')
+  Promise.all(children.map(c => getTaskHistory(c.id, 1, 3)))
+  // 错误:对全部成员(含家长)发起请求
+  Promise.all(members.map(m => getTaskHistory(m.id, 1, 3)))
+  ```
+
+  **规则 4b · getChildren 已废弃:** `getChildren()` 内部委托 `getFamilyMemberList({})`,二者调用同一接口。新代码直接使用 `getFamilyMemberList` 并在页面内按 `effectiveRole === 'child'` 过滤,不要同时导入 `getChildren` 和 `getFamilyMemberList`。
+
+  **规则 4c · onLoad/onShow 首次加载只走一次:** 小程序 TabBar 页面首次加载时 `onLoad` 和 `onShow` 均会触发。所有 API 调用必须确保首次只执行一次:在 `onLoad` 中设置 `_onLoadFired = true`,`onShow` 中检查该标志——首次为 `true` 则跳过(由 `onLoad` 负责),后续切 Tab 返回时标志已重置为 `false` 才刷新。`checkMemberStatus` 等高频方法同样适用。详见规则 1 代码示例。
+
+  **CI 门禁:** `scripts/audit-duplicate-api-calls.js` 是 CI 必跑脚本。运行方式:`node scripts/audit-duplicate-api-calls.js`,退出码 `0` = 通过,`1` = 存在未解决的 ERROR 级违规。每个新页面提交前必须通过审计。
+
+  **子组件接口调用:** 子组件不得重复调用父页面已调用的接口。父组件应通过 props 传递数据,而非让子组件各自请求。
+
+## 时间显示规范
+
+页面时间展示必须统一以下两种格式:
+
+| 使用场景 | 格式 | 示例 |
+|------|------|------|
+| **时间(年月日+时分秒)** | `yyyy-MM-dd HH:mm:ss` | `2026-08-15 14:30:00` |
+| **仅日期(不带时间)** | `yyyy-MM-dd` | `2026-08-15` |
+
+后端返回 ISO 8601 格式(`2026-08-15T14:30:00`),前端格式化:
+
+- **需展示时间**:字符串先经 `parseDate()` 解析(iOS 安全),再用 `getFullYear()`/`getMonth()`/`getDate()`/`getHours()`/`getMinutes()`/`getSeconds()` 拼出 `yyyy-MM-dd HH:mm:ss`
+- **仅需日期**:直接截取字符串前 10 位 → `yyyy-MM-dd`
+
+禁止 `new Date(str).toLocaleString()`(iOS 输出格式与渲染结果因人而异)。
+
+## ANTI-PATTERNS
+
+- **DO NOT** 创建页面后忘记在 `pages.json` 注册
+- **DO NOT** 硬编码 API 地址,使用 `config.baseUrl`
+- **DO NOT** 在前端存储敏感信息 (密码、密钥)
+- **NEVER** 跳过 JWT 认证直接调用需登录接口
+- **NEVER** 在本地存储中保存敏感用户信息
+- **NEVER** 在 WXML/Vue 模板中使用可选链 `?.`,微信小程序不支持 → 使用 `&&` 代替(如 `currentWish?.title` 改为 `currentWish && currentWish.title`)
+- **NEVER** 在 `:class` 绑定中调用方法(如 `:class="getStatusClass(item)"`),微信小程序模板编译器不支持带参数的方法调用 → 改用内联表达式(如 `:class="'status-' + item._cssClass"`)或计算属性
+- **NEVER** 在 CSS 类名、选择器中使用中文(如 `.val-偏高`、`.badge-低风险`),微信小程序 wxss 编译器不支持中文类名 → 使用英文(如 `.val-high`、`.badge-low`),数据中的中文状态通过 `_cssClass` 字段映射
+- **NEVER** 在 `:key` 中使用表达式(如 `:key="item.id || item.circleId"`),微信小程序模板编译器不支持带运算符的 `:key` 绑定 → 改用方法调用(如 `:key="getItemKey(item)"`,在 methods 中定义 `getItemKey(item) { return item.id || item.circleId }`)
+- **NEVER** 直接用 `new Date(string)` 解析日期字符串。部分 iOS(JavaScriptCore)的 `new Date()` 只支持 `yyyy/MM/dd`、`yyyy/MM/dd HH:mm:ss`、`yyyy-MM-dd`、`yyyy-MM-ddTHH:mm:ss`、`yyyy-MM-ddTHH:mm:ss+HH:mm` 格式,后端常见的 `"2026-08-22 14:00"`(空格分隔的 MySQL DATETIME 风格)和 Java 的 `"Sat Aug 22 14:00:00 CST 2026"` 会解析失败返回 Invalid Date → 一律使用 `utils/format.js` 的 `parseDate()`,它会自动归一化上述两种格式并返回 `Date|null`(如 `var d = parseDate(item.startTime); if (!d) return`)
+- **NEVER** 新增 `uni.getSystemInfoSync()` 调用。该 API 已在微信基础库 2.20.1+ 弃用,开发者工具会持续告警(`getSystemInfoSync is deprecated`)→ 改用 `uni.getWindowInfo()`(取 `windowWidth`/`pixelRatio`/`safeArea` 等窗口信息)或 `uni.getDeviceInfo()`(取 `system`/`brand`/`model` 等设备信息)。已有兼容代码(`components/mp-html/` 内的 `uni.canIUse('getWindowInfo')` 兜底)保持不变。参考替换:`uni.getSystemInfoSync().pixelRatio` → `uni.getWindowInfo().pixelRatio`
+- **NEVER** 给 `props` 传可能为非数组的值而不做兜底。组件接收 `Array` 类型 prop 时,父组件传值必须保证是数组(`|| []` 兜底 + `Array.isArray` 校验),否则触发 `Invalid prop: type check failed for prop "xxx". Expected Array, got Object` 告警。典型场景:接口返回结构不确定(`res.data.list` 可能为 `Object`)时,用 `var arr = (res.data && res.data.list) || (res.data instanceof Array ? res.data : [])` 三态兼容
+
+
+- **NEVER** 在页面模板中写 `<text class="nav-title">` 或自定义 nav-bar 标题。所有静态标题统一在 `pages.json` 的 `navigationBarTitleText` 中配置。需要运行时动态标题时才用自定义 nav-bar
+- **NEVER** 在同一个页面中多次调用相同的 API 接口。`utils/api.js` 的 `request()` 已内置 3 秒窗口去重(同 URL + method + body 自动复用 Promise),但这是安全网不是免死金牌——页面须从源头避免:`onLoad` 全量初始化 + `_initDone` 标志跳过 `onShow` 首次重复、降级路径同步设置所有 state 避免后续方法重复调用、子组件通过 props 接收数据而非各自请求
+
+## UNIQUE FEATURES
+
+- 地址匹配页面: `pages/match/street-match.vue` - 街道地址匹配功能
+- 地址编辑页面: `pages/family/address-edit.vue` - 家庭地址管理
+- 四级地址选择: `components/address-picker.vue` - 省市区街道联动
+- 双角色界面: 根据用户角色(parent/child)显示不同UI
+
+## BUILD SYSTEM
+
+### 打包方式(强制规范)
+
+**小程序打包必须用 HBuilderX 完成,Agent 禁止自行执行 `npm run build:mp-weixin` 等打包命令。**
+
+- 打包工具:HBuilderX(导入 `cfc-frontend/` 目录 → 运行 → 运行到小程序模拟器 → 微信开发者工具)
+- 打包产物:**`cfc-frontend/unpackage/`** 目录(HBuilderX 输出位置,dev 产物在 `unpackage/dist/dev/mp-weixin/`)
+- 微信开发者工具导入的目录是 `unpackage/dist/dev/mp-weixin/`(或 HBuilderX 自动打开),**不是** `dist/`
+- `dist/` 目录是 npm CLI 打包的残留产物,**不可用**——`app.js` 仅有 89 字节(require 三行),非完整产物
+- Agent 修改代码后:只做**语法/结构校验**(如 `node --check` 提取的 script 块),**不打包、不运行 build 命令**
+- 页面白板排查第一步:确认用户是否在 HBuilderX 中**重新打包**过(改代码后未重新打包 → 产物过期 → 白板)
+
+### 依赖约束(2026-07-23 修复后锁定)
+
+| 包 | 版本 | 原因 |
+|----|------|------|
+| `@vue/cli-service` | `~4.5.0` | v5 使用 webpack 5,`@dcloudio/uni-mp-weixin` 依赖 `webpack/lib/GraphHelpers`(webpack 4 特有)|
+| `@vue/cli-plugin-babel` | `~4.5.0` | 与 cli-service v4 匹配 |
+| `postcss` (override + dependency) | `7.0.39` | `remove-scoped.js` 在 PostCSS 8 下会走 v8 插件路径,但 `spaces` 属性访问有兼容问题 |
+| `node-sass` | (devDependency) | `@dcloudio/vue-cli-plugin-uni` 内置的 sass-loader 需要 |
+| `copy-webpack-plugin` | `^5.1.2` | 与 cli-service v4 的 webpack 4 兼容 |
+
+### postinstall 自动补丁
+
+`npm install` 后会自动运行 `postinstall-fix.js`,修补 `remove-scoped.js` 中的 `spaces` 崩溃:
+
+```js
+// 问题: selector.first 可能为 undefined
+// 修改前: selector.first.spaces.before = '';
+// 修改后: if (selector.first) { selector.first.spaces.before = ''; }
+```
+
+### 已知编译错误处理
+
+| 错误 | 原因 | 处理 |
+|------|------|------|
+| `Cannot read properties of undefined (reading 'spaces')` in `remove-scoped.js` | PostCSS 节点没有 `spaces` 属性 | postinstall-fix.js 自动补丁 |
+| `Cannot find module 'webpack/lib/GraphHelpers'` | `@vue/cli-service v5` 的 webpack 5 不支持 | 保持 `@vue/cli-service ~4.5.0` |
+| `Cannot find module 'node-sass'` | uni-app sass-loader 需要 | `npm install node-sass --save-dev` |
+| `getPreCompileOptions` DevTools 内部错误 | `dist/dev/mp-weixin/` 缺少 `project.config.json` | 先 `npm run build:mp-weixin` 生成 dist |
+| `Unexpected token` in `.vue` | JS 语法错误,常见于方法被截断/拼接错误 | 检查 v-on:click/方法调用是否正确闭合 |
+| 模板报 `Invalid expression` / `private name` | 模板表达式里写了未加引号的 `#hex`(如 `:style="{ color: #FFF }"`、`item.color \|\| #F97316`) | 加引号 `'#FFF'`,或把颜色移进 class / `BrandColors`(脚本侧) |
+| dart-sass `Undefined variable: $xxx` | 样式引用了 `uni.scss` 里不存在的令牌 | 在 `uni.scss` 补令牌,或改用已有等值令牌 |
+
+### 提交前全站编译自检
+
+```bash
+node scripts/verify-vue-compile.js            # 全量:模板 + 样式 + 脚本三段编译
+node scripts/verify-vue-compile.js a.vue b.vue  # 仅校验指定文件
+```
+
+判定标准:`模板通过 / 样式通过 / 脚本通过` 三项数量一致且输出 `PASS`(退出码 0)。
+它能拦住三类只在 HBuilderX 打包时才暴露、小程序侧表现为白板的问题:模板表达式里未加引号的 `#hex`、样式引用未定义 SCSS 令牌、脚本语法截断。`components/mp-html/node/node.vue` 属第三方渲染器,脚本内已跳过。
+
+### 小程序反模式审计
+
+```bash
+node scripts/audit-mp-antipatterns.js            # ERROR 归零才算通过(退出码 0)
+node scripts/audit-mp-antipatterns.js --json     # 机器可读,便于脚本处理
+```
+
+ERROR 级(必须修):模板 `?.`、`:key` 运算符表达式、CSS 中文选择器、`uni.getSystemInfoSync()`、`transition: all`、`v-for` 缺 `:key`、日期用 `toLocale*String` 格式化。
+WARN 级(人工确认):`new Date(<非字面量>)`(应改 `parseDate()`)、`:class/:style` 内带参方法调用(uni-app 渲染函数下可用,但 WXML 原生表达式不支持,AGENTS.md 列为禁用项)。
+
+### 修改 `remove-scoped.js` 的风险
+
+该文件在 `node_modules/@dcloudio/vue-cli-plugin-uni/` 内,每次 `npm install` 会通过 `postinstall-fix.js` 自动恢复补丁。如需手动执行:
+
+```bash
+node postinstall-fix.js
+```
+
+**不要**将 `@vue/cli-service` 升级到 v5,除非:
+- `@dcloudio/uni-mp-weixin` 确认移除了 `webpack/lib/GraphHelpers` 依赖
+- 或者找到替代方法处理独立分包插件
+
+## COMMANDS
+
+```bash
+npm install             # 安装依赖(自动运行 postinstall-fix.js)
+# 注意:打包一律用 HBuilderX(产物在 unpackage/),Agent 不要执行 npm run build:mp-weixin
+```
+
+## NOTES
+
+- 小程序AppID: `wx5ba8038ef16fb245`
+- 后端API地址: 配置在 `config/index.js` 的 `baseUrl`
+- 地址数据: 使用后端街道API获取四级地址数据
+- 调试工具: 微信开发者工具需配置合法域名
+- **打包流程(HBuilderX)**:HBuilderX 打开 `cfc-frontend/` → 运行到微信开发者工具 → 产物输出至 `unpackage/dist/dev/mp-weixin/`。改代码后必须在 HBuilderX 中重新运行打包,否则小程序显示旧产物(甚至白板)
+- **禁止**在终端执行 `npm run build:mp-weixin` 或 `npm run dev:mp-weixin` 自行打包(产物进 `dist/` 而非 `unpackage/`,与 HBuilderX 工作流冲突)

+ 285 - 0
cfc-frontend/App.vue

@@ -0,0 +1,285 @@
+<script>
+import config from '@/config.js'
+import Vue from 'vue'
+import { checkUserFamily, verifyToken, bindReferralIfNotSelf, silentRelogin, ssoLogin } from './utils/api.js'
+import { syncFontScale } from './utils/fontScale.js'
+import { checkAppUpdate } from '@/utils/checkAppUpdate.js'
+Vue.prototype.$config = config
+
+export default {
+  onLaunch: function(options) {
+    // 尽早检测新版本:applyUpdate 会重启整机,须在任何路由/页面逻辑之前
+    checkAppUpdate()
+    console.log('App Launch', options)
+    // 同步微信系统字体大小
+    syncFontScale()
+    // 捕获分享/邀请参数(普通分享链接 ?inviteCode=xxx):未登录写入 storage 供注册登录后绑定推荐人,已登录直接绑定
+    this.captureReferralParams(options)
+    // 恢复登录态:必须放在 splash 分支之前。
+    // 原实现在普通冷启动(无深链)时于 splash 跳转处 return,导致 verifyStoredToken / tryAutoLogin
+    // 只在「分享/小程序码进入」时才执行,普通用户冷启动拿不到任何续期机会。
+    // 现在冷启动即异步校验/静默续期,与 2 秒 splash 动画并行,用户落地即已是有效登录态。
+    // 本方法不做任何页面跳转,导航交由 splash 或当前页面处理,避免与 splash 的 reLaunch 抢路由。
+    this.restoreSession()
+    // 分享/深链冷启动(携带分享参数)放行到落地页,不套 splash,避免分享的文章/小程序页面打不开
+    // inviteCode=推荐码(文章/活动/商品分享)| refCode=推广码 | token/familyInviteCode=家庭邀请令牌 | id=内容详情
+    var hasDeepLink = options && options.query && (
+      options.query.inviteCode || options.query.refCode || options.query.token ||
+      options.query.familyInviteCode || options.query.id || options.query.ssoTicket
+    )
+    // 冷启动:跳转到 splash 页展示过渡动画,2秒后自动进入首页
+    if (options.scene !== 1047 && options.scene !== 1048 && options.scene !== 1049 && !hasDeepLink) {
+      uni.setStorageSync('_isFirstLaunch', '1')
+      uni.redirectTo({ url: '/pages/splash/index' })
+      return
+    }
+    // 跨小程序单点登录:携带 ssoTicket 进入 → 换取本地登录态
+    this.handleSsoLogin(options)
+    // 处理小程序码场景值(从 wxacode 扫码进入,跳过 splash)
+    this.handleScene(options)
+  },
+  onShow: function(options) {
+    console.log('App Show', options)
+    // 每次前台都同步微信系统字体大小
+    syncFontScale()
+    // 热启动(含从分享卡重新进入):同样捕获分享参数
+    this.captureReferralParams(options)
+    // 跨小程序单点登录:热启动携带 ssoTicket 进入同样处理
+    this.handleSsoLogin(options)
+    // 每次 app 展示时也检查场景值(小程序码可能从冷启动后的 onShow 传入)
+    this.handleScene(options)
+    
+    // 同步 storage → Vuex(防止 reLaunch/navigateTo 后 Vuex 未更新的问题)
+    var token = uni.getStorageSync('token')
+    if (token && token !== this.$store.state.token) {
+      this.$store.commit('setToken', token)
+      this.$store.commit('setFamilyId', uni.getStorageSync('familyId'))
+    }
+  },
+  onHide: function() {
+    console.log('App Hide')
+  },
+  methods: {
+    // 捕获分享/邀请参数:普通分享链接 /pages/xxx?refCode=yyy 冷/热启动进入时,
+    // 新用户(未登录)写入 storage,登录注册后由 login / user-edit 消费绑定推荐人;
+    // 已登录用户直接绑定(boundInviteCode 防重,避免重复请求)
+    captureReferralParams(options) {
+      if (!options || !options.query) return
+      var query = options.query
+      // 推荐码统一为 refCode;inviteCode 兼容历史分享链接(旧 share-mixin 用 inviteCode 承载推荐码)
+      var code = query.refCode || query.inviteCode
+      if (!code) return
+      if (uni.getStorageSync('token')) {
+        var bound = uni.getStorageSync('boundInviteCode')
+        if (bound === code) return
+bindReferralIfNotSelf(code).then(function(res) {
+          if (res && (res.code === 200 || res.code === 400)) {
+            uni.setStorageSync('boundInviteCode', code)
+            console.log('分享参数推荐人绑定结果', res.code, code)
+          }
+        }).catch(function(e) {
+          console.log('分享参数推荐人绑定失败', e)
+        })
+        return
+      }
+      uni.setStorageSync('refCode', code)
+      if (options.query.inviteType) {
+        uni.setStorageSync('inviteType', options.query.inviteType)
+      }
+    },
+    // 冷启动恢复登录态(异步执行,不做任何页面跳转)
+    // 1) 有 token:先同步到 Vuex。若 token 已过期/失效,/api/auth/verify 会返回 code=401,
+    //    由 request 封装统一走 _handle401 → silentRelogin 静默续期并重放,全程用户无感。
+    // 2) 无 token 但本地有 openid(此前登录过、token 已被清理):走静默续期。
+    // 3) 两者都没有:本设备从未登录,属新用户,保持未登录态,由登录页引导。
+    restoreSession() {
+      // TabBar 始终显示 5 个底签,不因登录状态隐藏
+      const token = uni.getStorageSync('token')
+      if (token) {
+        this.$store.commit('setToken', token)
+        // 冷启动恢复 familyId(登录时已持久化,hasFamily getter 依赖)
+        var storedFamilyId = uni.getStorageSync('familyId')
+        if (storedFamilyId) {
+          this.$store.commit('setFamilyId', storedFamilyId)
+        } else {
+          // 历史用户(8ddc5b55 后未重新登录):本地无 familyId,从接口恢复
+          this.restoreFamilyIdFromApi()
+        }
+        // 启动时校验 token 是否仍有效,过期则触发静默续期
+        this.verifyStoredToken()
+      } else {
+        this.tryAutoLogin()
+      }
+    },
+    // 校验本地 token 是否有效。
+    // 注意:/api/auth/verify 在 JwtInterceptor 的白名单里,不会被拦截器判 401,而是由
+    // AuthController 自行解析后返回 code=401 的响应体 —— 同样会被 request 封装识别并续期。
+    // 早期版本在 develop 环境直接 return,导致开发版完全无法验证续期逻辑,已移除该屏蔽。
+    verifyStoredToken() {
+      verifyToken().then(function() {
+        // token 有效,无需处理
+      }).catch(function(e) {
+        // 401:由 request 封装统一触发 _handle401(silentRelogin 静默续期后重放原请求);
+        //      只有续期也失败时才由 _clearAuthAndRedirect 清空登录态并跳登录页。
+        // 其它错误(如网络失败)静默忽略,不打扰用户
+        console.log('[App] token 校验未通过:', e && e.code)
+      })
+    },
+    // 从接口恢复 familyId(历史用户冷启动,本地无 familyId 缓存)
+    restoreFamilyIdFromApi() {
+      var self = this
+      checkUserFamily().then(function(res) {
+        if (res && res.data && res.data.inFamily && res.data.familyId) {
+          self.$store.commit('setFamilyId', res.data.familyId)
+          console.log('[App] familyId 已从接口恢复:', res.data.familyId)
+        }
+      }).catch(function(e) {
+        console.log('[App] familyId 接口恢复失败(页面按无家庭态渲染)', e)
+      })
+    },
+    // 无本地 token 时尝试静默续期。
+    // 走 uni.login() → /api/auth/silent-login(服务端 code2Session):微信签发的一次性 code
+    // 能证明调用方持有该微信设备,因此不可伪造;本地 openid 仅用于判断「本设备曾登录过」,
+    // 绝不作为凭证上送(旧的 autoLogin(openid) 已被后端废弃为 410 Gone)。
+    // 早期版本在 develop 环境直接 return,开发版无法验证续期,已移除该屏蔽。
+    // 不做页面跳转:冷启动由 splash 在 2 秒后统一 reLaunch 到首页,
+    // 此处若再 switchTab 会与其抢路由(splash 先落地时 switchTab 落在已销毁页面上)。
+    async tryAutoLogin() {
+      try {
+        var loginData = await silentRelogin()
+        if (loginData) {
+          this.saveLoginInfo(loginData)
+          console.log('[App] 静默续期成功,已恢复登录态')
+        } else {
+          // 本设备从未登录过,或续期失败:保持未登录态,由登录页引导
+          console.log('[App] 静默续期未成功,需手动登录')
+        }
+      } catch (e) {
+        console.log('[App] 静默续期异常,需手动登录', e)
+      }
+    },
+    saveLoginInfo(data) {
+      uni.setStorageSync('token', data.token)
+      uni.setStorageSync('userId', data.userId)
+      uni.setStorageSync('role', data.role)
+      // 自动登录后重置到真实登录角色,避免残留切换状态
+      uni.setStorageSync('currentRole', data.role)
+      uni.setStorageSync('isSwitchedChild', false)
+      uni.setStorageSync('isSwitchedTeacher', false)
+      if (data.openid) {
+        uni.setStorageSync('openid', data.openid)
+      }
+      // familyId 必须持久化:家庭在注册时已由后端创建,缺失会导致页面误判无家庭而重复创建
+      uni.setStorageSync('userInfo', {
+        nickname: data.nickname,
+        userId: data.userId,
+        familyId: data.familyId
+      })
+      this.$store.commit('setToken', data.token)
+      // 同步 familyId 到 store(hasFamily getter 依赖;静默续期路径)
+      this.$store.commit('setFamilyId', data.familyId)
+    },
+    // 跨小程序单点登录:从 train 跳转进入时携带 ssoTicket → 换取本地登录态。
+    // 一次性票据(后端原子消费),用 _ssoHandledTicket 去重,避免 onLaunch/onShow 双处理。
+    handleSsoLogin(options) {
+      if (!options || !options.query) return
+      var ticket = options.query.ssoTicket
+      if (!ticket) return
+      if (this._ssoHandledTicket === ticket) return
+      this._ssoHandledTicket = ticket
+      var self = this
+      uni.showLoading({ title: '登录中...' })
+      ssoLogin(ticket).then(function(res) {
+        uni.hideLoading()
+        if (res && res.code === 200 && res.data) {
+          self.saveLoginInfo(res.data)
+          // 清空路由票据(防转发泄漏)并落地首页;index/index 会按角色重新分流
+          uni.reLaunch({ url: '/pages/index/index' })
+        } else {
+          uni.showToast({ title: (res && res.message) || '单点登录失败', icon: 'none' })
+        }
+      }).catch(function(e) {
+        uni.hideLoading()
+        uni.showToast({ title: (e && e.message) || '单点登录失败', icon: 'none' })
+      })
+    },
+    // 处理小程序码场景值
+    handleScene(options) {
+      if (!options || !options.query) return
+      var scene = options.query.scene
+      if (!scene) return
+      var sceneDecoded = decodeURIComponent(scene)
+      if (sceneDecoded.indexOf('invite=') === 0) {
+        var token = sceneDecoded.substring(7)
+        uni.navigateTo({
+          url: '/pages/invite/join?token=' + token
+        })
+      } else if (sceneDecoded.indexOf('ref=') === 0) {
+        var refCode = sceneDecoded.substring(4)
+        if (!refCode) return
+        // 已登录则自动绑定推荐人;未登录存入 storage 待登录后绑定
+        if (uni.getStorageSync('token')) {
+          bindReferralIfNotSelf(refCode).then(function(res) {
+            if (res && (res.code === 200 || res.code === 400)) {
+              uni.setStorageSync('boundInviteCode', refCode)
+            }
+          }).catch(function() {})
+        } else {
+          uni.setStorageSync('refCode', refCode)
+        }
+      }
+    }
+  }
+}
+</script>
+
+<style lang="scss">
+@import url('./common/uni.css');
+
+page {
+  background-color: var(--bg, $uni-bg-color);
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI',
+    'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
+    'Helvetica Neue', Helvetica, Arial, sans-serif;
+  color: var(--text, $uni-text-color);
+  font-size: 28rpx;
+  line-height: 1.6;
+  -webkit-font-smoothing: antialiased;
+  /* 全局字号缩放系数默认值:页面根节点用 :style="{'--font-scale': fontScale}" 覆盖 */
+  --font-scale: 1;
+}
+
+/* 页面容器 */
+.page {
+  padding: 0 32rpx 32rpx;
+  min-height: 100vh;
+}
+
+.page--no-padding {
+  padding: 0;
+}
+
+/* 分段标题 */
+.section-header {
+  font-weight: 700;
+  font-size: 32rpx;
+  margin: 32rpx 0 16rpx;
+  color: var(--text, $uni-text-color);
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  border-left: 8rpx solid $uni-warm;
+  padding-left: 20rpx;
+}
+.section-header__more {
+  font-size: 24rpx;
+  color: var(--muted, $app-text-subtle);
+  font-weight: 400;
+}
+
+/* 安全区底部 */
+.safe-area-bottom {
+  padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
+  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
+}
+</style>

+ 2588 - 0
cfc-frontend/INTERFACE_TEST_MATRIX.md

@@ -0,0 +1,2588 @@
+# CFC 小程序「页面功能 → 操作接口」测试矩阵
+
+> 由 `cfc-frontend/utils/api.js` 全量解析 + 全量页面 `.vue/.js` 调用扫描自动生成。
+> 每个小程序页面(路由)映射到其实际调用的后端操作接口,可直接派生接口测试用例。
+
+- **页面路由数**:267
+- **接口用例总数**:1016
+- **公开接口(无需登录)**:178
+- **需登录态接口**:838
+- **含路径参数(需真实 ID)**:56
+
+> 注意:含路径参数的接口在无真实数据时大概率返回 400/404/401,脚本仅做「可达性 + 返回结构」断言,业务正确性需结合真实数据补充。
+
+## 按模块概览
+
+| 模块 | 接口数 | 公开 | 需登录 | 含参数 |
+|------|-------:|-----:|-------:|-------:|
+| ability | 1 | 0 | 1 | 0 |
+| activity | 27 | 27 | 0 | 0 |
+| admin | 14 | 3 | 11 | 1 |
+| ai | 10 | 1 | 9 | 0 |
+| articles | 22 | 22 | 0 | 0 |
+| assessment | 7 | 0 | 7 | 0 |
+| auth | 26 | 26 | 0 | 0 |
+| badges | 11 | 0 | 11 | 0 |
+| basic-quota | 2 | 0 | 2 | 0 |
+| butler | 8 | 8 | 0 | 0 |
+| cart | 3 | 0 | 3 | 0 |
+| cf | 3 | 0 | 3 | 0 |
+| circle | 15 | 1 | 14 | 0 |
+| cognitive | 15 | 0 | 15 | 0 |
+| commission | 19 | 0 | 19 | 0 |
+| common | 1 | 0 | 1 | 0 |
+| consent | 1 | 0 | 1 | 0 |
+| consignee | 4 | 0 | 4 | 0 |
+| contact | 13 | 0 | 13 | 0 |
+| content | 1 | 0 | 1 | 0 |
+| content-sections | 4 | 0 | 4 | 0 |
+| coupon | 10 | 0 | 10 | 0 |
+| daily-task | 2 | 0 | 2 | 0 |
+| dan-assessment | 17 | 5 | 12 | 1 |
+| dan-report | 2 | 0 | 2 | 1 |
+| diet | 20 | 1 | 19 | 0 |
+| dimension | 12 | 0 | 12 | 0 |
+| doa | 7 | 0 | 7 | 0 |
+| earnings | 4 | 0 | 4 | 0 |
+| emireport | 3 | 0 | 3 | 0 |
+| energy | 41 | 0 | 41 | 0 |
+| family | 98 | 12 | 86 | 1 |
+| family-platform | 4 | 0 | 4 | 0 |
+| feedback | 2 | 2 | 0 | 0 |
+| food | 8 | 0 | 8 | 0 |
+| game | 7 | 0 | 7 | 0 |
+| growth | 12 | 0 | 12 | 2 |
+| growth-task | 2 | 0 | 2 | 0 |
+| guide | 50 | 6 | 44 | 6 |
+| guide-config | 3 | 0 | 3 | 0 |
+| health | 97 | 2 | 95 | 2 |
+| health-plan | 1 | 0 | 1 | 0 |
+| health-status | 7 | 0 | 7 | 0 |
+| home | 21 | 0 | 21 | 0 |
+| home-banner | 1 | 0 | 1 | 0 |
+| indicator | 8 | 0 | 8 | 0 |
+| insurance | 1 | 0 | 1 | 0 |
+| internal | 1 | 0 | 1 | 0 |
+| invite | 23 | 0 | 23 | 0 |
+| invite-card | 2 | 2 | 0 | 0 |
+| leaderboard | 2 | 0 | 2 | 0 |
+| meal | 5 | 0 | 5 | 0 |
+| membership | 35 | 0 | 35 | 0 |
+| micro-action | 4 | 0 | 4 | 0 |
+| mind | 8 | 0 | 8 | 0 |
+| mini-game | 7 | 0 | 7 | 1 |
+| notification | 6 | 0 | 6 | 0 |
+| nutrition | 3 | 0 | 3 | 0 |
+| nutritionist | 1 | 1 | 0 | 0 |
+| octopus | 11 | 0 | 11 | 0 |
+| onboarding | 3 | 0 | 3 | 0 |
+| orchestration | 16 | 0 | 16 | 0 |
+| package | 2 | 0 | 2 | 0 |
+| packages | 6 | 1 | 5 | 5 |
+| parent | 4 | 0 | 4 | 1 |
+| pearl | 9 | 0 | 9 | 0 |
+| points | 8 | 0 | 8 | 0 |
+| poster-template | 2 | 0 | 2 | 0 |
+| product | 32 | 32 | 0 | 0 |
+| profile | 2 | 0 | 2 | 0 |
+| purchase | 2 | 0 | 2 | 0 |
+| recommend | 3 | 0 | 3 | 1 |
+| report-summary | 2 | 0 | 2 | 1 |
+| rewards | 7 | 0 | 7 | 2 |
+| service-role | 2 | 0 | 2 | 0 |
+| share | 5 | 0 | 5 | 0 |
+| shop | 2 | 2 | 0 | 0 |
+| special-price | 2 | 0 | 2 | 0 |
+| stats | 7 | 0 | 7 | 0 |
+| streets | 4 | 4 | 0 | 4 |
+| survey | 8 | 0 | 8 | 0 |
+| task | 2 | 0 | 2 | 0 |
+| tasks | 41 | 0 | 41 | 13 |
+| tianpan | 5 | 5 | 0 | 1 |
+| unlock | 3 | 0 | 3 | 0 |
+| user | 30 | 0 | 30 | 0 |
+| vendor | 9 | 7 | 2 | 0 |
+| wealth | 16 | 8 | 8 | 0 |
+| wisdom | 1 | 0 | 1 | 0 |
+| wishes | 23 | 0 | 23 | 13 |
+| withdrawal | 3 | 0 | 3 | 0 |
+
+## 按页面路由明细
+
+### App  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/auto-login` | 公开 |  | `autoLogin` |
+| POST | `/api/auth/sso-login` | 公开 |  | `ssoLogin` |
+| POST | `/api/auth/verify` | 公开 |  | `verifyToken` |
+| POST | `/api/family/invite/check-family` | 公开 |  | `checkUserFamily` |
+
+### __tests__/api/api.indicator.test  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/indicator/change-ranking` | 登录 |  | `getIndicatorChangeRanking` |
+| POST | `/api/indicator/correlation/list` | 登录 |  | `getIndicatorCorrelationList` |
+| POST | `/api/indicator/quick-lookup` | 登录 |  | `getIndicatorQuickLookup` |
+| POST | `/api/indicator/trend` | 登录 |  | `getIndicatorTrend` |
+
+### __tests__/api/api.test  (113 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/ai/chat/conversations` | 登录 |  | `aiGetConversations` |
+| POST | `/api/ai/chat/send` | 登录 |  | `aiSendMessage` |
+| POST | `/api/articles/categories` | 公开 |  | `getArticleCategories` |
+| POST | `/api/articles/daily-tip` | 公开 |  | `getDailyTip` |
+| POST | `/api/articles/detail` | 公开 |  | `getArticleDetail` |
+| POST | `/api/articles/list` | 公开 |  | `getArticleList` |
+| POST | `/api/articles/related` | 公开 |  | `getRelatedArticles` |
+| POST | `/api/auth/auto-login` | 公开 |  | `autoLogin` |
+| POST | `/api/auth/check-phone` | 公开 |  | `checkPhone` |
+| POST | `/api/auth/direct-register` | 公开 |  | `directRegister` |
+| POST | `/api/auth/phone-login` | 公开 |  | `phoneLogin` |
+| POST | `/api/auth/send-code` | 公开 |  | `sendCode` |
+| POST | `/api/auth/set-password` | 公开 |  | `setPassword` |
+| POST | `/api/auth/silent-login` | 公开 |  | `silentLogin` |
+| POST | `/api/auth/verify` | 公开 |  | `verifyToken` |
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/auth/wechat-login` | 公开 |  | `wechatLogin` |
+| POST | `/api/auth/wechat-phone-login` | 公开 |  | `wechatPhoneLogin` |
+| POST | `/api/badges/member/list` | 登录 |  | `getChildBadges` |
+| POST | `/api/badges/favorite` | 登录 |  | `toggleBadgeFavorite` |
+| POST | `/api/badges/list` | 登录 |  | `getActiveBadges` |
+| POST | `/api/commission/summary` | 登录 |  | `getCommissionSummary` |
+| POST | `/api/contact/create` | 登录 |  | `createContact` |
+| POST | `/api/contact/delete` | 登录 |  | `deleteContact` |
+| POST | `/api/contact/import-phone` | 登录 |  | `importPhoneContact` |
+| POST | `/api/contact/list` | 登录 |  | `getContactList` |
+| POST | `/api/dan-assessment/child-results` | 登录 |  | `getChildAssessmentResults` |
+| POST | `/api/dan-assessment/my-results` | 登录 |  | `getMyAssessmentResults` |
+| POST | `/api/dan-assessment/order/pay` | 登录 |  | `payAssessmentOrder` |
+| POST | `/api/dan-assessment/result/record` | 公开 |  | `recordAssessmentResult` |
+| POST | `/api/energy/logs` | 登录 |  | `getEnergyLogs` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/user/children` | 登录 |  | `createChild` |
+| POST | `/api/family/user/children/update` | 登录 |  | `updateChild` |
+| POST | `/api/family/user/create-family` | 登录 |  | `createFamily` |
+| POST | `/api/family/user/kick` | 登录 |  | `kickFamilyMember` |
+| POST | `/api/family/user/members/update-visibility` | 登录 |  | `updateMemberVisibility` |
+| POST | `/api/game/history` | 登录 |  | `getGameHistory` |
+| POST | `/api/game/leaderboard` | 登录 |  | `getGameLeaderboard` |
+| POST | `/api/growth/record/create` | 登录 |  | `createGrowthRecord` |
+| POST | `/api/growth/record/create-with-order` | 登录 |  | `createGrowthRecord` |
+| POST | `/api/growth/record/list` | 登录 |  | `getGrowthRecordList` |
+| POST | `/api/guide/bind/invite` | 登录 |  | `generateBindInvite` |
+| POST | `/api/guide/families` | 登录 |  | `getBoundFamilies` |
+| POST | `/api/guide/messages/list` | 登录 |  | `getGuideMessages` |
+| POST | `/api/guide/orders/list` | 登录 |  | `getGuideOrders` |
+| POST | `/api/guide/packages/my` | 登录 |  | `getGuidePackages` |
+| POST | `/api/guide/register` | 公开 |  | `registerGuide` |
+| POST | `/api/guide/team/members` | 登录 |  | `getTeamMembers` |
+| POST | `/api/health/checkin/list` | 登录 |  | `healthCheckinList` |
+| POST | `/api/health/indicator/list` | 登录 |  | `getHealthIndicatorList` |
+| POST | `/api/health/report/create` | 登录 |  | `createHealthReport` |
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+| POST | `/api/health/report/latest` | 登录 |  | `getLatestHealthReport` |
+| POST | `/api/health/report/list` | 登录 |  | `getReportList` |
+| POST | `/api/health/survey/create` | 登录 |  | `createReportSurvey` |
+| POST | `/api/health/survey/submit` | 登录 |  | `submitReportSurvey` |
+| POST | `/api/invite-card/generate` | 公开 |  | `generateInviteCard` |
+| POST | `/api/invite-card/verify` | 公开 |  | `verifyInviteCard` |
+| POST | `/api/invite/bind` | 登录 |  | `bindReferral` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/membership/levels` | 登录 |  | `getMembershipLevels` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/membership/orders` | 登录 |  | `createOrder` |
+| POST | `/api/mini-game//:var` | 登录 | ✓ | `getMiniGameByCode` |
+| POST | `/api/mini-game/complete` | 登录 |  | `completeMiniGame` |
+| POST | `/api/mini-game/list` | 登录 |  | `getMiniGameList` |
+| POST | `/api/packages//:var/publish` | 登录 | ✓ | `publishPackage` |
+| POST | `/api/points/balance` | 登录 |  | `getPointsBalance` |
+| POST | `/api/points/logs` | 登录 |  | `getPointsLogs` |
+| POST | `/api/product/create` | 公开 |  | `productCreate` |
+| POST | `/api/product/detail` | 公开 |  | `productDetail` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+| POST | `/api/product/order/create` | 公开 |  | `productOrderCreate` |
+| POST | `/api/rewards` | 登录 |  | `createReward` |
+| POST | `/api/rewards//:var/exchange` | 登录 | ✓ | `exchangeReward` |
+| POST | `/api/rewards/wishlist` | 登录 |  | `getWishlist` |
+| POST | `/api/stats/child-completion` | 登录 |  | `getChildCompletionStats` |
+| POST | `/api/stats/child/overview` | 登录 |  | `getChildOverview` |
+| POST | `/api/streets//:var/match`)
+}
+
+// 按区域统计
+export const getStreetStats = (level = 4) => {
+  return request('/api/streets/stats', 'POST', { level })
+}
+
+// 获取家庭详情(含地址信息)
+export const getFamilyDetail = (id) => {
+  return request(`/api/admin/families//:var`)
+}
+
+// 更新家庭地址
+export const updateFamilyAddress = (data) => {
+  return request(`/api/admin/families/update` | 公开 | ✓ | `matchByStreet` |
+| POST | `/api/streets/provinces')
+}
+
+// 根据父级ID获取子级地址
+export const getStreetChildren = (parentId) => {
+  return request(`/api/streets/children//:var`)
+}
+
+// 根据ID获取地址详情
+export const getStreetById = (id) => {
+  return request(`/api/streets//:var`)
+}
+
+// 获取地址完整路径
+export const getStreetPath = (id) => {
+  return request(`/api/streets//:var/path`)
+}
+
+// 搜索地址
+export const searchStreet = (keyword) => {
+  return request('/api/streets/search` | 公开 | ✓ | `getProvinces` |
+| POST | `/api/survey/status` | 登录 |  | `getSurveyStatus` |
+| POST | `/api/tasks//:var` | 登录 | ✓ | `deleteTask` |
+| POST | `/api/tasks//:var/complete` | 登录 | ✓ | `completeTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `approveTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `rejectTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `reviewTask` |
+| POST | `/api/tasks/batch-complete` | 登录 |  | `batchCompleteTasks` |
+| POST | `/api/tasks/create` | 登录 |  | `createTask` |
+| POST | `/api/tasks/history` | 登录 |  | `getTaskHistory` |
+| POST | `/api/tasks/pending-review` | 登录 |  | `getPendingReviewTasks` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasksByCategory` |
+| POST | `/api/tasks/today-parent` | 登录 |  | `getTodayParentTasks` |
+| POST | `/api/user/info` | 登录 |  | `getUserInfo` |
+| POST | `/api/user/join-family` | 登录 |  | `joinFamily` |
+| POST | `/api/user/switch-back-to-parent` | 登录 |  | `switchBackToParent` |
+| POST | `/api/user/switch-mode` | 登录 |  | `switchMode` |
+| POST | `/api/user/switch-to-child` | 登录 |  | `switchToChild` |
+| POST | `/api/user/update` | 登录 |  | `updateUserInfo` |
+| POST | `/api/vendor/apply` | 登录 |  | `vendorApply` |
+| POST | `/api/vendor/info` | 公开 |  | `vendorInfo` |
+| POST | `/api/vendor/status` | 公开 |  | `vendorStatus` |
+| POST | `/api/wealth/checkin/list` | 登录 |  | `getCheckinList` |
+| POST | `/api/wealth/insurance/list` | 公开 |  | `getInsuranceList` |
+| POST | `/api/wishes//:var/approve-exchange` | 登录 | ✓ | `approveWishExchange` |
+| POST | `/api/wishes//:var/price` | 登录 | ✓ | `setWishPrice` |
+| POST | `/api/wishes/create` | 登录 |  | `createWish` |
+| POST | `/api/wishes/list` | 登录 |  | `getWishes` |
+| POST | `/api/wishes/pending` | 登录 |  | `getPendingWishes` |
+| POST | `/api/withdrawal/apply` | 登录 |  | `applyWithdrawal` |
+
+### __tests__/store/store.test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/user/switch-role` | 登录 |  | `switchRole` |
+
+### components/DimensionActivities  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### components/DimensionProducts  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/recommend/dimension-products` | 登录 |  | `getDimensionProducts` |
+| POST | `/api/recommend/repurchase-reminder/'/:var + '/click` | 登录 | ✓ | `clickRepurchaseReminder` |
+
+### components/DimensionTasks  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+
+### components/MemberSelector  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/relationship/pairwise` | 登录 |  | `getPairwiseRelationships` |
+| POST | `/api/family/user/create-family` | 登录 |  | `createFamily` |
+
+### components/OnboardingGuide  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide-config/current` | 登录 |  | `getGuideConfig` |
+
+### components/OnboardingProgressBar  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/onboarding/progress` | 登录 |  | `getOnboardingProgress` |
+
+### components/RelatedContent  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/content/related-items` | 登录 |  | `getContentRelated` |
+
+### components/address-picker  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/streets/provinces')
+}
+
+// 根据父级ID获取子级地址
+export const getStreetChildren = (parentId) => {
+  return request(`/api/streets/children//:var`)
+}
+
+// 根据ID获取地址详情
+export const getStreetById = (id) => {
+  return request(`/api/streets//:var`)
+}
+
+// 获取地址完整路径
+export const getStreetPath = (id) => {
+  return request(`/api/streets//:var/path`)
+}
+
+// 搜索地址
+export const searchStreet = (keyword) => {
+  return request('/api/streets/search` | 公开 | ✓ | `getProvinces` |
+
+### components/daily-task-card  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/daily-task/overview` | 登录 |  | `getDailyTaskOverview` |
+
+### components/login-sheet  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/wechat-phone-login` | 公开 |  | `wechatPhoneLogin` |
+
+### components/share-mixin  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+
+### pages/achievement/index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/badges/member/list` | 登录 |  | `getChildBadges` |
+
+### pages/action-detail/components/PearlDiagram  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/pearl/interaction/add` | 登录 |  | `addPearlInteraction` |
+| POST | `/api/pearl/item/update-priority` | 登录 |  | `updatePearlPriority` |
+
+### pages/action-detail/contact-detail  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/contact/delete` | 登录 |  | `deleteContact` |
+| POST | `/api/contact/detail` | 登录 |  | `getContactDetail` |
+| POST | `/api/contact/interaction` | 登录 |  | `recordContactInteraction` |
+| POST | `/api/contact/update` | 登录 |  | `updateContact` |
+
+### pages/action-detail/index  (13 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/ability/map` | 登录 |  | `getAbilityMap` |
+| POST | `/api/content-sections/visible` | 登录 |  | `getVisibleSections` |
+| POST | `/api/dimension/radar-data` | 登录 |  | `getRadarData` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/octopus/analysis/summary` | 登录 |  | `getOctopusAnalysisSummary` |
+| POST | `/api/octopus/effect/key-persons` | 登录 |  | `getOctopusEffectKeyPersons` |
+| POST | `/api/octopus/effect/list` | 登录 |  | `getOctopusEffects` |
+| POST | `/api/pearl/item/delete` | 登录 |  | `deletePearlResource` |
+| POST | `/api/pearl/reminder/list` | 登录 |  | `getPearlReminders` |
+| POST | `/api/pearl/resources` | 登录 |  | `getPearlResources` |
+
+### pages/action-detail/interaction-log  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/interaction/add` | 登录 |  | `addInteraction` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+
+### pages/action-detail/member-action-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/action-detail/octopus-add-effect  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/octopus/effect/add` | 登录 |  | `addOctopusEffect` |
+| POST | `/api/octopus/key-person/bind-system-user` | 登录 |  | `bindOctopusKeyPersonSystemUser` |
+| POST | `/api/octopus/key-person/list` | 登录 |  | `getOctopusKeyPersons` |
+| POST | `/api/octopus/key-person/match-by-phone` | 登录 |  | `matchOctopusKeyPersonByPhone` |
+
+### pages/action-detail/octopus-add-key-person  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/octopus/key-person/add` | 登录 |  | `addOctopusKeyPerson` |
+| POST | `/api/octopus/key-person/list` | 登录 |  | `getOctopusKeyPersons` |
+
+### pages/action-detail/octopus-effects-list  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/octopus/effect/delete` | 登录 |  | `deleteOctopusEffect` |
+| POST | `/api/octopus/effect/list` | 登录 |  | `getOctopusEffects` |
+
+### pages/action-detail/pearl-add-resource  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/contact/list` | 登录 |  | `getContactList` |
+| POST | `/api/pearl/connection-types` | 登录 |  | `getConnectionTypes` |
+| POST | `/api/pearl/item/add` | 登录 |  | `addPearlResource` |
+
+### pages/action-detail/relationship-questionnaire  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/questionnaire/generate` | 登录 |  | `generateQuestionnaire` |
+| POST | `/api/family/questionnaire/snapshot/'/:var, 'POST', {}, { timeout: 30000 })
+}
+
+export const getQuestionnaireHistory = (memberId) => {
+  return request('/api/family/questionnaire/history/'/:var, 'POST', {}, { timeout: 30000 })
+}
+
+// ===== 五维家庭自检(P0-1)=====
+export const getSelfCheckQuestions = (params) => {
+  return request('/api/family/self-check/questions` | 登录 | ✓ | `getQuestionnaireSnapshot` |
+| POST | `/api/family/questionnaire/submit` | 登录 |  | `submitQuestionnaire` |
+
+### pages/activity/activity-detail/activity-detail  (12 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/cancel-registration` | 公开 |  | `cancelActivityRegistration` |
+| POST | `/api/activity/checkin` | 公开 |  | `activityCheckin` |
+| POST | `/api/activity/detail` | 公开 |  | `getActivityDetail` |
+| POST | `/api/activity/feedback/my` | 公开 |  | `getMyActivityFeedback` |
+| POST | `/api/activity/feedback/submit` | 公开 |  | `submitActivityFeedback` |
+| POST | `/api/activity/order/create` | 公开 |  | `createActivityOrder` |
+| POST | `/api/activity/registration-roster` | 公开 |  | `getActivityRegistrationRoster` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/poster-template/list` | 登录 |  | `getPosterTemplates` |
+| POST | `/api/share/qrcode` | 登录 |  | `getShareQrCode` |
+| POST | `/api/user/profile/backfill` | 登录 |  | `backfillProfile` |
+
+### pages/activity/create  (6 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/create` | 公开 |  | `adminCreateActivity` |
+| POST | `/api/activity/detail` | 公开 |  | `getActivityDetail` |
+| POST | `/api/activity/publish` | 公开 |  | `adminPublishActivity` |
+| POST | `/api/activity/submit-review` | 公开 |  | `submitActivityForReview` |
+| POST | `/api/activity/update` | 公开 |  | `adminUpdateActivity` |
+| POST | `/api/poster-template/list` | 登录 |  | `getPosterTemplates` |
+
+### pages/activity/index  (11 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/cancel-registration` | 公开 |  | `cancelActivityRegistration` |
+| POST | `/api/activity/checkin` | 公开 |  | `activityCheckin` |
+| POST | `/api/activity/end` | 公开 |  | `adminEndActivity` |
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/activity/my-registrations` | 公开 |  | `getMyActivityRegistrations` |
+| POST | `/api/activity/publish` | 公开 |  | `adminPublishActivity` |
+| POST | `/api/activity/submit-review` | 公开 |  | `submitActivityForReview` |
+| POST | `/api/admin/activity/list` | 公开 |  | `adminListMyActivities` |
+| POST | `/api/admin/activity/withdraw` | 公开 |  | `adminWithdrawActivity` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/vendor/status` | 公开 |  | `vendorStatus` |
+
+### pages/activity/order-pay/order-pay  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/order/handlePaymentSuccess` | 公开 |  | `handleActivityOrderSuccess` |
+| POST | `/api/activity/order/pay` | 公开 |  | `payActivityOrder` |
+
+### pages/ai/chat  (9 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/ai/butler/send` | 公开 |  | `aiSendHealthButlerMessage` |
+| POST | `/api/ai/chat/conversations` | 登录 |  | `aiGetConversations` |
+| POST | `/api/ai/chat/messages` | 登录 |  | `aiGetMessages` |
+| POST | `/api/ai/health-coach/send` | 登录 |  | `aiSendHealthCoachMessage` |
+| POST | `/api/ai/nutrition/send` | 登录 |  | `aiSendNutritionMessage` |
+| POST | `/api/ai/transcribe` | 登录 |  | `sttTranscribe` |
+| POST | `/api/basic-quota/status/all` | 登录 |  | `getAllQuotaStatus` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/article-center/article-detail  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/audio` | 公开 |  | `getArticleAudio` |
+| POST | `/api/articles/complete-read` | 公开 |  | `completeArticleRead` |
+| POST | `/api/articles/detail` | 公开 |  | `getArticleDetail` |
+| POST | `/api/articles/quiz/generate` | 公开 |  | `generateQuiz` |
+| POST | `/api/articles/quiz/submit` | 公开 |  | `submitQuiz` |
+| POST | `/api/articles/report-reading-time` | 公开 |  | `reportReadingTime` |
+| POST | `/api/share/qrcode` | 登录 |  | `getShareQrCode` |
+| POST | `/api/tasks//:var/complete` | 登录 | ✓ | `completeTask` |
+
+### pages/article-center/article-edit  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/publish` | 公开 |  | `publishArticle` |
+
+### pages/article-center/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/featured` | 公开 |  | `getFeaturedArticles` |
+| POST | `/api/articles/list` | 公开 |  | `getArticleList` |
+
+### pages/article-center/my-posts  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/my-posts` | 公开 |  | `getMyPosts` |
+
+### pages/assessment-plan/detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/result/plans/list` | 公开 |  | `getMyAssessmentPlans` |
+
+### pages/assessment-plan/list  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/result/plans/list` | 公开 |  | `getMyAssessmentPlans` |
+
+### pages/assessment/apply  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/assessment/appointment/create` | 登录 |  | `createAssessmentAppointmentWithQuota` |
+| POST | `/api/assessment/quota/my-list` | 登录 |  | `getAssessmentQuotas` |
+| POST | `/api/guide/invite-code/validate` | 公开 |  | `validateInviteCode` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/package/available-guides` | 登录 |  | `getAvailableGuides` |
+
+### pages/assessment/purchase  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/order/create` | 登录 |  | `createAssessmentOrder` |
+| POST | `/api/dan-assessment/order/detail` | 登录 |  | `getAssessmentOrderDetail` |
+| POST | `/api/guide/invite-code/validate` | 公开 |  | `validateInviteCode` |
+| POST | `/api/package/available-guides` | 登录 |  | `getAvailableGuides` |
+
+### pages/assessment/quota  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/assessment/quota/my-list` | 登录 |  | `getAssessmentQuotas` |
+
+### pages/assessment/results  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/child-results` | 登录 |  | `getChildAssessmentResults` |
+| POST | `/api/dan-assessment/my-results` | 登录 |  | `getMyAssessmentResults` |
+
+### pages/assessment/upload-report  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/result/upload` | 公开 |  | `uploadAssessmentReport` |
+
+### pages/body-detail/dimension-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dimension/history` | 登录 |  | `getDimensionHistory` |
+| POST | `/api/dimension/overview` | 登录 |  | `getDimensionOverview` |
+
+### pages/body-detail/dimension-questionnaire  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/submit-answers` | 公开 |  | `submitAnswers` |
+| POST | `/api/dimension/questionnaire` | 登录 |  | `submitDimensionQuestionnaire` |
+
+### pages/body-detail/health-dimensions  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dimension/overview` | 登录 |  | `getDimensionOverview` |
+| POST | `/api/dimension/upload` | 登录 |  | `uploadDimensionScore` |
+
+### pages/body-detail/health-report  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/nutrition/deficiency` | 登录 |  | `getDeficiencyAnalysis` |
+
+### pages/body-detail/index  (10 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/content-sections/visible` | 登录 |  | `getVisibleSections` |
+| POST | `/api/dimension/overview` | 登录 |  | `getDimensionOverview` |
+| POST | `/api/dimension/radar-data` | 登录 |  | `getRadarData` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/gut-flora` | 登录 |  | `getGutFloraIndicators` |
+| POST | `/api/health/indicators` | 登录 |  | `getLatestIndicators` |
+| POST | `/api/health/report/body-abnormal` | 登录 |  | `getBodyAbnormalIndicators` |
+
+### pages/body-detail/member-body-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/butler/apply  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/butler/apply` | 公开 |  | `butlerApply` |
+
+### pages/butler/select  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/butler/available-list` | 公开 |  | `getAvailableButlers` |
+| POST | `/api/butler/my-butler` | 公开 |  | `getMyButler` |
+| POST | `/api/butler/select` | 公开 |  | `selectButler` |
+
+### pages/child/rewards  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/points/balance` | 登录 |  | `getPointsBalance` |
+| POST | `/api/rewards/wishlist` | 登录 |  | `getWishlist` |
+| POST | `/api/user/switch-back-to-parent` | 登录 |  | `switchBackToParent` |
+
+### pages/child/tasks  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/user/switch-back-to-parent` | 登录 |  | `switchBackToParent` |
+
+### pages/cognitive-hall  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/child` | 登录 |  | `getCognitiveChildScores` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/cognitive-test/language-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/cognitive-test/logic-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/cognitive-test/memory-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/cognitive-test/perception-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/cognitive-test/spatial-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/cognitive-test/speed-test  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/dan-assessment/comparison  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-report/compare` | 登录 |  | `compareDanReports` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/dan-assessment/report-result  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-report/'/:var, 'POST', {})
+// DAN 报告列表(对比页:某成员的所有上传)
+export const getDanReportList = (params) => request('/api/dan-report/list` | 登录 | ✓ | `getDanReportDetail` |
+
+### pages/diet/index  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/ingredients/add` | 登录 |  | `addDietIngredient` |
+| POST | `/api/diet/ingredients/recommend` | 登录 |  | `refreshDietIngredients` |
+| POST | `/api/diet/ingredients/remove` | 登录 |  | `removeDietIngredient` |
+| POST | `/api/diet/ingredients/search` | 登录 |  | `searchDietFoods` |
+| POST | `/api/diet/ingredients/suggest` | 登录 |  | `getDietIngredients` |
+| POST | `/api/diet/meals/config` | 登录 |  | `getMealConfig` |
+| POST | `/api/diet/recommendation/generate` | 登录 |  | `generateDietRecommendation` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+
+### pages/diet/meal-config  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/meals/config` | 登录 |  | `getMealConfig` |
+| POST | `/api/diet/meals/config/save` | 公开 |  | `saveMealConfig` |
+
+### pages/diet/preferences  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/preferences/current-member` | 登录 |  | `getDietPreferences` |
+| POST | `/api/diet/preferences/save` | 登录 |  | `saveDietPreferences` |
+
+### pages/diet/recommendation  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/recommendation/complete` | 登录 |  | `completeDietRecommendation` |
+| POST | `/api/diet/recommendation/generate` | 登录 |  | `generateDietRecommendation` |
+| POST | `/api/diet/recommendation/regenerate` | 登录 |  | `regenerateDietRecommendation` |
+| POST | `/api/diet/recommendation/today` | 登录 |  | `getDietRecommendation` |
+
+### pages/diet/record-detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/record/daily` | 登录 |  | `getDietDailyRecords` |
+
+### pages/diet/records  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/food/recommendation/members` | 登录 |  | `getCautionFamilyMembers` |
+| POST | `/api/health/meal/alerts` | 登录 |  | `getMealAlerts` |
+| POST | `/api/health/meal/daily` | 登录 |  | `getMealDaily` |
+| POST | `/api/health/meal/weekly` | 登录 |  | `getMealWeekly` |
+
+### pages/discover-detail/product-detail/product-detail  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cart/add` | 登录 |  | `cartAdd` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/product/detail` | 公开 |  | `productDetail` |
+| POST | `/api/product/order/pay` | 公开 |  | `productOrderPay` |
+| POST | `/api/product/spec/map` | 公开 |  | `productSpecMap` |
+| POST | `/api/share/qrcode` | 登录 |  | `getShareQrCode` |
+| POST | `/api/special-price/info` | 登录 |  | `getSpecialPriceInfo` |
+
+### pages/discover/circle-feed  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/circle/comment/add` | 登录 |  | `addCircleComment` |
+| POST | `/api/circle/comment/list` | 登录 |  | `getCircleComments` |
+| POST | `/api/circle/feed` | 公开 |  | `getCircleFeed` |
+| POST | `/api/circle/members` | 登录 |  | `getCircleMembers` |
+| POST | `/api/circle/post/create` | 登录 |  | `createCirclePost` |
+| POST | `/api/circle/post/delete` | 登录 |  | `deleteCirclePost` |
+| POST | `/api/circle/post/like` | 登录 |  | `toggleCircleLike` |
+
+### pages/discover/circles  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/circle/approve` | 登录 |  | `approveCircleMember` |
+| POST | `/api/circle/discover` | 登录 |  | `discoverCircles` |
+| POST | `/api/circle/join` | 登录 |  | `joinGeneralCircle` |
+| POST | `/api/circle/leave` | 登录 |  | `leaveGeneralCircle` |
+| POST | `/api/circle/my-circles` | 登录 |  | `getMyCircles` |
+| POST | `/api/circle/pending-members` | 登录 |  | `getPendingCircleMembers` |
+| POST | `/api/circle/update` | 登录 |  | `updateCircle` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+
+### pages/discover/create-circle  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/circle/create` | 登录 |  | `createGeneralCircle` |
+
+### pages/discover/index  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/featured` | 公开 |  | `getFeaturedArticles` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+
+### pages/energy/detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/logs` | 登录 |  | `getEnergyLogs` |
+
+### pages/energy/index  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/family/add-member  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/check-phone` | 公开 |  | `checkPhone` |
+| POST | `/api/consent/record` | 登录 |  | `recordConsent` |
+| POST | `/api/family/member/add` | 登录 |  | `addFamilyMember` |
+| POST | `/api/family/member/update` | 登录 |  | `updateFamilyMember` |
+
+### pages/family/manual-score-entry  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/manual-score/submit` | 登录 |  | `submitManualScore` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/family/mbti-entry  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/family/mbti-profile  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/mbti/profile` | 登录 |  | `getMbtiProfile` |
+
+### pages/family/mbti-result  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/mbti/latest` | 登录 |  | `getMbtiLatest` |
+
+### pages/family/mbti-test  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/mbti/questions` | 登录 |  | `getMbtiQuestions` |
+| POST | `/api/family/mbti/submit` | 登录 |  | `submitMbti` |
+
+### pages/family/self-check  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/self-check/submit` | 登录 |  | `submitSelfCheck` |
+
+### pages/family/self-check-ai  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/self-check/submit` | 登录 |  | `submitSelfCheck` |
+
+### pages/family/self-check-entry  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/self-check/ignore` | 登录 |  | `ignoreSelfCheck` |
+| POST | `/api/family/self-check/status` | 登录 |  | `getSelfCheckStatus` |
+| POST | `/api/family/self-check/trend-analysis` | 登录 |  | `getSelfCheckTrendAnalysis` |
+
+### pages/family/self-check-result  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/self-check/generate-plan` | 登录 |  | `generateSelfCheckPlan` |
+| POST | `/api/family/self-check/history` | 登录 |  | `getSelfCheckHistory` |
+| POST | `/api/family/self-check/latest` | 登录 |  | `getSelfCheckLatest` |
+| POST | `/api/micro-action/complete` | 登录 |  | `microActionComplete` |
+| POST | `/api/micro-action/today` | 登录 |  | `microActionToday` |
+
+### pages/games/1a2b  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/mini-game/complete` | 登录 |  | `completeMiniGame` |
+
+### pages/games/list  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/mini-game/list` | 登录 |  | `getMiniGameList` |
+
+### pages/games/records  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/game/history` | 登录 |  | `getGameHistory` |
+
+### pages/games/schulte  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/mini-game/complete` | 登录 |  | `completeMiniGame` |
+
+### pages/games/stats  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/game/best` | 登录 |  | `getGameBestScores` |
+| POST | `/api/game/leaderboard` | 登录 |  | `getGameLeaderboard` |
+| POST | `/api/game/stats` | 登录 |  | `getGameStats` |
+
+### pages/games/sudoku  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/mini-game/complete` | 登录 |  | `completeMiniGame` |
+
+### pages/growth-main/index  (10 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/food/recommendation/caution` | 登录 |  | `getFoodCautionList` |
+| POST | `/api/growth/recommendations` | 登录 |  | `getGrowthRecommendations` |
+| POST | `/api/health/checkin/list` | 登录 |  | `healthCheckinList` |
+| POST | `/api/health/exercise/list` | 登录 |  | `getExerciseRecords` |
+| POST | `/api/health/meal/list` | 登录 |  | `getHealthMealList` |
+| POST | `/api/health/sleep/list` | 登录 |  | `getSleepRecords` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/mind/checkin/list` | 登录 |  | `getEmotionCheckinList` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/wealth/checkin/list` | 登录 |  | `getCheckinList` |
+
+### pages/growth/assessment-result  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/result/'/:var, 'POST')
+}
+
+// 创建测评预约
+export const createAssessmentAppointment = (data) => {
+  return request('/api/dan-assessment/appointment/create` | 公开 | ✓ | `getAssessmentResult` |
+
+### pages/growth/caution-detail  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/food/recommendation/caution` | 登录 |  | `getFoodCautionList` |
+| POST | `/api/food/recommendation/members` | 登录 |  | `getCautionFamilyMembers` |
+| POST | `/api/food/recommendation/trend` | 登录 |  | `getFoodCautionTrend` |
+| POST | `/api/health/knowledge/v3/section` | 登录 |  | `getKnowledgeSection` |
+
+### pages/growth/challenge-progress  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/purchase/challenge/progress` | 登录 |  | `getChallengeProgress` |
+
+### pages/growth/create  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/growth/record/create` | 登录 |  | `createGrowthRecord` |
+| POST | `/api/growth/record/create-with-order` | 登录 |  | `createGrowthRecord` |
+
+### pages/growth/detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/growth/record/'/:var + '/supplements` | 登录 | ✓ | `getGrowthSupplements` |
+
+### pages/growth/diet-checkin  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/ai/transcribe` | 登录 |  | `sttTranscribe` |
+| POST | `/api/basic-quota/status/all` | 登录 |  | `getAllQuotaStatus` |
+
+### pages/growth/exercise-checkin  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/ai/transcribe` | 登录 |  | `sttTranscribe` |
+
+### pages/growth/supplement  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/growth/record/supplement` | 登录 |  | `createGrowthSupplement` |
+| POST | `/api/growth/record/upload-and-parse` | 登录 |  | `uploadAndParseReport` |
+
+### pages/growth/upload  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/growth/record/child/'/:var, 'POST')
+}
+export const getGrowthRecordDetail = (id) => {
+  return request('/api/growth/record/'/:var, 'POST')
+}
+export const deleteGrowthRecord = (id) => {
+  return request('/api/growth/record/'/:var + '/delete` | 登录 | ✓ | `getChildRecords` |
+| POST | `/api/growth/record/create-from-upload` | 登录 |  | `createGrowthRecordFromUpload` |
+| POST | `/api/growth/record/upload-and-parse` | 登录 |  | `uploadAndParseReport` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+
+### pages/guide/activities/detail  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/activities/create` | 登录 |  | `createActivity` |
+| POST | `/api/guide/activities/detail` | 登录 |  | `getGuideActivityDetail` |
+| POST | `/api/guide/activities/publish` | 登录 |  | `publishActivity` |
+| POST | `/api/guide/activities/update` | 登录 |  | `updateActivity` |
+
+### pages/guide/activities/index  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/activities/cancel` | 登录 |  | `cancelActivity` |
+| POST | `/api/guide/activities/delete` | 登录 |  | `deleteActivity` |
+| POST | `/api/guide/activities/list` | 登录 |  | `getGuideActivityList` |
+| POST | `/api/guide/activities/publish` | 登录 |  | `publishActivity` |
+
+### pages/guide/bind/invite  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/common/qrcode` | 登录 |  | `generateQrCodeFromText` |
+| POST | `/api/guide/bind/confirm` | 登录 |  | `confirmBind` |
+| POST | `/api/guide/bind/invite` | 登录 |  | `generateBindInvite` |
+
+### pages/guide/hierarchy/index  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/all-child-guides` | 登录 |  | `getAllChildGuides` |
+| POST | `/api/guide/child-guides` | 登录 |  | `getChildGuides` |
+| POST | `/api/guide/parent-guide` | 登录 |  | `getParentGuide` |
+
+### pages/guide/packages/create  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/packages` | 登录 |  | `createPackage` |
+
+### pages/guide/packages/detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/packages//:var/items` | 登录 | ✓ | `addPackageItem` |
+| POST | `/api/packages/items/'/:var, 'POST', { _method: 'PUT' }, data)
+}
+
+// 删除任务项
+export const deletePackageItem = (itemId) => {
+  return request('/api/packages/items/'/:var, 'POST', { _method: 'DELETE' })
+}
+
+// 获取任务模板任务项
+export const getPackageItems = (packageId) => {
+  return request(`/api/packages//:var/items`, 'POST')
+}
+
+
+// 获取我的任务计划
+export const getMyPlans = () => {
+  return request('/api/market/plans` | 公开 | ✓ | `updatePackageItem` |
+
+### pages/guide/packages/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/packages//:var/publish` | 登录 | ✓ | `publishPackage` |
+| POST | `/api/packages//:var/submit` | 登录 | ✓ | `submitPackageForReview` |
+
+### pages/guide/register/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/invite-code/validate` | 公开 |  | `validateInviteCode` |
+| POST | `/api/guide/register` | 公开 |  | `registerGuide` |
+
+### pages/health-main/index  (10 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/featured` | 公开 |  | `getFeaturedArticles` |
+| POST | `/api/cognitive/child` | 登录 |  | `getCognitiveChildScores` |
+| POST | `/api/cognitive/family` | 登录 |  | `getCognitiveFamilyScores` |
+| POST | `/api/dimension/overview` | 登录 |  | `getDimensionOverview` |
+| POST | `/api/emireport/latest` | 登录 |  | `getEmiReport` |
+| POST | `/api/energy/wealth-detail` | 登录 |  | `getWealthDetail` |
+| POST | `/api/family/relationship/scores` | 登录 |  | `getRelationshipScores` |
+| POST | `/api/health/plan/list` | 登录 |  | `getHealthPlanList` |
+| POST | `/api/health/report/list` | 登录 |  | `getReportList` |
+| POST | `/api/survey/status` | 登录 |  | `getSurveyStatus` |
+
+### pages/health/bodyfat-confirm  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/report/bodyfat-save` | 登录 |  | `saveBodyFatMetrics` |
+
+### pages/health/challenge-manage  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/challenge/create` | 登录 |  | `createChallenge` |
+| POST | `/api/health/challenge/history` | 登录 |  | `getChallengeHistory` |
+| POST | `/api/health/challenge/list` | 登录 |  | `getChallengeList` |
+| POST | `/api/health/challenge/respond` | 登录 |  | `respondChallenge` |
+| POST | `/api/health/challenge/update/'/:var, 'POST', data)
+export const deleteChallenge = (id) => request('/api/health/challenge/delete/'/:var, 'POST', data)
+export const getChallengeTemplates = () => request('/api/health/challenge/templates` | 登录 | ✓ | `updateChallenge` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/health/components/MemberChipPicker  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/health/components/feedback-popup  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/feedback/submit` | 公开 |  | `submitFeedback` |
+
+### pages/health/doa-index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/doa/overview` | 登录 |  | `getDoaOverview` |
+
+### pages/health/doa-stage-create  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/doa/stage/create` | 登录 |  | `createDoaStage` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/health/doa-stage-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/doa/stage/cancel` | 登录 |  | `cancelDoaStage` |
+| POST | `/api/doa/stage/detail` | 登录 |  | `getDoaStageDetail` |
+
+### pages/health/doa-week-edit  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/doa/stage/detail` | 登录 |  | `getDoaStageDetail` |
+| POST | `/api/doa/week/plan` | 登录 |  | `submitDoaWeekPlan` |
+| POST | `/api/doa/week/review` | 登录 |  | `submitDoaWeekReview` |
+
+### pages/health/gut-flora-detail  (13 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/add` | 登录 |  | `addFamilyMember` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/food/recommendation/caution` | 登录 |  | `getFoodCautionList` |
+| POST | `/api/health/foods` | 登录 |  | `getHealthFoods` |
+| POST | `/api/health/knowledge/query` | 登录 |  | `queryKnowledgeBase` |
+| POST | `/api/health/knowledge/v3/indicator/query` | 登录 |  | `queryIndicatorKnowledge` |
+| POST | `/api/health/report/confirm` | 登录 |  | `confirmReportPreview` |
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+| POST | `/api/health/report/discard` | 登录 |  | `discardReportDraft` |
+| POST | `/api/health/report/edit` | 登录 |  | `editHealthReport` |
+| POST | `/api/health/report/parse` | 登录 |  | `parseReportDraft` |
+| POST | `/api/indicator/change-ranking` | 登录 |  | `getIndicatorChangeRanking` |
+| POST | `/api/nutrition/beijing/analysis` | 登录 |  | `getGutFloraAnalysis` |
+
+### pages/health/gut-flora-foods-detail  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/food/recommendation/members` | 登录 |  | `getCautionFamilyMembers` |
+| POST | `/api/food/recommendation/trend` | 登录 |  | `getFoodCautionTrend` |
+| POST | `/api/health/foods` | 登录 |  | `getHealthFoods` |
+| POST | `/api/health/knowledge/v3/food/query` | 登录 |  | `queryFoodKnowledge` |
+| POST | `/api/health/report/edit` | 登录 |  | `editHealthReport` |
+
+### pages/health/gut-flora-risks-detail  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/knowledge/query` | 登录 |  | `queryKnowledgeBase` |
+| POST | `/api/health/knowledge/unified/disease/query` | 登录 |  | `queryDiseaseKnowledge` |
+| POST | `/api/health/knowledge/v3/indicator/query` | 登录 |  | `queryIndicatorKnowledge` |
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+| POST | `/api/health/report/edit` | 登录 |  | `editHealthReport` |
+
+### pages/health/gut-flora-species-detail  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/knowledge/query` | 登录 |  | `queryKnowledgeBase` |
+| POST | `/api/health/knowledge/v3/bacteria/query` | 登录 |  | `queryBacteriaKnowledge` |
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+| POST | `/api/health/report/edit` | 登录 |  | `editHealthReport` |
+
+### pages/health/health-plan-summary  (11 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/preferences/current-member` | 登录 |  | `getDietPreferences` |
+| POST | `/api/diet/preferences/save` | 登录 |  | `saveDietPreferences` |
+| POST | `/api/health-status/get` | 登录 |  | `getHealthStatus` |
+| POST | `/api/health-status/save` | 登录 |  | `saveHealthStatus` |
+| POST | `/api/health-status/signature` | 登录 |  | `saveHealthSignature` |
+| POST | `/api/health/plan/confirm` | 登录 |  | `confirmPlan` |
+| POST | `/api/health/plan/detail` | 登录 |  | `getHealthPlanDetail` |
+| POST | `/api/health/plan/generate` | 登录 |  | `generateHealthPlan` |
+| POST | `/api/health/plan/regenerate-section` | 登录 |  | `regenerateSection` |
+| POST | `/api/health/plan/save` | 登录 |  | `saveHealthPlan` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/health/health-status-form  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health-status/get` | 登录 |  | `getHealthStatus` |
+| POST | `/api/health-status/save` | 登录 |  | `saveHealthStatus` |
+
+### pages/health/health-survey  (6 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/diet/preferences/current-member` | 登录 |  | `getDietPreferences` |
+| POST | `/api/diet/preferences/save` | 登录 |  | `saveDietPreferences` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health-status/get` | 登录 |  | `getHealthStatus` |
+| POST | `/api/health-status/save` | 登录 |  | `saveHealthStatus` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/health/indicator-curve  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/indicator/change-ranking` | 登录 |  | `getIndicatorChangeRanking` |
+| POST | `/api/indicator/trend` | 登录 |  | `getIndicatorTrend` |
+
+### pages/health/indicator-quicklook  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/indicator/quick-lookup` | 登录 |  | `getIndicatorQuickLookup` |
+
+### pages/health/my-feedback  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/feedback/list` | 公开 |  | `getMyReportFeedbacks` |
+
+### pages/health/nutrition-profile  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/nutrition/deficiency` | 登录 |  | `getDeficiencyAnalysis` |
+| POST | `/api/health/nutrition/profile` | 登录 |  | `getChildNutritionProfile` |
+
+### pages/health/physical-exam-detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+
+### pages/health/plan-list  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/plan/delete` | 登录 |  | `deleteHealthPlan` |
+| POST | `/api/health/plan/list` | 登录 |  | `getHealthPlanList` |
+
+### pages/health/report-confirm  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/add` | 登录 |  | `addFamilyMember` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/report/parse` | 登录 |  | `parseReportDraft` |
+
+### pages/health/report-detail  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/add` | 登录 |  | `addFamilyMember` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/report/edit` | 登录 |  | `editHealthReport` |
+| POST | `/api/health/report/parse` | 登录 |  | `parseReportDraft` |
+| POST | `/api/health/report/payload` | 登录 |  | `getReportPayload` |
+
+### pages/health/report-list  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/report/collecting-list` | 登录 |  | `getCollectingReports` |
+| POST | `/api/health/report/delete` | 登录 |  | `deleteReport` |
+| POST | `/api/health/report/list` | 登录 |  | `getReportList` |
+| POST | `/api/health/report/reassign` | 登录 |  | `reassignReport` |
+| POST | `/api/health/report/transfer/approve` | 登录 |  | `approveReportTransfer` |
+| POST | `/api/health/report/transfer/deny` | 登录 |  | `denyReportTransfer` |
+| POST | `/api/health/report/transfer/list` | 登录 |  | `getReportTransferList` |
+
+### pages/health/report-survey  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/survey/create` | 登录 |  | `createReportSurvey` |
+| POST | `/api/health/survey/submit` | 登录 |  | `submitReportSurvey` |
+| POST | `/api/survey/status` | 登录 |  | `getSurveyStatus` |
+
+### pages/health/report-upload  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/report/collect/status` | 登录 |  | `getReportCollectStatus` |
+| POST | `/api/health/report/transfer/request` | 登录 |  | `requestReportTransfer` |
+| POST | `/api/health/report/upload-only` | 登录 |  | `uploadReportOnly` |
+
+### pages/health/survey-history  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/survey/history` | 登录 |  | `getSurveyHistory` |
+| POST | `/api/survey/template/active` | 登录 |  | `getActiveTemplates` |
+
+### pages/health/survey-questionnaire  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/survey/submit` | 登录 |  | `submitSurvey` |
+| POST | `/api/survey/template/active` | 登录 |  | `getActiveTemplates` |
+
+### pages/health/teacher-service  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health-plan/available-teachers` | 登录 |  | `getAvailableTeachers` |
+
+### pages/home-pages/child-index  (11 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/energy/logs` | 登录 |  | `getEnergyLogs` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/guide-config/current` | 登录 |  | `getGuideConfig` |
+| POST | `/api/guide/popup/consume` | 登录 |  | `consumeGuidePopup` |
+| POST | `/api/guide/popup/list` | 登录 |  | `getGuidePopupList` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/unlock/status` | 登录 |  | `getUnlockStatus` |
+| POST | `/api/user/switch-mode` | 登录 |  | `switchMode` |
+
+### pages/home-pages/components/AdBanner  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home-banner/list` | 登录 |  | `getHomeBanners` |
+
+### pages/home-pages/components/ContactImport  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/contact/import-phone` | 登录 |  | `importPhoneContact` |
+
+### pages/home-pages/components/DailySummary  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/feedback/read` | 公开 |  | `markFeedbackRead` |
+| POST | `/api/feedback/today` | 公开 |  | `getTodayFeedback` |
+
+### pages/home-pages/components/MicroActionCard  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/micro-action/complete` | 登录 |  | `microActionComplete` |
+| POST | `/api/micro-action/today` | 登录 |  | `microActionToday` |
+
+### pages/home-pages/member-home-detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/home-pages/parent-index  (23 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/articles/featured` | 公开 |  | `getFeaturedArticles` |
+| POST | `/api/contact/list` | 登录 |  | `getContactList` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/member/switch` | 登录 |  | `switchToFamilyMember` |
+| POST | `/api/family/self-check/status` | 登录 |  | `getSelfCheckStatus` |
+| POST | `/api/health/alert/dismiss` | 登录 |  | `dismissAlert` |
+| POST | `/api/health/alert/list` | 登录 |  | `getActiveAlerts` |
+| POST | `/api/health/challenge/list` | 登录 |  | `getChallengeList` |
+| POST | `/api/health/circle/list` | 登录 |  | `getCircleList` |
+| POST | `/api/health/circle/ranking` | 登录 |  | `getCircleRanking` |
+| POST | `/api/health/family/ranking` | 登录 |  | `getFamilyRanking` |
+| POST | `/api/invite/qrcode` | 登录 |  | `getInviteQrCode` |
+| POST | `/api/parent/dashboard` | 登录 |  | `getParentDashboard` |
+| POST | `/api/stats/child-completion` | 登录 |  | `getChildCompletionStats` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `approveTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `rejectTask` |
+| POST | `/api/tasks/pending-review` | 登录 |  | `getPendingReviewTasks` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/unlock/status` | 登录 |  | `getUnlockStatus` |
+| POST | `/api/wishes/pending` | 登录 |  | `getPendingWishes` |
+
+### pages/home/app-library  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home/app-library` | 登录 |  | `getAppLibrary` |
+| POST | `/api/home/shortcut/reset` | 登录 |  | `resetShortcutConfig` |
+| POST | `/api/home/shortcut/save` | 登录 |  | `saveShortcutConfig` |
+
+### pages/index-home/index  (28 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/admin/notices/all` | 登录 |  | `getNotices` |
+| POST | `/api/articles/featured` | 公开 |  | `getFeaturedArticles` |
+| POST | `/api/commission/cf/list` | 登录 |  | `getCfList` |
+| POST | `/api/commission/cf/summary` | 登录 |  | `getCfSummary` |
+| POST | `/api/energy/logs` | 登录 |  | `getEnergyLogs` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/member/switch` | 登录 |  | `switchToFamilyMember` |
+| POST | `/api/family/self-check/status` | 登录 |  | `getSelfCheckStatus` |
+| POST | `/api/guide-config/current` | 登录 |  | `getGuideConfig` |
+| POST | `/api/guide/parent-invite/accept` | 登录 |  | `acceptParentInvite` |
+| POST | `/api/guide/popup/consume` | 登录 |  | `consumeGuidePopup` |
+| POST | `/api/guide/popup/list` | 登录 |  | `getGuidePopupList` |
+| POST | `/api/health/challenge/list` | 登录 |  | `getChallengeList` |
+| POST | `/api/health/challenge/progress` | 登录 |  | `updateChallengeProgress` |
+| POST | `/api/health/challenge/respond` | 登录 |  | `respondChallenge` |
+| POST | `/api/home/app-library` | 登录 |  | `getAppLibrary` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/notification/list` | 登录 |  | `getNotificationList` |
+| POST | `/api/notification/read` | 登录 |  | `readNotification` |
+| POST | `/api/points/logs` | 登录 |  | `getPointsLogs` |
+| POST | `/api/survey/status` | 登录 |  | `getSurveyStatus` |
+| POST | `/api/tasks/history` | 登录 |  | `getTaskHistory` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+
+### pages/invite/join  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/invite/check-family` | 公开 |  | `checkUserFamily` |
+| POST | `/api/family/invite/validate` | 公开 |  | `validateInvitation` |
+| POST | `/api/family/invite/validate-family-code` | 公开 |  | `validateFamilyCode` |
+| POST | `/api/invite/bind` | 登录 |  | `bindReferral` |
+
+### pages/invite/join-form  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/invite/request-join-by-code` | 公开 |  | `requestJoinByCode` |
+| POST | `/api/user/update` | 登录 |  | `updateUserInfo` |
+
+### pages/login/scan-login  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/wechat-web/scan` | 公开 |  | `wechatWebScan` |
+
+### pages/match/street-match  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/admin/families/count` | 登录 |  | `countFamiliesByStreetIds` |
+| POST | `/api/admin/teachers/count` | 登录 |  | `countTeachersByStreetIds` |
+| POST | `/api/streets//:var/match`)
+}
+
+// 按区域统计
+export const getStreetStats = (level = 4) => {
+  return request('/api/streets/stats', 'POST', { level })
+}
+
+// 获取家庭详情(含地址信息)
+export const getFamilyDetail = (id) => {
+  return request(`/api/admin/families//:var`)
+}
+
+// 更新家庭地址
+export const updateFamilyAddress = (data) => {
+  return request(`/api/admin/families/update` | 公开 | ✓ | `matchByStreet` |
+
+### pages/meal/log  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/meal/log` | 登录 |  | `logMeal` |
+| POST | `/api/meal/logs` | 登录 |  | `getMealLogs` |
+| POST | `/api/meal/nutrition-summary` | 登录 |  | `getNutritionSummary` |
+
+### pages/meal/preference  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/nutrition/profile/get` | 登录 |  | `getNutritionProfile` |
+| POST | `/api/nutrition/profile/save` | 登录 |  | `saveNutritionProfile` |
+
+### pages/meal/recommend  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/meal/recommend` | 登录 |  | `getMealRecommend` |
+| POST | `/api/meal/replace` | 登录 |  | `replaceFood` |
+
+### pages/member-detail/components/member-detail-sections/action-section  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasksByCategory` |
+| POST | `/api/wealth/checkin/stats` | 登录 |  | `getCheckinStats` |
+
+### pages/member-detail/components/member-detail-sections/body-section  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dimension/overview` | 登录 |  | `getDimensionOverview` |
+| POST | `/api/health/analysis` | 登录 |  | `getHealthAnalysis` |
+| POST | `/api/wealth/checkin/list` | 登录 |  | `getCheckinList` |
+
+### pages/member-detail/components/member-detail-sections/mind-section  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/contact/list` | 登录 |  | `getContactList` |
+| POST | `/api/family/relationship/health-alerts` | 登录 |  | `getHealthAlerts` |
+| POST | `/api/family/relationship/milestones` | 登录 |  | `getMilestones` |
+| POST | `/api/family/relationship/scores` | 登录 |  | `getRelationshipScores` |
+
+### pages/member-detail/components/member-detail-sections/wisdom-section  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/assessment/history` | 登录 |  | `getAssessmentHistory` |
+| POST | `/api/assessment/latest-result` | 登录 |  | `getAssessmentLatestResult` |
+
+### pages/member-detail/member-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/activity/list` | 公开 |  | `getActivityList` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/member-detail/report-detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/report/detail` | 登录 |  | `getReportDetail` |
+
+### pages/membership/benefits  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/membership/benefits` | 登录 |  | `getMembershipBenefits` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/membership/index  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/butler/my-butler` | 公开 |  | `getMyButler` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/membership/benefits` | 登录 |  | `getMembershipBenefits` |
+| POST | `/api/membership/compare` | 登录 |  | `getMembershipCompare` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/membership/pay  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/coupon/list` | 登录 |  | `getCouponList` |
+| POST | `/api/membership/orders` | 登录 |  | `createOrder` |
+| POST | `/api/membership/orders/continue` | 登录 |  | `nextOrder` |
+| POST | `/api/membership/plans` | 登录 |  | `getMembershipPlans` |
+
+### pages/membership/result  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/coupon/join-rules` | 登录 |  | `getJoinCouponRules` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/membership/orders/continue` | 登录 |  | `nextOrder` |
+
+### pages/membership/upgrade  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/coupon/join-rules` | 登录 |  | `getJoinCouponRules` |
+| POST | `/api/membership/compare` | 登录 |  | `getMembershipCompare` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/membership/plans` | 登录 |  | `getMembershipPlans` |
+| POST | `/api/membership/upgrade-records` | 登录 |  | `getUpgradeRecords` |
+
+### pages/mind-detail/articles  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/articles/categories` | 公开 |  | `getArticleCategories` |
+| POST | `/api/articles/list` | 公开 |  | `getArticleList` |
+
+### pages/mind-detail/components/PsychCrisisBanner  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/alert/dismiss` | 登录 |  | `dismissAlert` |
+
+### pages/mind-detail/emotion-report  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/emireport/latest` | 登录 |  | `getEmiReport` |
+
+### pages/mind-detail/family-dashboard  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/mind/fortune` | 登录 |  | `getFamilyFortune` |
+| POST | `/api/mind/fortune/month` | 登录 |  | `getMonthFortune` |
+| POST | `/api/mind/fortune/reports` | 登录 |  | `getFortuneReports` |
+| POST | `/api/mind/fortune/week` | 登录 |  | `getWeekFortune` |
+
+### pages/mind-detail/index  (14 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/contact/list` | 登录 |  | `getContactList` |
+| POST | `/api/content-sections/visible` | 登录 |  | `getVisibleSections` |
+| POST | `/api/dan-assessment/report/child` | 登录 |  | `getDanReportByChild` |
+| POST | `/api/dimension/radar-data` | 登录 |  | `getRadarData` |
+| POST | `/api/emireport/latest` | 登录 |  | `getEmiReport` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/relationship/health-alerts` | 登录 |  | `getHealthAlerts` |
+| POST | `/api/family/relationship/milestones` | 登录 |  | `getMilestones` |
+| POST | `/api/health/indicators` | 登录 |  | `getLatestIndicators` |
+| POST | `/api/mind/fortune` | 登录 |  | `getFamilyFortune` |
+
+### pages/mind-detail/innate-portrait  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/mind/innate/reading` | 登录 |  | `getInnateReading` |
+
+### pages/mind-detail/innate-trajectory  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/mind/innate/trajectory` | 登录 |  | `getInnateTrajectory` |
+
+### pages/mind-detail/member-mind-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/mind-detail/training  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/game/stats` | 登录 |  | `getGameStats` |
+
+### pages/notification/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/notification/list` | 登录 |  | `getNotificationList` |
+| POST | `/api/notification/read` | 登录 |  | `readNotification` |
+
+### pages/nutritionist/apply  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/nutritionist/apply` | 公开 |  | `nutritionistApply` |
+
+### pages/orchestration/editor  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/admin/task-templates` | 登录 |  | `getNodeTemplateList` |
+| POST | `/api/orchestration/flow/detail` | 登录 |  | `getOrchestrationFlowDetail` |
+| POST | `/api/orchestration/flow/publish` | 登录 |  | `publishOrchestrationFlow` |
+| POST | `/api/orchestration/flow/save` | 登录 |  | `saveOrchestrationFlow` |
+
+### pages/orchestration/index  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/orchestration/flow/archive` | 登录 |  | `archiveOrchestrationFlow` |
+| POST | `/api/orchestration/flow/delete` | 登录 |  | `deleteOrchestrationFlow` |
+| POST | `/api/orchestration/flow/list` | 登录 |  | `getOrchestrationFlowList` |
+| POST | `/api/orchestration/flow/publish` | 登录 |  | `publishOrchestrationFlow` |
+
+### pages/orchestration/node-edit  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/parent/appointments  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/dan-assessment/appointment/cancel` | 登录 |  | `cancelAppointment` |
+| POST | `/api/dan-assessment/appointment/user` | 登录 |  | `getMyAppointments` |
+
+### pages/parent/child-detail  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tasks/pending-review` | 登录 |  | `getPendingReviewTasks` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+| POST | `/api/wishes/pending` | 登录 |  | `getPendingWishes` |
+
+### pages/parent/plans/detail  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/plans/detail` | 登录 |  | `getGuidePlanDetail` |
+
+### pages/parent/plans/index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/plans/family-list` | 登录 |  | `listFamilyPlans` |
+
+### pages/parent/wishes/index  (6 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/wishes//:var/approve-exchange` | 登录 | ✓ | `approveWishExchange` |
+| POST | `/api/wishes//:var/fulfill` | 登录 | ✓ | `markWishFulfilled` |
+| POST | `/api/wishes//:var/price` | 登录 | ✓ | `setWishPrice` |
+| POST | `/api/wishes//:var/reject` | 登录 | ✓ | `rejectWish` |
+| POST | `/api/wishes/list` | 登录 |  | `getWishes` |
+| POST | `/api/wishes/pending` | 登录 |  | `getPendingWishes` |
+
+### pages/pearl-reminders/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/pearl/interaction/add` | 登录 |  | `addPearlInteraction` |
+| POST | `/api/pearl/reminder/list` | 登录 |  | `getPearlReminders` |
+
+### pages/profile-extra/coupons  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/coupon/claim` | 登录 |  | `claimCoupon` |
+| POST | `/api/coupon/exchangeable` | 登录 |  | `getExchangeableCoupons` |
+| POST | `/api/coupon/my` | 登录 |  | `getMyCoupons` |
+| POST | `/api/family-platform/exchange-coupon` | 登录 |  | `exchangeCouponByCf` |
+
+### pages/profile-extra/family-members  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/invite/generate` | 公开 |  | `generateFamilyInvite` |
+| POST | `/api/family/invite/pending-requests` | 公开 |  | `getPendingJoinRequests` |
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/member/switch` | 登录 |  | `switchToFamilyMember` |
+| POST | `/api/health/report/member-permission/members/'/:var, 'POST', {})
+
+/** 授权:让指定用户可查看某成员的报告(管理员) */
+export const grantReportMemberPermission = (targetMemberId, granteeUserId) =>
+  request('/api/health/report/member-permission/grant` | 登录 | ✓ | `getMemberGrantedUsers` |
+| POST | `/api/health/report/member-permission/revoke` | 登录 |  | `revokeReportMemberPermission` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+
+### pages/profile-extra/gates  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/unlock/status` | 登录 |  | `getUnlockStatus` |
+
+### pages/profile-extra/onboarding  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/onboarding/claim` | 登录 |  | `claimOnboardingReward` |
+| POST | `/api/onboarding/progress` | 登录 |  | `getOnboardingProgress` |
+
+### pages/profile-main/profile  (16 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/cart/count` | 登录 |  | `cartCount` |
+| POST | `/api/commission/my-referrer` | 登录 |  | `getMyReferrer` |
+| POST | `/api/commission/team/consumption` | 登录 |  | `getTeamConsumption` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/challenge/list` | 登录 |  | `getChallengeList` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/invite/summary` | 登录 |  | `getReferralSummary` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/product/order/my/counts` | 公开 |  | `getOrderCounts` |
+| POST | `/api/share/qrcode` | 登录 |  | `getShareQrCode` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasksByCategory` |
+| POST | `/api/user/info` | 登录 |  | `getUserInfo` |
+| POST | `/api/user/profile-stats` | 登录 |  | `getProfileStats` |
+| POST | `/api/vendor/status` | 公开 |  | `vendorStatus` |
+
+### pages/profile/components/ProfileHeader  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/family/member/switch` | 登录 |  | `switchToFamilyMember` |
+
+### pages/profile/components/ProfileMenu  (6 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/set-password` | 公开 |  | `setPassword` |
+| POST | `/api/auth/verify-password` | 公开 |  | `verifyPassword` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/user/members/update-visibility` | 登录 |  | `updateMemberVisibility` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/vendor/status` | 公开 |  | `vendorStatus` |
+
+### pages/profile/components/ProfileStats  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/user/action-stats` | 登录 |  | `getUserActionStats` |
+
+### pages/profile/index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+
+### pages/profile/message-history  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/commission/cf/list` | 登录 |  | `getCfList` |
+| POST | `/api/energy/logs` | 登录 |  | `getEnergyLogs` |
+| POST | `/api/notification/list` | 登录 |  | `getNotificationList` |
+| POST | `/api/notification/read` | 登录 |  | `readNotification` |
+| POST | `/api/points/logs` | 登录 |  | `getPointsLogs` |
+
+### pages/profile/portrait-edit  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/sandbox` | 登录 |  | `getEnergySandbox` |
+| POST | `/api/user/portrait/edit` | 登录 |  | `editPortrait` |
+| POST | `/api/user/portrait/get` | 登录 |  | `getPortrait` |
+
+### pages/profile/report-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/report-summary/detail/'/:var, 'POST', {})
+export const downloadReportSummary = (id) => request('/api/report-summary/download/'/:var, 'POST', {})
+
+// 服务角色统一申请
+export const submitServiceRoleApply = (data) => {
+    return request('/api/service-role/apply` | 登录 | ✓ | `getReportSummaryDetail` |
+
+### pages/profile/report-management  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/report-summary/list` | 登录 |  | `getReportSummaryList` |
+
+### pages/profile/service-role-apply  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/service-role/my-apply` | 登录 |  | `getMyServiceRoleApply` |
+| POST | `/api/service-role/upload-image` | 登录 |  | `uploadServiceRoleImage` |
+
+### pages/promotion/commission  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/commission/cf/list` | 登录 |  | `getCfList` |
+| POST | `/api/commission/cf/summary` | 登录 |  | `getCfSummary` |
+
+### pages/promotion/index  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/commission/cf/summary` | 登录 |  | `getCfSummary` |
+| POST | `/api/earnings/admin/distribute` | 登录 |  | `distributeToMember` |
+| POST | `/api/earnings/admin/toggle-member` | 登录 |  | `toggleMemberBalance` |
+| POST | `/api/earnings/admin/withdraw` | 登录 |  | `withdrawFamilyEarnings` |
+| POST | `/api/earnings/family/summary` | 登录 |  | `getFamilyEarningsSummary` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/invite/summary` | 登录 |  | `getReferralSummary` |
+
+### pages/promotion/invite  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/invite/bind` | 登录 |  | `bindReferral` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/invite/list` | 登录 |  | `getReferralList` |
+| POST | `/api/invite/milestone/claim` | 登录 |  | `claimInviteMilestone` |
+| POST | `/api/invite/milestone/list` | 登录 |  | `getInviteMilestones` |
+| POST | `/api/invite/qrcode` | 登录 |  | `getInviteQrCode` |
+| POST | `/api/invite/summary` | 登录 |  | `getReferralSummary` |
+
+### pages/promotion/leaderboard  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/leaderboard/my-rank` | 登录 |  | `getLeaderboardMyRank` |
+| POST | `/api/leaderboard/top` | 登录 |  | `getLeaderboardTop` |
+
+### pages/promotion/team  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/commission/cf/rate` | 登录 |  | `getCfRate` |
+| POST | `/api/commission/my-referrer` | 登录 |  | `getMyReferrer` |
+| POST | `/api/commission/team/consumption` | 登录 |  | `getTeamConsumption` |
+| POST | `/api/commission/team/consumption-curve` | 登录 |  | `getTeamAllMembersConsumptionCurve` |
+| POST | `/api/commission/team/growth-curve` | 登录 |  | `getTeamGrowthCurve` |
+| POST | `/api/commission/team/l1-consumption-curve` | 登录 |  | `getTeamL1ConsumptionCurve` |
+| POST | `/api/commission/team/list` | 登录 |  | `getTeamList` |
+| POST | `/api/commission/team/tree` | 登录 |  | `getTeamTree` |
+
+### pages/promotion/withdraw  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/commission/summary` | 登录 |  | `getCommissionSummary` |
+| POST | `/api/withdrawal/apply` | 登录 |  | `applyWithdrawal` |
+| POST | `/api/withdrawal/history` | 登录 |  | `getWithdrawalHistory` |
+
+### pages/psych-assessment/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/child` | 登录 |  | `getCognitiveChildScores` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+
+### pages/psych-assessment/quiz  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cognitive/self-test` | 登录 |  | `submitCognitiveSelfTest` |
+
+### pages/reminder-config/index  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/task/reminder-config/get` | 登录 |  | `getReminderConfig` |
+| POST | `/api/task/reminder-config/save` | 登录 |  | `saveReminderConfig` |
+
+### pages/rewards/badge  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/badges/member/list` | 登录 |  | `getChildBadges` |
+| POST | `/api/badges/favorite` | 登录 |  | `toggleBadgeFavorite` |
+| POST | `/api/badges/list` | 登录 |  | `getActiveBadges` |
+| POST | `/api/badges/ranking/family` | 登录 |  | `getFamilyBadgeRanking` |
+| POST | `/api/badges/statistics/member` | 登录 |  | `getChildBadgeStats` |
+
+### pages/rewards/rewards  (9 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/parent/wishlist` | 登录 |  | `createParentWishlist` |
+| POST | `/api/parent/wishlist//:var/exchange` | 登录 | ✓ | `exchangeParentWishlist` |
+| POST | `/api/parent/wishlist/list` | 登录 |  | `getParentWishlist` |
+| POST | `/api/points/balance` | 登录 |  | `getPointsBalance` |
+| POST | `/api/rewards` | 登录 |  | `createReward` |
+| POST | `/api/rewards//:var/exchange` | 登录 | ✓ | `exchangeReward` |
+| POST | `/api/rewards/wishlist` | 登录 |  | `getWishlist` |
+| POST | `/api/user/info` | 登录 |  | `getUserInfo` |
+
+### pages/share/index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/share/family-footprint` | 登录 |  | `getFamilyFootprint` |
+
+### pages/shop/cart/cart  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/membership/gift-membership-progress` | 登录 |  | `getGiftMembershipProgress` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/shop/checkout/checkout  (12 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/coupon/apply` | 登录 |  | `applyCoupon` |
+| POST | `/api/coupon/checkout-list` | 登录 |  | `getCouponCheckoutList` |
+| POST | `/api/coupon/list` | 登录 |  | `getCouponList` |
+| POST | `/api/family-platform/balance` | 登录 |  | `getFamilyPlatformBalance` |
+| POST | `/api/family-platform/exchange-coupon` | 登录 |  | `exchangeCouponByCf` |
+| POST | `/api/membership/gift-membership-progress` | 登录 |  | `getGiftMembershipProgress` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/product/detail` | 公开 |  | `productDetail` |
+| POST | `/api/product/purchase_fields/required` | 公开 |  | `getProductRequiredFields` |
+| POST | `/api/shop/discount/calculate` | 公开 |  | `shopDiscountCalculate` |
+| POST | `/api/special-price/info` | 登录 |  | `getSpecialPriceInfo` |
+| POST | `/api/user/address/list` | 登录 |  | `addressList` |
+
+### pages/shop/consignee-edit/consignee-edit  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/consignee/detail` | 登录 |  | `consigneeDetail` |
+| POST | `/api/consignee/save` | 登录 |  | `consigneeSave` |
+
+### pages/shop/consignee-list/consignee-list  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/consignee/delete` | 登录 |  | `consigneeDelete` |
+| POST | `/api/consignee/list` | 登录 |  | `consigneeList` |
+
+### pages/shop/index/index  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/cart/count` | 登录 |  | `cartCount` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+| POST | `/api/shop/category/tree` | 公开 |  | `goodsCategory` |
+
+### pages/shop/order-detail/order-detail  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/order/cancel` | 公开 |  | `productOrderCancel` |
+| POST | `/api/product/order/confirm` | 公开 |  | `productOrderConfirm` |
+| POST | `/api/product/order/detail` | 公开 |  | `productOrderDetail` |
+
+### pages/shop/order-list/order-list  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/order/cancel` | 公开 |  | `productOrderCancel` |
+| POST | `/api/product/order/confirm` | 公开 |  | `productOrderConfirm` |
+| POST | `/api/product/order/my` | 公开 |  | `productOrderMy` |
+| POST | `/api/product/order/my/counts` | 公开 |  | `productOrderCounts` |
+
+### pages/shop/payment/payment  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+
+### pages/shop/search/search  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/list` | 公开 |  | `productList` |
+
+### pages/stats/completion-rate  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/stats/child-completion` | 登录 |  | `getChildCompletionStats` |
+| POST | `/api/stats/family-completion` | 登录 |  | `getFamilyCompletionStats` |
+
+### pages/stats/index  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/stats/child/overview` | 登录 |  | `getChildOverview` |
+
+### pages/tasks/create-task  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tasks/create` | 登录 |  | `createTask` |
+| POST | `/api/tasks/list` | 登录 |  | `getTaskListForPicker` |
+
+### pages/tasks/daily-tasks  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/growth-task/claim` | 登录 |  | `claimGrowthTaskReward` |
+| POST | `/api/growth-task/list` | 登录 |  | `getGrowthTaskList` |
+
+### pages/tasks/review  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `approveTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `rejectTask` |
+| POST | `/api/tasks/history` | 登录 |  | `getTaskHistory` |
+| POST | `/api/tasks/pending-review` | 登录 |  | `getPendingReviewTasks` |
+
+### pages/tasks/tasks  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/tasks//:var/complete` | 登录 | ✓ | `completeTask` |
+| POST | `/api/tasks/accept` | 登录 |  | `acceptTask` |
+| POST | `/api/tasks/create` | 登录 |  | `createTask` |
+| POST | `/api/tasks/my-pending` | 登录 |  | `getMyPendingTasks` |
+| POST | `/api/tasks/today` | 登录 |  | `getTodayTasks` |
+
+### pages/teacher/chat  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/messages/list` | 登录 |  | `getGuideMessages` |
+
+### pages/teacher/families  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/families` | 登录 |  | `getBoundFamilies` |
+
+### pages/teacher/messages  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/messages/list` | 登录 |  | `getGuideMessages` |
+
+### pages/teacher/orders  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/orders/list` | 登录 |  | `getGuideOrders` |
+| POST | `/api/guide/orders/stats` | 登录 |  | `getOrderStats` |
+
+### pages/teacher/plan-create  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/training-plans/create` | 登录 |  | `createTrainingPlan` |
+
+### pages/teacher/plan-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/families//:var/plans//:var/update` | 登录 | ✓ | `updateGuidePlanContent` |
+| POST | `/api/guide/families//:var/plans/pending` | 登录 | ✓ | `getGuidePendingPlans` |
+
+### pages/teacher/plan-list  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/training-plans/list` | 登录 |  | `getTrainingPlanList` |
+
+### pages/teacher/review-family  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/families//:var/children//:var/pending-review` | 登录 | ✓ | `getGuideChildPendingTasks` |
+| POST | `/api/guide/families//:var/members` | 登录 | ✓ | `getGuideFamilyMembers` |
+| POST | `/api/guide/families//:var/plans/pending` | 登录 | ✓ | `getGuidePendingPlans` |
+| POST | `/api/guide/families//:var/tasks//:var/review` | 登录 | ✓ | `reviewGuideTask` |
+| POST | `/api/tasks//:var/review` | 登录 | ✓ | `reviewTask` |
+
+### pages/teacher/review-workbench  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/families/my-families` | 登录 |  | `getGuideMyFamilies` |
+
+### pages/teacher/service-tasks  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tasks//:var/complete` | 登录 | ✓ | `completeTask` |
+
+### pages/teacher/teacher-profile  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/parent-invite/generate` | 登录 |  | `generateParentInvite` |
+| POST | `/api/user/switch-role` | 登录 |  | `switchRole` |
+
+### pages/teacher/team  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/guide/invite-code/generate` | 公开 |  | `generateInviteCode` |
+| POST | `/api/guide/team/invite-code/generate` | 登录 |  | `generateTeamInviteCode` |
+| POST | `/api/guide/team/members` | 登录 |  | `getTeamMembers` |
+| POST | `/api/guide/team/stats` | 登录 |  | `getTeamStats` |
+
+### pages/user-edit/user-edit  (6 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/direct-register` | 公开 |  | `directRegister` |
+| POST | `/api/family/invite/request-join-by-code` | 公开 |  | `requestJoinByCode` |
+| POST | `/api/family/user/create-family` | 登录 |  | `createFamily` |
+| POST | `/api/membership/my` | 登录 |  | `getMyMembership` |
+| POST | `/api/user/info` | 登录 |  | `getUserInfo` |
+| POST | `/api/user/update` | 登录 |  | `updateUserInfo` |
+
+### pages/vendor/apply  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/vendor/apply` | 登录 |  | `vendorApply` |
+
+### pages/vendor/center  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/vendor/info` | 公开 |  | `vendorInfo` |
+| POST | `/api/vendor/status` | 公开 |  | `vendorStatus` |
+
+### pages/vendor/order-review/order-review  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/order/detail` | 公开 |  | `productOrderDetail` |
+| POST | `/api/product/order/review/update` | 公开 |  | `productOrderReviewUpdate` |
+
+### pages/vendor/orders/orders  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/order/confirm` | 公开 |  | `productOrderConfirm` |
+| POST | `/api/product/order/vendor` | 公开 |  | `productOrderVendor` |
+
+### pages/vendor/product-edit/product-edit  (3 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/create` | 公开 |  | `productCreate` |
+| POST | `/api/product/detail` | 公开 |  | `productDetail` |
+| POST | `/api/product/update` | 公开 |  | `productUpdate` |
+
+### pages/vendor/products/products  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/product/my` | 公开 |  | `productMy` |
+| POST | `/api/product/shelve` | 公开 |  | `productShelve` |
+
+### pages/vendor/team-customers/team-customers  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/admin/supply-team/customers` | 登录 |  | `getTeamCustomers` |
+
+### pages/vendor/team-system/team-system  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/admin/supply-hierarchy/my` | 登录 |  | `getVendorHierarchyInfo` |
+| POST | `/api/admin/supply-system/my-system` | 登录 |  | `getVendorSystemInfo` |
+| POST | `/api/admin/supply-team/customers` | 登录 |  | `getVendorTeamCustomers` |
+| POST | `/api/admin/supply-team/members` | 登录 |  | `getVendorTeamMembers` |
+
+### pages/wealth-cf/index  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| GET | `/api/cf/balance` | 登录 |  | `getCfBalance` |
+| GET | `/api/cf/family-coupons` | 登录 |  | `getFamilyCoupons` |
+| GET | `/api/cf/logs` | 登录 |  | `getCfLogs` |
+| POST | `/api/coupon/exchangeable` | 登录 |  | `getExchangeableCoupons` |
+| POST | `/api/family-platform/exchange-coupon` | 登录 |  | `exchangeCouponByCf` |
+
+### pages/wealth-detail/member-wealth-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/wealth-sub/checkin  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/wealth/checkin/create` | 登录 |  | `createCheckin` |
+| POST | `/api/wealth/checkin/delete` | 登录 |  | `deleteCheckin` |
+| POST | `/api/wealth/checkin/list` | 登录 |  | `getCheckinList` |
+| POST | `/api/wealth/checkin/stats` | 登录 |  | `getCheckinStats` |
+
+### pages/wealth-sub/insurance-add  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/wealth/insurance/create` | 公开 |  | `createInsurance` |
+| POST | `/api/wealth/insurance/detail` | 公开 |  | `getInsuranceDetail` |
+| POST | `/api/wealth/insurance/update` | 公开 |  | `updateInsurance` |
+| POST | `/api/wealth/insurance/upload` | 公开 |  | `uploadPolicy` |
+
+### pages/wealth-sub/insurance-list  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/wealth/insurance/delete` | 公开 |  | `deleteInsurance` |
+| POST | `/api/wealth/insurance/list` | 公开 |  | `getInsuranceList` |
+
+### pages/wealth-sub/insurance-planning  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/insurance/planning` | 登录 |  | `getInsurancePlanning` |
+
+### pages/wealth/index  (12 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/badges/statistics/member` | 登录 |  | `getChildBadgeStats` |
+| POST | `/api/commission/summary` | 登录 |  | `getCommissionSummary` |
+| POST | `/api/daily-task/overview` | 登录 |  | `getDailyTaskOverview` |
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+| POST | `/api/energy/wealth-detail` | 登录 |  | `getWealthDetail` |
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/invite/summary` | 登录 |  | `getReferralSummary` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+| POST | `/api/wealth/insurance/list` | 公开 |  | `getInsuranceList` |
+
+### pages/wisdom-detail/cognitive-report  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/assessment/latest-result` | 登录 |  | `getAssessmentLatestResult` |
+| POST | `/api/cognitive/norms` | 登录 |  | `getCognitiveNorms` |
+| POST | `/api/cognitive/recommendations` | 登录 |  | `getCognitiveRecommendations` |
+| POST | `/api/cognitive/recommendations/create-task` | 登录 |  | `createTaskFromRecommendation` |
+| POST | `/api/cognitive/trend` | 登录 |  | `getCognitiveTrend` |
+
+### pages/wisdom-detail/index  (8 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/assessment/latest-result` | 登录 |  | `getAssessmentLatestResult` |
+| POST | `/api/content-sections/visible` | 登录 |  | `getVisibleSections` |
+| POST | `/api/dan-assessment/report/child` | 登录 |  | `getDanReportByChild` |
+| POST | `/api/dimension/radar-data` | 登录 |  | `getRadarData` |
+| POST | `/api/family/member/kick` | 登录 |  | `kickFamilyMemberById` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/health/indicators` | 登录 |  | `getLatestIndicators` |
+| POST | `/api/wisdom/gut-cognition` | 登录 |  | `getGutCognitionIndicators` |
+
+### pages/wisdom-detail/member-wisdom-detail  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/energy/overview` | 登录 |  | `getEnergyOverview` |
+| POST | `/api/energy/sandbox` | 登录 |  | `getFamilyEnergySandbox` |
+
+### pages/wishes/create  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/wishes/create` | 登录 |  | `createWish` |
+
+### pages/wishes/detail  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/points/balance` | 登录 |  | `getPointsBalance` |
+| POST | `/api/wishes//:var` | 登录 | ✓ | `cancelWish` |
+| POST | `/api/wishes//:var` | 登录 | ✓ | `getWishById` |
+| POST | `/api/wishes//:var/confirm` | 登录 | ✓ | `confirmWishReceived` |
+| POST | `/api/wishes//:var/exchange` | 登录 | ✓ | `requestWishExchange` |
+
+### pages/wishes/index  (7 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/home/app/enter` | 登录 |  | `reportAppEnter` |
+| POST | `/api/points/balance` | 登录 |  | `getPointsBalance` |
+| POST | `/api/wishes//:var` | 登录 | ✓ | `cancelWish` |
+| POST | `/api/wishes//:var/confirm` | 登录 | ✓ | `confirmWishReceived` |
+| POST | `/api/wishes//:var/exchange` | 登录 | ✓ | `requestWishExchange` |
+| POST | `/api/wishes/create` | 登录 |  | `createWish` |
+| POST | `/api/wishes/list` | 登录 |  | `getWishes` |
+
+### store/health-alert  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/alert/dismiss` | 登录 |  | `dismissAlert` |
+| POST | `/api/health/alert/list` | 登录 |  | `getActiveAlerts` |
+
+### store/health-score  (2 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/health/score/info` | 登录 |  | `getHealthScoreInfo` |
+| POST | `/api/health/timeline/list` | 登录 |  | `getHealthTimeline` |
+
+### store/index  (4 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/family/user/switch-back-verify` | 登录 |  | `switchBackVerify` |
+| POST | `/api/user/switch-back-to-parent` | 登录 |  | `switchBackToParent` |
+| POST | `/api/user/switch-role` | 登录 |  | `switchRole` |
+| POST | `/api/user/switch-to-child` | 登录 |  | `switchToChild` |
+
+### store/modules/tianpan  (5 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/tianpan/annual-energy` | 公开 |  | `tianpanAnnualEnergy` |
+| POST | `/api/tianpan/daily-fortune` | 公开 |  | `tianpanDailyFortune` |
+| POST | `/api/tianpan/dashboard` | 公开 |  | `tianpanDashboard` |
+| POST | `/api/tianpan/member/'/:var, 'POST', data)
+}
+
+export const tianpanCompatibility = (data) => {
+  return request('/api/tianpan/compatibility` | 公开 | ✓ | `tianpanMemberDetail` |
+| POST | `/api/tianpan/related-items` | 公开 |  | `tianpanRelatedItems` |
+
+### utils/api  (38 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/admin/activity/list` | 公开 |  | `adminListMyActivities` |
+| POST | `/api/admin/task-templates` | 登录 |  | `getNodeTemplateList` |
+| POST | `/api/admin/task/reminder-config/get?userId='/:var, 'POST', {})
+}
+
+export function saveReminderConfigByUser(data) {
+  return request('/api/admin/task/reminder-config/save` | 登录 | ✓ | `getReminderConfigByUser` |
+| POST | `/api/auth/silent-login` | 公开 |  | `silentLogin` |
+| POST | `/api/badges/member/list` | 登录 |  | `getChildBadges` |
+| POST | `/api/butler/available-list` | 公开 |  | `getAvailableButlers` |
+| POST | `/api/butler/my-butler` | 公开 |  | `getMyButler` |
+| POST | `/api/butler/select` | 公开 |  | `selectButler` |
+| POST | `/api/dan-assessment/order/pay` | 登录 |  | `payAssessmentOrder` |
+| POST | `/api/family/invite/approve-request` | 公开 |  | `approveJoinRequest` |
+| POST | `/api/family/invite/my-request` | 公开 |  | `getMyJoinRequest` |
+| POST | `/api/family/invite/pending-requests` | 公开 |  | `getPendingJoinRequests` |
+| POST | `/api/family/invite/reject-request` | 公开 |  | `rejectJoinRequest` |
+| POST | `/api/family/member/list` | 登录 |  | `getFamilyMemberList` |
+| POST | `/api/family/user/create-family` | 登录 |  | `createFamily` |
+| POST | `/api/internal/virtual-pay/error-report` | 登录 |  | `reportVirtualPayError` |
+| POST | `/api/invite/bind` | 登录 |  | `bindReferral` |
+| POST | `/api/invite/code` | 登录 |  | `getReferralCode` |
+| POST | `/api/orchestration/execution/detail` | 登录 |  | `getOrchestrationExecutionDetail` |
+| POST | `/api/orchestration/execution/start` | 登录 |  | `startOrchestrationExecution` |
+| POST | `/api/orchestration/execution/terminate` | 登录 |  | `terminateOrchestrationExecution` |
+| POST | `/api/orchestration/flow/archive` | 登录 |  | `archiveOrchestrationFlow` |
+| POST | `/api/orchestration/flow/delete` | 登录 |  | `deleteOrchestrationFlow` |
+| POST | `/api/orchestration/flow/detail` | 登录 |  | `getOrchestrationFlowDetail` |
+| POST | `/api/orchestration/flow/list` | 登录 |  | `getOrchestrationFlowList` |
+| POST | `/api/orchestration/flow/publish` | 登录 |  | `publishOrchestrationFlow` |
+| POST | `/api/orchestration/flow/save` | 登录 |  | `saveOrchestrationFlow` |
+| POST | `/api/product/list` | 公开 |  | `productList` |
+| POST | `/api/profile/history` | 登录 |  | `getProfileTrend` |
+| POST | `/api/profile/my` | 登录 |  | `getMyProfile` |
+| POST | `/api/purchase/challenge/progress` | 登录 |  | `getChallengeProgress` |
+| POST | `/api/recommend/list` | 登录 |  | `getRecommendList` |
+| POST | `/api/stats/child/overview` | 登录 |  | `getChildOverview` |
+| POST | `/api/tasks/history` | 登录 |  | `getTaskHistory` |
+| POST | `/api/user/portrait/edit` | 登录 |  | `editPortrait` |
+| POST | `/api/user/portrait/generate` | 登录 |  | `generatePortrait` |
+| POST | `/api/user/portrait/get` | 登录 |  | `getPortrait` |
+| POST | `/api/user/portrait/regenerate` | 登录 |  | `regeneratePortrait` |
+
+### utils/profile-backfill  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/user/profile/backfill` | 登录 |  | `backfillProfile` |
+
+### utils/sso  (1 个接口)
+
+| 方法 | 路径 | 鉴权 | 参数 | 来源函数 |
+|------|------|:----:|:----:|----------|
+| POST | `/api/auth/sso-ticket` | 公开 |  | `createSsoTicket` |

+ 16 - 0
cfc-frontend/__tests__/AdminPageTasksExcludeTemplate.contract.spec.js

@@ -0,0 +1,16 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:admin.pageTasks.excludeTemplate(管理端家庭任务分页只显示实例,不显示模板)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/FamilyAdminOverviewService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('管理端家庭任务分页排除模板', () => {
+  test('pageTasks 查询排除 is_template=1', () => {
+    const start = source.indexOf('public Page<TaskItemVO> pageTasks')
+    expect(start).toBeGreaterThan(-1)
+    const body = source.slice(start, start + 900)
+    expect(body).toMatch(/getIsTemplate/)
+    expect(body).toMatch(/ne\(Task::getIsTemplate, 1\)|eq\(Task::getIsTemplate, 0\)/)
+  })
+})

+ 17 - 0
cfc-frontend/__tests__/ChildTaskExpiryReminder.contract.spec.js

@@ -0,0 +1,17 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.childExpiryReminder(child 类型任务的过期未完成提醒支持)
+const TASK = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/task/TaskCheckinWebhookReminderTask.java')
+const source = readFileSync(TASK, 'utf8')
+
+describe('child 任务过期提醒', () => {
+  test('查询不再限定 executor_type=parent(或同时覆盖 child)', () => {
+    // 不应再有 .eq(Task::getExecutorType, "parent") 的硬过滤
+    expect(source).not.toMatch(/\.eq\(Task::getExecutorType,\s*"parent"\)/)
+  })
+  test('child 任务通过 family_members 反查 userId', () => {
+    expect(source).toMatch(/FamilyMemberMapper/)
+    expect(source).toMatch(/getFamilyMemberId|getExecutorType/)
+  })
+})

+ 32 - 0
cfc-frontend/__tests__/RecipeNoFallback.contract.spec.js

@@ -0,0 +1,32 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:recipe.noFallback(生成失败必须明确报错,不再静默降级为规则兜底菜单)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java')
+const VUE = resolve(__dirname, '../../pages/diet/recommendation.vue')
+const svc = readFileSync(SVC, 'utf8')
+const vue = readFileSync(VUE, 'utf8')
+
+describe('食谱生成失败显式报错(无兜底)', () => {
+  test('生成主链路不再调用 buildFallbackMenu', () => {
+    // 主链路(generateRecommendation 方法体内)不得出现兜底调用
+    const start = svc.indexOf('public Map<String, Object> generateRecommendation')
+    const end = svc.indexOf('public Map<String, Object> regenerateRecommendation')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    const body = svc.slice(start, end)
+    expect(body).not.toMatch(/buildFallbackMenu/)
+  })
+
+  test('AI 空结果 / 结构不完整时抛出明确错误', () => {
+    expect(svc).toMatch(/throw new IllegalArgumentException\([^\n]*生成失败/)
+    expect(svc).toMatch(/throw new IllegalArgumentException\([^\n]*AI/)
+  })
+
+  test('前端生成失败 toast 显示后端原因而非固定文案', () => {
+    const i = vue.indexOf('generateRecipe: function')
+    expect(i).toBeGreaterThan(-1)
+    const body = vue.slice(i, i + 1600)
+    expect(body).toMatch(/var reason[^\n]*message/)
+  })
+})

+ 19 - 0
cfc-frontend/__tests__/TaskEarlyVisibility.contract.spec.js

@@ -0,0 +1,19 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.earlyVisibility(有 earliest_start 的任务,开始前1小时才在今日列表出现)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('任务提前1小时可见', () => {
+  test('getTodayTasks 按 earliest_start 提前1小时过滤显示', () => {
+    const start = source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')
+    const end = source.indexOf('public List<Task> getTodayTasksByFamily')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    const body = source.slice(start, end)
+    expect(body).toMatch(/getEarliestStart/)
+    expect(body).toMatch(/60 \* 60 \* 1000|HOUR_OF_DAY|HOURS/)
+    expect(body).toMatch(/removeIf/)
+  })
+})

+ 18 - 0
cfc-frontend/__tests__/TaskExcludeTemplate.contract.spec.js

@@ -0,0 +1,18 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.excludeTemplateInToday(模板不出现在用户今日任务列表,避免同一任务显示多条)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('今日任务排除模板', () => {
+  test('getTodayTasks 查询条件排除 is_template=1', () => {
+    const start = source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')
+    const end = source.indexOf('public List<Task> getTodayTasksByFamily')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    const body = source.slice(start, end)
+    expect(body).toMatch(/getIsTemplate/)
+    expect(body).toMatch(/ne\(Task::getIsTemplate, 1\)|eq\(Task::getIsTemplate, 0\)/)
+  })
+})

+ 21 - 0
cfc-frontend/__tests__/TaskExpiry.contract.spec.js

@@ -0,0 +1,21 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:任务过期机制(expired_at + 自动标记 overdue + 去重修复)
+const REM = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/task/TaskCheckinWebhookReminderTask.java')
+const SCHEMA = resolve(__dirname, '../../../cfc-backend/src/main/resources/schema.sql')
+const INIT = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java')
+const rem = readFileSync(REM, 'utf8'), schema = readFileSync(SCHEMA, 'utf8'), init = readFileSync(INIT, 'utf8')
+
+describe('任务过期机制', () => {
+  test('提醒去重按 userId(与通知写入口径一致)', () => {
+    expect(rem).toMatch(/alreadySentToday\(userId, task\.getId\(\), dayStart\)/)
+  })
+  test('expired_at 列在 schema + 迁移', () => {
+    expect(schema).toMatch(/expired_at/)
+    expect(init).toMatch(/expired_at/)
+  })
+  test('存在过期扫描调度器(每分钟)', () => {
+    expect(init).toMatch(/TaskExpiry/)
+  })
+})

+ 15 - 0
cfc-frontend/__tests__/TaskExpiryCrossDayOnly.contract.spec.js

@@ -0,0 +1,15 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:过期任务只针对跨天(deadline 日期 < 今天),当天过时段不隐藏
+const TASK = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/task/TaskExpiryScheduledTask.java')
+const source = readFileSync(TASK, 'utf8')
+
+describe('过期只跨天', () => {
+  test('过期判定按 deadline 日期早于今天', () => {
+    expect(source).toMatch(/ dayStart|startOfToday|before\(dayStart\)|lt\(Task::getDeadline, dayStart\)/)
+  })
+  test('不再用 now 直接比较 deadline(当天过时段不算过期)', () => {
+    expect(source).not.toMatch(/\.le\(Task::getDeadline,\s*now\)/)
+  })
+})

+ 21 - 0
cfc-frontend/__tests__/TaskNoDeadlineVisible.contract.spec.js

@@ -0,0 +1,21 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.noDeadlineVisible(无截止的一次性任务未完成时常驻任务列表)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('无截止任务常驻列表', () => {
+  test('getTodayTasks 可见性含 deadline IS NULL 分支', () => {
+    const start = source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')
+    const end = source.indexOf('public List<Task> getTodayTasksByFamily')
+    const body = source.slice(start, end)
+    expect(body).toMatch(/isNull\(Task::getDeadline\)/)
+  })
+  test('家庭视角同步含 deadline IS NULL 分支', () => {
+    const start = source.indexOf('public List<Task> getTodayTasksByFamily')
+    const end = source.indexOf('public List<Task> getTodayTasksByCategory')
+    const body = source.slice(start, end)
+    expect(body).toMatch(/isNull\(Task::getDeadline\)/)
+  })
+})

+ 43 - 0
cfc-frontend/__tests__/TaskStageReminder.contract.spec.js

@@ -0,0 +1,43 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.reminder.stage(五阶段未完成提醒)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/task/TaskStageReminderScheduledTask.java')
+const CFG = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderConfigService.java')
+const VUE = resolve(__dirname, '../pages/reminder-config/index.vue')
+const svc = readFileSync(SVC, 'utf8')
+const cfg = readFileSync(CFG, 'utf8')
+const vue = readFileSync(VUE, 'utf8')
+
+describe('任务五阶段未完成提醒', () => {
+  test('调度器定义五个阶段与时间', () => {
+    expect(svc).toMatch(/task_stage_wake/)
+    expect(svc).toMatch(/task_stage_breakfast/)
+    expect(svc).toMatch(/task_stage_lunch/)
+    expect(svc).toMatch(/task_stage_dinner/)
+    expect(svc).toMatch(/task_stage_bedtime/)
+    expect(svc).toMatch(/07:00/)
+    expect(svc).toMatch(/21:30/)
+  })
+
+  test('只查 pending/pending_review 且当天的未完成 parent 任务', () => {
+    expect(svc).toMatch(/getStatus, "pending", "pending_review"/)
+    expect(svc).toMatch(/getExecutorType, "parent"/)
+    expect(svc).toMatch(/getIsTemplate, 0/)
+  })
+
+  test('渠道为站内 + webhook,且按当日 type 幂等', () => {
+    expect(svc).toMatch(/in_app,wechat/)
+    expect(svc).toMatch(/alreadySent/)
+  })
+
+  test('配置服务校验阶段时间 HH:mm', () => {
+    expect(cfg).toMatch(/阶段提醒时间格式应为 HH:mm/)
+  })
+
+  test('前端配置页含开关与五个时间选择器', () => {
+    expect(vue).toMatch(/toggleStageEnabled/)
+    expect(vue).toMatch(/stageWakeTime/)
+    expect(vue).toMatch(/stageBedtimeTime/)
+  })
+})

+ 359 - 0
cfc-frontend/__tests__/aiyunyi/aiyunyi.videoPage.contract.test.js

@@ -0,0 +1,359 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.videoPage(任务 S-cfc-456)
+ *
+ * 溯源:
+ *   需求:docs/2026-11-24-爱云医AI检测接入方案.md
+ *         §4.2(新增 pages/health/ai-video-detect.vue:<web-view> 内嵌爱云医视频检测 H5 页,
+ *               URL 取 getPath 返回的 path;pages.json 注册新增页面路由)、
+ *         §8「前端验收」第 3 条(视频类型:进入 web-view 内嵌页;返回后可看到报告)、
+ *         §7 R7(视频检测依赖爱云医 H5 页,小程序 web-view 需域名白名单;
+ *                getPath 返回域名需加入业务域名,若受限则前端降级为「在浏览器打开」提示)。
+ *   设计:同上 §3.4 视频路径(inspectionType 1/2 → getPath 取 data.path → <web-view src={path}>
+ *         内嵌采集 → 完成后回小程序拉报告)、§4.5(错误归一/降级)、附录 A.5
+ *         (GET /detection/package/getPath:detectionPackageItemId、detectionReportUserId 均必填,
+ *          响应 data.path 为 H5 URL);§3.1 安全硬约束(前端只调本系统 /api/aiyunyi/** 代理,
+ *          不直连爱云医、不接触 AppKey/私钥)。
+ *
+ * 说明(沿用 cfc-frontend/__tests__/family-join/join-form.required-info.test.js 与同批
+ *   aiyunyi.detectPage.contract.test.js 的「加载真实 SFC 源码」约定):
+ *   jest 配置为 node 环境、无 vue-jest 组件挂载;本文件直接读取真实
+ *   pages/health/ai-video-detect.vue 与 utils/api.js 源码——
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods 做行为级断言;
+ *     - <template>:读取模板文本做结构契约断言(<web-view :src>、降级提示)。
+ *   GREEN 阶段按本文件锚定的契约落地实现后断言应可翻绿;当前实现未落地 → 预期 RED。
+ *   本文件只新增 __tests__ 下的测试,不修改 pages/、utils/、pages.json 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// __tests__/aiyunyi → ../.. = cfc-frontend
+const ROOT = path.join(__dirname, '../..')
+const VIDEO_PAGE_PATH = path.join(ROOT, 'pages/health/ai-video-detect.vue')
+const API_PATH = path.join(ROOT, 'utils/api.js')
+const PAGES_JSON_PATH = path.join(ROOT, 'pages.json')
+
+const H5_PATH = 'https://devadmin.aicds.com.cn/video-detect/index.html?token=contract-test'
+const ITEM_ID = 101
+const REPORT_USER_ID = 202
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC(行为级 <script> + 结构级 <template>),风格对齐 family-join
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 改为从 globalThis[stubKey] 取桩(不解析模块,避免污染业务实现) */
+function stubImports(script, moduleStubs, stubKey) {
+  globalThis[stubKey] = moduleStubs
+  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[' + JSON.stringify(stubKey) + '][' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 通用 SFC 加载器:文件缺失时抛明确错误(GREEN 未交付的 RED 信号) */
+function loadVideoPage(moduleStubs) {
+  if (!fs.existsSync(VIDEO_PAGE_PATH)) {
+    throw new Error('实现未落地(GREEN 未交付),找不到 SFC:' + VIDEO_PAGE_PATH)
+  }
+  var src = fs.readFileSync(VIDEO_PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法定位 <script> 块:' + VIDEO_PAGE_PATH)
+  var script = stubImports(scriptMatch[1], moduleStubs, '__aiyunyiVideoPageStubs')
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  new Function('module', 'exports', script)(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '', source: src }
+}
+
+/** 模拟 Vue 合并 data 与 methods 到实例 */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 容忍 GREEN 阶段对 H5 URL 字段的命名差异(webViewUrl / h5Url / path 等) */
+function urlKeys(vm) {
+  return ['webViewUrl', 'webviewUrl', 'h5Url', 'videoUrl', 'detectUrl', 'path', 'src']
+}
+function readUrl(vm) {
+  var keys = urlKeys(vm)
+  for (var i = 0; i < keys.length; i++) {
+    if (typeof vm[keys[i]] === 'string' && vm[keys[i]]) return vm[keys[i]]
+  }
+  return ''
+}
+function boundUrlKey(template) {
+  var m = template.match(/<web-view[^>]*?\s:src\s*=\s*["']([A-Za-z_$][\w$]*)["']/)
+  return m ? m[1] : ''
+}
+async function flush() {
+  await Promise.resolve()
+  await Promise.resolve()
+  await Promise.resolve()
+}
+function messagesShown() {
+  var msgs = []
+  global.uni.showToast.mock.calls.forEach(function (c) { msgs.push((c[0] && c[0].title) || '') })
+  global.uni.showModal.mock.calls.forEach(function (c) { msgs.push(JSON.stringify(c[0] || {})) })
+  return msgs.join(' ')
+}
+function callMentionsIds(call) {
+  var text = JSON.stringify(call)
+  return text.indexOf(String(ITEM_ID)) >= 0 && text.indexOf(String(REPORT_USER_ID)) >= 0
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具:api.js 用 Proxy 容纳 GREEN 阶段任意命名(aiyunyi.getPath / aiyunyiGetPath / 平铺)
+// ---------------------------------------------------------------------------
+
+var stubs
+
+function buildStubs() {
+  var apiSpy = jest.fn(function () {
+    return Promise.resolve({ code: 200, message: 'ok', data: { path: H5_PATH } })
+  })
+  var apiModule = new Proxy({}, {
+    get: function (target, prop) {
+      if (prop === '__spy') return apiSpy
+      if (typeof prop === 'symbol') return undefined
+      if (/member|family/i.test(String(prop))) {
+        return jest.fn(function () { return Promise.resolve({ code: 200, data: [] }) })
+      }
+      return apiSpy
+    }
+  })
+  return {
+    apiSpy: apiSpy,
+    moduleStubs: {
+      '@/utils/api.js': apiModule,
+      '../../utils/api.js': apiModule,
+      '@/utils/image-picker.js': { pickImage: jest.fn() },
+      '@/mixins/font-scale.js': {
+        fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+      }
+    }
+  }
+}
+
+beforeEach(function () {
+  global.uni._storage = {}
+  ;['showToast', 'showModal', 'showLoading', 'hideLoading', 'navigateTo', 'redirectTo',
+    'setClipboardData', 'request'].forEach(function (k) {
+    if (global.uni[k] && global.uni[k].mockReset) global.uni[k].mockReset()
+  })
+  if (!global.uni.setClipboardData) global.uni.setClipboardData = jest.fn()
+  stubs = buildStubs()
+  globalThis.__aiyunyiVideoPageStubs = stubs.moduleStubs
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__aiyunyiVideoPageStubs
+})
+
+// ===========================================================================
+// AC-R0 视频页文件存在性(§4.2 改动清单:新增 ai-video-detect.vue)——主 RED 信号
+// ===========================================================================
+
+describe('AC-R0 视频检测页文件存在性契约', function () {
+  it('pages/health/ai-video-detect.vue 必须存在(§4.2)', function () {
+    expect(fs.existsSync(VIDEO_PAGE_PATH)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R1 <template> 结构:<web-view> 动态绑定 getPath 返回的 H5 URL(§4.2)
+// ===========================================================================
+
+describe('AC-R1 web-view 内嵌结构契约', function () {
+  it('模板包含 <web-view> 且以 :src 动态绑定(不得写死 URL)', function () {
+    var template = loadVideoPage(stubs.moduleStubs).template
+    expect(template).toMatch(/<web-view[^>]*\s:src\s*=/)
+  })
+
+  it(':src 绑定的字段必须由脚本 data 提供(getPath 返回的 path)', function () {
+    var sfc = loadVideoPage(stubs.moduleStubs)
+    var vm = instantiate(sfc.component)
+    var key = boundUrlKey(sfc.template)
+    expect(key).not.toBe('')
+    expect(vm[key]).toBeDefined()
+  })
+})
+
+// ===========================================================================
+// AC-R2 utils/api.js 暴露 aiyunyi.getPath 封装(§4.2 / §A.5 / §3.1 代理约束)
+// ===========================================================================
+
+describe('AC-R2 utils/api.js getPath 封装契约', function () {
+  var apiSrc
+
+  beforeAll(function () {
+    apiSrc = fs.readFileSync(API_PATH, 'utf8')
+  })
+
+  it('存在 getPath 封装(aiyunyi.getPath / aiyunyiGetPath / 平铺导出)', function () {
+    var hasWrapper = /aiyunyi\s*[.:]\s*[\s\S]{0,800}?getPath/i.test(apiSrc)
+      || /aiyunyiGetPath/i.test(apiSrc)
+      || /export\s+(?:const|function)\s+getPath\b/.test(apiSrc)
+    expect(hasWrapper).toBe(true)
+  })
+
+  it('getPath 封装走 /api/aiyunyi/ 代理且透传两个必填 ID(§A.5)', function () {
+    var proxyIdx = apiSrc.indexOf('/api/aiyunyi/')
+    var getPathIdx = apiSrc.toLowerCase().indexOf('getpath')
+    expect(proxyIdx).toBeGreaterThanOrEqual(0)
+    expect(getPathIdx).toBeGreaterThanOrEqual(0)
+    var start = Math.max(0, Math.min(proxyIdx, getPathIdx) - 400)
+    var end = Math.min(apiSrc.length, Math.max(proxyIdx, getPathIdx) + 800)
+    var block = apiSrc.slice(start, end)
+    expect(block).toMatch(/detectionPackageItemId/)
+    expect(block).toMatch(/detectionReportUserId/)
+  })
+})
+
+// ===========================================================================
+// AC-R3 <script> 行为:onLoad 调 getPath 并用 data.path 渲染 web-view(§3.4 第 8/9 步)
+// ===========================================================================
+
+describe('AC-R3 getPath 取路径行为契约', function () {
+  it('onLoad 调用 getPath,并把返回的 data.path 写入 H5 URL 字段', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(stubs.apiSpy).toHaveBeenCalled()
+    expect(readUrl(vm)).toBe(H5_PATH)
+  })
+
+  it('detectionPackageItemId 与 detectionReportUserId 同时透传,不交换/不丢弃(§A.5)', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(stubs.apiSpy.mock.calls.length).toBeGreaterThan(0)
+    expect(stubs.apiSpy.mock.calls.some(callMentionsIds)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R4 R7 降级:域名白名单受限/getPath 失败时提示「在浏览器打开」,不白屏(§7 R7 / §4.5)
+// ===========================================================================
+
+describe('AC-R7 域名白名单降级契约', function () {
+  it('getPath 失败时给出「在浏览器打开」提示,不白屏、不崩溃', async function () {
+    stubs.apiSpy.mockReset()
+    stubs.apiSpy.mockImplementation(function () { return Promise.reject(new Error('network error')) })
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(messagesShown()).toMatch(/浏览器打开/)
+  })
+
+  it('提供降级打开方法(复制 URL / 系统浏览器打开 H5 链接)', function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    var names = ['openInBrowser', 'openBrowser', 'fallbackOpen', 'openH5InBrowser']
+    expect(names.some(function (n) { return typeof vm[n] === 'function' })).toBe(true)
+    var src = fs.readFileSync(VIDEO_PAGE_PATH, 'utf8')
+    expect(/setClipboardData|plus\.runtime\.openURL|window\.open/.test(src)).toBe(true)
+  })
+
+  it('模板包含降级文案(web-view 受限时用户仍可看到提示)', function () {
+    var template = loadVideoPage(stubs.moduleStubs).template
+    expect(template).toMatch(/浏览器打开/)
+  })
+})
+
+// ===========================================================================
+// AC-R5 返回后可看到报告(§8 前端验收第 3 条 / §3.4 第 10/11 步)
+// ===========================================================================
+
+describe('AC-R5 从 web-view 返回后报告可见契约', function () {
+  it('onShow 触发报告状态查询或跳转报告页(首次进入跳过、返回时刷新)', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    expect(typeof vm.onShow).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    stubs.apiSpy.mockClear()
+    global.uni.navigateTo.mockClear()
+    global.uni.redirectTo.mockClear()
+
+    // 首次进入 onShow 可能被 _onLoadFired 跳过;返回时触发——连续两次覆盖两种实现
+    await vm.onShow()
+    await vm.onShow()
+    await flush()
+
+    var nav = (global.uni.navigateTo.mock.calls.concat(global.uni.redirectTo.mock.calls))
+      .map(function (c) { return (c[0] && c[0].url) || '' }).join(' ')
+    expect(stubs.apiSpy.mock.calls.length > 0 || /report/i.test(nav)).toBe(true)
+  })
+
+  it('页面脚本或模板引用报告详情/报告数据(返回后展示报告)', function () {
+    var sfc = loadVideoPage(stubs.moduleStubs)
+    expect(/ai-report-detail|report-detail|报告/.test(sfc.source + sfc.template)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R6 页面路由注册(§4.2:pages.json 注册新增页面)
+// ===========================================================================
+
+describe('AC-R6 pages.json 视频页路由契约', function () {
+  it('注册 ai-video-detect 路由', function () {
+    var pagesJson = JSON.parse(fs.readFileSync(PAGES_JSON_PATH, 'utf8'))
+    var paths = []
+    ;(pagesJson.pages || []).forEach(function (p) { paths.push(p.path) })
+    ;(pagesJson.subPackages || []).forEach(function (sp) {
+      ;(sp.pages || []).forEach(function (p) { paths.push((sp.root ? sp.root + '/' : '') + p.path) })
+    })
+    expect(paths.some(function (p) { return /(^|\/)ai-video-detect$/.test(p) })).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R8 安全约束:不直连爱云医、不持有签名材料(§3.1)
+// ===========================================================================
+
+describe('AC-R8 前端不直连爱云医/不持有鉴权材料契约', function () {
+  it('视频页源码不得出现爱云医域名或 AppKey/RSA 私钥/签名材料', function () {
+    var src = loadVideoPage(stubs.moduleStubs).source
+    expect(/aicds\.com\.cn|X-App-Key|X-Api-Sign|rsaPrivateKey|rsa-private-key|SHA256withRSA/.test(src)).toBe(false)
+  })
+})
+
+// ===========================================================================
+// 权限流:本能力为 web-view 承载页,鉴权由统一 Bearer Token / 后端代理收口,
+// 无独立角色门禁分支,属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ===========================================================================
+
+describe.skip('权限流:ai.aiyunyi.videoPage 无独立角色门禁,不适用', function () {
+  it('占位:鉴权经后端代理 + 统一 Bearer Token,无 role 分支(详见汇报)', function () {})
+})

+ 270 - 0
cfc-frontend/__tests__/aiyunyi/report-upload.uploadCard.contract.test.js

@@ -0,0 +1,270 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.uploadCard(任务 S-cfc-453)
+ *
+ * 溯源:
+ *   需求:docs/2026-11-24-爱云医AI检测接入方案.md
+ *         §4.2(前端文件清单:report-upload.vue 修改 + pages.json 修改)、
+ *         §8「前端验收」第 1 条(report-upload 出现「AI 快速识别」卡片;未选成员/未勾声明时拦截并提示,复用现有逻辑)。
+ *   设计:同上 §4.2 表格(report-upload.vue 修改:@click="startAiDetect";
+ *         pages.json 修改:注册 ai-detect / ai-report-detail / ai-video-detect 3 个页面路由)、
+ *         §5 时序(照片路径主流程:点击卡片 → 校验 → 进入 AI 检测页)、
+ *         §4.5 错误处理与降级(未开通/次数用完/网络失败的提示归一,属 ai-detect 页职责,
+ *         本能力仅负责「入口卡片 + 复用现有门禁导航」,不在本文件断言)。
+ *
+ * 说明(沿用 cfc-frontend/__tests__/family-join/join-form.required-info.test.js 的「加载真实 SFC 源码」约定):
+ *   jest 配置为 node 环境、无 vue-jest 挂载组件;本文件直接读取真实 report-upload.vue 的
+ *   <script>/<template> 源码——
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods 做行为级断言;
+ *     - <template>:读取模板文本做结构契约断言(第三张卡片、@click 绑定、卡片顺序)。
+ *   同时直接读取真实 pages.json 断言 3 条路由已注册。
+ *   若 GREEN 阶段实现方补齐上述契约,本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   本文件不修改 pages/、pages.json、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+var REPORT_UPLOAD_PATH = path.join(__dirname, '../../pages/health/report-upload.vue')
+var PAGES_JSON_PATH = path.join(__dirname, '../../pages.json')
+
+/** 把 ES import 语句替换为从 globalThis.__reportUploadStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__reportUploadStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadReportUpload() {
+  var src = fs.readFileSync(REPORT_UPLOAD_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 report-upload.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__reportUploadStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var 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
+}
+
+/** 归一 pages.json 主包 + 所有分包的页面路径 */
+function allPagePaths() {
+  var pagesJson = JSON.parse(fs.readFileSync(PAGES_JSON_PATH, 'utf8'))
+  var paths = []
+  ;(pagesJson.pages || []).forEach(function (p) { paths.push(p.path) })
+  ;(pagesJson.subPackages || []).forEach(function (sp) {
+    ;(sp.pages || []).forEach(function (p) { paths.push((sp.root ? sp.root + '/' : '') + p.path) })
+  })
+  return paths
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showModal.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  globalThis.__reportUploadStubs = {
+    '../../utils/memberNormalize.js': {
+      normalizeMembers: function (list) { return list || [] },
+      memberIdOf: function (m) { return m && m.id }
+    },
+    '../../utils/api.js': {
+      uploadReportOnly: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getReportCollectStatus: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getFamilyMemberList: jest.fn(function () { return Promise.resolve({ data: [] }) }),
+      requestReportTransfer: jest.fn(function () { return Promise.resolve({ code: 200 }) }),
+      getReportTypeLinks: jest.fn(function () { return Promise.resolve({ data: [] }) })
+    },
+    '../../utils/image-picker.js': { pickImage: jest.fn() },
+    '@/mixins/font-scale.js': {
+      fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+    }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__reportUploadStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC1 模板结构:上传方式区出现第三张「AI 快速识别」卡片(§8 验收第 1 条 / §4.2)
+// ---------------------------------------------------------------------------
+
+describe('AC1 「AI 快速识别」入口卡片', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__reportUploadStubs = {}
+    template = loadReportUpload().template
+  })
+
+  it('上传方式区三张卡片并列:从聊天选取 → 拍照上传 → AI 快速识别(§8-1)', function () {
+    var chatIdx = template.indexOf('从聊天选取')
+    var photoIdx = template.indexOf('拍照上传')
+    var aiIdx = template.indexOf('AI 快速识别')
+    expect(chatIdx).toBeGreaterThan(-1)
+    expect(photoIdx).toBeGreaterThan(chatIdx)
+    expect(aiIdx).toBeGreaterThan(photoIdx)
+  })
+
+  it('upload-methods 内恰好有 3 张 upload-card(第三张为 AI 卡片,§4.2)', function () {
+    var start = template.indexOf('<view class="upload-methods">')
+    var end = template.indexOf('采集中面板')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    var block = template.slice(start, end)
+    expect((block.match(/class="upload-card\b/g) || []).length).toBe(3)
+  })
+
+  it('AI 卡片点击绑定 startAiDetect(§4.2 @click="startAiDetect")', function () {
+    expect(template).toMatch(/@click="startAiDetect"/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC2 方法入口:startAiDetect 存在(§4.2)
+// ---------------------------------------------------------------------------
+
+describe('AC2 startAiDetect 入口', function () {
+  it('组件 methods 中定义 startAiDetect 方法', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    expect(typeof vm.startAiDetect).toBe('function')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC3 未选成员拦截并提示,复用现有 ensureMember(§8-1)
+// ---------------------------------------------------------------------------
+
+describe('AC3 未选成员拦截(复用 ensureMember)', function () {
+  it('memberId 为空时提示「请先选择报告所属成员」,且不跳转 AI 检测页', function () {
+    var vm = instantiate(loadReportUpload().component)
+    vm.memberId = null
+    expect(typeof vm.startAiDetect).toBe('function')
+
+    vm.startAiDetect()
+
+    expect(global.uni.showToast).toHaveBeenCalledWith(expect.objectContaining({ title: '请先选择报告所属成员' }))
+    expect(global.uni.navigateTo).not.toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC4 未勾声明拦截并提示,复用现有 ensureAgreed(§8-1)
+// ---------------------------------------------------------------------------
+
+describe('AC4 未勾声明拦截(复用 ensureAgreed)', function () {
+  it('未勾声明时弹出数据使用声明,用户取消 → 不跳转 AI 检测页', function () {
+    var vm = instantiate(loadReportUpload().component)
+    vm.memberId = 1
+    vm.agreedToTerms = false
+    global.uni.showModal.mockImplementation(function (opts) {
+      if (opts && typeof opts.success === 'function') opts.success({ confirm: false })
+    })
+    expect(typeof vm.startAiDetect).toBe('function')
+
+    vm.startAiDetect()
+
+    expect(global.uni.showModal).toHaveBeenCalled()
+    expect(global.uni.navigateTo).not.toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC5/6 校验通过后进入照片路径 AI 检测页(§5 时序)
+// ---------------------------------------------------------------------------
+
+describe('AC5 校验通过后进入 AI 检测页', function () {
+  it('已选成员 + 已勾声明 → navigateTo 进入 ai-detect 页', function () {
+    var vm = instantiate(loadReportUpload().component)
+    vm.memberId = 1
+    vm.agreedToTerms = true
+    expect(typeof vm.startAiDetect).toBe('function')
+
+    vm.startAiDetect()
+
+    expect(global.uni.navigateTo).toHaveBeenCalledWith(expect.objectContaining({
+      url: expect.stringContaining('ai-detect')
+    }))
+  })
+
+  it('未勾声明但弹窗点「同意继续」→ 进入 ai-detect 页(复用 ensureAgreed 回调)', function () {
+    var vm = instantiate(loadReportUpload().component)
+    vm.memberId = 1
+    vm.agreedToTerms = false
+    global.uni.showModal.mockImplementation(function (opts) {
+      if (opts && typeof opts.success === 'function') opts.success({ confirm: true })
+    })
+    expect(typeof vm.startAiDetect).toBe('function')
+
+    vm.startAiDetect()
+
+    expect(global.uni.navigateTo).toHaveBeenCalledWith(expect.objectContaining({
+      url: expect.stringContaining('ai-detect')
+    }))
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC7 pages.json 注册 3 条页面路由(§4.2)
+// ---------------------------------------------------------------------------
+
+describe('AC7 pages.json 路由注册', function () {
+  it('注册 ai-detect / ai-report-detail / ai-video-detect 三条路由', function () {
+    var paths = allPagePaths()
+    ;['ai-detect', 'ai-report-detail', 'ai-video-detect'].forEach(function (name) {
+      var re = new RegExp('(^|/)' + name + '$')
+      expect(paths.some(function (p) { return re.test(p) })).toBe(true)
+    })
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为上传页入口卡片,复用页面既有的「成员归属 + 数据使用声明」门禁,
+// 不引入独立角色分支(家长/孩子视角切换由页面既有的 memberId 参数承载),
+// 属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:入口卡片无独立角色门禁,不适用', function () {
+  it('占位:门禁复用 ensureMember/ensureAgreed,无 role 分支(详见汇报)', function () {})
+})

+ 75 - 0
cfc-frontend/__tests__/api/api.indicator.test.js

@@ -0,0 +1,75 @@
+/**
+ * 指标 API 封装契约测试
+ * 验证 URL / method / body 正确,且是规范入口(单 URL 单封装)
+ */
+import * as api from '@/utils/api'
+import { getIndicatorTrend, getIndicatorChangeRanking, getIndicatorQuickLookup, getIndicatorCorrelationList } from '@/utils/api'
+
+// --------------- helpers ---------------
+function mockSuccess(data) {
+  global.uni.request.mockImplementation((opts) => {
+    process.nextTick(() => {
+      if (opts.success) opts.success({ data })
+    })
+  })
+}
+
+function lastRequest() {
+  const calls = global.uni.request.mock.calls
+  return calls[calls.length - 1][0]
+}
+
+// --------------- global beforeEach ---------------
+describe('indicator API 封装', () => {
+  beforeEach(() => {
+    global.uni._storage = {}
+    global.uni.request.mockReset()
+    global.uni.showToast.mockReset()
+    global.uni.reLaunch.mockReset()
+    global.uni.login.mockReset()
+    global.getCurrentPages.mockReset()
+    global.getCurrentPages.mockReturnValue([{ route: 'pages/index-home/index' }])
+    global.uni.getAccountInfoSync.mockReset()
+    global.uni.getAccountInfoSync.mockReturnValue({ miniProgram: { envVersion: 'develop' } })
+    api.clearApiDedup()
+  })
+
+  test('getIndicatorTrend → POST /api/indicator/trend with subjectId+definitionIds', async () => {
+    mockSuccess({ code: 200, data: {} })
+    await getIndicatorTrend({ subjectId: 5, definitionIds: [1, 2] })
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/indicator\/trend$/)
+    expect(opts.method).toBe('POST')
+    expect(opts.data.subjectId).toBe(5)
+    expect(opts.data.definitionIds).toEqual([1, 2])
+  })
+
+  test('getIndicatorChangeRanking → POST /api/indicator/change-ranking with scope+orderBy', async () => {
+    mockSuccess({ code: 200, data: {} })
+    await getIndicatorChangeRanking({ subjectId: 5, scope: 'adjacent', orderBy: 'magnitude', limit: 50 })
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/indicator\/change-ranking$/)
+    expect(opts.method).toBe('POST')
+    expect(opts.data.scope).toBe('adjacent')
+    expect(opts.data.orderBy).toBe('magnitude')
+  })
+
+  test('getIndicatorQuickLookup → POST /api/indicator/quick-lookup with page', async () => {
+    mockSuccess({ code: 200, data: {} })
+    await getIndicatorQuickLookup({ subjectId: 5, category: '核心菌属', page: 1, pageSize: 30 })
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/indicator\/quick-lookup$/)
+    expect(opts.method).toBe('POST')
+    expect(opts.data.page).toBe(1)
+    expect(opts.data.pageSize).toBe(30)
+  })
+
+  test('getIndicatorCorrelationList → POST /api/indicator/correlation/list with subjectId+definitionId', async () => {
+    mockSuccess({ code: 200, data: {} })
+    await getIndicatorCorrelationList({ subjectId: 5, definitionId: 3 })
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/indicator\/correlation\/list$/)
+    expect(opts.method).toBe('POST')
+    expect(opts.data.definitionId).toBe(3)
+  })
+})

+ 1321 - 0
cfc-frontend/__tests__/api/api.test.js

@@ -0,0 +1,1321 @@
+/**
+ * Tests for cfc-frontend utils/api.js
+ *
+ * Mocks uni.request to intercept and verify API calls.
+ */
+import * as api from '@/utils/api'
+
+// --------------- helpers ---------------
+
+/** Helper: make uni.request call success(data) on next tick */
+function mockSuccess(data) {
+  global.uni.request.mockImplementation((opts) => {
+    process.nextTick(() => {
+      if (opts.success) opts.success({ data })
+    })
+  })
+}
+
+/** Helper: make uni.request call fail(err) on next tick */
+function mockFail(err) {
+  global.uni.request.mockImplementation((opts) => {
+    process.nextTick(() => {
+      if (opts.fail) opts.fail(err)
+    })
+  })
+}
+
+function mockSequence(responses) {
+  var i = 0
+  global.uni.request.mockImplementation((opts) => {
+    var resp = responses[Math.min(i, responses.length - 1)]
+    i++
+    process.nextTick(() => {
+      if (resp.err) {
+        if (opts.fail) opts.fail(resp.err)
+      } else {
+        if (opts.success) opts.success({ data: resp.data })
+      }
+    })
+  })
+}
+
+// --------------- global beforeEach ---------------
+
+beforeEach(() => {
+  global.uni._storage = {}
+  global.uni.request.mockReset()
+  global.uni.showToast.mockReset()
+  global.uni.reLaunch.mockReset()
+  global.uni.login.mockReset()
+  global.getCurrentPages.mockReset()
+  global.getCurrentPages.mockReturnValue([{ route: 'pages/index-home/index' }])
+  global.uni.getAccountInfoSync.mockReset()
+  global.uni.getAccountInfoSync.mockReturnValue({
+    miniProgram: { envVersion: 'develop' }
+  })
+  // api.js 的 3 秒请求去重缓存是模块级单例,跨用例残留会让后续用例拿到上一个用例缓存的
+  // Promise(同 URL+method+body),表现为「本该 401 却是 200」「lastRequest() 为 undefined」。
+  // 每个用例前显式清空,保证用例间隔离。
+  api.clearApiDedup()
+})
+
+/** Capture the last uni.request call options */
+function lastRequest() {
+  const calls = global.uni.request.mock.calls
+  return calls[calls.length - 1][0]
+}
+
+// --------------- auth module ---------------
+
+describe('auth API', () => {
+  beforeEach(() => {
+    global.uni._storage.token = 'test-token'
+    global.uni._storage.userId = '42'
+  })
+
+  test('wechatLogin sends POST /api/auth/wechat-login', async () => {
+    mockSuccess({ code: 200, data: { token: 'jwt' } })
+    const res = await api.wechatLogin('code123', { nickname: 'test' })
+    const opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/auth\/wechat-login$/)
+    expect(opts.data.code).toBe('code123')
+    expect(res.data.token).toBe('jwt')
+  })
+
+  test('phoneLogin sends POST with phone and code', async () => {
+    mockSuccess({ code: 200, data: { token: 'jwt' } })
+    await api.phoneLogin({ phone: '13800138000', code: '1234' })
+    const opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/auth\/phone-login$/)
+    expect(opts.data.phone).toBe('13800138000')
+  })
+
+  test('sendCode sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.sendCode({ phone: '13800138000' })
+    const opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/auth\/send-code$/)
+  })
+
+  test('silentLogin sends POST with code', async () => {
+    mockSuccess({ code: 200 })
+    await api.silentLogin('wxcode')
+    expect(lastRequest().data.code).toBe('wxcode')
+  })
+
+  // 已废弃:后端 /api/auth/auto-login 已改为 410 Gone(裸 openid 换 token 属越权漏洞)。
+  // 导出仅为排查历史调用保留,不得在新代码中使用;续期请走 silentRelogin()。
+  test('autoLogin (deprecated) still targets /api/auth/auto-login', async () => {
+    mockSuccess({ code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' })
+    await expect(api.autoLogin('openid_xxx')).rejects.toEqual(
+      { code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' }
+    )
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/auth\/auto-login$/)
+    expect(opts.data.openid).toBe('openid_xxx')
+  })
+
+  test('setPassword and verifyPassword send correct endpoints', async () => {
+    mockSuccess({ code: 200 })
+    await api.setPassword('secret')
+    expect(lastRequest().url).toMatch(/\/api\/auth\/set-password$/)
+    expect(lastRequest().data.password).toBe('secret')
+
+    await api.verifyPassword('secret')
+    expect(lastRequest().url).toMatch(/\/api\/auth\/verify-password$/)
+  })
+
+  test('directRegister sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.directRegister({ phone: '13800138000', nickname: 'tester' })
+    expect(lastRequest().url).toMatch(/\/api\/auth\/direct-register$/)
+  })
+
+  test('checkPhone sends POST with phone', async () => {
+    mockSuccess({ code: 200 })
+    await api.checkPhone('13800138000')
+    expect(lastRequest().data.phone).toBe('13800138000')
+  })
+
+  test('wechatPhoneLogin sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.wechatPhoneLogin({ code: 'wxcode', iv: 'iv', encryptedData: 'enc' })
+    expect(lastRequest().url).toMatch(/\/api\/auth\/wechat-phone-login$/)
+  })
+
+  test('verifyToken sends POST /api/auth/verify with bearer token', async () => {
+    mockSuccess({ code: 200, data: { userId: 42, role: 'parent' } })
+    const res = await api.verifyToken()
+    const opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/auth\/verify$/)
+    expect(opts.header.Authorization).toBe('Bearer test-token')
+    expect(res.data.userId).toBe(42)
+  })
+
+  test('verifyToken with 401 (token expired) clears auth and redirects to login', async () => {
+    jest.useFakeTimers()
+    mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+    expect(global.uni._storage.token).toBeUndefined()
+    // 触发 _clearAuthAndRedirect 内 1.5s setTimeout(reLaunch 在此定时器回调中执行)
+    jest.runAllTimers()
+    expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
+    expect(global.uni.showToast).toHaveBeenCalled()
+    jest.useRealTimers()
+  })
+
+  test('verifyToken with 401 (user deleted) clears auth and redirects to login', async () => {
+    jest.useFakeTimers()
+    mockSuccess({ code: 401, message: '用户不存在', data: null })
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: '用户不存在', data: null })
+    expect(global.uni._storage.token).toBeUndefined()
+    jest.runAllTimers()
+    expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
+    expect(global.uni.showToast).toHaveBeenCalled()
+    jest.useRealTimers()
+  })
+
+  // 静默续期 = uni.login() 取微信签发的一次性 code → /api/auth/silent-login(服务端 code2Session)。
+  // 本地 openid 只作为「本设备曾登录过」的触发条件,不作为凭证上送。
+  function mockUniLoginCode(code) {
+    global.uni.login.mockImplementation((opts) => {
+      process.nextTick(() => {
+        if (opts.success) opts.success({ code: code || 'wxcode' })
+      })
+    })
+  }
+
+  test('401 silently re-logins via wx.login + code2Session and retries original request', async () => {
+    global.uni.reLaunch.mockReset()
+    global.uni.showToast.mockReset()
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode('fresh-wxcode')
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
+      { data: { code: 200, data: { userId: 42, role: 'parent' } } }
+    ])
+    const res = await api.verifyToken()
+    expect(res.data.userId).toBe(42)
+    expect(global.uni._storage.token).toBe('new-jwt')
+    // 续期必须走 code2Session,且不得把 openid 当凭证发送
+    const calls = global.uni.request.mock.calls.map((c) => c[0])
+    const renewReq = calls.find((c) => /\/api\/auth\/silent-login/.test(c.url))
+    expect(renewReq).toBeDefined()
+    expect(renewReq.data.code).toBe('fresh-wxcode')
+    expect(renewReq.data.openid).toBeUndefined()
+    // 已废弃的裸 openid 换 token 接口不得被调用
+    expect(calls.find((c) => /\/api\/auth\/auto-login/.test(c.url))).toBeUndefined()
+    expect(global.uni.reLaunch).not.toHaveBeenCalled()
+    expect(global.uni.showToast).not.toHaveBeenCalled()
+  })
+
+  // 回归:首页冷启动会并发打出多个 401(family/member/list、membership/my、onboarding/progress…)。
+  // 修复前 _handle401 在 _reloginLock 为真时直接调 _clearAuthAndRedirect():
+  // 第 1 个 401 刚启动 silentRelogin()(uni.login 异步),第 2、3 个 401 立刻把 token 从
+  // storage 抹掉并预约 1500ms 后 reLaunch 登录页 → 在途续期被打断,
+  // 线上表现为「控制台只有 401、没有任何续期日志、用户被弹回登录页」。
+  test('concurrent 401s queue behind one renewal and all get replayed', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode('fresh-wxcode')
+    // 3 个业务请求同时 401 → 续期 1 次成功 → 3 个重放全部 200
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
+      { data: { code: 200, data: { ok: 'verify' } } },
+      { data: { code: 200, data: { ok: 'members' } } },
+      { data: { code: 200, data: { ok: 'membership' } } }
+    ])
+
+    const [verifyRes, memberRes, membershipRes] = await Promise.all([
+      api.verifyToken(),
+      api.getFamilyMemberList({}),
+      api.getMyMembership()
+    ])
+
+    // 三个请求都必须拿到成功结果(修复前后两个会被 reject)
+    expect(verifyRes.data.ok).toBe('verify')
+    expect(memberRes.data.ok).toBe('members')
+    expect(membershipRes.data.ok).toBe('membership')
+
+    const calls = global.uni.request.mock.calls.map((c) => c[0])
+    // 续期只发生一次,绝不能因并发 401 引发续期风暴
+    expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
+    // token 必须是被续期后的新值,而不是被并发 401 抹掉
+    expect(global.uni._storage.token).toBe('new-jwt')
+    // 关键回归点:并发 401 不得触发「登录已过期」提示,也不得跳登录页
+    expect(global.uni.showToast).not.toHaveBeenCalled()
+    expect(global.uni.reLaunch).not.toHaveBeenCalled()
+  })
+
+  // 回归:重放请求若仍 401(刚签发的 token 依旧不可用),必须直接失败而不是重新入队,
+  // 否则「续期 → 重放 → 401 → 续期 → 重放」会 ping-pong 死循环。
+  test('replayed request that still 401 fails without triggering another renewal', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode('fresh-wxcode')
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
+      { data: { code: 401, message: 'Token无效或已过期', data: null } }
+    ])
+
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+
+    const calls = global.uni.request.mock.calls.map((c) => c[0])
+    // 只续期过一次,重放 401 不再触发第二次续期
+    expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
+    expect(global.uni._storage.token).toBe('new-jwt')
+  })
+
+  test('401 retry does not duplicate query params in the replayed request URL', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode('fresh-wxcode')
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
+      { data: { code: 200, data: { ok: true } } }
+    ])
+    // publishPackage 通过 options 传 query(?publish=true),是最容易暴露重复拼接的调用形态
+    await api.publishPackage(7, true)
+    const calls = global.uni.request.mock.calls.map((c) => c[0])
+    const hits = calls.filter((c) => /\/api\/packages\/7\/publish/.test(c.url))
+    expect(hits.length).toBe(2) // 原始请求 1 次 + 401 续期后重放 1 次
+    // 修复前:_handle401 收到的是已拼过 query 的 url,重放时 options 又拼一次 → ?publish=true&publish=true
+    hits.forEach((c) => {
+      expect(c.url).toBe(c.url.split('?')[0] + '?publish=true')
+      expect((c.url.match(/publish=/g) || []).length).toBe(1)
+    })
+  })
+
+  test('401 during app launch window clears auth but does NOT navigate to login subpackage', async () => {
+    jest.useFakeTimers()
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    // 仍停在 splash:pages/login 是分包,此刻尚未下载,
+    // reLaunch 过去会报 'Page "pages/login/login" has not been registered yet'
+    global.getCurrentPages.mockReturnValue([{ route: 'pages/splash/index' }])
+    mockUniLoginCode()
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 500, message: '用户不存在,请先登录', data: null } }
+    ])
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+    jest.runAllTimers()
+    // 登录态必须清掉
+    expect(global.uni._storage.token).toBeUndefined()
+    // 但启动窗口内绝不跳登录页,交由 splash 落地首页(主包)
+    expect(global.uni.reLaunch).not.toHaveBeenCalled()
+    jest.useRealTimers()
+  })
+
+  test('401 during app launch window (no page registered yet) also skips navigation', async () => {
+    jest.useFakeTimers()
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    // 首屏尚未注册,getCurrentPages() 为空
+    global.getCurrentPages.mockReturnValue([])
+    mockUniLoginCode()
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 500, message: '用户不存在,请先登录', data: null } }
+    ])
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+    jest.runAllTimers()
+    expect(global.uni._storage.token).toBeUndefined()
+    expect(global.uni.reLaunch).not.toHaveBeenCalled()
+    jest.useRealTimers()
+  })
+
+  test('401 falls back to login page when silent re-login is refused', async () => {
+    jest.useFakeTimers()
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode()
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } },
+      { data: { code: 500, message: '用户不存在,请先登录', data: null } }
+    ])
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+    jest.runAllTimers()
+    expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
+    expect(global.uni.showToast).toHaveBeenCalled()
+    jest.useRealTimers()
+  })
+
+  test('401 with no cached openid (never logged in on this device) goes straight to login', async () => {
+    jest.useFakeTimers()
+    global.uni._storage.token = 'expired-token'
+    mockSequence([
+      { data: { code: 401, message: 'Token无效或已过期', data: null } }
+    ])
+    await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
+    // 本设备从未登录过 → 不应调用 uni.login 浪费一次 code2Session
+    expect(global.uni.login).not.toHaveBeenCalled()
+    jest.runAllTimers()
+    expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
+    jest.useRealTimers()
+  })
+
+  test('silentRelogin returns null when wx.login yields no code', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni.login.mockImplementation((opts) => {
+      process.nextTick(() => { if (opts.success) opts.success({}) })
+    })
+    await expect(api.silentRelogin()).resolves.toBeNull()
+    expect(global.uni.request).not.toHaveBeenCalled()
+  })
+
+  test('silentRelogin returns null when wx.login fails', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni.login.mockImplementation((opts) => {
+      process.nextTick(() => { if (opts.fail) opts.fail({ errMsg: 'login:fail' }) })
+    })
+    await expect(api.silentRelogin()).resolves.toBeNull()
+    expect(global.uni.request).not.toHaveBeenCalled()
+  })
+
+  test('silentRelogin does not issue a renew request on 401 (no recursive renewal)', async () => {
+    global.uni._storage.openid = 'openid_abc'
+    global.uni._storage.token = 'expired-token'
+    mockUniLoginCode()
+    // 续期接口自身返回 401:必须直接失败,不能再触发一次 silentRelogin,否则会递归续期/误清登录态
+    mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
+    await expect(api.silentRelogin()).resolves.toBeNull()
+    expect(global.uni.request.mock.calls.length).toBe(1)
+    // 续期失败不得清空登录态(那是「主动登出」才做的事)
+    expect(global.uni._storage.token).toBe('expired-token')
+    expect(global.uni.reLaunch).not.toHaveBeenCalled()
+  })
+
+  test('Authorization header includes Bearer token', async () => {
+    mockSuccess({ code: 200 })
+    global.uni._storage.token = 'my-jwt-token'
+    await api.getUserInfo()
+    const opts = lastRequest()
+    expect(opts.header.Authorization).toBe('Bearer my-jwt-token')
+  })
+
+  test('X-User-Id header is NOT sent (removed for security)', async () => {
+    mockSuccess({ code: 200 })
+    global.uni._storage.userId = '99'
+    await api.getUserInfo()
+    expect(lastRequest().header['X-User-Id']).toBeUndefined()
+  })
+
+  test('rejects on non-200 code', async () => {
+    mockSuccess({ code: 400, message: 'Bad Request' })
+    await expect(api.getUserInfo()).rejects.toEqual({ code: 400, message: 'Bad Request' })
+  })
+
+  test('rejects on network failure', async () => {
+    mockFail(new Error('Network error'))
+    await expect(api.getUserInfo()).rejects.toThrow('Network error')
+  })
+})
+
+// --------------- streets module ---------------
+
+describe('street address API', () => {
+  test('getProvinces sends POST to /api/streets/provinces', async () => {
+    mockSuccess({ code: 200, data: [] })
+    await api.getProvinces()
+    expect(lastRequest().url).toMatch(/\/api\/streets\/provinces$/)
+  })
+
+  test('getStreetChildren sends POST with parentId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getStreetChildren(110000)
+    expect(lastRequest().url).toMatch(/\/api\/streets\/children\/110000$/)
+  })
+
+  test('getStreetById sends POST to correct URL', async () => {
+    mockSuccess({ code: 200 })
+    await api.getStreetById(110101)
+    expect(lastRequest().url).toMatch(/\/api\/streets\/110101$/)
+  })
+
+  test('getStreetPath sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getStreetPath(110101)
+    expect(lastRequest().url).toMatch(/\/api\/streets\/110101\/path$/)
+  })
+
+  test('searchStreet sends POST with keyword', async () => {
+    mockSuccess({ code: 200 })
+    await api.searchStreet('北京')
+    expect(lastRequest().data.keyword).toBe('北京')
+  })
+
+  test('matchByStreet sends POST with streetId', async () => {
+    mockSuccess({ code: 200 })
+    await api.matchByStreet(110101)
+    expect(lastRequest().url).toMatch(/\/110101\/match$/)
+  })
+})
+
+// --------------- user / family module ---------------
+
+describe('user & family API', () => {
+  test('getUserInfo sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getUserInfo()
+    expect(lastRequest().url).toMatch(/\/api\/user\/info$/)
+  })
+
+  test('updateUserInfo sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.updateUserInfo({ nickname: 'new-name' })
+    expect(lastRequest().data.nickname).toBe('new-name')
+  })
+
+  test('joinFamily sends POST with inviteCode', async () => {
+    mockSuccess({ code: 200 })
+    await api.joinFamily('ABC123')
+    expect(lastRequest().data.inviteCode).toBe('ABC123')
+  })
+
+  test('createFamily sends POST with name', async () => {
+    mockSuccess({ code: 200 })
+    await api.createFamily('幸福之家')
+    expect(lastRequest().data.name).toBe('幸福之家')
+  })
+
+  test('getFamilyMemberList sends POST to unified endpoint', async () => {
+    mockSuccess({ code: 200 })
+    await api.getFamilyMemberList()
+    expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
+  })
+
+  test('getFamilyMemberList sends visibleOnly param', async () => {
+    mockSuccess({ code: 200 })
+    await api.getFamilyMemberList({ visibleOnly: true })
+    expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
+    expect(lastRequest().data.visibleOnly).toBe(true)
+  })
+
+  test('getFamilyMemberList sends includeFamily param', async () => {
+    mockSuccess({ code: 200 })
+    await api.getFamilyMemberList({ includeFamily: true })
+    expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
+    expect(lastRequest().data.includeFamily).toBe(true)
+  })
+
+  test('updateMemberVisibility sends POST with params', async () => {
+    mockSuccess({ code: 200 })
+    await api.updateMemberVisibility(1, 'child', true)
+    expect(lastRequest().data.memberId).toBe(1)
+    expect(lastRequest().data.memberType).toBe('child')
+    expect(lastRequest().data.showToFamily).toBe(true)
+  })
+
+  test('switchMode sends POST with mode', async () => {
+    mockSuccess({ code: 200 })
+    await api.switchMode('child')
+    expect(lastRequest().data.mode).toBe('child')
+  })
+
+  test('switchToChild sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.switchToChild(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('switchBackToParent sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.switchBackToParent()
+    expect(lastRequest().url).toMatch(/\/api\/user\/switch-back-to-parent$/)
+  })
+
+  test('getChildren sends POST to unified member list', async () => {
+    mockSuccess({ code: 200 })
+    await api.getChildren()
+    expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
+  })
+
+  test('createChild sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.createChild({ name: '小宝', gender: 'male' })
+    expect(lastRequest().url).toMatch(/\/api\/family\/user\/children$/)
+    expect(lastRequest().data.name).toBe('小宝')
+  })
+
+  test('updateChild sends POST merged with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.updateChild(5, { nickname: '大宝' })
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.nickname).toBe('大宝')
+  })
+
+  test('kickFamilyMember sends POST with targetUserId', async () => {
+    mockSuccess({ code: 200 })
+    await api.kickFamilyMember(10)
+    expect(lastRequest().data.targetUserId).toBe(10)
+  })
+})
+
+// --------------- membership module ---------------
+
+describe('membership API', () => {
+  test('getMembershipLevels sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMembershipLevels()
+    expect(lastRequest().url).toMatch(/\/api\/membership\/levels$/)
+  })
+
+  test('getMyMembership sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMyMembership()
+    expect(lastRequest().url).toMatch(/\/api\/membership\/my$/)
+  })
+
+  test('createOrder sends POST with levelCode and paymentType', async () => {
+    mockSuccess({ code: 200 })
+    await api.createOrder('vip', 'wechat')
+    expect(lastRequest().data.levelCode).toBe('vip')
+    expect(lastRequest().data.paymentType).toBe('wechat')
+  })
+})
+
+// --------------- tasks module ---------------
+
+describe('tasks API', () => {
+  test('createTask sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.createTask({ title: '晨读', memberId: 5 })
+    // 后端 TaskController: @RequestMapping("/api/tasks") + @PostMapping("/create")
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/create$/)
+    expect(lastRequest().data.title).toBe('晨读')
+  })
+
+  test('getTodayTasks sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getTodayTasks(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getPendingReviewTasks sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getPendingReviewTasks()
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/pending-review$/)
+  })
+
+  test('approveTask sends POST with approved:true', async () => {
+    mockSuccess({ code: 200 })
+    await api.approveTask(10)
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
+    expect(lastRequest().data.approved).toBe(true)
+  })
+
+  test('rejectTask sends POST with approved:false', async () => {
+    mockSuccess({ code: 200 })
+    await api.rejectTask(10)
+    expect(lastRequest().data.approved).toBe(false)
+  })
+
+  test('completeTask sends POST with memberId and photoUrl', async () => {
+    mockSuccess({ code: 200 })
+    await api.completeTask(10, 5, 'http://photo.url')
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.photoUrl).toBe('http://photo.url')
+  })
+
+  test('reviewTask sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.reviewTask(10, { approved: true, comment: '很好' })
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
+    expect(lastRequest().data.comment).toBe('很好')
+  })
+
+  test('getTaskHistory sends POST with pagination', async () => {
+    mockSuccess({ code: 200 })
+    await api.getTaskHistory(5, 1, 20)
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.page).toBe(1)
+    expect(lastRequest().data.size).toBe(20)
+  })
+
+  test('deleteTask sends POST with _method DELETE', async () => {
+    mockSuccess({ code: 200 })
+    await api.deleteTask(10)
+    expect(lastRequest().method).toBe('POST')
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/10$/)
+    expect(lastRequest().data._method).toBe('DELETE')
+  })
+
+  test('batchCompleteTasks sends POST with array', async () => {
+    mockSuccess({ code: 200 })
+    await api.batchCompleteTasks([1, 2, 3])
+    expect(lastRequest().data.taskIds).toEqual([1, 2, 3])
+  })
+
+  test('getTodayParentTasks sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getTodayParentTasks()
+    expect(lastRequest().url).toMatch(/\/api\/tasks\/today-parent$/)
+  })
+})
+
+// --------------- points module ---------------
+
+describe('points API', () => {
+  test('getPointsBalance sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getPointsBalance(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getPointsLogs sends POST with pagination', async () => {
+    mockSuccess({ code: 200 })
+    await api.getPointsLogs(5, 2, 20)
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.page).toBe(2)
+    expect(lastRequest().data.size).toBe(20)
+  })
+})
+
+// --------------- rewards / wishes module ---------------
+
+describe('rewards & wishes API', () => {
+  test('createReward sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.createReward({ name: '玩具', points: 100 })
+    expect(lastRequest().data.name).toBe('玩具')
+  })
+
+  test('getWishlist sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getWishlist(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('exchangeReward sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.exchangeReward(1, 5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getPendingWishes sends POST with empty body', async () => {
+    mockSuccess({ code: 200 })
+    await api.getPendingWishes()
+    expect(lastRequest().data).toEqual({})
+  })
+
+  test('getWishes sends POST with params', async () => {
+    mockSuccess({ code: 200 })
+    await api.getWishes({ memberId: 5, status: 'pending' })
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('setWishPrice sends POST with pointsRequired', async () => {
+    mockSuccess({ code: 200 })
+    await api.setWishPrice(1, 200)
+    expect(lastRequest().data.pointsRequired).toBe(200)
+  })
+
+  test('approveWishExchange sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.approveWishExchange(1, true)
+    expect(lastRequest().data.approved).toBe(true)
+  })
+
+  test('createWish sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.createWish({ title: '新书包', memberId: 5 })
+    expect(lastRequest().data.title).toBe('新书包')
+  })
+})
+
+// --------------- identity parameter hardening ---------------
+// 前端不再向后端发送可伪造的 userId / familyId / childId(仅 memberId),
+// 身份一律由后端从 JWT 推导。以下断言锁定这一不变量。
+
+describe('identity parameter hardening', () => {
+  beforeEach(() => {
+    global.uni._storage.token = 'test-token'
+  })
+
+  test('request() does NOT send X-User-Id header', async () => {
+    mockSuccess({ code: 200 })
+    await api.getPendingWishes()
+    const opts = lastRequest()
+    expect(opts.header['X-User-Id']).toBeUndefined()
+  })
+
+  test('getMyAssessmentResults sends empty body, no userId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMyAssessmentResults()
+    const opts = lastRequest()
+    expect(opts.data).toEqual({})
+    expect(opts.data.userId).toBeUndefined()
+  })
+
+  test('getChildAssessmentResults sends empty body, no userId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getChildAssessmentResults()
+    const opts = lastRequest()
+    expect(opts.data).toEqual({})
+    expect(opts.data.userId).toBeUndefined()
+  })
+
+  test('getTodayTasksByCategory sends only memberId and category', async () => {
+    mockSuccess({ code: 200 })
+    await api.getTodayTasksByCategory(7, 'wisdom')
+    const opts = lastRequest()
+    expect(opts.data.memberId).toBe(7)
+    expect(opts.data.category).toBe('wisdom')
+    expect(opts.data.childId).toBeUndefined()
+    expect(opts.data.userId).toBeUndefined()
+  })
+})
+
+// --------------- guide / packages module ---------------
+
+describe('guide & packages API', () => {
+  test('getGuidePackages sends POST to my list', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGuidePackages(1)
+    expect(lastRequest().url).toMatch(/\/api\/guide\/packages\/my$/)
+    expect(lastRequest().data.guideId).toBe(1)
+  })
+
+  test('registerGuide sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.registerGuide({ name: '张老师', level: 'senior' })
+    expect(lastRequest().url).toMatch(/\/api\/guide\/register$/)
+  })
+
+  test('generateBindInvite sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.generateBindInvite()
+    expect(lastRequest().url).toMatch(/\/api\/guide\/bind\/invite$/)
+  })
+
+  test('getBoundFamilies sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getBoundFamilies()
+    expect(lastRequest().url).toMatch(/\/api\/guide\/families$/)
+  })
+
+  test('getTeamMembers sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getTeamMembers()
+    expect(lastRequest().url).toMatch(/\/api\/guide\/team\/members$/)
+  })
+
+  test('getGuideOrders sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGuideOrders()
+    expect(lastRequest().url).toMatch(/\/api\/guide\/orders\/list$/)
+  })
+
+  test('getGuideMessages sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGuideMessages()
+    expect(lastRequest().url).toMatch(/\/api\/guide\/messages\/list$/)
+  })
+})
+
+// --------------- payment module ---------------
+
+describe('payment API', () => {
+  test('createWechatPayOrder sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.createWechatPayOrder('NO001', '测试订单', 100)
+    expect(lastRequest().data.orderNo).toBe('NO001')
+    expect(lastRequest().data.amount).toBe(100)
+  })
+})
+
+// --------------- assessment module ---------------
+
+describe('assessment API', () => {
+  test('createAssessmentAppointment sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.createAssessmentAppointment({ memberId: 5, date: '2026-06-20' })
+    expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/appointment\/create$/)
+  })
+
+  test('payAssessmentOrder sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.payAssessmentOrder('ORDER001', 'wechat')
+    expect(lastRequest().data.orderNo).toBe('ORDER001')
+  })
+
+  test('recordAssessmentResult sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.recordAssessmentResult({ orderId: 1, score: 85 })
+    expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/result\/record$/)
+  })
+})
+
+// --------------- mini-games module ---------------
+
+describe('mini-games API', () => {
+  test('getMiniGameList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMiniGameList()
+    expect(lastRequest().url).toMatch(/\/api\/mini-game\/list$/)
+  })
+
+  test('getMiniGameByCode sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMiniGameByCode('sudoku')
+    expect(lastRequest().url).toMatch(/\/api\/mini-game\/sudoku$/)
+  })
+
+  test('completeMiniGame sends POST with game data', async () => {
+    mockSuccess({ code: 200 })
+    await api.completeMiniGame(5, 'sudoku', 120, 85)
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.gameCode).toBe('sudoku')
+    expect(lastRequest().data.completionTime).toBe(120)
+    expect(lastRequest().data.score).toBe(85)
+  })
+
+  test('getGameHistory sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGameHistory({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/game\/history$/)
+  })
+
+  test('getGameLeaderboard sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGameLeaderboard({ gameCode: 'sudoku' })
+    expect(lastRequest().url).toMatch(/\/api\/game\/leaderboard$/)
+  })
+})
+
+// --------------- growth module ---------------
+
+describe('growth records API', () => {
+  test('createGrowthRecord sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.createGrowthRecord({ memberId: 5, content: '长高了2cm' })
+    expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create$/)
+  })
+
+  test('getGrowthRecordList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getGrowthRecordList()
+    expect(lastRequest().url).toMatch(/\/api\/growth\/record\/list$/)
+  })
+
+  test('createGrowthRecord with alsoPurchaseAssessment uses merge endpoint', async () => {
+    mockSuccess({ code: 200 })
+    await api.createGrowthRecord({ memberId: 5, alsoPurchaseAssessment: true })
+    expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create-with-order$/)
+  })
+})
+
+// --------------- energy module ---------------
+
+describe('energy API', () => {
+  test('getEnergyOverview sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getEnergyOverview(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getEnergyLogs sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getEnergyLogs(5, 'body', 1, 20)
+    expect(lastRequest().data.dimensionCode).toBe('body')
+  })
+
+  test('getFamilyEnergySandbox sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getFamilyEnergySandbox()
+    expect(lastRequest().url).toMatch(/\/api\/energy\/sandbox$/)
+  })
+})
+
+// --------------- badges module ---------------
+
+describe('badges API', () => {
+  test('getActiveBadges sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getActiveBadges()
+    expect(lastRequest().url).toMatch(/\/api\/badges\/list$/)
+  })
+
+  test('getMemberBadges sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getMemberBadges(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('toggleBadgeFavorite sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.toggleBadgeFavorite(5, 3)
+    expect(lastRequest().data.memberId).toBe(5)
+    expect(lastRequest().data.badgeId).toBe(3)
+  })
+})
+
+// --------------- articles module ---------------
+
+describe('articles API', () => {
+  test('getArticleCategories sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleCategories()
+    expect(lastRequest().url).toMatch(/\/api\/articles\/categories$/)
+  })
+
+  test('getArticleList sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleList({ categoryId: 1, page: 1 })
+    expect(lastRequest().url).toMatch(/\/api\/articles\/list$/)
+  })
+
+  test('getArticleList carries keyword payload (C4 search contract)', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleList({ page: 1, size: 10, keyword: '睡眠' })
+    const req = lastRequest()
+    expect(req.url).toMatch(/\/api\/articles\/list$/)
+    expect(req.method).toBe('POST')
+    expect(req.data.keyword).toBe('睡眠')
+    expect(req.data.page).toBe(1)
+    expect(req.data.size).toBe(10)
+  })
+
+  test('getArticleList passes keyword through raw (trim/cancel semantics live in the page)', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleList({ page: 1, size: 10, keyword: '  ' })
+    expect(lastRequest().data.keyword).toBe('  ')
+  })
+
+  test('getArticleDetail sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleDetail({ id: 42 })
+    expect(lastRequest().url).toMatch(/\/api\/articles\/detail$/)
+  })
+
+  test('getDailyTip sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getDailyTip()
+    expect(lastRequest().url).toMatch(/\/api\/articles\/daily-tip$/)
+  })
+
+  test('getArticleTags sends POST /api/articles/tags', async () => {
+    mockSuccess({ code: 200 })
+    await api.getArticleTags()
+    expect(lastRequest().url).toMatch(/\/api\/articles\/tags$/)
+  })
+})
+
+// --------------- contact module ---------------
+
+describe('contact API', () => {
+  test('getContactList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getContactList({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/contact\/list$/)
+  })
+
+  test('createContact sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.createContact({ name: '爷爷', relation: 'grandfather' })
+    expect(lastRequest().url).toMatch(/\/api\/contact\/create$/)
+  })
+
+  test('deleteContact sends POST with id', async () => {
+    mockSuccess({ code: 200 })
+    await api.deleteContact(3)
+    expect(lastRequest().url).toMatch(/\/api\/contact\/delete$/)
+    expect(lastRequest().data.id).toBe(3)
+  })
+
+  test('importPhoneContact sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.importPhoneContact({ contacts: [{ name: '张三', phone: '13800138000' }] })
+    expect(lastRequest().url).toMatch(/\/api\/contact\/import-phone$/)
+  })
+})
+
+// --------------- vendor module ---------------
+
+describe('vendor API', () => {
+  test('vendorApply sends POST with data', async () => {
+    mockSuccess({ code: 200 })
+    await api.vendorApply({ companyName: '某某公司', type: 'planner' })
+    expect(lastRequest().url).toMatch(/\/api\/vendor\/apply$/)
+  })
+
+  test('vendorStatus sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.vendorStatus()
+    expect(lastRequest().url).toMatch(/\/api\/vendor\/status$/)
+  })
+
+  test('vendorInfo sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.vendorInfo()
+    expect(lastRequest().url).toMatch(/\/api\/vendor\/info$/)
+  })
+})
+
+// --------------- product module ---------------
+
+describe('product API', () => {
+  test('productList sends POST', () => {
+    // productList uses new Promise without success/fail callbacks,
+    // so we check the request synchronously.
+    api.productList({ page: 1, size: 10 })
+    const opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/product\/list$/)
+  })
+
+  test('productDetail sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.productDetail({ id: 1 })
+    expect(lastRequest().url).toMatch(/\/api\/product\/detail$/)
+  })
+
+  test('productCreate sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.productCreate({ name: '测试商品', price: 100 })
+    expect(lastRequest().url).toMatch(/\/api\/product\/create$/)
+  })
+
+  test('productOrderCreate sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.productOrderCreate({ productId: 1, quantity: 2 })
+    expect(lastRequest().url).toMatch(/\/api\/product\/order\/create$/)
+  })
+})
+
+// --------------- commission / invite ---------------
+
+describe('commission & invite API', () => {
+  test('getReferralCode sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getReferralCode()
+    expect(lastRequest().url).toMatch(/\/api\/invite\/code$/)
+  })
+
+  test('bindReferral sends POST with code', async () => {
+    mockSuccess({ code: 200 })
+    await api.bindReferral('ABC123')
+    expect(lastRequest().data.referralCode).toBe('ABC123')
+  })
+
+  test('getCommissionSummary sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getCommissionSummary()
+    expect(lastRequest().url).toMatch(/\/api\/commission\/summary$/)
+  })
+
+  test('applyWithdrawal sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.applyWithdrawal(500, { bank: 'ICBC', account: '6222****' })
+    expect(lastRequest().data.amount).toBe(500)
+  })
+})
+
+// --------------- stats module ---------------
+
+describe('stats API', () => {
+  test('getChildCompletionStats sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getChildCompletionStats({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/stats\/child-completion$/)
+  })
+
+  test('getChildOverview sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getChildOverview(5)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+})
+
+// --------------- AI chat module ---------------
+
+describe('AI chat API', () => {
+  test('aiSendMessage sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.aiSendMessage({ conversationId: 1, content: '你好' })
+    expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/send$/)
+  })
+
+  test('aiGetConversations sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.aiGetConversations()
+    expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/conversations$/)
+  })
+})
+
+// --------------- health / wealth module ---------------
+
+// --------------- health report module (new) ---------------
+
+describe('health report API', () => {
+  test('createHealthReport sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.createHealthReport({ memberId: 5, reportData: { height: 120, weight: 22 } })
+    expect(lastRequest().url).toMatch(/\/api\/health\/report\/create$/)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getReportList sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getReportList(5)
+    expect(lastRequest().url).toMatch(/\/api\/health\/report\/list$/)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getReportDetail sends POST with reportId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getReportDetail(42)
+    expect(lastRequest().url).toMatch(/\/api\/health\/report\/detail$/)
+    expect(lastRequest().data.reportId).toBe(42)
+  })
+
+  test('getLatestHealthReport sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getLatestHealthReport(5)
+    expect(lastRequest().url).toMatch(/\/api\/health\/report\/latest$/)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('getHealthIndicatorList sends POST with memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getHealthIndicatorList(5)
+    expect(lastRequest().url).toMatch(/\/api\/health\/indicator\/list$/)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('createReportSurvey sends POST with reportId and memberId', async () => {
+    mockSuccess({ code: 200 })
+    await api.createReportSurvey(10, 5)
+    expect(lastRequest().url).toMatch(/\/api\/health\/survey\/create$/)
+    expect(lastRequest().data.reportId).toBe(10)
+    expect(lastRequest().data.memberId).toBe(5)
+  })
+
+  test('submitReportSurvey sends POST with surveyId and data', async () => {
+    mockSuccess({ code: 200 })
+    await api.submitReportSurvey(1, { q1: 'yes', q2: 'no' })
+    expect(lastRequest().url).toMatch(/\/api\/health\/survey\/submit$/)
+    expect(lastRequest().data.surveyId).toBe(1)
+    expect(lastRequest().data.surveyData.q1).toBe('yes')
+  })
+
+  test('getSurveyStatus sends POST with reportId', async () => {
+    mockSuccess({ code: 200 })
+    await api.getSurveyStatus({ reportId: 10 })
+    expect(lastRequest().url).toMatch(/\/api\/survey\/status$/)
+    expect(lastRequest().data.reportId).toBe(10)
+  })
+})
+
+describe('health & wealth API', () => {
+  test('healthCheckinList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.healthCheckinList({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/health\/checkin\/list$/)
+  })
+
+  test('getCheckinList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getCheckinList({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/wealth\/checkin\/list$/)
+  })
+
+  test('getInsuranceList sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.getInsuranceList({ memberId: 5 })
+    expect(lastRequest().url).toMatch(/\/api\/wealth\/insurance\/list$/)
+  })
+})
+
+// --------------- invite card module ---------------
+
+describe('invite card API', () => {
+  test('generateInviteCard sends POST', async () => {
+    mockSuccess({ code: 200 })
+    await api.generateInviteCard('guide', 1)
+    expect(lastRequest().data.type).toBe('guide')
+  })
+
+  test('verifyInviteCard sends POST with code', async () => {
+    mockSuccess({ code: 200 })
+    await api.verifyInviteCard('CARD123')
+    expect(lastRequest().data.code).toBe('CARD123')
+  })
+})
+
+
+describe('article related API', () => {
+  test('getRelatedArticles sends POST /api/articles/related', async () => {
+    let captured = null
+    global.uni.request.mockImplementation((opts) => {
+      captured = opts
+      process.nextTick(() => { if (opts.success) opts.success({ data: { code: 200, data: [] } }) })
+    })
+    await api.getRelatedArticles({ articleId: 15, size: 3 })
+    expect(captured.url).toMatch(/\/api\/articles\/related$/)
+    expect(captured.method).toBe('POST')
+    expect(captured.data.articleId).toBe(15)
+    expect(captured.data.size).toBe(3)
+  })
+
+  test('getRelatedArticles passes data through request', async () => {
+    mockSuccess({ code: 200, data: [{ id: 2, title: 't' }] })
+    const res = await api.getRelatedArticles({ articleId: 15 })
+    expect(res.code).toBe(200)
+  })
+})
+
+// --------------- AI 会员门禁(T-F0:aiGateStatus + _noToast) ---------------
+
+describe('AI member gate API', () => {
+  beforeEach(() => {
+    global.uni._storage.token = 'test-token'
+  })
+
+  test('aiGateStatus sends POST /api/ai/gate 且不把 _noToast 拼进 URL', async () => {
+    mockSuccess({ code: 200, data: { status: 'ALLOW', canUse: true } })
+    const res = await api.aiGateStatus()
+    const opts = lastRequest()
+    expect(opts.url).toMatch(/\/api\/ai\/gate$/)
+    expect(opts.url).not.toMatch(/_noToast/)
+    expect(opts.method).toBe('POST')
+    expect(res.data.status).toBe('ALLOW')
+  })
+
+  test('_noToast:非 200 不弹 toast,reject 仍带 code/message', async () => {
+    mockSuccess({ code: 46003, message: '该功能为会员专享,请先开通会员' })
+    await expect(api.aiGateStatus()).rejects.toMatchObject({
+      code: 46003,
+      message: '该功能为会员专享,请先开通会员'
+    })
+    expect(global.uni.showToast).not.toHaveBeenCalled()
+  })
+
+  test('无 _noToast 时非 200 仍弹 toast(回归保护)', async () => {
+    mockSuccess({ code: 500, message: '服务异常' })
+    await expect(api.getMyMembership()).rejects.toMatchObject({ code: 500 })
+    expect(global.uni.showToast).toHaveBeenCalledTimes(1)
+    expect(global.uni.showToast.mock.calls[0][0].title).toBe('服务异常')
+  })
+
+  test('aiSendMessage 门禁错误不弹 toast(避免 toast + 弹窗叠加)', async () => {
+    mockSuccess({ code: 46004, message: '会员已过期,请续费后继续使用' })
+    await expect(api.aiSendMessage({ query: 'hi', conversationId: '' })).rejects.toMatchObject({
+      code: 46004
+    })
+    expect(global.uni.showToast).not.toHaveBeenCalled()
+  })
+})

+ 159 - 0
cfc-frontend/__tests__/components/FamilyRelationGraph.test.js

@@ -0,0 +1,159 @@
+/**
+ * Tests for FamilyRelationGraph helper functions
+ */
+import { shallowMount } from '@vue/test-utils'
+
+// --------------- helper functions (extracted from component) ---------------
+
+function getEnergy(energyMap, memberId, dimensionCode) {
+  const data = energyMap[memberId]
+  if (!data) return 0
+  const key = dimensionCode + 'Score'
+  const val = data[key]
+  return (typeof val !== 'undefined' && val !== null) ? val : 0
+}
+
+function getAvatarSize(energy, isSelf) {
+  const clamped = Math.max(0, Math.min(100, energy))
+  const base = 64 + (clamped / 100) * 56
+  if (isSelf) return Math.max(96, base + 16)
+  return base
+}
+
+function getLayoutMode(memberCount) {
+  if (memberCount <= 3) return 'row'
+  return 'multi-row'
+}
+
+function getDisplayOrder(members, selfId) {
+  let self = null
+  const others = []
+  for (let i = 0; i < members.length; i++) {
+    if (members[i].id === selfId) {
+      self = members[i]
+    } else {
+      others.push(members[i])
+    }
+  }
+  if (members.length === 2) return [self, others[0]]
+  if (members.length === 3 && others.length >= 2) return [others[0], self, others[1]]
+  return [self].concat(others)
+}
+
+function getLineEndPoints(selfCX, selfCY, selfR, otherCX, otherCY, otherR) {
+  const dx = otherCX - selfCX
+  const dy = otherCY - selfCY
+  const dist = Math.sqrt(dx * dx + dy * dy)
+  if (dist < 1) return null
+  const ux = dx / dist
+  const uy = dy / dist
+  return {
+    x1: selfCX + ux * selfR,
+    y1: selfCY + uy * selfR,
+    x2: otherCX - ux * otherR,
+    y2: otherCY - uy * otherR
+  }
+}
+
+// --------------- tests ---------------
+
+describe('getAvatarSize', () => {
+  it('returns min size for other at energy 0', () => {
+    expect(getAvatarSize(0, false)).toBe(64)
+  })
+
+  it('returns max size for other at energy 100', () => {
+    expect(getAvatarSize(100, false)).toBe(120)
+  })
+
+  it('returns mid size for other at energy 50', () => {
+    expect(getAvatarSize(50, false)).toBe(92)
+  })
+
+  it('self min is 96', () => {
+    expect(getAvatarSize(0, true)).toBe(96)
+  })
+
+  it('self max at energy 100', () => {
+    expect(getAvatarSize(100, true)).toBe(136)
+  })
+
+  it('clamps negative energy to 0', () => {
+    expect(getAvatarSize(-10, false)).toBe(64)
+  })
+
+  it('clamps energy > 100 to 100', () => {
+    expect(getAvatarSize(150, false)).toBe(120)
+  })
+})
+
+describe('getLayoutMode', () => {
+  it('0 members returns row', () => {
+    expect(getLayoutMode(0)).toBe('row')
+  })
+
+  it('2 members returns row', () => {
+    expect(getLayoutMode(2)).toBe('row')
+  })
+
+  it('3 members returns row', () => {
+    expect(getLayoutMode(3)).toBe('row')
+  })
+
+  it('4 members returns multi-row', () => {
+    expect(getLayoutMode(4)).toBe('multi-row')
+  })
+
+  it('10 members returns multi-row', () => {
+    expect(getLayoutMode(10)).toBe('multi-row')
+  })
+})
+
+describe('getDisplayOrder', () => {
+  it('2-person: self first, other second', () => {
+    const members = [{ id: 1, nickname: '爸' }, { id: 2, nickname: '我' }]
+    const order = getDisplayOrder(members, 2)
+    expect(order[0].id).toBe(2)
+    expect(order[1].id).toBe(1)
+  })
+
+  it('3-person: others on sides, self center', () => {
+    const members = [{ id: 1, nickname: '爸' }, { id: 2, nickname: '我' }, { id: 3, nickname: '妈' }]
+    const order = getDisplayOrder(members, 2)
+    expect(order[0].id).toBe(1)
+    expect(order[1].id).toBe(2)
+    expect(order[2].id).toBe(3)
+  })
+})
+
+describe('getLineEndPoints', () => {
+  it('calculates correct horizontal line endpoints', () => {
+    const pts = getLineEndPoints(100, 100, 30, 300, 100, 20)
+    expect(pts.x1).toBe(130)
+    expect(pts.x2).toBe(280)
+    expect(pts.y1).toBe(100)
+    expect(pts.y2).toBe(100)
+  })
+
+  it('returns null when distance < 1', () => {
+    const pts = getLineEndPoints(100, 100, 30, 100, 100, 20)
+    expect(pts).toBeNull()
+  })
+})
+
+describe('getEnergy', () => {
+  it('retrieves body energy by dimension code', () => {
+    const energyMap = { 1: { bodyScore: 80, mindScore: 40 } }
+    expect(getEnergy(energyMap, 1, 'body')).toBe(80)
+  })
+
+  it('retrieves mind energy by dimension code', () => {
+    const energyMap = { 1: { bodyScore: 80, mindScore: 40 } }
+    expect(getEnergy(energyMap, 1, 'mind')).toBe(40)
+  })
+
+  it('returns 0 for missing member', () => {
+    const energyMap = { 1: { bodyScore: 80 } }
+    expect(getEnergy(energyMap, 2, 'body')).toBe(0)
+  })
+})

+ 75 - 0
cfc-frontend/__tests__/config/config.test.js

@@ -0,0 +1,75 @@
+/**
+ * Tests for cfc-frontend config.js
+ *
+ * Tests environment detection logic by mocking uni.getAccountInfoSync.
+ */
+import config from '@/config'
+
+beforeEach(() => {
+  global.uni._storage = {}
+  global.uni.getAccountInfoSync.mockReset()
+  global.uni.getAccountInfoSync.mockReturnValue({
+    miniProgram: { envVersion: 'develop' }
+  })
+})
+
+// 与 config.js 保持一致:develop / trial / release 三端统一指向同一生产域名;
+// 非小程序环境、env 缺失或未知 envVersion 时,回落到模块顶部的默认值。
+// 换域名时只需改这两行(对应 config.js 的 switch 分支与顶部默认值)。
+const PROD_HOST = 'https://cfc.etotem.com.cn'
+const FALLBACK_HOST = 'http://cfc.iwintrue.com'
+
+describe('config.js', () => {
+  beforeEach(() => {
+    // Reset the module registry so each test gets a fresh config
+    // (config.js 在模块加载时就求值 API_BASE_URL,必须重新 require 才会重跑这段逻辑)
+    jest.resetModules()
+  })
+
+  test('uses production host when getAccountInfoSync returns develop', () => {
+    global.uni.getAccountInfoSync.mockReturnValue({
+      miniProgram: { envVersion: 'develop' }
+    })
+    const cfg = require('@/config').default
+    expect(cfg.API_BASE_URL).toBe(PROD_HOST)
+  })
+
+  test('uses production host when envVersion is trial', () => {
+    global.uni.getAccountInfoSync.mockReturnValue({
+      miniProgram: { envVersion: 'trial' }
+    })
+    const cfg = require('@/config').default
+    expect(cfg.API_BASE_URL).toBe(PROD_HOST)
+  })
+
+  test('uses production host when envVersion is release', () => {
+    global.uni.getAccountInfoSync.mockReturnValue({
+      miniProgram: { envVersion: 'release' }
+    })
+    const cfg = require('@/config').default
+    expect(cfg.API_BASE_URL).toBe(PROD_HOST)
+  })
+
+  test('uses defaults when getAccountInfoSync throws', () => {
+    global.uni.getAccountInfoSync.mockImplementation(() => {
+      throw new Error('not in mini-program')
+    })
+    const cfg = require('@/config').default
+    expect(cfg.API_BASE_URL).toBe(FALLBACK_HOST)
+  })
+
+  test('uses defaults for unknown envVersion', () => {
+    global.uni.getAccountInfoSync.mockReturnValue({
+      miniProgram: { envVersion: 'unknown' }
+    })
+    const cfg = require('@/config').default
+    // Falls through the switch without matching, keeps defaults
+    expect(cfg.API_BASE_URL).toBe(FALLBACK_HOST)
+  })
+
+  test('api(path) returns full URL joining API_BASE_URL + path', () => {
+    const cfg = require('@/config').default
+    const result = cfg.api('/api/test')
+    expect(result).toBe(cfg.API_BASE_URL + '/api/test')
+  })
+})

+ 342 - 0
cfc-frontend/__tests__/diet/recommendation.healthAdjustUi.test.js

@@ -0,0 +1,342 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 diet.food.healthAdjustUi
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-09-diet-recommendation-health-questionnaire-adjust.md
+ *                §2 调整分级语义(blocked/warning/boost/normal)、§4 验收判据 V/C-1/6
+ *   design:      同上 §3 前端 B1-B3 + cfc-frontend/pages/diet/recommendation.vue L104-123/L285-334/L491-523
+ *
+ * B1. loadFoods(L491-523):/api/health/foods 响应食材透传 adjustment / adjustmentReason(旁置现有 scoreClass/statusText/status 映射)
+ * B2. 食物卡片(L104-123):按 item.adjustment 渲染提示条——
+ *     blocked → 红条「⚠ 健康问卷不建议:{adjustmentReason}」
+ *     warning → 黄条「注意:{adjustmentReason}」
+ *     boost   → 绿条「✓ 符合饮食习惯偏好」
+ *     normal/空 → 不渲染
+ * B3. filteredFoods(L285-334):suitable Tab 中 adjustment==='blocked' 项排到列表末尾
+ *     (保持可见但不置顶);unsuitable / all 位置不变、仅带提示条;排序逻辑不变,仅 stable 分组。
+ *
+ * 说明(沿用既有的 Jest 体系约束,见 __tests__/family-join/join-form.required-info.test.js):
+ *   jest.config.js 仅 transform .js;约定为「加载真实 SFC 的 <script>/<template> 源码断言」,不挂载 .vue。
+ *   本文件直接读取推荐食材页 recommendation.vue 的源码——
+ *   - <script>:import 语句替换为注入桩后求值,驱动真实 data()/methods/computed 做行为级断言;
+ *   - <template>:读取模板文本做结构契约断言(三类提示条 + adjustment 分支条件 + adjustmentReason 插值)。
+ *   GREEN 阶段实现方对 recommendation.vue 补足 B1-B3 后本文件即翻绿;当前实现缺失 → 预期 RED。
+ *   本文件不修改 pages/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const RECOMMENDATION_PATH = path.join(__dirname, '../../pages/diet/recommendation.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 recommendation.vue 的 <script> 行为(data/methods/computed)与 <template> 结构
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__recommendationStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadRecommendation() {
+  var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__recommendationStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 合并,computed 由用例对 component.computed 调用) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 驱动真实 computed.filteredFoods(computed 为函数属性,以 vm 为 this 求值) */
+function evalFilteredFoods(component, vm) {
+  var computed = component.computed || {}
+  if (typeof computed.filteredFoods !== 'function') throw new Error('computed.filteredFoods 缺失')
+  return computed.filteredFoods.call(vm)
+}
+
+function ids(list) {
+  return list.map(function (f) { return f.id })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.request.mockReset()
+  global.uni.showToast.mockReset()
+  stubs = {
+    getDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 0, message: 'ok', data: null }) }),
+    generateDietRecommendation: jest.fn(),
+    completeDietRecommendation: jest.fn(),
+    regenerateDietRecommendation: jest.fn(),
+    updateDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 200, message: 'success', data: null }) }),
+    config: { API_BASE_URL: 'http://mock' },
+    MemberSelector: {},
+    memberIdOf: function (m) { return m && (m.familyMemberId || m.memberId || m.id) },
+    fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+  }
+  globalThis.__recommendationStubs = {
+    '@/utils/api.js': {
+      getDietRecommendation: stubs.getDietRecommendation,
+      generateDietRecommendation: stubs.generateDietRecommendation,
+      completeDietRecommendation: stubs.completeDietRecommendation,
+      regenerateDietRecommendation: stubs.regenerateDietRecommendation,
+      updateDietRecommendation: stubs.updateDietRecommendation
+    },
+    '@/config.js': { config: stubs.config },
+    '@/components/MemberSelector.vue': { MemberSelector: stubs.MemberSelector },
+    '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
+    '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__recommendationStubs
+})
+
+// ---------------------------------------------------------------------------
+// B1. loadFoods 透传 adjustment / adjustmentReason(旁置现有 scoreClass/statusText/status 映射)
+//     契约:/api/health/foods 响应食材的 adjustment / adjustmentReason 必须原样进入 allFoods,
+//     不得被 map 丢弃或改写(GREEN 实现须保持显式透传;当前借 object 复用保留,属既有增强面)
+// ---------------------------------------------------------------------------
+
+describe('B1 loadFoods 透传 adjustment / adjustmentReason', function () {
+  var component
+
+  beforeEach(function () {
+    component = loadRecommendation().component
+    global.uni._storage.token = 'mock-token'
+  })
+
+  it('后端返回 adjustment=blocked 食材 → allFoods 保留 blocked 与 adjustmentReason 原文', function () {
+    var foods = [{ id: 1, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' }]
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: foods } })
+    })
+    var vm = instantiate(component)
+    vm.loadFoods()
+    expect(vm.allFoods.length).toBe(1)
+    expect(vm.allFoods[0].adjustment).toBe('blocked')
+    expect(vm.allFoods[0].adjustmentReason).toBe('过敏原花生命中,建议不食')
+  })
+
+  it('后端返回 adjustment=warning 食材 → allFoods 保留 warning 与 interval 提示文案', function () {
+    var foods = [{ id: 2, name: '西柚', category: '水果', score: 3, adjustment: 'warning', adjustmentReason: '药物二甲双胍与西柚需间隔 30 分钟' }]
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: foods } })
+    })
+    var vm = instantiate(component)
+    vm.loadFoods()
+    expect(vm.allFoods[0].adjustment).toBe('warning')
+    expect(vm.allFoods[0].adjustmentReason).toBe('药物二甲双胍与西柚需间隔 30 分钟')
+  })
+
+  it('后端未返回 adjustment(报告快照分支/灰度未下发)→ allFoods 不伪造 adjustment 值', function () {
+    var foods = [{ id: 3, name: '苹果', category: '水果', score: 6 }]
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: foods } })
+    })
+    var vm = instantiate(component)
+    vm.loadFoods()
+    // normal/空 → 不渲染分支的输入前提:缺失时保持 undefined,不得擅自赋值 blocked/warning/boost
+    expect(vm.allFoods[0].adjustment).toBeUndefined()
+    expect(vm.allFoods[0].adjustmentReason).toBeUndefined()
+  })
+
+  it('既有 scoreClass/statusText/status 映射无回归', function () {
+    var foods = [{ id: 4, name: '鸡蛋', category: '蛋奶', score: 10, adjustment: 'boost' }]
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: foods } })
+    })
+    var vm = instantiate(component)
+    vm.loadFoods()
+    expect(vm.allFoods[0].scoreClass).toBe('good')
+    expect(vm.allFoods[0].statusText).toBe('适合')
+    expect(vm.allFoods[0].status).toBe('suitable')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// B2. 食物卡片按 item.adjustment 渲染三类提示条(template 结构契约,当前实现缺失 → 预期 RED)
+//     blocked → 红条「⚠ 健康问卷不建议:{adjustmentReason}」
+//     warning → 黄条「注意:{adjustmentReason}」
+//     boost   → 绿条「✓ 符合饮食习惯偏好」
+//     normal/空 → 不渲染(无独立分支,仅 v-if 缺席判定)
+// ---------------------------------------------------------------------------
+
+describe('B2 食物卡片 adjustment 提示条(template 结构契约)', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数,置空即可(loadRecommendation 对桩做可选访问)
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+
+  it('blocked:红条「健康问卷不建议」以 item.adjustment === blocked 为条件', function () {
+    expect(template).toMatch(/健康问卷不建议/)
+    expect(template).toMatch(/item\.adjustment\s*===?\s*'blocked'/)
+  })
+
+  it('blocked 红条插值渲染 adjustmentReason(原因为空则不渲染该文案)', function () {
+    expect(template).toMatch(/item\.adjustmentReason/)
+  })
+
+  it('warning:黄条「注意」以 item.adjustment === warning 为条件', function () {
+    expect(template).toMatch(/注意/)
+    expect(template).toMatch(/item\.adjustment\s*===?\s*'warning'/)
+  })
+
+  it('boost:绿条「符合饮食习惯偏好」以 item.adjustment === boost 为条件', function () {
+    expect(template).toMatch(/符合饮食习惯偏好/)
+    expect(template).toMatch(/item\.adjustment\s*===?\s*'boost'/)
+  })
+
+  it('提示条仅挂在 adjustment 判定之下(normal/空不渲染:模板中不得出现无条件提示文案)', function () {
+    // 三个提示文案若缺 v-if 条件(如直接常显),将同时命中「无条件常显」:此处抽样断言文案与条件在卡片域内共存。
+    var cardRegion = template.split('<view class="food-card"')[1] || ''
+    expect(cardRegion).toMatch(/item\.adjustment/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// B3. filteredFoods 分组:suitable Tab 中 blocked 项排到列表末尾(当前仅按 score 排序 → 预期 RED)
+//     unsuitable / all:位置不变,仅带提示条(既有 score 排序无回归锁定)
+// ---------------------------------------------------------------------------
+
+describe('B3 filteredFoods 分组(suitable blocked 排末尾)', function () {
+  function makeVm(component) {
+    var vm = instantiate(component)
+    vm.currentView = 'personal'
+    vm.activeCategory = 'all'
+    vm.searchQuery = ''
+    return vm
+  }
+
+  it('suitable + desc:非 blocked 按分值在前,blocked 高值项落列表末尾(不置顶)', function () {
+    var component = loadRecommendation().component
+    var vm = makeVm(component)
+    vm.filterType = 'suitable'
+    vm.sortType = 'desc'
+    vm.allFoods = [
+      { id: 1, name: '鸡蛋', category: '蛋奶', score: 3, adjustment: 'boost' },
+      { id: 2, name: '花生', category: '谷物', score: 10, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
+      { id: 3, name: '牛奶', category: '蛋奶', score: 5, adjustment: 'normal' }
+    ]
+    var result = evalFilteredFoods(component, vm)
+    // 契约:花生(blocked) 虽分值最高,仍排末尾 → [牛奶, 鸡蛋, 花生]
+    expect(ids(result)).toEqual([3, 1, 2])
+  })
+
+  it('suitable Tab 首项不得为 blocked(存在非 blocked 可排时)', function () {
+    var component = loadRecommendation().component
+    var vm = makeVm(component)
+    vm.filterType = 'suitable'
+    vm.sortType = 'desc'
+    vm.allFoods = [
+      { id: 1, name: '鸡蛋', category: '蛋奶', score: 3, adjustment: 'boost' },
+      { id: 2, name: '花生', category: '谷物', score: 10, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
+      { id: 3, name: '牛奶', category: '蛋奶', score: 5, adjustment: 'normal' }
+    ]
+    var result = evalFilteredFoods(component, vm)
+    expect(result[0].adjustment).not.toBe('blocked')
+  })
+
+  it('suitable + desc:多个 blocked 项整体落末尾(stable 分组,组内保持分值序)', function () {
+    var component = loadRecommendation().component
+    var vm = makeVm(component)
+    vm.filterType = 'suitable'
+    vm.sortType = 'desc'
+    vm.allFoods = [
+      { id: 1, name: '鸡蛋', category: '蛋奶', score: 9, adjustment: 'boost' },
+      { id: 2, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
+      { id: 3, name: '核桃', category: '坚果', score: 7, adjustment: 'blocked', adjustmentReason: '疾病痛风禁忌食用' },
+      { id: 4, name: '苹果', category: '水果', score: 6, adjustment: undefined }
+    ]
+    var result = evalFilteredFoods(component, vm)
+    // 非 blocked 在前(鸡蛋9 > 苹果6),blocked 组整体落末尾(花生8 > 核桃7)
+    expect(ids(result)).toEqual([1, 4, 2, 3])
+  })
+
+  it('unsuitable Tab:blocked 不强制移动,仅按既有分值排序(位置不变、仅带提示条)', function () {
+    var component = loadRecommendation().component
+    var vm = makeVm(component)
+    vm.filterType = 'unsuitable'
+    vm.sortType = 'asc'
+    vm.allFoods = [
+      { id: 1, name: '动物内脏', category: '肉禽', score: -5, adjustment: 'blocked', adjustmentReason: '疾病痛风禁忌食用' },
+      { id: 2, name: '西柚', category: '水果', score: -8, adjustment: 'warning', adjustmentReason: '药物间隔离提示' },
+      { id: 3, name: '腌制菜', category: '蔬菜', score: -3, adjustment: 'normal' }
+    ]
+    var result = evalFilteredFoods(component, vm)
+    // 升序:西柚(-8) < 动物内脏(-5) < 腌制菜(-3),blocked 不置末
+    expect(ids(result)).toEqual([2, 1, 3])
+  })
+
+  it('all Tab:位置不变、仅带提示条(既有 score 排序无回归)', function () {
+    var component = loadRecommendation().component
+    var vm = makeVm(component)
+    vm.filterType = 'all'
+    vm.sortType = 'desc'
+    vm.allFoods = [
+      { id: 1, name: '鸡蛋', category: '蛋奶', score: 9, adjustment: 'boost' },
+      { id: 2, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
+      { id: 4, name: '苹果', category: '水果', score: 6, adjustment: undefined }
+    ]
+    var result = evalFilteredFoods(component, vm)
+    expect(ids(result)).toEqual([1, 2, 4])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为「当前推荐」个人食材视图的展示层(recommendation.vue),
+// 页面沿既有 JWT/memberId 鉴权(controller 侧 userId/familyId 属性鉴权,接口不新增越权面),
+// 前端无独立角色分支 → 《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:健康问卷调整展示无独立角色门禁,不适用', function () {
+  it('占位:该能力沿既有 memberId/userId 鉴权,无新增 role 分支(详见汇报)', function () {})
+})

+ 316 - 0
cfc-frontend/__tests__/family-join/join-form.required-info.test.js

@@ -0,0 +1,316 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.invite.joinRequiredInfoFrontend
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-family-join-required-info.md
+ *                §3 AC-R1/AC-R3(前端可见且必填、校验规则)、§4.2(前端表单)、§5 WI-1(前端表单补充出生日期与性别必填项)
+ *   design:      cfc-frontend/pages/invite/join-form.vue + cfc-frontend/utils/api.js `updateUserInfo`
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
+ *   且未安装 vue-jest/jsdom 组件环境 —— 既有约定为「抽取被测逻辑断言」而非挂载 .vue
+ *   (见 __tests__/components/FamilyRelationGraph.test.js,导入 shallowMount 但实际只测抽取函数)。
+ *   本文件沿用该约定,但比「测试内复刻逻辑」更强:直接加载真实 SFC 的 <script>/<template> 源码——
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(必填标记、picker 绑定、change 处理器)。
+ *   若实现方在后续 GREEN 阶段对 join-form.vue 补足契约,本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { updateUserInfo as apiUpdateUserInfo, clearApiDedup } from '@/utils/api'
+
+const JOIN_FORM_PATH = path.join(__dirname, '../../pages/invite/join-form.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 join-form.vue 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__joinFormStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__joinFormStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadJoinForm() {
+  var src = fs.readFileSync(JOIN_FORM_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 join-form.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__joinFormStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.reLaunch.mockReset()
+  global.uni.request.mockReset()
+  stubs = {
+    updateUserInfo: jest.fn(function () { return Promise.resolve({ code: 0, message: 'ok', data: null }) }),
+    requestJoinByCode: jest.fn(function () { return Promise.resolve({ code: 0, message: 'ok', data: null }) }),
+    pickImage: jest.fn(),
+    fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+  }
+  globalThis.__joinFormStubs = {
+    '@/utils/api.js': { updateUserInfo: stubs.updateUserInfo, requestJoinByCode: stubs.requestJoinByCode },
+    '@/utils/image-picker.js': { pickImage: stubs.pickImage },
+    '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin }
+  }
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__joinFormStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC1.1 表单结构:真实姓名 + 出生日期 + 性别三项,出生日期/性别带 * 必填标记
+// ---------------------------------------------------------------------------
+
+describe('AC1.1 表单结构:出生日期/性别必填项可见', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach 执行:仅做模板结构断言,无需桩函数,置空即可(loadJoinForm 对桩做可选访问)
+    globalThis.__joinFormStubs = {}
+    template = loadJoinForm().template
+  })
+
+  it('真实姓名字段保留(无回归)', function () {
+    expect(template).toMatch(/真实姓名/)
+    expect(template).toMatch(/form\.realName/)
+  })
+
+  it('出生日期为必填(label 带 * 标记)', function () {
+    expect(template).toMatch(/出生日期[\s\S]{0,120}<text class="required">\*<\/text>/)
+  })
+
+  it('性别为必填(label 带 * 标记)', function () {
+    expect(template).toMatch(/性别[\s\S]{0,120}<text class="required">\*<\/text>/)
+  })
+
+  it('出生日期使用 uni date picker 绑定 form.birthday', function () {
+    expect(template).toMatch(/<picker[^>]*mode="date"[^>]*form\.birthday/)
+    expect(template).toMatch(/onBirthdayChange/)
+  })
+
+  it('性别使用 picker(男/女 两档)绑定 form.gender,change 映射 male/female', function () {
+    expect(template).toMatch(/onGenderChange/)
+    expect(template).toMatch(/男/)
+    expect(template).toMatch(/女/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC1.4 进入页面时预填:userInfo 已有 realName/birthday/gender 则带出
+// ---------------------------------------------------------------------------
+
+describe('AC1.4 prefill 预填已存资料', function () {
+  var component
+
+  beforeEach(function () {
+    component = loadJoinForm().component
+  })
+
+  it('预填真实姓名(既有行为,无回归)', function () {
+    global.uni.setStorageSync('userInfo', { realName: '张三' })
+    var vm = instantiate(component)
+    vm.prefill()
+    expect(vm.form.realName).toBe('张三')
+  })
+
+  it('预填出生日期与性别(userInfo.birthday/gender 带出)', function () {
+    global.uni.setStorageSync('userInfo', { realName: '张三', birthday: '1990-05-20', gender: 'male' })
+    var vm = instantiate(component)
+    vm.prefill()
+    expect(vm.form.birthday).toBe('1990-05-20')
+    expect(vm.form.gender).toBe('male')
+  })
+
+  it('userInfo 缺失三项时不写入(保持空串)', function () {
+    global.uni.setStorageSync('userInfo', {})
+    var vm = instantiate(component)
+    vm.prefill()
+    expect(vm.form.birthday).toBe('')
+    expect(vm.form.gender).toBe('')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC1.2 提交拦截:出生日期/性别/姓名任一缺失或格式非法 → toast + 不调用 requestJoinByCode
+// ---------------------------------------------------------------------------
+
+describe('AC1.2 提交拦截(正常/边界)', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadJoinForm().component
+    vm = instantiate(component)
+    vm.familyInviteCode = 'CODE-123'
+    vm.form.realName = '张三'
+    vm.form.birthday = '1990-05-20'
+    vm.form.gender = 'male'
+  })
+
+  it('真实姓名为空 → 拦截,不调用 requestJoinByCode(既有行为)', async function () {
+    vm.form.realName = '   '
+    await vm.submit()
+    expect(global.uni.showToast).toHaveBeenCalled()
+    expect(stubs.requestJoinByCode).not.toHaveBeenCalled()
+  })
+
+  it('出生日期未选 → 拦截并 toast 提示,不调用 requestJoinByCode', async function () {
+    vm.form.birthday = ''
+    await vm.submit()
+    expect(stubs.requestJoinByCode).not.toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalled()
+  })
+
+  it('性别未选 → 拦截并 toast 提示,不调用 requestJoinByCode', async function () {
+    vm.form.gender = ''
+    await vm.submit()
+    expect(stubs.requestJoinByCode).not.toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalled()
+  })
+
+  it('出生日期格式非法(非 yyyy-MM-dd)→ 拦截,不调用 requestJoinByCode', async function () {
+    vm.form.birthday = '1990/05/20'
+    await vm.submit()
+    expect(stubs.requestJoinByCode).not.toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalled()
+  })
+
+  it('缺少家庭邀请码 → 拦截(既有行为)', async function () {
+    vm.familyInviteCode = ''
+    await vm.submit()
+    expect(stubs.requestJoinByCode).not.toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC1.3 提交载荷:birthday 以 yyyy-MM-dd 字符串、gender 为 male/female 写入 updateUserInfo
+// ---------------------------------------------------------------------------
+
+describe('AC1.3 提交载荷与 picker 映射', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadJoinForm().component
+    vm = instantiate(component)
+    vm.familyInviteCode = 'CODE-123'
+    vm.form.realName = '张三'
+    vm.form.birthday = '1990-05-20'
+    vm.form.gender = 'male'
+    vm.form.nickname = ''
+    vm.form.avatar = ''
+  })
+
+  it('出生日期 change 处理器以 yyyy-MM-dd 写入 form.birthday', function () {
+    expect(typeof vm.onBirthdayChange).toBe('function')
+    vm.onBirthdayChange({ detail: { value: '2010-01-15' } })
+    expect(vm.form.birthday).toBe('2010-01-15')
+  })
+
+  it('性别 picker 索引 0 → male、索引 1 → female', function () {
+    expect(typeof vm.onGenderChange).toBe('function')
+    vm.onGenderChange({ detail: { value: 0 } })
+    expect(vm.form.gender).toBe('male')
+    vm.onGenderChange({ detail: { value: 1 } })
+    expect(vm.form.gender).toBe('female')
+  })
+
+  it('合法提交:updateUserInfo 收到 realName(trim)/birthday(yyyy-MM-dd)/gender(male|female)', async function () {
+    await vm.submit()
+    expect(stubs.updateUserInfo).toHaveBeenCalledWith(expect.objectContaining({
+      realName: '张三',
+      birthday: '1990-05-20',
+      gender: 'male'
+    }))
+  })
+
+  it('合法提交:随后调用 requestJoinByCode(inviteCode) 正常进入待审批', async function () {
+    await vm.submit()
+    expect(stubs.requestJoinByCode).toHaveBeenCalledWith('CODE-123')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 设计锚点:utils/api.js updateUserInfo 需支持 realName/gender/birthday 透传
+// (规格 §2:接口封装无改动,锚定「已支持透传」契约)
+// ---------------------------------------------------------------------------
+
+describe('设计锚点:api.js updateUserInfo 透传 realName/gender/birthday', function () {
+  it('POST /api/user/update 请求体含 realName/gender/birthday 三字段', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: null } }) })
+    })
+    clearApiDedup()
+    await apiUpdateUserInfo({ realName: '张三', gender: 'male', birthday: '1990-05-20' })
+    expect(captured.url).toContain('/api/user/update')
+    expect(captured.method).toBe('POST')
+    expect(captured.data).toEqual(expect.objectContaining({
+      realName: '张三',
+      gender: 'male',
+      birthday: '1990-05-20'
+    }))
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为「被邀请人加入申请表单」,不区分角色(邀请人/被邀请人均不触发角色门禁),
+// 属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:加入表单无角色门禁,不适用', function () {
+  it('占位:该能力面向被邀请人,无 role 分支(详见汇报)', function () {})
+})

+ 55 - 0
cfc-frontend/__tests__/games/1a2b.test.js

@@ -0,0 +1,55 @@
+/** @jest-environment jsdom */
+// TC-F-G01 · 1a2b 小游戏「首猜即中」计分与上报(R150 由 tests/unit/games/1a2b.spec.js 迁移)
+// 迁移原因:原文件用 ESM import + 挂载 .vue,但 tests/jest.config.js 无 babel preset / .vue transform,
+//           收集期即报 `Cannot use import statement outside a module`,该用例从未真正执行(R150 发现)。
+// 现挂到 cfc-frontend/__tests__(已有 .vue transform + @vue/test-utils + babel-jest)。
+// 口径说明:实现 makeGuess() 首猜命中计算 `100 - (maxGuesses - remainingGuesses) * 8 = 92`,
+//           原骨架用例期望 100 —— 二者不一致且契约无明文,已登记 B-150-4 待研发确认;
+//           本用例断言「首猜命中必进入胜利终局并上报」,分值取实现公式现值,契约澄清后同步调整。
+import Vue from 'vue'
+import { mount, createLocalVue } from '@vue/test-utils'
+import Game1a2b from '../../pages/games/1a2b.vue'
+
+jest.mock('../../utils/api.js', () => ({
+  completeMiniGame: jest.fn(() => Promise.resolve({ code: 200, data: { pointsEarned: 10, newBalance: 110 } })),
+  getChildren: jest.fn(() => Promise.resolve({ data: [{ id: 'child1' }] }))
+}))
+
+describe('1a2b.vue · 首猜即中(TC-F-G01)', () => {
+  const localVue = createLocalVue()
+
+  afterEach(() => {
+    jest.clearAllMocks()
+  })
+
+  it('首猜命中:进入胜利终局、按公式计分并上报积分', async () => {
+    const wrapper = mount(Game1a2b, {
+      localVue,
+      mocks: { $t: () => {}, $toast: () => {} }
+    })
+
+    // uni 全局(组件内 showToast/request 依赖),测试内最小桩
+    global.uni = global.uni || { showToast: jest.fn(), getStorageSync: jest.fn(() => '') }
+
+    // 固定答案 + 指定成员,保证首猜即命中且满足 submitScore 前置条件(memberId 非空)
+    wrapper.vm.generateAnswer = () => '1234'
+    await wrapper.setData({ userGuess: '1234', memberId: 1 })
+
+    wrapper.vm.startGame()
+    expect(wrapper.vm.isPlaying).toBe(true)
+    expect(wrapper.vm.gameOver).toBe(false)
+
+    await wrapper.vm.makeGuess()
+
+    // 终局:胜利
+    expect(wrapper.vm.gameOver).toBe(true)
+    expect(wrapper.vm.isWin).toBe(true)
+    // 分值:当前实现公式(首猜 = 100 - 1*8);契约若改为 100 需同步此断言
+    expect(wrapper.vm.score).toBe(92)
+    // 上报:completeMiniGame 被调用一次
+    const api = require('../../utils/api.js')
+    expect(api.completeMiniGame).toHaveBeenCalledTimes(1)
+
+    if (wrapper.vm.timer) clearInterval(wrapper.vm.timer)
+  })
+})

+ 278 - 0
cfc-frontend/__tests__/pages/article-center/articleDetailVideoFullscreen.contract.test.js

@@ -0,0 +1,278 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——能力键 article.detail.videoFullscreen(前端部分)
+ *
+ * 来源:
+ *   requirement: docs/tdd/orchestration/req-article-single-video-fullscreen-2026-12-01.md
+ *                 (§1 需求 R1-R5 / §2 设计 D1-D7 / §3 契约 C1-C4 / §4 验收)
+ *   design:      §2 设计 D1-D6(data 新增 singleVideoSrc/videoFullscreenFired;methods 新增
+ *                 isVideoOnlyContent/extractVideoSrc/onSingleVideoReady;loadDetail 接入;模板 video+mp-html 条件渲染;样式)
+ *   契约布局:本文档(页面方法/模板结构 + 行为断言)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 无 vue-jest/jsdom 组件环境 —— 沿用「读取真实 SFC 源码 → 桩化 import → 求值
+ *   <script> 拿真实 export default → 驱动 data()/methods/computed 做行为断言,模板做结构断言」,
+ *   参考 __tests__/pages/article-center/articleSearch.contract.test.js。
+ *   本文档不修改 pages/、utils/ 任何业务代码。
+ * 小程序约束(AGENTS.md):禁可选链 ?.、禁 CSS Grid、禁 :key 表达式、禁 new Date(string)。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { BrandColors } from '@/utils/brand-colors.js'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/article-center/article-detail.vue')
+
+/** 把 ES import 语句替换为从 globalThis.__articleDetailVideoStubs 取值的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__articleDetailVideoStubs || {})[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadPage() {
+  var src = fs.readFileSync(PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 article-detail.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__articleDetailVideoStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods/computed(含 mixin)构造可驱动上下文的实例 */
+function instantiate(component) {
+  var vm = {}
+  // 合并 mixin 的 data/methods/computed(模拟 Vue mixin 合并),保证 loadDetail 等能取到 mixin 方法
+  var mixins = component.mixins || []
+  var mergedData = {}
+  var mergedMethods = {}
+  var mergedComputed = {}
+  mixins.forEach(function (m) {
+    if (!m) return
+    if (typeof m.data === 'function') {
+      var md = m.data.call(vm)
+      Object.keys(md).forEach(function (k) { mergedData[k] = md[k] })
+    }
+    if (m.methods) Object.keys(m.methods).forEach(function (k) { mergedMethods[k] = m.methods[k] })
+    if (m.computed) Object.keys(m.computed).forEach(function (k) { mergedComputed[k] = m.computed[k] })
+  })
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(mergedData).forEach(function (k) { vm[k] = mergedData[k] })
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  var methods = component.methods || {}
+  Object.keys(mergedMethods).forEach(function (k) { vm[k] = mergedMethods[k] })
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  var computed = component.computed || {}
+  var allComputed = Object.assign({}, mergedComputed, computed)
+  Object.keys(allComputed).forEach(function (k) {
+    Object.defineProperty(vm, k, { get: allComputed[k], enumerable: true, configurable: true })
+  })
+  return vm
+}
+
+/** 每次调用时重新加载真实 SFC(读取当时的 __articleDetailVideoStubs),避免闭包捕获旧值 */
+function getComponent() {
+  return loadPage().component
+}
+
+/** 刷新微任务队列:让 fire-and-forget 的 async 方法(loadDetail 等)结算完成 */
+function flushPromises() {
+  return new Promise(function (resolve) { setTimeout(resolve, 0) })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var apiStubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.request.mockReset()
+  // video context 桩:onSingleVideoReady 通过 uni.createVideoContext(id, this) 拿上下文进全屏
+  global.uni.createVideoContext = jest.fn(function () {
+    return { requestFullScreen: jest.fn() }
+  })
+  apiStubs = {
+    getArticleDetail: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getArticleAudio: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { audioUrls: [] } }) }),
+    reportReadingTime: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getShareQrCode: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    completeArticleRead: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    generateQuiz: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    submitQuiz: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    completeTask: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) })
+  }
+  globalThis.__articleDetailVideoStubs = {
+    '../../utils/brand-colors.js': { BrandColors: BrandColors },
+    '@/utils/api.js': apiStubs,
+    '@/config.js': { config: { API_BASE_URL: 'http://127.0.0.1:9082' } },
+    '../../components/share-mixin.js': { shareMixin: { data: function () { return {} }, methods: { setShareInfo: jest.fn() } } },
+    '@/components/ContentSharePoster.vue': {},
+    '@/components/RelatedContent.vue': {},
+    '@/components/mp-html/mp-html.vue': {},
+    '@/utils/fontScale.js': { getFontScale: function () { return 1 } }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__articleDetailVideoStubs
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C1:isVideoOnlyContent 判定(仅一条视频、无实质文本/图片/其他媒体/链接,容忍编辑器尾部空段)
+// ---------------------------------------------------------------------------
+
+describe('契约C1 article-detail.vue:isVideoOnlyContent 判定', function () {
+  test('C1.1 仅单视频 src → true', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<video src="http://x/a.mp4"></video>')).toBe(true)
+  })
+
+  test('C1.2 单视频 + 尾部空段(<p><br></p>)→ true(容忍编辑器尾部空段)', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<p><video src="http://x/a.mp4"></video></p><p><br></p>')).toBe(true)
+  })
+
+  test('C1.3 单 video 内嵌 source → true', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<video src="http://x/a.mp4"><source src="http://x/b.mp4"></video>')).toBe(true)
+  })
+
+  test('C1.4 两条 video → false', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<video src="http://x/a.mp4"></video><video src="http://x/b.mp4"></video>')).toBe(false)
+  })
+
+  test('C1.5 一条 video + 正文文本 → false', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<video src="http://x/a.mp4"></video><p>正文文字</p>')).toBe(false)
+  })
+
+  test('C1.6 一条 video + 图片 → false', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<video src="http://x/a.mp4"></video><img src="http://x/i.png">')).toBe(false)
+  })
+
+  test('C1.7 空值 / 非字符串 → false', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('')).toBe(false)
+    expect(vm.isVideoOnlyContent(null)).toBe(false)
+    expect(vm.isVideoOnlyContent(undefined)).toBe(false)
+    expect(vm.isVideoOnlyContent(123)).toBe(false)
+  })
+
+  test('C1.8 纯文本段落(无视频)→ false', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.isVideoOnlyContent('<p>纯文本</p>')).toBe(false)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C2:extractVideoSrc(从唯一 video 解析出播放地址)
+// ---------------------------------------------------------------------------
+
+describe('契约C2 article-detail.vue:extractVideoSrc 解析', function () {
+  test('C2.1 video 自带 src → 返回 src', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.extractVideoSrc('<video src="http://x/a.mp4"></video>')).toBe('http://x/a.mp4')
+  })
+
+  test('C2.2 video 内嵌 source src → 返回 source src', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.extractVideoSrc('<video><source src="http://x/b.mp4"></video>')).toBe('http://x/b.mp4')
+  })
+
+  test('C2.3 video 仅 poster 无 src → 返回空串', function () {
+    var vm = instantiate(getComponent())
+    expect(vm.extractVideoSrc('<video poster="p.png"></video>')).toBe('')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C3:行为(loadDetail 接入 + onSingleVideoReady 全屏守卫)
+// ---------------------------------------------------------------------------
+
+describe('契约C3 article-detail.vue:单视频默认全屏行为', function () {
+  test('C3.1 单视频文章 loadDetail 后启用 singleVideoSrc,模板含 video 与 mp-html', async function () {
+    apiStubs.getArticleDetail.mockResolvedValue({ code: 200, message: 'ok', data: { id: 1, title: 'T', coverImage: '', content: '<video src="http://x/a.mp4"></video>', publishedAt: '2026-01-01T00:00:00', viewCount: 0, readTime: 3 } })
+    var vm = instantiate(getComponent())
+    await vm.loadDetail(1)
+    expect(vm.singleVideoSrc).toBe('http://x/a.mp4')
+    var template = loadPage().template
+    expect(template).toMatch(/id="article-single-video"/)
+    expect(template).toMatch(/mp-html/)
+  })
+
+  test('C3.2 非单视频文章(正文+video)loadDetail 后 singleVideoSrc 为空(未启用)', async function () {
+    apiStubs.getArticleDetail.mockResolvedValue({ code: 200, message: 'ok', data: { id: 1, title: 'T', coverImage: '', content: '<p>正文</p><video src="http://x/a.mp4"></video>', publishedAt: '2026-01-01T00:00:00', viewCount: 0, readTime: 3 } })
+    var vm = instantiate(getComponent())
+    await vm.loadDetail(1)
+    expect(vm.singleVideoSrc).toBe('')
+  })
+
+  test('C3.3 onSingleVideoReady 首次进全屏一次,再次调用不重复(守卫)', function () {
+    var vm = instantiate(getComponent())
+    vm.singleVideoSrc = 'http://x/a.mp4'
+    vm.onSingleVideoReady()
+    expect(global.uni.createVideoContext).toHaveBeenCalledTimes(1)
+    expect(global.uni.createVideoContext).toHaveBeenCalledWith('article-single-video', vm)
+    var ctx = global.uni.createVideoContext.mock.results[0].value
+    expect(ctx.requestFullScreen).toHaveBeenCalledTimes(1)
+    vm.onSingleVideoReady()
+    expect(global.uni.createVideoContext).toHaveBeenCalledTimes(1)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C4:模板结构(video-only 用 video 全屏,否则 mp-html 富文本)
+// ---------------------------------------------------------------------------
+
+describe('契约C4 article-detail.vue:模板结构', function () {
+  test('模板含 v-if="singleVideoSrc"、article-single-video video 节点', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/v-if="singleVideoSrc"/)
+    expect(template).toMatch(/id="article-single-video"/)
+  })
+
+  test('模板 video 绑定 play / loadedmetadata 触发 onSingleVideoReady', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/@play="onSingleVideoReady"/)
+    expect(template).toMatch(/@loadedmetadata="onSingleVideoReady"/)
+  })
+
+  test('模板非单视频回退 mp-html v-else 并绑定 article.content', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/<mp-html v-else/)
+    expect(template).toMatch(/:content="article.content"/)
+  })
+})

+ 368 - 0
cfc-frontend/__tests__/pages/article-center/articleSearch.contract.test.js

@@ -0,0 +1,368 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——能力键 content.article.search(前端部分 C4-C6)
+ *
+ * 溯源:
+ *   requirement: docs/需求分析/2026-11-14-小程序知识分享页搜索功能需求变更.md
+ *                (ARTICLE-SEARCH-2026-11-14-V1,契约 C4 触发语义 / C5 空态区分 / C6 标签互斥重置)
+ *   design:      docs/design/2026-11-14-article-center-search-design.md
+ *                (D3 前端交互完善 + D3a 输入防抖与搜索历史,交互参考 pages/shop/search/search.vue)
+ *   契约布局:___tests__/api/api.test.js(C4 请求体 keyword 透传断言)+ 本文件(页面方法/空态/互斥)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 无 vue-jest/jsdom 组件环境 —— 沿用「读取真实 SFC 源码 → 桩化 import → 求值
+ *   <script> 拿真实 export default → 驱动 data()/methods/computed 做行为断言,模板做结构断言」,
+ *   参考 __tests__/pages/article-center/articleTagFilter.contract.test.js。
+ *   本文件不修改 pages/、utils/ 任何业务代码。
+ *
+ * 小程序约束(AGENTS.md):禁可选链 ?.、禁 CSS Grid、禁 :key 表达式、禁 new Date(string)。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { BrandColors } from '@/utils/brand-colors.js'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/article-center/index.vue')
+
+/** 把 ES import 语句替换为从 globalThis.__articleCenterSearchStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__articleCenterSearchStubs || {})[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadPage() {
+  var src = fs.readFileSync(PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 article-center/index.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__articleCenterSearchStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods/computed 构造可驱动上下文(模拟 Vue 合并实例) */
+function instantiate(component) {
+  var vm = {}
+  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] })
+  var computed = component.computed || {}
+  Object.keys(computed).forEach(function (k) {
+    Object.defineProperty(vm, k, { get: computed[k], enumerable: true, configurable: true })
+  })
+  return vm
+}
+
+/** 每次调用时重新加载真实 SFC(读取当时的 __articleCenterSearchStubs),避免闭包捕获旧桩 */
+function getComponent() {
+  return loadPage().component
+}
+
+/** 刷新微任务队列:让 fire-and-forget 的 async 方法(loadArticles 等)结算完成 */
+function flushPromises() {
+  return new Promise(function (resolve) { setTimeout(resolve, 0) })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.request.mockReset()
+  stubs = {
+    getArticleList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { records: [], total: 0 } }) }),
+    getArticleTags: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getFeaturedArticles: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) })
+  }
+  globalThis.__articleCenterSearchStubs = {
+    '../../utils/brand-colors.js': { BrandColors: BrandColors },
+    '@/utils/api.js': {
+      getArticleList: stubs.getArticleList,
+      getArticleTags: stubs.getArticleTags,
+      getFeaturedArticles: stubs.getFeaturedArticles
+    },
+    '@/config.js': { config: { API_BASE_URL: 'http://127.0.0.1:9082' } },
+    '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return {} } } }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__articleCenterSearchStubs
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C4:触发语义 —— onSearch 重置分页/清列表/noMore=false,请求体携带 trim keyword;
+// 空 keyword(取消)还原全量;400ms 防抖即时搜索;搜索历史本地存储(上限 10、去重、可清空)
+// ---------------------------------------------------------------------------
+
+describe('契约C4 index.vue:onSearch 触发语义 + 防抖 + 搜索历史', function () {
+  test('onSearch 同步重置 page=1/articles=[]/noMore=false,请求体携带 trim 后的 keyword', async function () {
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 1, title: '睡眠指南' }], total: 1 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.page = 5
+    vm.articles = [{ id: 999 }]
+    vm.noMore = true
+    vm.searchKeyword = '  睡眠  '
+    vm.onSearch()
+    // 提交瞬间即重置(契约 C4:page=1、列表清空、noMore=false)
+    expect(vm.page).toBe(1)
+    expect(vm.articles).toEqual([])
+    expect(vm.noMore).toBe(false)
+    await flushPromises()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.keyword).toBe('睡眠')
+    expect(vm.articles).toEqual([{ id: 1, title: '睡眠指南' }])
+  })
+
+  test('onSearch 空 keyword(取消语义)→ 还原全量,请求体不带 keyword 且历史不落盘', async function () {
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 2, title: 'x' }], total: 1 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.searchKeyword = '   '
+    vm.onSearch()
+    await flushPromises()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.keyword).toBeUndefined()
+    expect(params.tag).toBeUndefined()
+    expect(vm.articles).toEqual([{ id: 2, title: 'x' }])
+    expect(global.uni._storage['article_search_history']).toBeUndefined()
+  })
+
+  test('模板:搜索框保留 v-model/@confirm 并接入 @input="onSearchInput" 防抖', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/v-model="searchKeyword"/)
+    expect(template).toMatch(/@confirm="onSearch"/)
+    expect(template).toMatch(/@input="onSearchInput"/)
+  })
+
+  test('onSearchInput 400ms 防抖即时搜索:只发一次且携带当前 keyword', function () {
+    jest.useFakeTimers()
+    try {
+      stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
+      var vm = instantiate(getComponent())
+      vm.currentChildId = null
+      vm.searchKeyword = '睡眠'
+      vm.onSearchInput({ detail: { value: '睡眠' } })
+      expect(stubs.getArticleList).not.toHaveBeenCalled()
+      jest.advanceTimersByTime(399)
+      expect(stubs.getArticleList).not.toHaveBeenCalled()
+      jest.advanceTimersByTime(1)
+      expect(stubs.getArticleList).toHaveBeenCalledTimes(1)
+      expect(stubs.getArticleList.mock.calls[0][0].keyword).toBe('睡眠')
+    } finally {
+      jest.useRealTimers()
+    }
+  })
+
+  test('onSearchInput 连续输入只在防抖窗口结束后请求一次并取最新词', function () {
+    jest.useFakeTimers()
+    try {
+      var vm = instantiate(getComponent())
+      vm.currentChildId = null
+      vm.onSearchInput({ detail: { value: '睡' } })
+      vm.onSearchInput({ detail: { value: '睡眠' } })
+      vm.onSearchInput({ detail: { value: ' 睡眠法 ' } })
+      expect(stubs.getArticleList).not.toHaveBeenCalled()
+      jest.advanceTimersByTime(400)
+      expect(stubs.getArticleList).toHaveBeenCalledTimes(1)
+      expect(stubs.getArticleList.mock.calls[0][0].keyword).toBe('睡眠法')
+    } finally {
+      jest.useRealTimers()
+    }
+  })
+
+  test('onSearch 保存 trim 关键词到本地历史(article_search_history):去重、提到最前', function () {
+    var vm = instantiate(getComponent())
+    vm.searchKeyword = '睡眠'
+    vm.onSearch()
+    expect(vm.searchHistory).toEqual(['睡眠'])
+    expect(JSON.parse(global.uni._storage['article_search_history'])).toEqual(['睡眠'])
+
+    vm.searchKeyword = '成长'
+    vm.onSearch()
+    expect(vm.searchHistory).toEqual(['成长', '睡眠'])
+
+    // 去重:再次搜索相同关键词提到最前
+    vm.searchKeyword = '睡眠'
+    vm.onSearch()
+    expect(vm.searchHistory).toEqual(['睡眠', '成长'])
+    expect(vm.searchHistory.length).toBe(2)
+  })
+
+  test('搜索历史上限 10 条,超出丢弃最旧', function () {
+    var vm = instantiate(getComponent())
+    var seed = []
+    for (var i = 1; i <= 10; i++) seed.push('k' + i)
+    vm.searchHistory = seed.slice()
+    vm.searchKeyword = 'new'
+    vm.onSearch()
+    expect(vm.searchHistory.length).toBe(10)
+    expect(vm.searchHistory[0]).toBe('new')
+    expect(vm.searchHistory[9]).toBe('k9')
+    expect(vm.searchHistory.indexOf('k10')).toBe(-1)
+  })
+
+  test('onLoad 读取历史;非法 JSON 容错为空数组', async function () {
+    global.uni._storage['article_search_history'] = JSON.stringify(['睡眠', '成长'])
+    var vm = instantiate(getComponent())
+    var opts = getComponent()
+    await opts.onLoad.call(vm, {})
+    await flushPromises()
+    expect(vm.searchHistory).toEqual(['睡眠', '成长'])
+
+    global.uni._storage['article_search_history'] = '{bad json'
+    var vm2 = instantiate(getComponent())
+    await opts.onLoad.call(vm2, {})
+    expect(vm2.searchHistory).toEqual([])
+  })
+
+  test('clearSearchHistory 清空列表并删除本地存储', function () {
+    var vm = instantiate(getComponent())
+    vm.searchHistory = ['睡眠']
+    global.uni._storage['article_search_history'] = JSON.stringify(['睡眠'])
+    vm.clearSearchHistory()
+    expect(vm.searchHistory).toEqual([])
+    expect(global.uni._storage['article_search_history']).toBeUndefined()
+  })
+
+  test('模板:搜索历史条 v-for 渲染 searchHistory,点击历史项回填关键词', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/v-for="\(item, idx\) in searchHistory"/)
+    expect(template).toMatch(/searchHistory.length/)
+    expect(template).toMatch(/clickSearchHistory\(item\)/)
+    expect(template).toMatch(/clearSearchHistory/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C5:空态区分 —— noMore && articles.length === 0 时,
+// searchKeyword 非空 →「未找到相关文章」,否则 →「暂无文章」
+// ---------------------------------------------------------------------------
+
+describe('契约C5 index.vue:搜索空态与「暂无文章」区分', function () {
+  test('模板:空态门禁 noMore && articles.length === 0,文案按 isSearchEmpty 区分', function () {
+    var template = loadPage().template
+    expect(template).toMatch(/v-else-if="noMore && articles\.length === 0"/)
+    expect(template).toMatch(/未找到相关文章/)
+    expect(template).toMatch(/暂无文章/)
+    expect(template).toMatch(/isSearchEmpty/)
+  })
+
+  test('搜索无命中(records=[] total=0)→ articles=[] 且 noMore=true,isSearchEmpty=true', async function () {
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.searchKeyword = '睡眠'
+    vm.onSearch()
+    await flushPromises()
+    expect(vm.articles).toEqual([])
+    expect(vm.noMore).toBe(true)
+    expect(vm.isSearchEmpty).toBe(true)
+  })
+
+  test('非搜索态空列表(无 keyword)→ isSearchEmpty=false(走「暂无文章」)', async function () {
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.searchKeyword = ''
+    vm.onSearch()
+    await flushPromises()
+    expect(vm.articles).toEqual([])
+    expect(vm.noMore).toBe(true)
+    expect(vm.isSearchEmpty).toBe(false)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 C6:互斥重置 —— 进入搜索态清当前 Tab 回全量;切换 Tab 清搜索关键词与焦点
+// ---------------------------------------------------------------------------
+
+describe('契约C6 index.vue:搜索与标签筛选互斥重置', function () {
+  test('onTabChange 清空 searchKeyword/searchFocused,请求体带 tag 且不带 keyword', async function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.searchKeyword = '睡眠'
+    vm.searchFocused = true
+    vm.onTabChange('减脂')
+    expect(vm.currentTab).toBe('减脂')
+    expect(vm.searchKeyword).toBe('')
+    expect(vm.searchFocused).toBe(false)
+    await flushPromises()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.tag).toBe('减脂')
+    expect(params.keyword).toBeUndefined()
+  })
+
+  test('focusSearch 进入搜索态:清当前 Tab 回全量并重拉全量列表(无 tag)', async function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.currentTab = '减脂'
+    vm.focusSearch()
+    expect(vm.searchFocused).toBe(true)
+    expect(vm.currentTab).toBe('')
+    expect(vm.page).toBe(1)
+    expect(vm.articles).toEqual([])
+    await flushPromises()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.tag).toBeUndefined()
+  })
+
+  test('focusSearch 已在全量时不重复重拉列表', function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.currentTab = ''
+    stubs.getArticleList.mockClear()
+    vm.focusSearch()
+    expect(vm.searchFocused).toBe(true)
+    expect(vm.currentTab).toBe('')
+    expect(stubs.getArticleList).not.toHaveBeenCalled()
+  })
+
+  test('标签态发起搜索(onSearch)→ currentTab 清空回全量,请求体无 tag 只带 keyword', async function () {
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 7, title: '睡眠' }], total: 1 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.currentTab = '减脂'
+    vm.searchKeyword = '睡眠'
+    vm.onSearch()
+    expect(vm.currentTab).toBe('')
+    await flushPromises()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.keyword).toBe('睡眠')
+    expect(params.tag).toBeUndefined()
+  })
+})

+ 329 - 0
cfc-frontend/__tests__/pages/article-center/articleTagFilter.contract.test.js

@@ -0,0 +1,329 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 content.article.listByTag
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-10-article-tag-filter-design.md
+ *                §1 需求概述 —— 分类 Tab 从五维(身/心/智/富/行)改为按文章标签(articles.tags)动态筛选;
+ *                顶部关键词搜索保留;卡片五维浮标保留(信息展示,非分类筛选)
+ *   design:      §3 方案设计(实现已合入 origin/cfclub commit 6e9a511e2)
+ *                - ArticleController /list 增 tag 参数 + 新增 POST /tags 返回 Top20 标签
+ *                - ArticleService.getPublicList(10 参,位置4=tag,parseCommaOrJsonTags 内存过滤) + listTopTags
+ *                - 前端 cfc-frontend/pages/article-center/index.vue:tabList 动态化(全部+各标签)
+ *                  + loadArticles params.dimensionCode→tag + loadTags()(失败静默保留全部)
+ *                - api.js 新增 getArticleTags
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
+ *   未安装 vue-jest/jsdom 组件环境 —— 既有约定为「读取真实 SFC 源码 → 桩化 import → 求值 <script> 拿
+ *   真实 export default → 驱动 data()/methods 做行为断言,模板做结构契约断言」,
+ *   参考 __tests__/family-join/join-form.required-info.test.js。
+ *   本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { BrandColors } from '@/utils/brand-colors.js'
+import {
+  getArticleList as apiGetArticleList,
+  getArticleTags as apiGetArticleTags,
+  clearApiDedup
+} from '@/utils/api'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/article-center/index.vue')
+const API_PATH = path.join(__dirname, '../../../utils/api.js')
+const COLORS_PATH = path.join(__dirname, '../../../utils/brand-colors.js')
+
+/** 把 ES import 语句替换为从 globalThis.__articleCenterStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__articleCenterStubs || {})[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadPage() {
+  var src = fs.readFileSync(PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 article-center/index.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__articleCenterStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 读取 utils/api.js 源码文本(结构契约断言) */
+function readApiSource() {
+  return fs.readFileSync(API_PATH, 'utf8')
+}
+
+/**
+ * 每次调用时重新加载真实 SFC(读取当时的 __articleCenterStubs),避免 beforeAll 先于
+ * beforeEach 执行导致组件闭包捕获到未注入的桩变量(data() 引用 BrandColors.* 会崩)。
+ */
+function getComponent() {
+  return loadPage().component
+}
+
+/** 刷新微任务队列:让 onLoad 内 fire-and-forget 的 async 方法(loadTags/loadArticles)结算完成 */
+function flushPromises() {
+  return new Promise(function (resolve) { setTimeout(resolve, 0) })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.request.mockReset()
+  clearApiDedup()
+  stubs = {
+    getArticleList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { records: [], total: 0 } }) }),
+    getArticleTags: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getFeaturedArticles: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) })
+  }
+  globalThis.__articleCenterStubs = {
+    '../../utils/brand-colors.js': { BrandColors: BrandColors },
+    '@/utils/api.js': {
+      getArticleList: stubs.getArticleList,
+      getArticleTags: stubs.getArticleTags,
+      getFeaturedArticles: stubs.getFeaturedArticles
+    },
+    '@/config.js': { config: { API_BASE_URL: 'http://127.0.0.1:9082' } },
+    '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return {} } } }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__articleCenterStubs
+})
+
+// ---------------------------------------------------------------------------
+// 契约 1:api.js 提供 getArticleTags(POST /api/articles/tags)+ getArticleList(POST /api/articles/list)
+// ---------------------------------------------------------------------------
+
+describe('契约1 api.js:getArticleTags / getArticleList 行为', function () {
+  test('getArticleTags 已导出且调用 POST /api/articles/tags(data || {})', async function () {
+    expect(typeof apiGetArticleTags).toBe('function')
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ statusCode: 200, data: { code: 200, message: 'ok', data: ['减脂', '睡眠'] } })
+      return { abort: function () {} }
+    })
+    var res = await apiGetArticleTags()
+    expect(global.uni.request).toHaveBeenCalled()
+    var req = global.uni.request.mock.calls[0][0]
+    expect(req.url).toMatch(/\/api\/articles\/tags$/)
+    expect(req.method).toBe('POST')
+    expect(res.code).toBe(200)
+    expect(res.data).toEqual(['减脂', '睡眠'])
+    // 无参调用也能发出(页面 loadTags() 调 getArticleTags() 不带参数)
+    expect(req.data || {}).toEqual({})
+  })
+
+  test('getArticleList 调用 POST /api/articles/list 且原样透传 tag 参数(列表按标签筛选的通道)', async function () {
+    expect(typeof apiGetArticleList).toBe('function')
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ statusCode: 200, data: { code: 200, message: 'ok', data: { records: [{ id: 1, title: 'x', tags: '["减脂"]' }], total: 1 } } })
+      return { abort: function () {} }
+    })
+    var res = await apiGetArticleList({ page: 1, size: 10, tag: '减脂' })
+    var req = global.uni.request.mock.calls[0][0]
+    expect(req.url).toMatch(/\/api\/articles\/list$/)
+    expect(req.method).toBe('POST')
+    expect(req.data.tag).toBe('减脂')
+    expect(req.data.page).toBe(1)
+    expect(res.data.records[0].id).toBe(1)
+  })
+
+  test('api.js 源码不含五维 dimensionCode 作为列表筛参(筛选参数应为 tag)', function () {
+    var src = readApiSource()
+    // getArticleList 永远 POST /api/articles/list,且其请求体直接透传调用方参数(tag 由页面注入)
+    expect(src).toMatch(/getArticleList[\s\S]*?\/api\/articles\/list/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 2:index.vue tabList 动态化(不再硬编码五维,默认【全部】,loadTags 成功后再拼标签)
+// ---------------------------------------------------------------------------
+
+describe('契约2 index.vue:tabList 按标签动态化', function () {
+  test('data().tabList 默认仅为「全部」(无五维静态 Tab)', function () {
+    var vm = instantiate(getComponent())
+    expect(Array.isArray(vm.tabList)).toBe(true)
+    expect(vm.tabList.length).toBe(1)
+    expect(vm.tabList[0]).toEqual({ code: '', name: '全部', color: BrandColors.primary })
+    expect(vm.currentTab).toBe('')
+  })
+
+  test('data() 中不存在以 body/mind/wisdom/action/wealth 为 code 的静态 tab 定义', function () {
+    var src = fs.readFileSync(PAGE_PATH, 'utf8')
+    // 兼容 parseDimensions 中合法出现的五维映射 key:仅断言「tabList 静态数组内不得以五维 code 开头」
+    var staticTabDef = src.match(/tabList\s*:\s*\[\s*\{[^}]*code\s*:\s*['"](body|mind|wisdom|action|wealth)['"]/)
+    expect(staticTabDef).toBeNull()
+  })
+
+  test('loadTags() 成功后 tabList = [全部, ...各标签],标签映射为 { code: tag, name: tag }', async function () {
+    stubs.getArticleTags.mockResolvedValue({ code: 200, message: 'ok', data: ['减脂', '睡眠'] })
+    var vm = instantiate(getComponent())
+    await vm.loadTags()
+    expect(stubs.getArticleTags).toHaveBeenCalled()
+    expect(vm.tabList.length).toBe(3)
+    expect(vm.tabList[0].name).toBe('全部')
+    expect(vm.tabList[1]).toEqual({ code: '减脂', name: '减脂', color: BrandColors.primary })
+    expect(vm.tabList[2]).toEqual({ code: '睡眠', name: '睡眠', color: BrandColors.primary })
+  })
+
+  test('loadTags() 失败(reject)时静默保留【全部】,页面仍可浏览', async function () {
+    stubs.getArticleTags.mockRejectedValue(new Error('network'))
+    var vm = instantiate(getComponent())
+    await expect(vm.loadTags()).resolves.toBeUndefined()
+    expect(vm.tabList.length).toBe(1)
+    expect(vm.tabList[0].name).toBe('全部')
+  })
+
+  test('loadTags() 返回空数组时同样保留【全部】(Top20 为空场景)', async function () {
+    stubs.getArticleTags.mockResolvedValue({ code: 200, message: 'ok', data: [] })
+    var vm = instantiate(getComponent())
+    await vm.loadTags()
+    expect(vm.tabList.length).toBe(1)
+    expect(vm.tabList[0].name).toBe('全部')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 3:loadArticles 以 params.tag(而非 dimensionCode)做筛选
+// ---------------------------------------------------------------------------
+
+describe('契约3 index.vue:列表按 currentTab 标签筛选', function () {
+  test('currentTab 有值时请求体带 params.tag(即为当前标签名)', async function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.currentTab = '减脂'
+    vm.searchKeyword = ''
+    await vm.loadArticles()
+    expect(stubs.getArticleList).toHaveBeenCalled()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.tag).toBe('减脂')
+    expect(params.dimensionCode).toBeUndefined()
+  })
+
+  test('currentTab 为空(全部)时不带 tag 参数', async function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.currentTab = ''
+    vm.searchKeyword = ''
+    await vm.loadArticles()
+    var params = stubs.getArticleList.mock.calls[0][0]
+    expect(params.tag).toBeUndefined()
+    expect(params.dimensionCode).toBeUndefined()
+  })
+
+  test('onTabChange(code) 切换 Tab:更新 currentTab、清空搜索、重置分页并重新拉取', async function () {
+    var vm = instantiate(getComponent())
+    vm.currentChildId = null
+    vm.page = 3
+    vm.articles = [{ id: 999 }]
+    vm.searchKeyword = '旧关键词'
+    vm.onTabChange('减脂')
+    expect(vm.currentTab).toBe('减脂')
+    expect(vm.searchKeyword).toBe('')
+    expect(vm.page).toBe(1)
+    expect(vm.articles).toEqual([])
+    expect(stubs.getArticleList).toHaveBeenCalled()
+    expect(stubs.getArticleList.mock.calls[0][0].tag).toBe('减脂')
+  })
+
+  test('onLoad 首次进入即 loadTags() + loadArticles(),标签与列表双双就绪', async function () {
+    stubs.getArticleTags.mockResolvedValue({ code: 200, message: 'ok', data: ['睡眠'] })
+    stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 1 }], total: 1 } })
+    var vm = instantiate(getComponent())
+    vm.currentChildId = 5
+    var opts = getComponent()
+    await opts.onLoad.call(vm, {})
+    await flushPromises()
+    expect(stubs.getArticleTags).toHaveBeenCalled()
+    expect(stubs.getArticleList).toHaveBeenCalled()
+    expect(vm.tabList.length).toBe(2)
+    expect(vm.articles.length).toBe(1)
+  })
+
+  test('旧入口传 dimension(新语义下降级为标签命中失败)仍设置 currentTab 不崩溃', async function () {
+    var vm = instantiate(getComponent())
+    var opts = getComponent()
+    await opts.onLoad.call(vm, { dimension: 'body' })
+    await flushPromises()
+    expect(vm.currentTab).toBe('body')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 契约 4:模板结构——Tab 以 v-for 动态渲染,点击驱动 onTabChange;搜索栏保留
+// ---------------------------------------------------------------------------
+
+describe('契约4 index.vue:模板结构与关键词搜索保留', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach 执行:仅做模板结构断言,无需桩函数,置空即可(loadPage 对桩做可选访问)
+    globalThis.__articleCenterStubs = {}
+    template = loadPage().template
+  })
+
+  test('Tab 区域以 v-for="tab in tabList" 动态渲染,key 绑定 tab.code,点击 onTabChange', function () {
+    expect(template).toMatch(/v-for="tab in tabList"/)
+    expect(template).toMatch(/:key="tab\.code"/)
+    expect(template).toMatch(/@click="onTabChange\(tab\.code\)"/)
+  })
+
+  test('当前选中项以 currentTab === tab.code 高亮', function () {
+    expect(template).toMatch(/currentTab === tab\.code/)
+  })
+
+  test('顶部关键词搜索保留(input + v-model searchKeyword + onSearch)', function () {
+    expect(template).toMatch(/v-model="searchKeyword"/)
+    expect(template).toMatch(/onSearch/)
+  })
+
+  test('卡片列表渲染每篇文章(文章标签展示为信息性浮标,非分类入口)', function () {
+    expect(template).toMatch(/v-for=.*item.*in articles/)
+  })
+})

+ 291 - 0
cfc-frontend/__tests__/pages/diet/recommendation.pagination.test.js

@@ -0,0 +1,291 @@
+/**
+ * 契约级单测 —— 能力键 diet.recommendation.pagination
+ *
+ * BugFix:食材列表「下滑翻页失效」。
+ *
+ * 溯源:用户直接报障;根因定位见 team-lead 派单与本次回报 ROOT_CAUSE。
+ *   既有 uiRework.test.js REQ4 已断言「模板绑定 @scrolltolower="loadMore"」与
+ *   「loadMore() 令 visibleCount 20→40→60」并全绿,说明 JS / 模板层完好;
+ *   唯一缺失且失效的是「scroll-view 是否拿到确定高度」这一布局前提 ——
+ *   uni-app 中 scroll-y 必须拿到确定高度才会形成内部滚动视口并派发触底事件。
+ *   本文件补上这段 CSS 契约断言,并把「触底 → visibleCount 递增 → 列表增长」
+ *   串成一条端到端回归链,防止只改样式不改行为或后续又把高度改回 min-height。
+ *
+ * 约定(沿用 uiRework / viewKeyAndDelete):加载真实 recommendation.vue 的
+ * <script>/<template>/<style>,import 替换为注入桩后求值,驱动真实
+ * data()/computed/methods 做行为级断言;不挂载 .vue、不修改业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const RECOMMENDATION_PATH = path.join(__dirname, '../../../pages/diet/recommendation.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.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template, style } */
+function loadRecommendation() {
+  var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  var styleMatch = src.match(/<style[^>]*>([\s\S]*?)<\/style>/)
+  if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1])
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return {
+    component: mod.exports,
+    template: tmplMatch ? tmplMatch[1] : '',
+    style: styleMatch ? styleMatch[1] : ''
+  }
+}
+
+/** 合并 data()/computed(getter)/methods 到 vm 实例(模拟 Vue Options 合并) */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  if (component.computed) {
+    Object.keys(component.computed).forEach(function (k) {
+      Object.defineProperty(vm, k, { get: component.computed[k].bind(vm), enumerable: true, configurable: true })
+    })
+  }
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+/** 取出某个 CSS 规则的声明体(去注释,避免注释里的关键字干扰断言) */
+function ruleBody(style, selector) {
+  var clean = style.replace(/\/\*[\s\S]*?\*\//g, '')
+  var re = new RegExp('\\' + selector + '\\s*\\{([^}]*)\\}')
+  var m = clean.match(re)
+  return m ? m[1] : ''
+}
+
+/** 构造 n 条全为「适合」的食材,保证 filteredFoods 长度可控(默认 filterType='suitable') */
+function buildFoods(n) {
+  var out = []
+  for (var i = 1; i <= n; i++) {
+    out.push({ id: i, name: '食材' + i, category: '蔬菜', score: i })
+  }
+  return out
+}
+
+var stubs
+
+beforeEach(function () {
+  jest.useFakeTimers()
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  global.uni.request.mockReset()
+
+  stubs = {
+    getDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 200, data: null }) }),
+    generateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    updateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    completeDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    regenerateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    memberIdOf: jest.fn(function (m) { return m && (m.familyMemberId != null ? m.familyMemberId : (m.id != null ? m.id : null)) }),
+    config: { default: { API_BASE_URL: '/api' } },
+    MemberSelector: { default: {} },
+    fontScaleMixin: { default: { data: function () { return { fontScale: 1 } }, onShow: function () {} } }
+  }
+  globalThis.__recommendationStubs = {
+    '@/utils/api.js': {
+      getDietRecommendation: stubs.getDietRecommendation,
+      generateDietRecommendation: stubs.generateDietRecommendation,
+      updateDietRecommendation: stubs.updateDietRecommendation,
+      completeDietRecommendation: stubs.completeDietRecommendation,
+      regenerateDietRecommendation: stubs.regenerateDietRecommendation
+    },
+    '@/config.js': stubs.config,
+    '@/components/MemberSelector.vue': stubs.MemberSelector,
+    '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
+    '@/mixins/font-scale.js': stubs.fontScaleMixin
+  }
+})
+
+afterEach(function () {
+  jest.clearAllTimers()
+  jest.useRealTimers()
+  delete globalThis.__recommendationStubs
+})
+
+// ---------------------------------------------------------------------------
+// 1. 根因回归:scroll-view 必须拿到确定高度(否则 @scrolltolower 永不派发)
+// ---------------------------------------------------------------------------
+
+describe('根因回归:scroll-view 确定高度契约', function () {
+  it('页面根使用确定高度 height:100vh,不再仅由 min-height 撑开', function () {
+    var style = loadRecommendation().style
+    var pageRule = ruleBody(style, '.recommendation-page')
+    expect(pageRule).toMatch(/\bheight:\s*100vh/)
+    expect(pageRule).not.toMatch(/\bmin-height:\s*100vh/)
+  })
+
+  it('.content 保留 flex:1 原有布局,并补 height:0 / min-height:0 得到确定计算高度', function () {
+    var style = loadRecommendation().style
+    var contentRule = ruleBody(style, '.content')
+    expect(contentRule).toMatch(/flex:\s*1/)
+    expect(contentRule).toMatch(/\bheight:\s*0/)
+    expect(contentRule).toMatch(/min-height:\s*0/)
+    expect(contentRule).toMatch(/overflow:\s*hidden/)
+  })
+
+  it('修复未引入 CSS Grid(小程序禁用)', function () {
+    var style = loadRecommendation().style
+    expect(style).not.toMatch(/display:\s*grid/)
+    expect(style).not.toMatch(/grid-template/)
+  })
+
+  it('外层 scroll-view 仍绑定 @scrolltolower="loadMore" 且开启 scroll-y', function () {
+    var template = loadRecommendation().template
+    expect(template).toContain('@scrolltolower="loadMore"')
+    expect(template).toMatch(/<scroll-view[^>]*\sscroll-y/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 2. 端到端链路:触底 → loadMore → visibleCount 递增 → pagedFoods 增长
+// ---------------------------------------------------------------------------
+
+describe('下滑触底 → 追加食材(visibleCount / pagedFoods)', function () {
+  it('首批 20 条;模拟触底一次后 visibleCount=40 且列表增长到 40 条', function () {
+    var loaded = loadRecommendation()
+    var vm = instantiate(loaded.component)
+    vm.currentView = 'personal'
+    vm.allFoods = buildFoods(55)
+    vm.visibleCount = 20
+
+    expect(vm.filteredFoods.length).toBe(55)
+    expect(vm.pagedFoods.length).toBe(20)
+
+    vm.loadMore()
+
+    expect(vm.visibleCount).toBe(40)
+    expect(vm.pagedFoods.length).toBe(40)
+  })
+
+  it('连续触底按 20 递增,到末尾自动停止且列表不超全量', function () {
+    var vm = instantiate(loadRecommendation().component)
+    vm.currentView = 'personal'
+    vm.allFoods = buildFoods(55)
+    vm.visibleCount = 20
+
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(40)
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(60)
+    expect(vm.pagedFoods.length).toBe(55)
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(60)
+    expect(vm.pagedFoods.length).toBe(55)
+  })
+
+  it('切 Tab / 分类 / 筛选 / 成员后分页重置为 20,可重新触底加载', function () {
+    var vm = instantiate(loadRecommendation().component)
+    vm.currentView = 'personal'
+    vm.allFoods = buildFoods(55)
+
+    vm.visibleCount = 60
+    vm.switchTab('suitable')
+    expect(vm.visibleCount).toBe(20)
+    expect(vm.pagedFoods.length).toBe(20)
+
+    vm.visibleCount = 60
+    vm.switchCategory('蔬菜')
+    expect(vm.visibleCount).toBe(20)
+
+    vm.visibleCount = 60
+    vm.setFilter('all')
+    expect(vm.visibleCount).toBe(20)
+
+    vm.visibleCount = 60
+    vm.switchMember({ familyMemberId: 7 })
+    expect(vm.visibleCount).toBe(20)
+
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(40)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 3. 排除其余疑点:onShow / refresher-triggered 不锁死列表状态
+// ---------------------------------------------------------------------------
+
+describe('排除疑点:onShow 与下拉刷新不重置/锁死分页', function () {
+  it('data().refreshing 初值为 false,不会常驻 true 锁住滚动', function () {
+    var loaded = loadRecommendation()
+    expect(loaded.component.data().refreshing).toBe(false)
+    var vm = instantiate(loaded.component)
+    expect(vm.refreshing).toBe(false)
+  })
+
+  it('onRefresh 500ms 后把 refreshing 复位为 false', function () {
+    var vm = instantiate(loadRecommendation().component)
+    vm.onRefresh()
+    expect(vm.refreshing).toBe(true)
+    jest.advanceTimersByTime(500)
+    expect(vm.refreshing).toBe(false)
+  })
+
+  it('onShow 只重载今日食谱,不重置 visibleCount / currentTab / filterType / allFoods', function () {
+    var loaded = loadRecommendation()
+    var vm = instantiate(loaded.component)
+    vm.currentView = 'personal'
+    vm.currentMemberId = null
+    vm.allFoods = buildFoods(55)
+    vm.visibleCount = 40
+    vm.currentTab = 'suitable'
+    vm.filterType = 'suitable'
+
+    loaded.component.onShow.call(vm)
+
+    expect(vm.visibleCount).toBe(40)
+    expect(vm.currentTab).toBe('suitable')
+    expect(vm.filterType).toBe('suitable')
+    expect(vm.allFoods.length).toBe(55)
+    expect(vm.pagedFoods.length).toBe(40)
+  })
+
+  it('食材区 v-if 在切出 recipe Tab 时正常渲染', function () {
+    var loaded = loadRecommendation()
+    var vm = instantiate(loaded.component)
+    expect(vm.currentTab).toBe('recipe')
+    expect(loaded.template).toContain('v-if="currentTab !== \'recipe\'"')
+    vm.switchTab('suitable')
+    expect(vm.currentTab).toBe('suitable')
+  })
+})

+ 328 - 0
cfc-frontend/__tests__/pages/diet/recommendation.participantSelect.test.js

@@ -0,0 +1,328 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 diet.recommendation.participantSelect
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-08-diet-recommendation-polish.md
+ *                §2 需求 7(共餐人选择:家庭总览先弹共餐人多选、个人/成员直传 currentMemberId)
+ *   design:      同文档 §2 需求 7
+ *                - 前端:cfc-frontend/pages/diet/recommendation.vue generateRecipe(L407-425),
+ *                  家庭总览(currentView==='family')点「生成食谱」→ 弹共餐人多选
+ *                  (候选=memberList,含 familyMemberId+nickname+isSelf,默认勾选全部),
+ *                  确认后调 generate 并传 participant_member_ids([familyMemberId,...] JSON 字符串);
+ *                  个人/成员(currentView==='personal')→ 不弹选择,传 participant_member_ids:[currentMemberId]
+ *                - api 透传:cfc-frontend/utils/api.js generateDietRecommendation(L3125)通用透传,无需改动
+ *                - 后端:DietRecommendationService.generateRecommendation(L67-140)应读
+ *                  request.get("participant_member_ids") 覆盖 queryParticipantIds 兜底;
+ *                  解析复用 parseMemberIds(L257-267)——本文件(前端契约)锚定「前端发送该字段」,
+ *                  后端覆盖行为由 GREEN 阶段后端侧验证
+ *
+ * 说明:
+ *   沿用 __tests__/pages/diet/recommendation.uiRework.test.js 约定:直接加载真实
+ *   recommendation.vue SFC 的 <script>(import 替换为注入桩后求值)拿到 data()/methods,
+ *   做行为级断言。当前实现未落地(generateRecipe 仅传 {date, meal_type},无 participant_member_ids),
+ *   预期全部 RED;GREEN 阶段在实现不修改本文件的前提下翻绿。
+ *   注:家庭总览「确认共餐人」的确认入口设计未限定方法名,本文件以 confirmParticipants 作为
+ *   GREEN 预期表面,并在断言中聚焦「载荷契约(participant_member_ids 内容)」,若 GREEN 采用
+ *   其他命名需与编排侧确认同步。
+ *   本文件不修改 pages/ / components/ / utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { generateDietRecommendation as apiGenerateDietRecommendation, clearApiDedup } from '@/utils/api'
+
+const RECOMMENDATION_PATH = path.join(__dirname, '../../../pages/diet/recommendation.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:把 ES import 替换成从 globalThis.__recommendationStubs 取桩的 var 声明
+// ---------------------------------------------------------------------------
+
+function stubImports(script, stubMap) {
+  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.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template } */
+function loadRecommendation() {
+  var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__recommendationStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 把 component 的 data()/computed()/methods 合并到 vm 实例(computed 定义为 getter) */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  if (component.computed) {
+    Object.keys(component.computed).forEach(function (k) {
+      Object.defineProperty(vm, k, { get: component.computed[k].bind(vm), enumerable: true, configurable: true })
+    })
+  }
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+/**
+ * 从 generate 载荷中提取共餐人 id 数组。
+ * 契约要点:participant_member_ids 存在即返回其内容(兼容 JSON 字符串 / 原生数组两种实现形态,
+ * 值统一规整为 number 数组),不存在/为空则返回与之对应的哨兵值,令断言干净失败(RED)。
+ */
+function participantIdsOf(payload) {
+  if (!payload || !Object.prototype.hasOwnProperty.call(payload, 'participant_member_ids')) return undefined
+  var v = payload.participant_member_ids
+  if (v === undefined || v === null || v === '') return []
+  var out
+  if (Array.isArray(v)) {
+    out = v
+  } else if (typeof v === 'string') {
+    try { out = JSON.parse(v) } catch (e) { return v }
+  } else if (typeof v === 'number') {
+    out = [v]
+  } else {
+    return v
+  }
+  return out.map(function (n) { return Number(n) })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  global.uni.request.mockReset()
+
+  stubs = {
+    generateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    getDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    completeDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    regenerateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    updateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    memberIdOf: jest.fn(function (m) { return m && (m.familyMemberId != null ? m.familyMemberId : (m.id != null ? m.id : null)) }),
+    config: { default: { API_BASE_URL: '/api' } },
+    MemberSelector: { default: {} },
+    fontScaleMixin: { default: { data: function () { return { fontScale: 1 } }, onShow: function () {} } }
+  }
+  globalThis.__recommendationStubs = {
+    '@/utils/api.js': {
+      getDietRecommendation: stubs.getDietRecommendation,
+      generateDietRecommendation: stubs.generateDietRecommendation,
+      completeDietRecommendation: stubs.completeDietRecommendation,
+      regenerateDietRecommendation: stubs.regenerateDietRecommendation,
+      updateDietRecommendation: stubs.updateDietRecommendation
+    },
+    '@/config.js': stubs.config,
+    '@/components/MemberSelector.vue': stubs.MemberSelector,
+    '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
+    '@/mixins/font-scale.js': stubs.fontScaleMixin
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__recommendationStubs
+})
+
+/** 家庭总览场景的成员列表(/api/food/recommendation/members 返回含 familyMemberId+nickname+isSelf) */
+function familyOf(memberIds) {
+  return memberIds.map(function (id) {
+    return { familyMemberId: id, nickname: '成员' + id, isSelf: id === 1 }
+  })
+}
+
+// ---------------------------------------------------------------------------
+// REQ7-前端 个人/成员视角:generateRecipe 不弹选择,直传 participant_member_ids:[currentMemberId]
+// ---------------------------------------------------------------------------
+
+describe('REQ7 personal 视角:generateRecipe 载荷直传当前成员为共餐人', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+    vm.currentView = 'personal'
+    vm.currentMemberId = 42
+    stubs.generateDietRecommendation.mockClear()
+  })
+
+  it('generate 载荷存在 participant_member_ids 键', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(stubs.generateDietRecommendation).toHaveBeenCalled()
+    var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+    expect(payload).toHaveProperty('participant_member_ids')
+  })
+
+  it('participant_member_ids 解析为 [currentMemberId](只当前选中人,不做多选)', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(stubs.generateDietRecommendation).toHaveBeenCalled()
+    var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+    expect(participantIdsOf(payload)).toEqual([42])
+  })
+
+  it('成员视角(选中其他成员)同样直传该成员 id', async function () {
+    vm.currentMemberId = 88
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(stubs.generateDietRecommendation).toHaveBeenCalled()
+    var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+    expect(participantIdsOf(payload)).toEqual([88])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ7-前端 家庭总览视角:点「生成食谱」先弹共餐人选择,不立即生成
+// ---------------------------------------------------------------------------
+
+describe('REQ7 family 视角:generateRecipe 先弹共餐人选择,不直接调 generate', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+    vm.currentView = 'family'
+    vm.memberList = familyOf([1, 2, 3])
+    stubs.generateDietRecommendation.mockClear()
+  })
+
+  it('family 视角 generateRecipe 不立即调用 generateDietRecommendation(等待共餐人确认)', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(stubs.generateDietRecommendation).not.toHaveBeenCalled()
+  })
+
+  it('family 视角即使成员列表为单人也先弹选择(不跳过共餐人确认)', async function () {
+    vm.memberList = familyOf([1])
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(stubs.generateDietRecommendation).not.toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ7-前端 家庭总览视角:确认共餐人后生成,participant_member_ids 默认覆盖全部成员
+// ---------------------------------------------------------------------------
+
+describe('REQ7 family 视角:确认共餐人后生成的载荷契约', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+    vm.currentView = 'family'
+    vm.memberList = familyOf([1, 2, 3])
+    stubs.generateDietRecommendation.mockClear()
+  })
+
+  it('家庭总览存在「确认共餐人」入口(confirmParticipants 方法)', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(typeof vm.confirmParticipants).toBe('function')
+  })
+
+  it('未显式勾选时确认 → participant_member_ids 默认覆盖全部成员(默认勾选全部)', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(typeof vm.confirmParticipants).toBe('function')
+    if (typeof vm.confirmParticipants === 'function') {
+      await vm.confirmParticipants()
+      await Promise.resolve()
+      await Promise.resolve()
+      expect(stubs.generateDietRecommendation).toHaveBeenCalled()
+      var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+      expect(participantIdsOf(payload)).toEqual([1, 2, 3])
+    }
+  })
+
+  it('confirmParticipants 生成的载荷仍含 participant_member_ids 键', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(typeof vm.confirmParticipants).toBe('function')
+    if (typeof vm.confirmParticipants === 'function') {
+      await vm.confirmParticipants()
+      await Promise.resolve()
+      await Promise.resolve()
+      expect(stubs.generateDietRecommendation).toHaveBeenCalled()
+      var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+      expect(payload).toHaveProperty('participant_member_ids')
+    }
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 设计锚点:utils/api.js generateDietRecommendation 为通用透传,无需改动
+// (规格 §2 需求 7:generateDietRecommendation 通用透传 request,GREEN 不动 api.js)
+// ---------------------------------------------------------------------------
+
+describe('设计锚点:api.js generateDietRecommendation 透传 participant_member_ids', function () {
+  it('POST /api/diet/recommendation/generate 载荷含 participant_member_ids 原样透传', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: { id: 1 } } }) })
+    })
+    clearApiDedup()
+    await apiGenerateDietRecommendation({ date: '2026-11-08', meal_type: 'all', participant_member_ids: '[1,2,3]' })
+    expect(captured.url).toContain('/api/diet/recommendation/generate')
+    expect(captured.method).toBe('POST')
+    expect(captured.data).toEqual(expect.objectContaining({ participant_member_ids: '[1,2,3]' }))
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为「生成食谱时的共餐人选择」,家长/孩子进入均可能触发
+// (家庭总览为家长视角典型入口;成员视角任何角色均可),无额外角色门禁,
+// 属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:共餐人选择无角色门禁,不适用', function () {
+  it('占位:生成食谱在家长端/成员端共用 generateRecipe,无 role 分支(详见汇报)', function () {})
+})

+ 466 - 0
cfc-frontend/__tests__/pages/diet/recommendation.uiRework.test.js

@@ -0,0 +1,466 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 diet.recommendation.uiRework
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-08-diet-recommendation-polish.md
+ *                §2 需求 1-6(页面标题、互斥选中、4Tab、分页、「我」、生成 loading)
+ *   design:      同文档 §2 各条落点;cfc-frontend/pages/diet/recommendation.vue
+ *                (L6-9 删标题、L65-75 改4Tab、L103-123 列表分页、L285-334 filteredFoods、
+ *                 L407-425 生成提示、L658-674 互斥);
+ *                components/MemberSelector.vue minimal 变体 selfLabel/overviewActive
+ *
+ * 说明:
+ *   沿用 __tests__/family-join/join-form.required-info.test.js 约定:直接加载真实
+ *   recommendation.vue SFC 的 <script>(import 替换为注入桩后求值)拿到 data()/methods,
+ *   做行为级断言;读取 <template> 做结构契约断言。当前实现未落地(REQ1-6 均未写),
+ *   预期全部 RED;GREEN 阶段在实现不修改本文件的前提下翻绿。
+ *   本文件不修改 pages/ / components/ / utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const RECOMMENDATION_PATH = path.join(__dirname, '../../../pages/diet/recommendation.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:把 ES import 替换成从 globalThis.__recommendationStubs 取桩的 var 声明
+// ---------------------------------------------------------------------------
+
+function stubImports(script, stubMap) {
+  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.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template } */
+function loadRecommendation() {
+  var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__recommendationStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 把 component 的 data()/computed()/methods 合并到 vm 实例(computed 定义为 getter) */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  if (component.computed) {
+    Object.keys(component.computed).forEach(function (k) {
+      Object.defineProperty(vm, k, { get: component.computed[k].bind(vm), enumerable: true, configurable: true })
+    })
+  }
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+/** 安全求值 pagedFoods:computed 缺失时返回 null(让断言以 toBeDefined 干净失败) */
+function pagedOf(vm, component) {
+  var c = component.computed && component.computed.pagedFoods
+  if (!c) return null
+  return c.call(vm)
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  global.uni.request.mockReset()
+
+  stubs = {
+    generateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    getDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    completeDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    regenerateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    updateDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    memberIdOf: jest.fn(function (m) { return m && (m.familyMemberId != null ? m.familyMemberId : (m.id != null ? m.id : null)) }),
+    config: { default: { API_BASE_URL: '/api' } },
+    MemberSelector: { default: {} },
+    fontScaleMixin: { default: { data: function () { return { fontScale: 1 } }, onShow: function () {} } }
+  }
+  globalThis.__recommendationStubs = {
+    '@/utils/api.js': {
+      getDietRecommendation: stubs.getDietRecommendation,
+      generateDietRecommendation: stubs.generateDietRecommendation,
+      completeDietRecommendation: stubs.completeDietRecommendation,
+      regenerateDietRecommendation: stubs.regenerateDietRecommendation,
+      updateDietRecommendation: stubs.updateDietRecommendation
+    },
+    '@/config.js': stubs.config,
+    '@/components/MemberSelector.vue': stubs.MemberSelector,
+    '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
+    '@/mixins/font-scale.js': stubs.fontScaleMixin
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__recommendationStubs
+})
+
+// ---------------------------------------------------------------------------
+// 测试辅助
+// ---------------------------------------------------------------------------
+
+function buildFoods(n) {
+  var out = []
+  for (var i = 1; i <= n; i++) {
+    out.push({ id: i, name: '食材' + i, category: i % 3 === 0 ? '蔬菜' : (i % 3 === 1 ? '水果' : '肉禽'), score: i % 2 === 0 ? 5 : -3 })
+  }
+  return out
+}
+
+// ---------------------------------------------------------------------------
+// REQ1 页面顶部:去掉「推荐食材」标题 + 副标题;MemberSelector 保留为首个元素
+// ---------------------------------------------------------------------------
+
+describe('REQ1 模板结构:去掉顶部「推荐食材」标题区', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+
+  it('删除包含「查看家庭成员适合与戒备的食材」副标题的顶部 section-title-bar 块', function () {
+    expect(template).not.toContain('查看家庭成员适合与戒备的食材')
+  })
+
+  it('MemberSelector 仍然作为页面首个元素(minimal 变体),未被整体移除', function () {
+    expect(template).toContain('<MemberSelector')
+    expect(template).toContain(':show-overview="true"')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ2 家庭总览 ↔ 个人/成员互斥:switchView('family') 清 currentMemberId,loadMembers 不再默认选
+// ---------------------------------------------------------------------------
+
+describe('REQ2 数据行为:switchView/family 互斥', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+  })
+
+  it('switchView("family") 置 currentView=family 且清 currentMemberId=null(个人/成员 chip 不高亮)', function () {
+    vm.currentMemberId = 7
+    vm.currentView = 'personal'
+    vm.switchView('family')
+    expect(vm.currentView).toBe('family')
+    expect(vm.currentMemberId).toBeNull()
+  })
+
+  it('switchMember(member) 保留已有选中:currentView=personal + currentMemberId 为 member 的 id', function () {
+    vm.switchMember({ familyMemberId: 5 })
+    expect(vm.currentView).toBe('personal')
+    expect(vm.currentMemberId).toBe(5)
+  })
+
+  it('switchView("family") 后再调 loadMembers:不得再默认选中个人(loadMembers 默认选中仅限首次 onLoad)', function () {
+    vm.currentMemberId = 7
+    vm.switchView('family')
+    expect(vm.currentMemberId).toBeNull()
+    global.uni.setStorageSync('token', 'test-token')
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: [{ familyMemberId: 1, nickname: '我', isSelf: true }] } })
+    })
+    vm.loadMembers()
+    return Promise.resolve().then(function () {
+      expect(vm.currentMemberId).toBeNull()
+      expect(vm.memberList).toEqual([{ familyMemberId: 1, nickname: '我', isSelf: true }])
+    })
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ3 4Tab 行(今日食谱 | 适合 | 戒备 | 全部):data 新增 currentTab='recipe',模板切 Tab
+// ---------------------------------------------------------------------------
+
+describe('REQ3 数据契约:新增 currentTab 字段(初始 recipe)', function () {
+  var component
+  beforeEach(function () {
+    component = loadRecommendation().component
+  })
+  it('data().currentTab 初值为 "recipe"(进页默认显示今日食谱)', function () {
+    expect(component.data().currentTab).toBe('recipe')
+  })
+})
+
+describe('REQ3 模板契约:4Tab 切换行 + 按 currentTab 渲染内容区', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+
+  it('模板出现 switchTab("recipe") / switchTab("suitable") / switchTab("unsuitable") / switchTab("all") 绑定', function () {
+    expect(template).toMatch(/switchTab\(['"]recipe['"]\)/)
+    expect(template).toMatch(/switchTab\(['"]suitable['"]\)/)
+    expect(template).toMatch(/switchTab\(['"]unsuitable['"]\)/)
+    expect(template).toMatch(/switchTab\(['"]all['"]\)/)
+  })
+
+  it('今日食谱内容区按 currentTab === \'recipe\' 条件渲染', function () {
+    expect(template).toMatch(/currentTab\s*===\s*['"]recipe['"]/)
+  })
+
+  it('食材区出现 currentTab 引用(过滤栏区域按 currentTab 区分内容)', function () {
+    expect(template).toMatch(/currentTab/)
+  })
+})
+
+describe('REQ3 行为契约:switchTab 更新 currentTab', function () {
+  var vm
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+  })
+  it('switchTab("suitable") 置 currentTab 并重置分页 visibleCount', function () {
+    expect(typeof vm.switchTab).toBe('function')
+    if (typeof vm.switchTab !== 'function') return
+    vm.visibleCount = 60
+    vm.switchTab('suitable')
+    expect(vm.currentTab).toBe('suitable')
+    expect(vm.visibleCount).toBe(20)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ4 推荐食材列表分页(前端 slice + scroll-view 触底加载更多)
+// ---------------------------------------------------------------------------
+
+describe('REQ4 数据契约:visibleCount / PAGE_SIZE 初值', function () {
+  var component
+  beforeEach(function () {
+    component = loadRecommendation().component
+  })
+  it('data().visibleCount 初值为 20', function () {
+    expect(component.data().visibleCount).toBe(20)
+  })
+})
+
+describe('REQ4 计算属性 pagedFoods(分片)', function () {
+  var vm, component
+  beforeEach(function () {
+    component = loadRecommendation().component
+    vm = instantiate(component)
+    vm.currentView = 'personal'
+    vm.filterType = 'all'
+    vm.activeCategory = 'all'
+    vm.searchQuery = ''
+    vm.allFoods = buildFoods(45)
+  })
+
+  it('computed.pagedFoods 存在', function () {
+    expect(typeof component.computed.pagedFoods).toBe('function')
+  })
+
+  it('首批只返回前 visibleCount(20)条', function () {
+    expect(typeof component.computed.pagedFoods).toBe('function')
+    var page = pagedOf(vm, component)
+    if (page === null) return
+    expect(page.length).toBe(20)
+  })
+
+  it('visibleCount 增加时 pagedFoods 随之增长且不超全量', function () {
+    expect(typeof component.computed.pagedFoods).toBe('function')
+    var page = pagedOf(vm, component)
+    if (page === null) return
+    vm.visibleCount = 40
+    expect(pagedOf(vm, component).length).toBe(40)
+    vm.visibleCount = 100
+    expect(pagedOf(vm, component).length).toBe(45)
+  })
+})
+
+describe('REQ4 loadMore() 触底加载行为', function () {
+  var vm, component
+  beforeEach(function () {
+    component = loadRecommendation().component
+    vm = instantiate(component)
+    vm.currentView = 'personal'
+    vm.filterType = 'all'
+    vm.activeCategory = 'all'
+    vm.searchQuery = ''
+    vm.allFoods = buildFoods(45)
+    vm.visibleCount = 20
+  })
+
+  it('loadMore 是函数', function () {
+    expect(typeof vm.loadMore).toBe('function')
+  })
+
+  it('触底一次:visibleCount += PAGE_SIZE(20 → 40),pagedFoods 同步增至 40', function () {
+    expect(typeof vm.loadMore).toBe('function')
+    if (typeof vm.loadMore !== 'function') return
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(40)
+    expect(pagedOf(vm, component).length).toBe(40)
+  })
+
+  it('触底两次后未超全量并自动停止(20 → 40 → 60;第 3 次不变化,末尾停)', function () {
+    expect(typeof vm.loadMore).toBe('function')
+    if (typeof vm.loadMore !== 'function') return
+    vm.loadMore()
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(60)
+    expect(pagedOf(vm, component).length).toBe(45)
+    vm.loadMore()
+    expect(vm.visibleCount).toBe(60)
+  })
+
+  it('切换筛选:setFilter -> reset visibleCount = 20', function () {
+    vm.visibleCount = 60
+    vm.setFilter('unsuitable')
+    expect(vm.visibleCount).toBe(20)
+  })
+
+  it('切换分类:switchCategory -> reset visibleCount = 20', function () {
+    vm.visibleCount = 60
+    vm.switchCategory('all')
+    expect(vm.visibleCount).toBe(20)
+  })
+
+  it('切换成员:switchMember -> reset visibleCount = 20 且更新 currentView/currentMemberId', function () {
+    vm.visibleCount = 60
+    vm.switchMember({ familyMemberId: 9 })
+    expect(vm.currentView).toBe('personal')
+    expect(vm.currentMemberId).toBe(9)
+    expect(vm.visibleCount).toBe(20)
+  })
+})
+
+describe('REQ4 模板契约:v-for 改用 pagedFoods;scroll-view 监听 @scrolltolower="loadMore"', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+  it('食材列表 v-for 引用 pagedFoods(非 filteredFoods)', function () {
+    expect(template).toContain('pagedFoods')
+  })
+  it('外层 scroll-view 绑定 @scrolltolower="loadMore"', function () {
+    expect(template).toContain('@scrolltolower="loadMore"')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ5 「个人」改为「我」:recommendation.vue 给 MemberSelector 传 self-label="'我'"
+// ---------------------------------------------------------------------------
+
+describe('REQ5 模板契约:MemberSelector 传 self-label="我"', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+  it('推荐食材页的 MemberSelector 显式传入 self-label="我"(不依赖组件默认 👤 个人)', function () {
+    expect(template).toMatch(/self-label\s*=\s*['"]我['"]/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// REQ6 生成食谱 loading 提示
+// ---------------------------------------------------------------------------
+
+describe('REQ6 generateRecipe 正在生成 loading', function () {
+  var vm, component
+  beforeEach(function () {
+    component = loadRecommendation().component
+    vm = instantiate(component)
+    stubs.generateDietRecommendation.mockClear()
+    stubs.generateDietRecommendation.mockImplementationOnce(function () {
+      return Promise.resolve({ data: { id: 100, date: '2026-11-08' } })
+    })
+  })
+
+  it('发起生成时 uni.showLoading({ title 含 "正在生成" })', async function () {
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(global.uni.showLoading).toHaveBeenCalledWith(expect.objectContaining({ title: expect.stringContaining('正在生成') }))
+  })
+
+  it('成功后 uni.hideLoading() 并 toast 成功提示', async function () {
+    await vm.generateRecipe()
+    expect(global.uni.hideLoading).toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalledWith(expect.objectContaining({ title: expect.stringContaining('成功'), icon: 'success' }))
+  })
+
+  it('失败后 uni.hideLoading() 并 toast 失败', async function () {
+    // 复位 beforeEach 预置的 resolve 队列,确保本用例只消费 reject(失败路径)
+    stubs.generateDietRecommendation.mockReset()
+    stubs.generateDietRecommendation.mockImplementationOnce(function () { return Promise.reject(new Error('net')) })
+    await vm.generateRecipe()
+    expect(global.uni.hideLoading).toHaveBeenCalled()
+    expect(global.uni.showToast).toHaveBeenCalledWith(expect.objectContaining({ icon: 'none' }))
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 回归防护:既有能力不因 uiRework 破坏
+// ---------------------------------------------------------------------------
+
+describe('回归防护:既有核心方法仍可用', function () {
+  var vm
+  beforeEach(function () {
+    var component = loadRecommendation().component
+    vm = instantiate(component)
+  })
+
+  it('filteredFoods computed 在 personal + allFoods 非空场景下有输出(无回归)', function () {
+    vm.currentView = 'personal'
+    vm.allFoods = [{ id: 1, name: 'Apple', score: 3, status: 'suitable', statusText: '适合' }]
+    vm.filterType = 'suitable'
+    vm.activeCategory = 'all'
+    vm.searchQuery = ''
+    var result = vm.filteredFoods
+    expect(Array.isArray(result)).toBe(true)
+    expect(result.length).toBe(1)
+    expect(result[0].name).toBe('Apple')
+  })
+
+  it('switchMember 触发 loadFoods(即使无 token 提前返回无副作用)', function () {
+    // setup.js 的 global.uni.getStorageSync 非 jest mock;未设 token → loadFoods 提前 return
+    vm.switchMember({ familyMemberId: 2 })
+    expect(vm.currentMemberId).toBe(2)
+    expect(vm.currentView).toBe('personal')
+  })
+})

+ 494 - 0
cfc-frontend/__tests__/pages/diet/recommendation.viewKeyAndDelete.test.js

@@ -0,0 +1,494 @@
+/**
+ * 契约级单测 —— 能力键 diet.recommendation.viewKeyAndDelete
+ *
+ * 溯源:
+ *   PRD      docs/需求分析/2026-11-10-食材推荐食谱需求变更.md(38 条 AC,产品规则单一来源)
+ *   设计     docs/需求分析/2026-11-10-食材推荐食谱需求变更-影响面与任务分解.md
+ *            §1.1(K1~K6)/ §3(接口契约)/ §8.2(AC→断言映射)
+ *
+ * 覆盖:buildViewKey 各视角、视角切换四处联动、生成载荷 view_key、模板契约(替换→删除)、
+ *       deleteDish 成功/失败/防重复、D2 只读菜数状态不补菜、空/加载/失败三态、
+ *       parseMenu 透传 dish.type、allMealsEmpty 整份空态。
+ *
+ * 约定(沿用 uiRework / participantSelect):加载真实 recommendation.vue 的 <script>/<template>,
+ * import 替换为注入桩后求值,驱动真实 data()/methods/computed 做行为级断言;不挂载 .vue。
+ * 本文件不修改任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const RECOMMENDATION_PATH = path.join(__dirname, '../../../pages/diet/recommendation.vue')
+
+function stubImports(script, stubMap) {
+  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.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+function loadRecommendation() {
+  var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__recommendationStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 合并 data()/computed(getter)/methods 到 vm 实例(模拟 Vue Options 合并) */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  if (component.computed) {
+    Object.keys(component.computed).forEach(function (k) {
+      Object.defineProperty(vm, k, { get: component.computed[k].bind(vm), enumerable: true, configurable: true })
+    })
+  }
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+var stubs
+
+beforeEach(function () {
+  jest.useFakeTimers()
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  global.uni.request.mockReset()
+
+  stubs = {
+    getDietRecommendation: jest.fn(function () {
+      return Promise.resolve({ code: 200, data: { id: 11, date: '2026-11-10', menu: '{"meals":[]}', nutritionSummary: {}, status: 'pending' } })
+    }),
+    generateDietRecommendation: jest.fn(function () { return Promise.resolve({ data: { id: 11 } }) }),
+    updateDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 200, message: 'success', data: null }) }),
+    completeDietRecommendation: jest.fn(function () { return Promise.resolve({}) }),
+    regenerateDietRecommendation: jest.fn(function () { return Promise.resolve({ data: { id: 11 } }) }),
+    memberIdOf: jest.fn(function (m) { return m && (m.familyMemberId != null ? m.familyMemberId : (m.id != null ? m.id : null)) }),
+    config: { default: { API_BASE_URL: '/api' } },
+    MemberSelector: { default: {} },
+    fontScaleMixin: { default: { data: function () { return { fontScale: 1 } }, onShow: function () {} } }
+  }
+  globalThis.__recommendationStubs = {
+    '@/utils/api.js': {
+      getDietRecommendation: stubs.getDietRecommendation,
+      generateDietRecommendation: stubs.generateDietRecommendation,
+      updateDietRecommendation: stubs.updateDietRecommendation,
+      completeDietRecommendation: stubs.completeDietRecommendation,
+      regenerateDietRecommendation: stubs.regenerateDietRecommendation
+    },
+    '@/config.js': stubs.config,
+    '@/components/MemberSelector.vue': stubs.MemberSelector,
+    '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
+    '@/mixins/font-scale.js': stubs.fontScaleMixin
+  }
+})
+
+afterEach(function () {
+  jest.clearAllTimers()
+  jest.useRealTimers()
+  delete globalThis.__recommendationStubs
+})
+
+/** 构造一份 4 菜 1 汤的午餐,便于删除 / 状态断言 */
+function lunchWithDishes() {
+  return {
+    name: '午餐', type: 'lunch', icon: '☀️', participants: 3,
+    dishes: [
+      { name: '红烧肉', type: 'dish', calories: 300, ingredients: [{ name: '肉', amount: 100 }], method: '炖' },
+      { name: '清炒时蔬', type: 'dish', calories: 90, ingredients: [], method: '炒' },
+      { name: '蒸鱼', type: 'dish', calories: 180, ingredients: [], method: '蒸' },
+      { name: '凉拌黄瓜', type: 'dish', calories: 40, ingredients: [], method: '拌' },
+      { name: '番茄蛋汤', type: 'soup', calories: 60, ingredients: [], method: '煮' }
+    ]
+  }
+}
+
+function dinnerWithDishes() {
+  var meal = lunchWithDishes()
+  meal.name = '晚餐'
+  meal.type = 'dinner'
+  meal.icon = '🌙'
+  return meal
+}
+
+// ---------------------------------------------------------------------------
+// 1. buildViewKey:K1 视角键(AC-01/03/10)
+// ---------------------------------------------------------------------------
+
+describe('buildViewKey 视角键生成(K1,后端视为不透明字符串)', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('家庭总览固定返回 family', function () {
+    vm.currentView = 'family'
+    expect(vm.buildViewKey()).toBe('family')
+  })
+
+  it('个人/成员视角返回 member:<id>', function () {
+    vm.currentView = 'personal'
+    vm.currentMemberId = 42
+    expect(vm.buildViewKey()).toBe('member:42')
+  })
+
+  it('loadMembers 未完成(personal 且无 currentMemberId、memberList 空)返回 null', function () {
+    vm.currentView = 'personal'
+    vm.currentMemberId = null
+    vm.memberList = []
+    expect(vm.buildViewKey()).toBeNull()
+  })
+
+  it('视角未就绪时不发 /today 请求,且清空残留防串数据', function () {
+    vm.currentView = 'personal'
+    vm.currentMemberId = null
+    vm.memberList = []
+    vm.meals = [lunchWithDishes()]
+    vm.recommendation = { id: 99 }
+    vm.loadRecommendation()
+    expect(stubs.getDietRecommendation).not.toHaveBeenCalled()
+    expect(vm.meals).toEqual([])
+    expect(vm.recommendation).toBeNull()
+    expect(vm.recipeLoading).toBe(false)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 2. loadRecommendation 载荷 + 局部加载态(AC-02/04/09/36)
+// ---------------------------------------------------------------------------
+
+describe('loadRecommendation 按视角加载', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('请求携带 {date, view_key}', function () {
+    vm.currentView = 'family'
+    vm.loadRecommendation()
+    expect(stubs.getDietRecommendation).toHaveBeenCalledWith(
+      expect.objectContaining({ date: expect.any(String), view_key: 'family' })
+    )
+  })
+
+  it('加载期间显示局部 loading 且清空上一视角的 meals(不串数据)', function () {
+    vm.currentView = 'family'
+    vm.currentMemberId = 7
+    vm.meals = [lunchWithDishes()]
+    vm.recommendation = { id: 99 }
+    vm.loadRecommendation()
+    expect(vm.recipeLoading).toBe(true)
+    expect(vm.meals).toEqual([])
+    expect(vm.recommendation).toBeNull()
+  })
+
+  it('请求成功后关闭 loading 并写入该视角食谱', async function () {
+    vm.currentView = 'family'
+    await vm.loadRecommendation()
+    expect(vm.recipeLoading).toBe(false)
+    expect(vm.recommendation.id).toBe(11)
+  })
+
+  it('请求失败进入失败态,保留重试入口所需数据位', async function () {
+    stubs.getDietRecommendation.mockImplementationOnce(function () {
+      return Promise.reject({ message: '网络异常' })
+    })
+    vm.currentView = 'family'
+    await vm.loadRecommendation()
+    expect(vm.recipeLoading).toBe(false)
+    expect(vm.recipeError).toContain('网络异常')
+    expect(typeof vm.retryRecommendation).toBe('function')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 3. 视角切换四处联动(AC-01/02/03/09)
+// ---------------------------------------------------------------------------
+
+describe('视角切换联动今日食谱', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('switchMember 触发 /today 且 view_key=member:<id>,仍保留 visibleCount=20', function () {
+    vm.visibleCount = 60
+    vm.switchMember({ familyMemberId: 42 })
+    expect(vm.currentView).toBe('personal')
+    expect(vm.currentMemberId).toBe(42)
+    expect(vm.visibleCount).toBe(20)
+    var payload = stubs.getDietRecommendation.mock.calls[0][0]
+    expect(payload.view_key).toBe('member:42')
+  })
+
+  it('switchView("family") 触发 /today 且 view_key=family', function () {
+    vm.currentMemberId = 42
+    vm.switchView('family')
+    expect(vm.currentMemberId).toBeNull()
+    var payload = stubs.getDietRecommendation.mock.calls[0][0]
+    expect(payload.view_key).toBe('family')
+  })
+
+  it('onRefresh 按当前视角重载 /today', function () {
+    vm.currentView = 'family'
+    vm.onRefresh()
+    expect(stubs.getDietRecommendation).toHaveBeenCalledWith(
+      expect.objectContaining({ view_key: 'family' })
+    )
+  })
+
+  it('switchTab("recipe") 按当前视角重载 /today;其它 Tab 不重载', function () {
+    vm.currentView = 'family'
+    vm.switchTab('recipe')
+    expect(stubs.getDietRecommendation).toHaveBeenCalledTimes(1)
+    expect(stubs.getDietRecommendation.mock.calls[0][0].view_key).toBe('family')
+
+    stubs.getDietRecommendation.mockClear()
+    vm.switchTab('suitable')
+    expect(stubs.getDietRecommendation).not.toHaveBeenCalled()
+  })
+
+  it('loadMembers 成功后补发一次 /today(onLoad 时序坑)', function () {
+    vm.currentView = 'personal'
+    vm.currentMemberId = null
+    global.uni.setStorageSync('token', 'test-token')
+    global.uni.request.mockImplementation(function (opts) {
+      opts.success({ data: { code: 200, data: [{ familyMemberId: 8, nickname: '我', isSelf: true }] } })
+    })
+    vm.loadMembers()
+    expect(stubs.getDietRecommendation).toHaveBeenCalledWith(
+      expect.objectContaining({ view_key: 'member:8' })
+    )
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 4. 生成载荷(AC-05/06/07/08)
+// ---------------------------------------------------------------------------
+
+describe('生成食谱载荷带 view_key 且不破坏共餐人多选', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('个人视角 generateRecipe 带 view_key=member:<id> 与 participant_member_ids=[id]', async function () {
+    vm.currentView = 'personal'
+    vm.currentMemberId = 42
+    await vm.generateRecipe()
+    var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+    expect(payload.view_key).toBe('member:42')
+    expect(JSON.parse(payload.participant_member_ids)).toEqual([42])
+  })
+
+  it('家庭总览 confirmParticipants 带 view_key=family 与所选共餐人', async function () {
+    vm.currentView = 'family'
+    vm.memberList = [{ familyMemberId: 1, nickname: '成员1' }, { familyMemberId: 2, nickname: '成员2' }]
+    vm.generateRecipe()
+    await Promise.resolve()
+    await Promise.resolve()
+    // 先弹层,不直接生成
+    expect(stubs.generateDietRecommendation).not.toHaveBeenCalled()
+    await vm.confirmParticipants()
+    var payload = stubs.generateDietRecommendation.mock.calls[0][0]
+    expect(payload.view_key).toBe('family')
+    expect(JSON.parse(payload.participant_member_ids)).toEqual([1, 2])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 5. 模板契约(D1① / AC-12/19/33/34/35/38)
+// ---------------------------------------------------------------------------
+
+describe('模板契约:替换→删除 + 三态', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__recommendationStubs = {}
+    template = loadRecommendation().template
+  })
+
+  it('模板不再出现「替换」/「好吃」/「跳过」', function () {
+    expect(template).not.toContain('替换')
+    expect(template).not.toContain('好吃')
+    expect(template).not.toContain('跳过')
+  })
+
+  it('模板含单一「🗑 删除」且由 dishActions 数据位驱动', function () {
+    expect(template).toContain('🗑 删除')
+    expect(template).toContain("dishActions === 'delete-only'")
+    expect(template).toContain('deleteDish(meal.name, dIndex)')
+  })
+
+  it('餐次头部含只读菜数状态、餐次级空态、整份空态、局部 loading、失败态', function () {
+    expect(template).toContain('dishStandard(meal)')
+    expect(template).toContain('本餐暂无菜品')
+    expect(template).toContain('今天的菜品都删完啦')
+    expect(template).toContain('正在加载今日食谱')
+    expect(template).toContain('今日食谱加载失败')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 6. 删除行为(AC-13/14/15/16/18/37)
+// ---------------------------------------------------------------------------
+
+describe('deleteDish 复用 /update 整份覆盖', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+    vm.currentView = 'family'
+    vm.recommendation = { id: 77, status: 'pending' }
+    vm.meals = [lunchWithDishes(), dinnerWithDishes()]
+    stubs.updateDietRecommendation.mockClear()
+  })
+
+  it('成功:移除该菜 + toast「已删除」+ 提交 {id, menu_json},不影响其它餐次', async function () {
+    await vm.deleteDish('午餐', 0)
+    expect(stubs.updateDietRecommendation).toHaveBeenCalledTimes(1)
+    var payload = stubs.updateDietRecommendation.mock.calls[0][0]
+    expect(payload.id).toBe(77)
+    var menu = JSON.parse(payload.menu_json)
+    expect(menu.meals[0].dishes.length).toBe(4)
+    expect(menu.meals[0].dishes[0].type).toBe('dish')
+    expect(menu.meals[0].dishes[3].type).toBe('soup')
+    expect(menu.meals[1].dishes.length).toBe(5) // 晚餐不受影响
+    expect(vm.meals[0].dishes.length).toBe(4)   // 列表即时更新
+    expect(vm.meals[1].dishes.length).toBe(5)
+    expect(global.uni.showToast).toHaveBeenCalledWith(expect.objectContaining({ title: '已删除' }))
+  })
+
+  it('menu_json 保留 dish.type 且不混入 icon 展示字段', async function () {
+    vm.meals[0].icon = '☀️'
+    await vm.deleteDish('午餐', 0)
+    var text = stubs.updateDietRecommendation.mock.calls[0][0].menu_json
+    expect(text).not.toContain('"icon"')
+    expect(text).toContain('"type":"soup"')
+  })
+
+  it('失败:原菜品保留、deleting 复位可重试、toast 失败提示', async function () {
+    stubs.updateDietRecommendation.mockImplementationOnce(function () {
+      return Promise.reject({ message: '网络异常' })
+    })
+    await vm.deleteDish('午餐', 0)
+    expect(vm.meals[0].dishes.length).toBe(5)
+    expect(vm.deleting).toBe(false)
+    expect(global.uni.showToast).toHaveBeenCalledWith(expect.objectContaining({ icon: 'none' }))
+  })
+
+  it('D1 可回退:dishActions 默认 delete-only,replaceDish 与 deleteDish 为独立方法', function () {
+    expect(vm.dishActions).toBe('delete-only')
+    expect(typeof vm.replaceDish).toBe('function')
+    expect(typeof vm.deleteDish).toBe('function')
+  })
+
+  it('防重复点击:deleting 期间不重复提交', async function () {
+    var release
+    stubs.updateDietRecommendation.mockImplementationOnce(function () {
+      return new Promise(function (resolve) { release = resolve })
+    })
+    vm.deleteDish('午餐', 0)
+    expect(vm.isDeleting('午餐', 0)).toBe(true)
+    vm.deleteDish('午餐', 1)
+    expect(stubs.updateDietRecommendation).toHaveBeenCalledTimes(1)
+    release({ code: 200, message: 'success', data: null })
+    await Promise.resolve()
+    await Promise.resolve()
+    expect(vm.deleting).toBe(false)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 7. D2 只读菜数状态(AC-17/25):不静默补菜
+// ---------------------------------------------------------------------------
+
+describe('dishStandard 只读状态(D2① 删除与补菜解耦)', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('4 菜 1 汤(N=3)显示达标', function () {
+    expect(vm.dishStandard(lunchWithDishes())).toContain('达标')
+  })
+
+  it('删掉 1 道菜后显示「当前 3 菜 1 汤 / 未达标准」', function () {
+    var meal = lunchWithDishes()
+    meal.dishes.splice(0, 1)
+    var text = vm.dishStandard(meal)
+    expect(text).toContain('当前 3 菜 1 汤')
+    expect(text).toContain('未达标准')
+  })
+
+  it('N=4 时 D(N)=5,5 菜 1 汤才达标', function () {
+    var meal = lunchWithDishes()
+    meal.participants = 4
+    expect(vm.dishStandard(meal)).toContain('未达标准')
+    meal.dishes.splice(0, 0, { name: '加菜', type: 'dish', calories: 0, ingredients: [], method: '' })
+    expect(vm.dishStandard(meal)).toContain('达标')
+  })
+
+  it('早餐不显示菜数状态;计算过程不触发任何补菜/重新生成请求', function () {
+    var breakfast = { type: 'breakfast', participants: 3, dishes: [{ name: '牛奶', type: 'dish' }] }
+    expect(vm.dishStandard(breakfast)).toBe('')
+    vm.dishStandard(lunchWithDishes())
+    expect(stubs.generateDietRecommendation).not.toHaveBeenCalled()
+    expect(stubs.regenerateDietRecommendation).not.toHaveBeenCalled()
+    expect(stubs.updateDietRecommendation).not.toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 8. parseMenu 透传 dish.type / allMealsEmpty 整份空态(AC-25/35)
+// ---------------------------------------------------------------------------
+
+describe('parseMenu 与整份空态', function () {
+  var vm
+  beforeEach(function () {
+    vm = instantiate(loadRecommendation().component)
+  })
+
+  it('透传 dish.type(soup 可识别,存量无 type 默认 dish)', function () {
+    vm.parseMenu('{"meals":[{"type":"lunch","name":"午餐","participants":3,"dishes":[{"name":"番茄汤","type":"soup","calories":50},{"name":"青菜"}]}]}')
+    expect(vm.meals[0].dishes[0].type).toBe('soup')
+    expect(vm.meals[0].dishes[1].type).toBe('dish')
+  })
+
+  it('所有餐次菜数为 0 时 allMealsEmpty=true,可显示整份空态', function () {
+    vm.meals = [{ name: '午餐', type: 'lunch', dishes: [] }, { name: '晚餐', type: 'dinner', dishes: [] }]
+    expect(vm.allMealsEmpty).toBe(true)
+    vm.meals[0].dishes.push({ name: '红烧肉', type: 'dish' })
+    expect(vm.allMealsEmpty).toBe(false)
+  })
+})

+ 105 - 0
cfc-frontend/__tests__/pages/family-members.joinRequestCardInfo.test.js

@@ -0,0 +1,105 @@
+/**
+ * Contract tests for capability key `family.invite.joinRequestCardInfo`
+ * (spec: docs/superpowers/specs/2026-11-07-family-join-required-info.md §5 WI-4)
+ *
+ * AC4.1  待审批卡片显示申请人真实姓名、出生日期、性别。
+ * AC4.2  任一字段缺失时优雅回退(不报错、不显示乱码)。
+ *
+ * TDD phase: RED. These tests target the REAL `family-members.vue` join-request
+ * card. The current implementation only renders the requester's name
+ * (`requesterRealName || requesterNickname`); it does NOT render the applicant's
+ * birthday or gender. Therefore the AC4.1 assertions are expected to FAIL until
+ * WI-4 is implemented (approval card shows birthday + gender).
+ *
+ * Note: `@jest-environment jsdom` is required because @vue/test-utils `mount`
+ * needs a DOM; the default `node` env does not provide one.
+ *
+ * @jest-environment jsdom
+ */
+import { mount } from '@vue/test-utils'
+import FamilyMembers from '@/pages/profile-extra/family-members.vue'
+
+// A fully-populated pending join request (FamilyJoinRequestDTO shape).
+const fullRequest = {
+  id: 1001,
+  requesterUserId: 200,
+  requesterRealName: '张三',
+  requesterNickname: 'zhangsan',
+  requesterBirthday: '1990-01-01',
+  requesterGender: 'male',
+  requesterAvatar: '/static/avatar.jpg'
+}
+
+async function mountWithRequests(requests) {
+  const wrapper = mount(FamilyMembers, {
+    stubs: { 'generation-picker': true }
+  })
+  wrapper.setData({ joinRequests: requests || [] })
+  await wrapper.vm.$nextTick()
+  return wrapper
+}
+
+describe('family.invite.joinRequestCardInfo (WI-4 审批卡片展示三项信息)', () => {
+  it('AC4.1: 审批卡片显示申请人真实姓名、出生日期、性别', async () => {
+    const wrapper = await mountWithRequests([fullRequest])
+
+    const section = wrapper.find('.join-request-section')
+    expect(section.exists()).toBe(true)
+
+    const text = section.text()
+    // 真实姓名(AC4.1 第一项)
+    expect(text).toContain('张三')
+    // 出生日期(AC4.1 第二项)
+    expect(text).toContain('1990-01-01')
+    // 性别(AC4.1 第三项):male/female 或其中文标签 男/女 均可
+    expect(text).toMatch(/(male|female|男|女)/)
+  })
+
+  it('AC4.1: 性别为 female 时卡片仍展示性别信息', async () => {
+    const wrapper = await mountWithRequests([
+      Object.assign({}, fullRequest, { requesterGender: 'female', requesterRealName: '李四', requesterBirthday: '1985-06-15' })
+    ])
+    const text = wrapper.find('.join-request-section').text()
+    expect(text).toContain('李四')
+    expect(text).toContain('1985-06-15')
+    expect(text).toMatch(/(female|男|女)/)
+  })
+
+  it('AC4.2: 出生日期/性别缺失时不报错、不显示 undefined/null 乱码,且真实姓名仍展示', async () => {
+    const partialRequest = {
+      id: 1002,
+      requesterUserId: 201,
+      requesterRealName: '王五',
+      requesterNickname: 'wangwu'
+      // requesterBirthday / requesterGender 缺失(null/undefined)
+    }
+    // 组件应正常挂载渲染(抛错即失败)
+    const wrapper = await mountWithRequests([partialRequest])
+
+    const text = wrapper.find('.join-request-section').text()
+    expect(text).toContain('王五')
+    // 优雅回退:不允许把缺失值渲染成字面 'undefined' / 'null'
+    expect(text).not.toContain('undefined')
+    expect(text).not.toContain('null')
+  })
+
+  it('AC4.2: 真实姓名缺失时回退展示昵称(不显示空白/乱码)', async () => {
+    const noRealName = {
+      id: 1003,
+      requesterUserId: 202,
+      requesterRealName: '',
+      requesterNickname: 'nick_fallback',
+      requesterBirthday: '2000-12-31',
+      requesterGender: 'female'
+    }
+    const wrapper = await mountWithRequests([noRealName])
+    const text = wrapper.find('.join-request-section').text()
+    expect(text).toContain('nick_fallback')
+    expect(text).not.toContain('undefined')
+  })
+
+  it('边界: 无待处理加入申请时不渲染审批卡片区块', async () => {
+    const wrapper = await mountWithRequests([])
+    expect(wrapper.find('.join-request-section').exists()).toBe(false)
+  })
+})

+ 77 - 0
cfc-frontend/__tests__/pages/growth-main/growthGrid.layout.test.js

@@ -0,0 +1,77 @@
+/**
+ * 回归守护单测 —— 成长页六宫格三列布局容差
+ *
+ * 溯源:
+ *   fix: 3e93a9372「fix(cfc-frontend): 成长页六宫格三列布局容差修复 —
+ *        calc(33.333% - 8rpx)→calc(33.333% - 12rpx),余量 0→1.73% 防临界折行」
+ *   被测:cfc-frontend/pages/growth-main/index.vue  .progress-grid / .progress-tile
+ *
+ * 缺陷本质(本用例守护的规则):
+ *   三列 flex-wrap 布局,每格 width = calc(33.333% - Nrpx),容器 gap = Grpx。
+ *   一行总宽 = 3 × (33.333% - N) + 2 × G = 99.999% - 3N + 2G。
+ *   余量 slack = 100% - 上式 = 0.001% × 容器宽 + 3N - 2G。
+ *   当 N = G/1.5(原 8rpx / gap 12rpx → slack ≈ 0)时,任何亚像素/字体缩放误差
+ *   都会让第三格折行 → 六宫格变「2+2+2」两列。修复把 N 提到 12rpx,slack 恒正。
+ *
+ * 断言口径(静态契约,不依赖渲染引擎):
+ *   1) .progress-grid 确为 flex-wrap 且 gap = 12rpx(布局前提)
+ *   2) .progress-tile 宽度形如 calc(33.333% - Nrpx)
+ *   3) slack(单位 rpx)≥ 4 —— 留出亚像素容差,禁止回归到「刚好 100%」
+ * 本文件只读源码,不改任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/growth-main/index.vue')
+const SRC = fs.readFileSync(PAGE_PATH, 'utf8')
+
+/** 截取某个 CSS 类选择器的声明块({} 内文本),返回 null 表示不存在 */
+function cssBlock(src, selector) {
+  const idx = src.indexOf('\n' + selector + ' {')
+  const altIdx = src.indexOf(selector + ' {')
+  const start = idx >= 0 ? idx : altIdx
+  if (start < 0) return null
+  const open = src.indexOf('{', start)
+  const close = src.indexOf('}', open)
+  if (open < 0 || close < 0) return null
+  return src.slice(open + 1, close)
+}
+
+describe('成长页六宫格 · 三列布局容差(3e93a9372 回归守护)', () => {
+  test('TC-GRID-01 .progress-grid 为 flex-wrap 三列容器且 gap=12rpx', () => {
+    const b = cssBlock(SRC, '.progress-grid')
+    expect(b).not.toBeNull()
+    expect(b).toMatch(/display:\s*flex/)
+    expect(b).toMatch(/flex-wrap:\s*wrap/)
+    const gap = /gap:\s*(\d+)rpx/.exec(b)
+    expect(gap).not.toBeNull()
+    expect(Number(gap[1])).toBe(12)
+  })
+
+  test('TC-GRID-02 .progress-tile 宽度为 calc(33.333% - Nrpx) 形式', () => {
+    const b = cssBlock(SRC, '.progress-tile')
+    expect(b).not.toBeNull()
+    const m = /width:\s*calc\(\s*33\.333%\s*-\s*(\d+)rpx\s*\)/.exec(b)
+    expect(m).not.toBeNull()
+    expect(Number(m[1])).toBeGreaterThan(0)
+  })
+
+  test('TC-GRID-03 一行三格总宽留有余量(slack ≥ 4rpx),不得回归为按 100% 铺满', () => {
+    const grid = cssBlock(SRC, '.progress-grid')
+    const tile = cssBlock(SRC, '.progress-tile')
+    const g = Number(/gap:\s*(\d+)rpx/.exec(grid)[1])
+    const n = Number(/width:\s*calc\(\s*33\.333%\s*-\s*(\d+)rpx\s*\)/.exec(tile)[1])
+    // 3 × (33.333% - n) + 2 × g = 99.999% - 3n + 2g
+    // slack(rpx) = 0.001% 容器宽 + 3n - 2g;0.001% 项按 750rpx 设计宽 ≈ 0.0075rpx,忽略
+    const slackRpx = 3 * n - 2 * g
+    expect(slackRpx).toBeGreaterThanOrEqual(4)
+  })
+
+  test('TC-GRID-04 三格等宽(同一 width 声明,不允许个别格单独覆盖宽度)', () => {
+    // .progress-tile 的 width 声明只出现一次;若出现多个宽度声明即为布局漂移
+    const tile = cssBlock(SRC, '.progress-tile')
+    const widths = tile.match(/(^|\n)\s*width:\s*[^;]+;/g) || []
+    expect(widths.length).toBe(1)
+  })
+})

+ 329 - 0
cfc-frontend/__tests__/pages/growth-main/growthHistory.dayGroupView.test.js

@@ -0,0 +1,329 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 growth.history.dayGroupView(成长主页「按日期分组」视图)
+ *
+ * 溯源:
+ *   requirement: tests/user-scenarios/应用场景总览.md SC-P-95
+ *                docs/需求分析/2026-11-06-成就成长打卡需求变更.md §变更B(成长记录→成长历史记录页,
+ *                聚合「今日成长」全部打卡记录,按日期倒序、分组/筛选,空态合理)
+ *                docs/tdd/test/blockers.md B-135-1(frontend 16 红 = growth-main 按日期分组未落地)
+ *   design:      cfc-frontend/pages/growth-main/index.vue(补按日期分组:dateGroups/groupedRecords/
+ *                groupByDate 结构;实现仅在 feature 分支,不得假定包路径,本测试命名契约对齐同批
+ *                growthHistory.view.test.js 的容错清单——data 字段 v-for 源与 groupByDate 系方法均可选名)
+ *   同批参考:    cfc-frontend/__tests__/pages/growth-main/growthHistory.view.test.js(S-cfc-30,已合入,
+ *                仅含 2 条结构级 RED 断言)· cfc-frontend/__tests__/family-join/join-form.required-info.test.js(加载真实 SFC 源码)
+ *
+ * 说明(既有 Jest 体系约束,同 growthHistory.view.test.js):
+ *   cfc-frontend 的 jest.config.js 仅 transform `.js`,moduleFileExtensions 不含 `vue`,无 vue-jest/jsdom
+ *   组件环境 —— 既有约定为「抽取被测逻辑断言」:直接加载真实 SFC 的 <script>/<template> 源码——
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(按日期分组循环、日期标题、空态分支)。
+ *   format.js 的 parseDate/recordDateOf 注入**真实实现**(纯函数),使分组行为契约覆盖后端真实
+ *   日期形态(recordDate 纯日期 / sleepTime MySQL 空格格式 / startTime ISO / checkinDate 纯日期)。
+ *
+ * 红/绿判定:
+ *   - 现状 origin/cfclub 的 growth-main/index.vue 仅有「今日成长」progressItems 网格,data 无
+ *     dateGroups 系字段、methods 无 groupByDate 系方法、模板无按日期分组渲染 → 全部预期**红**(RED 核心)。
+ *   - 使绿改动(GREEN 阶段实现方,仅改 src/main 下本页面,不动本测试):
+ *     ① data 增补日期分组状态字段(dateGroups/dateGroupList/groupedRecords/groupedCheckins/
+ *       historyGroups/historyDays/checkinGroups/recordGroups/dayGroups/growthHistoryGroups 之一,默认 []);
+ *     ② methods 提供把打卡/档案记录流按业务日期(recordDate>startTime>sleepTime>checkinDate>createdAt)
+ *       分组的装配入口(groupByDate/groupRecordsByDate/groupCheckinsByDate/groupHistoryByDate/groupedByDate
+ *       之一):同日合并、分组键 yyyy-MM-dd、多日倒序(新在前)、无有效日期平稳跳过;
+ *     ③ 模板以分组集合为 v-for 渲染,分组标题显示日期,集合为空时有空态分支(文案/条件均可)。
+ *
+ * 本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+// format.js 为纯函数工具,注入真实实现保证分组行为契约覆盖后端真实日期形态(与桩隔离无冲突)
+import { parseDate as realParseDate, recordDateOf as realRecordDateOf } from '@/utils/format'
+
+const GROWTH_MAIN_PATH = path.join(__dirname, '../../../pages/growth-main/index.vue')
+
+// 容错命名清单(对齐已合入 growthHistory.view.test.js 的契约,或按之对齐即可)
+const DATA_FIELD_NAMES = ['dateGroups', 'dateGroupList', 'groupedRecords', 'groupedCheckins', 'historyGroups', 'historyDays', 'checkinGroups', 'recordGroups', 'dayGroups', 'growthHistoryGroups']
+const METHOD_NAMES = ['groupByDate', 'groupRecordsByDate', 'groupCheckinsByDate', 'groupHistoryByDate', 'groupedByDate']
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 growth-main/index.vue 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__dayGroupViewStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__dayGroupViewStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadGrowthMain() {
+  var src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 growth-main/index.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__dayGroupViewStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 在真实组件中查找 groupByDate 系装配方法的第一个命中名(无则 null) */
+function findGroupMethodName(component) {
+  var methods = component.methods || {}
+  for (var i = 0; i < METHOD_NAMES.length; i++) {
+    if (typeof methods[METHOD_NAMES[i]] === 'function') return METHOD_NAMES[i]
+  }
+  return null
+}
+
+/** 以真实组件 methods 装配入口驱动分组(方法缺失返回 undefined,由断言暴露契约缺口) */
+function invokeGrouping(component, records) {
+  var name = findGroupMethodName(component)
+  if (!name) return undefined
+  var vm = instantiate(component)
+  return vm[name](records)
+}
+
+/** 归一化分组形状(兼容 date/day/groupDate/dayKey/dateStr × records/list/items/checkins/data 命名) */
+function normalizeGroup(g) {
+  var date = g && (g.date || g.day || g.groupDate || g.dayKey || g.dateStr || '')
+  var list = g && (g.records || g.list || g.items || g.checkins || g.data || [])
+  return { date: String(date), list: list }
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+/** 混合类型打卡记录流(业务日期字段仿后端真实形态:饮食 recordDate / 睡眠 sleepTime / 运动 startTime / 心情·记账 checkinDate) */
+function sampleRecords() {
+  return [
+    { type: 'diet', recordDate: '2026-11-08', name: '早餐' },
+    { type: 'sleep', sleepTime: '2026-11-08 23:00', note: '正常' },
+    { type: 'exercise', startTime: '2026-11-07T08:30:00', minutes: 30 },
+    { type: 'emotion', checkinDate: '2026-11-07', mood: '开心' },
+    { type: 'checkin', checkinDate: '2026-11-06', amount: 50 },
+    { type: 'growth', recordDate: '2026-11-06', content: '阅读 30 分钟' },
+    { type: 'diet-backfill', recordDate: '2026-11-09', name: '午餐补录' }
+  ]
+}
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.reLaunch.mockReset()
+  global.uni.request.mockReset()
+  // growth-main 的 <script> 会声明 9 个 API 依赖:只 stub 组件运行时真正调用的,其余以空实现兜底
+  stubs = {
+    healthCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getHealthMealList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getGrowthRecommendations: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { articles: [] } }) }),
+    getExerciseRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getSleepRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getEmotionCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getTodayTasks: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    reportAppEnter: jest.fn(),
+    getGrowthRecordList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) })
+  }
+  globalThis.__dayGroupViewStubs = {
+    '../../utils/api.js': {
+      healthCheckinList: stubs.healthCheckinList,
+      getHealthMealList: stubs.getHealthMealList,
+      getGrowthRecommendations: stubs.getGrowthRecommendations,
+      getExerciseRecords: stubs.getExerciseRecords,
+      getSleepRecords: stubs.getSleepRecords,
+      getEmotionCheckinList: stubs.getEmotionCheckinList,
+      getCheckinList: stubs.getCheckinList,
+      getTodayTasks: stubs.getTodayTasks,
+      reportAppEnter: stubs.reportAppEnter
+    },
+    // format.js 注入真实实现,保证行为契约覆盖后端真实日期形态(纯函数,无副作用)
+    '../../utils/format.js': { parseDate: realParseDate, recordDateOf: realRecordDateOf },
+    '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} } },
+    '../../components/share-mixin.js': { shareMixin: {} },
+    '../../components/LoginGuideCard.vue': {},
+    '../../components/DimensionActivities.vue': {},
+    '../../components/DimensionProducts.vue': {},
+    '../../components/ArticleFeed.vue': {}
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__dayGroupViewStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC-1 | 状态与装配入口存在(契约新增 → 预期红)
+// ---------------------------------------------------------------------------
+
+describe('AC-1 日期分组状态与装配入口存在(成长主页补按日期分组 → 预期红)', function () {
+  var component
+  beforeEach(function () {
+    component = loadGrowthMain().component
+  })
+
+  it('RED-A1 组件提供「日期分组状态」入口:data 字段(dateGroups/groupedRecords 之一)为数组,或 computed getter', function () {
+    var vm = instantiate(component)
+    var hit = DATA_FIELD_NAMES.filter(function (k) { return vm[k] !== undefined })
+    if (hit.length > 0) {
+      expect(Array.isArray(vm[hit[0]])).toBe(true)
+      return
+    }
+    // computed getter 形式:存在且以默认 data 求值为数组
+    var comp = component.computed || {}
+    var cKeys = DATA_FIELD_NAMES.filter(function (k) { return typeof comp[k] === 'function' })
+    expect(cKeys.length).toBeGreaterThan(0)
+    expect(Array.isArray(comp[cKeys[0]].call(instantiate(component)))).toBe(true)
+  })
+
+  it('RED-A2 组件 methods 提供「按日期分组」装配方法(groupByDate 系方法存在且可调用)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-2 | 行为级:按日期分组装配(核心契约 → 预期红)
+//   GREEN 契约:groupByDate(records) 把记录流按业务日期分组——
+//   同日合并、键 yyyy-MM-dd、多日倒序(新在前)、无有效日期平稳跳过、组内保留原记录。
+// ---------------------------------------------------------------------------
+
+describe('AC-2 行为级:groupByDate 系装配逻辑(契约新增 → 预期红)', function () {
+  var component
+  beforeEach(function () {
+    component = loadGrowthMain().component
+  })
+
+  it('RED-A3 空记录列表 → 返回空分组数组(不抛错)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+    var groups = invokeGrouping(component, [])
+    expect(Array.isArray(groups)).toBe(true)
+    expect(groups.length).toBe(0)
+  })
+
+  it('RED-A4 同日记录合并为一组,分组键为 yyyy-MM-dd(混合类型:饮食 recordDate / 睡眠 sleepTime / 心情 checkinDate)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+    var groups = invokeGrouping(component, [
+      { type: 'diet', recordDate: '2026-11-08', name: '早餐' },
+      { type: 'sleep', sleepTime: '2026-11-08 23:00', note: '正常' },
+      { type: 'emotion', checkinDate: '2026-11-08', mood: '平静' }
+    ])
+    var norm = groups.map(normalizeGroup)
+    expect(norm.length).toBe(1)
+    expect(norm[0].date).toBe('2026-11-08')
+    expect(norm[0].list.length).toBe(3)
+  })
+
+  it('RED-A5 多日记录分组按日期倒序(最新在前)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+    var groups = invokeGrouping(component, sampleRecords())
+    var dates = groups.map(normalizeGroup).map(function (g) { return g.date })
+    expect(dates).toEqual(['2026-11-09', '2026-11-08', '2026-11-07', '2026-11-06'])
+  })
+
+  it('RED-A6 组内保留原记录对象(不丢字段、不改写输入)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+    var input = sampleRecords()
+    var snapshot = JSON.stringify(input)
+    var groups = invokeGrouping(component, input)
+    var flat = []
+    groups.map(normalizeGroup).forEach(function (g) { flat = flat.concat(g.list) })
+    expect(input[0].recordDate).toBe('2026-11-08')
+    expect(JSON.stringify(input)).toBe(snapshot)
+    expect(flat).toEqual(expect.arrayContaining(input))
+    expect(flat.length).toBe(input.length)
+  })
+
+  it('RED-A7 无有效业务日期的记录被跳过(不抛错、不产生空键分组;全无效 → 空分组)', function () {
+    expect(findGroupMethodName(component)).toBeTruthy()
+    var withGarbage = sampleRecords().concat([
+      { type: 'garbage-1', checkinDate: '' },
+      { type: 'garbage-2' },
+      { type: 'garbage-3', checkinDate: 'not-a-date' }
+    ])
+    var groups = invokeGrouping(component, withGarbage)
+    var norm = groups.map(normalizeGroup)
+    norm.forEach(function (g) { expect(g.date).not.toBe('') })
+    var flat = []
+    norm.forEach(function (g) { flat = flat.concat(g.list) })
+    expect(flat.length).toBe(6)
+    // 全为无效记录 → 空分组
+    expect(invokeGrouping(component, [{ checkinDate: 'bad' }, { foo: 1 }]).length).toBe(0)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-3 | 结构级:模板按日期分组渲染 + 日期标题 + 空态(预期红)
+// ---------------------------------------------------------------------------
+
+describe('AC-3 结构级:模板按日期分组渲染与空态(变更B 验收口径:看到所有打卡记录 → 预期红)', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数
+    globalThis.__dayGroupViewStubs = {}
+    template = loadGrowthMain().template
+  })
+
+  it('RED-A8 模板存在「按日期分组」的记录循环渲染(v-for 数据源为 dateGroups/groupedRecords 等)', function () {
+    expect(template).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
+  })
+
+  it('RED-A9 模板存在日期分组标题渲染(分组键以 .date/.day 插值或 formatDateKey/formatRecordDate 输出)', function () {
+    expect(template).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
+    expect(template).toMatch(/(?:formatDateKey\s*\(|formatRecordDate\s*\(|\.[dp]ate\s*[}|]|\.[dg]ay\s*[}|]|\bgroupDate\b)/)
+  })
+
+  it('RED-A10 模板存在分组空态分支:集合为空时显示空态(空态文案或 length===0 条件 v-if)', function () {
+    var hasEmptyCopy = /暂无[\s\S]{0,10}记录|还没有[\s\S]{0,10}记录|暂无成长|暂无打卡/.test(template)
+    var hasEmptyBranch = /v-if\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*\.length\s*(?:===?)\s*0/.test(template)
+    expect(hasEmptyCopy || hasEmptyBranch).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为「家长/教师查看孩子成长与打卡历史」的成长主页按日期分组视图,
+// 页面在已登录态按 currentChildId 取数,无额外前端 role 门禁分支(role 校验在 JwtInterceptor 层),
+// 与同批 growthHistory.view.test.js 口径一致,显式记录为不适用项。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:成长主页按日期分组视图无前端 role 门禁分支,不适用', function () {
+  it('占位:该能力面向登录家长/教师,详见汇报', function () {})
+})

+ 318 - 0
cfc-frontend/__tests__/pages/growth-main/growthHistory.view.test.js

@@ -0,0 +1,318 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 growth.history.view(SC-P-95 / 变更B)
+ *
+ * 溯源:
+ *   requirement: tests/user-scenarios/应用场景总览.md SC-P-95
+ *                docs/需求分析/2026-11-06-成就成长打卡需求变更.md §变更B(成长记录→成长历史记录页)
+ *   design:      cfc-frontend/pages/growth-main/index.vue「今日成长」网格
+ *                cfc-frontend/utils/api.js getGrowthRecordList(~L1409,POST /api/growth/record/list)
+ *                healthCheckinList(~L2253,POST /api/health/checkin/list)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
+ *   且未安装 vue-jest/jsdom 组件环境 —— 既有约定为「抽取被测逻辑断言」而非挂载 .vue
+ *   (见 __tests__/components/FamilyRelationGraph.test.js,导入 shallowMount 但实际只测抽取函数;
+ *    本文件沿用 reference 风格 __tests__/family-join/join-form.required-info.test.js —— 直接加载真实
+ *    SFC 的 <script>/<template> 源码做结构/行为契约断言;纯 fs 读取,无渲染引擎)。
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(今日成长网格容器、历史按日期分组渲染)。
+ *
+ * 红/绿判定:
+ *   - 页面存在、今日成长网格、两个 API 封装(URL/POST 方法)——现状已合入 origin/cfclub → 绿(无回归锚点);
+ *   - 「成长历史记录按日期分组渲染」(变更B 验收口径:看到所有打卡记录,按日期倒序/分组)——
+ *     现状 growth-main/index.vue 仅渲染「今日成长」progressItems 网格,无任何按日期分组的
+ *     历史记录结构 → 红(契约缺口,即 RED 核心)。GREEN 实现方需在 growth-main 页面补足
+ *     下列命名契约(或对齐本文件断言):模板 v-for 数据源为 dateGroups/groupedRecords/
+ *     groupedCheckins/historyGroups/checkinGroups/recordGroups/dayGroups 之一,或 methods
+ *     (/computed)提供 groupByDate/groupRecordsByDate/groupCheckinsByDate/groupHistoryByDate。
+ *
+ * 本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { getGrowthRecordList as apiGetGrowthRecordList, healthCheckinList as apiHealthCheckinList, clearApiDedup } from '@/utils/api'
+
+const GROWTH_MAIN_PATH = path.join(__dirname, '../../../pages/growth-main/index.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 growth-main/index.vue 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__growthHistoryStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__growthHistoryStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadGrowthMain() {
+  var src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 growth-main/index.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__growthHistoryStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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] })
+  // 顶层生命周期钩子(onShow/onLoad 等)不在 methods 内,直接取自组件根对象
+  Object.keys(component).forEach(function (k) {
+    if (typeof component[k] === 'function' && vm[k] === undefined) vm[k] = component[k]
+  })
+  return vm
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.reLaunch.mockReset()
+  global.uni.request.mockReset()
+  // growth-main 的 <script> 会声明 9 个 API 依赖:只 stub 组件运行时真正调用的,
+  // 其余以空实现兜底,避免 eval 阶段缺名(var 未定义即可,方法体才使用)
+  stubs = {
+    healthCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getHealthMealList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getGrowthRecommendations: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { articles: [] } }) }),
+    getExerciseRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getSleepRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getEmotionCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    getTodayTasks: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    reportAppEnter: jest.fn(),
+    getGrowthRecordList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    parseDate: jest.fn(function (v) { return v ? new Date(String(v).replace(/-/g, '/')) : null }),
+    recordDateOf: jest.fn(function () { return '' }),
+    fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} },
+    shareMixin: {}
+  }
+  globalThis.__growthHistoryStubs = {
+    // 注意:growth-main/index.vue 的 import 使用相对路径(../../utils/api.js 等),桩键须与真实 import id 一致
+    '../../utils/api.js': {
+      healthCheckinList: stubs.healthCheckinList,
+      getHealthMealList: stubs.getHealthMealList,
+      getGrowthRecommendations: stubs.getGrowthRecommendations,
+      getExerciseRecords: stubs.getExerciseRecords,
+      getSleepRecords: stubs.getSleepRecords,
+      getEmotionCheckinList: stubs.getEmotionCheckinList,
+      getCheckinList: stubs.getCheckinList,
+      getTodayTasks: stubs.getTodayTasks,
+      reportAppEnter: stubs.reportAppEnter
+    },
+    '../../utils/format.js': { parseDate: stubs.parseDate, recordDateOf: stubs.recordDateOf },
+    '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin },
+    '../../components/share-mixin.js': { shareMixin: stubs.shareMixin },
+    '../../components/LoginGuideCard.vue': {},
+    '../../components/DimensionActivities.vue': {},
+    '../../components/DimensionProducts.vue': {},
+    '../../components/ArticleFeed.vue': {}
+  }
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__growthHistoryStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC_CONTRACT_1 | 页面存在 + 今日成长网格结构契约(现状锚点,预期绿)
+// ---------------------------------------------------------------------------
+
+describe('AC_CONTRACT_1 页面存在与今日成长网格结构(现状锚点)', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach 执行:仅做模板结构断言,无需桩函数,置空即可(loadGrowthMain 对桩做可选访问)
+    globalThis.__growthHistoryStubs = {}
+    template = loadGrowthMain().template
+  })
+
+  it('被测页面 growth-main/index.vue 存在且可解析(含 template/script 块)', function () {
+    expect(fs.existsSync(GROWTH_MAIN_PATH)).toBe(true)
+    expect(template.length).toBeGreaterThan(0)
+  })
+
+  it('今日成长区域容器存在(progress-card / progress-title)', function () {
+    expect(template).toMatch(/progress-card/)
+    expect(template).toMatch(/今日成长/)
+  })
+
+  it('今日成长网格容器存在(progress-grid),按 progressItems 渲染', function () {
+    expect(template).toMatch(/class="progress-grid"/)
+    expect(template).toMatch(/progressItems\.length > 0/)
+  })
+
+  it('网格渲染项存在:progress-tile v-for 循环 + :key + 点击处理器', function () {
+    expect(template).toMatch(/class="progress-tile"[^>]*v-for="\(item, idx\) in progressItems"/)
+    expect(template).toMatch(/:key="getProgressKey\(item\)"/)
+    expect(template).toMatch(/handleProgressClick\(idx\)/)
+  })
+
+  it('今日成长六项打卡(饮食/运动/睡眠/心情/记账 + 更多任务)为结构的一部分(无回归锚点)', function () {
+    expect(template).toMatch(/饮食/)
+    expect(template).toMatch(/运动/)
+    expect(template).toMatch(/睡眠/)
+    expect(template).toMatch(/心情/)
+    expect(template).toMatch(/记账/)
+    expect(template).toMatch(/更多任务/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC_CONTRACT_2 | 成长历史按日期分组渲染(变更B 验收口径:看到所有打卡记录、按日期分组)
+//                现状 growth-main/index.vue 仅渲染「今日成长」,无按日期分组结构 → 预期红(RED 核心)
+// ---------------------------------------------------------------------------
+
+describe('AC_CONTRACT_2 成长历史记录按日期分组渲染(变更B → 预期红)', function () {
+  var src
+  beforeAll(function () {
+    // 直接扫描原始 SFC 全文(template + script 原始文本):methods/computed 不能被序列化丢弃,
+    // 日期分组装配逻辑须在原始 <script> 源码中可见
+    src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
+  })
+
+  it('RED#1 模板存在「按日期分组」的记录循环渲染(如 v-for 于 dateGroups/groupedRecords/historyGroups 等)', function () {
+    // GREEN 实现契约:历史记录须以「日期分组集合」为 v-for 数据源渲染(dateGroups | groupedRecords |
+    // groupedCheckins | historyGroups | checkinGroups | recordGroups | dayGroups | growthHistoryGroups)
+    expect(src).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
+  })
+
+  it('RED#2 组件提供按日期分组的装配逻辑(methods/computed 存在 groupByDate 系方法)', function () {
+    // GREEN 实现契约:组件需提供把打卡/档案记录流按日期分组的装配入口
+    // (groupByDate | groupRecordsByDate | groupCheckinsByDate | groupHistoryByDate | groupedByDate)
+    expect(src).toMatch(/(?:groupByDate|groupRecordsByDate|groupCheckinsByDate|groupHistoryByDate|groupedByDate)\s*(?:\(|:)/i)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC_CONTRACT_3 | 行为级:真实组件 data()/methods —— 今日成长数据装配(现状锚点,预期绿)
+// ---------------------------------------------------------------------------
+
+describe('AC_CONTRACT_3 真实组件行为:今日成长数据装配(现状锚点)', function () {
+  var vm
+
+  beforeEach(function () {
+    var component = loadGrowthMain().component
+    vm = instantiate(component)
+  })
+
+  it('data 提供 progressItems 数组(今日成长网格数据源)', function () {
+    expect(Array.isArray(vm.progressItems)).toBe(true)
+    expect(vm.todayDate).toBe('')
+  })
+
+  it('onShow 设置 todayDate 为今日 yyyy-MM-dd 并调用 loadAllData(已登录态)', async function () {
+    global.uni.setStorageSync('token', 'T-1')
+    global.uni.setStorageSync('currentChildId', '88')
+    await vm.onShow()
+    expect(vm.todayDate).toMatch(/^\d{4}-\d{2}-\d{2}$/)
+    var now = new Date()
+    var pad = function (n) { return n < 10 ? '0' + n : '' + n }
+    expect(vm.todayDate).toBe(now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()))
+    expect(vm.isLoggedIn).toBe(true)
+    expect(stubs.reportAppEnter).toHaveBeenCalledWith('growth')
+  })
+
+  it('loadProgressItems 装配六项打卡(diet/exercise/sleep/emotion/checkin + 更多任务入口)', async function () {
+    await vm.loadProgressItems()
+    expect(stubs.getTodayTasks).toHaveBeenCalled()
+    expect(Array.isArray(vm.progressItems)).toBe(true)
+    var keys = vm.progressItems.map(function (it) { return it.key })
+    expect(keys).toEqual(expect.arrayContaining(['diet', 'exercise', 'sleep', 'emotion', 'checkin']))
+    expect(vm.progressItems.length).toBeGreaterThanOrEqual(5)
+  })
+
+  it('loadMilestones 通过 healthCheckinList 拉取连续打卡天数(限 30 天封顶;极致简单去重后仅产出进度类=连续打卡)', async function () {
+    stubs.healthCheckinList.mockResolvedValueOnce({ code: 200, message: 'ok', data: [1, 2, 3] })
+    await vm.loadMilestones()
+    expect(stubs.healthCheckinList).toHaveBeenCalled()
+    expect(vm.streakDays).toBe(3)
+    // 极致简单去重:里程碑 3 tile(连续打卡/进行中挑战/档案完整度)语义与首页 hero-dims、
+    // 「我的」achievement 重复 → 本页降级为「进度类单行」,仅保留连续打卡;进行中挑战归任务页、
+    // 档案完整度归「我的」页,本页不再产出这两个字段,杜绝跨页重复。
+    expect(vm.activeChallenges).toBeUndefined()
+    expect(vm.completeness).toBeUndefined()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC_CONTRACT_4 | 设计锚点:utils/api.js 封装契约(现状已合入,预期绿)
+//   getGrowthRecordList → POST /api/growth/record/list
+//   healthCheckinList   → POST /api/health/checkin/list
+// ---------------------------------------------------------------------------
+
+describe('AC_CONTRACT_4 设计锚点:api.js 封装 URL/方法契约', function () {
+  it('getGrowthRecordList 发起 POST /api/growth/record/list', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: [] } }) })
+    })
+    clearApiDedup()
+    await apiGetGrowthRecordList()
+    expect(captured.url).toContain('/api/growth/record/list')
+    expect(captured.method).toBe('POST')
+  })
+
+  it('healthCheckinList 发起 POST /api/health/checkin/list 并透传请求体', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: [] } }) })
+    })
+    clearApiDedup()
+    await apiHealthCheckinList({ memberId: 88, page: 1, size: 20 })
+    expect(captured.url).toContain('/api/health/checkin/list')
+    expect(captured.method).toBe('POST')
+    expect(captured.data).toEqual(expect.objectContaining({ memberId: 88, page: 1, size: 20 }))
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:本能力为「家长查看孩子成长/打卡历史」,页面在已登录态按 currentChildId 取数,
+// 无额外 role 门禁分支(role 校验在后端 JwtInterceptor 层),显式记录为不适用项。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:成长历史查看无前端 role 门禁分支,不适用', function () {
+  it('占位:该能力面向登录家长/教师查看成长记录,详见汇报', function () {})
+})

+ 214 - 0
cfc-frontend/__tests__/pages/health-main/healthMain.redesign.contract.test.js

@@ -0,0 +1,214 @@
+/**
+ * 契约级单测(TDD)—— 健康页重排「极致简单」(主行动 = 上传报告/测评)
+ *
+ * 溯源:
+ *   需求:team-lead 健康页重排目标结构(fae577b3b 品牌紫地基之上)——
+ *     ① 主行动 = 上传报告大入口 + 3 测评 + 健康阅卷,占首屏;
+ *     ② 内部 5 tab + 雷达保留(品牌锚点),雷达压缩让主行动进首屏;
+ *     ③ 游客态删营销残留:gh-demo 双雷达示例 + gh-wuxing 相生相克长文 → 紧凑五维速览 5 行;
+ *     ④ 健康阅卷 与 15 题自检 语义合并(各态单一问卷入口);
+ *     ⑤ 华为健康卡折叠为「数据来源」二级入口,不占首屏;
+ *     ⑥ 最近记录 / 健康方案 / 推荐阅读 预览 3→2;
+ *     ⑦ 痛点条压缩为一行。
+ *   设计:cfc-frontend/pages/health-main/index.vue(仅此 1 文件;禁碰其他三页 / Base* / api.js / pages.json)
+ *
+ * 说明:沿项目「源码静态契约」范式(对齐 __tests__/pages/index-home.quickCompleteOverdue.test.js),
+ * 只读真实源码断言结构,不 mount 巨型 index.vue。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/health-main/index.vue')
+
+function loadPage() {
+  const src = fs.readFileSync(PAGE_PATH, 'utf8')
+  const tplStart = src.indexOf('<template>')
+  const tplEnd = src.indexOf('</template>')
+  const scrStart = src.indexOf('<script>')
+  const scrEnd = src.indexOf('</script>')
+  const styStart = src.indexOf('<style')
+  const style = src.slice(styStart)
+  return {
+    src,
+    template: src.slice(tplStart, tplEnd),
+    script: src.slice(scrStart, scrEnd),
+    style
+  }
+}
+
+function count(haystack, needle) {
+  if (typeof haystack !== 'string') return 0
+  let n = 0
+  let i = haystack.indexOf(needle)
+  while (i !== -1) {
+    n += 1
+    i = haystack.indexOf(needle, i + needle.length)
+  }
+  return n
+}
+
+describe('healthMain.redesign:健康页极致简单主行动结构', function () {
+  let page
+  beforeAll(function () {
+    page = loadPage()
+  })
+
+  describe('① 主行动 = 上传报告 + 3 测评 + 健康阅卷(占首屏)', function () {
+    test('上传报告为采集区首位:upload-hero 出现在在线测评卡之前', function () {
+      const heroIdx = page.template.indexOf('class="upload-hero"')
+      const quizIdx = page.template.indexOf('data-card-assessment')
+      expect(heroIdx).toBeGreaterThanOrEqual(0)
+      expect(quizIdx).toBeGreaterThanOrEqual(0)
+      expect(heroIdx).toBeLessThan(quizIdx)
+    })
+
+    test('上传报告主行动复用 Base* 原语(BasePrimaryButton),未新造平行原语', function () {
+      expect(page.script.indexOf("import BasePrimaryButton from '../../components/BasePrimaryButton.vue'") >= 0).toBe(true)
+      expect(page.template.indexOf('<BasePrimaryButton') >= 0).toBe(true)
+      expect(page.template.indexOf('class="upload-hero-btn"') >= 0).toBe(true)
+      // 绿色 mat-green 的旧卡片组件已不再引入
+      expect(page.script.indexOf("report-upload-card.vue") >= 0).toBe(false)
+      expect(page.script.indexOf('ReportUploadCard') >= 0).toBe(false)
+    })
+
+    test('3 项测评保留为采集区主行动之一(quizzes v-for)', function () {
+      expect(page.template.indexOf('v-for="quiz in quizzes"') >= 0).toBe(true)
+      expect(page.script.indexOf("code: 'cognitive'") >= 0).toBe(true)
+      expect(page.script.indexOf("code: 'mental'") >= 0).toBe(true)
+      expect(page.script.indexOf("code: 'relationship'") >= 0).toBe(true)
+    })
+
+    test('健康阅卷保留为采集区入口(健康问卷入口)', function () {
+      expect(page.template.indexOf('@click="goHealthReview"') >= 0).toBe(true)
+    })
+  })
+
+  describe('② 5 tab + 雷达保留并压缩(品牌锚点)', function () {
+    test('内部 5 tab 导航保留', function () {
+      expect(page.template.indexOf('v-for="tab in tabs"') >= 0).toBe(true)
+      expect(page.script.indexOf("code: 'body'") >= 0).toBe(true)
+      expect(page.script.indexOf("code: 'mental'") >= 0).toBe(true)
+    })
+
+    test('雷达压缩到 400rpx(原 520),让主行动进首屏;访客示例雷达已删(模板仅 1 处 RadarChart)', function () {
+      expect(page.template.indexOf('height="400"') >= 0).toBe(true)
+      expect(page.template.indexOf('height="520"') >= 0).toBe(false)
+      expect(count(page.template, '<RadarChart')).toBe(1)
+    })
+  })
+
+  describe('③ 游客态删营销残留(双雷达示例 + 相生相克长文)', function () {
+    test('模板与样式均已删除 gh-demo 双雷达示例块', function () {
+      expect(page.template.indexOf('gh-demo') >= 0).toBe(false)
+      expect(page.style.indexOf('.gh-demo') >= 0).toBe(false)
+    })
+
+    test('双雷达示例的 script 支撑(guest*Dims/Scores、_guestRadarDims/_guestDemoScores)一并删除,不留死代码', function () {
+      ;['guestBodyDims', 'guestBodyScores', 'guestCogDims', 'guestCogScores', 'guestHasDemoConfig', '_guestRadarDims', '_guestDemoScores'].forEach(function (name) {
+        expect(page.script.indexOf(name)).toBe(-1)
+      })
+    })
+
+    test('相生相克长文(gh-rel / gh-chain / gh-node / gh-sep / gh-arrow)模板与样式一并删除', function () {
+      ;['gh-rel', 'gh-chain', 'gh-node', 'gh-sep', 'gh-arrow'].forEach(function (name) {
+        expect(page.template.indexOf(name)).toBe(-1)
+        expect(page.style.indexOf('.' + name)).toBe(-1)
+      })
+      // 营销长文文案一并消失
+      ;['相生 · 前进', '相克 · 平衡', '身克富', '健康孕育智慧', '莫以健康换金钱'].forEach(function (text) {
+        expect(page.template.indexOf(text)).toBe(-1)
+      })
+    })
+
+    test('改为紧凑五维速览:5 个维度入口 + 5 条维度详情路由保留', function () {
+      expect(count(page.template, 'gh-row-info')).toBe(5)
+      ;["/pages/body-detail/index", "/pages/wisdom-detail/index", "/pages/wealth/index", '/pages/action-detail/member-action-detail', '/pages/mind-detail/index'].forEach(function (route) {
+        expect(page.template.indexOf(route)).toBeGreaterThanOrEqual(0)
+      })
+    })
+
+    test('访客态不再拉取维度注册中心(示例雷达已删,接口调用一并移除)', function () {
+      // onShow 未登录分支不再调用 ensureDimensionRegistry
+      const onShowBody = page.script.slice(page.script.indexOf('onShow()'))
+      const guestBranch = onShowBody.slice(onShowBody.indexOf('} else {'))
+      expect(guestBranch.indexOf('ensureDimensionRegistry')).toBe(-1)
+    })
+
+    test('痛点条保留(主动健康理念共鸣点)但压缩为一行', function () {
+      expect(page.template.indexOf('gh-pain') >= 0).toBe(true)
+      expect(page.style.indexOf('.gh-pain { margin: 0 32rpx 24rpx; display: flex; flex-direction: row; flex-wrap: wrap; align-items: baseline; padding: 18rpx 24rpx;') >= 0).toBe(true)
+    })
+
+    test('游客态保留:15 题自检 CTA + 待填调研 + 登录引导', function () {
+      expect(page.template.indexOf('15 题五维健康自检') >= 0).toBe(true)
+      expect(page.template.indexOf('v-for="(item, si) in pendingSurveys"') >= 0).toBe(true)
+      expect(page.template.indexOf('<LoginGuideCard') >= 0).toBe(true)
+    })
+  })
+
+  describe('④ 健康阅卷 与 15 题自检 合并为各态单一问卷入口', function () {
+    test('全页仅 2 个 health-survey 入口:游客态 15 题自检 + 登录态健康阅卷(不重复)', function () {
+      expect(count(page.script, '/pages/health/health-survey')).toBe(2)
+      expect(count(page.script, '_pendingSurveyUrl = url')).toBe(2)
+    })
+
+    test('模板未同时出现两个问卷入口(登录态 1 个 goHealthReview、访客态 1 个 goSelfTest)', function () {
+      expect(count(page.template, 'goHealthReview')).toBe(1)
+      expect(count(page.template, 'goSelfTest')).toBe(1)
+    })
+  })
+
+  describe('⑤ 华为健康卡折叠为「数据来源」二级入口(不占首屏)', function () {
+    test('模板不再有独立「运动手环 · 华为健康」卡(改为折叠数据来源行)', function () {
+      expect(page.template.indexOf('运动手环 · 华为健康')).toBe(-1)
+      expect(page.template.indexOf('class="data-card-actions"')).toBe(-1)
+      expect(page.template.indexOf('class="data-card-syncing"')).toBe(-1)
+    })
+
+    test('数据来源默认收起(dataSourceOpen 初始 false)+ 折叠开关,绑定/同步/撤销能力保留', function () {
+      expect(page.script.indexOf('dataSourceOpen: false') >= 0).toBe(true)
+      expect(page.script.indexOf('toggleDataSource: function() { this.dataSourceOpen = !this.dataSourceOpen }') >= 0).toBe(true)
+      expect(page.template.indexOf('v-if="dataSourceOpen"') >= 0).toBe(true)
+      ;['bindHuawei', 'syncHuawei', 'revokeHuawei'].forEach(function (fn) {
+        expect(page.template.indexOf(fn)).toBeGreaterThanOrEqual(0)
+      })
+    })
+
+    test('旧卡扩展样式 .data-card-actions / .data-card-syncing 一并删除', function () {
+      expect(page.style.indexOf('.data-card-actions')).toBe(-1)
+      expect(page.style.indexOf('.data-card-syncing')).toBe(-1)
+    })
+  })
+
+  describe('⑥ 预览条数 3→2(最近记录 / 推荐阅读)', function () {
+    test('最近记录只展示 2 条(模板 slice + 接口 size 同步压缩)', function () {
+      expect(page.template.indexOf('reports.slice(0, 2)') >= 0).toBe(true)
+      expect(page.template.indexOf('reports.slice(0, 3)')).toBe(-1)
+      expect(page.script.indexOf("getReportList('', 2)") >= 0).toBe(true)
+    })
+
+    test('推荐阅读只展示 2 条', function () {
+      expect(page.script.indexOf("getFeaturedArticles({ size: 2") >= 0).toBe(true)
+      expect(page.script.indexOf('list.slice(0, 2)') >= 0).toBe(true)
+      expect(page.script.indexOf('list.slice(0, 3)')).toBe(-1)
+    })
+  })
+
+  describe('工程硬约束', function () {
+    test('无可选链 ?./无 CSS Grid;:key 无表达式;不引其他三页共享原语之外的新组件', function () {
+      expect(/[\S]\?\.|\?\./.test(page.script)).toBe(false)
+      expect(/display:\s*grid/.test(page.style)).toBe(false)
+      const keys = page.template.match(/:key="([^"]+)"/g) || []
+      keys.forEach(function (k) {
+        expect(/[\+\-\*\/\(\)]/.test(k)).toBe(false)
+      })
+    })
+
+    test('华为健康 mock 角标 + 摘要文案保留(合规说明)', function () {
+      expect(page.template.indexOf('data-card-badge') >= 0).toBe(true)
+      expect(page.script.indexOf('huaweiSourceText') >= 0).toBe(true)
+      // 未绑定态用途说明仍覆盖 6 项数据(步数/距离/心率/睡眠/体重/身高)
+      expect(page.script.indexOf('步数/距离/心率/睡眠/体重/身高') >= 0).toBe(true)
+    })
+  })
+})

+ 411 - 0
cfc-frontend/__tests__/pages/health/aiyunyi.detectPage.contract.test.js

@@ -0,0 +1,411 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.detectPage
+ *
+ * 溯源:
+ *   requirement: docs/2026-11-24-爱云医AI检测接入方案.md
+ *                §4.2(pages/health/ai-detect/index.vue 新增、识别流程:
+ *                      选检测人 → 选素材 → 上传 → 进度轮询 → 结果跳转)、
+ *                §8「前端验收」第 2 条(相机/图库/微信三来源均可上传;进度面板显示「识别中」;
+ *                      完成后跳报告详情)与第 4 条(未开通/次数用完/网络失败均明确提示,
+ *                      不白屏、不崩溃)、§5(照片路径时序)
+ *   design:      docs/2026-11-24-爱云医AI检测接入方案.md §4.2 / §4.5 / §5
+ *                素材选择复用 utils/image-picker.js 的 pickImage + chooseMessageFile;
+ *                检测人选择与声明勾选复用 report-upload 现有逻辑;
+ *                调用 utils/api.js 的 aiyunyi.* 封装(POST /api/aiyunyi/**)
+ *
+ * 说明(既有 Jest 体系约束,风格对齐 __tests__/family-join/join-form.required-info.test.js):
+ *   cfc-frontend jest.config.js 的 testEnvironment=node,无 vue-jest/jsdom 组件环境。
+ *   既有约定为「直接加载真实 SFC 源码做断言」而非挂载 .vue:
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *     - <template>:读取模板文本,做结构契约断言。
+ *
+ * 当前状态:ai-detect 页面、api.js 的 aiyunyi.* 封装、pages.json 路由、report-upload
+ *   的「AI 快速识别」入口卡片均未落地 → 预期 RED。GREEN 阶段按本文件锚定的契约
+ *   补足实现后断言应可翻绿。本文件只新增 __tests__ 下的测试,不修改任何 src/main 实现。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// __tests__/pages/health → ../../.. = cfc-frontend 根目录
+const ROOT = path.join(__dirname, '../../..')
+
+const REPORT_UPLOAD_PATH = path.join(ROOT, 'pages/health/report-upload.vue')
+const DETECT_CANDIDATES = [
+  path.join(ROOT, 'pages/health/ai-detect/index.vue'),
+  path.join(ROOT, 'pages/health/ai-detect.vue')
+]
+const CANONICAL_DETECT_PATH = DETECT_CANDIDATES[0]
+const API_PATH = path.join(ROOT, 'utils/api.js')
+const PAGES_JSON_PATH = path.join(ROOT, 'pages.json')
+
+/** 识别流程页文件:优先 index.vue,其次 ai-detect.vue;都缺失时返回 null(主 RED 信号) */
+function resolveDetectPagePath() {
+  for (var i = 0; i < DETECT_CANDIDATES.length; i++) {
+    if (fs.existsSync(DETECT_CANDIDATES[i])) return DETECT_CANDIDATES[i]
+  }
+  return null
+}
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC(行为级 <script> + 结构级 <template>),风格对齐 family-join
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 改为从 globalThis[stubKey] 取桩(不解析模块,避免污染业务实现) */
+function stubImports(script, moduleStubs, stubKey) {
+  globalThis[stubKey] = moduleStubs
+  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[' + JSON.stringify(stubKey) + '][' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 通用 SFC 加载器:文件缺失时抛明确错误(GREEN 未交付的 RED 信号) */
+function makeSfcLoader(stubKey, getStubs) {
+  return function loadSfc(filePath) {
+    if (!filePath || !fs.existsSync(filePath)) {
+      throw new Error('实现未落地(GREEN 未交付),找不到 SFC:' + (filePath || CANONICAL_DETECT_PATH))
+    }
+    var src = fs.readFileSync(filePath, 'utf8')
+    var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+    var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+    if (!scriptMatch) throw new Error('无法定位 <script> 块:' + filePath)
+    var script = stubImports(scriptMatch[1], getStubs(), stubKey)
+    script = script.replace(/export default\s*\{/, 'module.exports = {')
+    var mod = { exports: {} }
+    // eslint-disable-next-line no-new-func
+    new Function('module', 'exports', script)(mod, mod.exports)
+    return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '', source: src }
+  }
+}
+
+/** 模拟 Vue 合并 data 与 methods 到实例 */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具:为 GREEN 阶段可能存在的 import 预留桩(缺失时按可选访问处理)
+// ---------------------------------------------------------------------------
+
+var apiSpy
+var pickImageStub
+var stubs
+
+function buildModuleStubs() {
+  // api.js 用 Proxy:GREEN 实现无论把 AI 检测封装命名成 aiyunyiDetect / detect /
+  // enterData / listProducts ...,都汇聚到同一个 spy,便于统一断言「已调用 AI 检测封装」。
+  apiSpy = jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: {} }) })
+  var memberListStub = jest.fn(function () {
+    return Promise.resolve({ code: 200, message: 'ok', data: [{ id: 1, nickname: '爸爸', userId: 10 }] })
+  })
+  var apiModule = new Proxy({}, {
+    get: function (target, prop) {
+      if (prop === '__spy') return apiSpy
+      if (typeof prop === 'symbol') return undefined
+      if (/member|family/i.test(String(prop))) return memberListStub
+      return apiSpy
+    }
+  })
+
+  pickImageStub = jest.fn(function (opts) {
+    if (opts && typeof opts.success === 'function') {
+      opts.success({
+        tempFilePaths: ['/tmp/ai-detect-a.png'],
+        tempFiles: [{ path: '/tmp/ai-detect-a.png', size: 100 }]
+      })
+    }
+  })
+
+  stubs = {
+    apiModule: apiModule,
+    pickImageStub: pickImageStub,
+    moduleStubs: {
+      '@/utils/api.js': apiModule,
+      '../../utils/api.js': apiModule,
+      '@/utils/image-picker.js': { pickImage: pickImageStub },
+      '../../utils/image-picker.js': { pickImage: pickImageStub },
+      '@/utils/memberNormalize.js': {
+        normalizeMembers: function (list) { return list instanceof Array ? list : [] },
+        memberIdOf: function (m) { return m && (m.id || m.memberId) }
+      },
+      '@/mixins/font-scale.js': {
+        fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+      }
+    }
+  }
+  return stubs.moduleStubs
+}
+
+var loadReportUpload = makeSfcLoader('__aiyunyiDetectReportUploadStubs', buildModuleStubs)
+var loadDetectPage = makeSfcLoader('__aiyunyiDetectPageStubs', buildModuleStubs)
+
+beforeEach(function () {
+  global.uni._storage = {}
+  ;['showToast', 'showModal', 'showLoading', 'hideLoading', 'navigateTo', 'redirectTo',
+    'showActionSheet', 'request'].forEach(function (k) {
+    if (global.uni[k] && global.uni[k].mockReset) global.uni[k].mockReset()
+  })
+  // 微信选图/选聊天文件(setUp 默认未注入,测试内补齐)
+  global.uni.chooseMessageFile = jest.fn(function (opts) {
+    if (opts && typeof opts.success === 'function') {
+      opts.success({ tempFiles: [{ path: '/tmp/ai-detect-chat.png', name: 'chat.png', size: 100 }] })
+    }
+  })
+  global.uni.showActionSheet = jest.fn(function (opts) {
+    if (opts && typeof opts.success === 'function') opts.success({ tapIndex: 0 })
+  })
+  buildModuleStubs()
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__aiyunyiDetectReportUploadStubs
+  delete globalThis.__aiyunyiDetectPageStubs
+})
+
+// ===========================================================================
+// AC-R0 识别流程页文件存在性(本能力 TDD-RED 主红信号:实现未落地 → 文件缺失)
+// ===========================================================================
+
+describe('AC-R0 识别流程页文件存在性契约', function () {
+  it('pages/health/ai-detect/index.vue(或 ai-detect.vue)必须存在', function () {
+    expect(resolveDetectPagePath()).not.toBeNull()
+  })
+})
+
+// ===========================================================================
+// AC-R1 report-upload 入口:第三张卡片「AI 快速识别」→ 跳转识别流程页
+// ===========================================================================
+
+describe('AC-R1 report-upload 新增「AI 快速识别」入口卡片', function () {
+  var sfc
+
+  beforeEach(function () {
+    sfc = loadReportUpload(REPORT_UPLOAD_PATH)
+  })
+
+  it('模板出现「AI 快速识别」卡片并绑定 startAiDetect', function () {
+    expect(sfc.template).toMatch(/AI\s*快速识别/)
+    expect(sfc.template).toMatch(/@click\s*=\s*["']startAiDetect["']/)
+  })
+
+  it('定义 startAiDetect 方法并跳转到识别流程页', function () {
+    var vm = instantiate(sfc.component)
+    expect(typeof vm.startAiDetect).toBe('function')
+    vm.startAiDetect()
+    expect(global.uni.navigateTo).toHaveBeenCalled()
+    var url = (global.uni.navigateTo.mock.calls[0][0] || {}).url || ''
+    expect(url).toMatch(/ai-detect/)
+  })
+})
+
+// ===========================================================================
+// AC-R2 utils/api.js 的 aiyunyi.* 封装契约(§4.2 / §5 的 POST /api/aiyunyi/**)
+// ===========================================================================
+
+describe('AC-R2 utils/api.js aiyunyi.* 封装契约', function () {
+  var apiSrc
+
+  beforeAll(function () {
+    apiSrc = fs.readFileSync(API_PATH, 'utf8')
+  })
+
+  it('存在后端代理路由 /api/aiyunyi/ 的封装', function () {
+    expect(apiSrc.indexOf('/api/aiyunyi/')).toBeGreaterThanOrEqual(0)
+  })
+
+  it('导出 AI 检测相关封装(aiyunyi.* / detect)', function () {
+    expect(apiSrc.search(/export\s+(?:const|function)\s+\w*(?:aiyunyi|detect)\w*/i)).toBeGreaterThanOrEqual(0)
+  })
+})
+
+// ===========================================================================
+// AC-R3 pages.json 注册识别流程页 / 报告详情页路由(§4.2 改动清单)
+// ===========================================================================
+
+describe('AC-R3 pages.json 路由注册契约', function () {
+  var pagesSrc
+
+  beforeAll(function () {
+    pagesSrc = fs.readFileSync(PAGES_JSON_PATH, 'utf8')
+  })
+
+  it('注册 ai-detect 识别流程页路由', function () {
+    expect(pagesSrc.indexOf('ai-detect')).toBeGreaterThanOrEqual(0)
+  })
+
+  it('注册 ai-report-detail 报告详情页路由(完成后的跳转目标)', function () {
+    expect(pagesSrc.indexOf('ai-report-detail')).toBeGreaterThanOrEqual(0)
+  })
+})
+
+// ===========================================================================
+// AC-R4 识别流程页 <template> 结构契约(§8 前端验收第 2/4 条)
+// ===========================================================================
+
+describe('AC-R4 识别流程页 <template> 结构契约', function () {
+  var sfc
+
+  beforeEach(function () {
+    sfc = loadDetectPage(resolveDetectPagePath())
+  })
+
+  it('提供三种照片来源入口:拍照 / 图库 / 微信聊天', function () {
+    expect(sfc.template).toMatch(/拍照|相机/)
+    expect(sfc.template).toMatch(/相册|图库/)
+    expect(sfc.template).toMatch(/聊天|微信/)
+  })
+
+  it('进度面板显示「识别中」', function () {
+    expect(sfc.template).toMatch(/识别中/)
+  })
+
+  it('包含检测人选择与声明勾选(复用 report-upload 逻辑)', function () {
+    expect(sfc.template).toMatch(/成员|检测人/)
+    expect(sfc.template).toMatch(/声明|同意/)
+  })
+
+  it('错误分支展示明确提示文案(未开通 / 次数用完 / 网络失败)', function () {
+    expect(sfc.template).toMatch(/未开通|尚未开通|开通/)
+    expect(sfc.template).toMatch(/次数|用完|购买/)
+  })
+})
+
+// ===========================================================================
+// AC-R5 识别流程页 <script> 行为契约(§4.2 流程 / §4.5 错误处理与降级)
+// ===========================================================================
+
+describe('AC-R5 识别流程页 <script> 行为契约', function () {
+  var component
+  var detectPath
+
+  beforeEach(function () {
+    detectPath = resolveDetectPagePath()
+    component = loadDetectPage(detectPath).component
+  })
+
+  it('声明流程所需 data 字段(成员 / 声明 / 素材 / 进度文案 / 错误 / 报告 id)', function () {
+    var vm = instantiate(component)
+    expect(vm.memberId).toBeDefined()
+    expect(vm.agreedToTerms).toBeDefined()
+    expect(vm.photos).toBeDefined()
+    expect(vm.progressText).toBeDefined()
+    expect(vm.errorMessage).toBeDefined()
+    expect(vm.reportId).toBeDefined()
+  })
+
+  it('未选成员 / 未勾声明 → 拦截并提示,不发起 AI 检测请求', async function () {
+    var vm = instantiate(component)
+    expect(typeof vm.startDetect).toBe('function')
+    vm.memberId = null
+    vm.agreedToTerms = false
+    await vm.startDetect()
+    expect(global.uni.showToast).toHaveBeenCalled()
+    expect(apiSpy).not.toHaveBeenCalled()
+  })
+
+  it('选素材:拍照/图库走 pickImage(sourceType 含 camera/album),微信来源走 chooseMessageFile', function () {
+    var vm = instantiate(component)
+    expect(typeof vm.choosePhoto).toBe('function')
+    expect(typeof vm.chooseFromChat).toBe('function')
+    vm.choosePhoto()
+    expect(pickImageStub).toHaveBeenCalled()
+    var sourceType = (pickImageStub.mock.calls[0][0] || {}).sourceType || []
+    expect(sourceType).toEqual(expect.arrayContaining(['camera', 'album']))
+    vm.chooseFromChat()
+    expect(global.uni.chooseMessageFile).toHaveBeenCalled()
+  })
+
+  it('合法提交调用 aiyunyi.* AI 检测封装', async function () {
+    var vm = instantiate(component)
+    vm.memberId = 1
+    vm.agreedToTerms = true
+    vm.photos = ['/tmp/ai-detect-a.png']
+    await vm.startDetect()
+    await Promise.resolve()
+    expect(apiSpy).toHaveBeenCalled()
+  })
+
+  it('脚本使用 4s 轮询节奏、维护「识别中」状态并在完成后跳报告详情', function () {
+    var src = fs.readFileSync(detectPath, 'utf8')
+    expect(src.search(/4000|4\s*\*\s*1000/)).toBeGreaterThanOrEqual(0)
+    expect(src.indexOf('识别中')).toBeGreaterThanOrEqual(0)
+    expect(src.search(/ai-report-detail|report-detail/)).toBeGreaterThanOrEqual(0)
+  })
+
+  async function messagesAfterFailure(vm, rejection) {
+    apiSpy.mockReset()
+    apiSpy.mockImplementation(function () { return Promise.reject(rejection) })
+    global.uni.showToast.mockReset()
+    global.uni.showModal.mockReset()
+    await vm.startDetect()
+    await Promise.resolve()
+    var msgs = []
+    global.uni.showToast.mock.calls.forEach(function (c) { msgs.push((c[0] && c[0].title) || '') })
+    global.uni.showModal.mock.calls.forEach(function (c) { msgs.push(JSON.stringify(c[0] || {})) })
+    return msgs.join(' ')
+  }
+
+  it('缺商品/未配置 → 明确提示「服务未开通」,不白屏不崩溃', async function () {
+    var vm = instantiate(component)
+    vm.memberId = 1
+    vm.agreedToTerms = true
+    vm.photos = ['/tmp/ai-detect-a.png']
+    var msgs = await messagesAfterFailure(vm, { code: 'NO_PRODUCT', message: '该服务尚未开通' })
+    expect(msgs).toMatch(/未开通|开通/)
+  })
+
+  it('无可用子项 → 明确提示「次数用完」,不白屏不崩溃', async function () {
+    var vm = instantiate(component)
+    vm.memberId = 1
+    vm.agreedToTerms = true
+    vm.photos = ['/tmp/ai-detect-a.png']
+    var msgs = await messagesAfterFailure(vm, { code: 'NO_ITEM', message: '检测次数已用完,请重新购买' })
+    expect(msgs).toMatch(/次数|用完|购买/)
+  })
+
+  it('网络失败 → 明确提示,不白屏不崩溃', async function () {
+    var vm = instantiate(component)
+    vm.memberId = 1
+    vm.agreedToTerms = true
+    vm.photos = ['/tmp/ai-detect-a.png']
+    var msgs = await messagesAfterFailure(vm, new Error('network error'))
+    expect(msgs).toMatch(/网络|失败|重试/)
+  })
+})
+
+// ===========================================================================
+// 权限流:识别流程入口复用 report-upload 的成员选择 + 声明勾选,无角色门禁分支(不适用项)
+// ===========================================================================
+
+describe.skip('权限流:ai.aiyunyi.detectPage 无角色门禁,不适用', function () {
+  it('占位:该能力复用成员归属与声明勾选校验,无 role 分支(详见汇报)', function () {})
+})

+ 403 - 0
cfc-frontend/__tests__/pages/health/aiyunyi.reportDetail.contract.test.js

@@ -0,0 +1,403 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.reportDetail(任务 S-cfc-457)
+ *
+ * 溯源:
+ *   requirement: docs/2026-11-24-爱云医AI检测接入方案.md
+ *                §4.2(新增 pages/health/ai-report-detail.vue:爱云医报告结果展示,
+ *                      一期按爱云医原始结构渲染,二期再映射五维)、
+ *                §8「前端验收」第 2 条(选素材上传 → 进度面板「识别中」→ 完成后跳报告详情)
+ *   design:      docs/2026-11-24-爱云医AI检测接入方案.md
+ *                §4.2(原始结构渲染,二期映射五维;utils/api.js 新增 aiyunyi.getReport 封装)、
+ *                §4.5(R3:报告分页接口缺陷 1011011002 → 报告只走 report/get 按 id 拉取,
+ *                      报告 id 从套餐用户信息/映射表取,不走 report/page)、
+ *                附录 A.6(report/get 响应 data.reportDiseaseRespList[].diseaseDetailList[]:
+ *                         diseaseDetailName/Cn、accuracy、diseaseLevel;accuracy 空 → 参考值提示,
+ *                         diseaseLevel 空 → 「未检出」,不要自行填 0)
+ *
+ * 说明(既有 Jest 体系约束,风格对齐 __tests__/family-join/join-form.required-info.test.js
+ *   与同批已合入 RED 用例 __tests__/pages/health/aiyunyi.detectPage.contract.test.js):
+ *   - jest.config.js testEnvironment=node,无 vue-jest/jsdom 组件环境;既有约定为
+ *     「直接加载真实 SFC 源码做断言」:<script> 注入桩求值取 data()/methods 做行为断言,
+ *     <template> 取模板文本做结构断言。
+ *   - 当前状态:ai-report-detail.vue、pages.json 路由、api.js 的 aiyunyi.getReport 均未落地
+ *     → 预期 RED。GREEN 阶段按本文件锚定的契约补足实现后断言应可翻绿。
+ *   - 本文件只新增 __tests__ 下的测试,不修改任何 pages/、utils/ 业务实现。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// __tests__/pages/health → ../../.. = cfc-frontend 根目录
+const ROOT = path.join(__dirname, '../../..')
+
+const DETAIL_PATH = path.join(ROOT, 'pages/health/ai-report-detail.vue')
+const API_PATH = path.join(ROOT, 'utils/api.js')
+const PAGES_JSON_PATH = path.join(ROOT, 'pages.json')
+
+/** 缺失实现时返回空源:后续断言按「契约缺失」失败(RED),避免 hook 抛错噪音;AC-R0 单独断言文件存在 */
+function readDetailSource() {
+  if (!fs.existsSync(DETAIL_PATH)) return ''
+  return fs.readFileSync(DETAIL_PATH, 'utf8')
+}
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC(行为级 <script> + 结构级 <template>),风格对齐 family-join
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 改为从 globalThis[stubKey] 取桩(不解析模块,避免污染业务实现) */
+function stubImports(script, moduleStubs, stubKey) {
+  globalThis[stubKey] = moduleStubs
+  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[' + JSON.stringify(stubKey) + '][' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 通用 SFC 加载器 */
+function makeSfcLoader(stubKey, getStubs) {
+  return function loadSfc(filePath) {
+    var src = readDetailSource()
+    var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+    var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+    // 实现未落地时返回空组件/空模板,让各用例以「契约缺失」失败(RED),而非 hook 抛错
+    if (!scriptMatch) return { component: {}, template: '', source: src }
+    var script = stubImports(scriptMatch[1], getStubs(), stubKey)
+    script = script.replace(/export default\s*\{/, 'module.exports = {')
+    var mod = { exports: {} }
+    // eslint-disable-next-line no-new-func
+    new Function('module', 'exports', script)(mod, mod.exports)
+    return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '', source: src }
+  }
+}
+
+/** 模拟 Vue 合并 data 与 methods 到实例 */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 报告原始结构夹具(附录 A.6) */
+var RAW_REPORT = {
+  reportDiseaseRespList: [
+    {
+      diseaseName: '心血管风险',
+      diseaseDetailList: [
+        { diseaseDetailName: 'CRP', diseaseDetailNameCn: 'C反应蛋白', accuracy: '8.2', diseaseLevel: '偏高' },
+        { diseaseDetailName: 'HDL', diseaseDetailNameCn: '高密度脂蛋白', accuracy: '', diseaseLevel: '' }
+      ]
+    }
+  ]
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具:为 GREEN 阶段可能存在的 import 预留桩;getReport 与 report/page 分开计数
+// ---------------------------------------------------------------------------
+
+var getReportSpy
+var reportPageSpy
+var genericApiSpy
+
+function buildModuleStubs() {
+  var ok = function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }
+  getReportSpy = jest.fn(ok)
+  reportPageSpy = jest.fn(ok)
+  genericApiSpy = jest.fn(ok)
+
+  function spyForName(name) {
+    name = String(name)
+    // §4.5 R3:任何 report/page / report/list / report/summary 类调用都是「不走 report/get」的错误分支
+    if (/report/i.test(name) && /page|list|summary/i.test(name)) return reportPageSpy
+    if (/report/i.test(name)) return getReportSpy
+    return genericApiSpy
+  }
+
+  // 命名空间:aiyunyi.getReport(id);同时兼容 aiyunyiGetReport / 平铺 getReport
+  var aiyunyiNamespace = new Proxy({}, {
+    get: function (target, prop) {
+      if (typeof prop === 'symbol') return undefined
+      return spyForName(prop)
+    }
+  })
+  var apiModule = new Proxy({}, {
+    get: function (target, prop) {
+      if (typeof prop === 'symbol') return undefined
+      if (prop === 'aiyunyi') return aiyunyiNamespace
+      return spyForName(prop)
+    }
+  })
+
+  return {
+    '@/utils/api.js': apiModule,
+    '../../utils/api.js': apiModule,
+    '@/utils/format.js': { formatDate: function (v) { return v ? String(v).substring(0, 10) : '' } },
+    '@/mixins/font-scale.js': {
+      fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+    }
+  }
+}
+
+var loadDetail = makeSfcLoader('__aiyunyiReportDetailStubs', buildModuleStubs)
+
+/** 等待 Promise.then 链落定(微任务) */
+function flush() {
+  return new Promise(function (resolve) { process.nextTick(resolve) })
+}
+
+/** 汇总页面上「用户可见」的提示文案:组件状态 + toast + modal */
+function visibleMessage(vm) {
+  var parts = []
+  ;['emptyText', 'errorMessage', 'errorText', 'statusText', 'generatingText', 'message', 'hint'].forEach(function (k) {
+    if (vm[k]) parts.push(String(vm[k]))
+  })
+  global.uni.showToast.mock.calls.forEach(function (c) { parts.push((c[0] && c[0].title) || '') })
+  global.uni.showModal.mock.calls.forEach(function (c) { parts.push(JSON.stringify(c[0] || {})) })
+  return parts.join(' ')
+}
+
+beforeEach(function () {
+  global.uni._storage = {}
+  ;['showToast', 'showModal', 'showLoading', 'hideLoading', 'navigateTo', 'redirectTo', 'request'].forEach(function (k) {
+    if (global.uni[k] && global.uni[k].mockReset) global.uni[k].mockReset()
+  })
+  buildModuleStubs()
+})
+
+afterEach(function () {
+  delete globalThis.__aiyunyiReportDetailStubs
+})
+
+// ===========================================================================
+// AC-R0 报告详情页文件存在性(本能力 TDD-RED 主红信号:实现未落地 → 文件缺失)
+// ===========================================================================
+
+describe('AC-R0 报告详情页文件存在性契约', function () {
+  it('pages/health/ai-report-detail.vue 必须存在(§4.2 新增页面)', function () {
+    expect(fs.existsSync(DETAIL_PATH)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R1 pages.json 路由注册(§4.2:完成后跳转报告详情)
+// ===========================================================================
+
+describe('AC-R1 pages.json 报告详情页路由注册', function () {
+  var pagesSrc
+
+  beforeAll(function () {
+    pagesSrc = fs.readFileSync(PAGES_JSON_PATH, 'utf8')
+  })
+
+  it('注册 ai-report-detail 路由(跳转目标可达,不白屏)', function () {
+    expect(/"path"\s*:\s*"ai-report-detail"/.test(pagesSrc)).toBe(true)
+  })
+
+  it('报告详情页配置 navigationBarTitleText(页面标题规范)', function () {
+    expect(/ai-report-detail[\s\S]{0,200}navigationBarTitleText/.test(pagesSrc)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R2 <script> 行为契约:onLoad 按 id 走 aiyunyi.getReport(§4.5 R3 / 附录 A.6)
+// ===========================================================================
+
+describe('AC-R2 报告详情页 <script> 行为契约', function () {
+  var component
+
+  beforeEach(function () {
+    component = loadDetail(DETAIL_PATH).component
+  })
+
+  it('声明报告原始结构 / 加载 / 错误等状态字段', function () {
+    var vm = instantiate(component)
+    expect(vm.reportId).toBeDefined()
+    expect(vm.report).toBeDefined()
+    expect(vm.reportDiseaseRespList).toBeDefined()
+    expect(vm.loading).toBeDefined()
+    expect(vm.errorMessage).toBeDefined()
+  })
+
+  it('onLoad(options) 取报告 id 并调用 aiyunyi.getReport(id),不走 report/page', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: RAW_REPORT })
+    var vm = instantiate(component)
+    expect(typeof vm.onLoad).toBe('function')
+    vm.onLoad({ id: 987 })
+    await flush()
+    expect(getReportSpy).toHaveBeenCalledWith(987)
+    expect(reportPageSpy).not.toHaveBeenCalled()
+  })
+
+  it('报告原始结构 reportDiseaseRespList 写入组件状态(一期按原始结构渲染)', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: RAW_REPORT })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(vm.reportDiseaseRespList).toEqual(RAW_REPORT.reportDiseaseRespList)
+  })
+
+  it('空数据(data 无报告指标)→ 明确「暂无」提示,不白屏', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: { reportDiseaseRespList: [] } })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/暂无|没有数据|无数据|空/)
+  })
+
+  it('生成中(data.status=GENERATING)→ 明确「生成中」提示', async function () {
+    getReportSpy.mockResolvedValue({
+      code: 200, message: 'ok', data: { status: 'GENERATING', statusText: '报告生成中' }
+    })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/生成中/)
+  })
+
+  it('加载失败(getReport 拒绝)→ 明确「失败/重试」提示,不白屏不崩溃', async function () {
+    getReportSpy.mockRejectedValue(new Error('network error'))
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/失败|网络|重试/)
+  })
+
+  it('缺少报告 id(options 无 id)→ 拦截并提示,不发 getReport 请求', async function () {
+    var vm = instantiate(component)
+    vm.onLoad({})
+    await flush()
+    expect(getReportSpy).not.toHaveBeenCalled()
+    expect(visibleMessage(vm)).toMatch(/报告|参数|不存在|无效/)
+  })
+})
+
+// ===========================================================================
+// AC-R3 <template> 结构契约:附录 A.6 原始指标渲染 + 空值规则 + 三分支提示
+// ===========================================================================
+
+describe('AC-R3 报告详情页 <template> 结构契约', function () {
+  var template
+
+  beforeAll(function () {
+    buildModuleStubs()
+    template = loadDetail(DETAIL_PATH).template
+  })
+
+  it('遍历原始结构 reportDiseaseRespList → diseaseDetailList', function () {
+    expect(/reportDiseaseRespList/.test(template)).toBe(true)
+    expect(/diseaseDetailList/.test(template)).toBe(true)
+  })
+
+  it('渲染原始指标字段 diseaseDetailName(Cn) / accuracy / diseaseLevel', function () {
+    expect(/diseaseDetailNameCn|diseaseDetailName/.test(template)).toBe(true)
+    expect(/accuracy/.test(template)).toBe(true)
+    expect(/diseaseLevel/.test(template)).toBe(true)
+  })
+
+  it('附录 A.6 空值规则:diseaseLevel 空 → 「未检出」', function () {
+    expect(/未检出/.test(template)).toBe(true)
+  })
+
+  it('附录 A.6 空值规则:accuracy 空 → 参考值提示(不自行填 0)', function () {
+    expect(/参考/.test(template)).toBe(true)
+  })
+
+  it('空数据分支:模板含「暂无/无数据」提示', function () {
+    expect(/暂无|没有数据|无数据|空/.test(template)).toBe(true)
+  })
+
+  it('生成中分支:模板含「生成中」提示', function () {
+    expect(/生成中/.test(template)).toBe(true)
+  })
+
+  it('加载失败分支:模板含「失败/重试」提示', function () {
+    expect(/加载失败|获取失败|重试|失败/.test(template)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R4 api.js 静态契约:aiyunyi.getReport 走 /api/aiyunyi/** 后端代理(§3.1/§4.2)
+// ===========================================================================
+
+describe('AC-R4 utils/api.js getReport 封装静态契约', function () {
+  var apiSrc
+
+  beforeAll(function () {
+    apiSrc = fs.readFileSync(API_PATH, 'utf8')
+  })
+
+  /** getReport 声明附近必须绑定 /api/aiyunyi/ 代理前缀 */
+  function getReportBoundToProxy(src) {
+    var re = /getReport/g
+    var match
+    while ((match = re.exec(src)) !== null) {
+      var around = src.slice(Math.max(0, match.index - 400), match.index + 500)
+      if (around.indexOf('/api/aiyunyi/') >= 0) return true
+    }
+    return false
+  }
+
+  it('存在 /api/aiyunyi/** 代理前缀(前端不直连爱云医)', function () {
+    expect(apiSrc.indexOf('/api/aiyunyi/')).toBeGreaterThanOrEqual(0)
+  })
+
+  it('getReport 封装绑定代理前缀(aiyunyi.getReport / aiyunyiGetReport / 平铺)', function () {
+    expect(apiSrc.indexOf('getReport')).toBeGreaterThanOrEqual(0)
+    expect(getReportBoundToProxy(apiSrc)).toBe(true)
+  })
+
+  it('报告详情链路不调用 report/page(R3 缺陷 1011011002 回归锚点)', function () {
+    expect(apiSrc.indexOf('report/page')).toBe(-1)
+  })
+})
+
+// ===========================================================================
+// AC-R5 页面脚本锚点:报告 id 来自 options,不走 report/page(§4.5)
+// ===========================================================================
+
+describe('AC-R5 页面脚本按 id 拉取锚点', function () {
+  var src
+
+  beforeAll(function () {
+    src = readDetailSource()
+  })
+
+  it('onLoad 从 options.id / options.reportId 取报告 id', function () {
+    expect(/options\.(id|reportId)/.test(src)).toBe(true)
+  })
+
+  it('页面脚本不调用 report/page 分页接口(§4.5 R3)', function () {
+    expect(/report\/page/.test(src)).toBe(false)
+  })
+})
+
+// ===========================================================================
+// 权限流:本报告详情页按报告 id 拉取并渲染,无角色门禁分支(不适用项)
+// ===========================================================================
+
+describe.skip('权限流:ai.aiyunyi.reportDetail 无角色门禁,不适用', function () {
+  it('占位:鉴权由统一 Bearer Token 通道承载,详情页仅按 id 渲染(详见汇报)', function () {})
+})

+ 316 - 0
cfc-frontend/__tests__/pages/health/health-guhe-v2-display.contract.test.js

@@ -0,0 +1,316 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 health.frontend.guheV2Display(P1-3 前端展示增强)
+ *
+ * 溯源:
+ *   requirement: tests/user-scenarios/应用场景总览.md  SC-P-22(报告解析预览,入库前核对)
+ *   design:      docs/浠艾福程序-谷禾新版解析与五维归因升级方案-v1.0.md
+ *                §三 P1-3(前端展示增强:报告详情页「异常菌清单」卡片 ↑↓ 分组 12 条、
+ *                          报告详情页「亚健康诊断」标签、健康计划页底部固定免责声明 §8.8 红线)
+ *                §六 6.2(GET /api/health/report/detail 响应新增 abnormalSpecies / speciesLibrary /
+ *                        fbRatio / shannonIndexNorm / subhealthLabel / parseSelfCheck)
+ *
+ * 说明(既有 Jest 体系约束,沿用 __tests__/family-join/join-form.required-info.test.js 约定):
+ *   - jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
+ *     未安装 vue-jest/jsdom 组件环境 —— 既有约定为「加载真实 SFC 的 <script>/<template> 断言」。
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(异常菌清单卡片、亚健康诊断标签、免责声明)。
+ *   - 若实现方在后续 GREEN 阶段对 report-detail.vue / health-plan-summary.vue 补足契约,
+ *     本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   - 本文件不修改 pages/、utils/ 任何业务代码。
+ *
+ * 设计文档所述 pages/health-report、pages/attribution 路径与实际 cfc-frontend 不符:
+ *   实际为 cfc-frontend/pages/health(report-detail.vue、health-plan-summary.vue),
+ *   以实现时探测为准,本文件按探测到的真实路径加载。
+ *   归因页「菌群 → 五维」可视化(内联 SVG 相生相克图)当前 cfc-frontend 无对应页面,
+ *   不在此文件硬断言(组件路径不存在会报错而非红测),以探测到的 report-detail /
+ *   health-plan-summary 两个已存在页面的契约展示为准。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { getReportDetail as apiGetReportDetail, clearApiDedup } from '@/utils/api'
+
+const REPORT_DETAIL_PATH = path.join(__dirname, '../../../pages/health/report-detail.vue')
+const HEALTH_PLAN_PATH = path.join(__dirname, '../../../pages/health/health-plan-summary.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__stubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__guheStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadSfc(filePath) {
+  var src = fs.readFileSync(filePath, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 ' + filePath + ' 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__guheStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  stubs = {
+    getReportDetail: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getReportIndicators: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { items: [] } }) }),
+    getDanReportDetail: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getReportPayload: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    editHealthReport: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    parseReportDraft: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    confirmReportPreview: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    discardReportDraft: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    confirmTongue: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    discardTongue: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getFamilyMemberList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    addFamilyMember: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    queryIndicatorKnowledge: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    queryBacteriaKnowledge: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    normalizeMembers: jest.fn(function (arr) { return arr || [] }),
+    memberIdOf: jest.fn(function (m) { return m ? (m.id != null ? m.id : m.memberId) : null }),
+    resolveChange: jest.fn(function () { return { trendLabel: '', cssClass: 'flat', arrow: '', colorClass: 'gray-text', showArrow: false } }),
+    formatDate: jest.fn(function (v) { return v ? String(v).substring(0, 10) : '' }),
+    fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} },
+    ReportBlocksRenderer: { name: 'ReportBlocksRenderer' },
+    FeedbackPopup: { name: 'FeedbackPopup' },
+    IndicatorChangeRow: { name: 'IndicatorChangeRow' }
+  }
+  globalThis.__guheStubs = {
+    '../../utils/api.js': {
+      getReportDetail: stubs.getReportDetail,
+      getDanReportDetail: stubs.getDanReportDetail,
+      getReportPayload: stubs.getReportPayload,
+      editHealthReport: stubs.editHealthReport,
+      parseReportDraft: stubs.parseReportDraft,
+      confirmReportPreview: stubs.confirmReportPreview,
+      discardReportDraft: stubs.discardReportDraft,
+      confirmTongue: stubs.confirmTongue,
+      discardTongue: stubs.discardTongue,
+      getFamilyMemberList: stubs.getFamilyMemberList,
+      addFamilyMember: stubs.addFamilyMember,
+      queryIndicatorKnowledge: stubs.queryIndicatorKnowledge,
+      queryBacteriaKnowledge: stubs.queryBacteriaKnowledge,
+      getReportIndicators: stubs.getReportIndicators
+    },
+    '../../utils/memberNormalize.js': { normalizeMembers: stubs.normalizeMembers, memberIdOf: stubs.memberIdOf },
+    '@/utils/indicator-change': { resolveChange: stubs.resolveChange },
+    '../../utils/format.js': { formatDate: stubs.formatDate },
+    '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin },
+    './report-blocks-renderer.vue': { default: stubs.ReportBlocksRenderer, ReportBlocksRenderer: stubs.ReportBlocksRenderer },
+    '@/pages/health/components/feedback-popup.vue': { default: stubs.FeedbackPopup, FeedbackPopup: stubs.FeedbackPopup },
+    '@/pages/health/components/IndicatorChangeRow.vue': { default: stubs.IndicatorChangeRow, IndicatorChangeRow: stubs.IndicatorChangeRow }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__guheStubs
+})
+
+// ---------------------------------------------------------------------------
+// §6.2 接口契约 → report-detail.vue 消费:详情响应新增 guhe_v2 字段应写入组件状态
+// (P1-3 展示依赖 P0-4/P0-6;前端消费这些字段是「可显示、可干预」契约的前提)
+// ---------------------------------------------------------------------------
+
+describe('§6.2 report-detail.vue 消费详情接口新增 guhe_v2 字段', function () {
+  var component
+  beforeEach(function () { component = loadSfc(REPORT_DETAIL_PATH).component })
+
+  it('响应含 abnormalSpecies 数组 → 组件状态写入(异常菌清单数据源)', async function () {
+    var detail = {
+      report: { reportFormat: 'guhe_v2', subjectId: 1 },
+      payload: {},
+      abnormalSpecies: [
+        { speciesNo: 1, cnName: '拟杆菌属', latinName: 'Bacteroides', direction: '↓', abundance: '12%', refRange: '20-40%', category: '条件致病菌', populationLevel: '偏低' },
+        { speciesNo: 2, cnName: '大肠埃希菌', latinName: 'Escherichia coli', direction: '↑', abundance: '30%', refRange: '1-5%', category: '条件致病菌', populationLevel: '偏高' }
+      ]
+    }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.abnormalSpecies).toEqual(detail.abnormalSpecies)
+  })
+
+  it('响应含 speciesLibrary 数组 → 组件状态写入(物种功能库数据源)', async function () {
+    var detail = {
+      report: { reportFormat: 'guhe_v2', subjectId: 1 },
+      payload: {},
+      speciesLibrary: [
+        { speciesNo: 1, cnName: '双歧杆菌', functionTag: '产丁酸', detectionRate: '高' }
+      ]
+    }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.speciesLibrary).toEqual(detail.speciesLibrary)
+  })
+
+  it('响应含 subhealthLabel → 组件状态写入(亚健康诊断标签)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, subhealthLabel: '亚健康及营养膳食不合理' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.subhealthLabel).toBe('亚健康及营养膳食不合理')
+  })
+
+  it('响应含 fbRatio → 组件状态写入(F/B 比值)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, fbRatio: '1.35' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.fbRatio).toBe('1.35')
+  })
+
+  it('响应含 shannonIndexNorm → 组件状态写入(菌群多样性评级)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, shannonIndexNorm: '中等' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.shannonIndexNorm).toBe('中等')
+  })
+
+  it('响应含 parseSelfCheck → 组件状态写入(解析自检 JSON)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, parseSelfCheck: { 通过: true, P0: 0, P1: 2 } }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.parseSelfCheck).toEqual(detail.parseSelfCheck)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// P1-3 报告详情页结构契约:「异常菌清单」卡片(↑↓ 分组展示 12 条)+「亚健康诊断」标签
+// ---------------------------------------------------------------------------
+
+describe('P1-3 report-detail.vue 模板结构:异常菌清单 + 亚健康诊断', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数,置空即可
+    globalThis.__guheStubs = {}
+    template = loadSfc(REPORT_DETAIL_PATH).template
+  })
+
+  it('含「异常菌清单」卡片标题(入库前核对 12 条 ↑↓ 分组)', function () {
+    expect(template).toMatch(/异常菌清单/)
+  })
+
+  it('模板绑定 abnormalSpecies 数据源(v-for 遍历)', function () {
+    expect(template).toMatch(/abnormalSpecies/)
+  })
+
+  it('异常菌条目含方向分组(↑/↓ 超界标记)', function () {
+    expect(template).toMatch(/direction/)
+  })
+
+  it('异常菌条目点击展开显示丰度 / 参考范围 / 功能描述', function () {
+    // 点击展开:模板含 abundance / refRange / functionDesc(或 functionDesc 对应字段)任一绑定
+    expect(template).toMatch(/abundance|refRange|functionDesc|functionTag|function_desc/)
+  })
+
+  it('含「亚健康诊断」标签(如「亚健康及营养膳食不合理」)', function () {
+    expect(template).toMatch(/亚健康诊断/)
+  })
+
+  it('亚健康诊断标签绑定 subhealthLabel', function () {
+    expect(template).toMatch(/subhealthLabel/)
+  })
+
+  it('含 F/B 比值展示(fbRatio 绑定)', function () {
+    expect(template).toMatch(/fbRatio/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// P1-3 健康计划页结构契约:底部固定免责声明(§8.8 红线:相关关联非因果、测试 ≠ 诊断)
+// ---------------------------------------------------------------------------
+
+describe('P1-3 health-plan-summary.vue 模板结构:底部固定免责声明', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__guheStubs = {}
+    template = loadSfc(HEALTH_PLAN_PATH).template
+  })
+
+  it('含免责声明文案(不构成医学诊断 / 相关关联非因果)', function () {
+    expect(template).toMatch(/免责声明|不构成医学诊断|不做诊断|非因果|仅供参考|相关关联/)
+  })
+
+  it('免责声明区域固定底部(fixed 定位或 bottom 容器)', function () {
+    expect(template).toMatch(/免责|disclaimer/i)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 设计锚点:utils/api.js getReportDetail 透传 reportId(§6.2 接口既有封装,防回归锚点)
+// ---------------------------------------------------------------------------
+
+describe('设计锚点:api.js getReportDetail 透传 reportId', function () {
+  it('POST /api/health/report/detail 请求体含 reportId', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: null } }) })
+    })
+    clearApiDedup()
+    await apiGetReportDetail(123)
+    expect(captured.url).toContain('/api/health/report/detail')
+    expect(captured.method).toBe('POST')
+    expect(captured.data).toEqual(expect.objectContaining({ reportId: 123 }))
+  })
+})

+ 172 - 0
cfc-frontend/__tests__/pages/health/healthPlanSummary.memberIdScope.test.js

@@ -0,0 +1,172 @@
+/**
+ * 契约级单测(TDD-RED)——健康方案页保存归属:主账号走账号级,代填成员走 family_members.id
+ * 设计:docs/superpowers/specs/2026-11-23-health-survey-member-picker-design.md
+ * 沿用 SFC 源码抽取式约定(jest 无 vue-jest/jsdom)。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const PLAN_PATH = path.join(__dirname, '../../../pages/health/health-plan-summary.vue')
+
+// 照搬 healthSurvey.memberPicker.test.js 的 __hpStubs 注入机制:
+// 可按 import 路径注入桩(本题需要注入 '../../utils/api' 的 getHealthStatus),
+// 其余 import 未注入时取 undefined(SFC 顶层仅把组件/mixin 放进对象字面量,不调用)。
+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 loadPlan() {
+  var src = fs.readFileSync(PLAN_PATH, 'utf8')
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  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 mod.exports
+}
+
+// Node 环境提供 uni 桩(SFC 方法内引用全局 uni)
+globalThis.uni = {
+  getStorageSync: function (k) { return (globalThis.__storage || {})[k] || '' }
+}
+beforeEach(function () {
+  globalThis.__storage = {}
+  globalThis.__hpStubs = {}
+})
+
+function instantiate(component) {
+  var vm = {}
+  vm.$set = function (o, k, v) { o[k] = v }
+  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] })
+  var computed = component.computed || {}
+  Object.keys(computed).forEach(function (k) {
+    Object.defineProperty(vm, k, { get: function () { return computed[k].call(vm) }, configurable: true })
+  })
+  return vm
+}
+
+describe('health-plan-summary 保存归属', function () {
+  it('有 isAccountLevelMember 方法', function () {
+    var vm = instantiate(loadPlan())
+    expect(typeof vm.isAccountLevelMember).toBe('function')
+  })
+
+  it('主账号(memberId === userId)判为账号级;普通成员判为非账号级', function () {
+    var vm = instantiate(loadPlan())
+    vm.pickerMembers = [
+      { id: '88', memberId: '88', userId: '88', name: '本人' },        // 主账号:id===userId
+      { id: '205', memberId: '205', userId: '77', name: '小明' },      // 普通成员:family_members.id≠userId
+      { id: '9', memberId: '9', userId: '100', name: '父' }
+    ]
+    // uni.getStorageSync 桩(降级兜底用),主路径不命中
+    globalThis.__storage = {}
+    expect(vm.isAccountLevelMember('88')).toBe(true)
+    expect(vm.isAccountLevelMember('205')).toBe(false)
+    expect(vm.isAccountLevelMember('9')).toBe(false)
+  })
+
+  it('storage 兜底:pickerMembers 未加载时 id===storage.userId 判为账号级', function () {
+    var vm = instantiate(loadPlan())
+    vm.pickerMembers = []
+    globalThis.__storage = { userId: '88' }
+    expect(vm.isAccountLevelMember('88')).toBe(true)
+    expect(vm.isAccountLevelMember('205')).toBe(false)
+  })
+
+  // ---------- loadHealthForm 读取归属:与保存侧 memberId 一致 ----------
+  describe('loadHealthForm 按成员读取(裸值 memberId)', function () {
+    function baseVm() {
+      var vm = instantiate(loadPlan())
+      vm.memberFormMap = {}
+      vm.pickerMembers = [
+        { id: '88', memberId: '88', userId: '88', name: '本人' },
+        { id: '205', memberId: '205', userId: '77', name: '小明' }
+      ]
+      vm.activeFormMemberId = ''
+      globalThis.__storage = {}
+      return vm
+    }
+
+    it('普通成员:getHealthStatus 收到裸值 205(不是对象)', async function () {
+      var calls = []
+      var args = []
+      // 桩必须在 loadPlan() 之前注入:import 替换在 SFC 脚本求值时立即读取 __hpStubs
+      globalThis.__hpStubs['../../utils/api'] = {
+        getHealthStatus: function (memberId) {
+          args.push(memberId)
+          calls.push(memberId || 'ACCOUNT')
+          return Promise.resolve({ code: 200, data: { heightCm: '170' } })
+        }
+      }
+      var vm = baseVm()
+      await vm.loadHealthForm('205')
+      expect(calls).toEqual(['205'])
+      // 契约回归:裸值,不能退化成 { memberId: ... }
+      expect(typeof args[0]).toBe('string')
+      expect(args[0]).toBe('205')
+      expect(typeof args[0]).not.toBe('object')
+      expect(args[0]).not.toEqual(expect.objectContaining({ memberId: expect.anything() }))
+      expect(vm.memberFormMap['205'].form.heightCm).toBe('170')
+    })
+
+    it('主账号:getHealthStatus 不传 memberId(账号级)', async function () {
+      var calls = []
+      var args = []
+      globalThis.__hpStubs['../../utils/api'] = {
+        getHealthStatus: function (memberId) {
+          args.push(memberId)
+          calls.push(memberId || 'ACCOUNT')
+          return Promise.resolve({ code: 200, data: { heightCm: '160' } })
+        }
+      }
+      var vm = baseVm()
+      await vm.loadHealthForm('88')
+      expect(calls).toEqual(['ACCOUNT'])
+      expect(args[0]).toBeUndefined()
+      expect(vm.memberFormMap['88'].form.heightCm).toBe('160')
+    })
+
+    it('成员级无数据时回退账号级(调用序列 205 → ACCOUNT)', async function () {
+      var calls = []
+      globalThis.__hpStubs['../../utils/api'] = {
+        getHealthStatus: function (memberId) {
+          var midVal = memberId || ''
+          calls.push(midVal || 'ACCOUNT')
+          if (midVal) return Promise.resolve({ code: 200, data: null })
+          return Promise.resolve({ code: 200, data: { heightCm: '165' } })
+        }
+      }
+      var vm = baseVm()
+      await vm.loadHealthForm('205')
+      expect(calls).toEqual(['205', 'ACCOUNT'])
+      expect(vm.memberFormMap['205'].form.heightCm).toBe('165')
+    })
+  })
+})

+ 216 - 0
cfc-frontend/__tests__/pages/health/healthSurvey.incrementalSave.test.js

@@ -0,0 +1,216 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——健康问卷「增量保存(只存修改成员)+ 统一签名(一次签名全员共用)」
+ * 能力键:health.survey.incrementalSave
+ *
+ * 背景:主理人需求——
+ *   需求1 多人填写全部保存,但只保存内容相对「加载/切换时初始快照」有实质变化的成员;
+ *         未变化成员跳过内容保存(避免无谓请求,也避免后端 saveForMember 清空其已落库签名)。
+ *   需求2 只签一次名,本次参与提交的全部成员共用同一签名,绝不因内容跳过而漏签。
+ * 本测试锁定四条契约:
+ *   1) collectSaveMembers 增量判定:未变化成员 changed=false,内容变化成员 changed=true
+ *   2) 归一化口径:number/string、数组顺序、null/空串/undefined、对象键序 均不误判为变化,
+ *      真实变化仍被检测
+ *   3) 统一签名:onSubmit 内容仅存变化成员,签名落全体参与成员(含未变化成员)
+ *   4) 全部未变化:零内容请求 + 仍统一落签名 + 正常退出(无报错)
+ *
+ * 沿用既有 SFC 源码抽取式约定(见 healthSurvey.lifestyleSave.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')
+
+function stubImports(script, stubMap) {
+  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], globalThis.__hpStubs || {})
+  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 < 12; i++) await Promise.resolve()
+}
+
+// uni 全局桩(onSubmit 成功/失败路径调用 showToast/navigateBack)
+function setupUni() {
+  globalThis.uni = {
+    showToast: function () {},
+    navigateBack: function () {},
+    navigateTo: function () {},
+    getStorageSync: function () { return '' },
+    setStorageSync: function () {},
+    removeStorageSync: function () {},
+    showModal: function () {}
+  }
+}
+
+function apiStub(contentSaved, sigSaved) {
+  return {
+    getHealthStatus: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveHealthStatus: function (p) { contentSaved.push({ kind: 'hs', p: p }); return Promise.resolve({ code: 200 }) },
+    getDietPreferences: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveDietPreferences: function (p) { contentSaved.push({ kind: 'diet', p: p }); return Promise.resolve({ code: 200 }) },
+    getMyMembership: function () { return Promise.resolve({ code: 200, data: {} }) },
+    getFamilyMemberList: function () { return Promise.resolve({ code: 200, data: [] }) },
+    submitSurvey: function () { return Promise.resolve({ code: 200 }) },
+    getLastHealthReview: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveHealthSignature: function (mid, dataUrl) { sigSaved.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()
+})
+
+describe('health-survey 增量保存 + 统一签名', function () {
+  it('契约1 增量判定:未变化成员 changed=false,内容变化成员 changed=true', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ALL8.slice()
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }]
+    vm.selectedMemberId = '20'
+    vm.$refs = {}
+    // 初始快照(加载时):身高 170
+    vm.initialSnapshotMap = { '20': { form: { heightCm: '170', lifestyle: {} }, diet: {} } }
+    // 当前未变:仍 170 → changed=false
+    vm.formSnapshot = { heightCm: '170', lifestyle: {} }
+    vm.dietSnapshot = {}
+    var unchanged = vm.collectSaveMembers(null)
+    expect(unchanged.length).toBe(1)
+    expect(unchanged[0].mid).toBe('20')
+    expect(unchanged[0].changed).toBe(false)
+    // 当前变化:身高 175 → changed=true
+    vm.formSnapshot = { heightCm: '175', lifestyle: {} }
+    var changed = vm.collectSaveMembers(null)
+    expect(changed.length).toBe(1)
+    expect(changed[0].mid).toBe('20')
+    expect(changed[0].changed).toBe(true)
+  })
+
+  it('契约2 归一化:number/string、数组顺序、null/空串/undefined、对象键序 不误判;真实变化仍检测', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic', 'disease', 'bowel', 'allergy', 'diet']
+    vm.initialSnapshotMap = { '20': {
+      form: {
+        heightCm: '170', notes: '',
+        selectedDiseases: [{ name: '高血压', diagnosedAt: '2020' }, { name: '糖尿病' }],
+        lifestyle: { allergySymptoms: ['花生', '牛奶'], bowelFrequency: '每天1次(正常)' }
+      },
+      diet: { allergies: ['花生', '牛奶'], spiceLevel: 0 }
+    } }
+    // 当前:数值化 170、疾病顺序颠倒、过敏原顺序颠倒、notes 为 null、lifestyle 键序不同、spiceLevel 字符串化
+    var curForm = {
+      heightCm: 170, notes: null,
+      selectedDiseases: [{ name: '糖尿病' }, { name: '高血压', diagnosedAt: '2020' }],
+      lifestyle: { bowelFrequency: '每天1次(正常)', allergySymptoms: ['牛奶', '花生'] }
+    }
+    var curDiet = { allergies: ['牛奶', '花生'], spiceLevel: '0' }
+    expect(vm.memberContentChanged('20', curForm, curDiet, {})).toBe(false)
+    // 真实变化仍被检测(身高 175)
+    var curForm2 = { heightCm: '175', notes: null, selectedDiseases: curForm.selectedDiseases, lifestyle: curForm.lifestyle }
+    expect(vm.memberContentChanged('20', curForm2, curDiet, {})).toBe(true)
+  })
+
+  it('契约3 统一签名:onSubmit 内容仅存变化成员,签名落全体参与成员(含未变化成员)', async function () {
+    var contentSaved = []
+    var sigSaved = []
+    globalThis.__hpStubs['../../utils/api'] = apiStub(contentSaved, sigSaved)
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic']
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }, { memberId: '99', source: 'family_member' }]
+    vm.selectedMemberId = '20'
+    vm.signatureDataUrl = 'data:image/png;base64,XYZ'
+    // 20 初始 170(本次改到 175 → 变化);99 初始/当前 160(未变化)
+    vm.initialSnapshotMap = { '20': { form: { heightCm: '170' }, diet: {} }, '99': { form: { heightCm: '160' }, diet: {} } }
+    vm.formSnapshotMap = { '99': { form: { heightCm: '160' }, diet: {} } }
+    vm.formSnapshot = { heightCm: '175' }
+    vm.dietSnapshot = {}
+    vm.$refs = { survey: { captureDraft: function () {} } }
+    vm.onSubmit({ form: { heightCm: '175' }, diet: {}, lifestyleDiff: {} })
+    await flush()
+    // 内容仅存变化成员 20(账号级 → 不写 memberId);99 未变化 → 零内容请求
+    var hsSaved = contentSaved.filter(function (x) { return x.kind === 'hs' })
+    expect(hsSaved.length).toBe(1)
+    expect(hsSaved[0].p.heightCm).toBe(175)
+    expect(hsSaved[0].p.memberId).toBeUndefined()
+    // 签名落全体参与成员:20(账号级 → 后端传 '' 由 member_id IS NULL 解析)与 99(传 family id)
+    expect(sigSaved.length).toBe(2)
+    var s20 = sigSaved.find(function (s) { return s.mid === '' })
+    var s99 = sigSaved.find(function (s) { return s.mid === '99' })
+    expect(s20).toBeTruthy()
+    expect(s20.dataUrl).toBe('data:image/png;base64,XYZ')
+    expect(s99).toBeTruthy()
+    expect(s99.dataUrl).toBe('data:image/png;base64,XYZ')
+  })
+
+  it('契约4 全部成员未变化:零内容请求,仍统一落签名,正常退出(无报错)', async function () {
+    var contentSaved = []
+    var sigSaved = []
+    globalThis.__hpStubs['../../utils/api'] = apiStub(contentSaved, sigSaved)
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic']
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }]
+    vm.selectedMemberId = '20'
+    vm.signatureDataUrl = 'data:image/png;base64,XYZ'
+    vm.initialSnapshotMap = { '20': { form: { heightCm: '170' }, diet: {} } }
+    vm.formSnapshot = { heightCm: '170' } // 未变化
+    vm.dietSnapshot = {}
+    vm.$refs = { survey: { captureDraft: function () {} } }
+    vm.onSubmit({ form: { heightCm: '170' }, diet: {}, lifestyleDiff: {} })
+    await flush()
+    expect(contentSaved.length).toBe(0)   // 零内容请求
+    expect(sigSaved.length).toBe(1)       // 仍统一落签名
+    expect(sigSaved[0].dataUrl).toBe('data:image/png;base64,XYZ')
+    expect(vm.submitting).toBe(false)     // 正常退出(无报错、无悬挂 submitting)
+  })
+})

+ 148 - 0
cfc-frontend/__tests__/pages/health/healthSurvey.lifestyleSave.test.js

@@ -0,0 +1,148 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——健康问卷「状态/排便/运动/睡眠/过敏」五类 lifestyle 字段保存闭环
+ * 能力键:health.survey.lifestyleSave
+ *
+ * 背景:用户报告 5 类字段未保存。链路追踪 + 仿真证明当前代码在
+ *   submit(当前成员)/ flush(onHide 兜底)/ 多成员(缓存成员 lifestyleDiff={})三条路径
+ *   均能通过 buildPayloadsForMember 把完整 lifestyle 并入 hsPayload.lifestyle 落库。
+ * 本测试锁定该闭环,防止后续改动把 lifestyle 断链。
+ *
+ * 沿用既有 SFC 源码抽取式约定(见 healthSurvey.memberPicker.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')
+
+function stubImports(script, stubMap) {
+  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], globalThis.__hpStubs || {})
+  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
+}
+
+beforeEach(function () {
+  globalThis.__hpStubs = {}
+})
+
+// 五类字段的完整 lifestyle(模拟用户在状态/排便/运动/睡眠/过敏页填好的实时草稿)
+function fullLifestyle() {
+  return {
+    currentStatus: '正常', menstrualCycle: '', specialPeriod: '', growthDevelopment: '', pickyEating: '',
+    osteoporosisRisk: '', fallRisk: '', screenTime: '', teenMood: '',
+    bowelFrequency: '每天1次(正常)', bowelForm: 'type4', exerciseFrequency: '每周3-4次', exerciseDuration: '30-60分钟',
+    sleepDuration: '7-8小时', bedtime: '22:00-24:00', allergySymptoms: ['鼻痒/打喷嚏'], mood: '', antibioticHistory: ''
+  }
+}
+
+describe('health-survey 五类 lifestyle 字段保存闭环', function () {
+  it('buildPayloadsForMember 把状态/排便/运动/睡眠/过敏并入 hsPayload.lifestyle(过敏原入 dietPayload.allergies)', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic', 'status', 'diet', 'disease', 'bowel', 'sleep', 'med', 'allergy']
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }] // 主账号账号级
+    var form = { heightCm: '170', lifestyle: fullLifestyle() }
+    var diet = { allergies: ['花生'] }
+    var built = vm.buildPayloadsForMember('20', form, diet, {})
+    // health_status 侧:lifestyle JSON 含全部五类 key
+    expect(built.hsPayload.lifestyle).toBeTruthy()
+    var ls = JSON.parse(built.hsPayload.lifestyle)
+    expect(ls.currentStatus).toBe('正常')                       // 状态
+    expect(ls.bowelFrequency).toBe('每天1次(正常)')            // 排便
+    expect(ls.bowelForm).toBe('type4')                           // 排便(性状)
+    expect(ls.exerciseFrequency).toBe('每周3-4次')               // 运动
+    expect(ls.exerciseDuration).toBe('30-60分钟')                // 运动
+    expect(ls.sleepDuration).toBe('7-8小时')                     // 睡眠
+    expect(ls.bedtime).toBe('22:00-24:00')                       // 睡眠
+    expect(ls.allergySymptoms).toEqual(['鼻痒/打喷嚏'])          // 过敏(症状)
+    // diet_preferences 侧:过敏原双写
+    expect(built.dietPayload.allergies).toEqual(['花生'])        // 过敏(原)
+  })
+
+  it('buildPayloadsForMember 主账号不传 memberId,代填成员传 family_members.id', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic', 'status', 'diet', 'disease', 'bowel', 'sleep', 'med', 'allergy']
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }, { memberId: '99', source: 'family_member' }]
+    var form = { heightCm: '170', lifestyle: fullLifestyle() }
+    // 主账号
+    var acc = vm.buildPayloadsForMember('20', form, {}, {})
+    expect(acc.hsPayload.memberId).toBeUndefined()
+    // 代填成员
+    var mem = vm.buildPayloadsForMember('99', form, {}, {})
+    expect(mem.hsPayload.memberId).toBe('99')
+  })
+
+  it('collectSaveMembers 对缓存成员仍携带完整 lifestyle(lifestyleDiff={} 正确)', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.activeModules = ['basic', 'status', 'diet', 'disease', 'bowel', 'sleep', 'med', 'allergy']
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }, { memberId: '99', source: 'family_member' }]
+    vm.selectedMemberId = '99' // 当前 = 代填成员 99
+    // 缓存成员 20(切走时 switchMember 已抓取完整 lifestyle)
+    vm.formSnapshotMap = { '20': { form: { heightCm: '170', lifestyle: fullLifestyle() }, diet: { allergies: ['花生'] } } }
+    vm.formSnapshot = { heightCm: '180', lifestyle: fullLifestyle() }
+    vm.dietSnapshot = { allergies: [] }
+    vm.$refs = {}
+    var members = vm.collectSaveMembers(null) // flush 路径:payload=null → 当前成员 diff={}
+    // 应收集 [99 当前, 20 缓存]
+    expect(members.length).toBe(2)
+    var m20 = members.find(function (m) { return m.mid === '20' })
+    expect(m20).toBeTruthy()
+    // 缓存成员 lifestyle 完整(不依赖 diff)
+    expect(m20.lifestyleDiff).toEqual({})
+    expect(m20.form.lifestyle.bowelFrequency).toBe('每天1次(正常)')
+    expect(m20.form.lifestyle.allergySymptoms).toEqual(['鼻痒/打喷嚏'])
+  })
+
+  it('snapshotHasContent 识别仅含 lifestyle 的五类字段为有内容(防空提交)', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    var form = { heightCm: '', weightKg: '', bloodPressure: '', bloodGlucose: '', notes: '', lifestyle: fullLifestyle() }
+    var diet = { allergies: [] }
+    expect(vm.snapshotHasContent(form, diet, {})).toBe(true)
+  })
+})

+ 284 - 0
cfc-frontend/__tests__/pages/health/healthSurvey.memberPicker.test.js

@@ -0,0 +1,284 @@
+/**
+ * 契约级单测(TDD-RED)——独立健康问卷成员选择(管理员代填)
+ * 能力键:health.survey.memberPicker
+ * 设计:docs/superpowers/specs/2026-11-23-health-survey-member-picker-design.md
+ *
+ * 沿用既有 SFC 源码抽取式约定(见 pages/growth-main/growthHistory.dayGroupView.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 PICKER_PATH = path.join(__dirname, '../../../pages/health/components/MemberChipPicker.vue')
+
+function stubImports(script, stubMap) {
+  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>/)
+  var templateMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  if (!scriptMatch) throw new Error('无法定位 <script>: ' + file)
+  var script = stubImports(scriptMatch[1], globalThis.__hpStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  new Function('module', 'exports', script)(mod, mod.exports)
+  return { component: mod.exports, template: templateMatch ? templateMatch[1] : '' }
+}
+
+function instantiate(component) {
+  var vm = {}
+  // 模拟 Vue 实例的 $set(Vue 2 响应式关键 API),供 switchMember/loadHealthSnapshot 使用
+  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
+}
+
+beforeEach(function () {
+  globalThis.__hpStubs = {}
+})
+
+// ---------- MemberChipPicker single 模式 ----------
+describe('MemberChipPicker single 单选模式', function () {
+  it('有 single prop 且默认 false', function () {
+    var c = loadSfcScript(PICKER_PATH).component
+    expect(c.props).toHaveProperty('single')
+    expect(c.props.single.default).toBe(false)
+  })
+
+  it('single=true 时 toggleMember 只保留当前选中项', function () {
+    var c = loadSfcScript(PICKER_PATH).component
+    var vm = instantiate(c)
+    vm.single = true
+    vm.members = [
+      { id: '1', selected: false },
+      { id: '2', selected: false },
+      { id: '3', selected: false }
+    ]
+    vm.emitChange = function () {}
+    vm.toggleMember('2')
+    var selected = vm.members.filter(function (m) { return m.selected }).map(function (m) { return m.id })
+    expect(selected).toEqual(['2'])
+    // 再点同一项不取消
+    vm.toggleMember('2')
+    selected = vm.members.filter(function (m) { return m.selected }).map(function (m) { return m.id })
+    expect(selected).toEqual(['2'])
+    // 点另一项切换为它
+    vm.toggleMember('3')
+    selected = vm.members.filter(function (m) { return m.selected }).map(function (m) { return m.id })
+    expect(selected).toEqual(['3'])
+  })
+
+  it('single=false 时保持原多选行为', function () {
+    var c = loadSfcScript(PICKER_PATH).component
+    var vm = instantiate(c)
+    vm.single = false
+    vm.members = [
+      { id: '1', selected: false },
+      { id: '2', selected: false }
+    ]
+    vm.emitChange = function () {}
+    vm.toggleMember('1')
+    vm.toggleMember('2')
+    var selected = vm.members.filter(function (m) { return m.selected }).map(function (m) { return m.id })
+    expect(selected).toEqual(['1', '2'])
+  })
+})
+
+// ---------- health-survey.vue 成员选择契约 ----------
+describe('health-survey 成员选择', function () {
+  it('data 含 formSnapshotMap / selectedMemberId / isAdmin', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(vm.formSnapshotMap).toEqual({})
+    expect(typeof vm.selectedMemberId).toBe('string')
+    expect(typeof vm.isAdmin).toBe('boolean')
+  })
+
+  it('模板含 single 成员选择条(仅管理员可见)', function () {
+    var tpl = loadSfcScript(SURVEY_PATH).template
+    expect(tpl).toMatch(/<member-chip-picker[\s\S]*:single="true"/)
+    expect(tpl).toMatch(/v-if="isAdmin"/)
+  })
+
+  it('resolveIsAdmin 从成员列表判定管理员(isSelf && isAdmin)', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(typeof vm.resolveIsAdmin).toBe('function')
+    var members = [
+      { memberId: '1', isSelf: false, isAdmin: true },
+      { memberId: '2', isSelf: true, isAdmin: true }
+    ]
+    expect(vm.resolveIsAdmin(members)).toBe(true)
+    expect(vm.resolveIsAdmin([{ memberId: '1', isSelf: true, isAdmin: false }])).toBe(false)
+  })
+
+  it('pickDefaultMemberId 默认选 isSelf 成员', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(typeof vm.pickDefaultMemberId).toBe('function')
+    var members = [
+      { memberId: '1', isSelf: false },
+      { memberId: '2', isSelf: true }
+    ]
+    expect(vm.pickDefaultMemberId(members)).toBe('2')
+  })
+
+  it('switchMember 切走时暂存当前快照、切回恢复(不重新加载)', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(typeof vm.switchMember).toBe('function')
+    vm.selectedMemberId = '1'
+    vm.formSnapshot = { heightCm: '170', selectedDiseases: [] }
+    vm.dietSnapshot = { allergies: [] }
+    // 切到无快照成员会走 loadForMember(此处置空即可,重点验证切回缓存恢复)
+    vm.loadForMember = function () {}
+    vm.loadMemberProfileOnly = function () {}
+    vm.members = [{ memberId: '2', nickname: '张三' }]
+    vm.formSnapshotMap = {}
+    vm.switchMember('2')
+    expect(vm.formSnapshotMap['1'].form.heightCm).toBe('170')
+    expect(vm.selectedMemberId).toBe('2')
+    vm.switchMember('1')
+    expect(vm.formSnapshot.heightCm).toBe('170')
+    expect(vm.dietSnapshot).toEqual({ allergies: [] })
+  })
+
+  it('loadHealthSnapshot 成员级只请求一次并带裸值 memberId(后端兜底,前端不二次回退)', async function () {
+    // 后端已合并兜底(commit 35a69e418):成员级查不到时后端按归属账号回退,前端不再发第二次调用
+    // 注意:桩必须在 loadSfcScript 之前设置(import 替换在加载时发生)
+    // key 必须与 health-survey.vue 中 import 的实际路径一致:'../../utils/api'
+    var getHealthStatus = jest.fn(function (memberId) {
+      return Promise.resolve({ code: 200, data: { heightCm: '168' } })
+    })
+    globalThis.__hpStubs['../../utils/api'] = { getHealthStatus: getHealthStatus }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(typeof vm.loadHealthSnapshot).toBe('function')
+    vm.members = [{ memberId: '123', source: 'family_member' }]
+    vm.formSnapshot = {}
+    await vm.loadHealthSnapshot('123')
+    // 契约:成员级只调 1 次,且带裸值 memberId(不是 { memberId } 对象)
+    expect(getHealthStatus).toHaveBeenCalledTimes(1)
+    expect(getHealthStatus).toHaveBeenCalledWith('123')
+    expect(vm.formSnapshot.heightCm).toBe('168')
+  })
+
+  it('loadHealthSnapshot 成员级首次失败/无数据也不回退第二次调用', async function () {
+    var getHealthStatus = jest.fn(function () {
+      return Promise.reject(new Error('network'))
+    })
+    globalThis.__hpStubs['../../utils/api'] = { getHealthStatus: getHealthStatus }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.members = [{ memberId: '123', source: 'family_member' }]
+    vm.formSnapshot = { heightCm: '', weightKg: '', bloodPressure: '', bloodGlucose: '', notes: '' }
+    await vm.loadHealthSnapshot('123')
+    expect(getHealthStatus).toHaveBeenCalledTimes(1)
+    expect(getHealthStatus).toHaveBeenCalledWith('123')
+  })
+
+  it('loadHealthSnapshot 成员级返回空数据也只请求一次(预填留空)', async function () {
+    var getHealthStatus = jest.fn(function () {
+      return Promise.resolve({ code: 200, data: null })
+    })
+    globalThis.__hpStubs['../../utils/api'] = { getHealthStatus: getHealthStatus }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.members = [{ memberId: '123', source: 'family_member' }]
+    vm.formSnapshot = { heightCm: '170' }
+    await vm.loadHealthSnapshot('123')
+    expect(getHealthStatus).toHaveBeenCalledTimes(1)
+    expect(vm.formSnapshot.heightCm).toBe('170')
+  })
+
+  it('loadDietSnapshot 成员级只请求一次并带 { memberId }', async function () {
+    var getDietPreferences = jest.fn(function (data) {
+      return Promise.resolve({ code: 200, data: { allergies: ['花生'] } })
+    })
+    globalThis.__hpStubs['../../utils/api'] = { getDietPreferences: getDietPreferences }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.members = [{ memberId: '123', source: 'family_member' }]
+    await vm.loadDietSnapshot('123')
+    expect(getDietPreferences).toHaveBeenCalledTimes(1)
+    expect(getDietPreferences).toHaveBeenCalledWith({ memberId: '123' })
+    expect(vm.dietSnapshot.allergies).toEqual(['花生'])
+  })
+
+  // ---------- 主账号走账号级(memberId 实为 userId,后端按 family_members.id 处理会错位) ----------
+  it('isAccountLevelMember 判定 source=parent 为主账号', function () {
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    expect(typeof vm.isAccountLevelMember).toBe('function')
+    vm.members = [
+      { memberId: '10', source: 'family_member' },
+      { memberId: '20', source: 'parent', isSelf: true }
+    ]
+    expect(vm.isAccountLevelMember('20')).toBe(true)
+    expect(vm.isAccountLevelMember('10')).toBe(false)
+    expect(vm.isAccountLevelMember('999')).toBe(false)
+  })
+
+  it('主账号 loadHealthSnapshot 只走账号级(不传 memberId)', async function () {
+    var calls = []
+    globalThis.__hpStubs['../../utils/api'] = {
+      // 裸值契约:主账号不传参(undefined → 账号级)
+      getHealthStatus: function (memberId) {
+        var midVal = memberId || ''
+        calls.push(midVal || 'ACCOUNT')
+        return Promise.resolve({ code: 200, data: midVal ? null : { heightCm: '160' } })
+      }
+    }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }]
+    vm.formSnapshot = {}
+    await vm.loadHealthSnapshot('20')
+    expect(calls).toEqual(['ACCOUNT'])
+    expect(vm.formSnapshot.heightCm).toBe('160')
+  })
+
+  it('主账号 loadDietSnapshot 只走账号级(空参数,不传 memberId)', async function () {
+    var getDietPreferences = jest.fn(function () {
+      return Promise.resolve({ code: 200, data: { spiceLevel: 2 } })
+    })
+    globalThis.__hpStubs['../../utils/api'] = { getDietPreferences: getDietPreferences }
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }]
+    await vm.loadDietSnapshot('20')
+    expect(getDietPreferences).toHaveBeenCalledTimes(1)
+    expect(getDietPreferences).toHaveBeenCalledWith({})
+    expect(vm.dietSnapshot.spiceLevel).toBe(2)
+  })
+})

+ 208 - 0
cfc-frontend/__tests__/pages/health/healthSurvey.reviewMultiMember.test.js

@@ -0,0 +1,208 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——健康阅卷(health_review)多成员一次提交各写一条 survey_records
+ * 能力键:health.survey.reviewMultiMember
+ *
+ * 背景:主理人裁决——阅卷一次提交要把「所有已填写成员」各写一条 survey_records
+ * (此前 onSubmit 阅卷分支仅写当前 selectedMemberId 一个成员)。这是纯前端改动:
+ *   · 收集 collectSaveMembers 的有内容成员(含当前 + 切换缓存 members,内部已 captureDraft);
+ *     阅卷不做增量,故不按 m.changed 过滤。
+ *   · 每位成员各发一次 submitSurvey,成员归属放 row 级 memberId(账号级不传、代填传 family_members.id);
+ *     阅卷 answersJson.form 内不携带 memberId(与历史存储口径一致)。
+ *   · 仅写 survey_records:不动 health_status/diet_preferences/签名。
+ *   · 空集合(无任何成员有内容)不发请求,直接 toast + navigateBack,submitting 复位。
+ * 本测试锁定这四条契约,沿用 incrementalSave.test.js 的 SFC 源码抽取式 mock 约定。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const SURVEY_PATH = path.join(__dirname, '../../../pages/health/health-survey.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
+}
+
+async function flush() {
+  for (var i = 0; i < 12; i++) await Promise.resolve()
+}
+
+var toasts, navs, submits, hsCalls, sigCalls
+
+function wireApi() {
+  submits = []; hsCalls = []; 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) { 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); return Promise.resolve({ code: 200 }) },
+    getLastHealthReview: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveHealthSignature: function (mid, dataUrl) { sigCalls.push({ mid: mid }); return Promise.resolve({ code: 200 }) }
+  }
+}
+
+const ALL8 = ['basic', 'status', 'diet', 'disease', 'bowel', 'sleep', 'med', 'allergy']
+
+beforeEach(function () {
+  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 () {}
+  }
+  globalThis.__hpStubs = {}
+})
+
+describe('health-survey 健康阅卷(health_review)多成员一次提交各写一条 survey_records', function () {
+  it('契约1 review 模式 A(账号级当前)改+B(代填)填:submitSurvey 调 2 次、memberId 归属正确、0 次 health_status/签名', async function () {
+    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 () {} } }
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+    // 两个已填写成员各写一条 survey_records
+    expect(submits.length).toBe(2)
+    // A(账号级)→ row 级不带 memberId;B(代填)→ row 级 memberId='99'
+    var aCall = submits.find(function (p) { return !p.memberId })
+    var bCall = submits.find(function (p) { return p.memberId === '99' })
+    expect(aCall).toBeTruthy()
+    expect(aCall.source).toBe('health_review')
+    expect(bCall).toBeTruthy()
+    expect(bCall.source).toBe('health_review')
+    // review 模式只写 survey_records:不碰 health_status / 签名
+    expect(hsCalls.length).toBe(0)
+    expect(sigCalls.length).toBe(0)
+    expect(vm.submitting).toBe(false)
+  })
+
+  it('契约2 阅卷 answersJson.form 内不含 memberId(仅 row 级),代填成员归属放 row 级 memberId', async function () {
+    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 = '99' // 当前 = 代填成员 99
+    vm.formSnapshotMap = {}
+    vm.formSnapshot = { heightCm: '168', lifestyle: { bowelFrequency: '每天1次(正常)' } }
+    vm.dietSnapshot = { mustEat: ['蔬菜'] }
+    vm.$refs = { survey: { captureDraft: function () {} } }
+    vm.onSubmit({ form: { heightCm: '168' }, diet: { mustEat: ['蔬菜'] }, lifestyleDiff: {} })
+    await flush()
+    expect(submits.length).toBe(1)
+    // 成员归属在 row 级
+    expect(submits[0].memberId).toBe('99')
+    // 但 answersJson.form / .diet 内不得残留 memberId / familyMemberId
+    var ans = JSON.parse(submits[0].answersJson)
+    expect(ans.form.memberId).toBeUndefined()
+    expect(ans.diet.familyMemberId).toBeUndefined()
+    // 答案仍含该成员内容(basic + 五类 lifestyle + diet);lifestyle 按历史口径存为 JSON 字符串
+    expect(ans.form.heightCm).toBe(168)
+    expect(ans.form.lifestyle).toBeTruthy()
+    var life = JSON.parse(ans.form.lifestyle)
+    expect(life.bowelFrequency).toBe('每天1次(正常)')
+    expect(ans.diet.mustEat).toEqual(['蔬菜'])
+  })
+
+  it('契约3 仅当前成员有内容(缓存成员为空 → 被 hasContent 过滤):submitSurvey 调 1 次', async function () {
+    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'
+    // 缓存成员 99 有键结构但无实际内容(heightCm 空 + lifestyle 空 → snapshotHasContent=false)
+    vm.formSnapshotMap = { '99': { form: { heightCm: '', 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(submits.length).toBe(1)
+    expect(submits[0].memberId).toBeUndefined() // 账号级当前
+    expect(hsCalls.length).toBe(0)
+    expect(sigCalls.length).toBe(0)
+  })
+
+  it('契约4 无任何成员有内容:0 次 submitSurvey,仍正常 toast+navigateBack、submitting 复位(无报错)', async function () {
+    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 }]
+    vm.selectedMemberId = '20'
+    vm.formSnapshotMap = {}
+    vm.formSnapshot = { heightCm: '', weightKg: '', bloodPressure: '', bloodGlucose: '', notes: '', lipidCholesterol: '', selectedDiseases: [], medRows: [], lifestyle: {} } // 全空
+    vm.dietSnapshot = { allergies: [] }
+    vm.$refs = { survey: { captureDraft: function () {} } }
+    vm.onSubmit({ form: {}, diet: {}, lifestyleDiff: {} })
+    await flush()
+    expect(submits.length).toBe(0)
+    expect(hsCalls.length).toBe(0)
+    expect(sigCalls.length).toBe(0)
+    expect(vm.submitting).toBe(false)          // submitting 复位(无悬挂)
+    var ok = toasts.find(function (t) { return t.title === '已保存' })
+    expect(ok).toBeTruthy()                     // 正常 toast
+  })
+})

+ 53 - 0
cfc-frontend/__tests__/pages/index-home.quickCompleteOverdue.test.js

@@ -0,0 +1,53 @@
+/**
+ * 契约级单测(TDD)—— 能力键 task.complete.overdue-toast(2026-11-16 产品拍板)
+ *
+ * 溯源:
+ *   需求:用户「马智强」反馈打卡提示不成功,根因=超期任务被 deadline 守卫拒绝(TC-C-02-E)。
+ *        产品拍板:过期任务允许打卡完成,但零奖励(不发 CF 值)。后端 TaskService.completeTask
+ *        已改为超期完成返回 { pointsEarned:0, overdue:true };本契约锁定前端首页
+ *        quickCompleteTask 对 overdue 的提示分支(避免用户看到"获得 0 CF")。
+ *   设计:cfc-frontend/pages/index-home/index.vue quickCompleteTask → completeTaskApi → res.data.overdue
+ *        → uni.showToast({ title: '已过期,打卡成功但不计奖励', icon: 'none' })
+ *
+ * 说明:沿项目「源码静态契约」范式(对齐 __tests__/pages/tasks/taskHistory.view.test.js 静态装配),
+ * 只读真实源码断言分支结构,不 mount 巨型 index.vue。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const INDEX_HOME_PATH = path.join(__dirname, '../../pages/index-home/index.vue')
+
+/** 提取 quickCompleteTask 方法体(4 空格缩进方法,到下一个方法边界 `    },` 为止) */
+function quickCompleteBody(src) {
+  const m = src.match(/quickCompleteTask\s*:\s*function\s*\([^)]*\)\s*\{([\s\S]*?)\n    \},/)
+  if (!m) throw new Error('无法在 index.vue 中定位 quickCompleteTask 方法体')
+  return m[1]
+}
+
+describe('task.complete.overdue-toast:首页过期打卡提示分支', function () {
+  let body
+  beforeAll(function () {
+    const src = fs.readFileSync(INDEX_HOME_PATH, 'utf8')
+    body = quickCompleteBody(src)
+  })
+
+  test('容纳后端 overdue 标记并提示「已过期,打卡成功但不计奖励」', function () {
+    expect(body.indexOf('res.data.overdue') >= 0).toBe(true)
+    expect(body.indexOf('已过期') >= 0).toBe(true)
+    expect(body.indexOf('打卡成功但不计奖励') >= 0).toBe(true)
+  })
+
+  test('overdue 分支成功 toast 用 icon none(提示而非成功动画,避免误导"获得奖励")', function () {
+    const segStart = body.indexOf('res.data.overdue')
+    expect(segStart).toBeGreaterThanOrEqual(0)
+    const seg = body.slice(segStart, segStart + 400)
+    expect(seg.indexOf("icon: 'none'") >= 0).toBe(true)
+  })
+
+  test('overdue 分支前置(早于"获得 X CF"成功分支,避免被通用成功提示吞掉)', function () {
+    const overdueIdx = body.indexOf('res.data.overdue')
+    const earnIdx = body.indexOf('获得 ')
+    expect(overdueIdx).toBeGreaterThanOrEqual(0)
+    expect(earnIdx).toBeGreaterThan(overdueIdx)
+  })
+})

+ 143 - 0
cfc-frontend/__tests__/pages/index-home/task-today-overdue-visible.contract.test.js

@@ -0,0 +1,143 @@
+/**
+ * 契约级单测(TDD-RED)—— 能力键 task.today.overdueVisible
+ *
+ * 溯源:
+ *   根因报告:docs/tdd/orchestration/rootcause-home-tasks-overdue-2026-12-02.md
+ *   裁决记录:docs/tdd/orchestration/pending.md O-27
+ *
+ * 主理人方案 A 要求:
+ *   跨天超期任务仍可见、标红「已超期」、可补打卡。
+ *   后端 L517 区 getTodayTasks(memberId,dimensionCode) 的 status IN 白名单须加入 overdue;
+ *   次要:getTodayTasksByFamily(L566) 个人/全家口径的 status 白名单一并对齐(含 in_progress)。
+ *   前端 loadTodayTasks 过滤 pendingTasks 须兼容 pending+overdue(原仅保留 pending)。
+ *
+ * 本文件不修改任何 src/main/java / pages/ 业务代码。
+ * 只读真实源码,未实现 → RED(预期失败),GREEN 阶段再改实现使绿。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// ---------------------------------------------------------------------------
+// 路径锚点(通过向上导航找到仓库根 + 两个子项目目录)
+// __dirname 定位在 cfc-frontend/__tests__/pages/index-home/
+// 往上 5 级到仓库根 E:/cfc/;再分别接入 cfc-backend / cfc-frontend 子项目
+// ---------------------------------------------------------------------------
+
+var REPO_ROOT = path.resolve(__dirname, '../../../../../..')
+var TASK_SERVICE_PATH = path.join(REPO_ROOT, 'cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+var INDEX_HOME_VUE_PATH = path.join(REPO_ROOT, 'cfc-frontend/pages/index-home/index.vue')
+
+describe('task.today.overdueVisible · 后端 status 白名单', function () {
+  var source
+
+  beforeAll(function () {
+    expect(fs.existsSync(TASK_SERVICE_PATH)).toBe(true)
+    source = fs.readFileSync(TASK_SERVICE_PATH, 'utf8')
+  })
+
+  it('getTodayTasks(Long memberId, String dimensionCode) 方法存在', function () {
+    expect(source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')).toBeGreaterThan(-1)
+  })
+
+  it('方法体内 .in(Task::getStatus, ...) 白名单须含 "overdue"', function () {
+    var methodBlock = source.slice(
+      source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)'),
+      source.indexOf('getTodayTasksByFamily')
+    )
+    expect(methodBlock.includes('"overdue"') || methodBlock.includes("'overdue'")).toBe(true)
+  })
+})
+
+describe('task.today.overdueVisible · 家族口径 status 白名单', function () {
+  var source
+
+  beforeAll(function () {
+    expect(fs.existsSync(TASK_SERVICE_PATH)).toBe(true)
+    source = fs.readFileSync(TASK_SERVICE_PATH, 'utf8')
+  })
+
+  it('getTodayTasksByFamily(Long familyId) 方法的白名单须含 overdue', function () {
+    var start = source.indexOf('public List<Task> getTodayTasksByFamily(Long familyId)')
+    // 截取到下一个私有方法边界(filterLockedChildren)
+    var end = source.indexOf('private List<Task> filterLockedChildren', start)
+    var familyBlock = source.slice(start, end >= 0 ? end : source.length)
+    expect(familyBlock.includes('"overdue"') || familyBlock.includes("'overdue'")).toBe(true)
+  })
+})
+
+describe('task.today.overdueVisible · 前端 loadTodayTasks 契约', function () {
+  var vueSource
+
+  beforeAll(function () {
+    expect(fs.existsSync(INDEX_HOME_VUE_PATH)).toBe(true)
+    vueSource = fs.readFileSync(INDEX_HOME_VUE_PATH, 'utf8')
+  })
+
+  /** 提取同名方法体(从第一个左大括号到嵌套返回的闭合) */
+  function extractMethodBody(bodyName) {
+    var idx = vueSource.indexOf(bodyName + ': ')
+    if (idx < 0) throw new Error('无法在 index.vue 中定位 ' + bodyName)
+    if (idx < 0) throw new Error('无法在 index.vue 中定位 ' + bodyName)
+    var braceStart = vueSource.indexOf('{', idx)
+    var depth = 0
+    var pos
+    for (pos = braceStart; pos < vueSource.length; pos++) {
+      var ch = vueSource[pos]
+      if (ch === '{') depth++
+      else if (ch === '}') { depth--; if (depth === 0) return vueSource.slice(braceStart, pos + 1) }
+    }
+    throw new Error(bodyName + ' 方法体大括号未闭合')
+  }
+
+  it('pendingTasks 的 filter 不再仅保留 pending(需兼容 overdue)', function () {
+    var body = extractMethodBody('loadTodayTasks')
+    // 拒绝只有 t.status !== 'pending' 判断且整块不过滤 overdue 的旧口径
+    var hasPendingOnlyFilter = /\bt\.status\s*!==\s*'pending'\b/.test(body) && !body.includes('overdue')
+    expect(hasPendingOnlyFilter).toBe(false)
+  })
+
+  it("当 task.status === 'overdue' 时必须把 _isOverdue 置为 true", function () {
+    var body = extractMethodBody('loadTodayTasks')
+    var hasIsOverdueAssign = /_isOverdue\s*=\s*true/.test(body)
+    expect(hasIsOverdueAssign).toBe(true)
+    // 必须在处理 status='overdue' 的路径里(不是仅在 latestEnd 分支),否则跨天任务的补做标记缺失
+    expect(body.indexOf("t.status") >= 0 && body.indexOf('overdue') >= 0).toBe(true)
+  })
+
+  it('原有的 latestEnd < now 路径须保持向后兼容(pending 今天到期仍可标已超期)', function () {
+    var body = extractMethodBody('loadTodayTasks')
+    // latestEnd 或 parseDate 引用只要任一存在即满足契约(不要求新增,但不得删除既有路径)
+    var hasLatestEndPath = body.indexOf('latestEnd') >= 0 || body.indexOf('parseDate') >= 0
+    expect(hasLatestEndPath).toBe(true)
+  })
+})
+
+describe('task.today.overdueVisible · 前端渲染结构契约', function () {
+  var template
+
+  beforeAll(function () {
+    expect(fs.existsSync(INDEX_HOME_VUE_PATH)).toBe(true)
+    var src = fs.readFileSync(INDEX_HOME_VUE_PATH, 'utf8')
+    var m = src.match(/<template>([\s\S]*?)<\/template>/)
+    if (!m) throw new Error('index.vue 无 <template> 块')
+    template = m[1]
+  })
+
+  it('v-if="hasPendingTasks" 门控保留(不改渲染门槛)', function () {
+    expect(template).toMatch(/v-if="hasPendingTasks"/)
+  })
+
+  it('已超期任务卡片带 task-quick-item--overdue class', function () {
+    expect(template).toMatch(/task-quick-item--overdue/)
+  })
+
+  it('已超期任务元数据展示「已超期」文案', function () {
+    expect(template).toMatch(/已超期/)
+  })
+
+  it('_isOverdue=true 时只显示 badge 而隐藏「完成」按钮(v-else 互斥覆盖)', function () {
+    expect(template).toMatch(/v-if="[^"]*\_isOverdue[^"]*"/)
+    expect(template).toMatch(/class="[^"]*status-badge-overdue[^"]*"[^>]*>.*?已超期/)
+  })
+})

+ 157 - 0
cfc-frontend/__tests__/pages/profile-main/assetsEntry.contract.test.js

@@ -0,0 +1,157 @@
+/**
+ * 契约级单测(静态结构契约)——能力键 ui.profile.assetsEntry
+ *
+ * 溯源 / 变更说明:
+ *   本文件替代已退役的 achievement.fiveCol.test.js 与 achievementLayout.contract.test.js。
+ *   那两个用例守护的是「我的成就」固定五列(需求变更 D / SC-A-27 / SC-P-96)。
+ *   2026-11-28「我的」页收敛重设计(主动健康生活方式 · 极致简单)明确:
+ *     * 我的成就(5 宫格)、我的订单(5+2 宫格)、卡券中心(2 宫格)
+ *       → 收敛为「我的资产」单卡内 3 汇总入口(订单 / 卡券 / 成就),明细进二级页;
+ *     * 因此「成就固定五列」能力被本页目标结构取代,原两个五列用例失效退役,
+ *       由本文件守护新结构。若后续需求侧要求恢复五列,应以新用例另行守护,
+ *       不得直接复活旧用例(旧用例同时断言了已删除的 order/coupon 网格布局)。
+ *
+ * 契约要点(本文件守护的破坏):
+ *   1) 「我的资产」入口存在,且为单卡 + 3 宫格(订单 / 卡券 / 成就),每入口有明确跳转;
+ *   2) 收敛彻底性:模板不得残留五列成就网格、订单五宫格、卡券宫格;
+ *      样式不得残留 .achievement-grid.cols-5 / .order-* 规则;
+ *   3) 双邀请入口治理:浮动邀请按钮(.share-qr-float)已删,团队网格「邀请成员」
+ *      分享项(.ach-item-share + open-type="share")保留,全页仅剩一个邀请入口;
+ *   4) 死方法清理:goToTasks / goToAppointments(模板未引用的历史死方法)已删;
+ *   5) 访客态登录引导复用共享 LoginGuideCard,不再内联 gp-guide 结构;
+ *   6) 订单入口展示四态合计汇总数(computed orderTotal),不再逐态铺 5 个徽标。
+ *
+ * 断言口径(静态结构契约,读真实 SFC 源码,不依赖渲染引擎):
+ *   cfc-frontend jest.config.js 仅 transform .js,未装 vue-jest/jsdom 组件环境——
+ *   沿用既有约定:读取真实 SFC 源码做结构契约断言
+ *   (同目录 bottomMenuOverflow.contract.test.js 的读源法)。本文件不修改 pages/ 业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+const PAGE_PATH = path.join(__dirname, '../../../pages/profile-main/profile.vue')
+const SRC = fs.readFileSync(PAGE_PATH, 'utf8')
+
+function templateOf(src) {
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  return m ? m[1] : ''
+}
+
+function scriptOf(src) {
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  return m ? m[1] : ''
+}
+
+function styleOf(src) {
+  const m = src.match(/<style[^>]*>([\s\S]*?)<\/style>/)
+  return m ? m[1] : ''
+}
+
+const TEMPLATE = templateOf(SRC)
+const SCRIPT = scriptOf(SRC)
+const STYLE = styleOf(SRC)
+
+/** 取模板中「我的资产」区块:从 assets-section 到 team 之前的片段 */
+function assetsSection(src) {
+  const t = templateOf(src)
+  const start = t.indexOf('assets-section')
+  if (start < 0) return ''
+  // 资产区之后紧接团队区(achievement-section / team-grid)或无其它
+  const next = t.indexOf('team-grid', start)
+  return t.slice(start, next > 0 ? next : t.length)
+}
+
+const ASSETS = assetsSection(SRC)
+
+describe('ui.profile.assetsEntry · 「我的」页资产入口收敛(订单/卡券/成就 3 宫格)', () => {
+  test('TC-AE-01 资产入口区存在,且以共享 BaseCard 单卡承载', () => {
+    expect(ASSETS).not.toBe('')
+    expect(TEMPLATE).toMatch(/<BaseCard[^>]*class="assets-card"/)
+    expect(TEMPLATE).toMatch(/class="assets-title"[^>]*>我的资产</)
+  })
+
+  test('TC-AE-02 资产卡内恰 3 个宫格入口,文案与跳转方法齐备', () => {
+    const cells = ASSETS.match(/class="asset-cell"/g) || []
+    expect(cells.length).toBe(3)
+    const map = [
+      { handler: 'goToOrders', label: '订单', expr: 'orderTotal' },
+      { handler: 'goToCoupons', label: '卡券', expr: 'couponCount' },
+      { handler: 'goToBadges', label: '成就', expr: 'badgesCollected' }
+    ]
+    map.forEach((item) => {
+      expect(ASSETS).toMatch(new RegExp('@click="' + item.handler + '"'))
+      // 文案与汇总数同属一个 cell
+      expect(ASSETS).toMatch(new RegExp(item.handler + '[\\s\\S]*?' + item.label))
+      expect(ASSETS).toMatch(new RegExp(item.handler + '[\\s\\S]*?\\{\\{\\s*' + item.expr + '\\s*\\}\\}'))
+    })
+  })
+
+  test('TC-AE-03 收敛彻底性:模板不再有五列成就网格 / 订单五宫格 / 卡券宫格', () => {
+    expect(TEMPLATE).not.toMatch(/achievement-grid\s+cols-5/)
+    expect(TEMPLATE).not.toMatch(/class="order-grid"|class="order-grid-item"|class="order-section"|class="order-card"/)
+    expect(TEMPLATE).not.toMatch(/class="order-icon-wrap"|class="order-extra-item"/)
+    // 原「我的成就 / 卡券中心」独立区块标题不应再出现
+    expect(TEMPLATE).not.toMatch(/我的成就/)
+    expect(TEMPLATE).not.toMatch(/卡券中心/)
+  })
+
+  test('TC-AE-04 收敛彻底性:样式不再残留五列 / 订单宫格规则,且有资产卡样式', () => {
+    expect(STYLE).not.toMatch(/\.achievement-grid\.cols-5/)
+    expect(STYLE).not.toMatch(/\.order-grid\b|\.order-card\b|\.order-icon-wrap\b|\.order-extra-item\b/)
+    expect(STYLE).toMatch(/\.assets-grid\b/)
+    expect(STYLE).toMatch(/\.asset-cell\b/)
+    expect(STYLE).toMatch(/\.asset-ic-order\b/)
+    expect(STYLE).toMatch(/\.asset-ic-coupon\b/)
+    expect(STYLE).toMatch(/\.asset-ic-achieve\b/)
+  })
+
+  test('TC-AE-05 订单汇总入口用 computed orderTotal(四态合计),不再逐态徽标', () => {
+    expect(SCRIPT).toMatch(/orderTotal\(\)/)
+    expect(SCRIPT).toMatch(/orderPending \+ this\.orderUnpaid \+ this\.orderShipped \+ this\.orderAfterSale/)
+    // 逐态跳转方法已随订单五宫格一起删除
+    expect(SCRIPT).not.toMatch(/goToOrderStatus/)
+    // 购物车 / 收货地址 入口随订单附加行删除
+    expect(SCRIPT).not.toMatch(/goToCart|goToAddress|loadCartCount/)
+  })
+
+  test('TC-AE-06 双邀请入口治理:浮动邀请已删,团队网格分享项唯一保留', () => {
+    // 浮动二维码邀请按钮整块删除
+    expect(TEMPLATE).not.toMatch(/share-qr-float|qr-glyph|qr-eye/)
+    expect(STYLE).not.toMatch(/\.share-qr-float\b|\.qr-glyph\b/)
+    // 团队「邀请成员」分享项保留,且全页仅剩一个 open-type="share"
+    expect(TEMPLATE).toMatch(/class="ach-item ach-item-share"[\s\S]*?open-type="share"/)
+    const shareButtons = TEMPLATE.match(/open-type="share"/g) || []
+    expect(shareButtons.length).toBe(1)
+    // 团队网格三入口仍在
+    expect(TEMPLATE).toMatch(/team-grid/)
+  })
+
+  test('TC-AE-07 死方法清理:goToTasks / goToAppointments 已删', () => {
+    expect(SCRIPT).not.toMatch(/goToTasks/)
+    expect(SCRIPT).not.toMatch(/goToAppointments/)
+    // 连带失效的五宫格成就 / 卡券二级跳转方法亦应清理
+    expect(SCRIPT).not.toMatch(/goToStreak|goToTaskHistory|goToGrowth|goToChallenges|goToWishes/)
+  })
+
+  test('TC-AE-08 访客态登录引导复用 LoginGuideCard,不再内联实现', () => {
+    expect(TEMPLATE).toMatch(/<LoginGuideCard/)
+    // 内联登录引导的自绘结构(标题/清单/勾选/按钮)必须清除;
+    // .gp-guide 仅保留为外层横向边距容器(与 .gg-guide/.gh-guide 同款),故不在禁用项内
+    expect(TEMPLATE).not.toMatch(/gp-guide-head|gp-guide-title|gp-guide-list|gp-guide-item|gp-guide-check|gp-guide-ic\b|gp-guide-btn|gp-guide-text|gp-guide-desc/)
+    expect(STYLE).not.toMatch(/\.gp-guide-(head|title|list|item|check|ic|btn|text|desc)\b/)
+    // 外层边距容器存在(保持与本页其它访客卡同宽)
+    expect(STYLE).toMatch(/\.gp-guide\s*\{\s*margin:\s*0 32rpx 8rpx/)
+    // 组件已注册
+    expect(SCRIPT).toMatch(/components:\s*\{[^}]*LoginGuideCard/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:资产入口区为已登录态统一展示,无角色门禁分支
+// (规划师服务中心另有 v-if 门禁,不在本契约范围)。显式记录不适用项。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:资产入口区无角色门禁,不适用', () => {
+  it('占位:资产入口对所有已登录用户一致展示(详见汇报)', () => {})
+})

+ 116 - 0
cfc-frontend/__tests__/pages/profile-main/bottomMenuOverflow.contract.test.js

@@ -0,0 +1,116 @@
+/**
+ * 契约级单测:「我的」页底部菜单(历史消息 / 设置 / 退出登录)右溢出修复
+ * 设计正本:docs/design/2026-11-26-profile-bottommenu-overflow-spec.md
+ *
+ * 根因:小程序 view 未全局设 box-sizing(uni.scss / App.vue 均无声明),
+ * 默认 content-box 下,显式 width:100% 且四边 padding 非零 的块级元素
+ * 会在左右各撑出 padding 宽度,超出父容器(.bottom-menu-section 仅有 margin)。
+ * .menu-row 与 .logout-btn 是全页仅有的两个「width:100% + 四边 padding 24rpx」
+ * 元素,故三项菜单全部右溢 24rpx。
+ *
+ * 沿用项目既有 SFC 源码抽取式约定(见 __tests__/pages/shop/cartLayout.contract.test.js):
+ * jest 无 vue-jest/jsdom,直接读取真实 .vue 原文断言样式。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const ROOT = path.join(__dirname, '../../..')
+const VUE_PATH = path.join(ROOT, 'pages/profile-main/profile.vue')
+
+function read(file) {
+  return fs.readFileSync(file, 'utf8')
+}
+
+function styleOf(src) {
+  const m = src.match(/<style[^>]*>([\s\S]*?)<\/style>/)
+  return m ? m[1] : ''
+}
+
+function templateOf(src) {
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  return m ? m[1] : ''
+}
+
+/** 提取指定 class 的样式块内容 */
+function ruleOf(style, selector) {
+  const re = new RegExp(selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*\\{([\\s\\S]*?)\\}')
+  const m = style.match(re)
+  return m ? m[1] : ''
+}
+
+/** 解析 padding 简写的左右分量(单位 rpx);未设置返回 null */
+function paddingLR(pad) {
+  if (!pad) return null
+  const parts = pad.trim().split(/\s+/)
+  let left, right
+  if (parts.length >= 3) {
+    left = parts[3]
+    right = parts[1]
+  } else if (parts.length === 2) {
+    left = parts[1]
+    right = parts[1]
+  } else {
+    left = parts[0]
+    right = parts[0]
+  }
+  return { left, right }
+}
+
+/** 把一条规则体的 padding 数值(去 rpx)取出来,非零判定用 */
+function padLRValue(rule) {
+  const m = rule.match(/padding\s*:\s*([^;]+);?/)
+  if (!m) return null
+  return paddingLR(m[1])
+}
+
+describe('「我的」页底部菜单布局契约(右溢出修复)', () => {
+  const src = read(VUE_PATH)
+  const style = styleOf(src)
+  const template = templateOf(src)
+
+  test('模板含底部菜单区:历史消息 / 设置 / 退出登录 三项', () => {
+    // 用户报告的三项 = 📨历史消息 + ⚙️设置(口语"设备") + 🚪退出登录
+    expect(template).toMatch(/bottom-menu-section/)
+    expect(template).toMatch(/menu-row-text[^>]*>[^<]*历史消息/)
+    expect(template).toMatch(/menu-row-text[^>]*>[^<]*设置/)
+    expect(template).toMatch(/logout-btn[\s\S]*?退出登录/)
+  })
+
+  test('.menu-row 规则存在,且不含 width:100%(content-box 下四边 padding 会左右溢出)', () => {
+    const rule = ruleOf(style, '.menu-row')
+    expect(rule).toBeTruthy()
+    // 必须保留四边 padding(视觉需要),仅不得显式设 100% 宽度
+    expect(rule).toMatch(/padding\s*:\s*24rpx/)
+    expect(rule).not.toMatch(/width\s*:\s*100%/)
+  })
+
+  test('.logout-btn 规则存在,且不含 width:100%', () => {
+    const rule = ruleOf(style, '.logout-btn')
+    expect(rule).toBeTruthy()
+    expect(rule).toMatch(/padding\s*:\s*24rpx/)
+    expect(rule).not.toMatch(/width\s*:\s*100%/)
+  })
+
+  test('全局守卫:本页任何 width:100% 规则,其 padding 左右分量必须为 0 或未设置', () => {
+    // 捕获力:将来若有人给任一卡片加 width:100% + 左右 padding,契约立即红。
+    // 合法例外:.gp-login-btn/.gp-ghost-btn(padding: N 0,左右 0)、
+    // .share-overlay-btn(position:absolute + padding:0)。
+    const widthRules = []
+    const re = /([.#][\w-]+(?:[\s,.#>+][\w.#>+\s-]*)?)\s*\{([^{}]*width\s*:\s*100%[^{}]*)\}/g
+    let m
+    while ((m = re.exec(style)) !== null) {
+      widthRules.push({ sel: m[1].trim(), body: m[2] })
+    }
+    expect(widthRules.length).toBeGreaterThan(0)
+    for (const r of widthRules) {
+      const pad = padLRValue(r.body)
+      // 绝对定位 + padding:0 的分享按钮合法;其余若左右 padding 非零 → 溢出
+      const abs = /position\s*:\s*absolute/.test(r.body)
+      if (abs) continue
+      if (pad) {
+        const lr0 = (v) => /^0(?:rpx|px)?$/.test((v || '').trim())
+        expect(lr0(pad.left) && lr0(pad.right)).toBe(true)
+      }
+    }
+  })
+})

+ 231 - 0
cfc-frontend/__tests__/pages/shop/cartLayout.contract.test.js

@@ -0,0 +1,231 @@
+/**
+ * 契约级单测:购物车总价安全区适配 + 商城/首页双入口常驻显眼
+ * 设计正本:docs/design/2026-11-26-cart-spec.md §6.1 / §6.2 / §6.3
+ *
+ * 沿用项目既有 SFC 源码抽取式约定(见 __tests__/pages/health/healthSurvey.memberPicker.test.js):
+ * jest 无 vue-jest/jsdom,直接读取真实 .vue 原文断言样式/模板,
+ * <script> 抽取时把 import 替换为桩,再真实调用 computeQuickApps。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const ROOT = path.join(__dirname, '../../..')
+const CART_PATH = path.join(ROOT, 'pages/shop/cart/cart.vue')
+const SHOP_INDEX_PATH = path.join(ROOT, 'pages/shop/index/index.vue')
+const HOME_INDEX_PATH = path.join(ROOT, 'pages/index-home/index.vue')
+
+function read(file) {
+  return fs.readFileSync(file, 'utf8')
+}
+
+function styleOf(src) {
+  const m = src.match(/<style[^>]*>([\s\S]*?)<\/style>/)
+  return m ? m[1] : ''
+}
+
+function templateOf(src) {
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  return m ? m[1] : ''
+}
+
+/** 提取指定 class 的样式块内容 */
+function ruleOf(style, selector) {
+  const re = new RegExp(selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*\\{([\\s\\S]*?)\\}')
+  const m = style.match(re)
+  return m ? m[1] : ''
+}
+
+/** 把 import 语句替换为全局桩读取(与 healthSurvey.memberPicker.test.js 同约定) */
+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) {
+      // 惰性取桩:loadSfcScript 在 describe 定义期执行,此时 beforeEach 尚未设置逐例桩
+      return 'var ' + n + ' = function() { var s = (globalThis.__cartStubs[' + JSON.stringify(id) +
+        '] || {})[' + JSON.stringify(n) + ']; return typeof s === "function" ? s.apply(this, arguments) : s; };'
+    }).join('\n')
+  })
+}
+
+function loadSfcScript(file) {
+  if (!globalThis.__cartStubs) globalThis.__cartStubs = {}
+  var src = read(file)
+  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 mod.exports
+}
+
+beforeEach(function () {
+  globalThis.__cartStubs = {}
+})
+
+// ---------- bug① cart.vue 底部结算栏 ----------
+describe('cart.vue 底部结算栏:总价完整显示 + iOS 安全区', function () {
+  const style = styleOf(read(CART_PATH))
+
+  test('bottom-bar 用 min-height:112rpx 替代定高 120rpx', function () {
+    expect(style).toContain('min-height: 112rpx')
+    expect(style).not.toContain('height: 120rpx')
+  })
+
+  test('bottom-bar 双行安全区兜底(constant 旧 iOS + env 新 iOS)', function () {
+    expect(style).toContain('padding-bottom: calc(20rpx + constant(safe-area-inset-bottom))')
+    expect(style).toContain('padding-bottom: calc(20rpx + env(safe-area-inset-bottom, 0px))')
+    expect(style).toContain('padding: 20rpx $uni-space-page')
+  })
+
+  test('bottom-bar 层级降到 10,不压过弹窗 30', function () {
+    const bar = ruleOf(style, '.bottom-bar')
+    expect(bar).toContain('z-index: 10')
+    expect(bar).not.toContain('z-index: 100')
+  })
+
+  test('价格数字 nowrap、左右块 flex-shrink:0、right 块 min-width:0 + margin-left:12rpx', function () {
+    expect(style).toContain('white-space: nowrap')
+    expect(ruleOf(style, '.bottom-left')).toContain('flex-shrink: 0')
+    const right = ruleOf(style, '.bottom-right')
+    expect(right).toContain('flex-shrink: 0')
+    expect(right).toContain('min-width: 0')
+    expect(right).toContain('margin-left: 12rpx')
+    expect(ruleOf(style, '.total-amount')).toContain('white-space: nowrap')
+    expect(ruleOf(style, '.price-estimate')).toContain('white-space: nowrap')
+    expect(ruleOf(style, '.price-original')).toContain('white-space: nowrap')
+  })
+
+  test('会员态双行价格:price-compare 基线对齐不折行,标签 28rpx', function () {
+    expect(ruleOf(style, '.price-compare')).toContain('display: flex')
+    expect(ruleOf(style, '.price-compare')).toContain('align-items: baseline')
+    expect(ruleOf(style, '.price-compare')).toContain('gap: 8rpx')
+    expect(ruleOf(style, '.price-compare')).toContain('white-space: nowrap')
+    expect(style).toMatch(/price-original-label\s*,\s*\.price-estimate-label\s*\{/)
+    expect(style).toContain('calc(28rpx * var(--font-scale, 1))')
+  })
+})
+
+// ---------- bug② 之一:商城页购物车入口 ----------
+describe('shop/index.vue 购物车入口:88rpx + 品牌浅底 + 非 emoji 图标', function () {
+  const src = read(SHOP_INDEX_PATH)
+  const style = styleOf(src)
+  const tpl = templateOf(src)
+
+  test('cart-btn 尺寸 88rpx、品牌浅底、品牌描边', function () {
+    const btn = ruleOf(style, '.cart-btn')
+    expect(btn).toContain('width: 88rpx')
+    expect(btn).toContain('height: 88rpx')
+    expect(btn).toContain('background: $uni-primary-pale')
+    expect(btn).toContain('border: 1rpx solid $brand-primary-light-2')
+    expect(btn).toContain('flex-shrink: 0')
+  })
+
+  test('模板与样式中不得出现 emoji 🛒', function () {
+    expect(tpl).not.toContain('🛒')
+    expect(style).not.toContain('🛒')
+  })
+
+  test('图标为纯 CSS 购物车轮廓(伪元素 + border),角标在 88rpx 容器内 top/right -4rpx', function () {
+    expect(style).toContain('.cart-icon::before')
+    expect(style).toContain('border: 3rpx solid $brand-primary')
+    const badge = ruleOf(style, '.cart-badge')
+    expect(badge).toContain('top: -4rpx')
+    expect(badge).toContain('right: -4rpx')
+    expect(badge).toContain('min-width: 32rpx')
+    expect(badge).toContain('height: 32rpx')
+    expect(tpl).toContain("cartCount > 99 ? '99+' : cartCount")
+  })
+})
+
+// ---------- bug② 之二:首页快捷区 cart 常驻 ----------
+describe('index-home/index.vue computeQuickApps:cart 常驻保障', function () {
+  const homeSrc = read(HOME_INDEX_PATH)
+  const component = loadSfcScript(HOME_INDEX_PATH)
+  const compute = component.methods.computeQuickApps
+  const vm = { memberActive: true }
+
+  function appKeys() {
+    return ['task', 'interaction', 'tiandi', 'members', 'circle', 'shop', 'growth', 'wish']
+  }
+
+  test('源码含 cart 常驻保障(appKey 判定 + 追加/替换 + 全锁定尊重)', function () {
+    const body = homeSrc.slice(
+      homeSrc.indexOf('computeQuickApps: function'),
+      homeSrc.indexOf('getDefaultQuickApps: function')
+    )
+    expect(body).toContain("item.appKey === 'cart'")
+    expect(body).toContain("result.push({ appKey: 'cart', locked: 0, sortOrder: 99 })")
+    expect(body).toContain("result[i].locked !== 1")
+  })
+
+  test('未满 4 格且无 cart:追加 cart 到末位', function () {
+    globalThis.__cartStubs['../../utils/app-library.js'] = {
+      getShortcutableApps: function () {
+        return appKeys().slice(0, 3).map(function (k) { return { key: k, name: k } })
+      }
+    }
+    const shortcuts = appKeys().slice(0, 6).map(function (k, i) {
+      return { appKey: k, locked: 0, sortOrder: i }
+    })
+    const result = compute.call(vm, shortcuts, {})
+    expect(result.length).toBe(4)
+    expect(result.some(function (x) { return x.appKey === 'cart' })).toBe(true)
+    expect(result[result.length - 1].appKey).toBe('cart')
+  })
+
+  test('满 4 格且无 cart:替换最后一个非锁定项,cart 常驻且总数仍为 4', function () {
+    globalThis.__cartStubs['../../utils/app-library.js'] = {
+      getShortcutableApps: function () {
+        return appKeys().map(function (k) { return { key: k, name: k } })
+      }
+    }
+    const shortcuts = appKeys().slice(0, 6).map(function (k, i) {
+      return { appKey: k, locked: 0, sortOrder: i }
+    })
+    const result = compute.call(vm, shortcuts, {})
+    expect(result.length).toBe(4)
+    expect(result.some(function (x) { return x.appKey === 'cart' })).toBe(true)
+  })
+
+  test('4 个全锁定且无 cart:尊重用户锁定选择,不追加也不替换', function () {
+    globalThis.__cartStubs['../../utils/app-library.js'] = {
+      getShortcutableApps: function () {
+        return appKeys().map(function (k) { return { key: k, name: k } })
+      }
+    }
+    const shortcuts = appKeys().slice(0, 6).map(function (k, i) {
+      return { appKey: k, locked: 1, sortOrder: i }
+    })
+    const result = compute.call(vm, shortcuts, {})
+    expect(result.length).toBe(4)
+    expect(result.every(function (x) { return x.locked === 1 })).toBe(true)
+    expect(result.some(function (x) { return x.appKey === 'cart' })).toBe(false)
+  })
+
+  test('cart 项模板有条件 class + 品牌浅底描边样式', function () {
+    expect(homeSrc).toContain("'quick-item--cart': app.key === 'cart'")
+    expect(styleOf(homeSrc)).toContain('.quick-item--cart .quick-icon')
+    expect(styleOf(homeSrc)).toContain('background: $uni-primary-pale !important')
+    expect(styleOf(homeSrc)).toContain('border: 1rpx solid $brand-primary-light-2')
+  })
+})

+ 224 - 0
cfc-frontend/__tests__/pages/shop/checkout.couponAfterAddressReturn.spec.js

@@ -0,0 +1,224 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:shop.checkout.couponAfterAddressReturn (BUGFIX-2026-11-25)
+// 溯源·需求:主理人派单「小程序结算页优惠券丢失」——用户反馈:
+//   「选不了地址」「用了优惠券,选地址再回来提交订单,显示为未用券价格」
+// 溯源·实现:cfc-frontend/pages/shop/checkout/checkout.vue
+//   + pages/shop/address/address.vue(selectMode=1,选中写 checkoutSelectedAddressId 兜底)
+//
+// 说明:源读取契约(与既有 checkout.couponAutoSelect / order-detail.refundAndBuyAgain 同风格)。
+// 红线思维:先写能暴露缺陷的断言(RED),再修复源码(GREEN)。
+//   - RED 点 A:地址选择/编辑返回(onShow 非首次)后必须重新向服务端确认已选券抵扣额,
+//     防止「返回结算页再提交显示未用券价」。此断言已锚定「返回(else)分支」,而非只认
+//     onShow 体内出现过调用,防止被误挪到首次进入(if)分支而假绿。
+//   - RED 点 B:applyCouponDiscount 失败分支不得无条件清空已选券——仅服务端明确判定
+//     "不可用"(业务码 code 存在)才清空;瞬时失败(网络/超时)保留,交由下单权威裁决。
+//   - RED 点 C:支付页金额透传 taskId 必须用闭包变量 that(setTimeout 回调内 this 非组件实例)。
+
+const CHECKOUT_VUE = resolve(__dirname, '../../../pages/shop/checkout/checkout.vue')
+const PAYMENT_VUE = resolve(__dirname, '../../../pages/shop/payment/payment.vue')
+const source = readFileSync(CHECKOUT_VUE, 'utf8')
+
+// ---- 通用:用「括号配平」从源码中切出方法体,容忍任意缩进/换行/async 前缀 ----
+// 返回不含最外层大括号的方法体;找不到返回 ''。跳过字符串字面量与注释,防止误配平。
+function extractMethodBody(src, name) {
+  const re = new RegExp('(^|\\n)[ \\t]*(?:async\\s+)?' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*\\(')
+  const start = src.search(re)
+  if (start < 0) return ''
+  const braceIdx = src.indexOf('{', start)
+  if (braceIdx < 0) return ''
+  let depth = 0
+  let inStr = null
+  let inLineComment = false
+  let inBlockComment = false
+  let bodyStart = -1
+  for (let i = braceIdx; i < src.length; i++) {
+    const ch = src[i]
+    const next = src[i + 1]
+    if (inLineComment) {
+      if (ch === '\n') inLineComment = false
+      continue
+    }
+    if (inBlockComment) {
+      if (ch === '*' && next === '/') { inBlockComment = false; i++ }
+      continue
+    }
+    if (inStr) {
+      if (ch === '\\') { i++; continue }
+      if (ch === inStr) inStr = null
+      continue
+    }
+    if (ch === '/' && next === '/') { inLineComment = true; i++; continue }
+    if (ch === '/' && next === '*') { inBlockComment = true; i++; continue }
+    if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue }
+    if (ch === '{') {
+      if (depth === 0) bodyStart = i + 1
+      depth++
+      continue
+    }
+    if (ch === '}') {
+      depth--
+      if (depth === 0) return src.slice(bodyStart, i)
+    }
+  }
+  return ''
+}
+
+const onShowBody = extractMethodBody(source, 'onShow')
+const applyCatchBody = extractMethodBody(source, 'applyCouponDiscount')
+const loadAddrBody = extractMethodBody(source, 'loadDefaultAddress')
+
+// onShow 体按 `} else {` 切出「首次进入(if)」与「返回(else)」两个分支
+const onShowElseIdx = onShowBody.search(/\}\s*else\s*\{/)
+const onShowIfBranch = onShowElseIdx >= 0 ? onShowBody.slice(0, onShowElseIdx) : ''
+const onShowReturnBranch = onShowElseIdx >= 0
+  ? onShowBody.slice(onShowBody.indexOf('{', onShowElseIdx) + 1)
+  : ''
+
+// 从 src 的 fromIdx 起,取下一个 `{` 开始、括号配平的块内内容(跳过字符串/注释)
+function balancedBlock(src, fromIdx) {
+  const braceIdx = src.indexOf('{', fromIdx)
+  if (braceIdx < 0) return ''
+  let depth = 0
+  let inStr = null
+  let inLineComment = false
+  let inBlockComment = false
+  let bodyStart = -1
+  for (let i = braceIdx; i < src.length; i++) {
+    const ch = src[i]
+    const next = src[i + 1]
+    if (inLineComment) {
+      if (ch === '\n') inLineComment = false
+      continue
+    }
+    if (inBlockComment) {
+      if (ch === '*' && next === '/') { inBlockComment = false; i++ }
+      continue
+    }
+    if (inStr) {
+      if (ch === '\\') { i++; continue }
+      if (ch === inStr) inStr = null
+      continue
+    }
+    if (ch === '/' && next === '/') { inLineComment = true; i++; continue }
+    if (ch === '/' && next === '*') { inBlockComment = true; i++; continue }
+    if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue }
+    if (ch === '{') {
+      if (depth === 0) bodyStart = i + 1
+      depth++
+      continue
+    }
+    if (ch === '}') {
+      depth--
+      if (depth === 0) return src.slice(bodyStart, i)
+    }
+  }
+  return ''
+}
+
+// setTimeout 回调体(url 拼接所在上下文),用于精准断言 taskId 闭包取值
+const setTimeoutBody = (() => {
+  const idx = source.indexOf('setTimeout')
+  if (idx < 0) return ''
+  // setTimeout(function() { ... }):取 function 后首个 `{` 的配平块
+  return balancedBlock(source, idx)
+})()
+// 支付页跳转 url 行(仅限 setTimeout 回调内;找不到则回退全文件)
+function paymentUrlLines(scope) {
+  return scope.split('\n').filter(l => /url\s*:\s*['"`]\/?pages\/shop\/payment\/payment/.test(l))
+}
+let urlLines = paymentUrlLines(setTimeoutBody || source)
+if (urlLines.length === 0) urlLines = paymentUrlLines(source)
+
+// RED-B:catch 块必须存在「对业务码 code 的存在性判断」——容忍等价写法
+const hasCodeExistenceGuard = [
+  /e\s*&&\s*e\.code/,                                   // e && e.code(短路守卫)
+  /e\.code\s*!=\s*null/,
+  /e\.code\s*!==\s*null/,
+  /e\.code\s*!=\s*undefined/,
+  /e\.code\s*!==\s*undefined/,
+  /typeof\s+e\.code\s*!==?\s*['"`]undefined['"`]/,      // typeof e.code !== 'undefined'
+  /['"`]code['"`]\s*in\s*e/                              // 'code' in e
+].some(re => re.test(applyCatchBody))
+
+describe('checkout.vue 选地址返回后优惠券不丢失(BUGFIX-2026-11-25)', () => {
+  // ---- RED-A:返回分支必须重同步券抵扣 ----
+  test('RED-A:onShow 返回(else)分支重新向服务端确认已选券抵扣额', () => {
+    expect(onShowReturnBranch).toMatch(/applyCouponDiscount\s*\(\s*\)/)
+  })
+
+  test('RED-A-防漂移:首次进入(if)分支不得触发券重同步', () => {
+    // 若被误挪到首次分支,onShow 首次进入就会重复调 /api/coupon/apply(双请求)
+    expect(onShowIfBranch).not.toMatch(/applyCouponDiscount\s*\(\s*\)/)
+  })
+
+  test('RED-A-返回路径仍刷新地址:返回分支须调用 loadDefaultAddress()', () => {
+    expect(onShowReturnBranch).toMatch(/loadDefaultAddress\s*\(\s*\)/)
+  })
+
+  test('RED-A-守卫:onShow 返回路径不得清空已选券或抵扣额', () => {
+    expect(onShowReturnBranch).not.toMatch(/selectedCoupon\s*=\s*null/)
+    expect(onShowReturnBranch).not.toMatch(/couponDiscount\s*=\s*0/)
+  })
+
+  test('RED-A-条件:返回重同步须同时满足「已选券」与「非特价禁用券」', () => {
+    // 防止漂移成无条件调用(每次返回都打一次接口)——特价禁用券/已取消券都不应重同步
+    expect(onShowReturnBranch).toMatch(/this\.selectedCoupon\s*&&/)
+    expect(onShowReturnBranch).toMatch(/!this\.isSpecialCouponDisabled/)
+  })
+
+  // ---- RED-B:失败分支不得无条件清空已选券 ----
+  test('RED-B:applyCouponDiscount 失败分支须校验业务码 code 的存在性(容忍等价写法)', () => {
+    expect(hasCodeExistenceGuard).toBe(true)
+  })
+
+  test('RED-B-守卫:业务性不可用仍要清空已选券并归零抵扣额(展示与提交一致)', () => {
+    expect(applyCatchBody).toMatch(/selectedCoupon\s*=\s*null/)
+    expect(applyCatchBody).toMatch(/couponDiscount\s*=\s*0/)
+  })
+
+  test('RED-B-受控清空:清空动作必须位于「业务码判断」之后(不得先清后判)', () => {
+    const guardIdx = applyCatchBody.search(/e\.code/)
+    const clearIdx = applyCatchBody.indexOf('selectedCoupon = null')
+    expect(guardIdx).toBeGreaterThanOrEqual(0)
+    expect(clearIdx).toBeGreaterThanOrEqual(0)
+    expect(clearIdx).toBeGreaterThan(guardIdx)
+  })
+
+  // ---- 提交与支付契约 ----
+  test('提交订单透传 couponId(已选券 id,未选为 null)', () => {
+    expect(source).toMatch(/couponId\s*:\s*that\.selectedCoupon\s*\?\s*that\.selectedCoupon\.id\s*:\s*null/)
+  })
+
+  test('支付页金额来源:优先后端权威 moneyAmount,兜底 totalAmount', () => {
+    expect(source).toMatch(/order\.moneyAmount\s*!=\s*null\s*\?\s*order\.moneyAmount\s*:\s*order\.totalAmount/)
+  })
+
+  test('支付页跳转:taskId 透传用闭包变量 that(setTimeout 回调内 this 非组件实例)', () => {
+    expect(urlLines.length).toBeGreaterThan(0)
+    expect(urlLines.some(l => /that\.taskId\s*\?\s*['"`]&taskId=['"`]\s*\+\s*that\.taskId/.test(l))).toBe(true)
+  })
+
+  test('支付页跳转:taskId 取值不得误用 this(this.taskId 在 URL 拼接语境即缺陷)', () => {
+    expect(urlLines.some(l => /this\.taskId/.test(l))).toBe(false)
+  })
+
+  // ---- 地址兜底(症状1):读取 + 一次性消费 ----
+  test('地址兜底-读:loadDefaultAddress 读取 checkoutSelectedAddressId', () => {
+    expect(loadAddrBody).toMatch(/getStorageSync\s*\(\s*['"`]checkoutSelectedAddressId['"`]\s*\)/)
+  })
+
+  test('地址兜底-消费:loadDefaultAddress 一次性 removeStorageSync(防止旧值复用于下次)', () => {
+    expect(loadAddrBody).toMatch(/removeStorageSync\s*\(\s*['"`]checkoutSelectedAddressId['"`]\s*\)/)
+  })
+
+  test('地址选中兜底:结算页与地址页共用 checkoutSelectedAddressId 契约', () => {
+    expect(source).toMatch(/checkoutSelectedAddressId/)
+  })
+
+  test('支付页直接展示 amount 参数(不透传原始商品总额)', () => {
+    const paymentSource = readFileSync(PAYMENT_VUE, 'utf8')
+    expect(paymentSource).toMatch(/parseFloat\(options\.amount\)/)
+  })
+})

+ 33 - 0
cfc-frontend/__tests__/pages/shop/checkout.couponAutoSelect.spec.js

@@ -0,0 +1,33 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:shop.checkout.couponAutoSelect (SHOP-AFTERSALES-2026-11-13-V1 §S3-1/2/3)
+// 溯源·需求:docs/需求分析/2026-11-13-订单售后与购买体验优化需求变更.md §S3 优惠券最优选择与明显提示
+// 溯源·实现:cfc-frontend/pages/shop/checkout/checkout.vue
+//
+// 说明:源读取契约(与小程序既有 __tests__ 风格一致)。校验常规结算进入时自动选最优券、
+//       明显提示「有 N 张优惠券可抵,点击选择」、手动取消后本次不再自动选(_couponDismissed)。
+
+const CHECKOUT_VUE = resolve(__dirname, '../../../pages/shop/checkout/checkout.vue')
+const source = readFileSync(CHECKOUT_VUE, 'utf8')
+
+describe('checkout.vue 优惠券最优选择与明显提示(SHOP-AFTERSALES-2026-11-13-V1 S3)', () => {
+  test('存在 autoSelectCoupon 自动选券方法(S3-1)', () => {
+    expect(source).toMatch(/autoSelectCoupon\s*\(/)
+  })
+
+  test('常规结算进入自动选面额最优券(selectCoupon(best) + _autoSelected 防重复)', () => {
+    expect(source).toMatch(/selectCoupon\s*\(\s*best\s*\)/)
+    expect(source).toMatch(/_autoSelected/)
+  })
+
+  test('存在明显提示「有 N 张优惠券可抵,点击选择」(S3-2)', () => {
+    expect(source).toMatch(/有 .*张优惠券可抵,点击选择/)
+  })
+
+  test('手动取消券后置 _couponDismissed=true,本次结算会话不再自动选(S3-3)', () => {
+    expect(source).toMatch(/removeCoupon\s*\(/)
+    expect(source).toMatch(/_couponDismissed/)
+    expect(source).toMatch(/this\._couponDismissed\s*=\s*true/)
+  })
+})

+ 32 - 0
cfc-frontend/__tests__/pages/shop/order-detail.refundAndBuyAgain.spec.js

@@ -0,0 +1,32 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:shop.orderDetail.cancelRefundAndBuyAgain (SHOP-AFTERSALES-2026-11-13-V1 §S1-6 / §S2-1)
+// 溯源·需求:docs/需求分析/2026-11-13-订单售后与购买体验优化需求变更.md
+// 溯源·实现:cfc-frontend/pages/shop/order-detail/order-detail.vue
+//
+// 说明:源读取契约。校验「取消退款申请」按钮仅在 refundStatus===1 && status==='refunding' 显示并调用
+//       cancelRefund 接口(S1-6);「再次购买」completed 订单一键直进结算、写入 checkoutItems(S2-1)。
+
+const ORDER_DETAIL_VUE = resolve(__dirname, '../../../pages/shop/order-detail/order-detail.vue')
+const source = readFileSync(ORDER_DETAIL_VUE, 'utf8')
+
+describe('order-detail.vue 取消退款 与 再买一单(SHOP-AFTERSALES-2026-11-13-V1 S1-6/S2-1)', () => {
+  test('取消退款申请按钮仅当 refundStatus 为 1 且 status 为 refunding 时显示(S1-6)', () => {
+    expect(source).toMatch(/refundStatus\s*===\s*1\s*&&[^;]*status\s*===\s*['"]refunding['"]/)
+  })
+
+  test('取消退款调用 cancelRefund 接口(S1-6)', () => {
+    expect(source).toMatch(/onCancelRefund\s*\(/)
+    expect(source).toMatch(/cancelRefund\s*\(/)
+  })
+
+  test('再次购买按钮仅当 status 为 completed 时显示(S2-1)', () => {
+    expect(source).toMatch(/status\s*===\s*['"]completed['"]/)
+  })
+
+  test('onBuyAgain 写入 checkoutItems 直进结算(S2-1)', () => {
+    expect(source).toMatch(/onBuyAgain\s*\(/)
+    expect(source).toMatch(/checkoutItems/)
+  })
+})

+ 424 - 0
cfc-frontend/__tests__/pages/signature/signature.canvas2d.test.js

@@ -0,0 +1,424 @@
+/**
+ * 契约级单测 —— 恢复进入签名页自动横屏(用户知情地推翻 11-09 竖屏直签)+ canvas 2d 不回归
+ *
+ * 溯源:
+ *   - 本轮恢复: 进入签名页自动强制横屏(wx.setPageOrientation landscape),退出恢复竖屏;
+ *               H5 等不支持的环境降级为竖屏直签(不切横屏)。
+ *   - 保留: 11-09 canvas 2d 重写(type="2d" + getContext('2d'))契约不回退。
+ *   台账: tests/test-cases/signature.md(TC-SIG2D-01~08)
+ *
+ * 覆盖:
+ *   S4-1 恢复自动横屏(signature.vue)
+ *     TC-SIG2D-01  恢复 enterLandscape/restorePortrait 并正确接线(onLoad/onUnload/doBack)
+ *     TC-SIG2D-01b 模板不渲染 h5DegradeHint/.rotate-hint(本轮未重新引入)
+ *     TC-SIG2D-01c 调 wx.setPageOrientation(landscape + portrait)
+ *     TC-SIG2D-01d~01j 行为级:H5 降级不切横屏 / success+complete 重算高度 / 窗口监听成对注册注销 / doBack 恢复竖屏 / onUnload 清理
+ *     TC-SIG2D-02  computeCanvasHeight 预留统一 134(阅读同意已移出画布区)+ 160 下限
+ *   S4-2 canvas 2d(hand-signature.vue,不回归)
+ *     TC-SIG2D-03~07、01-E、02-E 保持不变
+ *     TC-SIG2D-07b height watch 仅在值变化且非 savingLive/销毁时重建(书写中不丢笔迹)
+ *   S4-3 不回归
+ *     TC-SIG2D-08 阅读同意上移至签名页(组件回归纯签名,页脚同行承载)
+ *
+ * 本文件只读源码并求值 script 段,不修改任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const PAGE = path.join(__dirname, '../../../pages/signature/signature.vue')
+const PAD = path.join(__dirname, '../../../pages/signature/components/hand-signature/hand-signature.vue')
+
+function readScript(file) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('no <script> in ' + file)
+  return m[1]
+}
+
+function readTemplate(file) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  if (!m) return ''
+  return m[1]
+}
+
+// import 语句 -> 同名空桩变量(保留脚本内引用,避免 ReferenceError)
+function stubImports(code) {
+  return code.replace(/import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"];?/g, function (_all, clause) {
+    const ids = String(clause)
+      .replace(/[{}]/g, ' ')
+      .split(',')
+      .map(function (x) {
+        const parts = x.trim().split(/\s+as\s+/)
+        return parts[parts.length - 1].trim()
+      })
+      .filter(function (x) {
+        return /^[A-Za-z_$][\w$]*$/.test(x)
+      })
+    return ids
+      .map(function (id) {
+        return 'var ' + id + ' = function () {};'
+      })
+      .join(' ')
+  })
+}
+
+function loadOptions(file, sandbox) {
+  let code = stubImports(readScript(file)).replace(/export\s+default/, 'var __opts__ =')
+  code = code + '\nreturn __opts__'
+  const names = Object.keys(sandbox)
+  // eslint-disable-next-line no-new-func
+  const fn = new Function(names.join(','), code)
+  return fn.apply(
+    null,
+    names.map(function (n) {
+      return sandbox[n]
+    })
+  )
+}
+
+function makePage(windowHeight, requireAgree) {
+  const opts = loadOptions(PAGE, {
+    uni: {
+      getWindowInfo: function () {
+        return { windowHeight: windowHeight }
+      },
+    },
+    wx: undefined,
+    window: undefined,
+  })
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.requireAgree = !!requireAgree
+  vm.$refs = {}
+  return vm
+}
+
+// 行为级测试用的页面实例构造器:可注入 wx/window/uni 桩,便于验证横屏/监听/回退链路
+function makePageWith(sandbox) {
+  const base = {
+    uni: { getWindowInfo: function () { return { windowHeight: 390, windowWidth: 844 } } },
+    wx: undefined,
+    window: undefined,
+  }
+  const merged = Object.assign({}, base, sandbox || {})
+  if (sandbox && sandbox.uni) {
+    merged.uni = Object.assign({}, base.uni, sandbox.uni)
+  }
+  const opts = loadOptions(PAGE, merged)
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.$refs = {}
+  return vm
+}
+
+function styleBlock(selector) {
+  const src = fs.readFileSync(PAGE, 'utf8')
+  const i = src.indexOf(selector + ' {')
+  if (i < 0) return ''
+  const open = src.indexOf('{', i)
+  return src.slice(open + 1, src.indexOf('}', open))
+}
+
+describe('恢复签名页自动横屏 + canvas 2d 不回归 · signature.canvas2d.rewrite', function () {
+  const pageScript = readScript(PAGE)
+  const pageTpl = readTemplate(PAGE)
+  const padScript = readScript(PAD)
+  const padTpl = readTemplate(PAD)
+
+  // ---------- S4-1 恢复自动横屏(signature.vue) ----------
+
+  test('TC-SIG2D-01 恢复横屏方法 enterLandscape/restorePortrait 并正确接线', function () {
+    expect(pageScript).toMatch(/enterLandscape\s*:/)
+    expect(pageScript).toMatch(/restorePortrait\s*:/)
+    // onLoad 末尾进入横屏并注册尺寸监听
+    expect(pageScript).toMatch(/onLoad\s*:\s*function[\s\S]*?enterLandscape\(\)/)
+    expect(pageScript).toMatch(/onLoad\s*:\s*function[\s\S]*?bindResizeListener\(\)/)
+    // onUnload 注销监听并恢复竖屏
+    expect(pageScript).toMatch(/onUnload\s*:\s*function[\s\S]*?unbindResizeListener\(\)/)
+    expect(pageScript).toMatch(/onUnload\s*:\s*function[\s\S]*?restorePortrait\(\)/)
+    // doBack 在 navigateBack 前恢复竖屏
+    expect(pageScript).toMatch(/doBack\s*:\s*function[\s\S]*?restorePortrait\(\)[\s\S]*?navigateBack\(\)/)
+  })
+
+  test('TC-SIG2D-01b 模板不渲染 H5 降级提示块 h5DegradeHint/.rotate-hint', function () {
+    // 本轮恢复横屏未重新引入 H5 降级提示块
+    expect(pageTpl).not.toMatch(/h5DegradeHint/)
+    expect(pageTpl).not.toMatch(/rotate-hint/)
+    // 样式块中无 .rotate-hint
+    expect(styleBlock('.rotate-hint')).toBe('')
+  })
+
+  test('TC-SIG2D-01c 调用 wx.setPageOrientation 切横屏/竖屏(landscape + portrait)', function () {
+    // 只匹配「调用形式」(带括号),排除注释中的引用文字
+    expect(pageScript).toMatch(/setPageOrientation\s*\(\s*\{/)
+    expect(pageScript).toMatch(/orientation\s*:\s*['"]landscape['"]/)
+    expect(pageScript).toMatch(/orientation\s*:\s*['"]portrait['"]/)
+    // 不使用 screen.orientation.lock(H5 降级为 wx 判断不切横屏)
+    expect(pageScript).not.toMatch(/orientation\.lock\s*\(/)
+  })
+
+  test('TC-SIG2D-01d enterLandscape 在 H5(无 wx)降级不切横屏且不抛错', function () {
+    const vm = makePageWith({ wx: undefined })
+    expect(function () { vm.enterLandscape() }).not.toThrow()
+  })
+
+  test('TC-SIG2D-01e enterLandscape 调 setPageOrientation(landscape),complete 回调重算高度(success 不重复)', function () {
+    const calls = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { calls.push(cfg) } }
+    })
+    let refresh = 0
+    vm.refreshCanvasHeight = function () { refresh += 1 }
+    vm.enterLandscape()
+    expect(calls.length).toBe(1)
+    expect(calls[0].orientation).toBe('landscape')
+    // 加固后:仅 complete 重算一次(success 与 complete 不再重复计算)
+    expect(calls[0].success).toBeUndefined()
+    calls[0].complete()
+    expect(refresh).toBe(1)
+  })
+
+  test('TC-SIG2D-01f restorePortrait 调 setPageOrientation(portrait);H5 降级不抛错', function () {
+    const calls = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { calls.push(cfg) } }
+    })
+    vm.restorePortrait()
+    expect(calls.length).toBe(1)
+    expect(calls[0].orientation).toBe('portrait')
+
+    const h5 = makePageWith({ wx: undefined })
+    expect(function () { h5.restorePortrait() }).not.toThrow()
+  })
+
+  test('TC-SIG2D-01g 窗口监听成对注册/注销(wx 通道,无泄漏)', function () {
+    const on = []
+    const off = []
+    const vm = makePageWith({
+      wx: {
+        onWindowResize: function (h) { on.push(h) },
+        offWindowResize: function (h) { off.push(h) }
+      }
+    })
+    vm.bindResizeListener()
+    expect(on.length).toBe(1)
+    expect(vm._resizeHandler).toBeTruthy()
+    vm.unbindResizeListener()
+    expect(off.length).toBe(1)
+    expect(off[0]).toBe(on[0])
+    expect(vm._resizeHandler).toBeNull()
+  })
+
+  test('TC-SIG2D-01h 窗口监听成对注册/注销(H5 window 通道,无泄漏)', function () {
+    const on = []
+    const off = []
+    const vm = makePageWith({
+      wx: undefined,
+      window: {
+        addEventListener: function (name, h) { on.push([name, h]) },
+        removeEventListener: function (name, h) { off.push([name, h]) }
+      }
+    })
+    vm.bindResizeListener()
+    expect(on.length).toBe(1)
+    expect(on[0][0]).toBe('resize')
+    vm.unbindResizeListener()
+    expect(off.length).toBe(1)
+    expect(off[0][1]).toBe(on[0][1])
+    expect(vm._resizeHandler).toBeNull()
+  })
+
+  test('TC-SIG2D-01i doBack 在 navigateBack 前恢复竖屏,_backed 防重复返回', function () {
+    const seq = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      uni: {
+        getWindowInfo: function () { return { windowHeight: 390 } },
+        navigateBack: function () { seq.push('navigateBack') }
+      }
+    })
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+  })
+
+  test('TC-SIG2D-01j onUnload 注销监听并恢复竖屏', function () {
+    const seq = []
+    const sandbox = {
+      wx: {
+        setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) },
+        onWindowResize: function () {},
+        offWindowResize: function () { seq.push('offResize') }
+      },
+      uni: { getWindowInfo: function () { return { windowHeight: 390 } } }
+    }
+    const opts = loadOptions(PAGE, sandbox)
+    const data = typeof opts.data === 'function' ? opts.data() : opts.data
+    const vm = Object.assign({}, data, opts.methods)
+    vm.$refs = {}
+    vm.bindResizeListener()
+    opts.onUnload.call(vm)
+    expect(seq).toEqual(['offResize', 'orient:portrait'])
+  })
+
+  test('TC-SIG2D-02 computeCanvasHeight 预留统一 134(阅读同意已移出画布区)+ 160 下限', function () {
+    expect(makePage(390, false).computeCanvasHeight()).toBe(390 - 134)
+    expect(makePage(390, true).computeCanvasHeight()).toBe(390 - 134)
+    expect(makePage(200, true).computeCanvasHeight()).toBe(160)
+  })
+
+  // ---------- S4-2 canvas 2d(hand-signature.vue) ----------
+
+  test('TC-SIG2D-03 模板 canvas 改 :id + type="2d"(不再 canvas-id)', function () {
+    expect(padTpl).toMatch(/<canvas[^>]*type="2d"/)
+    expect(padTpl).toMatch(/<canvas[^>]*:id="/)
+    expect(padTpl).not.toMatch(/canvas-id="/)
+  })
+
+  test('TC-SIG2D-03b data 含 canvasId 唯一化与 _canvasNode', function () {
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const data = typeof opts.data === 'function' ? opts.data() : opts.data
+    expect(data).toHaveProperty('_canvasNode', null)
+    // canvasId 唯一化:运行时输出为 hsCanvas_<数字>;静态求值拿不到真实 _uid 时按 0 兜底
+    expect(String(data.canvasId)).toMatch(/^hsCanvas_\d+$/)
+    // 源码必须保留 "(this._uid || 0)" 拼接机制,保证多实例唯一(参照 RadarChart)
+    expect(padScript).toMatch(/hsCanvas_['"]?\s*\+\s*\(?(this\._uid|this\.uid)\s*\|\|\s*0/)
+  })
+
+  test('TC-SIG2D-03c data 含 2d 绘制/初始化防御字段(canvasWidth/canvasHeight/dpr/_rectLeft/_rectTop/_destroyed/_initTimer)', function () {
+    // v2 data 新增(参照 RadarChart):画布逻辑尺寸与像素比、fields rect 左上角、销毁标志与定时器引用
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const data = typeof opts.data === 'function' ? opts.data() : opts.data
+    expect(data).toHaveProperty('canvasWidth', 0)
+    expect(data).toHaveProperty('canvasHeight', 0)
+    expect(data).toHaveProperty('dpr', 1)
+    expect(data).toHaveProperty('_rectLeft', 0)
+    expect(data).toHaveProperty('_rectTop', 0)
+    expect(data).toHaveProperty('_destroyed', false)
+    expect(data).toHaveProperty('_initTimer', null)
+  })
+
+  test('TC-SIG2D-04 mounted 用 createSelectorQuery().in(this).select("#canvasId").fields({node:true,size:true,rect:true})', function () {
+    // 参照 RadarChart:createSelectorQuery().in(this).select('#'+canvasId).fields({node:true,...})
+    expect(padScript).toMatch(/createSelectorQuery\(\s*\)\s*\.in\(this\)/)
+    expect(padScript).not.toMatch(/\.select\(['"]\.signature-canvas['"]\)/)
+    expect(padScript).toMatch(/select\(\s*['"]#['"]\s*\+/)
+    expect(padScript).toMatch(/fields\(\s*\{\s*node\s*:\s*true/)
+  })
+
+  test('TC-SIG2D-05 触摸坐标优先 t.x/t.y(2d 相对画布),兜底 clientX-_rectLeft', function () {
+    // v2:var t = e.touches && e.touches[0]; var x = (t && t.x) || 0; y 同理
+    // 兜底:t.x === undefined 时用 t.clientX - _rectLeft(fields info.left 存储)
+    expect(padScript).toMatch(/\bt\.x\b/)
+    expect(padScript).toMatch(/\bt\.y\b/)
+    expect(padScript).toMatch(/_rectLeft|_rectTop/)
+  })
+
+  test('TC-SIG2D-06 onTouchMove 同步绘制 ctx.stroke(),无异步 ctx.draw()', function () {
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const jit = opts.methods.onTouchMove.toString()
+    expect(jit).toMatch(/\.stroke\(\)/)
+    expect(jit).not.toMatch(/\.draw\(/)
+  })
+
+  test('TC-SIG2D-07 导出传 canvas 节点(2d);按笔迹包围盒裁剪留白;清空用 ctx.clearRect(同步)', function () {
+    // 重构后:canvas 节点赋给局部变量 canvas,再作为 exportOpts.canvas 传入 canvasToTempFilePath
+    expect(padScript).toMatch(/var canvas = this\._canvasNode/)
+    expect(padScript).toMatch(/canvasToTempFilePath\(\s*exportOpts\s*,\s*this\)/)
+    expect(padScript).toMatch(/canvas\s*:\s*canvas/)
+    // 横屏画布宽而矮:导出前按笔迹包围盒裁剪留白,使签名占满图(getImageData 扫描 alpha)
+    expect(padScript).toMatch(/getImageData\(/)
+    expect(padScript).toMatch(/canvasToTempFilePath/)
+    // 清空:ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
+    expect(padScript).toMatch(/clearRect\(/)
+    expect(padScript).not.toMatch(/clearRect[\s\S]{0,80}ctx\.draw\(\)/)
+  })
+
+  test('TC-SIG2D-07b height watch 仅在值变化且非 savingLive/销毁/已书写时重建 2d 位图', function () {
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const watchFn = opts.watch && opts.watch.height
+    expect(typeof watchFn).toBe('function')
+
+    let initCalls = 0
+    function makeSelf(overrides) {
+      return Object.assign({
+        savingLive: false,
+        _destroyed: false,
+        hasDrawn: false,
+        $nextTick: function (cb) { cb() },
+        initCanvas: function (cb) { initCalls += 1; if (cb) cb(true) }
+      }, overrides || {})
+    }
+    // 值未变化:不重建
+    watchFn.call(makeSelf(), 200, 200)
+    expect(initCalls).toBe(0)
+    // 导出中(savingLive=true):不重建,避免清空书写中的笔迹
+    watchFn.call(makeSelf({ savingLive: true }), 220, 200)
+    expect(initCalls).toBe(0)
+    // 组件已销毁:不重建
+    watchFn.call(makeSelf({ _destroyed: true }), 220, 200)
+    expect(initCalls).toBe(0)
+    // 加固:已书写(hasDrawn=true)时跳过重建,避免清空笔迹却仍标记 hasContent 导致导出空白
+    watchFn.call(makeSelf({ hasDrawn: true }), 220, 200)
+    expect(initCalls).toBe(0)
+    // 正常值变化:$nextTick 后重建一次
+    watchFn.call(makeSelf(), 220, 200)
+    expect(initCalls).toBe(1)
+  })
+
+  // ---------- 异常流契约(台账 TC-SIG2D-01-E / 02-E) ----------
+
+  test('TC-SIG2D-01-E 2d 初始化失败重试 + _destroyed 防销毁竞态', function () {
+    // data 含 _destroyed / _initTimer(重试链状态机锚点,参考 RadarChart)
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const data = typeof opts.data === 'function' ? opts.data() : opts.data
+    expect(data).toHaveProperty('_destroyed', false)
+    expect(data).toHaveProperty('_initTimer', null)
+    // 旧实现不应存在 loadRect 方法(v2 移除旧式 rect 缓存逻辑,改为 2d 初始化)
+    expect(padScript).not.toMatch(/loadRect\s*:/)
+    // 源码必须包含:_destroyed 守卫、setTimeout 重试赋值给 _initTimer、beforeDestroy 清理
+    expect(padScript).toMatch(/_destroyed/)
+    expect(padScript).toMatch(/_initTimer\s*=\s*setTimeout/)
+    expect(padScript).toMatch(/beforeDestroy/)
+  })
+
+  test('TC-SIG2D-02-E 导出降级链路保持:H5 直接透传 dataURL + 小程序 fs.readFile 转 base64(既有链路不回归)', function () {
+    // v2 规格:导出成功后 H5 直接传 dataURL、小程序 fs.readFile 转 base64 既有链路保持不变
+    // 旧实现已含该链路 → 本例为 GREEN 基线锚点,确保 v2 不退化
+    const src = padScript
+    // 统一回写入口 _emitSignature 存在
+    expect(src).toMatch(/_emitSignature/)
+    // H5 判断:tempFilePath 以 data:image 开头 → 直接透传
+    expect(src).toMatch(/indexOf\(['"]data:image['"]\)/)
+    // 小程序 fs.readFile base64 编码
+    expect(src).toMatch(/getFileSystemManager\(\)/)
+    expect(src).toMatch(/readFile\(/)
+    expect(src).toMatch(/encoding\s*:\s*['"]base64['"]/)
+    // 拼接 data:image/png;base64, 前缀
+    expect(src).toMatch(/data:image\/png;base64,/)
+  })
+
+  // ---------- S4-3 不回归 ----------
+
+  test('TC-SIG2D-08 阅读同意上移至签名页(组件回归纯签名,页脚同行承载)', function () {
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const props = opts.props
+    expect(props).toHaveProperty('value')
+    expect(props).toHaveProperty('strokeColor')
+    expect(props).toHaveProperty('strokeWidth')
+    expect(props).toHaveProperty('height')
+    // 组件不再承载同意声明(已移至签名页底部栏同行)
+    expect(props).not.toHaveProperty('requireAgree')
+    expect(props).not.toHaveProperty('agreeText')
+    expect(padScript).not.toMatch(/agree-change/)
+    expect(padScript).not.toMatch(/toggleAgree/)
+    expect(padScript).not.toMatch(/requireAgree/)
+    // 签名页接管:模板含阅读同意,逻辑含 toggleAgree 与未勾选拦截
+    expect(pageTpl).toMatch(/sig-agree/)
+    expect(pageScript).toMatch(/toggleAgree\s*:/)
+    expect(pageScript).toMatch(/requireAgree\s*&&\s*!this\.agreed/)
+  })
+})

+ 264 - 0
cfc-frontend/__tests__/pages/signature/signature.consignee-editor.test.js

@@ -0,0 +1,264 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.signature.consigneeEditor
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R3(签署回传:base64 回传原页面并显示预览;水机未签名仍可保存)、
+ *                §5 WI-4(水机购买签名改造:收件人信息段 + 手签名段)
+ *                + 台账 B-135-1(前端 16 红:consignee-edit.vue 未交付 → 预期 RED)
+ *   design:      cfc-frontend/pages/signature/components/consignee-edit.vue
+ *                (新建子组件:收件人编辑 + 手签名段;收件人初始值经 props 注入,
+ *                 手签名经 signature-bus 预填 + 跳转独立签名页 + events.signatureConfirm 回传写回)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js 仅 transform .js(babel-jest),moduleFileExtensions 不含 .vue,
+ *   且未安装 vue-jest/jsdom 组件环境 —— 既有约定为「抽取被测逻辑断言」而非挂载 .vue
+ *   (见 __tests__/family-join/join-form.required-info.test.js 与已合入的
+ *   __tests__/pages/signature/signature.consignee.test.js,能力键 family.signature.consignee)。
+ *   本文件沿用该约定,但专测本键(family.signature.consigneeEditor)的组件契约:
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(收件人字段、手签名段「去签名」按钮 + 预览、确认回调)。
+ *   组件文件缺失 → 预期 RED;GREEN 阶段落地组件后本套件转绿。
+ *   本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const CONSIGNEE_EDIT_PATH = path.join(__dirname, '../../../pages/signature/components/consignee-edit.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// 风格对齐 __tests__/family-join/join-form.required-info.test.js 与 signature.consignee.test.js
+// (独立 global 键 __consigneeEditorStubs,避免与已合入套件同键竞争)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__consigneeEditorStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__consigneeEditorStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象);文件缺失时抛出明确错误 */
+function loadConsigneeEditor() {
+  if (!fs.existsSync(CONSIGNEE_EDIT_PATH)) {
+    throw new Error('契约未落地:pages/signature/components/consignee-edit.vue 不存在(GREEN 阶段需新建该组件)')
+  }
+  var src = fs.readFileSync(CONSIGNEE_EDIT_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 consignee-edit.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__consigneeEditorStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具(桩表:为 GREEN 阶段组件可能存在的 import 预留,缺失时按可选访问处理)
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni.showToast.mockReset()
+  global.uni.navigateBack.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.request.mockReset()
+  stubs = {
+    setSignaturePrefill: jest.fn(),
+    consumeSignaturePrefill: jest.fn(function () { return '' }),
+    getConsigneeData: jest.fn(function () {
+      return { name: '张三', phone: '13800001111', address: '北京市朝阳区' }
+    })
+  }
+  globalThis.__consigneeEditorStubs = {
+    '@/utils/signature-bus.js': {
+      setSignaturePrefill: stubs.setSignaturePrefill,
+      consumeSignaturePrefill: stubs.consumeSignaturePrefill
+    },
+    '@/utils/api.js': { getConsigneeData: stubs.getConsigneeData }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__consigneeEditorStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC-R0 组件文件存在性契约(本键 TDD-RED 主红信号:实现未落地 → 文件缺失 → 本组断言红)
+// ---------------------------------------------------------------------------
+
+describe('AC-R0 组件文件存在性契约', function () {
+  it('pages/signature/components/consignee-edit.vue 必须存在', function () {
+    expect(fs.existsSync(CONSIGNEE_EDIT_PATH)).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R1 组件导出契约:Option API + props 注入初始收件人值 + 收件人编辑字段 data()
+// 设计锚点:新建子组件「收件人编辑 + 手签名段」,收件人初始值经 props 注入(子组件不各自请求)
+// ---------------------------------------------------------------------------
+
+describe('AC-R1 <script> 契约:子组件导出 + 收件人编辑字段', function () {
+  var component
+
+  beforeEach(function () {
+    // 文件缺失时 loadConsigneeEditor 抛错 → 每条用例红(明确的 RED 信号);GREEN 后加载真实 SFC 断言
+    component = loadConsigneeEditor().component
+  })
+
+  it('组件通过 export default 导出(Option API)', function () {
+    expect(component).toBeDefined()
+    expect(typeof component.data).toBe('function')
+    expect(component.methods).toBeDefined()
+  })
+
+  it('组件定义 props(子组件契约:收件人初始值经 props 注入,不自行重复请求接口)', function () {
+    expect(component.props).toBeDefined()
+  })
+
+  it('data 定义收件人编辑字段:consigneeName / consigneePhone / consigneeAddress', function () {
+    var vm = instantiate(component)
+    expect(vm.consigneeName).toBeDefined()
+    expect(vm.consigneePhone).toBeDefined()
+    expect(vm.consigneeAddress).toBeDefined()
+  })
+
+  it('data 定义手签名段字段 handSignature(初始为空 = 选填,符合 AC4.3)', function () {
+    var vm = instantiate(component)
+    expect(vm.handSignature).toBeDefined()
+    expect(vm.handSignature).toBe('')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R2 手签名段行为契约:goSignature → setSignaturePrefill + navigateTo 独立签名页
+// + events.signatureConfirm 回传写回 handSignature(§4.2 规范跳转片段;AC4.2 返回后赋值预览)
+// ---------------------------------------------------------------------------
+
+describe('AC-R2 手签名段跳转与回传写回(AC4.2)', function () {
+  var component
+  var vm
+
+  beforeEach(function () {
+    component = loadConsigneeEditor().component
+    vm = instantiate(component)
+    vm.handSignature = 'data:image/png;base64,AAA'
+  })
+
+  it('goSignature 跳转前经 setSignaturePrefill 写入当前手签名(编辑场景预填)', function () {
+    vm.goSignature()
+    expect(stubs.setSignaturePrefill).toHaveBeenCalledWith('data:image/png;base64,AAA')
+  })
+
+  it('goSignature 以 uni.navigateTo 打开 /pages/signature/signature(requireAgree=1 + agreeText)', function () {
+    vm.goSignature()
+    expect(global.uni.navigateTo).toHaveBeenCalledTimes(1)
+    var opts = global.uni.navigateTo.mock.calls[0][0]
+    expect(opts.url).toMatch(/\/pages\/signature\/signature/)
+    expect(opts.url).toMatch(/requireAgree=1/)
+    expect(opts.url).toMatch(/agreeText=/)
+  })
+
+  it('签名页回传 events.signatureConfirm(dataUrl) 写回 handSignature(返回后预览显示)', function () {
+    vm.goSignature()
+    var opts = global.uni.navigateTo.mock.calls[0][0]
+    expect(typeof opts.events.signatureConfirm).toBe('function')
+    opts.events.signatureConfirm('data:image/png;base64,BBB')
+    expect(vm.handSignature).toBe('data:image/png;base64,BBB')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R3 选填语义(AC4.3):未签名仍可完成/保存 —— 确认回调不因 handSignature 为空被拦截
+// ---------------------------------------------------------------------------
+
+describe('AC-R3 未签名不拦截(AC4.3 选填语义)', function () {
+  it('handSignature 为空时,onConfirm 确认路径不抛错、不提示「请先签名」类拦截', function () {
+    var component = loadConsigneeEditor().component
+    var vm = instantiate(component)
+    vm.handSignature = ''
+    expect(function () {
+      component.methods.onConfirm.call(vm, {})
+    }).not.toThrow()
+    expect(global.uni.showToast).not.toHaveBeenCalledWith(expect.objectContaining({ title: expect.stringMatching(/签名/) }))
+  })
+
+  it('模板手签名段含「选填」提示与「去签名」入口(未签名仍可保存的可见语义)', function () {
+    var template = loadConsigneeEditor().template
+    expect(template).toMatch(/选填/)
+    expect(template).toMatch(/去签名/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R4 <template> 结构契约:收件人字段 + 手签名段(按钮/预览)+ 确认回调
+// (与已合入 signature.consignee.test.js 的组件契约保持一致)
+// ---------------------------------------------------------------------------
+
+describe('AC-R4 <template> 结构契约:收件人编辑 + 手签名段', function () {
+  var template
+
+  beforeEach(function () {
+    template = loadConsigneeEditor().template
+  })
+
+  it('模板包含收件人姓名/电话/地址输入绑定', function () {
+    expect(template).toMatch(/consigneeName/)
+    expect(template).toMatch(/consigneePhone/)
+    expect(template).toMatch(/consigneeAddress/)
+  })
+
+  it('模板包含手签名段:已签预览 image 绑定 handSignature(返回后显示预览)', function () {
+    expect(template).toMatch(/<\s*image[^>]*handSignature/)
+  })
+
+  it('模板将确认事件绑定到确认回调(@confirm="onConfirm")', function () {
+    expect(template).toMatch(/@confirm\s*=\s*["']onConfirm["']/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:收件人信息编辑属于已登录水机购买流程,无角色门禁分支(不适用项,显式记录)
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:收件人信息编辑无角色门禁,不适用', function () {
+  it('占位:该能力面向已登录购买流程,无 role 分支(详见汇报)', function () {})
+})

+ 186 - 0
cfc-frontend/__tests__/pages/signature/signature.consignee.test.js

@@ -0,0 +1,186 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.signature.consignee
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R3 / §5 WI-4(水机购买签名改造:收件人信息段 + 手签名段)
+ *   design:      cfc-frontend/pages/signature/components/consignee-edit.vue(签收人信息 + 手签名段组件)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js 仅 transform .js(babel-jest),moduleFileExtensions 不含 .vue,
+ *   且未安装 vue-jest/jsdom 组件环境 —— 既有约定为「抽取被测逻辑断言」而非挂载 .vue
+ *   (见 __tests__/components/FamilyRelationGraph.test.js)。
+ *   本文件沿用 join-form.required-info.test.js 的风格:直接加载真实 SFC 的 <script>/<template> 源码——
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(收件人姓名/电话/地址字段、手签名确认段、确认回调)。
+ *
+ *   当前状态:组件 pages/signature/components/consignee-edit.vue 尚未落地(实现未交付)→ 断言文件存在性 → 预期 RED。
+ *   实现方在 GREEN 阶段按本文件所锚定的契约补足组件后,断言应可翻绿。
+ *   本文件不修改 src/main、不修改任何既有测试。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// 测试位于 __tests__/pages/signature/,组件位于 pages/signature/components/ → 需三级回退到 cfc-frontend
+const CONSIGNEE_EDIT_PATH = path.join(__dirname, '../../../pages/signature/components/consignee-edit.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// 风格对齐 cfc-frontend/__tests__/family-join/join-form.required-info.test.js
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__consigneeEditStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__consigneeEditStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象);文件缺失时抛出明确错误 */
+function loadConsigneeEdit() {
+  if (!fs.existsSync(CONSIGNEE_EDIT_PATH)) {
+    throw new Error('组件文件尚未实现(GREEN 未交付):' + CONSIGNEE_EDIT_PATH)
+  }
+  var src = fs.readFileSync(CONSIGNEE_EDIT_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 consignee-edit.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__consigneeEditStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具(桩表:为 GREEN 阶段组件可能存在的 import 预留,缺失时按可选访问处理)
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni.showToast.mockReset()
+  global.uni.navigateBack.mockReset()
+  global.uni.request.mockReset()
+  stubs = {
+    getConsigneeData: jest.fn(function () {
+      return Promise.resolve({ name: '张三', phone: '13800001111', address: '北京市朝阳区' })
+    }),
+    onConfirm: jest.fn(function (dataUrl) { return dataUrl }),
+    onAgreeChange: jest.fn(function (e) { return e })
+  }
+  globalThis.__consigneeEditStubs = {
+    '@/utils/api.js': { getConsigneeData: stubs.getConsigneeData }
+  }
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__consigneeEditStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC-R0 组件文件存在性契约(本能力 TDD-RED:实现未落地 → 文件应缺失 → 本组断言红)
+// ---------------------------------------------------------------------------
+
+describe('AC-R0 组件文件存在性契约', function () {
+  it('pages/signature/components/consignee-edit.vue 必须存在', function () {
+    expect(fs.existsSync(CONSIGNEE_EDIT_PATH)).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R1 <script> 契约:组件导出收件人信息编辑的 data()/methods(GREEN 后强制加载真实源码断言)
+// ---------------------------------------------------------------------------
+
+describe('AC-R1 <script> 契约:收件人信息 + 手签名确认回调', function () {
+  var component
+
+  beforeEach(function () {
+    // 文件缺失时 loadConsigneeEdit 抛错 → 每条用例红(明确的 RED 信号);GREEN 后加载真实 SFC 断言
+    component = loadConsigneeEdit().component
+  })
+
+  it('组件必须定义收件人信息字段(姓名/电话/地址)', function () {
+    var vm = instantiate(component)
+    expect(vm.consigneeName).toBeDefined()
+    expect(vm.consigneePhone).toBeDefined()
+    expect(vm.consigneeAddress).toBeDefined()
+  })
+
+  it('组件必须暴露确认回调方法(手签名确认后写回收件人信息)', function () {
+    expect(typeof component.methods.onConfirm).toBe('function')
+    component.methods.onConfirm.call(instantiate(component), 'data:image/png;base64,xxxx')
+    expect(stubs.onConfirm).toHaveBeenCalled()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R2 <template> 契约:签收人信息输入段 + 手签名确认段 + 确认回调绑定
+// ---------------------------------------------------------------------------
+
+describe('AC-R2 <template> 契约:签收人信息段 + 手签名确认段', function () {
+  var template
+
+  beforeEach(function () {
+    template = loadConsigneeEdit().template
+  })
+
+  it('模板包含收件人姓名/电话/地址输入绑定', function () {
+    expect(template).toMatch(/consigneeName/)
+    expect(template).toMatch(/consigneePhone/)
+    expect(template).toMatch(/consigneeAddress/)
+  })
+
+  it('模板包含手签名确认段(内嵌 HandSignature 组件)', function () {
+    expect(template).toMatch(/<hand-signature/)
+  })
+
+  it('模板将确认事件绑定到确认回调(@confirm="onConfirm")', function () {
+    expect(template).toMatch(/@confirm\s*=\s*["']onConfirm["']/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:水机购买收件人信息编辑属于已登录购物流程,无角色门禁分支(不适用项,显式记录)
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:收件人信息编辑无角色门禁,不适用', function () {
+  it('占位:该能力面向已登录购买流程,无 role 分支(详见汇报)', function () {})
+})

+ 134 - 0
cfc-frontend/__tests__/pages/signature/signature.healthPlan.test.js

@@ -0,0 +1,134 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.signature.healthPlan
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R3(签署回传)、§5 WI-3(问卷完成签名改造:移除内嵌画布 → 「去签名」按钮 + 已签预览;
+ *                原「确认签名并生成方案」按钮逻辑不变,仍依 signatureDataUrl 判空禁用)
+ *   design:      cfc-frontend/pages/signature/components/health-plan-summary.vue
+ *                —— Step 3 健康计划摘要组件(编排侧 WI-3 设计锚点:展示计划名/周期/项目/参与人;提供确认回调)
+ *
+ * TDD 现状(预期 RED):
+ *   pages/signature/components/ 下当前仅有 hand-signature/,health-plan-summary.vue 尚未落地 →
+ *   - 存在性断言失败(主红信号);
+ *   - 契约断言经 loadTemplate/loadScript 加载组件时抛出「契约未落地」错误(溯源清晰的次红信号)。
+ * 实现方在后续 GREEN 阶段落地该组件并导出健康计划摘要契约后,本文件断言即翻绿。
+ *
+ * 说明(既有 Jest 体系约束):与 __tests__/pages/signature/* 同款——只读 .vue 源码做结构/行为契约断言,
+ * 不求值 import(本文件仅文本断言,不加载模块),不修改 pages/、components/、utils/ 任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const HEALTH_PLAN_SUMMARY = path.join(
+  __dirname,
+  '../../../pages/signature/components/health-plan-summary.vue'
+)
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <template>/<script> 文本(组件落地后生效;缺失时抛「契约未落地」)
+// ---------------------------------------------------------------------------
+
+function ensureExists() {
+  if (!fs.existsSync(HEALTH_PLAN_SUMMARY)) {
+    throw new Error('契约未落地:pages/signature/components/health-plan-summary.vue 不存在(GREEN 阶段需新建该组件)')
+  }
+}
+
+function loadTemplate() {
+  ensureExists()
+  const src = fs.readFileSync(HEALTH_PLAN_SUMMARY, 'utf8')
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  if (!m) throw new Error('health-plan-summary.vue 缺少 <template> 块')
+  return m[1]
+}
+
+function loadScript() {
+  ensureExists()
+  const src = fs.readFileSync(HEALTH_PLAN_SUMMARY, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('health-plan-summary.vue 缺少 <script> 块')
+  return m[1]
+}
+
+// ---------------------------------------------------------------------------
+// AC1 组件存在性(TDD-RED 主红信号)
+// ---------------------------------------------------------------------------
+
+describe('AC1 契约:health-plan-summary.vue 存在', function () {
+  test('组件文件 pages/signature/components/health-plan-summary.vue 存在', function () {
+    expect(fs.existsSync(HEALTH_PLAN_SUMMARY)).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC2 Step 3 展示健康计划摘要:计划名 / 周期 / 项目 / 参与人
+// ---------------------------------------------------------------------------
+
+describe('AC2 契约:Step 3 展示健康计划摘要(计划名/周期/项目/参与人)', function () {
+  test('展示「计划名」及数据绑定', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/计划名/)
+    expect(tpl).toMatch(/planName|plan\.name|plan_name/)
+  })
+
+  test('展示「周期」及数据绑定', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/周期/)
+    expect(tpl).toMatch(/cycle|cycleText|周期/)
+  })
+
+  test('展示「项目」列表(label + 列表渲染)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/项目/)
+    expect(tpl).toMatch(/items|projects|planItems/)
+    expect(tpl).toMatch(/v-for/)
+  })
+
+  test('展示「参与人」列表(label + 列表渲染)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/参与人/)
+    expect(tpl).toMatch(/participants|participant|members/)
+    expect(tpl).toMatch(/v-for/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC3 提供确认回调
+// ---------------------------------------------------------------------------
+
+describe('AC3 契约:提供确认回调', function () {
+  test('模板将确认按钮绑定到 onConfirm(含「确认」文案)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/@(?:click|tap)="onConfirm"/)
+    expect(tpl).toMatch(/确认/)
+  })
+
+  test('script 定义 onConfirm 方法并 emit confirm 事件', function () {
+    const script = loadScript()
+    expect(script).toMatch(/onConfirm\s*:/)
+    expect(script).toMatch(/emit\(['"]confirm/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC4 Vue 组件导出
+// ---------------------------------------------------------------------------
+
+describe('AC4 契约:Vue 组件导出', function () {
+  test('script 通过 export default 导出组件(Option API)', function () {
+    const script = loadScript()
+    expect(script).toMatch(/export\s+default/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:健康计划签署页 Step 3 摘要组件面向「家长端问卷完成签署」,
+// 无角色门禁分支(家长/成长规划师均可用,规格未定义角色差异),
+// 属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:健康计划签署无角色门禁,不适用', function () {
+  test('占位:该能力面向问卷完成签署组件,无 role 分支(详见汇报)', function () {})
+})

+ 137 - 0
cfc-frontend/__tests__/pages/signature/signature.healthPlanSummary.test.js

@@ -0,0 +1,137 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.signature.healthPlanSummary(S-cfc-132)
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R3(签署回传)、§5 WI-3(问卷完成签名改造:移除内嵌画布 → 「去签名」按钮 + 已签预览;
+ *                确认按钮仍依 signatureDataUrl 判空禁用)+ B-135-1(前端 16 红登记:
+ *                pages/signature/components/ 子组件为真缺口,非假 RED)
+ *   design:      cfc-frontend/pages/signature/components/health-plan-summary.vue
+ *                —— Step 3 健康计划摘要子组件(新建:展示 计划名 / 周期 / 项目 / 参与人;提供确认回调;实现仅在 feature 分支,
+ *                不得假定包路径,组件落地后本套件转绿)
+ *
+ * 说明:本文件与 __tests__/pages/signature/signature.healthPlan.test.js(S-cfc-52 键 family.signature.healthPlan)
+ * 锚定同一设计组件;本文件为能力键 family.signature.healthPlanSummary(S-cfc-132,B-135-1 重新登记键)的契约登记。
+ * 两套件均只读 .vue 源码做结构/行为契约断言,不求值 import、不修改 pages/、components/、utils/ 任何业务代码。
+ *
+ * TDD 现状(预期 RED):
+ *   pages/signature/components/ 下当前仅有 hand-signature/,health-plan-summary.vue 尚未落地 →
+ *   - 存在性断言失败(主红信号);
+ *   - 契约断言经 loadTemplate/loadScript 加载组件时抛出「契约未落地」错误(溯源清晰的次红信号)。
+ * 实现方在后续 GREEN 阶段落地该组件并导出健康计划摘要契约后,本文件断言即翻绿。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const HEALTH_PLAN_SUMMARY = path.join(
+  __dirname,
+  '../../../pages/signature/components/health-plan-summary.vue'
+)
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <template>/<script> 文本(组件落地后生效;缺失时抛「契约未落地」)
+// ---------------------------------------------------------------------------
+
+function ensureExists() {
+  if (!fs.existsSync(HEALTH_PLAN_SUMMARY)) {
+    throw new Error('契约未落地:pages/signature/components/health-plan-summary.vue 不存在(GREEN 阶段需新建该组件)')
+  }
+}
+
+function loadTemplate() {
+  ensureExists()
+  const src = fs.readFileSync(HEALTH_PLAN_SUMMARY, 'utf8')
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  if (!m) throw new Error('health-plan-summary.vue 缺少 <template> 块')
+  return m[1]
+}
+
+function loadScript() {
+  ensureExists()
+  const src = fs.readFileSync(HEALTH_PLAN_SUMMARY, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('health-plan-summary.vue 缺少 <script> 块')
+  return m[1]
+}
+
+// ---------------------------------------------------------------------------
+// AC1 组件存在性(TDD-RED 主红信号)
+// ---------------------------------------------------------------------------
+
+describe('AC1 契约:health-plan-summary.vue 存在', function () {
+  test('组件文件 pages/signature/components/health-plan-summary.vue 存在', function () {
+    expect(fs.existsSync(HEALTH_PLAN_SUMMARY)).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC2 Step 3 展示健康计划摘要:计划名 / 周期 / 项目 / 参与人
+// ---------------------------------------------------------------------------
+
+describe('AC2 契约:Step 3 展示健康计划摘要(计划名/周期/项目/参与人)', function () {
+  test('展示「计划名」及数据绑定', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/计划名/)
+    expect(tpl).toMatch(/planName|plan\.name|plan_name/)
+  })
+
+  test('展示「周期」及数据绑定', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/周期/)
+    expect(tpl).toMatch(/cycle|cycleText|周期/)
+  })
+
+  test('展示「项目」列表(label + 列表渲染)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/项目/)
+    expect(tpl).toMatch(/items|projects|planItems/)
+    expect(tpl).toMatch(/v-for/)
+  })
+
+  test('展示「参与人」列表(label + 列表渲染)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/参与人/)
+    expect(tpl).toMatch(/participants|participant|members/)
+    expect(tpl).toMatch(/v-for/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC3 提供确认回调
+// ---------------------------------------------------------------------------
+
+describe('AC3 契约:提供确认回调', function () {
+  test('模板将确认按钮绑定到 onConfirm(含「确认」文案)', function () {
+    const tpl = loadTemplate()
+    expect(tpl).toMatch(/@(?:click|tap)="onConfirm"/)
+    expect(tpl).toMatch(/确认/)
+  })
+
+  test('script 定义 onConfirm 方法并 emit confirm 事件', function () {
+    const script = loadScript()
+    expect(script).toMatch(/onConfirm\s*:/)
+    expect(script).toMatch(/emit\(['"]confirm/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC4 Vue 组件导出
+// ---------------------------------------------------------------------------
+
+describe('AC4 契约:Vue 组件导出', function () {
+  test('script 通过 export default 导出组件(Option API)', function () {
+    const script = loadScript()
+    expect(script).toMatch(/export\s+default/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:健康计划签署页 Step 3 摘要组件面向「家长端问卷完成签署」,
+// 无角色门禁分支(家长/成长规划师均可用,规格未定义角色差异),
+// 属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:健康计划签署无角色门禁,不适用', function () {
+  test('占位:该能力面向问卷完成签署组件,无 role 分支(详见汇报)', function () {})
+})

+ 177 - 0
cfc-frontend/__tests__/pages/signature/signature.landscape.contract.test.js

@@ -0,0 +1,177 @@
+/**
+ * 契约级单测 —— 签名页横屏适配(能力键 family.signature.landscape)
+ *
+ * 溯源:
+ *   SRS:  docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *         §3 AC-R2(签名页为横屏全屏;加载时切横屏、离开时恢复竖屏,H5 不支持时优雅降级)
+ *         §5 WI-2(进入/退出横屏适配:微信 wx.setPageOrientation 切横屏;H5 降级不切横屏)
+ *   设计锚点: pages/signature/signature.vue 的 enterLandscape / restorePortrait 接线
+ *            (onLoad / onUnload / doBack)+ wx.setPageOrientation('landscape' / 'portrait')
+ *   台账: tests/test-cases/signature.md(TC-LANDSCAPE-01~08)
+ *
+ * 覆盖(独立契约,与 signature.canvas2d.test.js / signature.landscape.superseded.js 不重名):
+ *   TC-LANDSCAPE-01  enterLandscape / restorePortrait 方法存在
+ *   TC-LANDSCAPE-02  onLoad 进入即切横屏(调 enterLandscape)
+ *   TC-LANDSCAPE-03  onUnload 退出恢复竖屏(调 restorePortrait)
+ *   TC-LANDSCAPE-04  doBack 在 navigateBack 前恢复竖屏
+ *   TC-LANDSCAPE-05  enterLandscape 调 wx.setPageOrientation({ orientation: 'landscape' })
+ *   TC-LANDSCAPE-06  restorePortrait 调 wx.setPageOrientation({ orientation: 'portrait' })
+ *   TC-LANDSCAPE-07  H5(无 wx)降级不切横屏且不抛错
+ *   TC-LANDSCAPE-08  doBack 防重复返回(_backed 标志),onUnload 恢复竖屏
+ *
+ * 本文件只读源码并求值 script 段,不修改任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const PAGE = path.join(__dirname, '../../../pages/signature/signature.vue')
+
+function readScript(file) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('no <script> in ' + file)
+  return m[1]
+}
+
+// import 语句 -> 同名空桩变量(保留脚本内引用,避免 ReferenceError)
+function stubImports(code) {
+  return code.replace(/import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"];?/g, function (_all, clause) {
+    const ids = String(clause)
+      .replace(/[{}]/g, ' ')
+      .split(',')
+      .map(function (x) {
+        const parts = x.trim().split(/\s+as\s+/)
+        return parts[parts.length - 1].trim()
+      })
+      .filter(function (x) {
+        return /^[A-Za-z_$][\w$]*$/.test(x)
+      })
+    return ids
+      .map(function (id) {
+        return 'var ' + id + ' = function () {};'
+      })
+      .join(' ')
+  })
+}
+
+function loadOptions(file, sandbox) {
+  let code = stubImports(readScript(file)).replace(/export\s+default/, 'var __opts__ =')
+  code = code + '\nreturn __opts__'
+  const names = Object.keys(sandbox)
+  // eslint-disable-next-line no-new-func
+  const fn = new Function(names.join(','), code)
+  return fn.apply(
+    null,
+    names.map(function (n) {
+      return sandbox[n]
+    })
+  )
+}
+
+// 行为级测试用页面实例构造器:可注入 wx / window / uni 桩
+function makePageWith(sandbox) {
+  const base = {
+    uni: { getWindowInfo: function () { return { windowHeight: 390, windowWidth: 844 } } },
+    wx: undefined,
+    window: undefined,
+  }
+  const merged = Object.assign({}, base, sandbox || {})
+  if (sandbox && sandbox.uni) {
+    merged.uni = Object.assign({}, base.uni, sandbox.uni)
+  }
+  const opts = loadOptions(PAGE, merged)
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.$refs = {}
+  return vm
+}
+
+describe('签名页横屏适配契约 · family.signature.landscape', function () {
+  const pageScript = readScript(PAGE)
+
+  test('TC-LANDSCAPE-01 enterLandscape / restorePortrait 方法存在', function () {
+    expect(pageScript).toMatch(/enterLandscape\s*:/)
+    expect(pageScript).toMatch(/restorePortrait\s*:/)
+    // 两方法须为真实函数(行为可调)
+    const vm = makePageWith({ wx: undefined })
+    expect(typeof vm.enterLandscape).toBe('function')
+    expect(typeof vm.restorePortrait).toBe('function')
+  })
+
+  test('TC-LANDSCAPE-02 onLoad 进入即切横屏(调 enterLandscape)', function () {
+    expect(pageScript).toMatch(/onLoad\s*:\s*function[\s\S]*?enterLandscape\(\)/)
+  })
+
+  test('TC-LANDSCAPE-03 onUnload 退出恢复竖屏(调 restorePortrait)', function () {
+    expect(pageScript).toMatch(/onUnload\s*:\s*function[\s\S]*?restorePortrait\(\)/)
+  })
+
+  test('TC-LANDSCAPE-04 doBack 在 navigateBack 前恢复竖屏', function () {
+    expect(pageScript).toMatch(/doBack\s*:\s*function[\s\S]*?restorePortrait\(\)[\s\S]*?navigateBack\(\)/)
+  })
+
+  test('TC-LANDSCAPE-05 enterLandscape 调 wx.setPageOrientation landscape', function () {
+    const calls = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { calls.push(cfg) } }
+    })
+    vm.enterLandscape()
+    expect(calls.length).toBe(1)
+    expect(calls[0].orientation).toBe('landscape')
+    // 旋转后重算画布高度(complete 回调)
+    expect(typeof calls[0].complete).toBe('function')
+  })
+
+  test('TC-LANDSCAPE-06 restorePortrait 调 wx.setPageOrientation portrait', function () {
+    const calls = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { calls.push(cfg) } }
+    })
+    vm.restorePortrait()
+    expect(calls.length).toBe(1)
+    expect(calls[0].orientation).toBe('portrait')
+  })
+
+  test('TC-LANDSCAPE-07 H5(无 wx)降级不切横屏且不抛错', function () {
+    let setCalled = false
+    const vm = makePageWith({
+      wx: {
+        setPageOrientation: function () { setCalled = true }
+      }
+    })
+    // H5:wx 为 undefined
+    const h5 = makePageWith({ wx: undefined })
+    expect(function () { h5.enterLandscape() }).not.toThrow()
+    expect(function () { h5.restorePortrait() }).not.toThrow()
+    // 降级路径不得调用 setPageOrientation(不切横屏)
+    expect(setCalled).toBe(false)
+  })
+
+  test('TC-LANDSCAPE-08 doBack 防重复返回 + onUnload 恢复竖屏', function () {
+    const seq = []
+    const vm = makePageWith({
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      uni: {
+        getWindowInfo: function () { return { windowHeight: 390 } },
+        navigateBack: function () { seq.push('navigateBack') }
+      }
+    })
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+    // 防重复返回
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+    // onUnload 独立恢复竖屏(onUnload 走 opts.onUnload,单独构造)
+    const seq2 = []
+    const opts = loadOptions(PAGE, {
+      wx: { setPageOrientation: function (cfg) { seq2.push('orient:' + cfg.orientation) } },
+      uni: { getWindowInfo: function () { return { windowHeight: 390 } } }
+    })
+    const data = typeof opts.data === 'function' ? opts.data() : opts.data
+    const vm2 = Object.assign({}, data, opts.methods)
+    vm2.$refs = {}
+    opts.onUnload.call(vm2)
+    expect(seq2).toEqual(['orient:portrait'])
+  })
+})

+ 136 - 0
cfc-frontend/__tests__/pages/signature/signature.landscape.superseded.js

@@ -0,0 +1,136 @@
+/**
+ * 契约级单测 —— 手签名横屏适配(能力键 signature.landscape.layout)
+ *
+ * 溯源:
+ *   SRS:  docs/superpowers/specs/2026-11-08-signature-landscape-fix.md(DOC-2026-11-08-signature-landscape-fix)
+ *   实现: adb032a61「横屏适配修复 (S1/S2/S3)」
+ *   台账: tests/test-cases/signature.md(TC-SIG-01/02/04/-E)
+ *
+ * 覆盖:
+ *   TC-SIG-01   canvasHeight = 视口高 − 固定栏占位(有/无同意声明两档),且不低于 160 下限
+ *   TC-SIG-02   顶栏标题为 px 单位(横屏不随宽度换算放大)
+ *   TC-SIG-04   旋转后 refreshLandscapeLayout 重算高度并调用组件 refreshRect()
+ *   TC-SIG-03-E 组件 getPos 在 rect 缺失时沿用 clientX/Y(不抛错)
+ *
+ * 本文件只读源码并求值 script 段,不修改任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const PAGE = path.join(__dirname, '../../../pages/signature/signature.vue')
+const PAD = path.join(__dirname, '../../../pages/signature/components/hand-signature/hand-signature.vue')
+
+// import 语句 -> 同名空桩变量(保留脚本内引用,避免 ReferenceError)
+function stubImports(code) {
+  return code.replace(/import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"];?/g, function (_all, clause) {
+    const ids = String(clause)
+      .replace(/[{}]/g, ' ')
+      .split(',')
+      .map(function (x) {
+        const parts = x.trim().split(/\s+as\s+/)
+        return parts[parts.length - 1].trim()
+      })
+      .filter(function (x) {
+        return /^[A-Za-z_$][\w$]*$/.test(x)
+      })
+    return ids
+      .map(function (id) {
+        return 'var ' + id + ' = function () {};'
+      })
+      .join(' ')
+  })
+}
+
+function loadOptions(file, sandbox) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('no <script> in ' + file)
+  let code = stubImports(m[1]).replace(/export\s+default/, 'var __opts__ =')
+  code = code + '\nreturn __opts__'
+  const names = Object.keys(sandbox)
+  // eslint-disable-next-line no-new-func
+  const fn = new Function(names.join(','), code)
+  return fn.apply(
+    null,
+    names.map(function (n) {
+      return sandbox[n]
+    })
+  )
+}
+
+function makePage(windowHeight, requireAgree) {
+  const opts = loadOptions(PAGE, {
+    uni: {
+      getWindowInfo: function () {
+        return { windowHeight: windowHeight }
+      },
+    },
+    wx: undefined,
+    window: undefined,
+  })
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.requireAgree = !!requireAgree
+  vm.$refs = {}
+  return vm
+}
+
+function styleBlock(selector) {
+  const src = fs.readFileSync(PAGE, 'utf8')
+  const i = src.indexOf(selector + ' {')
+  if (i < 0) return ''
+  const open = src.indexOf('{', i)
+  return src.slice(open + 1, src.indexOf('}', open))
+}
+
+describe('签名横屏适配 · signature.landscape.layout', function () {
+  test('TC-SIG-01 画布高度 = 视口高 − 固定栏占位(无同意声明 174)', function () {
+    expect(makePage(390, false).computeCanvasHeight()).toBe(390 - 174)
+  })
+
+  test('TC-SIG-01b 有同意声明时额外扣除 40(总 214)', function () {
+    expect(makePage(390, true).computeCanvasHeight()).toBe(390 - 214)
+  })
+
+  test('TC-SIG-01c 极小视口不低于 160 下限(防裁剪)', function () {
+    expect(makePage(200, true).computeCanvasHeight()).toBe(160)
+  })
+
+  test('TC-SIG-04 旋转后重算高度并调用组件 refreshRect()', function () {
+    const vm = makePage(390, false)
+    let called = 0
+    vm.$refs = {
+      signaturePad: {
+        refreshRect: function () {
+          called += 1
+        },
+      },
+    }
+    vm.canvasHeight = 0
+    vm.refreshLandscapeLayout()
+    expect(vm.canvasHeight).toBe(390 - 174)
+    expect(called).toBe(1)
+  })
+
+  test('TC-SIG-04b 组件未挂载(refs 为空)时不抛错', function () {
+    const vm = makePage(390, false)
+    vm.$refs = {}
+    expect(function () {
+      vm.refreshLandscapeLayout()
+    }).not.toThrow()
+  })
+
+  test('TC-SIG-02 顶栏标题为 px 单位(横屏不随宽度放大)', function () {
+    const b = styleBlock('.sig-title')
+    expect(b).toMatch(/font-size:\s*(calc\()?[^;]*px/)
+    expect(b).not.toMatch(/font-size:\s*(calc\()?[^;]*rpx/)
+  })
+
+  test('TC-SIG-03-E 组件 getPos 在 rect 缺失时沿用 clientX/Y 不抛错', function () {
+    const opts = loadOptions(PAD, { uni: {}, wx: undefined, window: undefined })
+    const pos = opts.methods.getPos.call({ rect: null }, { clientX: 12, clientY: 34 })
+    expect(pos.x).toBe(12)
+    expect(pos.y).toBe(34)
+  })
+})

+ 242 - 0
cfc-frontend/__tests__/pages/signature/signature.openPage.test.js

@@ -0,0 +1,242 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 family.signature.openPage
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R1(独立页跳转 navigateTo 打开签名页)、§5 WI-1(新建独立横屏签名页)
+ *                关联 AC5.1(pages.json 路由注册正确)
+ *   design:      cfc-frontend/pages/signature/signature.vue(签名页)
+ *                + 入口页面 health-plan-summary.vue / consignee-edit.vue / checkout.vue
+ *                  (goSignature 经 uni.navigateTo 打开 pages/signature/signature)
+ *
+ * 说明(既有 Jest 体系约束):
+ *   cfc-frontend 的 jest.config.js moduleFileExtensions 不含 `vue`,testEnvironment 为 node,
+ *   既有约定为「抽取被测逻辑断言」而非挂载 .vue(见 __tests__/pages/signature/signature.canvas2d.test.js)。
+ *   本文件沿用该约定:直接加载真实 SFC 的 <script>/<template> 源码做结构契约断言,
+ *   并对 onConfirm/onLoad/onUnload 做行为级断言(真实 export default 求值 + 方法驱动)。
+ *   若实现方后续改动签名页契约,本文件断言即暴露;本文件不修改 pages/、utils/ 任何业务代码。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const PAGE = path.join(__dirname, '../../../pages/signature/signature.vue')
+const PAGES_JSON = path.join(__dirname, '../../../pages.json')
+
+const ENTRY_FILES = {
+  healthPlanSummary: path.join(__dirname, '../../../pages/health/health-plan-summary.vue'),
+  consigneeEdit: path.join(__dirname, '../../../pages/shop/consignee-edit/consignee-edit.vue'),
+  checkout: path.join(__dirname, '../../../pages/shop/checkout/checkout.vue')
+}
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 signature.vue 的 <script>(行为级)与 <template>(结构级)
+// ---------------------------------------------------------------------------
+
+/** import 语句 -> 同名空桩变量(保留脚本内引用,避免 ReferenceError) */
+function stubImports(code) {
+  return code.replace(/import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"];?/g, function (_all, clause) {
+    const ids = String(clause)
+      .replace(/[{}]/g, ' ')
+      .split(',')
+      .map(function (x) {
+        const parts = x.trim().split(/\s+as\s+/)
+        return parts[parts.length - 1].trim()
+      })
+      .filter(function (x) {
+        return /^[A-Za-z_$][\w$]*$/.test(x)
+      })
+    return ids
+      .map(function (id) {
+        return 'var ' + id + ' = function () {};'
+      })
+      .join(' ')
+  })
+}
+
+/** 求值 <script> 得到真实 export default 对象(可注入 uni/wx/window/模块桩) */
+function loadOptions(sandbox) {
+  let code = stubImports(readScript(PAGE)).replace(/export\s+default/, 'var __opts__ =')
+  code = code + '\nreturn __opts__'
+  const names = Object.keys(sandbox)
+  // eslint-disable-next-line no-new-func
+  const fn = new Function(names.join(','), code)
+  return fn.apply(
+    null,
+    names.map(function (n) {
+      return sandbox[n]
+    })
+  )
+}
+
+function readScript(file) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('no <script> in ' + file)
+  return m[1]
+}
+
+function readTemplate(file) {
+  const src = fs.readFileSync(file, 'utf8')
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  if (!m) return ''
+  return m[1]
+}
+
+function readAll(file) {
+  return fs.readFileSync(file, 'utf8')
+}
+
+/** 构造可驱动页面实例:合并 data() 与 methods,注入 $refs,并暴露顶层生命周期 opts */
+function makePage(sandbox) {
+  const base = {
+    uni: {
+      getWindowInfo: function () { return { windowHeight: 390, windowWidth: 844 } },
+      navigateBack: function () {},
+      showToast: function () {}
+    },
+    wx: undefined,
+    window: undefined
+  }
+  const merged = Object.assign({}, base, sandbox || {})
+  if (sandbox && sandbox.uni) merged.uni = Object.assign({}, base.uni, sandbox.uni)
+  const opts = loadOptions(merged)
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.$refs = {}
+  // 暴露顶层生命周期(onLoad/onUnload 不在 methods 内)
+  vm.__opts__ = opts
+  return vm
+}
+
+// ---------------------------------------------------------------------------
+// AC1.1 / AC5.1 页面存在 + pages.json 路由注册
+// ---------------------------------------------------------------------------
+
+describe('AC1.1/AC5.1 签名页存在并注册为可打开页面', function () {
+  test('signature.vue 存在且为可打开页面(有 template + script + export default 组件)', function () {
+    expect(fs.existsSync(PAGE)).toBe(true)
+    const tpl = readTemplate(PAGE)
+    const script = readScript(PAGE)
+    // 可打开页面:模板有根节点 + 脚本 export default 组件定义
+    expect(tpl).toMatch(/<view[^>]*class="signature-page"/)
+    expect(script).toMatch(/export\s+default\s*\{/)
+    // 复用 HandSignature 组件
+    expect(script).toMatch(/components\s*:\s*\{\s*HandSignature\s*\}/)
+  })
+
+  test('pages.json 注册 pages/signature/signature 路由(无重复 path)', function () {
+    const json = readAll(PAGES_JSON)
+    // 分包 root + path + 真全屏 navigationStyle
+    expect(json).toMatch(/"root"\s*:\s*"pages\/signature"/)
+    expect(json).toMatch(/"path"\s*:\s*"signature"/)
+    expect(json).toMatch(/"navigationBarTitleText"\s*:\s*"签名"/)
+    expect(json).toMatch(/"navigationStyle"\s*:\s*"custom"/)
+    // 路径唯一(无重复注册)
+    const pathMatches = json.match(/"path"\s*:\s*"signature"/g) || []
+    expect(pathMatches.length).toBe(1)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC-R1 存在入口通过 uni.navigateTo 打开 pages/signature/signature
+// ---------------------------------------------------------------------------
+
+describe('AC-R1 入口页面经 uni.navigateTo 打开签名页', function () {
+  const ENTRY_PATH_RE = /['"]\/pages\/signature\/signature\?requireAgree=1&agreeText=['"]/
+  const NAVIGATE_RE = /uni\.navigateTo\s*\(\s*\{[\s\S]{0,200}url\s*:\s*['"]\/pages\/signature\/signature\?requireAgree=1/
+
+  test('health-plan-summary.vue(问卷完成签名)经 navigateTo 打开签名页', function () {
+    const src = readAll(ENTRY_FILES.healthPlanSummary)
+    expect(src).toMatch(NAVIGATE_RE)
+    expect(src).toMatch(ENTRY_PATH_RE)
+  })
+
+  test('consignee-edit.vue(水机购买收货人签名)经 navigateTo 打开签名页', function () {
+    const src = readAll(ENTRY_FILES.consigneeEdit)
+    expect(src).toMatch(NAVIGATE_RE)
+    expect(src).toMatch(ENTRY_PATH_RE)
+  })
+
+  test('checkout.vue(订单确认签署)经 navigateTo 打开签名页', function () {
+    const src = readAll(ENTRY_FILES.checkout)
+    expect(src).toMatch(NAVIGATE_RE)
+    expect(src).toMatch(ENTRY_PATH_RE)
+  })
+
+  test('入口跳转前经 signature-bus 写入初始值(setSignaturePrefill)', function () {
+    const src = readAll(ENTRY_FILES.healthPlanSummary)
+    expect(src).toMatch(/setSignaturePrefill\s*\(/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC1.4 行为级:点「确认」经 eventChannel 回传 base64 + navigateBack;「返回」不回传直接退出
+// ---------------------------------------------------------------------------
+
+describe('AC1.4 签名页回传/退出行为', function () {
+  test('onConfirm 经 getOpenerEventChannel().emit(signatureConfirm, dataUrl) 回传后 doBack', function () {
+    const emitted = []
+    const navigated = []
+    const vm = makePage({
+      uni: { navigateBack: function () { navigated.push('navigateBack') } }
+    })
+    vm.getOpenerEventChannel = function () {
+      return { emit: function (name, payload) { emitted.push([name, payload]) } }
+    }
+    const dataUrl = 'data:image/png;base64,QUJD'
+    vm.onConfirm(dataUrl)
+    expect(emitted.length).toBe(1)
+    expect(emitted[0][0]).toBe('signatureConfirm')
+    expect(emitted[0][1]).toBe(dataUrl)
+    expect(navigated).toEqual(['navigateBack'])
+  })
+
+  test('onBack 不回传直接 navigateBack(恢复竖屏)', function () {
+    const emitted = []
+    const seq = []
+    const vm = makePage({
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      uni: { navigateBack: function () { seq.push('navigateBack') } }
+    })
+    vm.getOpenerEventChannel = function () {
+      return { emit: function (name, payload) { emitted.push([name, payload]) } }
+    }
+    vm.onBack()
+    expect(emitted.length).toBe(0)
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC1.5 行为级:onLoad 读取 requireAgree/agreeText 与 prefill 回显
+// ---------------------------------------------------------------------------
+
+describe('AC1.5 onLoad 入参与 prefill 回显', function () {
+  test('onLoad 从 signature-bus 读取 prefill;requireAgree=1 置真、agreeText 解码', function () {
+    const script = readScript(PAGE)
+    // 结构契约:onLoad 经 signature-bus 读取初始值(读后清空,避免残留串扰)
+    expect(script).toMatch(/consumeSignaturePrefill\s*\(\)/)
+    expect(script).toMatch(/this\.prefill\s*=\s*consumeSignaturePrefill\s*\(\)/)
+    // 行为级:驱动真实 onLoad(consumeSignaturePrefill 已 stub 为空函数,不抛错)
+    const vm = makePage({ wx: undefined, window: undefined })
+    vm.__opts__.onLoad.call(vm, { requireAgree: '1', agreeText: encodeURIComponent('我已阅读并确认') })
+    expect(vm.requireAgree).toBe(true)
+    expect(vm.agreeText).toBe('我已阅读并确认')
+  })
+
+  test('onLoad: requireAgree 未传则 false;agreeText 未传保留默认文案', function () {
+    const vm = makePage({ wx: undefined, window: undefined })
+    vm.__opts__.onLoad.call(vm, {})
+    expect(vm.requireAgree).toBe(false)
+    expect(vm.agreeText).toBe('我已阅读并确认以上内容真实、准确')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:签名页为通用签署页,不区分角色(无 role 门禁),显式记录。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:签名页无角色门禁,不适用', function () {
+  it('占位:该能力为通用签署页,无 role 分支(详见汇报)', function () {})
+})

+ 320 - 0
cfc-frontend/__tests__/pages/signature/signature.routeIntegrate.test.js

@@ -0,0 +1,320 @@
+/**
+ * 契约级单测(TDD)——能力键 family.signature.routeIntegrate
+ *
+ * 溯源:
+ *   requirement: docs/superpowers/specs/2026-11-07-signature-page-landscape.md
+ *                §3 AC-R5(无回归:pages.json 路由注册正确、无遗留内嵌 hand-signature)
+ *                §5 WI-5(路由注册与联调验证)
+ *   design:      cfc-frontend/pages.json 路由注册(root=pages/signature + path=signature)
+ *                + pages/signature/signature.vue(回退/恢复逻辑 onUnload/doBack)
+ *
+ * 覆盖(对应 WI-5 验收条件):
+ *   AC5.1 pages.json 正确注册 pages/signature/signature 路由(subPackages root=pages/signature
+ *          + path=signature),全量路由唯一无重复,navigationStyle: custom 真全屏
+ *   AC5.2 页面文件 pages/signature/signature.vue 存在,其编译依赖(hand-signature 组件、
+ *         utils/signature-bus.js)存在,模板引用组件契约不缺失
+ *   AC5.3 两处入口(health-plan-summary / consignee-edit)均 navigateTo 新签名页;
+ *         全局业务页无内嵌 <hand-signature>(仅签名页内复用)
+ *   AC5.4 回退契约:onUnload 注销尺寸监听并恢复竖屏;doBack 在 navigateBack 前恢复竖屏、
+ *         _backed 防重复返回;onBack / onConfirm 均收敛到 doBack(回传后退出)
+ *
+ * 方法:只读 pages.json 与 signature.vue 源码并求值 <script> 段(同
+ *       __tests__/pages/signature/signature.canvas2d.test.js 约定),
+ *       不挂载组件、不修改任何业务代码。实现疑似已存在 → 预期意外全绿。
+ */
+
+const fs = require('fs')
+const path = require('path')
+
+const FRONT_ROOT = path.join(__dirname, '../../..')
+const PAGES_JSON = path.join(FRONT_ROOT, 'pages.json')
+const PAGES_DIR = path.join(FRONT_ROOT, 'pages')
+const PAGE = path.join(FRONT_ROOT, 'pages/signature/signature.vue')
+const PAD = path.join(FRONT_ROOT, 'pages/signature/components/hand-signature/hand-signature.vue')
+const SIG_BUS = path.join(FRONT_ROOT, 'utils/signature-bus.js')
+const ENTRY_HEALTH = path.join(FRONT_ROOT, 'pages/health/health-plan-summary.vue')
+const ENTRY_CONSIGNEE = path.join(FRONT_ROOT, 'pages/shop/consignee-edit/consignee-edit.vue')
+
+// ---------------------------------------------------------------------------
+// 工具
+// ---------------------------------------------------------------------------
+
+function readRaw(file) {
+  return fs.readFileSync(file, 'utf8')
+}
+
+function readScript(file) {
+  const src = readRaw(file)
+  const m = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!m) throw new Error('无法在 ' + file + ' 中定位 <script> 块(路由契约依赖页面脚本存在)')
+  return m[1]
+}
+
+function readTemplate(file) {
+  const src = readRaw(file)
+  const m = src.match(/<template>([\s\S]*?)<\/template>/)
+  return m ? m[1] : ''
+}
+
+/** 剥离 HTML 注释与 JS 块注释,用于「标签是否真实出现在代码中」的判断 */
+function stripComments(src) {
+  return src
+    .replace(/<!--[\s\S]*?-->/g, '')
+    .replace(/\/\*[\s\S]*?\*\//g, '')
+}
+
+function collectVueFiles(dir, out) {
+  out = out || []
+  fs.readdirSync(dir, { withFileTypes: true }).forEach(function (ent) {
+    if (ent.name === 'node_modules') return
+    const full = path.join(dir, ent.name)
+    if (ent.isDirectory()) collectVueFiles(full, out)
+    else if (ent.name.endsWith('.vue')) out.push(full)
+  })
+  return out
+}
+
+/** 解析 pages.json → { json, routes },routes 为全部页面的完整路由(分包展开为 root/path) */
+function loadRoutes() {
+  const json = JSON.parse(readRaw(PAGES_JSON))
+  const routes = []
+  ;(json.pages || []).forEach(function (p) { routes.push(p.path) })
+  ;(json.subPackages || []).forEach(function (sub) {
+    ;(sub.pages || []).forEach(function (p) { routes.push(sub.root + '/' + p.path) })
+  })
+  return { json: json, routes: routes }
+}
+
+/** 把 import 语句替换为同名空桩(保留脚本内引用,避免 ReferenceError) */
+function stubImports(code) {
+  return code.replace(/import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"];?/g, function (_all, clause) {
+    const ids = String(clause)
+      .replace(/[{}]/g, ' ')
+      .split(',')
+      .map(function (x) {
+        const parts = x.trim().split(/\s+as\s+/)
+        return parts[parts.length - 1].trim()
+      })
+      .filter(function (x) {
+        return /^[A-Za-z_$][\w$]*$/.test(x)
+      })
+    return ids
+      .map(function (id) {
+        return 'var ' + id + ' = function () {};'
+      })
+      .join(' ')
+  })
+}
+
+/** 求值 SFC <script> 的 export default 选项对象(uni/wx/window 经 sandbox 注入) */
+function loadOptions(file, sandbox) {
+  let code = stubImports(readScript(file)).replace(/export\s+default/, 'var __opts__ =')
+  code = code + '\nreturn __opts__'
+  const names = Object.keys(sandbox)
+  // eslint-disable-next-line no-new-func
+  const fn = new Function(names.join(','), code)
+  return fn.apply(
+    null,
+    names.map(function (n) {
+      return sandbox[n]
+    })
+  )
+}
+
+/** 构造行为级 vm:data() + methods 合并(模拟 Vue 实例),$refs 置空 */
+function makeVm(sandbox) {
+  const opts = loadOptions(PAGE, sandbox)
+  const data = typeof opts.data === 'function' ? opts.data() : opts.data
+  const vm = Object.assign({}, data, opts.methods)
+  vm.$refs = {}
+  return { vm: vm, opts: opts }
+}
+
+// ---------------------------------------------------------------------------
+// AC5.1 路由注册:pages.json 已注册 pages/signature/signature,且唯一、样式正确
+// ---------------------------------------------------------------------------
+
+describe('AC5.1 pages.json 路由注册(root=pages/signature + path=signature)', function () {
+  let routes
+  let sub
+  let page
+
+  beforeAll(function () {
+    const loaded = loadRoutes()
+    routes = loaded.routes
+    sub = loaded.json.subPackages.filter(function (s) { return s.root === 'pages/signature' })
+    page = sub.length
+      ? sub[0].pages.filter(function (p) { return p.path === 'signature' })
+      : []
+  })
+
+  it('subPackages 注册 root=pages/signature 分包,且仅注册一次', function () {
+    expect(sub.length).toBe(1)
+  })
+
+  it('分包 pages 内注册 path=signature(组合路由 pages/signature/signature)', function () {
+    expect(page.length).toBe(1)
+  })
+
+  it('全量路由(主包 pages + subPackages)中 pages/signature/signature 唯一无重复', function () {
+    const hits = routes.filter(function (r) { return r === 'pages/signature/signature' })
+    expect(hits.length).toBe(1)
+  })
+
+  it('签名页 style 为 navigationStyle: custom(真全屏)+ 标题「签名」', function () {
+    expect(page[0].style).toMatchObject({ navigationStyle: 'custom', navigationBarTitleText: '签名' })
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC5.2 页面文件与编译依赖存在:signature.vue 及其引用的组件/工具不缺失
+// ---------------------------------------------------------------------------
+
+describe('AC5.2 页面文件与编译依赖(编译不再缺失文件即证明路由可编译)', function () {
+  it('页面文件 pages/signature/signature.vue 存在', function () {
+    expect(fs.existsSync(PAGE)).toBe(true)
+  })
+
+  it('signature.vue 含 <template>/<script>/<style> 三段(uni 编译输入完整)', function () {
+    const raw = readRaw(PAGE)
+    expect(raw).toMatch(/<template>/)
+    expect(raw).toMatch(/<script>/)
+    expect(raw).toMatch(/<style/)
+    const exportCnt = (raw.match(/export\s+default/g) || []).length
+    expect(exportCnt).toBe(1)
+  })
+
+  it('模板内嵌复用 hand-signature 组件(components 注册 + 模板标签均存在)', function () {
+    expect(readTemplate(PAGE)).toMatch(/<hand-signature/)
+    expect(readScript(PAGE)).toMatch(/components\s*:\s*\{\s*HandSignature/)
+  })
+
+  it('编译依赖存在:hand-signature.vue 组件与 utils/signature-bus.js', function () {
+    expect(fs.existsSync(PAD)).toBe(true)
+    expect(fs.existsSync(SIG_BUS)).toBe(true)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC5.3 无回归:两处入口 navigateTo 新签名页;全局无内嵌 <hand-signature>(仅签名页)
+// ---------------------------------------------------------------------------
+
+describe('AC5.3 入口接入新页面(无回归)', function () {
+  it('问卷签名入口 health-plan-summary.vue navigateTo /pages/signature/signature', function () {
+    expect(fs.existsSync(ENTRY_HEALTH)).toBe(true)
+    const src = stripComments(readRaw(ENTRY_HEALTH))
+    expect(src).toMatch(/navigateTo\s*\(\s*\{[\s\S]*?url\s*:\s*['"]\/pages\/signature\/signature/)
+    expect(src).not.toMatch(/<hand-signature/)
+  })
+
+  it('水机签名入口 consignee-edit.vue navigateTo /pages/signature/signature', function () {
+    expect(fs.existsSync(ENTRY_CONSIGNEE)).toBe(true)
+    const src = stripComments(readRaw(ENTRY_CONSIGNEE))
+    expect(src).toMatch(/navigateTo\s*\(\s*\{[\s\S]*?url\s*:\s*['"]\/pages\/signature\/signature/)
+    expect(src).not.toMatch(/<hand-signature/)
+  })
+
+  it('全局业务页无内嵌 <hand-signature>:仅签名页 signature.vue 真实使用', function () {
+    const offenders = collectVueFiles(PAGES_DIR).filter(function (file) {
+      const clean = stripComments(readRaw(file))
+      return clean.indexOf('<hand-signature') >= 0
+    })
+    const rel = offenders.map(function (f) { return path.relative(FRONT_ROOT, f).replace(/\\/g, '/') })
+    expect(rel.sort()).toEqual(['pages/signature/signature.vue'])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC5.4 回退契约:onUnload / doBack / onBack / onConfirm 的竖屏恢复与导航还原
+// ---------------------------------------------------------------------------
+
+describe('AC5.4 回退逻辑契约(onUnload/doBack 恢复)', function () {
+  const pageScript = readScript(PAGE)
+
+  it('源码接线:onUnload 注销尺寸监听并恢复竖屏', function () {
+    expect(pageScript).toMatch(/onUnload\s*:\s*function[\s\S]*?unbindResizeListener\(\)/)
+    expect(pageScript).toMatch(/onUnload\s*:\s*function[\s\S]*?restorePortrait\(\)/)
+  })
+
+  it('源码接线:doBack 在 navigateBack 前恢复竖屏,_backed 防重复返回', function () {
+    expect(pageScript).toMatch(/doBack\s*:\s*function[\s\S]*?restorePortrait\(\)[\s\S]*?navigateBack\(\)/)
+    expect(pageScript).toMatch(/_backed/)
+  })
+
+  it('行为:doBack 先 setPageOrientation(portrait) 再 navigateBack,二次调用不再重复返回', function () {
+    const seq = []
+    const { vm } = makeVm({
+      uni: {
+        getWindowInfo: function () { return { windowHeight: 390 } },
+        navigateBack: function () { seq.push('navigateBack') }
+      },
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      window: undefined
+    })
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+    vm.doBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+  })
+
+  it('行为:onBack(返回按钮)收敛到 doBack,不回传直接退出', function () {
+    const seq = []
+    const { vm } = makeVm({
+      uni: {
+        getWindowInfo: function () { return { windowHeight: 390 } },
+        navigateBack: function () { seq.push('navigateBack') }
+      },
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      window: undefined
+    })
+    vm.onBack()
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+  })
+
+  it('行为:onUnload 兜底恢复(注销监听 + 恢复竖屏),异常退出也不污染原页面', function () {
+    const seq = []
+    const sandbox = {
+      uni: { getWindowInfo: function () { return { windowHeight: 390 } } },
+      wx: {
+        onWindowResize: function () {},
+        offWindowResize: function () { seq.push('offResize') },
+        setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) }
+      },
+      window: undefined
+    }
+    const { vm, opts } = makeVm(sandbox)
+    vm.bindResizeListener()
+    opts.onUnload.call(vm)
+    expect(seq).toEqual(['offResize', 'orient:portrait'])
+  })
+
+  it('行为:onConfirm 先 emit signatureConfirm 再收敛到 doBack(确认后回传并退出)', function () {
+    const emitted = []
+    const seq = []
+    const { vm } = makeVm({
+      uni: {
+        getWindowInfo: function () { return { windowHeight: 390 } },
+        navigateBack: function () { seq.push('navigateBack') }
+      },
+      wx: { setPageOrientation: function (cfg) { seq.push('orient:' + cfg.orientation) } },
+      window: undefined
+    })
+    vm.getOpenerEventChannel = function () {
+      return {
+        emit: function (name, payload) { emitted.push([name, payload]) }
+      }
+    }
+    vm.onConfirm('data:image/png;base64,ABC')
+    expect(emitted).toEqual([['signatureConfirm', 'data:image/png;base64,ABC']])
+    expect(seq).toEqual(['orient:portrait', 'navigateBack'])
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 权限流:签名页为通用独立页面,不区分角色,无 role 门禁 —— 适用性为「不适用」,
+// 显式记录(同 join-form.required-info.test.js 约定)。
+// ---------------------------------------------------------------------------
+
+describe.skip('权限流:签名页无角色门禁,不适用', function () {
+  it('占位:该能力面向通用签名交互,无 role 分支(详见汇报)', function () {})
+})

+ 336 - 0
cfc-frontend/__tests__/pages/tasks/taskHistory.view.test.js

@@ -0,0 +1,336 @@
+/**
+ * 契约级单测(TDD-RED/意外全绿)——能力键 task.history.view
+ *
+ * 溯源:
+ *   requirement: tests/user-scenarios/应用场景总览.md SC-P-94(家长·成就「完成任务」→ 历史完成任务页面)
+ *                + docs/需求分析/2026-11-06-成就成长打卡需求变更.md 变更 A(完成任务 → 历史完成任务页面)
+ *   design:      TaskController.getTaskHistory(POST /api/tasks/history,已合入 origin/cfclub)
+ *                + cfc-frontend/utils/api.js `getTaskHistory`(支持 memberId/page/size/category 分页)
+ *                + cfc-frontend/pages/tasks/history.vue(已合入 origin/cfclub,标题「历史完成任务」)
+ *                + cfc-frontend/pages.json 注册「pages/tasks/history」
+ *                + cfc-frontend/pages/profile-main/profile.vue「完成任务」卡 → goToTaskHistory
+ *
+ * 契约口径(key = unit.domain.action,「view」含页面装配,须按真实源码断言):
+ *   1) api 契约:api.js 导出 getTaskHistory(memberId, page, size, category),
+ *      以 POST 请求 /api/tasks/history,body = { memberId, page, size[, category] },
+ *      默认 page=1、size=10;category 缺省/空串时不携带。
+ *   2) view 装配:pages/tasks/history.vue 存在、在 pages.json 注册(标题「历史完成任务」)、
+ *      导入 getTaskHistory 并按 (memberId, page, pageSize, category||null) 分页调用、
+ *      含空态「暂无已完成任务」;loadHistory 行为级校验分页参数与响应装载。
+ *   3) 入口装配:profile.vue「完成任务」成就卡 goToTaskHistory → uni.navigateTo('/pages/tasks/history')。
+ *
+ * 本文件只读真实源码(utils/api.js / pages/tasks/history.vue / pages.json / profile.vue),
+ * 不改任何业务代码。若上述契约已由 origin/cfclub 实现满足,本文件为「意外全绿」。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import * as api from '@/utils/api'
+
+const HISTORY_PAGE_PATH = path.join(__dirname, '../../../pages/tasks/history.vue')
+const PAGES_JSON_PATH = path.join(__dirname, '../../../pages.json')
+const PROFILE_PATH = path.join(__dirname, '../../../pages/profile-main/profile.vue')
+
+// ---------------------------------------------------------------------------
+// API 契约工具(沿用 api.test.js 的 uni.request 打桩方式)
+// ---------------------------------------------------------------------------
+
+/** Helper: make uni.request call success(data) on next tick */
+function mockSuccess(data) {
+  global.uni.request.mockImplementation((opts) => {
+    process.nextTick(() => {
+      if (opts.success) opts.success({ data })
+    })
+  })
+}
+
+/** Capture the last uni.request call options */
+function lastRequest() {
+  const calls = global.uni.request.mock.calls
+  return calls[calls.length - 1][0]
+}
+
+// ---------------------------------------------------------------------------
+// SFC 加载工具(沿用 join-form.required-info.test.js 的「抽取 <script> 求值」约定)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__historyStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__historyStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 history.vue:返回 { component, template } */
+function loadHistoryPage() {
+  var src = fs.readFileSync(HISTORY_PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 history.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__historyStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 合并 data()/methods 到 vm 实例(模拟 Vue Options 合并) */
+function instantiate(component) {
+  var vm = {}
+  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
+}
+
+/** 让已 resolve 的 Promise 链(.then 微任务)跑完 */
+function flush() {
+  return new Promise(function (resolve) { setImmediate(resolve) })
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.request.mockReset()
+  global.uni.showToast.mockReset()
+  global.uni.reLaunch.mockReset()
+  global.uni.navigateTo.mockReset()
+  global.uni.getAccountInfoSync.mockReset()
+  global.uni.getAccountInfoSync.mockReturnValue({ miniProgram: { envVersion: 'develop' } })
+  // api.js 的 3 秒请求去重缓存是模块级单例,跨用例残留会让后续用例拿到上一次缓存的 Promise
+  api.clearApiDedup()
+  globalThis.__historyStubs = {
+    '@/components/MemberSelector.vue': { MemberSelector: { name: 'MemberSelector' } },
+    '../../utils/api.js': {
+      getFamilyMemberList: jest.fn(function () { return Promise.resolve({ code: 200, data: [] }) }),
+      getTaskHistory: jest.fn(function () { return Promise.resolve({ code: 200, data: { records: [] } }) })
+    },
+    '../../utils/format.js': { formatDateTime: jest.fn(function () { return '' }) },
+    '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} } }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__historyStubs
+})
+
+// ---------------------------------------------------------------------------
+// 1) API 契约:getTaskHistory(memberId, page, size, category) → POST /api/tasks/history
+// ---------------------------------------------------------------------------
+
+describe('api 契约:getTaskHistory → POST /api/tasks/history', function () {
+  test('导出 getTaskHistory 为函数', function () {
+    expect(typeof api.getTaskHistory).toBe('function')
+  })
+
+  test('以 POST 请求 /api/tasks/history 并携带 memberId/page/size', async function () {
+    mockSuccess({ code: 200 })
+    await api.getTaskHistory(5, 1, 20)
+    var opts = lastRequest()
+    expect(opts.method).toBe('POST')
+    expect(opts.url).toMatch(/\/api\/tasks\/history$/)
+    expect(opts.data.memberId).toBe(5)
+    expect(opts.data.page).toBe(1)
+    expect(opts.data.size).toBe(20)
+  })
+
+  test('缺省 page=1、size=10(分页契约默认值)', async function () {
+    mockSuccess({ code: 200 })
+    await api.getTaskHistory(5)
+    var opts = lastRequest()
+    expect(opts.data.memberId).toBe(5)
+    expect(opts.data.page).toBe(1)
+    expect(opts.data.size).toBe(10)
+  })
+
+  test('传入 category 时透传给 body', async function () {
+    mockSuccess({ code: 200 })
+    await api.getTaskHistory(5, 1, 20, '学习类')
+    var opts = lastRequest()
+    expect(opts.data.memberId).toBe(5)
+    expect(opts.data.page).toBe(1)
+    expect(opts.data.size).toBe(20)
+    expect(opts.data.category).toBe('学习类')
+  })
+
+  test('category 为空串时不携带(契约:仅传非空筛选)', async function () {
+    mockSuccess({ code: 200 })
+    await api.getTaskHistory(5, 1, 20, '')
+    var opts = lastRequest()
+    expect(opts.data.category).toBeUndefined()
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 2) view 装配(静态结构):history.vue 存在、注册、导入与分页调用、空态
+// ---------------------------------------------------------------------------
+
+describe('view 装配(静态):pages/tasks/history.vue', function () {
+  var src
+  beforeAll(function () {
+    src = fs.readFileSync(HISTORY_PAGE_PATH, 'utf8')
+  })
+
+  test('history.vue 存在且包含 <template> 与 <script> 块', function () {
+    expect(fs.existsSync(HISTORY_PAGE_PATH)).toBe(true)
+    expect(src).toMatch(/<template>/)
+    expect(src).toMatch(/<script>/)
+  })
+
+  test('导入 getTaskHistory 与 getFamilyMemberList(数据源装配)', function () {
+    expect(src).toMatch(/import\s*\{[^}]*getTaskHistory[^}]*\}\s*from\s*['"][^'"]*utils\/api\.js['"]/)
+    expect(src).toMatch(/import\s*\{[^}]*getFamilyMemberList[^}]*\}\s*from\s*['"][^'"]*utils\/api\.js['"]/)
+  })
+
+  test('导入 MemberSelector 组件(成员选择装配)', function () {
+    expect(src).toMatch(/import\s+MemberSelector\s+from\s*['"][^'"]*MemberSelector\.vue['"]/)
+  })
+
+  test('分页调用 getTaskHistory(memberId, page, pageSize, category||null)', function () {
+    // loadHistory 内以「4 参」调用,且第 4 参为 currentCategory || null(契约:无筛选传 null)
+    var call = src.match(/getTaskHistory\(\s*memberId\s*,\s*this\.page\s*,\s*this\.pageSize\s*,\s*this\.currentCategory\s*\|\|\s*null\s*\)/)
+    expect(call).not.toBeNull()
+  })
+
+  test('模板含空态「暂无已完成任务」与加载更多', function () {
+    var tmpl = (src.match(/<template>([\s\S]*?)<\/template>/) || [])[1] || ''
+    expect(tmpl).toContain('暂无已完成任务')
+    expect(tmpl).toContain('点击加载更多')
+  })
+})
+
+describe('view 装配(静态):pages.json 注册', function () {
+  var pagesJson
+  beforeAll(function () {
+    pagesJson = JSON.parse(fs.readFileSync(PAGES_JSON_PATH, 'utf8'))
+  })
+
+  test('pages/tasks 分包注册 history 页面且标题为「历史完成任务」', function () {
+    var sub = (pagesJson.subPackages || []).find(function (p) { return p.root === 'pages/tasks' })
+    expect(sub).toBeTruthy()
+    var page = (sub.pages || []).find(function (p) { return p.path === 'history' })
+    expect(page).toBeTruthy()
+    expect(page.style.navigationBarTitleText).toBe('历史完成任务')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 3) 入口装配(静态):profile.vue「完成任务」卡 → goToTaskHistory → /pages/tasks/history
+// ---------------------------------------------------------------------------
+
+describe('入口装配(静态):profile.vue「完成任务」卡', function () {
+  var src
+  beforeAll(function () {
+    src = fs.readFileSync(PROFILE_PATH, 'utf8')
+  })
+
+  test('成就卡「完成任务」绑定 goToTaskHistory', function () {
+    expect(src).toMatch(/@click="goToTaskHistory"/)
+    // 「完成任务」文案须与 goToTaskHistory 处于同一 ach-item 卡块内:
+    // 绑定出现后紧邻的「完成任务」label(同一卡内,间隔仅 ach-icon-wrap/ach-num)
+    var clickIdx = src.indexOf('@click="goToTaskHistory"')
+    var labelIdx = src.indexOf('完成任务', clickIdx)
+    expect(labelIdx).toBeGreaterThan(clickIdx)
+    expect(labelIdx - clickIdx).toBeLessThan(400)
+  })
+
+  test('goToTaskHistory 跳转 /pages/tasks/history', function () {
+    expect(src).toMatch(/goToTaskHistory\s*:\s*function\s*\([^)]*\)\s*\{[^}]*navigateTo\(\{\s*url:\s*['"]\/pages\/tasks\/history['"]\s*\}/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 4) view 装配(行为级):loadHistory 以分页参数调用 getTaskHistory 并装载响应
+// ---------------------------------------------------------------------------
+
+describe('view 装配(行为级):history.vue loadHistory', function () {
+  test('loadHistory(true) 以 (memberId, page, pageSize, category||null) 调用 getTaskHistory', async function () {
+    var getTaskHistorySpy = jest.fn(function () {
+      return Promise.resolve({ code: 200, data: { records: [{ id: 1, title: '任务A', category: '学习类' }] } })
+    })
+    globalThis.__historyStubs['../../utils/api.js'].getTaskHistory = getTaskHistorySpy
+    var page = loadHistoryPage()
+    var vm = instantiate(page.component)
+    vm.currentMemberId = 5
+    vm.page = 1
+    vm.pageSize = 20
+    vm.currentCategory = '学习类'
+    vm.loadHistory(true)
+    await flush()
+    expect(getTaskHistorySpy).toHaveBeenCalledWith(5, 1, 20, '学习类')
+  })
+
+  test('无筛选时第 4 参为 null(契约:不携带 category)', async function () {
+    var getTaskHistorySpy = jest.fn(function () {
+      return Promise.resolve({ code: 200, data: { records: [] } })
+    })
+    globalThis.__historyStubs['../../utils/api.js'].getTaskHistory = getTaskHistorySpy
+    var page = loadHistoryPage()
+    var vm = instantiate(page.component)
+    vm.currentMemberId = 5
+    vm.currentCategory = ''
+    vm.loadHistory(true)
+    await flush()
+    expect(getTaskHistorySpy).toHaveBeenCalledWith(5, 1, 20, null)
+  })
+
+  test('响应 records 装载进 taskList,hasMore 由 records 长度与 pageSize 决定', async function () {
+    var records = []
+    for (var i = 0; i < 20; i++) records.push({ id: i + 1, title: '任务' + (i + 1) })
+    globalThis.__historyStubs['../../utils/api.js'].getTaskHistory = jest.fn(function () {
+      return Promise.resolve({ code: 200, data: { records: records } })
+    })
+    var page = loadHistoryPage()
+    var vm = instantiate(page.component)
+    vm.currentMemberId = 5
+    vm.loadHistory(true)
+    await flush()
+    expect(vm.taskList.length).toBe(20)
+    // 20 条 == pageSize → hasMore 为 true 且 page 递增到 2
+    expect(vm.hasMore).toBe(true)
+    expect(vm.page).toBe(2)
+    expect(vm.loading).toBe(false)
+  })
+
+  test('无 memberId 时不发请求且 hasMore 置 false(空态前提)', async function () {
+    var getTaskHistorySpy = jest.fn()
+    globalThis.__historyStubs['../../utils/api.js'].getTaskHistory = getTaskHistorySpy
+    var page = loadHistoryPage()
+    var vm = instantiate(page.component)
+    vm.currentMemberId = null
+    global.uni._storage.userId = ''
+    vm.loadHistory(true)
+    await flush()
+    expect(getTaskHistorySpy).not.toHaveBeenCalled()
+    expect(vm.hasMore).toBe(false)
+    expect(vm.loading).toBe(false)
+  })
+})

+ 67 - 0
cfc-frontend/__tests__/setup.js

@@ -0,0 +1,67 @@
+/**
+ * Jest setup file for cfc-frontend mini-program tests.
+ * Mocks the global `uni` API and other mini-program runtime globals.
+ */
+
+// ---- Mock uni global ----
+global.uni = {
+  // Storage mocks
+  _storage: {},
+  getStorageSync(key) {
+    return this._storage[key] !== undefined ? this._storage[key] : ''
+  },
+  setStorageSync(key, value) {
+    this._storage[key] = value
+  },
+  removeStorageSync(key) {
+    delete this._storage[key]
+  },
+
+  // Request mock (override in individual tests)
+  request: jest.fn(),
+
+  // Toast mock
+  showToast: jest.fn(),
+
+  // Navigation mocks
+  navigateTo: jest.fn(),
+  redirectTo: jest.fn(),
+  reLaunch: jest.fn(),
+  switchTab: jest.fn(),
+  navigateBack: jest.fn(),
+
+  // Account info mock (set in tests as needed)
+  getAccountInfoSync: jest.fn(() => ({
+    miniProgram: { envVersion: 'develop' }
+  })),
+
+  // Other common uni APIs
+  showLoading: jest.fn(),
+  hideLoading: jest.fn(),
+  showModal: jest.fn(),
+  login: jest.fn(),
+  getUserProfile: jest.fn(),
+  getUserInfo: jest.fn(),
+  getSystemInfoSync: jest.fn(() => ({
+    platform: 'devtools',
+    language: 'zh_CN',
+    version: '8.0.0'
+  }))
+}
+
+// ---- Mock getCurrentPages ----
+// 小程序运行时全局(不在 uni 上)。utils/api.js 的 _inLaunchWindow() 用它判断
+// 是否仍处于启动窗口(splash 未切走),因为 pages/login 是分包,
+// 启动窗口内 reLaunch 到未下载的分包页会报 "Page has not been registered yet"。
+// 默认返回一个「已渲染的非 splash 页面」,即正常交互态(此时应允许跳登录页)。
+// 用例内可覆盖 global.getCurrentPages 返回 [] 或 splash 页面来测启动窗口分支。
+global.getCurrentPages = jest.fn(() => [{ route: 'pages/index-home/index' }])
+
+// ---- Mock Vue ----
+jest.mock('vue', () => {
+  const Vue = jest.requireActual('vue')
+  Vue.config.productionTip = false
+  return Vue
+})
+
+

+ 99 - 0
cfc-frontend/__tests__/specs/coupon-claimed-actions.test.js

@@ -0,0 +1,99 @@
+/**
+ * 验收逻辑守卫:我的优惠券「已领取券」按钮修复 + 使用按券类型跳转
+ * 对应需求文档:docs/superpowers/specs/2026-11-06-coupon-claimed-actions.md
+ *
+ * 说明(与仓库既有约定一致,见 FamilyRelationGraph.test.js):
+ *   cfc-frontend jest 配置 testEnvironment=node,且仅 babel-jest 转换 .js,
+ *   无 vue-jest,故 .vue SFC 方法无法直接挂载测试。仓库惯例是把组件中
+ *   的「纯决策逻辑」抽取为本地函数在此测试。以下函数镜像 coupons.vue
+ *   useCoupon()/giftCoupon() 的跳转决策表(spec §4.1 / §验收标准 2-5)。
+ *
+ *   建议(非本闭环范围,禁止改生产源码):将 resolveCouponUseRoute 抽到
+ *   utils/couponRoute.js,届时本测试直接 import 真实实现即可升级为真正单测。
+ */
+
+// ---- 镜像 coupons.vue useCoupon(coupon) 的路由决策 ----
+function resolveCouponUseRoute(coupon) {
+  const applicableTo = coupon && coupon.applicableTo
+  if (applicableTo === 'PRODUCT') {
+    // 指定商品券:跳确认订单页,自动选券(用券实例 id 作为 couponId)
+    const productId = coupon.productId
+    if (productId) {
+      return `/pages/shop/checkout/checkout?from=coupon&id=${productId}&couponId=${coupon.id}`
+    }
+    // productId 缺失兜底跳商城,不报错(spec §风险)
+    return '/pages/shop/index/index'
+  }
+  if (applicableTo === 'ALL') {
+    return '/pages/shop/index/index' // 全品类 → 商城
+  }
+  if (applicableTo === 'MEMBERSHIP') {
+    return '/pages/membership/upgrade' // 会员券 → 开通会员
+  }
+  // 兜底(ASSESSMENT/其他/null)→ 商城
+  return '/pages/shop/index/index'
+}
+
+// 转赠统一跳赠送会员券页(spec §4.1.3)
+function resolveCouponGiftRoute() {
+  return '/pages/membership/gift-coupon'
+}
+
+// 已领取券应显示「使用 + 转赠」,不再显示「立即领取」(spec §验收 1/6)
+function canClaim(coupon) {
+  // 已领取券 status 为 AVAILABLE/USED/EXPIRED,均非可领取态
+  const claimable = !coupon || !coupon.status || coupon.status === 'AVAILABLE'
+  // spec 根因:canClaim 对“已领取(有券实例)”应返回 false
+  const isClaimedInstance = !!(coupon && coupon.id && coupon.couponId)
+  return claimable && !isClaimedInstance
+}
+
+describe('resolveCouponUseRoute - 使用按钮按券类型跳转', () => {
+  it('PRODUCT 券带 productId → 跳确认订单并自动选券(实例id)', () => {
+    const route = resolveCouponUseRoute({ applicableTo: 'PRODUCT', productId: 9527, id: 7001, couponId: 2001 })
+    expect(route).toBe('/pages/shop/checkout/checkout?from=coupon&id=9527&couponId=7001')
+  })
+
+  it('PRODUCT 券 couponId 必须用实例id(7001)而非模板id(2001)', () => {
+    const route = resolveCouponUseRoute({ applicableTo: 'PRODUCT', productId: 9527, id: 7001, couponId: 2001 })
+    expect(route).toContain('couponId=7001')
+    expect(route).not.toContain('couponId=2001')
+  })
+
+  it('PRODUCT 券 productId 缺失 → 兜底跳商城(不报错)', () => {
+    const route = resolveCouponUseRoute({ applicableTo: 'PRODUCT', id: 7001 })
+    expect(route).toBe('/pages/shop/index/index')
+  })
+
+  it('ALL 全品类券 → 跳商城', () => {
+    expect(resolveCouponUseRoute({ applicableTo: 'ALL', id: 7001 })).toBe('/pages/shop/index/index')
+  })
+
+  it('MEMBERSHIP 会员券 → 跳开通会员', () => {
+    expect(resolveCouponUseRoute({ applicableTo: 'MEMBERSHIP', id: 7001 })).toBe('/pages/membership/upgrade')
+  })
+
+  it('兜底(ASSESSMENT/null) → 跳商城', () => {
+    expect(resolveCouponUseRoute({ applicableTo: 'ASSESSMENT', id: 7001 })).toBe('/pages/shop/index/index')
+    expect(resolveCouponUseRoute({ id: 7001 })).toBe('/pages/shop/index/index')
+  })
+})
+
+describe('resolveCouponGiftRoute - 转赠按钮跳转', () => {
+  it('转赠 → 跳赠送会员券页', () => {
+    expect(resolveCouponGiftRoute()).toBe('/pages/membership/gift-coupon')
+  })
+})
+
+describe('canClaim - 已领取券不再显示「立即领取」', () => {
+  it('已领取券实例(有 id+couponId) → 不可领取', () => {
+    expect(canClaim({ id: 7001, couponId: 2001, status: 'AVAILABLE' })).toBe(false)
+  })
+  it('已使用/已过期券 → 不可领取', () => {
+    expect(canClaim({ id: 7001, couponId: 2001, status: 'USED' })).toBe(false)
+    expect(canClaim({ id: 7001, couponId: 2001, status: 'EXPIRED' })).toBe(false)
+  })
+  it('无券实例(纯模板) → 可领取', () => {
+    expect(canClaim({ status: 'AVAILABLE' })).toBe(true)
+  })
+})

+ 331 - 0
cfc-frontend/__tests__/specs/report-upload-guide-config.test.js

@@ -0,0 +1,331 @@
+/**
+ * 验收逻辑守卫(TDD-RED):报告上传页「支持的报告类型」配置化改版(后台可配置 guide-list)
+ *
+ * 背景(2026-11-27 报告上传说明区配置化改版,四条用户需求):
+ *   ① 去掉页面最下面的「关联商品」区;
+ *   ② 素质测评/菌群检测等条目里的「商品+购买按钮」缩小、与类型标题放同一行;
+ *   ③ 菌群检测报告、体检报告等所有报告类型一致;
+ *   ④ 该区域改为后台可配置:标题、内容、关联商品都通过后台配置。
+ *   数据源 = utils/api.js 的 getReportTypeLinks()(POST /api/report-parser/types/links),
+ *   返回全部 is_active=1 类型,字段含 typeId/displayName/description/icon/sortOrder/
+ *   linkedProductId/productName,按 sortOrder 升序 + id 升序稳定排序。
+ *
+ * 说明(沿用 cfc-frontend/__tests__/aiyunyi/report-upload.uploadCard.contract.test.js 的
+ *   「加载真实 SFC 源码求值」约定):
+ *   jest 配置为 node 环境、无 vue-jest 挂载组件;本文件直接读取真实 report-upload.vue 的
+ *   <script>/<template> 源码——
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的
+ *       computed(sortedGuideTypes) 与 methods(guideIcon/guideIconClass) 做行为级断言;
+ *     - <template>:读取模板文本做结构契约断言(guide-title-row 标题与购买按钮同行、
+ *       购买按钮仅在 linkedProductId 时出现、无 linked-products 残留、无 guide-link 残留)。
+ *   同时镜像三个纯决策函数(sortedGuideTypes/guideIcon/hasBuyButton)做边界测试,
+ *   与组件实现逐位对齐(排序兜底/图标回退/按钮可见性)。
+ *   若 GREEN 阶段实现方补齐上述契约,本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   本文件不修改 pages/、pages.json、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+var REPORT_UPLOAD_PATH = path.join(__dirname, '../../pages/health/report-upload.vue')
+
+/** 把 ES import 语句替换为从 globalThis.__reportUploadStubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  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.__reportUploadStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadReportUpload() {
+  var src = fs.readFileSync(REPORT_UPLOAD_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 report-upload.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__reportUploadStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/computed/methods 构造可驱动上下文 */
+function instantiate(component) {
+  var 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
+}
+
+/** 取真实组件的 computed 定义(未被 instantiate 展开到 vm 上,需单独调用求值) */
+function getComputed(component) {
+  return component.computed || {}
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+beforeEach(function () {
+  globalThis.__reportUploadStubs = {
+    '../../utils/memberNormalize.js': {
+      normalizeMembers: function (list) { return list || [] },
+      memberIdOf: function (m) { return m && m.id }
+    },
+    '../../utils/api.js': {
+      uploadReportOnly: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getReportCollectStatus: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getFamilyMemberList: jest.fn(function () { return Promise.resolve({ data: [] }) }),
+      requestReportTransfer: jest.fn(function () { return Promise.resolve({ code: 200 }) }),
+      getReportTypeLinks: jest.fn(function () { return Promise.resolve({ data: [] }) })
+    },
+    '../../utils/image-picker.js': { pickImage: jest.fn() },
+    '@/mixins/font-scale.js': {
+      fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+    }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__reportUploadStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC1 sortedGuideTypes computed:sortOrder 升序 + typeId 稳定兜底(§配置化改版)
+// ---------------------------------------------------------------------------
+
+describe('AC1 sortedGuideTypes computed', function () {
+  it('组件 computed 中定义 sortedGuideTypes', function () {
+    var component = loadReportUpload().component
+    expect(typeof getComputed(component).sortedGuideTypes).toBe('function')
+  })
+
+  it('sortOrder 升序排列', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'dan_a2', sortOrder: 20, displayName: '素质测评' },
+      { typeId: 'gut_flora', sortOrder: 10, displayName: '菌群检测' },
+      { typeId: 'physical_exam', sortOrder: 30, displayName: '体检报告' }
+    ]
+    var out = getComputed(component).sortedGuideTypes.call(vm)
+    expect(out.map(function (x) { return x.typeId })).toEqual(['gut_flora', 'dan_a2', 'physical_exam'])
+  })
+
+  it('sortOrder 空(null/undefined)按 100 兜底排序,相等按 typeId 字符串稳定', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'tongue', sortOrder: null, displayName: '舌象照片' },
+      { typeId: 'body_fat', displayName: '体脂秤报告' }, // undefined sortOrder
+      { typeId: 'dan_a2', sortOrder: 10, displayName: '素质测评' }
+    ]
+    var out = getComputed(component).sortedGuideTypes.call(vm)
+    expect(out.map(function (x) { return x.typeId })).toEqual(['dan_a2', 'body_fat', 'tongue'])
+  })
+
+  it('reportTypeLinks 为空/非数组 → 返回 [](不抛错)', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = null
+    expect(getComputed(component).sortedGuideTypes.call(vm)).toEqual([])
+    vm.reportTypeLinks = 'not-array'
+    expect(getComputed(component).sortedGuideTypes.call(vm)).toEqual([])
+  })
+
+  it('不修改原数组(深比较)', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'dan_a2', sortOrder: 20 },
+      { typeId: 'gut_flora', sortOrder: 10 }
+    ]
+    var before = JSON.stringify(vm.reportTypeLinks)
+    getComputed(component).sortedGuideTypes.call(vm)
+    expect(JSON.stringify(vm.reportTypeLinks)).toBe(before)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC2 guideIcon(item):icon 优先,空回退 typeId 映射,未知回退 📄
+// ---------------------------------------------------------------------------
+
+describe('AC2 guideIcon(item) 图标回退', function () {
+  it('组件 methods 中定义 guideIcon', function () {
+    var component = loadReportUpload().component
+    expect(typeof instantiate(component).guideIcon).toBe('function')
+  })
+
+  it('有 icon 字段 → 优先使用', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'gut_flora', icon: '🦠' })).toBe('🦠')
+    expect(vm.guideIcon({ typeId: 'unknown_xyz', icon: '🌟' })).toBe('🌟')
+  })
+
+  it('icon 为空 → 回退 typeId 默认映射(gut_flora/dan_a2/physical_exam/tongue/body_fat)', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'gut_flora' })).toBe('📄')
+    expect(vm.guideIcon({ typeId: 'dan_a2', icon: '' })).toBe('🧠')
+    expect(vm.guideIcon({ typeId: 'physical_exam', icon: null })).toBe('📋')
+    expect(vm.guideIcon({ typeId: 'tongue' })).toBe('👅')
+    expect(vm.guideIcon({ typeId: 'body_fat' })).toBe('⚖️')
+  })
+
+  it('未知 typeId / 无 typeId / item 为 null → 回退 📄', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'some_new_type' })).toBe('📄')
+    expect(vm.guideIcon({})).toBe('📄')
+    expect(vm.guideIcon(null)).toBe('📄')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC3 guideIconClass(idx):循环四色视觉(blue/purple/orange/teal 按位取模)
+// ---------------------------------------------------------------------------
+
+describe('AC3 guideIconClass(idx) 循环四色', function () {
+  it('组件 methods 中定义 guideIconClass', function () {
+    var component = loadReportUpload().component
+    expect(typeof instantiate(component).guideIconClass).toBe('function')
+  })
+
+  it('按 idx 取模返回四色 class', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIconClass(0)).toBe('guide-icon-blue')
+    expect(vm.guideIconClass(1)).toBe('guide-icon-purple')
+    expect(vm.guideIconClass(2)).toBe('guide-icon-orange')
+    expect(vm.guideIconClass(3)).toBe('guide-icon-teal')
+    expect(vm.guideIconClass(4)).toBe('guide-icon-blue') // 循环
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC4 模板结构契约:标题与购买按钮同行、购买按钮仅在 linkedProductId 时出现、
+//     无 linked-products 残留、无 guide-link 残留(§配置化改版 ①②③)
+// ---------------------------------------------------------------------------
+
+describe('AC4 模板结构契约', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__reportUploadStubs = {}
+    template = loadReportUpload().template
+  })
+
+  it('guide-item 为 v-for 配置驱动(含 sortedGuideTypes 数据源,§④后台可配置)', function () {
+    expect(template).toMatch(/v-for="[^"]*\bsortedGuideTypes\b/)
+  })
+
+  it('标题与购买按钮同一行:guide-title-row 内含 guide-name 与 guide-buy(§②同行)', function () {
+    var start = template.indexOf('guide-title-row')
+    expect(start).toBeGreaterThan(-1)
+    var rowStart = template.lastIndexOf('<view class="guide-title-row"', start)
+    expect(rowStart).toBeGreaterThan(-1)
+    var rowEnd = template.indexOf('</view>', start)
+    var block = template.slice(rowStart, rowEnd)
+    expect(block).toMatch(/class="guide-name"/)
+    expect(block).toMatch(/class="guide-buy"/)
+  })
+
+  it('购买按钮仅在 linkedProductId 时出现(v-if="item.linkedProductId",§②缩小+一致)', function () {
+    expect(template).toMatch(/class="guide-buy"[^>]*v-if="item\.linkedProductId"|v-if="item\.linkedProductId"[^>]*class="guide-buy"/)
+  })
+
+  it('已删除重复的 guide-link(查看商品)块(§②去重复,只留一个小购买按钮)', function () {
+    expect(template).not.toMatch(/class="guide-link"/)
+  })
+
+  it('已删除「关联商品」区(linked-products-section,§①去掉底部关联商品区)', function () {
+    expect(template).not.toMatch(/linked-products-section/)
+    expect(template).not.toMatch(/linked-product-card/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 镜像纯决策函数(边界守卫,与组件实现逐位对齐)
+// ---------------------------------------------------------------------------
+
+function sortedGuideTypesMirror(links) {
+  if (!Array.isArray(links)) return []
+  return links.slice().sort(function (a, b) {
+    var sa = (a && a.sortOrder !== null && a.sortOrder !== undefined) ? a.sortOrder : 100
+    var sb = (b && b.sortOrder !== null && b.sortOrder !== undefined) ? b.sortOrder : 100
+    if (sa !== sb) return sa - sb
+    var ta = String((a && a.typeId) || '')
+    var tb = String((b && b.typeId) || '')
+    return ta < tb ? -1 : (ta > tb ? 1 : 0)
+  })
+}
+
+function hasBuyButtonMirror(item) {
+  if (!item) return false
+  var pid = item.linkedProductId
+  if (pid === null || pid === undefined || pid === '') return false
+  if (pid === 0) return false
+  return true
+}
+
+describe('镜像守卫 sortedGuideTypesMirror', function () {
+  it('非数组/空 → []', function () {
+    expect(sortedGuideTypesMirror(null)).toEqual([])
+    expect(sortedGuideTypesMirror(undefined)).toEqual([])
+    expect(sortedGuideTypesMirror('not-array')).toEqual([])
+    expect(sortedGuideTypesMirror([])).toEqual([])
+  })
+
+  it('sortOrder 升序;空按 100 兜底;相等按 typeId 稳定', function () {
+    var links = [
+      { typeId: 'tongue', sortOrder: null },
+      { typeId: 'body_fat' },
+      { typeId: 'dan_a2', sortOrder: 10 }
+    ]
+    expect(sortedGuideTypesMirror(links).map(function (x) { return x.typeId })).toEqual(['dan_a2', 'body_fat', 'tongue'])
+  })
+
+  it('不修改原数组', function () {
+    var links = [{ typeId: 'dan_a2', sortOrder: 20 }, { typeId: 'gut_flora', sortOrder: 10 }]
+    var before = JSON.stringify(links)
+    sortedGuideTypesMirror(links)
+    expect(JSON.stringify(links)).toBe(before)
+  })
+})
+
+describe('镜像守卫 hasBuyButtonMirror', function () {
+  it('linkedProductId 非空(正数/字符串数字) → true', function () {
+    expect(hasBuyButtonMirror({ linkedProductId: 100 })).toBe(true)
+    expect(hasBuyButtonMirror({ linkedProductId: '200' })).toBe(true)
+  })
+
+  it('linkedProductId = 0 / null / undefined / 空串 → false;item null → false', function () {
+    expect(hasBuyButtonMirror({ linkedProductId: 0 })).toBe(false)
+    expect(hasBuyButtonMirror({ linkedProductId: null })).toBe(false)
+    expect(hasBuyButtonMirror({})).toBe(false)
+    expect(hasBuyButtonMirror({ linkedProductId: '' })).toBe(false)
+    expect(hasBuyButtonMirror(null)).toBe(false)
+  })
+})

+ 59 - 0
cfc-frontend/__tests__/specs/shop-price-sort.test.js

@@ -0,0 +1,59 @@
+/**
+ * 验收逻辑守卫:商城商品列表「按价格排序」参数构造
+ * 对应需求文档:docs/需求分析/2026-11-07-商城价格排序需求变更.md(变更 S1)
+ * 实现任务书:docs/superpowers/specs/2026-11-07-shop-price-sort.md(已派发 lan-204 dev中)
+ *
+ * 说明(与仓库既有约定一致,见 coupon-claimed-actions.test.js):
+ *   cfc-frontend jest 配置 testEnvironment=node,无 vue-jest,.vue SFC 方法无法直接挂载。
+ *   约定是把组件中「纯决策逻辑」抽取为本地函数在此测试。以下函数镜像
+ *   shop/index/index.vue 的 `buildSort(sortType)`(spec §变更 S1):
+ *     price_asc  → [{column:'price',order:'asc'}]
+ *     price_desc → [{column:'price',order:'desc'}]
+ *     default/其他 → [](不传,走后端默认 sort_order asc + created_at desc)
+ *
+ *   关键风险(spec §风险 1):排序参数必须是数组 [{column,order}],字符串会被
+ *   后端 SortInterceptor 忽略(这是 loadRecommended 现有 sort:'sales' 无效的根因)。
+ *   本守卫显式断言返回值为数组,防前端复现该 bug。
+ *
+ *   注意:S1 当前在 dev 分支(lan-204)开发,cfclub 尚未合入;本文件为「验收逻辑守卫」,
+ *   守卫 spec 契约,而非已合入实现。建议合入后将 buildSort 抽到 utils 后改为 import 真实实现。
+ */
+
+// ---- 镜像 shop/index/index.vue buildSort(sortType) ----
+function buildSort(sortType) {
+  if (sortType === 'price_asc') return [{ column: 'price', order: 'asc' }]
+  if (sortType === 'price_desc') return [{ column: 'price', order: 'desc' }]
+  return [] // default / 未知类型 → 不传 sort,走后端默认排序
+}
+
+describe('buildSort - 商城按价格排序参数构造', () => {
+  it('price_asc → 数组 [{column:price,order:asc}]', () => {
+    expect(buildSort('price_asc')).toEqual([{ column: 'price', order: 'asc' }])
+  })
+
+  it('price_desc → 数组 [{column:price,order:desc}]', () => {
+    expect(buildSort('price_desc')).toEqual([{ column: 'price', order: 'desc' }])
+  })
+
+  it('default → 空数组(不传 sort,走后端默认排序)', () => {
+    expect(buildSort('default')).toEqual([])
+  })
+
+  it('未知/空 sortType → 空数组(不污染后端默认排序)', () => {
+    expect(buildSort('')).toEqual([])
+    expect(buildSort('sales')).toEqual([]) // 字符串 'sales' 旧 bug 形态,必须被忽略而非透传
+    expect(buildSort(undefined)).toEqual([])
+  })
+
+  it('守卫:返回值必须是数组(防 SortInterceptor 忽略字符串 bug)', () => {
+    for (const t of ['price_asc', 'price_desc', 'default', 'sales', '']) {
+      expect(Array.isArray(buildSort(t))).toBe(true)
+    }
+  })
+
+  it('守卫:price 列名拼写正确(与 SortUtil 驼峰→下划线映射 product.price 对应)', () => {
+    const asc = buildSort('price_asc')[0]
+    expect(asc && asc.column).toBe('price')
+    expect(asc.order).toBe('asc')
+  })
+})

+ 52 - 0
cfc-frontend/__tests__/specs/team-invite-share.test.js

@@ -0,0 +1,52 @@
+/**
+ * 验收逻辑守卫:我的团队「推广收益内外口径对齐」+「邀请成员直接分享」
+ * 对应需求文档:docs/superpowers/specs/2026-11-06-team-invite-share.md
+ *
+ * 说明(与仓库既有约定一致):cfc-frontend jest 无 vue-jest,SFC 方法不可挂载。
+ * 以下本地函数镜像 profile.vue loadReferralEarnings() 的口径换算逻辑
+ * (spec §3.1 / §验收 1):profile 推广收益改取 getCfSummary().totalEarned,
+ * 并 ÷100(分→元),与推广中心 promotion/index.vue 的 cfVal 显示一致。
+ *
+ * 建议(非本闭环范围,禁止改生产源码):将 toYuan 抽到 utils/money.js,
+ * 届时本测试 import 真实实现即升级为真正单测。
+ */
+
+// ---- 镜像 profile.vue loadReferralEarnings() 的换算 ----
+function toYuan(cfVal) {
+  // spec: self.referralEarnings = (res.data.totalEarned || 0) / 100
+  return (cfVal || 0) / 100
+}
+
+// 内外口径一致性:profile 展示值应与 promotion 收益总览(cfVal(totalEarned))相等
+function isEarningsAligned(profileCfVal, promotionCfVal) {
+  return toYuan(profileCfVal) === toYuan(promotionCfVal)
+}
+
+describe('toYuan - 推广收益 分→元 口径', () => {
+  it('正常分值为元(100分=1元)', () => {
+    expect(toYuan(100)).toBe(1)
+  })
+  it('非零分值正确换算', () => {
+    expect(toYuan(12345)).toBe(123.45)
+  })
+  it('0 → 0', () => {
+    expect(toYuan(0)).toBe(0)
+  })
+  it('null → 0(spec: totalEarned || 0)', () => {
+    expect(toYuan(null)).toBe(0)
+  })
+  it('undefined → 0', () => {
+    expect(toYuan(undefined)).toBe(0)
+  })
+})
+
+describe('isEarningsAligned - 内外口径一致(验收标准 1)', () => {
+  it('profile 与 promotion 取同一 CF 总览值 → 数字一致', () => {
+    // 同一用户、无新佣金变动时,两者 totalEarned 相同
+    expect(isEarningsAligned(8800, 8800)).toBe(true)
+  })
+  it('不同口径(旧佣金求和 vs 新 CF 总览)会不一致 → 需统一为 CF 口径', () => {
+    // 仅当两者都已改为 getCfSummary().totalEarned 才一致
+    expect(isEarningsAligned(8800, 8800)).toBe(true)
+  })
+})

+ 201 - 0
cfc-frontend/__tests__/store/store.test.js

@@ -0,0 +1,201 @@
+/**
+ * Tests for cfc-frontend store/index.js (Vuex store)
+ */
+import store from '@/store/index'
+
+beforeEach(() => {
+  global.uni._storage = {}
+  global.uni.request.mockReset()
+  global.uni.showToast.mockReset()
+})
+
+describe('Vuex Store', () => {
+  // --------------- initial state ---------------
+
+  test('has correct initial state', () => {
+    expect(store.state.token).toBe('')
+    expect(store.state.userId).toBe('')
+    expect(store.state.role).toBe('parent')
+    expect(store.state.currentRole).toBe('parent')
+    expect(store.state.familyId).toBe('')
+    expect(store.state.nickname).toBe('')
+    expect(store.state.currentChildId).toBe('')
+    expect(store.state.children).toEqual([])
+    expect(store.state.isSwitchedChild).toBe(false)
+  })
+
+  // --------------- mutations ---------------
+
+  describe('mutations', () => {
+    beforeEach(() => {
+      // reset storage between tests
+      global.uni._storage = {}
+    })
+
+    test('setToken stores token in state and storage', () => {
+      store.commit('setToken', 'jwt-token')
+      expect(store.state.token).toBe('jwt-token')
+      expect(global.uni._storage.token).toBe('jwt-token')
+    })
+
+    test('setUserInfo sets user fields and saves to storage', () => {
+      const userInfo = {
+        userId: '100',
+        role: 'parent',
+        familyId: '1',
+        nickname: '测试家长'
+      }
+      store.commit('setUserInfo', userInfo)
+
+      expect(store.state.userId).toBe('100')
+      expect(store.state.role).toBe('parent')
+      expect(store.state.currentRole).toBe('parent')
+      expect(store.state.familyId).toBe('1')
+      expect(store.state.nickname).toBe('测试家长')
+      expect(store.state.isSwitchedChild).toBe(false)
+
+      // Verify storage sync
+      // 注意:familyId 的持久化由 setFamilyId 负责(见下一个用例),
+      // setUserInfo 只负责 state.familyId,不写 storage
+      expect(global.uni._storage.userId).toBe('100')
+      expect(global.uni._storage.role).toBe('parent')
+      expect(global.uni._storage.isSwitchedChild).toBe(false)
+    })
+
+    test('setFamilyId persists familyId to storage for cold start', () => {
+      store.commit('setFamilyId', '42')
+      expect(store.state.familyId).toBe('42')
+      expect(global.uni._storage.familyId).toBe('42')
+
+      // 无家庭时写入空串而非 undefined,保证冷启动 getStorageSync 能取到键
+      store.commit('setFamilyId', '')
+      expect(store.state.familyId).toBe('')
+      expect(global.uni._storage.familyId).toBe('')
+    })
+
+    test('setUserInfo clears switched-child flag', () => {
+      global.uni._storage.isSwitchedChild = true
+      store.commit('setUserInfo', {
+        userId: '100',
+        role: 'parent',
+        familyId: '1',
+        nickname: 'test'
+      })
+      expect(store.state.isSwitchedChild).toBe(false)
+    })
+
+    test('setChildren stores children and sets currentChildId', () => {
+      const children = [{ id: 5, name: '小明' }, { id: 6, name: '小红' }]
+      store.commit('setChildren', children)
+      expect(store.state.children).toEqual(children)
+      expect(store.state.currentChildId).toBe(5)
+    })
+
+    test('setCurrentChild updates currentChildId in state and storage', () => {
+      store.commit('setCurrentChild', 5)
+      expect(store.state.currentChildId).toBe(5)
+      expect(global.uni._storage.currentChildId).toBe(5)
+    })
+
+    test('switchToChild sets currentRole to child and marks switched', () => {
+      store.commit('switchToChild', 7)
+      expect(store.state.currentRole).toBe('child')
+      expect(store.state.currentChildId).toBe(7)
+      expect(store.state.isSwitchedChild).toBe(true)
+      expect(global.uni._storage.currentRole).toBe('child')
+      expect(global.uni._storage.currentChildId).toBe(7)
+      expect(global.uni._storage.isSwitchedChild).toBe(true)
+    })
+
+    test('switchBackToParent resets to parent role', () => {
+      // First switch to child
+      store.commit('switchToChild', 7)
+      expect(store.state.currentRole).toBe('child')
+
+      // Then switch back
+      store.commit('switchBackToParent')
+      expect(store.state.currentRole).toBe('parent')
+      expect(store.state.currentChildId).toBe('')
+      expect(store.state.isSwitchedChild).toBe(false)
+      expect(global.uni._storage.currentRole).toBe('parent')
+      expect(global.uni._storage.currentChildId).toBeUndefined()
+      expect(global.uni._storage.isSwitchedChild).toBe(false)
+    })
+
+    test('switchViewMode changes currentRole', () => {
+      store.commit('switchViewMode', 'teacher')
+      expect(store.state.currentRole).toBe('teacher')
+      expect(global.uni._storage.currentRole).toBe('teacher')
+    })
+
+    test('switchRole (compat) changes currentRole', () => {
+      store.commit('switchRole', 'admin')
+      expect(store.state.currentRole).toBe('admin')
+      expect(global.uni._storage.currentRole).toBe('admin')
+    })
+
+    test('logout clears all state and storage', () => {
+      // Set up some state
+      store.commit('setToken', 'jwt')
+      store.commit('setUserInfo', {
+        userId: '100',
+        role: 'parent',
+        familyId: '1',
+        nickname: 'test'
+      })
+      store.commit('setChildren', [{ id: 5, name: '小明' }])
+      store.commit('switchToChild', 7)
+
+      // Logout
+      store.commit('logout')
+
+      // State is reset
+      expect(store.state.token).toBe('')
+      expect(store.state.userId).toBe('')
+      expect(store.state.role).toBe('parent')
+      expect(store.state.currentRole).toBe('parent')
+      expect(store.state.familyId).toBe('')
+      expect(store.state.nickname).toBe('')
+      expect(store.state.currentChildId).toBe('')
+      expect(store.state.children).toEqual([])
+      expect(store.state.isSwitchedChild).toBe(false)
+
+      // Storage is cleared
+      expect(global.uni._storage.token).toBeUndefined()
+      expect(global.uni._storage.currentRole).toBeUndefined()
+      expect(global.uni._storage.isSwitchedChild).toBeUndefined()
+    })
+  })
+
+  // --------------- actions ---------------
+
+  describe('actions', () => {
+    beforeEach(() => {
+      global.uni._storage = {}
+      // Reset state
+      store.commit('logout')
+    })
+
+    test('login dispatches setToken and setUserInfo', () => {
+      const userInfo = {
+        token: 'jwt-token',
+        userId: '100',
+        role: 'parent',
+        familyId: '1',
+        nickname: '测试家长'
+      }
+      store.dispatch('login', userInfo)
+
+      expect(store.state.token).toBe('jwt-token')
+      expect(store.state.userId).toBe('100')
+      expect(store.state.role).toBe('parent')
+      expect(store.state.nickname).toBe('测试家长')
+    })
+
+    test('updateChildren dispatches setChildren', () => {
+      const children = [{ id: 1, name: '孩子1' }]
+      store.dispatch('updateChildren', children)
+      expect(store.state.children).toEqual(children)
+    })
+  })
+})

+ 44 - 0
cfc-frontend/__tests__/utils/bundle-pricing.test.js

@@ -0,0 +1,44 @@
+/**
+ * Tests for cfc-frontend utils/bundle-pricing.js
+ *
+ * 验证购物车套餐offer展示辅助:comboOfferOf 命中/未激活语义;formatComboOfferText 提示文案;
+ * 总价不再被自动扣减(纯展示,权威计算在后端 POST /api/cart/combo-offer)。
+ */
+const {
+  comboOfferOf,
+  formatComboOfferText
+} = require('@/utils/bundle-pricing')
+
+describe('comboOfferOf', () => {
+  it('null/undefined → null', () => {
+    expect(comboOfferOf(null)).toBeNull()
+    expect(comboOfferOf(undefined)).toBeNull()
+  })
+  it('active 非 true → null', () => {
+    expect(comboOfferOf({ active: false, comboName: '套餐X' })).toBeNull()
+    expect(comboOfferOf({})).toBeNull()
+  })
+  it('active=true → 返回 offer(纯展示,不篡改总价)', () => {
+    const offer = { active: true, comboName: '套餐X', comboPrice: 15000, saving: 2000, groups: 1 }
+    expect(comboOfferOf(offer)).toBe(offer)
+  })
+})
+
+describe('formatComboOfferText', () => {
+  it('无 offer → 空串', () => {
+    expect(formatComboOfferText(null)).toBe('')
+    expect(formatComboOfferText({ active: false })).toBe('')
+  })
+  it('有 offer → 「这N件组成套餐「XX」,套餐价 ¥Y(省 ¥Z)」', () => {
+    const txt = formatComboOfferText({ active: true, comboName: '豪华套餐', comboPrice: 15000, saving: 2000 }, 3)
+    expect(txt).toContain('3 件')
+    expect(txt).toContain('豪华套餐')
+    expect(txt).toContain('150.00')
+    expect(txt).toContain('20.00')
+  })
+  it('有 offer 无 checkedCount → 用 groups 兜底;saving=0 不显示省', () => {
+    const txt = formatComboOfferText({ active: true, comboName: '豪华套餐', comboPrice: 15000, saving: 0, groups: 2 })
+    expect(txt).toContain('2 件')
+    expect(txt).not.toContain('省')
+  })
+})

+ 38 - 0
cfc-frontend/__tests__/utils/countAvailableCoupons.test.js

@@ -0,0 +1,38 @@
+/**
+ * 契约单测:我的页面优惠券计数口径与列表页「可使用」tab 一致。
+ *
+ * 背景:用户12家庭有 5 张券(4 AVAILABLE + 1 EXPIRED),我的页面显示 5,
+ * 但列表页默认「可使用」tab 只显示 4 —— 计数需只统计 AVAILABLE(与列表一致)。
+ */
+import { countAvailableCoupons } from '@/utils/couponCount'
+
+describe('countAvailableCoupons 我的页面可用券计数', () => {
+  test('只统计 AVAILABLE(含无 status 的老数据),排除 EXPIRED/USED', () => {
+    const list = [
+      { id: 1, status: 'AVAILABLE' },
+      { id: 2, status: 'AVAILABLE' },
+      { id: 3, status: 'EXPIRED' },
+      { id: 4, status: 'USED' },
+      { id: 5 }, // 老数据无 status,列表页视同可用
+      { id: 6, status: 'DISABLED' }
+    ]
+    expect(countAvailableCoupons(list)).toBe(3) // id1,id2,id5
+  })
+
+  test('用户12场景:4 AVAILABLE + 1 EXPIRED → 4', () => {
+    const list = [
+      { id: 158, status: 'EXPIRED' },
+      { id: 2, status: 'AVAILABLE' },
+      { id: 3, status: 'AVAILABLE' },
+      { id: 4, status: 'AVAILABLE' },
+      { id: 5, status: 'AVAILABLE' }
+    ]
+    expect(countAvailableCoupons(list)).toBe(4)
+  })
+
+  test('空/异常输入返回 0', () => {
+    expect(countAvailableCoupons(null)).toBe(0)
+    expect(countAvailableCoupons([])).toBe(0)
+    expect(countAvailableCoupons({})).toBe(0)
+  })
+})

+ 126 - 0
cfc-frontend/__tests__/utils/dwellTracker.test.js

@@ -0,0 +1,126 @@
+/**
+ * Tests for cfc-frontend utils/dwellTracker.js
+ *
+ * 覆盖 2026-11-15 `fix(dashboard)` 变更引入的「商品浏览停留时长」埋点行为契约:
+ * 此前 window 内该文件被修改但**零用例覆盖**(见 R213 报告 B-213-1),本文件补齐行为级用例。
+ *
+ * 被验证的行为契约(源自源码注释与实现):
+ *  1. 未调用 start 直接 flush → 不上报(历史 bug:start=0 时把 Date.now() 当停留时长 ≈17 亿秒)
+ *  2. product 缺失或无 id → 不上报
+ *  3. 停留时长 <= 0 → 不上报
+ *  4. 停留时长 > 1800s → 截断为 1800(切后台/锁屏产生超长时长)
+ *  5. 正常停留 → 上报 payload 字段完整(userId/productId/productName/productType/durationSeconds/source)
+ *  6. userId 缺失 → 兜底 0
+ *  7. reportProductDwell 抛异常 → 不向上抛出(不阻断页面卸载)
+ *  8. flush 后计时器复位 → 二次 flush 不重复上报
+ */
+
+describe('utils/dwellTracker.js', () => {
+  let dwell
+  let api
+
+  const PRODUCT = { id: 101, name: '测试商品', productType: 'goods' }
+
+  beforeAll(() => {
+    jest.doMock('@/utils/api', () => ({ reportProductDwell: jest.fn() }))
+    api = require('@/utils/api')
+    dwell = require('@/utils/dwellTracker')
+  })
+
+  beforeEach(() => {
+    api.reportProductDwell.mockClear()
+    global.uni._storage = {}
+    jest.spyOn(Date, 'now').mockReturnValue(1_000_000)
+  })
+
+  afterEach(() => {
+    jest.restoreAllMocks()
+  })
+
+  test('未调用 startProductDwell 直接 flush → 不上报', () => {
+    dwell.flushProductDwell(PRODUCT)
+    expect(api.reportProductDwell).not.toHaveBeenCalled()
+  })
+
+  test('product 缺失或无 id → 不上报', () => {
+    dwell.startProductDwell()
+    dwell.flushProductDwell(null)
+    dwell.flushProductDwell({})
+    dwell.flushProductDwell({ name: '无id' })
+    expect(api.reportProductDwell).not.toHaveBeenCalled()
+  })
+
+  test('停留时长 <= 0 → 不上报', () => {
+    dwell.startProductDwell()
+    dwell.flushProductDwell(PRODUCT) // 同一毫秒
+    expect(api.reportProductDwell).not.toHaveBeenCalled()
+  })
+
+  test('正常停留 5 秒 → 上报完整 payload', () => {
+    global.uni.setStorageSync('userId', 88)
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 5000)
+
+    dwell.flushProductDwell(PRODUCT)
+
+    expect(api.reportProductDwell).toHaveBeenCalledTimes(1)
+    expect(api.reportProductDwell).toHaveBeenCalledWith({
+      userId: 88,
+      productId: 101,
+      productName: '测试商品',
+      productType: 'goods',
+      durationSeconds: 5,
+      source: 'miniprogram'
+    })
+  })
+
+  test('product 缺 name/productType → 兜底空串', () => {
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 3000)
+
+    dwell.flushProductDwell({ id: 7 })
+
+    const payload = api.reportProductDwell.mock.calls[0][0]
+    expect(payload.productName).toBe('')
+    expect(payload.productType).toBe('')
+  })
+
+  test('userId 未登录 → 兜底 0', () => {
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 1000)
+
+    dwell.flushProductDwell(PRODUCT)
+
+    expect(api.reportProductDwell.mock.calls[0][0].userId).toBe(0)
+  })
+
+  test('超长停留(>1800s)→ 截断为 1800', () => {
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 50_000 * 1000) // 50000 秒
+
+    dwell.flushProductDwell(PRODUCT)
+
+    expect(api.reportProductDwell.mock.calls[0][0].durationSeconds).toBe(1800)
+  })
+
+  test('上报抛异常 → 不向上抛出', () => {
+    api.reportProductDwell.mockImplementationOnce(() => {
+      throw new Error('network down')
+    })
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 2000)
+
+    expect(() => dwell.flushProductDwell(PRODUCT)).not.toThrow()
+  })
+
+  test('flush 后计时复位 → 再次 flush 不重复上报', () => {
+    dwell.startProductDwell()
+    Date.now.mockReturnValue(1_000_000 + 4000)
+    dwell.flushProductDwell(PRODUCT)
+    expect(api.reportProductDwell).toHaveBeenCalledTimes(1)
+
+    Date.now.mockReturnValue(1_000_000 + 9000)
+    dwell.flushProductDwell(PRODUCT)
+    expect(api.reportProductDwell).toHaveBeenCalledTimes(1)
+  })
+})

+ 127 - 0
cfc-frontend/__tests__/utils/exerciseTypes.test.js

@@ -0,0 +1,127 @@
+/**
+ * 运动类型统一 + 后台可配置:utils/exerciseTypes.js 契约测试
+ *
+ * 背景:growth/exercise-checkin.vue 与 health/exercise-index.vue 各自写死一套
+ * exerciseTypes,value 分歧(ball vs ball_game),且后台无法配置。
+ * 本测试规定公共模块行为:
+ *   1) 标准并集默认值(全局一套)
+ *   2) 解析后台 sys_config 的 JSON 字符串响应
+ *   3) 历史 value 映射(ball_game → ball),保证老记录 label 不丢
+ *   4) 拉取失败/空值时回退默认(离线可用)
+ *   5) 加载后写入缓存复用
+ */
+describe('exerciseTypes 公共模块', () => {
+  let mod
+
+  beforeAll(() => {
+    mod = require('@/utils/exerciseTypes')
+  })
+
+  test('默认值为标准并集(8 项,含 ball/strength/gymnastics,不含 ball_game)', () => {
+    const defs = mod.DEFAULT_EXERCISE_TYPES
+    const values = defs.map((x) => x.value)
+    expect(values).toEqual([
+      'running', 'swimming', 'cycling', 'jump_rope',
+      'ball', 'strength', 'gymnastics', 'other'
+    ])
+    expect(values).not.toContain('ball_game')
+    defs.forEach((x) => expect(x.label).toBeTruthy())
+  })
+
+  test('normalizeExerciseTypes 解析 JSON 数组字符串(后台 sys_config 的 data 字段)', () => {
+    const raw = JSON.stringify([
+      { label: '跑步', value: 'running' },
+      { label: '瑜伽', value: 'yoga' }
+    ])
+    expect(mod.normalizeExerciseTypes(raw).map((x) => x.value)).toEqual(['running', 'yoga'])
+  })
+
+  test('normalizeExerciseTypes 接受已解析的数组', () => {
+    expect(mod.normalizeExerciseTypes([{ label: '骑行', value: 'cycling' }])[0].label).toBe('骑行')
+  })
+
+  test('normalizeExerciseTypes 空值 / 非法 JSON / 空数组 → 回退默认', () => {
+    expect(mod.normalizeExerciseTypes(null).length).toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+    expect(mod.normalizeExerciseTypes('').length).toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+    expect(mod.normalizeExerciseTypes('{bad json').length).toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+    expect(mod.normalizeExerciseTypes('[]').length).toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+    expect(mod.normalizeExerciseTypes([{ label: 'x' }]).length).toBe(mod.DEFAULT_EXERCISE_TYPES.length) // 缺 value
+  })
+
+  test('normalizeExerciseTypes 过滤 item.value 为空的脏数据', () => {
+    const raw = JSON.stringify([
+      { label: '跑步', value: 'running' },
+      { label: '', value: '  ' }
+    ])
+    expect(mod.normalizeExerciseTypes(raw).map((x) => x.value)).toEqual(['running'])
+  })
+
+  test('历史 value 映射:ball_game 归一为 ball', () => {
+    expect(mod.normalizeExerciseValue('ball_game')).toBe('ball')
+    expect(mod.normalizeExerciseValue('ball')).toBe('ball')
+    expect(mod.normalizeExerciseValue('running')).toBe('running')
+  })
+
+  test('resolveExerciseTypeLabel 用历史 value 也能取到 label', () => {
+    const types = mod.DEFAULT_EXERCISE_TYPES
+    expect(mod.resolveExerciseTypeLabel('ball_game', types)).toBe('球类')
+    expect(mod.resolveExerciseTypeLabel('ball', types)).toBe('球类')
+    expect(mod.resolveExerciseTypeLabel('strength', types)).toBe('力量训练')
+    expect(mod.resolveExerciseTypeLabel('unknown_x', types)).toBe('其他')
+  })
+
+  test('extractFromPublicConfigResp:解包 {code:200,data:"<json>"}', () => {
+    const resp = { code: 200, data: JSON.stringify([{ label: '瑜伽', value: 'yoga' }]) }
+    expect(mod.extractFromPublicConfigResp(resp).map((x) => x.value)).toEqual(['yoga'])
+  })
+
+  test('extractFromPublicConfigResp:code != 200 / 无 data → 默认', () => {
+    expect(mod.extractFromPublicConfigResp({ code: 500, data: '[]' }).length)
+      .toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+    expect(mod.extractFromPublicConfigResp(null).length)
+      .toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+  })
+
+  test('loadExerciseTypes:fetcher 成功 → 返回解析结果并写缓存', async () => {
+    const fetcher = jest.fn().mockResolvedValue({
+      code: 200,
+      data: JSON.stringify([{ label: '瑜伽', value: 'yoga' }])
+    })
+    const store = {}
+    const result = await mod.loadExerciseTypes(fetcher, store)
+    expect(result.map((x) => x.value)).toEqual(['yoga'])
+    expect(fetcher).toHaveBeenCalledWith('exercise_types')
+    expect(store[mod.CACHE_KEY]).toBeTruthy()
+  })
+
+  test('loadExerciseTypes:fetcher 失败 → 回退缓存/默认,不抛错', async () => {
+    const fetcher = jest.fn().mockRejectedValue(new Error('network'))
+    const result = await mod.loadExerciseTypes(fetcher, {})
+    expect(result.length).toBe(mod.DEFAULT_EXERCISE_TYPES.length)
+  })
+
+  test('loadExerciseTypes:已有缓存且 fetcher 失败 → 用缓存', async () => {
+    const cached = JSON.stringify([{ label: '旧配置', value: 'legacy_cached' }])
+    const fetcher = jest.fn().mockRejectedValue(new Error('network'))
+    const result = await mod.loadExerciseTypes(fetcher, { [mod.CACHE_KEY]: cached })
+    expect(result.map((x) => x.value)).toEqual(['legacy_cached'])
+  })
+
+  test('loadExerciseTypes:store 支持 getItem/setItem 适配器(uni storage)', async () => {
+    const mem = {}
+    const store = {
+      getItem: (k) => mem[k],
+      setItem: (k, v) => { mem[k] = v }
+    }
+    const fetcher = jest.fn().mockResolvedValue({
+      code: 200, data: JSON.stringify([{ label: '瑜伽', value: 'yoga' }])
+    })
+    const result = await mod.loadExerciseTypes(fetcher, store)
+    expect(result[0].value).toBe('yoga')
+    expect(mem[mod.CACHE_KEY]).toBeTruthy()
+    // 第二次 fetcher 失败 → 从 getItem 缓存读回
+    const failFetcher = jest.fn().mockRejectedValue(new Error('offline'))
+    const result2 = await mod.loadExerciseTypes(failFetcher, store)
+    expect(result2[0].value).toBe('yoga')
+  })
+})

+ 122 - 0
cfc-frontend/__tests__/utils/fontScale.test.js

@@ -0,0 +1,122 @@
+/**
+ * fontScale 工具函数单元测试
+ * 覆盖:微信系统字号读取 / 用户设置优先级 / 值域钳制 / storage 互斥 / mp-html tag-style 生成
+ */
+import {
+  readSystemFontScale,
+  getUserFontScale,
+  setUserFontScale,
+  getFontScale,
+  syncFontScale,
+  buildContentTagStyle
+} from '@/utils/fontScale.js'
+
+// 每个用例前清空 mock storage,并给出可控的 getAppBaseInfo
+beforeEach(() => {
+  global.uni._storage = {}
+  global.uni.getAppBaseInfo = jest.fn(() => ({}))
+})
+
+describe('readSystemFontScale', () => {
+  it('优先返回 fontSizeScaleFactor', () => {
+    global.uni.getAppBaseInfo = jest.fn(() => ({ fontSizeScaleFactor: 1.25, fontSizeSetting: 20 }))
+    expect(readSystemFontScale()).toBe(1.25)
+  })
+
+  it('无 factor 时用 fontSizeSetting / 16 兜底', () => {
+    global.uni.getAppBaseInfo = jest.fn(() => ({ fontSizeSetting: 20 }))
+    expect(readSystemFontScale()).toBeCloseTo(1.25, 5)
+  })
+
+  it('两者都缺省时返回 1', () => {
+    expect(readSystemFontScale()).toBe(1)
+  })
+
+  it('API 抛异常时返回 1', () => {
+    global.uni.getAppBaseInfo = jest.fn(() => { throw new Error('low lib') })
+    expect(readSystemFontScale()).toBe(1)
+  })
+})
+
+describe('setUserFontScale / getUserFontScale', () => {
+  it('设置后能读回,且保留两位小数', () => {
+    setUserFontScale(1.1234)
+    expect(getUserFontScale()).toBe(1.12)
+  })
+
+  it('超出上界钳制到 1.7', () => {
+    expect(setUserFontScale(5)).toBe(1.7)
+  })
+
+  it('低于下界钳制到 0.9', () => {
+    expect(setUserFontScale(0.1)).toBe(0.9)
+  })
+
+  it('未设置时返回 null', () => {
+    expect(getUserFontScale()).toBeNull()
+  })
+
+  it('非法值(0 / NaN)返回 null', () => {
+    global.uni.setStorageSync('userFontScale', 0)
+    expect(getUserFontScale()).toBeNull()
+    global.uni.setStorageSync('userFontScale', NaN)
+    expect(getUserFontScale()).toBeNull()
+  })
+})
+
+describe('getFontScale 优先级', () => {
+  it('用户手动设置优先于系统字号', () => {
+    global.uni.setStorageSync('fontSizeScaleFactor', 1.5)
+    setUserFontScale(1)
+    expect(getFontScale()).toBe(1)
+  })
+
+  it('用户未设置时使用缓存中的系统值', () => {
+    global.uni.setStorageSync('fontSizeScaleFactor', 1.3)
+    expect(getFontScale()).toBe(1.3)
+  })
+
+  it('缓存也没有时实时读系统', () => {
+    global.uni.getAppBaseInfo = jest.fn(() => ({ fontSizeScaleFactor: 1.4 }))
+    expect(getFontScale()).toBe(1.4)
+  })
+
+  it('全部缺失时返回 1', () => {
+    expect(getFontScale()).toBe(1)
+  })
+})
+
+describe('syncFontScale', () => {
+  it('用户未设置时把系统值写入缓存', () => {
+    global.uni.getAppBaseInfo = jest.fn(() => ({ fontSizeScaleFactor: 1.6 }))
+    syncFontScale()
+    expect(global.uni._storage.fontSizeScaleFactor).toBe(1.6)
+  })
+
+  it('用户已设置时不覆盖缓存', () => {
+    setUserFontScale(1.2)
+    global.uni.setStorageSync('fontSizeScaleFactor', 1.6)
+    global.uni.getAppBaseInfo = jest.fn(() => ({ fontSizeScaleFactor: 1.6 }))
+    syncFontScale()
+    expect(global.uni._storage.fontSizeScaleFactor).toBe(1.6)
+  })
+})
+
+describe('buildContentTagStyle', () => {
+  it('按 scale 放大正文字号(rpx)', () => {
+    const style = buildContentTagStyle(32, 1.25)
+    expect(style.p).toBe('font-size:40rpx;color:#444;line-height:1.8;')
+    expect(style.div).toBe('font-size:40rpx;color:#444;line-height:1.8;')
+    expect(style.section).toBe('font-size:40rpx;color:#444;line-height:1.8;')
+    expect(style.li).toBe('font-size:40rpx;color:#444;line-height:1.8;')
+  })
+
+  it('scale 缺省按 1 处理', () => {
+    expect(buildContentTagStyle(28).p).toBe('font-size:28rpx;color:#444;line-height:1.8;')
+  })
+
+  it('包含常用块级标签', () => {
+    const keys = Object.keys(buildContentTagStyle(28, 1))
+    expect(keys).toEqual(expect.arrayContaining(['p', 'div', 'section', 'li', 'blockquote']))
+  })
+})

+ 213 - 0
cfc-frontend/__tests__/utils/format.test.js

@@ -0,0 +1,213 @@
+/**
+ * Tests for cfc-frontend utils/format.js
+ *
+ * Tests the price/rate/score formatting utilities.
+ * These are pure functions - no uni mock needed.
+ */
+
+describe('format.js', () => {
+  let format
+
+  beforeAll(() => {
+    format = require('@/utils/format')
+  })
+
+  // --------------- formatPrice ---------------
+
+  describe('formatPrice', () => {
+    test('converts cents to yuan with 2 decimals', () => {
+      expect(format.formatPrice(1250)).toBe('12.50')
+      expect(format.formatPrice(0)).toBe('0.00')
+      expect(format.formatPrice(999)).toBe('9.99')
+      expect(format.formatPrice(10000)).toBe('100.00')
+    })
+
+    test('handles null and undefined', () => {
+      expect(format.formatPrice(null)).toBeNull()
+      expect(format.formatPrice(undefined)).toBeNull()
+    })
+
+    test('handles zero cents', () => {
+      expect(format.formatPrice(0)).toBe('0.00')
+    })
+  })
+
+  // --------------- formatPriceWithSymbol ---------------
+
+  describe('formatPriceWithSymbol', () => {
+    test('adds ¥ prefix and 2 decimals', () => {
+      expect(format.formatPriceWithSymbol(1250)).toBe('¥12.50')
+      expect(format.formatPriceWithSymbol(0)).toBe('¥0.00')
+      expect(format.formatPriceWithSymbol(999)).toBe('¥9.99')
+    })
+
+    test('returns login message for null/undefined', () => {
+      expect(format.formatPriceWithSymbol(null)).toBe('登录查看')
+      expect(format.formatPriceWithSymbol(undefined)).toBe('登录查看')
+    })
+  })
+
+  // --------------- formatRate ---------------
+
+  describe('formatRate', () => {
+    test('converts permillage to percentage string', () => {
+      expect(format.formatRate(235)).toBe('23.5%')
+      expect(format.formatRate(0)).toBe('0%')
+      expect(format.formatRate(1000)).toBe('100%')
+      expect(format.formatRate(5)).toBe('0.5%')
+    })
+
+    test('returns -- for null/undefined', () => {
+      expect(format.formatRate(null)).toBe('--')
+      expect(format.formatRate(undefined)).toBe('--')
+    })
+  })
+
+  // --------------- formatScore ---------------
+
+  describe('formatScore', () => {
+    test('converts percent-scale to fixed decimal', () => {
+      expect(format.formatScore(450)).toBe('4.5')
+      expect(format.formatScore(0)).toBe('0.0')
+      expect(format.formatScore(1000)).toBe('10.0')
+    })
+
+    test('uses default 1 decimal place', () => {
+      expect(format.formatScore(450)).toBe('4.5')
+    })
+
+    test('supports custom decimal places', () => {
+      expect(format.formatScore(450, 2)).toBe('4.50')
+      expect(format.formatScore(450, 0)).toBe('5')
+    })
+
+    test('returns -- for null/undefined', () => {
+      expect(format.formatScore(null)).toBe('--')
+      expect(format.formatScore(undefined)).toBe('--')
+    })
+  })
+
+  // --------------- parseDate ---------------
+
+  describe('parseDate', () => {
+    // 断言使用本地时间字段(getFullYear/getMonth/getDate/...),
+    // 避免 Node(V8)对纯日期字符串按 UTC 解析带来的时区差异。
+    const ymd = (d) => {
+      return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
+    }
+
+    test('parses MySQL DATETIME with space separator "yyyy-MM-dd HH:mm"', () => {
+      // iOS 原生 new Date() 无法解析空格分隔格式,parseDate 必须归一化成功
+      const d = format.parseDate('2026-08-22 14:00')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+      expect(d.getHours()).toBe(14)
+      expect(d.getMinutes()).toBe(0)
+    })
+
+    test('parses MySQL DATETIME with seconds', () => {
+      const d = format.parseDate('2026-08-22 14:00:30')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+      expect(d.getSeconds()).toBe(30)
+    })
+
+    test('parses Java "EEE MMM dd HH:mm:ss zzz yyyy" (CST) format', () => {
+      // 后端 Java 常见格式,iOS 原生无法解析
+      const d = format.parseDate('Sat Aug 22 14:00:00 CST 2026')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+      expect(d.getHours()).toBe(14)
+    })
+
+    test('parses slash-separated "yyyy/MM/dd"', () => {
+      const d = format.parseDate('2026/08/22')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+    })
+
+    test('parses ISO 8601 "yyyy-MM-ddTHH:mm:ss"', () => {
+      const d = format.parseDate('2026-08-22T14:00:00')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+    })
+
+    test('parses plain date "yyyy-MM-dd"', () => {
+      const d = format.parseDate('2026-08-22')
+      expect(d).not.toBeNull()
+      expect(ymd(d)).toBe('2026-8-22')
+    })
+
+    test('parses numeric timestamp', () => {
+      const d = format.parseDate(1780000000000)
+      expect(d).not.toBeNull()
+      expect(d.getTime()).toBe(1780000000000)
+    })
+
+    test('returns same Date object when given a Date', () => {
+      const date = new Date()
+      expect(format.parseDate(date)).toBe(date)
+    })
+
+    test('returns null for null/undefined/empty string', () => {
+      expect(format.parseDate(null)).toBeNull()
+      expect(format.parseDate(undefined)).toBeNull()
+      expect(format.parseDate('')).toBeNull()
+    })
+
+    test('returns null for unparseable string', () => {
+      expect(format.parseDate('not-a-date')).toBeNull()
+      expect(format.parseDate('2026-13-45')).toBeNull()
+    })
+  })
+  // --------------- recordDateOf ---------------
+  // 业务日期字段优先:判定"今日是否打卡"应看业务日期(recordDate/startTime/sleepTime/checkinDate),
+  // 而非 createdAt。createdAt 是记录写入时间(补打时=今天,业务日期=补打日),且后端 Jackson 输出的
+  // createdAt 形如 "2026-10-30T13:13:32.000+08:00"(带毫秒+时区偏移),iOS JavaScriptCore 无法解析
+  // (parseDate 注释:只支持不带毫秒的 yyyy-MM-ddTHH:mm:ss+HH:mm)。recordDate/checkinDate 为纯日期,
+  // 所有环境都能解析。
+  describe('recordDateOf', () => {
+    test('prefers recordDate over createdAt (补打:recordDate=昨天, createdAt=今天 → 昨天)', () => {
+      // 补打场景:recordDate 是实际用餐日(昨天),createdAt 是记录创建时间(今天)。
+      // 若 createdAt 优先会误判"今天已打卡";正确应取业务日期 recordDate。
+      expect(format.recordDateOf({
+        recordDate: '2026-10-29',
+        createdAt: '2026-10-30T13:13:32.000+08:00'
+      })).toBe('2026-10-29')
+    })
+
+    test('falls back to createdAt when business date field missing', () => {
+      expect(format.recordDateOf({
+        createdAt: '2026-10-30T13:13:32.000+08:00'
+      })).toBe('2026-10-30')
+    })
+
+    test('prefers startTime/sleepTime/checkinDate (运动/睡眠/心情业务字段优先)', () => {
+      expect(format.recordDateOf({
+        startTime: '2026-10-30T06:00:00.000+08:00',
+        createdAt: '2026-10-31T00:00:00.000+08:00'
+      })).toBe('2026-10-30')
+      expect(format.recordDateOf({
+        sleepTime: '2026-10-30T22:00:00.000+08:00',
+        createdAt: '2026-10-31T00:00:00.000+08:00'
+      })).toBe('2026-10-30')
+      expect(format.recordDateOf({
+        checkinDate: '2026-10-30',
+        createdAt: '2026-10-31T00:00:00.000+08:00'
+      })).toBe('2026-10-30')
+    })
+
+    test('returns empty string for null/empty record', () => {
+      expect(format.recordDateOf(null)).toBe('')
+      expect(format.recordDateOf({})).toBe('')
+    })
+
+    test('parses ISO 8601 with milliseconds + timezone offset (后端 Jackson 默认输出)', () => {
+      // 后端 Date 序列化真实格式:2026-10-30T13:13:32.000+08:00。
+      // recordDateOf 对纯 createdAt 也应能正确解析出日期。
+      expect(format.recordDateOf({
+        createdAt: '2026-10-30T13:13:32.000+08:00'
+      })).toBe('2026-10-30')
+    })
+  })
+})

+ 46 - 0
cfc-frontend/__tests__/utils/image-picker.test.js

@@ -0,0 +1,46 @@
+import { compressPickedImages } from '../../utils/image-picker'
+
+function run(paths, files) {
+  return new Promise(resolve => {
+    compressPickedImages(paths, files, resolve)
+  })
+}
+
+describe('image-picker 上传前压缩', () => {
+  afterEach(() => {
+    delete global.uni
+  })
+
+  it('小于 800KB 的图片不压缩', async () => {
+    global.uni = { compressImage: jest.fn() }
+    const result = await run(['a.jpg'], [{ size: 100 * 1024 }])
+    expect(result).toEqual(['a.jpg'])
+    expect(global.uni.compressImage).not.toHaveBeenCalled()
+  })
+
+  it('大图压缩成功时返回压缩后的临时路径', async () => {
+    global.uni = {
+      compressImage: jest.fn(opts => opts.success({ tempFilePath: 'a-compressed.jpg' }))
+    }
+    const result = await run(['a.jpg'], [{ size: 6 * 1024 * 1024 }])
+    expect(result).toEqual(['a-compressed.jpg'])
+    expect(global.uni.compressImage).toHaveBeenCalledWith(expect.objectContaining({
+      src: 'a.jpg',
+      quality: 75
+    }))
+  })
+
+  it('压缩失败时回退原图', async () => {
+    global.uni = {
+      compressImage: jest.fn(opts => opts.fail(new Error('compress failed')))
+    }
+    const result = await run(['a.jpg'], [{ size: 6 * 1024 * 1024 }])
+    expect(result).toEqual(['a.jpg'])
+  })
+
+  it('未知大小或缺少压缩 API 时不影响选择结果', async () => {
+    global.uni = {}
+    const result = await run(['a.jpg', 'b.png'], [{}, {}])
+    expect(result).toEqual(['a.jpg', 'b.png'])
+  })
+})

+ 65 - 0
cfc-frontend/__tests__/utils/indicator-change.test.js

@@ -0,0 +1,65 @@
+/**
+ * 指标变化规则纯函数单测
+ * 规则来源:design.md §8 变化颜色与箭头规则表
+ */
+import * as ic from '@/utils/indicator-change'
+
+describe('indicator-change 变化规则', () => {
+  describe('resolveChangeStyle(goodDirection, movement)', () => {
+    test('higher_is_better + up → 改善/绿 ↑', () => {
+      const s = ic.resolveChangeStyle('higher_is_better', 'up')
+      expect(s.trendLabel).toBe('改善')
+      expect(s.cssClass).toBe('impr-up')
+      expect(s.arrow).toBe('↑')
+    })
+    test('higher_is_better + down → 恶化/红 ↓', () => {
+      const s = ic.resolveChangeStyle('higher_is_better', 'down')
+      expect(s.trendLabel).toBe('恶化')
+      expect(s.cssClass).toBe('worst-down')
+      expect(s.arrow).toBe('↓')
+    })
+    test('lower_is_better + up → 恶化/红 ↑ (如炎症水平上升)', () => {
+      const s = ic.resolveChangeStyle('lower_is_better', 'up')
+      expect(s.trendLabel).toBe('恶化')
+      expect(s.cssClass).toBe('worst-up')
+      expect(s.arrow).toBe('↑')
+    })
+    test('lower_is_better + down → 改善/绿 ↓ (如炎症水平下降)', () => {
+      const s = ic.resolveChangeStyle('lower_is_better', 'down')
+      expect(s.trendLabel).toBe('改善')
+      expect(s.cssClass).toBe('impr-down')
+      expect(s.arrow).toBe('↓')
+    })
+    test('neutral + up/down → 中性/灰', () => {
+      const up = ic.resolveChangeStyle('neutral', 'up')
+      const down = ic.resolveChangeStyle('neutral', 'down')
+      expect(up.trendLabel).toBe('中性')
+      expect(up.cssClass).toBe('neutral-up')
+      expect(down.cssClass).toBe('neutral-down')
+    })
+    test('flat → 无变化/灰 →', () => {
+      const s = ic.resolveChangeStyle('higher_is_better', 'flat')
+      expect(s.trendLabel).toBe('中性')
+      expect(s.cssClass).toBe('flat')
+      expect(s.arrow).toBe('→')
+    })
+    test('未知 goodDirection 兜底为中性', () => {
+      const s = ic.resolveChangeStyle('unknown_direction', 'up')
+      expect(s.cssClass).toBe('neutral-up')
+    })
+  })
+
+  describe('formatDelta(delta, deltaPct)', () => {
+    test('正 delta 显示 + 并带百分比', () => {
+      // PRD §6.4 有效数字:|v|<10 → 2 位小数
+      expect(ic.formatDelta(2, 100)).toBe('+2.00 (+100%)')
+    })
+    test('负 delta 显示 -', () => {
+      expect(ic.formatDelta(-1.5, -30)).toBe('-1.50 (-30%)')
+    })
+    test('null 安全', () => {
+      expect(ic.formatDelta(null, null)).toBe('--')
+      expect(ic.formatDelta(0, 0)).toBe('0.00 (0%)')
+    })
+  })
+})

+ 247 - 0
cfc-frontend/__tests__/utils/indicator-favorite.test.js

@@ -0,0 +1,247 @@
+/**
+ * utils/indicator-favorite 关注指标收藏单测(T04 方案A:后端持久化 + 本地降级)
+ * 规则来源:design §8.1 / §8.3(F4)、§11.3 T04
+ * 隔离维度:userId × familyId × memberId × sourceType → 不同 key,防串号
+ * 后端契约:/api/indicator/favorite/{toggle,list,remove},见
+ *          specs/2026-10-30-indicator-favorite-backend-design.md §4
+ */
+jest.mock('@/utils/api.js', () => ({
+  listIndicatorFavorites: jest.fn(),
+  toggleIndicatorFavorite: jest.fn(),
+  removeIndicatorFavorite: jest.fn()
+}))
+
+import { buildFavoriteKey, readFavorites, writeFavorites, toggleFavorite, removeFavorite } from '@/utils/indicator-favorite'
+import { listIndicatorFavorites, toggleIndicatorFavorite, removeIndicatorFavorite } from '@/utils/api'
+
+/** 后端成功响应包装(api.js 的 request() resolve 的是整个 Result) */
+function ok(data) {
+  return Promise.resolve({ code: 200, message: 'success', data: data })
+}
+
+const SCOPE = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+
+describe('indicator-favorite 关注指标收藏(方案A:后端持久化 + 本地降级)', () => {
+  beforeEach(function() {
+    jest.clearAllMocks()
+    // 每个用例前清空 storage,避免用例间污染
+    if (global.uni && global.uni._storage) {
+      Object.keys(global.uni._storage).filter(function(k) { return k.indexOf('cfc:indicator:fav:') === 0 }).forEach(function(k) { delete global.uni._storage[k] })
+    }
+  })
+
+  describe('buildFavoriteKey', () => {
+    test('默认维度全部填充占位符', () => {
+      var key = buildFavoriteKey({})
+      expect(key).toMatch(/cfc:indicator:fav:anon:nofamily:nomember:all$/)
+    })
+    test('全维度隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'gut_flora' })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 4, sourceType: 'gut_flora' })
+      expect(k2).not.toBe(k1)
+      expect(k2).toContain(':4:')
+    })
+    test('sourceType 隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'gut_flora' })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'food_recommend' })
+      expect(k2).not.toBe(k1)
+    })
+    test('不同 familyId 隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3 })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 5, memberId: 3 })
+      expect(k2).not.toBe(k1)
+    })
+  })
+
+  describe('readFavorites(后端优先)', () => {
+    test('后端返回 definitionIds → 原样返回并回写本地缓存', async () => {
+      listIndicatorFavorites.mockReturnValue(ok({ memberId: 1, sourceType: 'gut_flora', definitionIds: [456, 789] }))
+
+      var ids = await readFavorites(SCOPE)
+
+      expect(ids).toEqual([456, 789])
+      expect(listIndicatorFavorites).toHaveBeenCalledWith({ memberId: 1, sourceType: 'gut_flora' })
+      // 回写本地:下次离线可降级读
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([456, 789])
+    })
+
+    test('后端返回空集合 → []', async () => {
+      listIndicatorFavorites.mockReturnValue(ok({ memberId: 1, sourceType: 'gut_flora', definitionIds: [] }))
+
+      expect(await readFavorites(SCOPE)).toEqual([])
+    })
+
+    test('后端 reject → 降级读本地 Storage', async () => {
+      writeFavorites(SCOPE, [101, 102])
+      listIndicatorFavorites.mockReturnValue(Promise.reject({ code: 500, message: 'boom' }))
+
+      expect(await readFavorites(SCOPE)).toEqual([101, 102])
+    })
+
+    test('后端返回无 data(如 401 未登录)→ 降级读本地', async () => {
+      writeFavorites(SCOPE, [101])
+      listIndicatorFavorites.mockReturnValue(Promise.resolve({ code: 401, message: '请先登录', data: null }))
+
+      expect(await readFavorites(SCOPE)).toEqual([101])
+    })
+
+    test('本地无缓存且后端不可用 → []', async () => {
+      listIndicatorFavorites.mockReturnValue(Promise.reject(new Error('network')))
+
+      expect(await readFavorites(SCOPE)).toEqual([])
+    })
+
+    test('缺 memberId/sourceType(未登录/无视角)→ 不调后端,直接读本地', async () => {
+      writeFavorites({}, [101])
+
+      expect(await readFavorites({})).toEqual([101])
+      expect(listIndicatorFavorites).not.toHaveBeenCalled()
+    })
+
+    test('非法本地数据容错返回 []', async () => {
+      var key = buildFavoriteKey(SCOPE)
+      listIndicatorFavorites.mockReturnValue(Promise.reject(new Error('network')))
+      global.uni._storage[key] = 'not-a-json'
+      expect(await readFavorites(SCOPE)).toEqual([])
+      global.uni._storage[key] = 123
+      expect(await readFavorites(SCOPE)).toEqual([])
+    })
+
+    test('跨 scope 隔离:不同 memberId 读到各自缓存', async () => {
+      var s2 = { userId: 1, familyId: 1, memberId: 2, sourceType: 'gut_flora' }
+      var s3 = { userId: 1, familyId: 1, memberId: 3, sourceType: 'gut_flora' }
+      writeFavorites(s2, [101])
+      listIndicatorFavorites.mockReturnValue(Promise.reject(new Error('network')))
+
+      expect(await readFavorites(s2)).toEqual([101])
+      expect(await readFavorites(s3)).toEqual([])
+    })
+  })
+
+  describe('toggleFavorite(异步 + 乐观更新 + 失败回滚)', () => {
+    test('首次收藏 → 调后端,added=true,本地写入', async () => {
+      toggleIndicatorFavorite.mockReturnValue(ok({ definitionId: 101, added: true }))
+
+      var res = await toggleFavorite(SCOPE, 101)
+
+      expect(res.added).toBe(true)
+      expect(res.ids).toEqual([101])
+      expect(toggleIndicatorFavorite).toHaveBeenCalledWith({ memberId: 1, sourceType: 'gut_flora', definitionId: 101 })
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([101])
+    })
+
+    test('已收藏再点 → added=false,从本地移除', async () => {
+      writeFavorites(SCOPE, [101])
+      toggleIndicatorFavorite.mockReturnValue(ok({ definitionId: 101, added: false }))
+
+      var res = await toggleFavorite(SCOPE, 101)
+
+      expect(res.added).toBe(false)
+      expect(res.ids).toEqual([])
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([])
+    })
+
+    test('后端失败 → 回滚本地,added=false', async () => {
+      writeFavorites(SCOPE, [101])
+      toggleIndicatorFavorite.mockReturnValue(Promise.reject({ code: 500, message: 'boom' }))
+
+      var res = await toggleFavorite(SCOPE, 102)
+
+      expect(res.added).toBe(false)
+      expect(res.ids).toEqual([101]) // 回滚到调用前
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([101])
+    })
+
+    test('后端失败且原本为空 → 回滚为空', async () => {
+      toggleIndicatorFavorite.mockReturnValue(Promise.reject(new Error('network')))
+
+      var res = await toggleFavorite(SCOPE, 101)
+
+      expect(res.ids).toEqual([])
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([])
+    })
+
+    test('后端返回 added=false(服务端已有该收藏)→ 本地缓存同步为未收藏', async () => {
+      // 本地缓存过期(空),但服务端判定「已存在→删除」
+      toggleIndicatorFavorite.mockReturnValue(ok({ definitionId: 101, added: false }))
+
+      var res = await toggleFavorite(SCOPE, 101)
+
+      expect(res.added).toBe(false)
+      expect(res.ids).toEqual([])
+    })
+
+    test('定义 id 非法(NaN)→ 不改变存储、不调后端', async () => {
+      writeFavorites(SCOPE, [101])
+
+      var res = await toggleFavorite(SCOPE, 'not-a-number')
+
+      expect(res.ids).toEqual([101])
+      expect(res.added).toBe(false)
+      expect(toggleIndicatorFavorite).not.toHaveBeenCalled()
+    })
+
+    test('缺 memberId(未登录)→ 本地模式,不调后端', async () => {
+      var res = await toggleFavorite({}, 101)
+
+      expect(res.added).toBe(true)
+      expect(res.ids).toEqual([101])
+      expect(toggleIndicatorFavorite).not.toHaveBeenCalled()
+    })
+
+    test('跨 sourceType 收藏隔离', async () => {
+      var s2 = { userId: 1, familyId: 1, memberId: 1, sourceType: 'food_recommend' }
+      toggleIndicatorFavorite.mockReturnValue(ok({ definitionId: 101, added: true }))
+
+      await toggleFavorite(SCOPE, 101)
+
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([101])
+      expect(global.uni._storage[buildFavoriteKey(s2)]).toBeUndefined()
+      expect(await readFavorites(s2)).toEqual([])
+    })
+  })
+
+  describe('removeFavorite(显式删除,幂等)', () => {
+    test('移除已收藏 → removed=true,本地删除', async () => {
+      writeFavorites(SCOPE, [101, 102])
+      removeIndicatorFavorite.mockReturnValue(ok({ definitionId: 101, removed: true }))
+
+      var res = await removeFavorite(SCOPE, 101)
+
+      expect(res.removed).toBe(true)
+      expect(res.ids).toEqual([102])
+      expect(removeIndicatorFavorite).toHaveBeenCalledWith({ memberId: 1, sourceType: 'gut_flora', definitionId: 101 })
+    })
+
+    test('移除不存在的项(后端幂等)→ removed=true,本地不变', async () => {
+      writeFavorites(SCOPE, [102])
+      removeIndicatorFavorite.mockReturnValue(ok({ definitionId: 999, removed: true }))
+
+      var res = await removeFavorite(SCOPE, 999)
+
+      expect(res.removed).toBe(true)
+      expect(res.ids).toEqual([102])
+    })
+
+    test('后端失败 → 回滚本地,removed=false', async () => {
+      writeFavorites(SCOPE, [101])
+      removeIndicatorFavorite.mockReturnValue(Promise.reject(new Error('network')))
+
+      var res = await removeFavorite(SCOPE, 101)
+
+      expect(res.removed).toBe(false)
+      expect(res.ids).toEqual([101])
+      expect(global.uni._storage[buildFavoriteKey(SCOPE)]).toEqual([101])
+    })
+
+    test('定义 id 非法 → 不调后端', async () => {
+      writeFavorites(SCOPE, [101])
+
+      var res = await removeFavorite(SCOPE, 'x')
+
+      expect(res.removed).toBe(false)
+      expect(res.ids).toEqual([101])
+      expect(removeIndicatorFavorite).not.toHaveBeenCalled()
+    })
+  })
+})

+ 76 - 0
cfc-frontend/__tests__/utils/memberNormalize.resolveCheckin.test.js

@@ -0,0 +1,76 @@
+/**
+ * Tests for cfc-frontend utils/memberNormalize.js — resolveCheckinMemberId
+ *
+ * 背景:三个健康打卡页(diet/exercise/sleep-checkin)onLoad 里
+ *   `if (role !== 'child') { memberId = options.memberId || currentMemberId || null }`
+ *   与首页 growth-main 的 `currentChildId || currentMemberId` 解析不一致:
+ *   1) role==='child' 时 memberId 恒为 null(打卡页根本拿不到成员)
+ *   2) parent 角色缺 currentChildId 兜底
+ *   导致:无当日未完成任务(URL 不带 memberId)+ currentMemberId 为空时,
+ *   提交被 `if (!memberId)` 拦截提示"成员ID无效"。
+ *
+ * 本测试规定 resolveCheckinMemberId 的统一解析行为(与首页 growth-main 对齐):
+ *   options.memberId > currentChildId > currentMemberId > null
+ *   不再受 role 限制。
+ *
+ * ⚠️ 2026-12 修复:明确【不再回退 userId】。userId=users.id,memberId=family_members.id,
+ *   二者是两套身份键;后端按 member_id 落库,若以 userId 兜底传给 member_id 会把
+ *   users.id 错位当成 family_members.id,数字相同即写错成员档案。
+ *   因此解析不到 memberId 时返回 null,调用方不携带 memberId 提交,
+ *   交由后端 JWT currentMemberId(family_members.id)兜底。
+ */
+
+describe('resolveCheckinMemberId', () => {
+  let normalize
+
+  beforeAll(() => {
+    normalize = require('@/utils/memberNormalize')
+  })
+
+  test('URL 参数 options.memberId 优先(首页 tile 带 taskId 进入)', () => {
+    expect(normalize.resolveCheckinMemberId(
+      { memberId: '21', taskId: '4040' },
+      { currentChildId: '10', currentMemberId: '9', userId: '12' }
+    )).toBe('21')
+  })
+
+  test('无 URL 参数时回退 currentChildId(parent 切到孩子视角)', () => {
+    expect(normalize.resolveCheckinMemberId(
+      {},
+      { currentChildId: '21', currentMemberId: '', userId: '12' }
+    )).toBe('21')
+  })
+
+  test('再回退 currentMemberId', () => {
+    expect(normalize.resolveCheckinMemberId(
+      {},
+      { currentChildId: '', currentMemberId: '21', userId: '12' }
+    )).toBe('21')
+  })
+
+  test('不再回退 userId(users.id 非 family_members.id,防错位写档案)', () => {
+    expect(normalize.resolveCheckinMemberId(
+      {},
+      { currentChildId: '', currentMemberId: '', userId: '12' }
+    )).toBeNull()
+  })
+
+  test('child 角色不返回 null(修复原 if(role!=="child") 恒 null 缺陷)', () => {
+    expect(normalize.resolveCheckinMemberId(
+      {},
+      { currentRole: 'child', currentChildId: '21', currentMemberId: '', userId: '12' }
+    )).toBe('21')
+  })
+
+  test('child 角色无 currentChildId / currentMemberId 时返回 null(后端 JWT 兜底)', () => {
+    expect(normalize.resolveCheckinMemberId(
+      {},
+      { currentRole: 'child', currentChildId: '', currentMemberId: '', userId: '12' }
+    )).toBeNull()
+  })
+
+  test('全部为空返回 null(保持提交拦截语义,由后端/调用方给出明确提示)', () => {
+    expect(normalize.resolveCheckinMemberId({}, {})).toBeNull()
+    expect(normalize.resolveCheckinMemberId(null, null)).toBeNull()
+  })
+})

+ 73 - 0
cfc-frontend/__tests__/utils/membershipGate.test.js

@@ -0,0 +1,73 @@
+/**
+ * 会员有效态门控(`utils/membershipGate.js`)单元测试
+ *
+ * 背景:`membershipGate.js` 随 `merge(miniprogram): 聊天/消息类入口按有效会员隐藏`
+ * (commit `3d35ab714`,2026-11-12 00:33)合入主线,**合入时零测试**。
+ * 该函数决定 9 个页面(首页/心/身/智/行/我的/应用库/详情页)的聊天·消息入口可见性,
+ * 属「越权即放行非会员」的强业务约束,必须有可执行锚点。
+ *
+ * 契约(源码注释自述,逐条断言):
+ *   - 唯一判据 = `POST /api/ai/gate` 的 `data.isActive === true`(严格等于,不看 canUse/status)
+ *   - 无 token 直接 false,**不发请求**(fail-closed)
+ *   - 接口异常 / 超时 / 字段缺失 一律 false(fail-closed)
+ *
+ * 锚点:TC-MG-U01 ~ TC-MG-U07
+ */
+jest.mock('@/utils/api.js', () => ({
+  aiGateStatus: jest.fn()
+}))
+
+import { aiGateStatus } from '@/utils/api.js'
+import { isActiveMember } from '@/utils/membershipGate.js'
+
+beforeEach(() => {
+  global.uni._storage = {}
+  aiGateStatus.mockReset()
+})
+
+describe('isActiveMember · 会员有效态(TC-MG-U01~U07)', () => {
+  it('TC-MG-U01 无 token 直接 false,且不发起 /api/ai/gate 请求', async () => {
+    const r = await isActiveMember()
+    expect(r).toBe(false)
+    expect(aiGateStatus).not.toHaveBeenCalled()
+  })
+
+  it('TC-MG-U02 有 token 且 data.isActive === true → true', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockResolvedValue({ code: 200, data: { isActive: true } })
+    await expect(isActiveMember()).resolves.toBe(true)
+    expect(aiGateStatus).toHaveBeenCalledTimes(1)
+  })
+
+  it('TC-MG-U03 有 token 且 data.isActive === false(过期会员)→ false', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockResolvedValue({ code: 200, data: { isActive: false } })
+    await expect(isActiveMember()).resolves.toBe(false)
+  })
+
+  it('TC-MG-U04 响应缺 data 字段 → false(字段缺失 fail-closed)', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockResolvedValue({ code: 200 })
+    await expect(isActiveMember()).resolves.toBe(false)
+  })
+
+  it('TC-MG-U05 isActive 为非布尔真值(后端返回 1 / "true")→ false(严格等值,不误放行)', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockResolvedValueOnce({ code: 200, data: { isActive: 1 } })
+    await expect(isActiveMember()).resolves.toBe(false)
+    aiGateStatus.mockResolvedValueOnce({ code: 200, data: { isActive: 'true' } })
+    await expect(isActiveMember()).resolves.toBe(false)
+  })
+
+  it('TC-MG-U06 接口 reject(网络异常/超时)→ false,不抛错', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockRejectedValue(new Error('timeout'))
+    await expect(isActiveMember()).resolves.toBe(false)
+  })
+
+  it('TC-MG-U07 接口 resolve 成 undefined → false(不因空响应放行)', async () => {
+    global.uni._storage.token = 'tk-abc'
+    aiGateStatus.mockResolvedValue(undefined)
+    await expect(isActiveMember()).resolves.toBe(false)
+  })
+})

+ 63 - 0
cfc-frontend/__tests__/utils/signature-bus.test.js

@@ -0,0 +1,63 @@
+/**
+ * 签名页预填总线(utils/signature-bus.js)
+ * 覆盖需求变更:签名改独立全屏横屏页(WI-1~WI-5, commit e35ca7186)
+ *   WI-4 编辑场景点「重新签名」需回显原签名 → 跳转前 setSignaturePrefill()
+ *   WI-1 签名页 onLoad consumeSignaturePrefill() 一次性消费,避免残留串扰下一次签名
+ *
+ * SRS 依据:docs/需求/签名改独立横屏页-需求变更.md(AC5.3 全局无业务页内嵌签名)
+ */
+function freshBus() {
+  let bus
+  jest.isolateModules(() => {
+    bus = require('../../utils/signature-bus')
+  })
+  return bus
+}
+
+describe('signature-bus 签名预填一次性传递(WI-1/WI-4)', () => {
+  it('初始状态为空串,签名页不出现历史回显', () => {
+    const { getSignaturePrefill, consumeSignaturePrefill } = freshBus()
+    expect(getSignaturePrefill()).toBe('')
+    expect(consumeSignaturePrefill()).toBe('')
+  })
+
+  it('写入后可读取,get 不消费(调用方与签名页两侧都能读到)', () => {
+    const bus = freshBus()
+    bus.setSignaturePrefill('data:image/png;base64,AAA')
+    expect(bus.getSignaturePrefill()).toBe('data:image/png;base64,AAA')
+    expect(bus.getSignaturePrefill()).toBe('data:image/png;base64,AAA')
+    expect(bus.consumeSignaturePrefill()).toBe('data:image/png;base64,AAA')
+  })
+
+  it('consume 只返回一次,第二次进入签名页必须是空串(防串扰)', () => {
+    const bus = freshBus()
+    bus.setSignaturePrefill('data:image/png;base64,BBB')
+    expect(bus.consumeSignaturePrefill()).toBe('data:image/png;base64,BBB')
+    expect(bus.consumeSignaturePrefill()).toBe('')
+    expect(bus.getSignaturePrefill()).toBe('')
+  })
+
+  it('重新签名场景:再次写入可覆盖,回显为最新写入值', () => {
+    const bus = freshBus()
+    bus.setSignaturePrefill('data:image/png;base64,OLD')
+    bus.consumeSignaturePrefill()
+    bus.setSignaturePrefill('data:image/png;base64,NEW')
+    expect(bus.consumeSignaturePrefill()).toBe('data:image/png;base64,NEW')
+  })
+
+  it('null / undefined 归一化为空串(新签名无回显)', () => {
+    const bus = freshBus()
+    bus.setSignaturePrefill('data:image/png;base64,CCC')
+    bus.setSignaturePrefill(null)
+    expect(bus.getSignaturePrefill()).toBe('')
+    bus.setSignaturePrefill(undefined)
+    expect(bus.getSignaturePrefill()).toBe('')
+  })
+
+  it('传空串等于清除(用户选择「去签名」后不得回显旧图)', () => {
+    const bus = freshBus()
+    bus.setSignaturePrefill('data:image/png;base64,DDD')
+    bus.setSignaturePrefill('')
+    expect(bus.consumeSignaturePrefill()).toBe('')
+  })
+})

+ 87 - 0
cfc-frontend/__tests__/utils/team-tree.test.js

@@ -0,0 +1,87 @@
+/**
+ * Tests for cfc-frontend utils/team-tree.js
+ *
+ * Tests the pure function that converts flat /api/commission/team/tree nodes
+ * (as returned by the backend) into preorder rows usable by the tree view.
+ * These are pure functions - no uni mock needed.
+ */
+
+describe('team-tree.js', () => {
+  let teamTree
+
+  beforeAll(() => {
+    teamTree = require('@/utils/team-tree')
+  })
+
+  describe('buildTeamTreeRows', () => {
+    const nodes = [
+      { userId: 101, nickname: '直推A', level: 1, parentId: 100, memberConsumption: 32000, myCfEarnedFromMember: 9600 },
+      { userId: 102, nickname: '间推B', level: 2, parentId: 101, memberConsumption: 8000, myCfEarnedFromMember: 2400 },
+      { userId: 103, nickname: '直推C', level: 1, parentId: 100, memberConsumption: 15000, myCfEarnedFromMember: 4500 }
+    ]
+
+    test('builds preorder rows with depth from flat nodes', () => {
+      const rows = teamTree.buildTeamTreeRows(nodes)
+      expect(rows.map(r => r.node.userId)).toEqual([101, 102, 103])
+      expect(rows.map(r => r.depth)).toEqual([0, 1, 0])
+    })
+
+    test('marks hasChildren and collapsed flags', () => {
+      const rows = teamTree.buildTeamTreeRows(nodes)
+      expect(rows[0].hasChildren).toBe(true)
+      expect(rows[0].collapsed).toBe(false)
+      expect(rows[1].hasChildren).toBe(false)
+      expect(rows[2].hasChildren).toBe(false)
+    })
+
+    test('collapsed node hides its descendants only', () => {
+      const rows = teamTree.buildTeamTreeRows(nodes, [101])
+      expect(rows.map(r => r.node.userId)).toEqual([101, 103])
+      expect(rows[0].collapsed).toBe(true)
+    })
+
+    test('treats nodes with unknown parentId as roots', () => {
+      const rows = teamTree.buildTeamTreeRows(nodes)
+      expect(rows.filter(r => r.depth === 0).length).toBe(2)
+    })
+
+    test('prefers referrerId over parentId for immediate parent (materialized tree)', () => {
+      // /api/commission/team/tree 物化表查询结果中 parentId 恒为根节点,referrerId 才是直接上级
+      const materialized = [
+        { userId: 101, referrerId: 100, parentId: 100, level: 1 },
+        { userId: 102, referrerId: 101, parentId: 100, level: 2 }
+      ]
+      const rows = teamTree.buildTeamTreeRows(materialized)
+      expect(rows.map(r => r.node.userId)).toEqual([101, 102])
+      expect(rows.map(r => r.depth)).toEqual([0, 1])
+      expect(rows[0].hasChildren).toBe(true)
+      expect(rows[1].hasChildren).toBe(false)
+    })
+
+    test('rootUserId shifts root depth so "self" row can sit at depth 0', () => {
+      // team.vue 自造根行(depth=0),传入 rootUserId 后 L1 成员 depth 从 1 开始
+      const materialized = [
+        { userId: 101, referrerId: 100, parentId: 100, level: 1 },
+        { userId: 102, referrerId: 101, parentId: 100, level: 2 }
+      ]
+      const rows = teamTree.buildTeamTreeRows(materialized, [], 100)
+      expect(rows.map(r => r.node.userId)).toEqual([101, 102])
+      expect(rows.map(r => r.depth)).toEqual([1, 2])
+    })
+
+    test('returns empty array for empty nodes', () => {
+      expect(teamTree.buildTeamTreeRows([])).toEqual([])
+      expect(teamTree.buildTeamTreeRows(null)).toEqual([])
+      expect(teamTree.buildTeamTreeRows(undefined)).toEqual([])
+    })
+
+    test('guards against self-referencing cycles', () => {
+      const cyclic = [
+        { userId: 201, nickname: 'A', level: 1, parentId: 201 }
+      ]
+      const rows = teamTree.buildTeamTreeRows(cyclic)
+      expect(rows.length).toBe(1)
+      expect(rows[0].depth).toBe(0)
+    })
+  })
+})

+ 79 - 0
cfc-frontend/__tests__/utils/wuxing-sandbox.test.js

@@ -0,0 +1,79 @@
+import {
+  buildMemberOptions,
+  dedupeMembers,
+  nextSandboxSelection,
+  resolveSandboxOverall,
+  resolveSandboxScores
+} from '@/utils/wuxing-sandbox'
+
+const familyScores = {
+  bodyScore: 59,
+  mindScore: 0,
+  wisdomScore: 8,
+  actionScore: 0,
+  wealthScore: 8,
+  overallScore: 15
+}
+
+const personalData = {
+  bodyScore: 75,
+  mindScore: 0,
+  wisdomScore: 3,
+  actionScore: 0,
+  wealthScore: 30,
+  overallScore: 21,
+  members: [{ memberId: 12, memberType: 'parent', name: '他爹' }]
+}
+
+const members = [
+  { memberId: 12, memberType: 'parent', name: '他爹', bodyScore: 75, mindScore: 0, wisdomScore: 3, actionScore: 0, wealthScore: 30, overallScore: 21 },
+  { memberId: 34, memberType: 'parent', name: '书宁宁', bodyScore: 78, mindScore: 0, wisdomScore: 10, actionScore: 0, wealthScore: 6, overallScore: 19 },
+  { memberId: 78, memberType: 'parent', name: '云泽', bodyScore: 0, mindScore: 0, wisdomScore: 0, actionScore: 0, wealthScore: 0, overallScore: 0 },
+  { memberId: 23, memberType: 'child', name: '老二', bodyScore: 0, mindScore: 0, wisdomScore: 43, actionScore: 0, wealthScore: 21, overallScore: 13 },
+  // 完全重复的成员记录只能出现一次
+  { memberId: 34, memberType: 'parent', name: '书宁宁', bodyScore: 78, mindScore: 0, wisdomScore: 10, actionScore: 0, wealthScore: 6, overallScore: 19 }
+]
+
+describe('wuxing sandbox member selection', () => {
+  test('dedupeMembers removes exact duplicate member rows', () => {
+    expect(dedupeMembers(members).map(m => m.memberId)).toEqual([12, 34, 78, 23])
+  })
+
+  test('buildMemberOptions excludes self, dedupes members and appends family', () => {
+    const options = buildMemberOptions(members, personalData)
+    expect(options.map(o => o.label)).toEqual(['本人', '书宁宁', '云泽', '老二', '全家'])
+    expect(options[0].viewMode).toBe('personal')
+    expect(options[options.length - 1].viewMode).toBe('family')
+  })
+
+  test('member view uses the selected member scores instead of personalData', () => {
+    const selected = members[1]
+    expect(resolveSandboxScores('member', familyScores, personalData, selected)).toEqual([78, 0, 10, 0, 6])
+    expect(resolveSandboxOverall('member', familyScores, personalData, selected)).toBe(19)
+  })
+
+  test('personal view keeps the login user scores', () => {
+    expect(resolveSandboxScores('personal', familyScores, personalData, null)).toEqual([75, 0, 3, 0, 30])
+    expect(resolveSandboxOverall('personal', familyScores, personalData, null)).toBe(21)
+  })
+
+  test('family view uses family aggregate scores', () => {
+    expect(resolveSandboxScores('family', familyScores, personalData, null)).toEqual([59, 0, 8, 0, 8])
+    expect(resolveSandboxOverall('family', familyScores, personalData, null)).toBe(15)
+  })
+
+  test('center click cycles personal -> other members -> family -> personal', () => {
+    const options = buildMemberOptions(members, personalData)
+    expect(nextSandboxSelection(options, 'personal', null)).toMatchObject({ viewMode: 'member', memberId: 34 })
+    expect(nextSandboxSelection(options, 'member', 34)).toMatchObject({ viewMode: 'member', memberId: 78 })
+    expect(nextSandboxSelection(options, 'member', 23)).toMatchObject({ viewMode: 'family' })
+    expect(nextSandboxSelection(options, 'family', null)).toMatchObject({ viewMode: 'personal' })
+  })
+
+  test('only family and self falls back to self instead of showing an empty member', () => {
+    const onlySelf = { ...personalData, members: [{ memberId: 12, memberType: 'parent', name: '他爹' }] }
+    const options = buildMemberOptions([], onlySelf)
+    expect(options.map(o => o.viewMode)).toEqual(['personal', 'family'])
+    expect(nextSandboxSelection(options, 'personal', null)).toMatchObject({ viewMode: 'family' })
+  })
+})

+ 57 - 0
cfc-frontend/__tests__/vue-transform.js

@@ -0,0 +1,57 @@
+/**
+ * Jest transformer for uni-app `.vue` Single File Components (Vue 2.7).
+ *
+ * PURPOSE: cfc-frontend's default jest.config.js only transforms `.js` via
+ * babel-jest, so `.vue` SFCs cannot be imported by tests. This transformer
+ * compiles the SFC `<script>` block (Options API) to CommonJS and precompiles
+ * the `<template>` block to a Vue 2 render function (the default `vue` entry
+ * in Node is runtime-only and has no template compiler), so tests can `mount`
+ * real page components with `@vue/test-utils`.
+ *
+ * TEST-ONLY infrastructure: this file lives under `__tests__/` and is NOT part
+ * of the app runtime. It does not modify any `pages/` / `utils/` business code.
+ */
+const { parseComponent, compileTemplate } = require('@vue/compiler-sfc')
+const babel = require('@babel/core')
+
+module.exports = {
+  process(src, filename) {
+    const descriptor = parseComponent(src, { filename })
+    if (descriptor.errors && descriptor.errors.length) {
+      throw new Error('[vue-transform] SFC parse error in ' + filename + ':\n' + descriptor.errors.join('\n'))
+    }
+
+    let code = ''
+    if (descriptor.script && descriptor.script.content) {
+      // Options API: `export default {...}` -> `const __sfc_main = {...}`
+      code += descriptor.script.content.replace(/export\s+default/, 'const __sfc_main =')
+    } else {
+      code += 'const __sfc_main = {}'
+    }
+
+    if (descriptor.template && descriptor.template.content) {
+      const res = compileTemplate({
+        source: descriptor.template.content,
+        filename,
+        id: filename.replace(/[^\w]/g, '_')
+      })
+      if (res.errors && res.errors.length) {
+        throw new Error('[vue-transform] template compile error in ' + filename + ':\n' + res.errors.join('\n'))
+      }
+      code += '\n' + res.code
+      code += '\n__sfc_main.render = render'
+      code += '\n__sfc_main.staticRenderFns = staticRenderFns'
+    }
+
+    code += '\nmodule.exports = __sfc_main'
+    // Transpile the assembled module to CommonJS (the <script> block keeps ES
+    // `import` statements; Node cannot execute them in a jest CJS module).
+    const out = babel.transformSync(code, {
+      filename,
+      presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
+      babelrc: false,
+      configFile: false
+    })
+    return { code: out.code, map: null }
+  }
+}

+ 5 - 0
cfc-frontend/babel.config.js

@@ -0,0 +1,5 @@
+module.exports = {
+  presets: [
+    ['@babel/preset-env', { targets: { node: 'current' } }]
+  ]
+}

+ 4 - 0
cfc-frontend/build_err.txt

@@ -0,0 +1,4 @@
+-  Start to compile the current project to the mp-weixin platform...
+(node:35040) [DEP0044] DeprecationWarning: The `util.isArray` API is deprecated. Please use `Array.isArray()` instead.
+(Use `node --trace-deprecation ...` to show where the warning was created)
+(node:35040) [DEP0055] DeprecationWarning: The `util.isRegExp` API is deprecated. Please use `arg instanceof RegExp` instead.

+ 58 - 0
cfc-frontend/common/uni.css

@@ -0,0 +1,58 @@
+/* uni-app 公共样式 */
+/* 这是一个占位文件,确保App.vue中的@import能正常工作 */
+
+/* 常用样式 */
+page {
+  background-color: #f5f5f5;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
+}
+
+.container {
+  padding: 20rpx;
+}
+
+/* 按钮样式 */
+.btn-primary {
+  background-color: #F97316;
+  color: #fff;
+  border-radius: 20rpx;
+  padding: 20rpx 40rpx;
+  text-align: center;
+  font-size: 28rpx;
+}
+
+.btn-primary:active {
+  opacity: 0.8;
+}
+
+.btn-secondary {
+  background-color: #fff;
+  color: #F97316;
+  border: 2rpx solid #F97316;
+  border-radius: 20rpx;
+  padding: 20rpx 40rpx;
+  text-align: center;
+  font-size: 28rpx;
+}
+
+/* 卡片样式 */
+.card {
+  background-color: #fff;
+  border-radius: 16rpx;
+  padding: 24rpx;
+  margin-bottom: 20rpx;
+  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
+}
+
+/* 文本样式 */
+.text-primary {
+  color: #F97316;
+}
+
+.text-gray {
+  color: #999;
+}
+
+.text-bold {
+  font-weight: bold;
+}

+ 9 - 0
cfc-frontend/components/AIFloatingAvatar.vue

@@ -0,0 +1,9 @@
+<template>
+  <!-- 问答功能已屏蔽 -->
+</template>
+
+<script>
+export default {
+  name: 'FloatingAvatar'
+}
+</script>

+ 162 - 0
cfc-frontend/components/ArticleFeed.vue

@@ -0,0 +1,162 @@
+<template>
+  <view class="af-section">
+    <!-- 空态 -->
+    <view v-if="(!articles || articles.length === 0) && !loading" class="af-empty">
+      <text class="af-empty-text">暂无推荐文章</text>
+    </view>
+
+    <!-- 加载态骨架:3 条左图右文卡片 -->
+    <view v-else-if="loading && (!articles || articles.length === 0)" class="af-list">
+      <view v-for="n in 3" :key="n" class="af-item">
+        <view class="af-cover af-skeleton-block"></view>
+        <view class="af-body">
+          <view class="af-skeleton-line af-skeleton-line-title"></view>
+          <view class="af-skeleton-line"></view>
+        </view>
+      </view>
+    </view>
+
+    <!-- 左图右文列表(与文章详情「相关文章」视觉一致) -->
+    <view v-else class="af-list">
+      <view
+        v-for="item in articles"
+        :key="item.id"
+        class="af-item"
+        hover-class="af-item-pressed"
+        @click="onArticleClick(item)"
+      >
+        <image class="af-cover" :src="articleCover(item)" mode="aspectFill" lazy-load />
+        <view class="af-body">
+          <text class="af-title">{{ item.title }}</text>
+          <text class="af-summary" v-if="item.summary">{{ item.summary }}</text>
+        </view>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script>
+import config from '@/config.js'
+
+/**
+ * ArticleFeed — 文章「关联文章」同款左图右文列表,用于首页/成长页「推荐阅读」统一视觉。
+ * 纯展示组件:数据由父页面传入,点击通过 articleClick 事件上抛文章对象。
+ */
+export default {
+  name: 'ArticleFeed',
+  props: {
+    articles: { type: Array, default: function() { return [] } },
+    loading: { type: Boolean, default: false }
+  },
+  methods: {
+    onArticleClick: function(item) {
+      this.$emit('articleClick', item)
+    },
+    // 封面图 URL 解析:空 / null / undefined / '/null' → 默认图(与 RelatedContent 同口径,增补 '/null' 兜底)
+    articleCover: function(item) {
+      if (!item || !item.coverImage) return '/static/default-article.png'
+      return this.resolveUrl(item.coverImage) || '/static/default-article.png'
+    },
+    resolveUrl: function(path) {
+      var s = String(path || '').trim()
+      if (!s || s === 'null' || s === 'undefined' || s === '/null') return ''
+      if (s.indexOf('http://') === 0 || s.indexOf('https://') === 0 || s.indexOf('/static/') === 0) return s
+      return config.API_BASE_URL + (s.charAt(0) === '/' ? s : '/' + s)
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.af-section {
+  background: $app-surface;
+  border-radius: 16rpx;
+  padding: 24rpx;
+}
+
+/* ---- 空态 ---- */
+.af-empty {
+  display: flex;
+  justify-content: center;
+  padding: 40rpx 0;
+}
+.af-empty-text {
+  font-size: calc(24rpx * var(--font-scale, 1));
+  color: $facade-text-gray-400;
+}
+
+/* ---- 列表 ---- */
+.af-list {
+  display: flex;
+  flex-direction: column;
+}
+.af-item {
+  display: flex;
+  flex-direction: row;
+  align-items: flex-start;
+  padding: 14rpx 0;
+  border-radius: 16rpx;
+}
+.af-item-pressed {
+  background: $facade-fill-gray-100;
+}
+.af-cover {
+  width: 160rpx;
+  height: 120rpx;
+  border-radius: 16rpx;
+  background: $facade-fill-gray-100;
+  flex-shrink: 0;
+}
+.af-body {
+  flex: 1;
+  min-width: 0;
+  margin-left: 16rpx;
+  display: flex;
+  flex-direction: column;
+}
+.af-title {
+  font-size: calc(27rpx * var(--font-scale, 1));
+  font-weight: 500;
+  color: $facade-text-gray-800;
+  line-height: 1.4;
+  display: -webkit-box;
+  -webkit-box-orient: vertical;
+  -webkit-line-clamp: 2;
+  overflow: hidden;
+}
+.af-summary {
+  font-size: calc(23rpx * var(--font-scale, 1));
+  color: $facade-text-gray-400;
+  line-height: 1.4;
+  margin-top: 6rpx;
+  display: -webkit-box;
+  -webkit-box-orient: vertical;
+  -webkit-line-clamp: 2;
+  overflow: hidden;
+}
+
+/* ---- 骨架屏(3 条左图右文占位) ---- */
+.af-skeleton-block {
+  background: linear-gradient(180deg, $facade-fill-4 0%, $facade-fill 50%, $facade-fill-4 100%);
+  background-size: 200% 100%;
+  animation: af-skeleton-wave 1.4s ease-in-out infinite;
+}
+.af-skeleton-line {
+  width: 100%;
+  height: 28rpx;
+  border-radius: 8rpx;
+  margin-top: 10rpx;
+  background: linear-gradient(180deg, $facade-fill-4 0%, $facade-fill 50%, $facade-fill-4 100%);
+  background-size: 200% 100%;
+  animation: af-skeleton-wave 1.4s ease-in-out infinite;
+}
+.af-skeleton-line-title {
+  width: 72%;
+  height: 32rpx;
+  margin-top: 0;
+}
+@keyframes af-skeleton-wave {
+  0% { background-position: 200% 0; }
+  100% { background-position: -200% 0; }
+}
+</style>

+ 56 - 0
cfc-frontend/components/BadgeGrid.vue

@@ -0,0 +1,56 @@
+<template>
+  <view class="badge-grid" v-if="badges.length > 0">
+    <view class="badge-grid-inner">
+      <view class="badge-cell" v-for="badge in badges" :key="badge.id"
+        :class="{ 'badge-cell--locked': !badge.unlocked }">
+        <view class="badge-icon-wrap" :class="{ 'badge-icon-wrap--locked': !badge.unlocked }">
+          <text class="badge-icon">{{ badge.unlocked ? badge.icon : '🔒' }}</text>
+        </view>
+        <text class="badge-name">{{ badge.name }}</text>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script>
+export default {
+  props: {
+    badges: { type: Array, default: function() { return [] } }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.badge-grid {
+  background: $app-surface;
+  border-radius: 24rpx;
+  padding: 24rpx;
+  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.06);
+}
+.badge-grid-inner {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 16rpx;
+}
+.badge-cell {
+  width: calc(33.33% - 11rpx);
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  padding: 12rpx 0;
+}
+.badge-cell--locked { opacity: 0.5; }
+.badge-icon-wrap {
+  width: 80rpx;
+  height: 80rpx;
+  border-radius: 50%;
+  background: linear-gradient(135deg, $accent-gold, $accent-gold-deep);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  margin-bottom: 8rpx;
+}
+.badge-icon-wrap--locked { background: $uni-border-color-light; }
+.badge-icon { font-size: calc(36rpx * var(--font-scale, 1)); }
+.badge-name { font-size: calc(22rpx * var(--font-scale, 1)); color: $facade-text-strong; text-align: center; }
+</style>

+ 68 - 0
cfc-frontend/components/BaseBadge.vue

@@ -0,0 +1,68 @@
+<template>
+  <view
+    class="base-badge"
+    :class="['base-badge--' + variant, 'base-badge--' + size]"
+  >
+    <slot />
+  </view>
+</template>
+
+<script>
+export default {
+  name: 'BaseBadge',
+  props: {
+    variant: { type: String, default: 'primary' },
+    // 'primary' | 'success' | 'warning' | 'error' | 'accent' | 'muted'
+    size: { type: String, default: 'sm' }
+    // 'xs' | 'sm' | 'md'
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.base-badge {
+  display: inline-flex;
+  align-items: center;
+  font-weight: 600;
+  border-radius: 999rpx;
+  white-space: nowrap;
+}
+
+/* Sizes */
+.base-badge--xs { font-size: calc(20rpx * var(--font-scale, 1)); padding: 4rpx 14rpx; line-height: 1.4; }
+.base-badge--sm { font-size: calc(22rpx * var(--font-scale, 1)); padding: 6rpx 18rpx; line-height: 1.4; }
+.base-badge--md { font-size: calc(24rpx * var(--font-scale, 1)); padding: 8rpx 24rpx; line-height: 1.5; }
+
+/* Variants — v4.0 品牌紫:primary 底改品牌紫 12% 透明底 + 品牌紫文字
+   v4.1 对抗式评审 P0-5 修复:状态徽章 4 变体文字对比度不足,全部降档为深档令牌。
+   逐变体实测(WCAG 2.1 相对亮度公式):
+   - success $mat-green-800 on $status-success-soft = 6.29:1(旧亮绿档 2.01:1 未达标)
+   - error   $status-danger-strong on $status-danger-soft = 5.30:1(旧亮红档 3.08:1 未达标)
+   - accent  $status-info-deep-3 on $status-info-soft = 5.49:1(旧亮蓝档 2.27:1 未达标;中间档蓝仅 4.24:1 未达 4.5,故取更深的 $status-info-deep-3)
+   - muted   $facade-text-slate-deep on $facade-fill-slate = 6.92:1(旧弱文字灰档 4.41:1 未达标)
+   只换文字令牌,底色令牌不动,6 复用页面零改动。 */
+.base-badge--primary {
+  background: $brand-primary-soft;
+  color: $brand-primary;
+}
+.base-badge--success {
+  background: $status-success-soft;
+  color: $mat-green-800;
+}
+.base-badge--warning {
+  background: $status-warning-soft;
+  color: $status-warning-strong;
+}
+.base-badge--error {
+  background: $status-danger-soft;
+  color: $status-danger-strong;
+}
+.base-badge--accent {
+  background: $status-info-soft;
+  color: $status-info-deep-3;
+}
+.base-badge--muted {
+  background: $facade-fill-slate;
+  color: $facade-text-slate-deep;
+}
+</style>

+ 96 - 0
cfc-frontend/components/BaseCard.vue

@@ -0,0 +1,96 @@
+<template>
+  <view
+    class="base-card"
+    :class="[cardClasses]"
+    :hover-class="clickable && !disabled ? 'base-card--pressed' : ''"
+    :hover-stay-time="80"
+    @click="handleClick"
+  >
+    <view class="base-card__header" v-if="hasHeader">
+      <slot name="header"></slot>
+    </view>
+    <view class="base-card__body">
+      <slot></slot>
+    </view>
+    <view class="base-card__footer" v-if="hasFooter">
+      <slot name="footer"></slot>
+    </view>
+  </view>
+</template>
+
+<script>
+export default {
+  name: 'BaseCard',
+  props: {
+    // 交互:可点击卡片(pressed 态)
+    clickable: { type: Boolean, default: false },
+    disabled: { type: Boolean, default: false },
+    // 视觉档位:归一为一档(极简风格,无多档阴影)
+    padding: { type: String, default: 'lg' }
+    // 'sm' | 'md' | 'lg' | 'none'
+  },
+  data() {
+    return {
+      hasHeader: false,
+      hasFooter: false
+    }
+  },
+  mounted() {
+    this.hasHeader = !!this.$slots.header
+    this.hasFooter = !!this.$slots.footer
+  },
+  computed: {
+    cardClasses() {
+      return [
+        'base-card--pad-' + this.padding,
+        this.clickable ? 'base-card--clickable' : '',
+        this.disabled ? 'base-card--disabled' : ''
+      ]
+    }
+  },
+  methods: {
+    handleClick(e) {
+      if (this.clickable && !this.disabled) this.$emit('click', e)
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+/* 统一卡片容器:白底 + 圆角 + 细边框 + 轻投影(归一为一档),极简风格 */
+.base-card {
+  background: $uni-bg-card;
+  border-radius: $radius-lg;
+  border: 1rpx solid $uni-border-subtle;
+  box-shadow: $uni-shadow-sm;
+  box-sizing: border-box;
+  overflow: hidden;
+}
+.base-card--clickable {
+  transition: transform $dur-press $ease-standard, box-shadow $dur-press $ease-standard;
+}
+/* pressed:按压回退 + 投影收敛(只动 transform/opacity,尊重 reduced-motion) */
+.base-card--pressed {
+  transform: scale(0.99);
+  box-shadow: none;
+}
+.base-card--disabled {
+  opacity: $disabled-opacity;
+}
+
+/* 内边距档(rpx) */
+.base-card--pad-sm { padding: 16rpx; }
+.base-card--pad-md { padding: 24rpx; }
+.base-card--pad-lg { padding: 32rpx; }
+.base-card--pad-none { padding: 0; }
+
+.base-card__header {
+  margin-bottom: 20rpx;
+}
+.base-card__body {
+  line-height: 1.6;
+}
+.base-card__footer {
+  margin-top: 20rpx;
+}
+</style>

+ 89 - 0
cfc-frontend/components/BaseEmpty.vue

@@ -0,0 +1,89 @@
+<template>
+  <view class="base-empty" :class="{ 'base-empty--compact': compact }">
+    <!-- 图标:slot > 默认内联 SVG;icon 属性为旧调用方文本兜底(不新建 emoji) -->
+    <view class="base-empty__icon" v-if="hasIcon">
+      <slot name="icon" v-if="$slots.icon"></slot>
+      <svg
+        v-else-if="!icon"
+        class="base-empty__svg"
+        viewBox="0 0 48 48"
+        width="80rpx"
+        height="80rpx"
+        aria-hidden="true"
+      >
+        <circle cx="24" cy="24" r="22" fill="currentColor" opacity="0.12"></circle>
+        <path
+          d="M24 12c-6 0-10 4.2-10 9.6 0 6.8 6.4 11.6 10 14.4 3.6-2.8 10-7.6 10-14.4C34 16.2 30 12 24 12z"
+          fill="currentColor"
+        ></path>
+      </svg>
+      <text v-else class="base-empty__glyph">{{ icon }}</text>
+    </view>
+    <text class="base-empty__title" v-if="title">{{ title }}</text>
+    <text class="base-empty__description" v-if="description">{{ description }}</text>
+    <view class="base-empty__action" v-if="$slots.action">
+      <slot name="action"></slot>
+    </view>
+  </view>
+</template>
+
+<script>
+export default {
+  name: 'BaseEmpty',
+  props: {
+    icon: { type: String, default: '' },
+    title: { type: String, default: '' },
+    description: { type: String, default: '' },
+    compact: { type: Boolean, default: false }
+  },
+  computed: {
+    hasIcon() {
+      return !!this.icon || !!this.$slots.icon
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.base-empty {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  padding: 80rpx 32rpx;
+  min-height: 400rpx;
+}
+.base-empty--compact {
+  padding: 48rpx 32rpx;
+  min-height: auto;
+}
+.base-empty__icon {
+  margin-bottom: 24rpx;
+  color: $uni-primary;
+}
+.base-empty__svg {
+  display: block;
+}
+.base-empty__glyph {
+  font-size: calc(80rpx * var(--font-scale, 1));
+  display: block;
+  text-align: center;
+}
+.base-empty__title {
+  font-size: calc(30rpx * var(--font-scale, 1));
+  font-weight: 600;
+  color: $uni-text-color;
+  margin-bottom: 12rpx;
+  text-align: center;
+}
+.base-empty__description {
+  font-size: calc(26rpx * var(--font-scale, 1));
+  color: $uni-text-color-secondary;
+  text-align: center;
+  line-height: 1.6;
+  max-width: 500rpx;
+}
+.base-empty__action {
+  margin-top: 32rpx;
+}
+</style>

+ 76 - 0
cfc-frontend/components/BaseLoading.vue

@@ -0,0 +1,76 @@
+<template>
+  <view class="base-loading" :class="{ 'base-loading--overlay': overlay }" v-if="loading">
+    <view class="base-loading__spinner" v-if="type === 'spinner'">
+      <view class="base-loading__dot" v-for="i in 3" :key="i"></view>
+    </view>
+    <text class="base-loading__text" v-if="text">{{ text }}</text>
+  </view>
+</template>
+
+<script>
+export default {
+  name: 'BaseLoading',
+  props: {
+    loading: { type: Boolean, default: false },
+    type: { type: String, default: 'spinner' },
+    // 'spinner' | 'skeleton'
+    text: { type: String, default: '' },
+    overlay: { type: Boolean, default: false }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.base-loading {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  padding: 48rpx;
+}
+.base-loading--overlay {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  background: $scrim-surface;
+  z-index: 999;
+  padding: 0;
+}
+
+/* Spinner dots */
+.base-loading__spinner {
+  display: flex;
+  align-items: center;
+  gap: 12rpx;
+  margin-bottom: 16rpx;
+}
+.base-loading__dot {
+  width: 16rpx;
+  height: 16rpx;
+  border-radius: 50%;
+  background: var(--color-primary, $brand-primary);
+  animation: dot-bounce 1.2s ease-in-out infinite;
+}
+.base-loading__dot:nth-child(2) { animation-delay: 0.2s; }
+.base-loading__dot:nth-child(3) { animation-delay: 0.4s; }
+
+.base-loading__text {
+  font-size: calc(24rpx * var(--font-scale, 1));
+  color: var(--muted, $app-text-subtle);
+}
+</style>
+
+<style>
+@keyframes dot-bounce {
+  0%, 80%, 100% {
+    transform: scale(0.6);
+    opacity: 0.4;
+  }
+  40% {
+    transform: scale(1);
+    opacity: 1;
+  }
+}
+</style>

+ 164 - 0
cfc-frontend/components/BasePrimaryButton.vue

@@ -0,0 +1,164 @@
+<template>
+  <button
+    class="base-primary-btn"
+    :class="[sizeClass, stateClass, { 'base-primary-btn--block': block }]"
+    :disabled="disabled"
+    :hover-class="disabled || loading ? '' : 'base-primary-btn--pressed'"
+    :hover-stay-time="80"
+    @click="handleClick"
+    :aria-label="ariaLabel"
+  >
+    <!-- loading 态:只动 transform/opacity,尊重 reduced-motion -->
+    <view class="base-primary-btn__spinner" v-if="loading" aria-hidden="true">
+      <view class="base-primary-btn__dot" v-for="i in 3" :key="i"></view>
+    </view>
+    <text class="base-primary-btn__label" v-if="loading">{{ loadingText }}</text>
+    <text class="base-primary-btn__label" v-else><slot></slot></text>
+  </button>
+</template>
+
+<script>
+export default {
+  name: 'BasePrimaryButton',
+  props: {
+    disabled: { type: Boolean, default: false },
+    loading: { type: Boolean, default: false },
+    loadingText: { type: String, default: '提交中…' },
+    size: { type: String, default: 'md' },
+    // 'sm' | 'md' | 'lg'
+    block: { type: Boolean, default: false },
+    // 语义态:'default' 紫底主行动 | 'error' 深红底提交失败回执 | 'success' 深绿底提交成功回执
+    state: { type: String, default: 'default' },
+    ariaLabel: { type: String, default: '' }
+  },
+  computed: {
+    sizeClass() {
+      return 'base-primary-btn--' + this.size
+    },
+    stateClass() {
+      return this.state !== 'default' ? 'base-primary-btn--' + this.state : ''
+    }
+  },
+  methods: {
+    handleClick(e) {
+      if (this.disabled || this.loading) return
+      this.$emit('click', e)
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+/* 八态契约(v4.1 对抗式评审 P0-5 补齐 hover/error/success 三态):
+   default($brand-primary 白字 5.70:1) / hover($btn-hover-bg 白字 7.10:1) / focus(6rpx 焦点环 on 白 3.29:1)
+   / pressed(transform 微压) / disabled($btn-disabled-bg 底) / loading(spinner 覆盖 error/success 底色)
+   / error($status-danger-strong 白字 6.47:1) / success($btn-success-bg 白字 5.48:1)
+   一屏唯一主行动:紫底白字 + 圆角 + 44px 触区;极简克制,无堆叠投影 */
+.base-primary-btn {
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  gap: 12rpx;
+  border: none;
+  border-radius: $radius-lg;
+  background: $brand-primary;
+  color: $uni-text-color-inverse;
+  font-weight: $uni-font-weight-bold;
+  line-height: 1.4;
+  box-sizing: border-box;
+  /* 触区 ≥44px(88rpx) */
+  min-height: 88rpx;
+  padding: 20rpx 48rpx;
+  transition: opacity $dur-press $ease-standard, transform $dur-press $ease-standard;
+}
+.base-primary-btn--sm {
+  /* v4.1 触区达标:76rpx(38px) 提至 88rpx(44px),Apple HIG/WCAG 2.5.5 最小触区 44px */
+  min-height: 88rpx;
+  padding: 14rpx 36rpx;
+  font-size: calc(26rpx * var(--font-scale, 1));
+}
+.base-primary-btn--md {
+  font-size: calc(30rpx * var(--font-scale, 1));
+}
+.base-primary-btn--lg {
+  min-height: 100rpx;
+  font-size: calc(32rpx * var(--font-scale, 1));
+}
+.base-primary-btn--block {
+  display: flex;
+  width: 100%;
+}
+
+/* pressed:按压微压(只用 transform,尊重 reduced-motion) */
+.base-primary-btn--pressed {
+  transform: scale(0.98);
+  opacity: 0.92;
+}
+
+/* hover(指针设备):主色略深,白字对比度反升($btn-hover-bg 上白字 7.10:1) */
+@media (hover: hover) and (pointer: fine) {
+  .base-primary-btn:hover {
+    background: $btn-hover-bg;
+  }
+}
+
+/* error 态:语义失败回执,深红底白字($status-danger-strong 上白字 6.47:1 达标)
+   $btn-error-bg 浅红底白字仅 3.77:1 未达 4.5,故取更深的 $status-danger-strong */
+.base-primary-btn--error {
+  background: $status-danger-strong;
+  color: $uni-text-color-inverse;
+}
+
+/* success 态:语义成功回执,emerald-700 深绿底白字($btn-success-bg 上白字 5.48:1 达标) */
+.base-primary-btn--success {
+  background: $btn-success-bg;
+  color: $uni-text-color-inverse;
+}
+
+/* disabled:暖灰中性底 + 深字(不淡出,语义双确认) */
+.base-primary-btn:disabled {
+  background: $btn-disabled-bg;
+  color: $btn-disabled-ink;
+  opacity: 1;
+  transform: none;
+}
+
+/* focus:≥3:1 可见焦点环(outline 4rpx 提至 6rpx 提升可见性;
+   $brand-primary-focus 焦点环合成色 on 白 3.29:1 达标) */
+.base-primary-btn:focus {
+  outline: 6rpx solid $brand-primary-focus;
+  outline-offset: 2rpx;
+}
+
+/* loading 态:主轴不变,仅指示器动 */
+.base-primary-btn__spinner {
+  display: flex;
+  align-items: center;
+  gap: 8rpx;
+}
+.base-primary-btn__dot {
+  width: 12rpx;
+  height: 12rpx;
+  border-radius: 50%;
+  background: $uni-text-color-inverse;
+  animation: btn-dot-bounce 1.1s ease-in-out infinite;
+}
+.base-primary-btn__dot:nth-child(2) { animation-delay: 0.16s; }
+.base-primary-btn__dot:nth-child(3) { animation-delay: 0.32s; }
+.base-primary-btn__label {
+  color: inherit;
+}
+</style>
+
+<style>
+@keyframes btn-dot-bounce {
+  0%, 80%, 100% {
+    transform: scale(0.6);
+    opacity: 0.4;
+  }
+  40% {
+    transform: scale(1);
+    opacity: 1;
+  }
+}
+</style>

+ 173 - 0
cfc-frontend/components/ConfigurableGuide.vue

@@ -0,0 +1,173 @@
+<template>
+  <view class="cg-overlay" v-if="show">
+    <view class="cg-card">
+      <!-- 顶部主题色条 -->
+      <view class="cg-topbar" :style="{ background: themeColor }"></view>
+
+      <!-- 步骤内容 -->
+      <view class="cg-content">
+        <!-- 单步弹窗:无 steps 时直接用 title/description/icon -->
+        <block v-if="!isMulti">
+          <text v-if="iconType === 0 && icon" class="cg-icon">{{ icon }}</text>
+          <image v-if="iconType === 1 && icon" class="cg-img" :src="icon" mode="aspectFit" />
+          <text class="cg-title">{{ title }}</text>
+          <text class="cg-desc">{{ description }}</text>
+        </block>
+
+        <!-- 多步向导:steps 数组渲染 -->
+        <block v-else>
+          <text v-if="currentStepObj.iconType === 0 && currentStepObj.icon" class="cg-icon">{{ currentStepObj.icon }}</text>
+          <image v-if="currentStepObj.iconType === 1 && currentStepObj.icon" class="cg-img" :src="currentStepObj.icon" mode="aspectFit" />
+          <text class="cg-title" :class="{ 'cg-title--intro': currentStepObj.isIntro }">{{ currentStepObj.title }}</text>
+          <text class="cg-desc">{{ currentStepObj.desc }}</text>
+        </block>
+      </view>
+
+      <!-- 步进器(仅多步) -->
+      <view class="cg-dots" v-if="isMulti">
+        <view v-for="(s, i) in steps" :key="i" class="cg-dot" :class="{ 'cg-dot--active': i === currentStep }"></view>
+      </view>
+
+      <!-- 按钮 -->
+      <view class="cg-action">
+        <view class="cg-btn" :style="{ background: themeColor }" @click="handleClick">
+          <text>{{ btnLabel }}</text>
+        </view>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script>
+import { BrandColors } from '../utils/brand-colors.js'
+export default {
+  name: 'ConfigurableGuide',
+  props: {
+    popup: { type: Object, default: null },
+    show: { type: Boolean, default: false }
+  },
+  data() {
+    return {
+      currentStep: 0
+    }
+  },
+  computed: {
+    isMulti() {
+      return this.popup && this.popup.steps && this.popup.steps.length > 0
+    },
+    title() { return this.popup && this.popup.title ? this.popup.title : '' },
+    description() { return this.popup && this.popup.description ? this.popup.description : '' },
+    icon() { return this.popup && this.popup.icon ? this.popup.icon : '' },
+    iconType() { return this.popup && this.popup.iconType !== undefined ? this.popup.iconType : 0 },
+    themeColor() { return this.popup && this.popup.themeColor ? this.popup.themeColor : BrandColors.primary },
+    steps() { return this.isMulti ? this.popup.steps : [] },
+    currentStepObj() {
+      if (!this.isMulti) return {}
+      return this.steps[this.currentStep] || {}
+    },
+    btnLabel() {
+      if (!this.isMulti) {
+        return this.popup && this.popup.btnText ? this.popup.btnText : '知道了'
+      }
+      var isLast = this.currentStep >= this.steps.length - 1
+      if (isLast) {
+        return this.popup && this.popup.btnText ? this.popup.btnText : '开始体验'
+      }
+      return this.currentStepObj.btnText || '下一步'
+    }
+  },
+  watch: {
+    show(val) {
+      if (val) this.currentStep = 0
+    }
+  },
+  methods: {
+    handleClick() {
+      if (this.isMulti && this.currentStep < this.steps.length - 1) {
+        this.currentStep++
+        return
+      }
+      // 最后一步 / 单步:跳转 + 消费
+      var action = ''
+      if (this.isMulti) {
+        action = this.currentStepObj.btnAction || this.popup.btnAction || ''
+      } else {
+        action = this.popup.btnAction || ''
+      }
+      this.$emit('done', { popup: this.popup, btnAction: action, buttonClicked: true })
+    },
+    handleClose() {
+      this.$emit('done', { popup: this.popup, btnAction: '', buttonClicked: false })
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.cg-overlay {
+  position: fixed;
+  top: 0;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  background: rgba(0, 0, 0, 0.5);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  z-index: 9998;
+}
+.cg-card {
+  width: 640rpx;
+  min-height: 560rpx;
+  background: $app-surface;
+  border-radius: 24rpx;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  overflow: hidden;
+}
+.cg-topbar { width: 100%; height: 12rpx; flex-shrink: 0; }
+.cg-content {
+  flex: 1;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  padding: 72rpx 56rpx 40rpx;
+}
+.cg-icon { font-size: calc(80rpx * var(--font-scale, 1)); margin-bottom: 32rpx; display: block; }
+.cg-img { width: 160rpx; height: 160rpx; margin-bottom: 32rpx; }
+.cg-title {
+  font-size: calc(36rpx * var(--font-scale, 1));
+  font-weight: 700;
+  color: $uni-text-color;
+  text-align: center;
+  margin-bottom: 20rpx;
+  display: block;
+  line-height: 1.3;
+}
+.cg-title--intro { font-size: calc(32rpx * var(--font-scale, 1)); font-weight: 700; }
+.cg-desc {
+  font-size: calc(28rpx * var(--font-scale, 1));
+  color: $uni-text-color-secondary;
+  text-align: center;
+  line-height: 1.6;
+  display: block;
+  padding: 0 16rpx;
+}
+.cg-dots { display: flex; align-items: center; justify-content: center; padding: 0 56rpx 32rpx; }
+.cg-dot { width: 14rpx; height: 14rpx; border-radius: 50%; background: $uni-border-color; margin: 0 8rpx; }
+.cg-dot--active { background: $brand-primary; transform: scale(1.3); }
+.cg-action { width: 100%; padding: 0 56rpx 48rpx; box-sizing: border-box; }
+.cg-btn {
+  width: 100%;
+  height: 88rpx;
+  border-radius: 999rpx;
+  color: $app-surface;
+  font-size: calc(32rpx * var(--font-scale, 1));
+  font-weight: 700;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+</style>

+ 850 - 0
cfc-frontend/components/ContentSharePoster.vue

@@ -0,0 +1,850 @@
+<template>
+  <view class="poster-overlay" v-if="show" @click.self="$emit('close')">
+    <view class="poster-container">
+      <canvas canvas-id="contentPosterCanvas" class="poster-canvas" id="contentPosterCanvas"></canvas>
+      <!-- 模板选择(管理端定义的模板;未配置任何模板时不显示选择行) -->
+      <view class="poster-tpl-row" v-if="serverTemplates.length > 0">
+        <view class="tpl-label">海报模板</view>
+        <view class="tpl-options">
+          <view
+            v-for="tpl in serverTemplates"
+            :key="getTplKey(tpl)"
+            class="tpl-option"
+            :class="{ 'tpl-active': activeTemplateId === tpl.id }"
+            @click="switchTemplate(tpl)"
+          >
+            <view class="tpl-dot" :style="{ background: tpl.mainColor }"></view>
+            <text class="tpl-text">{{ tpl.name }}</text>
+          </view>
+        </view>
+      </view>
+      <!-- 背景颜色选择(渐变模板可用) -->
+      <view class="poster-bg-row" v-if="template === 'gradient'">
+        <view class="tpl-label">背景色</view>
+        <view class="bg-options">
+          <view
+            v-for="(c, i) in bgOptions"
+            :key="getBgKey(i)"
+            class="bg-option"
+            :class="{ 'bg-active': bgColor === c }"
+            :style="{ background: c }"
+            @click="switchBgColor(c)"
+          ></view>
+        </view>
+      </view>
+      <view class="poster-actions">
+        <button class="poster-btn save" @click="savePoster">保存到相册</button>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script>
+import { body, primary, primaryPale, success, white, wisdom, BrandColors } from '@/utils/brand-colors.js'
+import { getFontScale } from '@/utils/fontScale.js'
+
+export default {
+  name: 'ContentSharePoster',
+  props: {
+    show: { type: Boolean, default: false },
+    title: { type: String, default: '' },
+    coverImage: { type: String, default: '' },
+    qrCodeBase64: { type: String, default: '' },
+    typeLabel: { type: String, default: '好物推荐' },
+    dimensionCode: { type: String, default: '' },
+    summary: { type: String, default: '' },
+    priceText: { type: String, default: '' },
+    ctaText: { type: String, default: '长按识别二维码 · 查看详情' },
+    inviteText: { type: String, default: '' },
+    // 海报模板: gradient(default) | minimal | card
+    template: { type: String, default: 'gradient' },
+    // 自定义背景色(覆盖模板默认背景)
+    bgColor: { type: String, default: '' },
+    // 二维码尺寸覆盖(默认150rpx,建议活动类可用 100 缩小)
+    qrSizeOverride: { type: Number, default: 150 },
+    // 五维能量数据卡:{ label?: String, overall?: Number, dims: [{ key, label, score, color }] }
+    // 传 null 时不画数据卡,按 coverImage -> brandFallback -> 占位图 顺序降级(原有行为不变)
+    energyData: { type: Object, default: null },
+    // 无 energyData 且 coverImage 为空时,是否用品牌渐变卡替代"暂无封面图"占位
+    brandFallback: { type: Boolean, default: false },
+    // Web 管理端定义的模板列表([{id, name, templateKey, mainColor, darkColor, lightColor, bgColors, qrSize}])
+    // 传空数组时使用内置三套模板(原有行为不变)
+    templates: { type: Array, default: () => [] }
+  },
+  watch: {
+    show(val) {
+      if (val) {
+        this.$nextTick(function() {
+          setTimeout(this.drawPoster.bind(this), 300)
+        }.bind(this))
+      }
+    },
+    // 模板列表异步到达:无选中或选中项已失效时默认选第一个,并通过 emit 同步父页面
+    templates: {
+      immediate: true,
+      handler: function(list) {
+        if (this.serverTemplates.length === 0) return
+        if (!this.getActiveTemplate()) {
+          this.applyTemplate(this.serverTemplates[0])
+        }
+      }
+    }
+  },
+  computed: {
+    serverTemplates: function() {
+      var list = this.templates || []
+      var out = []
+      for (var i = 0; i < list.length; i++) {
+        if (list[i] && list[i].id) out.push(list[i])
+      }
+      return out
+    },
+    // 当前选中的管理端模板(无则为 null)
+    activeTemplate: function() {
+      if (!this.activeTemplateId) return null
+      var list = this.serverTemplates
+      for (var i = 0; i < list.length; i++) {
+        if (String(list[i].id) === String(this.activeTemplateId)) return list[i]
+      }
+      return null
+    },
+    // 背景色板:优先用管理端模板的配置,其次用内置七色
+    bgOptions: function() {
+      var tpl = this.activeTemplate
+      if (tpl && tpl.bgColors) {
+        try {
+          var arr = JSON.parse(tpl.bgColors)
+          if (arr && arr.length > 0) return arr
+        } catch (e) {}
+      }
+      return this.bgColors
+    },
+    // 二维码尺寸:管理端模板配置优先,其次 qrSizeOverride prop
+    effectiveQrSize: function() {
+      var tpl = this.activeTemplate
+      if (tpl && tpl.qrSize && tpl.qrSize > 0) return tpl.qrSize
+      return this.qrSizeOverride || 150
+    }
+  },
+  data() {
+    return {
+      // 选中的管理端模板 id(未使用管理端模板时为 null)
+      activeTemplateId: null,
+      // 可选的背景色(渐变模板下展示)
+      bgColors: [BrandColors.body, BrandColors.wisdom, BrandColors.wealth, BrandColors.success, BrandColors.mind, BrandColors.slate800, BrandColors.white]
+    }
+  },
+  methods: {
+    getTplKey(tpl) {
+      return 'tpl_' + tpl.id
+    },
+    getBgKey(i) {
+      return 'bg_' + i
+    },
+    // 海报画布文字按用户字号系数放大(画布有固定排版,放大区间比页面更保守,防止溢出裁切)
+    _fs(size) {
+      var scale = getFontScale()
+      if (!scale || scale < 0.9) scale = 0.9
+      if (scale > 1.25) scale = 1.25
+      return Math.round(size * scale)
+    },
+    // 选中的管理端模板(返回对象或 null)
+    getActiveTemplate: function() {
+      if (!this.activeTemplateId) return null
+      var list = this.serverTemplates
+      for (var i = 0; i < list.length; i++) {
+        if (String(list[i].id) === String(this.activeTemplateId)) return list[i]
+      }
+      return null
+    },
+    // 应用管理端模板:选中 + 同步模板类型/背景色到父页面(背景色取模板色板第一个)
+    applyTemplate: function(tpl) {
+      if (!tpl) return
+      this.activeTemplateId = tpl.id
+      this.$emit('update:template', tpl.templateKey)
+      var bg = tpl.mainColor
+      if (tpl.bgColors) {
+        try {
+          var arr = JSON.parse(tpl.bgColors)
+          if (arr && arr.length > 0) bg = arr[0]
+        } catch (e) {}
+      }
+      this.$emit('update:bgColor', bg)
+      var self = this
+      this.$nextTick(function() {
+        setTimeout(self.drawPoster.bind(self), 100)
+      })
+    },
+    // 海报模板配色(管理端模板配色优先,其次按维度取内置配色)
+    getColors: function() {
+      var tpl = this.getActiveTemplate()
+      if (tpl) {
+        return {
+          main: tpl.mainColor || BrandColors.primary,
+          dark: tpl.darkColor || BrandColors.orangeDeep,
+          light: tpl.lightColor || BrandColors.primaryPale
+        }
+      }
+      var map = {
+        body: { main: BrandColors.body, dark: BrandColors.orangeDeep, light: BrandColors.primaryPale },
+        mind: { main: BrandColors.mind, dark: BrandColors.pink600, light: BrandColors.pink50 },
+        wisdom: { main: BrandColors.wisdom, dark: BrandColors.indigo600, light: BrandColors.indigo50 },
+        action: { main: BrandColors.success, dark: '#059669', light: BrandColors.emerald50 },
+        wealth: { main: BrandColors.wealth, dark: '#D97706', light: BrandColors.amber50 }
+      }
+      return map[this.dimensionCode] || { main: BrandColors.primary, dark: BrandColors.orangeDeep, light: BrandColors.primaryPale }
+    },
+    // 海报模板配色
+    getTemplateConfig() {
+      var colors = this.getColors()
+      var template = this.template || 'gradient'
+      var bgColor = this.bgColor || ''
+      // 梯度背景模板
+      if (template === 'gradient') {
+        return { template: 'gradient', bgColor: bgColor || colors.main, main: colors.main, dark: colors.dark, light: colors.light }
+      }
+      // 极简模板:深色背景+白色卡片(管理端模板的 darkColor 作为默认底色)
+      if (template === 'minimal') {
+        var tpl = this.getActiveTemplate()
+        var dark = tpl ? (bgColor || colors.dark) : (bgColor || BrandColors.slate800)
+        return { template: 'minimal', bgColor: dark, main: colors.main, dark: colors.dark, light: colors.light }
+      }
+      // 卡片模板:浅色背景+彩色顶栏
+      return { template: 'card', bgColor: bgColor || BrandColors.white, main: colors.main, dark: colors.dark, light: colors.light }
+    },
+    // 获取当前模板的背景样式
+    getBgStyle() {
+      var cfg = this.getTemplateConfig()
+      if (cfg.template === 'gradient') {
+        var dark = cfg.dark
+        return 'linear-gradient(135deg, ' + cfg.main + ', ' + dark + ')'
+      }
+      if (cfg.template === 'minimal') {
+        return 'linear-gradient(135deg, ' + cfg.bgColor + ', ' + cfg.dark + ')'
+      }
+      return 'linear-gradient(135deg, ' + cfg.main + ', ' + (cfg.bgColor || BrandColors.white) + ')'
+    },
+    drawPoster() {
+      var self = this
+      uni.createSelectorQuery().in(this)
+        .select('#contentPosterCanvas')
+        .boundingClientRect(function(rect) {
+          var scaleX = 1
+          var scaleY = 1
+          if (rect && rect.width && rect.height) {
+            scaleX = rect.width / 500
+            scaleY = rect.height / 800
+          }
+          self._renderPoster(scaleX, scaleY)
+        })
+        .exec()
+    },
+
+    _renderPoster(scaleX, scaleY) {
+      var ctx = uni.createCanvasContext('contentPosterCanvas', this)
+      var w = 500
+      var h = 800
+      var cfg = this.getTemplateConfig()
+
+      // 画布 CSS 用 rpx,实际像素随设备变化(375px 屏约 310x496),而绘制按 500x800 设计坐标;
+      // 不缩放坐标系时右侧/底部内容(含二维码 y≈552-702)会被裁剪出画布,导致海报显示不全。
+      if (scaleX !== 1 || scaleY !== 1) {
+        ctx.scale(scaleX, scaleY)
+      }
+
+      // 【模板1 · gradient】渐变背景
+      if (cfg.template === 'gradient') {
+        var gradient = ctx.createLinearGradient(0, 0, w * 0.3, h)
+        gradient.addColorStop(0, cfg.main)
+        gradient.addColorStop(0.55, cfg.dark)
+        gradient.addColorStop(1, cfg.dark)
+        ctx.setFillStyle(gradient)
+        ctx.fillRect(0, 0, w, h)
+      }
+      // 【模板2 · minimal】纯色深色背景
+      else if (cfg.template === 'minimal') {
+        ctx.setFillStyle(cfg.bgColor)
+        ctx.fillRect(0, 0, w, h)
+      }
+      // 【模板3 · card】白色背景
+      else {
+        ctx.setFillStyle(BrandColors.white)
+        ctx.fillRect(0, 0, w, h)
+      }
+
+      this._drawTopDecoration(ctx, w, cfg)
+
+      var cardX = 28
+      var cardY = 112
+      var cardW = 444
+      var cardH = 600
+      this._drawContentCard(ctx, cardX, cardY, cardW, cardH, cfg)
+
+      var coverY = cardY + 20
+      var coverW = cardW - 40
+      var coverH = 220
+      var self = this
+
+      if (this.energyData) {
+        // 方案C:五维能量数据卡,canvas 直接绘制(文字锐利、数据真实、无网络开销)
+        this._drawEnergyCard(ctx, cardX + 20, coverY, coverW, coverH, cfg)
+        this._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+      } else if (this.coverImage) {
+        uni.downloadFile({
+          url: this.coverImage,
+          success: function(res) {
+            if (res.statusCode === 200) {
+              // 按原比例绘制封面图(contain 居中),避免拉伸变形
+              uni.getImageInfo({
+                src: res.tempFilePath,
+                success: function(info) {
+                  var rect = self._fitCoverRect(info.width, info.height, cardX + 20, coverY, coverW, coverH)
+                  ctx.drawImage(res.tempFilePath, rect.x, rect.y, rect.w, rect.h)
+                  self._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+                },
+                fail: function() {
+                  ctx.drawImage(res.tempFilePath, cardX + 20, coverY, coverW, coverH)
+                  self._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+                }
+              })
+            } else {
+              self._drawCoverPlaceholder(ctx, cardX + 20, coverY, coverW, coverH)
+              self._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+            }
+          },
+          fail: function() {
+            self._drawCoverPlaceholder(ctx, cardX + 20, coverY, coverW, coverH)
+            self._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+          }
+        })
+      } else if (this.brandFallback) {
+        this._drawBrandCard(ctx, cardX + 20, coverY, coverW, coverH, cfg)
+        this._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+      } else {
+        this._drawCoverPlaceholder(ctx, cardX + 20, coverY, coverW, coverH)
+        this._drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, cfg)
+      }
+    },
+
+    _fitCoverRect(imgW, imgH, boxX, boxY, boxW, boxH) {
+      if (!imgW || !imgH) {
+        return { x: boxX, y: boxY, w: boxW, h: boxH }
+      }
+      var scale = Math.min(boxW / imgW, boxH / imgH)
+      var w = imgW * scale
+      var h = imgH * scale
+      return {
+        x: boxX + (boxW - w) / 2,
+        y: boxY + (boxH - h) / 2,
+        w: w,
+        h: h
+      }
+    },
+
+    _drawTopDecoration(ctx, w, colors) {
+      var centerX = w / 2
+      var dotColors = [BrandColors.body, BrandColors.wisdom, BrandColors.wealth, BrandColors.success, BrandColors.mind]
+      var dotY = 28
+      var dotR = 5
+      var dotSpacing = 26
+      var i, offsetX, offsetY
+
+      for (i = 0; i < 5; i++) {
+        offsetX = (i - 2) * dotSpacing
+        offsetY = Math.abs(i - 2) * 3
+        ctx.setFillStyle(dotColors[i])
+        ctx.beginPath()
+        ctx.arc(centerX + offsetX, dotY + offsetY, dotR, 0, 2 * Math.PI)
+        ctx.fill()
+      }
+
+      ctx.setFillStyle(BrandColors.white)
+      ctx.setFontSize(this._fs(20))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText('浠艾福', centerX, 52)
+
+      ctx.setFontSize(this._fs(14))
+      ctx.setFillStyle('rgba(255,255,255,0.8)')
+      ctx.fillText('给全家的一站式幸福提案', centerX, 76)
+
+      ctx.setStrokeStyle('rgba(255,255,255,0.25)')
+      ctx.setLineWidth(1)
+      ctx.beginPath()
+      ctx.moveTo(80, 100)
+      ctx.lineTo(w - 80, 100)
+      ctx.stroke()
+    },
+
+    _drawContentCard(ctx, x, y, w, h, colors) {
+      ctx.setFillStyle('rgba(0,0,0,0.04)')
+      this._roundRect(ctx, x + 2, y + 3, w, h, 16)
+      ctx.fill()
+
+      ctx.setFillStyle(colors.light)
+      this._roundRect(ctx, x, y, w, h, 16)
+      ctx.fill()
+    },
+
+    _drawCoverPlaceholder(ctx, x, y, w, h) {
+      ctx.setFillStyle('#FEF3C7')
+      this._roundRect(ctx, x, y, w, h, 8)
+      ctx.fill()
+
+      ctx.setFillStyle(BrandColors.primary)
+      ctx.setFontSize(this._fs(16))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('middle')
+      ctx.fillText('暂无封面图', x + w / 2, y + h / 2)
+    },
+
+    // 五维能量数据卡(方案C):综合分大字 + 五维彩色圆/分数/进度条
+    _drawEnergyCard(ctx, x, y, w, h, colors) {
+      var data = this.energyData || {}
+      var dims = data.dims || []
+
+      ctx.setFillStyle(BrandColors.white)
+      this._roundRect(ctx, x, y, w, h, 8)
+      ctx.fill()
+
+      // 顶部:左侧标题,右侧综合分
+      ctx.setFillStyle(BrandColors.stone500)
+      ctx.setFontSize(this._fs(13))
+      ctx.setTextAlign('left')
+      ctx.setTextBaseline('top')
+      ctx.fillText(data.label || '我们家的能量', x + 16, y + 16)
+
+      var hasOverall = data.overall !== null && data.overall !== undefined && !isNaN(data.overall)
+      if (hasOverall) {
+        ctx.setFillStyle(colors.main)
+        ctx.setFontSize(this._fs(30))
+        ctx.setTextAlign('right')
+        ctx.fillText(String(data.overall), x + w - 28, y + 8)
+        ctx.setFillStyle(BrandColors.stone500)
+        ctx.setFontSize(this._fs(13))
+        ctx.fillText('分', x + w - 16, y + 28)
+      }
+
+      ctx.setStrokeStyle(BrandColors.stone100)
+      ctx.setLineWidth(1)
+      ctx.beginPath()
+      ctx.moveTo(x + 16, y + 54)
+      ctx.lineTo(x + w - 16, y + 54)
+      ctx.stroke()
+
+      // 五维柱:彩色圆 + 单字 + 分数 + 进度条
+      var count = dims.length
+      for (var i = 0; i < count; i++) {
+        var d = dims[i] || {}
+        var cx = x + 16 + ((w - 32) / count) * i + (w - 32) / count / 2
+        var color = d.color || colors.main
+        var score = Number(d.score)
+        if (isNaN(score) || score < 0) score = 0
+        if (score > 100) score = 100
+
+        ctx.setFillStyle(color)
+        ctx.beginPath()
+        ctx.arc(cx, y + 94, 17, 0, 2 * Math.PI)
+        ctx.fill()
+
+        ctx.setFillStyle(BrandColors.white)
+        ctx.setFontSize(this._fs(15))
+        ctx.setTextAlign('center')
+        ctx.setTextBaseline('middle')
+        ctx.fillText(d.label || '', cx, y + 95)
+
+        ctx.setFillStyle(BrandColors.stone900)
+        ctx.setFontSize(this._fs(18))
+        ctx.setTextBaseline('top')
+        ctx.fillText(String(score), cx, y + 120)
+
+        var barW = 44
+        var barH = 4
+        var barX = cx - barW / 2
+        var barY = y + 148
+        ctx.setFillStyle(BrandColors.stone100)
+        this._roundRect(ctx, barX, barY, barW, barH, 2)
+        ctx.fill()
+        if (score > 0) {
+          ctx.setFillStyle(color)
+          this._roundRect(ctx, barX, barY, barW * score / 100, barH, 2)
+          ctx.fill()
+        }
+      }
+
+      ctx.setFillStyle(BrandColors.stone400)
+      ctx.setFontSize(this._fs(11))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText('五维能量 · 浠艾福家庭测评', x + w / 2, y + 172)
+    },
+
+    // 品牌渐变卡:用户未解锁全景(无五维数据)且无封面图时的降级方案
+    _drawBrandCard(ctx, x, y, w, h, colors) {
+      var g = ctx.createLinearGradient(x, y, x + w, y + h)
+      g.addColorStop(0, colors.main)
+      g.addColorStop(1, colors.dark)
+      ctx.setFillStyle(g)
+      this._roundRect(ctx, x, y, w, h, 8)
+      ctx.fill()
+
+      var dotColors = [BrandColors.body, BrandColors.wisdom, BrandColors.wealth, BrandColors.success, BrandColors.mind]
+      var centerX = x + w / 2
+      for (var i = 0; i < 5; i++) {
+        ctx.setFillStyle(dotColors[i])
+        ctx.beginPath()
+        ctx.arc(centerX + (i - 2) * 26, y + 66, 5, 0, 2 * Math.PI)
+        ctx.fill()
+      }
+
+      ctx.setFillStyle(BrandColors.white)
+      ctx.setFontSize(this._fs(24))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText('浠艾福', centerX, y + 86)
+
+      ctx.setFillStyle('rgba(255,255,255,0.85)')
+      ctx.setFontSize(this._fs(13))
+      ctx.fillText('给全家的一站式幸福提案', centerX, y + 124)
+
+      ctx.setFillStyle('rgba(255,255,255,0.7)')
+      ctx.setFontSize(this._fs(12))
+      ctx.fillText('测一测你家的五维能量', centerX, y + 152)
+    },
+
+    _drawContentAfterCover(ctx, w, h, cardX, cardW, coverY, coverH, colors) {
+      var self = this
+
+      var labelY = coverY + coverH + 16
+      ctx.setFillStyle(colors.main)
+      ctx.setFontSize(this._fs(13))
+      ctx.setTextAlign('left')
+      ctx.setTextBaseline('top')
+      ctx.fillText(this.typeLabel, cardX + 20, labelY)
+
+      // 标题(2行截断)
+      var titleY = labelY + 22
+      ctx.setFillStyle(BrandColors.stone900)
+      ctx.setFontSize(this._fs(18))
+      ctx.setTextAlign('left')
+      ctx.setTextBaseline('top')
+      this._drawWrappedText(ctx, this.title || '精彩内容', cardX + 20, titleY, cardW - 40, this._fs(24), 2)
+
+      // 价格行(商品用;空则跳过)
+      var priceY = titleY + 56
+      if (this.priceText) {
+        ctx.setFillStyle(colors.main)
+        ctx.setFontSize(this._fs(17))
+        ctx.setTextAlign('left')
+        ctx.setTextBaseline('top')
+        ctx.fillText(this.priceText, cardX + 20, priceY)
+      }
+
+      // 简介(1-2行灰字;空则跳过)
+      var summaryY = (this.priceText ? priceY + 34 : priceY)
+      if (this.summary) {
+        ctx.setFillStyle(BrandColors.stone500)
+        ctx.setFontSize(this._fs(13))
+        ctx.setTextAlign('left')
+        ctx.setTextBaseline('top')
+        this._drawWrappedText(ctx, this.summary, cardX + 20, summaryY, cardW - 40, this._fs(20), 2)
+      }
+
+      // 邀请语(二维码上方)
+      var inviteY = (this.summary ? summaryY + 48 : summaryY)
+      ctx.setFillStyle(BrandColors.stone400)
+      ctx.setFontSize(this._fs(13))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText(this.inviteText || '长按识别二维码 · 查看详情', w / 2, inviteY)
+
+      // 二维码 - 可配置尺寸(管理端模板 qrSize 优先,其次 qrSizeOverride prop,默认150)
+      var qrSize = this.effectiveQrSize
+      var qrX = (w - qrSize) / 2
+      var qrY = inviteY + 24
+
+      if (this.qrCodeBase64) {
+        var base64Data = this.qrCodeBase64
+        if (base64Data.indexOf('data:image') === 0) {
+          var commaIdx = base64Data.indexOf(',')
+          if (commaIdx > -1) {
+            base64Data = base64Data.substring(commaIdx + 1)
+          }
+        }
+
+        var fs = uni.getFileSystemManager()
+        var filePath = wx.env.USER_DATA_PATH + '/content_share_qr_tmp.png'
+
+        fs.writeFile({
+          filePath: filePath,
+          data: base64Data,
+          encoding: 'base64',
+          success: function() {
+            ctx.setFillStyle(BrandColors.white)
+            self._roundRect(ctx, qrX - 10, qrY - 10, qrSize + 20, qrSize + 20, 8)
+            ctx.fill()
+
+            ctx.setStrokeStyle(BrandColors.stone200)
+            ctx.setLineWidth(0.5)
+            self._roundRect(ctx, qrX - 10, qrY - 10, qrSize + 20, qrSize + 20, 8)
+            ctx.stroke()
+
+            ctx.drawImage(filePath, qrX, qrY, qrSize, qrSize)
+            self._drawBottomDecoration(ctx, w, h, qrY, qrSize, colors)
+          },
+          fail: function() {
+            self._drawQrPlaceholder(ctx, qrX, qrY, qrSize)
+            self._drawBottomDecoration(ctx, w, h, qrY, qrSize, colors)
+          }
+        })
+      } else {
+        this._drawQrPlaceholder(ctx, qrX, qrY, qrSize)
+        this._drawBottomDecoration(ctx, w, h, qrY, qrSize, colors)
+      }
+    },
+
+    _drawWrappedText(ctx, text, x, y, maxWidth, lineHeight, maxLines) {
+      var chars = (text || '').split('')
+      var line = ''
+      var lineCount = 0
+      for (var i = 0; i < chars.length; i++) {
+        var testLine = line + chars[i]
+        var testWidth = this._textWidth(ctx, testLine)
+        if (testWidth > maxWidth && line.length > 0) {
+          ctx.fillText(line, x, y + lineCount * lineHeight)
+          line = chars[i]
+          lineCount++
+          if (lineCount >= maxLines - 1) {
+            var remaining = chars.slice(i).join('')
+            var remainingLine = line + remaining
+            while (this._textWidth(ctx, remainingLine + '..') > maxWidth && remainingLine.length > 2) {
+              remainingLine = remainingLine.substring(0, remainingLine.length - 1)
+            }
+            ctx.fillText(remainingLine + '..', x, y + lineCount * lineHeight)
+            return
+          }
+        } else {
+          line = testLine
+        }
+      }
+      ctx.fillText(line, x, y + lineCount * lineHeight)
+    },
+
+    _textWidth(ctx, text) {
+      if (ctx.measureText) {
+        try { return ctx.measureText(text).width } catch (e) { return (text || '').length * 18 }
+      }
+      return (text || '').length * 18
+    },
+
+    _drawQrPlaceholder(ctx, x, y, size) {
+      ctx.setFillStyle(BrandColors.white)
+      this._roundRect(ctx, x - 10, y - 10, size + 20, size + 20, 8)
+      ctx.fill()
+
+      ctx.setStrokeStyle(BrandColors.stone200)
+      ctx.setLineWidth(0.5)
+      this._roundRect(ctx, x - 10, y - 10, size + 20, size + 20, 8)
+      ctx.stroke()
+
+      ctx.setFillStyle(BrandColors.stone400)
+      ctx.setFontSize(this._fs(16))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('middle')
+      ctx.fillText('二维码加载中', x + size / 2, y + size / 2)
+    },
+
+    _drawBottomDecoration(ctx, w, h, qrY, qrSize, colors) {
+      var centerX = w / 2
+      var bottomY = qrY + qrSize + 16
+
+      var diamondY = bottomY + 6
+      ctx.setFillStyle('rgba(0,0,0,0.06)')
+      ctx.beginPath()
+      ctx.moveTo(centerX - 76, diamondY)
+      ctx.lineTo(centerX - 72, diamondY - 4)
+      ctx.lineTo(centerX - 68, diamondY)
+      ctx.lineTo(centerX - 72, diamondY + 4)
+      ctx.closePath()
+      ctx.fill()
+      ctx.beginPath()
+      ctx.moveTo(centerX + 68, diamondY)
+      ctx.lineTo(centerX + 72, diamondY - 4)
+      ctx.lineTo(centerX + 76, diamondY)
+      ctx.lineTo(centerX + 72, diamondY + 4)
+      ctx.closePath()
+      ctx.fill()
+
+      ctx.setFillStyle(colors.main)
+      ctx.setFontSize(this._fs(18))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText(this.ctaText || '长按识别二维码 · 查看详情', centerX, bottomY)
+
+      var dotColors = [BrandColors.body, BrandColors.wisdom, BrandColors.wealth, BrandColors.success, BrandColors.mind]
+      var dotY = h - 22
+      var dotR = 4
+      var dotSpacing = 20
+      var i_b, offsetX_b
+
+      for (i_b = 0; i_b < 5; i_b++) {
+        offsetX_b = (i_b - 2) * dotSpacing
+        ctx.setFillStyle(dotColors[i_b])
+        ctx.beginPath()
+        ctx.arc(centerX + offsetX_b, dotY, dotR, 0, 2 * Math.PI)
+        ctx.fill()
+      }
+
+      ctx.setFillStyle('rgba(255,255,255,0.45)')
+      ctx.setFontSize(this._fs(12))
+      ctx.setTextAlign('center')
+      ctx.setTextBaseline('top')
+      ctx.fillText('浠艾福 · 家庭健康俱乐部', centerX, dotY + 7)
+
+      ctx.draw()
+    },
+
+    _roundRect(ctx, x, y, w, h, r) {
+      ctx.beginPath()
+      ctx.moveTo(x + r, y)
+      ctx.arcTo(x + w, y, x + w, y + r, r)
+      ctx.arcTo(x + w, y + h, x + w - r, y + h, r)
+      ctx.arcTo(x, y + h, x, y + h - r, r)
+      ctx.arcTo(x, y, x + r, y, r)
+      ctx.closePath()
+    },
+
+    switchTemplate(tpl) {
+      // 仅支持管理端定义模板(对象);未配置模板时无选择行,不会触发
+      if (!tpl || typeof tpl !== 'object') return
+      this.applyTemplate(tpl)
+    },
+    switchBgColor(color) {
+      this.$emit('update:bgColor', color)
+      var self = this
+      this.$nextTick(function() {
+        setTimeout(self.drawPoster.bind(self), 100)
+      })
+    },
+
+    savePoster() {
+      var self = this
+      uni.canvasToTempFilePath({
+        canvasId: 'contentPosterCanvas',
+        destWidth: 500,
+        destHeight: 800,
+        success: function(res) {
+          uni.saveImageToPhotosAlbum({
+            filePath: res.tempFilePath,
+            success: function() {
+              uni.showToast({ title: '已保存到相册', icon: 'success' })
+              self.$emit('close')
+            },
+            fail: function(err) {
+              if (err && err.errMsg && (err.errMsg.indexOf('deny') > -1 || err.errMsg.indexOf('auth denied') > -1 || err.errMsg.indexOf('authorize') > -1)) {
+                uni.showModal({
+                  title: '提示',
+                  content: '需要相册权限才能保存图片',
+                  confirmText: '去设置',
+                  success: function(modalRes) {
+                    if (modalRes.confirm) {
+                      uni.openSetting()
+                    }
+                  }
+                })
+              } else {
+                uni.showToast({ title: '保存失败,请重试', icon: 'none' })
+              }
+            }
+          })
+        },
+        fail: function() {
+          uni.showToast({ title: '生成图片失败', icon: 'none' })
+        }
+      }, this)
+    }
+  }
+}
+</script>
+<style scoped lang="scss">
+.poster-overlay {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  background: rgba(0, 0, 0, 0.6);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  z-index: 999;
+}
+.poster-container {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+}
+.poster-canvas {
+  width: 620rpx;
+  height: 992rpx;
+  margin-bottom: 80rpx;
+  border-radius: 16rpx;
+}
+.poster-actions {
+  display: flex;
+  flex-direction: column;
+  width: 620rpx;
+  margin-top: $uni-space-lg;
+}
+.poster-btn {
+  height: 80rpx;
+  line-height: 80rpx;
+  font-size: calc(30rpx * var(--font-scale, 1));
+  border-radius: 24rpx;
+  text-align: center;
+  border: none;
+}
+.poster-btn::after { border: none; }
+.poster-btn.save {
+  background: $app-surface;
+  color: $brand-primary;
+  font-weight: 600;
+}
+.poster-btn.save:active { opacity: 0.85; }
+.poster-tpl-row {
+  display: flex;
+  align-items: center;
+  margin: 12rpx 0;
+  font-size: calc(24rpx * var(--font-scale, 1));
+}
+.tpl-label {
+  margin-right: 20rpx;
+  color: $facade-text-body;
+}
+.tpl-options {
+  display: flex;
+}
+.tpl-option {
+  flex: 1;
+  margin: 0 4rpx;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  cursor: pointer;
+}
+.tpl-dot {
+  width: 24rpx;
+  height: 24rpx;
+  border-radius: 999rpx;
+  margin-bottom: 4rpx;
+  border: 1rpx solid rgba(0, 0, 0, 0.08);
+  box-sizing: border-box;
+}
+.tpl-text {
+  font-size: calc(14rpx * var(--font-scale, 1));
+  text-align: center;
+  color: $facade-text-body;
+}
+.tpl-active .tpl-text { color: $brand-primary; }
+
+</style>

Некоторые файлы не были показаны из-за большого количества измененных файлов