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

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

Agnes Agent 1 день назад
Родитель
Сommit
c2a2d271c5
100 измененных файлов с 19645 добавлено и 0 удалено
  1. 35 0
      cfc-backend/src/test/java/com/etotem/cfc/common/TestRoles.java
  2. 221 0
      cfc-backend/src/test/java/com/etotem/cfc/config/AttributionStage1FoundationTest.java
  3. 125 0
      cfc-backend/src/test/java/com/etotem/cfc/config/DatabaseInitializerSeedTest.java
  4. 241 0
      cfc-backend/src/test/java/com/etotem/cfc/config/FamilyAccessInterceptorTest.java
  5. 168 0
      cfc-backend/src/test/java/com/etotem/cfc/config/GrowthPublicEndpointMappingTest.java
  6. 316 0
      cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorContractEdgeTest.java
  7. 122 0
      cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorGrowthPolicyTest.java
  8. 129 0
      cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorLoginRequiredPathTest.java
  9. 106 0
      cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorLoginRequiredTest.java
  10. 130 0
      cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorWechatLoginTest.java
  11. 33 0
      cfc-backend/src/test/java/com/etotem/cfc/config/MyBatisPlusOptimisticLockerContractTest.java
  12. 303 0
      cfc-backend/src/test/java/com/etotem/cfc/config/ScG06JwtGuardTest.java
  13. 37 0
      cfc-backend/src/test/java/com/etotem/cfc/config/TasksFamilyCreatedIndexMigrationTest.java
  14. 103 0
      cfc-backend/src/test/java/com/etotem/cfc/config/WebConfigGrowthExcludeRemovedTest.java
  15. 145 0
      cfc-backend/src/test/java/com/etotem/cfc/context/MiniAppContextResolverTest.java
  16. 40 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/AttributionControllerTest.java
  17. 161 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/AttributionSurveyRoutingTest.java
  18. 520 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/AuthSessionMutexContractTest.java
  19. 270 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/AuthWechatLoginContractTest.java
  20. 384 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/BadgeControllerGetMemberBadgesTest.java
  21. 90 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/DanAssessmentControllerGetActiveMaterialTest.java
  22. 98 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/EnergyControllerGrantEnergyTest.java
  23. 194 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/FamilyEarningsAdminRoleGateTest.java
  24. 32 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/FamilyWorkbenchContractTest.java
  25. 231 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthCheckinCfEarnCallSiteTest.java
  26. 371 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthDimensionControllerUploadContractTest.java
  27. 158 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanControllerPlanTasksPermissionTest.java
  28. 95 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanDeleteControllerTest.java
  29. 249 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanProductSelectionContractTest.java
  30. 162 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerCreateReportTest.java
  31. 313 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerDeleteAuthzTest.java
  32. 151 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerListPaginationTest.java
  33. 82 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerProxyParseBindingTest.java
  34. 454 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerUploadTest.java
  35. 282 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/HealthSleepControllerContractTest.java
  36. 108 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/IndicatorControllerTest.java
  37. 171 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/IndicatorFavoriteControllerTest.java
  38. 85 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/MembershipControllerPlansLevelOrderTest.java
  39. 156 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ReportParserTypeLinksTest.java
  40. 143 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG01LandingContractTest.java
  41. 312 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG03LoginMethodContractTest.java
  42. 246 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG04InviteRegisterContractTest.java
  43. 193 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG05AnonymousBrowseContractTest.java
  44. 95 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG07TestModeContractTest.java
  45. 82 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG08EnvAdaptiveContractTest.java
  46. 131 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG09LogoutContractTest.java
  47. 174 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG10RegisterGuideContractTest.java
  48. 118 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG11AgreementContractTest.java
  49. 126 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ScG12H5FallbackContractTest.java
  50. 229 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/SurveyHealthReviewContractTest.java
  51. 182 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/TeamInvitationCreateContractTest.java
  52. 376 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleAuditContractTest.java
  53. 285 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleCreateContractTest.java
  54. 229 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleListContractTest.java
  55. 372 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthControllerLoginContractTest.java
  56. 250 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthControllerLoginStatusTest.java
  57. 249 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthWechatScanTest.java
  58. 139 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminButlerControllerEnvelopeTest.java
  59. 128 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminCommissionConfigControllerTest.java
  60. 69 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminCommissionConfigPartialUpdateTest.java
  61. 93 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminFamilyOverviewControllerTest.java
  62. 150 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminFamilyStatsContractTest.java
  63. 548 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminOrderManualContractTest.java
  64. 117 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminProductControllerBatchShelveTest.java
  65. 224 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminReferralContractTest.java
  66. 50 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminWorkbenchAuthContractTest.java
  67. 104 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/ReportParserAdminControllerTest.java
  68. 167 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/admin/SupplyTeamControllerInviteTest.java
  69. 315 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ai/AIChatControllerGateTest.java
  70. 161 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/ai/ButlerControllerGateTest.java
  71. 65 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/butler/ButlerControllerEnvelopeTest.java
  72. 180 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/config/SleepConfigTagsMechanismContractTest.java
  73. 159 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyInviteApproveRequestTest.java
  74. 223 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerAddMemberTest.java
  75. 147 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerListTest.java
  76. 69 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerRenameFamilyTest.java
  77. 210 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/growth/ChildGrowthArchiveContractTest.java
  78. 44 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/growth/GrowthAuthContractTest.java
  79. 291 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/growth/GrowthHistoryViewContractTest.java
  80. 61 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TeacherMessageControllerMyTest.java
  81. 200 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TrainingPlanControllerGetPlanDetailTest.java
  82. 230 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TrainingPlanControllerGetPlanListTest.java
  83. 267 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/reward/RewardEstimateControllerEstimateTest.java
  84. 321 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/reward/RewardEstimateControllerTest.java
  85. 85 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/shop/AfterSalesCancelControllerTest.java
  86. 138 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/stats/StatsControllerDashboardContractTest.java
  87. 221 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerCreateTaskTest.java
  88. 224 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerGetTaskHistoryTest.java
  89. 330 0
      cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerReviewTest.java
  90. 47 0
      cfc-backend/src/test/java/com/etotem/cfc/dto/ActivityDTOTest.java
  91. 403 0
      cfc-backend/src/test/java/com/etotem/cfc/e2e/WebAdminpanelRune2eContractTest.java
  92. 275 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/ArticleTagFilterContractTest.java
  93. 283 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/DailyCheckinStreakFlowTest.java
  94. 317 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/EnergySystemFlowTest.java
  95. 381 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/GrowthRecordSyncFlowTest.java
  96. 172 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/GuideModuleIntegrationTest.java
  97. 400 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/PlannerBindInviteFlowTest.java
  98. 383 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/controller/AIChatControllerTest.java
  99. 346 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/controller/ActivityControllerTest.java
  100. 45 0
      cfc-backend/src/test/java/com/etotem/cfc/integration/controller/AdminFamilyOverviewControllerTest.java

+ 35 - 0
cfc-backend/src/test/java/com/etotem/cfc/common/TestRoles.java

@@ -0,0 +1,35 @@
+package com.etotem.cfc.common;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * 测试角色常量与断言辅助方法。
+ * 系统四种角色: parent(家长), child(孩子), teacher(成长规划师), admin(管理员)
+ */
+public class TestRoles {
+
+    public static final String ROLE_PARENT = "parent";
+    public static final String ROLE_CHILD = "child";
+    public static final String ROLE_TEACHER = "teacher";
+    public static final String ROLE_ADMIN = "admin";
+
+    /** 所有非 teacher 角色,用于验证 teacher-only 接口的拒绝行为 */
+    public static final String[] NON_TEACHER_ROLES = {ROLE_PARENT, ROLE_CHILD, ROLE_ADMIN};
+
+    /** 全部四种角色 */
+    public static final String[] ALL_ROLES = {ROLE_PARENT, ROLE_CHILD, ROLE_TEACHER, ROLE_ADMIN};
+
+    /** 断言教师角色的操作成功 (code=200) */
+    public static void assertSuccess(Result<?> result) {
+        assertEquals(200, result.getCode(), "Expected success(200) for teacher role");
+    }
+
+    /** 断言非 teacher 角色的操作被拒绝:code=500, message 包含 "Access denied" */
+    public static void assertRoleDenied(Result<?> result) {
+        assertEquals(500, result.getCode(),
+            "Expected 500 for role denied but got " + result.getCode() + ": " + result.getMessage());
+        assertNotNull(result.getMessage(), "Expected error message");
+        assertTrue(result.getMessage().contains("Access denied"),
+            "Expected 'Access denied' but got: " + result.getMessage());
+    }
+}

+ 221 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/AttributionStage1FoundationTest.java

@@ -0,0 +1,221 @@
+package com.etotem.cfc.config;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * ATT-S1-A1/A2/A3:数据地基种子与迁移校验。
+ *
+ * <ul>
+ *   <li>A1:plan_type 迁移为幂等 ALTER ADD COLUMN</li>
+ *   <li>A2:家庭归因问卷模板种子按 title 判重,questionsJson 为 §3.2 扩展结构</li>
+ *   <li>A3:attribution_norm_values 建表含唯一键;常模种子按 data 行数幂等 upsert(S-cfc-426 填充后契约)</li>
+ * </ul>
+ */
+@ExtendWith(MockitoExtension.class)
+class AttributionStage1FoundationTest {
+
+    @Mock
+    private JdbcTemplate jdbcTemplate;
+
+    @InjectMocks
+    private DatabaseInitializer initializer;
+
+    private final ObjectMapper mapper = new ObjectMapper();
+
+    // ---------------- A1:plan_type 迁移 ----------------
+
+    @Test
+    void A1_planType迁移为幂等加列() {
+        initializer.migrateHealthPlansPlanType();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).execute(sql.capture());
+        assertTrue(sql.getValue().contains("ALTER TABLE health_plans ADD COLUMN plan_type"),
+                "应执行 health_plans.plan_type 幂等加列:" + sql.getValue());
+        assertTrue(sql.getValue().contains("DEFAULT 'health_plan'"), "plan_type 默认值应为 health_plan");
+        assertTrue(sql.getValue().contains("family_attribution_plan"), "plan_type 注释应含家庭归因方案枚举值");
+    }
+
+    // ---------------- A2:问卷模板种子 ----------------
+
+    @Test
+    void A2_模板已存在时幂等启用() {
+        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(1);
+
+        initializer.seedFamilyAttributionSurveyTemplate();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).update(sql.capture(), any(Object.class));
+        assertTrue(sql.getValue().contains("UPDATE survey_templates SET enabled = 1"),
+                "已存在时只幂等启用,不覆盖 questions_json:" + sql.getValue());
+    }
+
+    @Test
+    void A2_模板缺失时写入种子且JSON结构符合3_2() throws Exception {
+        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(0);
+
+        initializer.seedFamilyAttributionSurveyTemplate();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        ArgumentCaptor<Object> arg = ArgumentCaptor.forClass(Object.class);
+        verify(jdbcTemplate).update(sql.capture(), arg.capture(), arg.capture(), arg.capture(), arg.capture());
+
+        assertTrue(sql.getValue().contains("INSERT INTO survey_templates"), "应写入 survey_templates");
+        assertTrue(sql.getValue().contains("VALUES (?, ?, ?, ?, 0, 1, NOW(), NOW())"),
+                "模板种子应默认启用(enabled=1):" + sql.getValue());
+        List<Object> args = arg.getAllValues();
+        assertEquals(DatabaseInitializer.SURVEY_FAMILY_ATTRIBUTION_TITLE, args.get(0), "按 title 判重");
+        String questionsJson = (String) args.get(2);
+
+        JsonNode root = mapper.readTree(questionsJson);
+        assertEquals("1.1", root.get("schemaVersion").asText(), "应含 schemaVersion");
+        assertEquals("family_attribution", root.get("target").asText(), "target 应为 family_attribution");
+        JsonNode questions = root.get("questions");
+        assertNotNull(questions);
+        assertTrue(questions.isArray());
+        assertEquals(45, questions.size(), "第八章 16 条展开为 45 个采集项");
+
+        for (JsonNode q : questions) {
+            for (String field : new String[]{"id", "code", "group", "title", "type", "required", "riskLevel"}) {
+                assertTrue(q.has(field), "每题必须含字段 " + field + ":" + q.get("id"));
+            }
+            assertTrue(q.has("options") && q.has("unit") && q.has("condition") && q.has("refRange"),
+                    "每题必须含 options/unit/condition/refRange(可为 null):" + q.get("id"));
+            String risk = q.get("riskLevel").asText();
+            assertTrue("none".equals(risk) || "low".equals(risk) || "high".equals(risk),
+                    "riskLevel 枚举非法:" + q.get("id") + "=" + risk);
+        }
+
+        // 高风险题(Q11/Q12/Q13)必须标记 high(E4 弱提示)
+        for (JsonNode q : questions) {
+            String id = q.get("id").asText();
+            if (id.startsWith("Q11") || id.startsWith("Q12") || id.startsWith("Q13")) {
+                assertEquals("high", q.get("riskLevel").asText(), id + " 应为 high 风险级别");
+            }
+        }
+    }
+
+    @Test
+    void A2_种子文件本身可解析且含16条分组() throws Exception {
+        JsonNode root = mapper.readTree(
+                org.springframework.util.StreamUtils.copyToString(
+                        getClass().getResourceAsStream("/survey/family_attribution_questions.json"),
+                        java.nio.charset.StandardCharsets.UTF_8));
+        assertEquals("family_attribution", root.get("target").asText());
+        JsonNode questions = root.get("questions");
+        java.util.Set<String> groups = new java.util.LinkedHashSet<>();
+        for (JsonNode q : questions) {
+            groups.add(q.get("group").asText());
+        }
+        assertEquals(6, groups.size(), "应覆盖 四人/家长A/家长B/学员A/学员B/全家 6 个分组(O5 去实名):" + groups);
+        assertFalse(root.get("audience").isEmpty(), "应含 audience 列表");
+    }
+
+    // ---------------- A3:常模表与导入 ----------------
+
+    @Test
+    void A3_常模表建表语句含唯一键() {
+        initializer.createAttributionNormValuesTable();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).execute(sql.capture());
+        String ddl = sql.getValue();
+        assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS `attribution_norm_values`"), "应幂等建表");
+        assertTrue(ddl.contains("uk_type_code_band_gender_ver"), "应含唯一键 uk_type_code_band_gender_ver");
+        assertTrue(ddl.contains("`norm_type`") && ddl.contains("`member_age_band`") && ddl.contains("`gender`"),
+                "唯一键字段应齐全");
+    }
+
+    /**
+     * S-cfc-426(归因归一化真实数据填充管线)已把常模种子从「空壳模板」填充为真实数据(149 行,谷禾 17 份样本
+     * 回归估算)。原断言「placeholder=true + data 为空 + 导入 0 行」对应的是填充前的契约,故按新契约改写为:
+     * placeholder 与 data 双向一致、note 必须声明人群代表性限定、导入按 data 行数逐行幂等 upsert。
+     */
+    @Test
+    void A3_常模导入按data行数幂等upsert() throws Exception {
+        JsonNode root = readNormSeed();
+        JsonNode data = root.get("data");
+        assertNotNull(data, "常模文件应含 data 数组");
+        long expected = 0;
+        for (JsonNode row : data) {
+            if (!row.path("code").asText("").trim().isEmpty()) {
+                expected++;
+            }
+        }
+        assertTrue(expected > 0, "常模数据应已填充(S-cfc-426),期望 >0 行,实际 " + expected);
+
+        initializer.importAttributionNormGutFlora();
+
+        List<org.mockito.invocation.Invocation> updates = updateInvocations();
+        assertEquals((int) expected, updates.size(), "应按 data 行数逐行导入(不跳行、不重复)");
+        String sql = String.valueOf(updates.get(0).getArgument(0));
+        assertTrue(sql.contains("INSERT INTO attribution_norm_values"), "应写入 attribution_norm_values:" + sql);
+        assertTrue(sql.contains("ON DUPLICATE KEY UPDATE"), "必须为幂等 upsert(重复导入不新增):" + sql);
+    }
+
+    @Test
+    void A3_常模文件placeholder与data一致且note限定代表性() throws Exception {
+        JsonNode root = readNormSeed();
+        assertTrue(root.has("placeholder"), "常模文件应保留 placeholder 标记字段");
+        JsonNode data = root.get("data");
+        assertNotNull(data, "常模文件应含 data 数组");
+        assertTrue(data.isArray(), "data 应为数组");
+        if (data.size() > 0) {
+            assertFalse(root.get("placeholder").asBoolean(),
+                    "data 非空时 placeholder 必须为 false,否则导入会被整体跳过(data=" + data.size() + " 行)");
+        } else {
+            assertTrue(root.get("placeholder").asBoolean(), "data 为空时必须标记 placeholder=true(空壳模板)");
+        }
+        String note = root.path("note").asText("");
+        assertTrue(note.contains("非官方") || note.contains("代表性"),
+                "note 必须声明人群代表性限定(§八8.3 禁止夸大常模代表性):" + note);
+        assertTrue(root.get("fields").size() >= 10, "应含字段说明");
+    }
+
+    private JsonNode readNormSeed() throws Exception {
+        return mapper.readTree(
+                org.springframework.util.StreamUtils.copyToString(
+                        getClass().getResourceAsStream("/norm/attribution_norm_gut_flora.json"),
+                        java.nio.charset.StandardCharsets.UTF_8));
+    }
+
+    private List<org.mockito.invocation.Invocation> updateInvocations() {
+        List<org.mockito.invocation.Invocation> updates = new java.util.ArrayList<>();
+        for (org.mockito.invocation.Invocation invocation
+                : org.mockito.Mockito.mockingDetails(jdbcTemplate).getInvocations()) {
+            if ("update".equals(invocation.getMethod().getName())) {
+                updates.add(invocation);
+            }
+        }
+        return updates;
+    }
+
+    /** 断言未发生任何写库调用(不依赖 varargs matcher 的参数个数) */
+    private void assertNoUpdateCalled() {
+        for (org.mockito.invocation.Invocation invocation
+                : org.mockito.Mockito.mockingDetails(jdbcTemplate).getInvocations()) {
+            assertFalse("update".equals(invocation.getMethod().getName()),
+                    "不应执行写库操作:" + invocation);
+        }
+    }
+}

+ 125 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/DatabaseInitializerSeedTest.java

@@ -0,0 +1,125 @@
+package com.etotem.cfc.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class DatabaseInitializerSeedTest {
+
+    @Mock
+    private JdbcTemplate jdbcTemplate;
+
+    @InjectMocks
+    private DatabaseInitializer initializer;
+
+    @Test
+    void seedExpectedIndicator_onlyWritesWhenAbsent() {
+        initializer.seedExpectedIndicator("dan_a1", "[\"总分\"]");
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).update(sql.capture(), eq("[\"总分\"]"), eq("dan_a1"));
+        assertTrue(sql.getValue().contains("(expected_indicators IS NULL OR expected_indicators = '')"),
+                "SQL 必须仅在列为空时写入,避免覆盖管理员编辑");
+    }
+
+    // ---------------- F-4 迁移418/419(分佣收口) ----------------
+
+    @Test
+    void seedCfSalesTiers_档位缺失时补齐两级各7档() {
+        // 档位表为空 → 每档都插入
+        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(0);
+
+        initializer.seedCfSalesTiers();
+
+        List<String> sqls = updateSqls();
+        long directInserts = sqls.stream()
+                .filter(s -> s.startsWith("INSERT INTO cf_direct_sales_tier")).count();
+        long indirectInserts = sqls.stream()
+                .filter(s -> s.startsWith("INSERT INTO cf_indirect_sales_tier")).count();
+        assertEquals(7, directInserts, "直接销售奖应补齐 7 档(新秀/小成/中富/大成/进宝/富豪/至富)");
+        assertEquals(7, indirectInserts, "间接销售奖应补齐 7 档");
+    }
+
+    @Test
+    void seedCfSalesTiers_档位已存在时不重复插入() {
+        // 档位已存在 → 跳过
+        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(1);
+
+        initializer.seedCfSalesTiers();
+
+        assertEquals(0, updateSqls().stream()
+                .filter(s -> s.startsWith("INSERT INTO cf_")).count(),
+                "档位已存在时不得重复插入");
+    }
+
+    @Test
+    void seedCfSalesTiers_直接档位按团队P点下限判断() {
+        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(0);
+
+        initializer.seedCfSalesTiers();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate, Mockito.times(14)).queryForObject(sql.capture(), eq(Integer.class), any());
+        List<String> checks = sql.getAllValues();
+        assertEquals(7, checks.stream().filter(s -> s.contains("cf_direct_sales_tier")).count(),
+                "直接销售奖 7 档各判重一次");
+        assertEquals(7, checks.stream().filter(s -> s.contains("cf_indirect_sales_tier")).count(),
+                "间接销售奖 7 档各判重一次");
+        assertTrue(checks.stream().anyMatch(s -> s.contains("min_annual_ppoints = ?")),
+                "直接销售奖档位判重必须按团队年度 P 点下限(min_annual_ppoints)");
+        assertTrue(checks.stream().anyMatch(s -> s.contains("min_self_ppoints = ?")),
+                "间接销售奖档位判重必须按自身年度 P 点下限(min_self_ppoints)");
+    }
+
+    @Test
+    void alignSalesRuleRefTypes_把F03aF03b幂等键对齐为规则编码() {
+        initializer.alignSalesRuleRefTypes();
+
+        List<String> sqls = updateSqls();
+        assertTrue(sqls.stream().anyMatch(s -> s.contains("UPDATE cf_earn_rule SET dedup_ref_type = 'F03a'")
+                        && s.contains("WHERE code = 'F03a'")),
+                "F03a 的 dedup_ref_type 应对齐为 F03a");
+        assertTrue(sqls.stream().anyMatch(s -> s.contains("UPDATE cf_earn_rule SET dedup_ref_type = 'F03b'")
+                        && s.contains("WHERE code = 'F03b'")),
+                "F03b 的 dedup_ref_type 应对齐为 F03b");
+    }
+
+    @Test
+    void createPpointConsumptionLogTable_执行建表语句() {
+        initializer.createPpointConsumptionLogTable();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).execute(sql.capture());
+        assertTrue(sql.getValue().contains("CREATE TABLE IF NOT EXISTS `ppoint_consumption_log`"),
+                "应幂等建表 ppoint_consumption_log");
+        assertTrue(sql.getValue().contains("UNIQUE KEY `uk_order` (`order_type`, `order_id`)"),
+                "P 点消费日志必须带 (order_type, order_id) 唯一键以保证重复触发只记一行");
+        assertTrue(sql.getValue().contains("KEY `idx_user_time` (`user_id`, `created_at`)"),
+                "P 点消费日志必须带 user_id+created_at 索引以支持滚动一年聚合");
+    }
+
+    /** 收集 update 调用的 SQL(避免 varargs 匹配的脆弱性,用 mockingDetails 遍历) */
+    private List<String> updateSqls() {
+        return Mockito.mockingDetails(jdbcTemplate).getInvocations().stream()
+                .filter(inv -> "update".equals(inv.getMethod().getName()))
+                .map(inv -> inv.<String>getArgument(0))
+                .collect(Collectors.toList());
+    }
+}

+ 241 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/FamilyAccessInterceptorTest.java

@@ -0,0 +1,241 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.MockitoAnnotations;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Collections;
+import java.util.Set;
+import javax.servlet.http.HttpServletResponse;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+@ExtendWith(MockitoExtension.class)
+public class FamilyAccessInterceptorTest {
+
+    @Mock
+    private UserService userService;
+
+    @InjectMocks
+    private FamilyAccessInterceptor familyAccessInterceptor;
+
+    private HttpServletResponse response;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        response = mock(HttpServletResponse.class);
+    }
+
+    @Test
+    public void testChildAccessValid() throws Exception {
+        Long userId = 1L;
+        Long familyId = 1L;
+        User user = createMockUser(userId, familyId, "child");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(familyId));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", familyId.toString());
+        request.setAttribute("userId", userId);
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+        // 验证没有调用参数抛出 403
+    }
+
+    @Test
+    public void testChildAccessInvalid() throws Exception {
+        Long userId = 1L;
+        Long userFamilyId = 1L;
+        Long requestedFamilyId = 2L;
+        User user = createMockUser(userId, userFamilyId, "child");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(userFamilyId));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", requestedFamilyId.toString());
+        request.setAttribute("userId", userId);
+
+        when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        // 验证发送了 403 响应
+        verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
+    }
+
+    @Test
+    public void testTeacherAccessValid() throws Exception {
+        Long userId = 2L;
+        Long teacherFamilyId = 5L;
+        Long assignedFamilyId = 5L;
+        User user = createMockUser(userId, teacherFamilyId, "teacher");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(assignedFamilyId));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", assignedFamilyId.toString());
+        request.setAttribute("userId", userId);
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+    }
+
+    @Test
+    public void testMissingFamilyId() throws Exception {
+        Long userId = 1L;
+        Long familyId = 1L;
+        User user = createMockUser(userId, familyId, "child");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(familyId));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        // 不设置 familyId 则返回 true
+        request.setAttribute("userId", userId);
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+    }
+
+    @Test
+    public void testAdminPath() throws Exception {
+        Long userId = 1L;
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/admin/users");
+        // 任何 familyId 都不应该被拒绝,因为 admin path 会被跳过
+        request.setParameter("familyId", "999"); // 不存在的 familyId
+        request.setAttribute("userId", userId);
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+    }
+
+    @Test
+    public void testNoUserId() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", "1");
+        request.setAttribute("userId", null); // 没有 userId
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+    }
+
+    @Test
+    public void testEmptyEffectiveFamilyIds() throws Exception {
+        // B2-4 enforcement:effective set 为空但请求携带 familyId → 403 拒绝(非平台角色)
+        Long userId = 1L;
+        User user = createMockUser(userId, null, "teacher");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.emptySet());
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", "1");
+        request.setAttribute("userId", userId);
+
+        when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
+    }
+
+    @Test
+    public void testEmptyEffectiveFamilyIdsNoFamilyId() throws Exception {
+        // B2-4:effective set 为空,但请求无 familyId → 正常放行(不携带目标家庭无需拦截)
+        Long userId = 1L;
+        User user = createMockUser(userId, null, "teacher");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.emptySet());
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        // 不带 familyId
+        request.setAttribute("userId", userId);
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+    }
+
+    @Test
+    public void testPlatformRoleAdminBypass() throws Exception {
+        // B2-4 兜底:平台角色(admin/operator/finance)直接放行,不受 effective set 限制
+        Long userId = 1L;
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", "999");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "admin");
+        request.setAttribute("roles", java.util.Arrays.asList("admin"));
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+        // 平台角色直通发生在 getEffectiveFamilyIds 之前:永远不应触发用户查询
+        verify(userService, never()).getEffectiveFamilyIds(any());
+    }
+
+    @Test
+    public void testPlatformRoleOperatorBypass() throws Exception {
+        Long userId = 1L;
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family-platform/admin/balance");
+        request.setParameter("familyId", "1");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "operator");
+        request.setAttribute("roles", java.util.Arrays.asList("operator"));
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+        verify(userService, never()).getEffectiveFamilyIds(any());
+    }
+
+    @Test
+    public void testTeacherWithEmptyEffectiveIsBlocked() throws Exception {
+        // 非平台角色 + effective 集空 + 请求带 familyId → 403
+        Long userId = 2L;
+        User user = createMockUser(userId, null, "teacher");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.emptySet());
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/dan-assessment/materials");
+        request.setParameter("familyId", "1");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "teacher");
+        request.setAttribute("roles", java.util.Arrays.asList("teacher"));
+
+        when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
+    }
+
+    private User createMockUser(Long userId, Long familyId, String role) {
+        User user = new User();
+        user.setId(userId);
+        user.setFamilyId(familyId);
+        user.setTeacherFamilyIds(null);
+        return user;
+    }
+}

+ 168 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/GrowthPublicEndpointMappingTest.java

@@ -0,0 +1,168 @@
+package com.etotem.cfc.config;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import java.lang.reflect.Method;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * 成长板块「公开白名单端点必须真实存在」(死配置守卫)。
+ *
+ * <p>背景:2026-11-12 fix(auth) 1d8bd5267 将 {@code /api/growth/**} 收窄为 4 个精确公开端点。
+ * 若白名单里的路径与实际 {@code @PostMapping} 不一致(拼写/前缀拆分错误/控制器被删),
+ * 该端点会变成"看似公开实则 404"的死配置——鉴权语义被破坏且无任何用例报警。
+ *
+ * <p><b>R206 装置重构(B-206-2)</b>:原实现用 {@code @SpringBootTest} 注入
+ * {@code RequestMappingHandlerMapping} 再 {@code getHandler(new MockHttpServletRequest(...))},
+ * 存在两个缺陷:
+ * <ol>
+ *   <li><b>契约失效</b>:Spring Boot 2.7 要求 request 上存在已解析的
+ *       {@code ServletRequestPathUtils.PATH} 属性,未设置即抛
+ *       {@code IllegalArgumentException: Expected parsed RequestPath...} → 5 例稳定 ERROR,
+ *       断言从未真正触达映射查找(假失败)。</li>
+ *   <li><b>成本畸高</b>:全上下文启动实测 <b>370.5s</b> 只为 5 条字符串比对,
+ *       单类独占全量套件约 12% 的墙钟时间。</li>
+ * </ol>
+ * 改为纯反射扫描 {@code controller} 包下 {@code @RequestMapping} + {@code @PostMapping}
+ * 的组合路径,不启动任何 Spring 上下文(毫秒级),语义不变:路径不存在即失败。
+ *
+ * <p>只做映射声明比对,<b>不执行</b> controller,因此不会触发批量 AI 分类、外部同步等写副作用。
+ */
+class GrowthPublicEndpointMappingTest {
+
+    private static final String[] PUBLIC_GROWTH_ENDPOINTS = {
+            "/api/growth/recommendations",
+            "/api/growth/articles/ai-classify",
+            "/api/growth/products/ai-classify",
+            "/api/growth/external/sync",
+    };
+
+    private static final String[] PRIVATE_GROWTH_ENDPOINTS = {
+            "/api/growth/record/list",
+            "/api/growth/plan/list",
+    };
+
+    /** 扫出 controller 包下所有类级 @RequestMapping + 方法级 @PostMapping/@GetMapping 的组合路径。 */
+    private static Set<String> declaredMappings() throws Exception {
+        Set<String> out = new LinkedHashSet<String>();
+        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
+        Resource[] resources = resolver.getResources("classpath*:com/etotem/cfc/controller/**/*.class");
+        for (Resource r : resources) {
+            String url = r.getURL().toString();
+            if (url.indexOf("/controller/") < 0) {
+                continue;
+            }
+            String rel = url.substring(url.indexOf("com/etotem/cfc/controller/"));
+            String cls = rel.replace('/', '.').replace(".class", "");
+            Class<?> c;
+            try {
+                c = Class.forName(cls, false, GrowthPublicEndpointMappingTest.class.getClassLoader());
+            } catch (Throwable t) {
+                continue; // 内部类/无法加载的类跳过
+            }
+            String prefix = "";
+            RequestMapping cm = c.getAnnotation(RequestMapping.class);
+            if (cm != null) {
+                String[] v = cm.value().length > 0 ? cm.value() : cm.path();
+                if (v.length > 0) {
+                    prefix = v[0];
+                }
+            }
+            for (Method m : c.getDeclaredMethods()) {
+                for (String p : pathsOf(m)) {
+                    out.add(prefix + p);
+                }
+            }
+        }
+        return out;
+    }
+
+    private static Set<String> pathsOf(Method m) {
+        Set<String> s = new LinkedHashSet<String>();
+        PostMapping post = m.getAnnotation(PostMapping.class);
+        if (post != null) {
+            String[] v = post.value().length > 0 ? post.value() : post.path();
+            for (String x : v) {
+                s.add(x);
+            }
+        }
+        GetMapping get = m.getAnnotation(GetMapping.class);
+        if (get != null) {
+            String[] v = get.value().length > 0 ? get.value() : get.path();
+            for (String x : v) {
+                s.add(x);
+            }
+        }
+        RequestMapping rm = m.getAnnotation(RequestMapping.class);
+        if (rm != null) {
+            String[] v = rm.value().length > 0 ? rm.value() : rm.path();
+            boolean postMapped = false;
+            for (RequestMethod method : rm.method()) {
+                if (method == RequestMethod.POST) {
+                    postMapped = true;
+                }
+            }
+            if (v.length > 0 && (rm.method().length == 0 || postMapped)) {
+                for (String x : v) {
+                    s.add(x);
+                }
+            }
+        }
+        return s;
+    }
+
+    private void assertMapped(Set<String> declared, String path) {
+        boolean hit = declared.contains(path);
+        assertTrue(hit, "PUBLIC_PATHS 声明的公开端点 " + path
+                + " 在控制器映射中不存在(死配置):匿名调用只会得到 404,鉴权白名单形同虚设");
+    }
+
+    @Test
+    @DisplayName("TC-GA-M01 公开端点 /api/growth/recommendations 必须映射到真实控制器")
+    void recommendations必须可解析() throws Exception {
+        Set<String> d = declaredMappings();
+        assertNotNull(d);
+        assertMapped(d, "/api/growth/recommendations");
+    }
+
+    @Test
+    @DisplayName("TC-GA-M02 公开端点 /api/growth/articles/ai-classify 必须映射到真实控制器")
+    void articlesAiClassify必须可解析() throws Exception {
+        assertMapped(declaredMappings(), "/api/growth/articles/ai-classify");
+    }
+
+    @Test
+    @DisplayName("TC-GA-M03 公开端点 /api/growth/products/ai-classify 必须映射到真实控制器")
+    void productsAiClassify必须可解析() throws Exception {
+        assertMapped(declaredMappings(), "/api/growth/products/ai-classify");
+    }
+
+    @Test
+    @DisplayName("TC-GA-M04 公开端点 /api/growth/external/sync 必须映射到真实控制器")
+    void externalSync必须可解析() throws Exception {
+        assertMapped(declaredMappings(), "/api/growth/external/sync");
+    }
+
+    @Test
+    @DisplayName("TC-GA-M05 私有端点 /api/growth/record/list 与 /plan/list 必须映射到真实控制器")
+    void 私有端点必须可解析() throws Exception {
+        Set<String> d = declaredMappings();
+        for (String p : PRIVATE_GROWTH_ENDPOINTS) {
+            assertMapped(d, p);
+        }
+        for (String p : PUBLIC_GROWTH_ENDPOINTS) {
+            assertMapped(d, p);
+        }
+    }
+}

+ 316 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorContractEdgeTest.java

@@ -0,0 +1,316 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import io.jsonwebtoken.Claims;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * S-cfc-10 · auth.guest.jwtGuard — JwtInterceptor 契约边界补充测试(RED 阶段补齐)。
+ *
+ * <p>与 {@link ScG06JwtGuardTest}(TC-G-06 正常/异常/权限三类主用例)互补,专门覆盖
+ * JwtInterceptor 的关键边界与角色/权限上下文行为:
+ * <ol>
+ *   <li><b>OPTIONS 预检放行</b>:CORS 预检请求不做鉴权,任何路径无 token 直接放行(true),不写 401;</li>
+ *   <li><b>query 参数 token</b>:无 Authorization Header 时允许从 ?token= 读取 token(既有契约);</li>
+ *   <li><b>teacher 有效 token</b>:放行并注入 role=teacher + ROLE_teacher 权限上下文(成长规划师角色适用);</li>
+ *   <li><b>admin 有效 token</b>:放行并注入 role=admin + ROLE_admin 权限上下文(后台角色适用);</li>
+ *   <li><b>LOGIN_REQUIRED_PATHS 边界</b>:无 token 访问 family-role-switch / ai-health-coach → 401;
+ *       携有效 token 访问同一路径 → 放行(有 token 时登录必需路径不再拦截);</li>
+ * </ol>
+ *
+ * 纯单元测试:MockServlet 容器 + Mockito,不依赖数据库/微信/外部服务。
+ */
+public class JwtInterceptorContractEdgeTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+
+    @Mock
+    private UserMapper userMapper;
+
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        SecurityContextHolder.clearContext();
+    }
+
+    // ====================================================================
+    // 关键边界 1:OPTIONS 预检请求放行(不鉴权、不写 401)
+    // ====================================================================
+
+    @Test
+    public void optionsPreflight_受保护路径无token_直接放行() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("OPTIONS");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "OPTIONS 预检必须放行(CORS 前置握手)");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "OPTIONS 不应写 401/403");
+        assertTrue(response.getContentAsString().isEmpty(), "OPTIONS 不应写业务响应体");
+    }
+
+    @Test
+    public void optionsPreflight_公开路径_直接放行() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("OPTIONS");
+        request.setRequestURI("/api/product/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result);
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+    }
+
+    // ====================================================================
+    // 关键边界 2:query 参数 token(无 Authorization Header 时从 ?token= 读取)
+    // ====================================================================
+
+    @Test
+    public void queryToken_有效token_放行并注入用户上下文() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        // 无 Authorization Header,改用 query 参数 token
+        request.setParameter("token", "valid-query-token");
+
+        Claims claims = mock(Claims.class);
+        when(claims.getSubject()).thenReturn("7001");
+        when(claims.get("role")).thenReturn("parent");
+        when(claims.get("roles")).thenReturn(Collections.singletonList("parent"));
+        when(jwtConfig.parseToken("valid-query-token")).thenReturn(claims);
+
+        User user = new User();
+        user.setId(7001L);
+        user.setRole("parent");
+        user.setFamilyId(30001L);
+        when(userMapper.selectById(7001L)).thenReturn(user);
+
+        FamilyMember member = new FamilyMember();
+        member.setId(9999L);
+        member.setFamilyId(30001L);
+        member.setUserId(7001L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "query token 有效时应放行");
+        assertEquals(7001L, request.getAttribute("userId"));
+        assertEquals("parent", request.getAttribute("role"));
+        assertEquals(30001L, request.getAttribute("familyId"));
+        assertEquals(9999L, request.getAttribute("currentMemberId"));
+    }
+
+    @Test
+    public void queryToken_无效token_统一401不泄露() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        request.setParameter("token", "bad-query-token");
+
+        when(jwtConfig.parseToken("bad-query-token"))
+                .thenThrow(new RuntimeException("JWT compact of a plaintext string"));
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertTrue(response.getContentAsString().contains("请先登录"));
+        assertFalse(response.getContentAsString().contains("Exception"),
+                "异常信息不得泄露到响应体: " + response.getContentAsString());
+    }
+
+    // ====================================================================
+    // 角色/权限:teacher 有效 token → 放行 + ROLE_teacher 权限上下文
+    // ====================================================================
+
+    @Test
+    public void teacherToken_放行并注入teacher上下文() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        request.addHeader("Authorization", "Bearer teacher-token");
+
+        Claims claims = mock(Claims.class);
+        when(claims.getSubject()).thenReturn("6001");
+        when(claims.get("role")).thenReturn("teacher");
+        when(claims.get("roles")).thenReturn(Collections.singletonList("teacher"));
+        when(jwtConfig.parseToken("teacher-token")).thenReturn(claims);
+
+        User user = new User();
+        user.setId(6001L);
+        user.setRole("teacher");
+        user.setFamilyId(60001L);
+        when(userMapper.selectById(6001L)).thenReturn(user);
+
+        FamilyMember member = new FamilyMember();
+        member.setId(6666L);
+        member.setFamilyId(60001L);
+        member.setUserId(6001L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "teacher 有效 token 应放行");
+        assertEquals(6001L, request.getAttribute("userId"));
+        assertEquals("teacher", request.getAttribute("role"));
+        List<String> roles = (List<String>) request.getAttribute("roles");
+        assertTrue(roles.contains("teacher"), "roles 应含 teacher");
+
+        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+        assertTrue(auth != null && hasAuthority(auth, "ROLE_teacher"),
+                "SecurityContext 应发布 ROLE_teacher 供 @PreAuthorize 使用");
+    }
+
+    // ====================================================================
+    // 角色/权限:admin 有效 token → 放行 + ROLE_admin 权限上下文
+    // ====================================================================
+
+    @Test
+    public void adminToken_放行并注入admin权限上下文() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family-platform/balance");
+        request.addHeader("Authorization", "Bearer admin-token");
+
+        Claims claims = mock(Claims.class);
+        when(claims.getSubject()).thenReturn("8001");
+        when(claims.get("role")).thenReturn("admin");
+        when(claims.get("roles")).thenReturn(Collections.singletonList("admin"));
+        when(jwtConfig.parseToken("admin-token")).thenReturn(claims);
+
+        User user = new User();
+        user.setId(8001L);
+        user.setRole("admin");
+        user.setFamilyId(80001L);
+        when(userMapper.selectById(8001L)).thenReturn(user);
+
+        FamilyMember member = new FamilyMember();
+        member.setId(8008L);
+        member.setFamilyId(80001L);
+        member.setUserId(8001L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "admin 有效 token 应放行");
+        assertEquals(8001L, request.getAttribute("userId"));
+        assertEquals("admin", request.getAttribute("role"));
+
+        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+        assertTrue(auth != null && hasAuthority(auth, "ROLE_admin"),
+                "SecurityContext 应发布 ROLE_admin 供 @PreAuthorize 使用");
+    }
+
+    // ====================================================================
+    // 关键边界 3:LOGIN_REQUIRED_PATHS —— 无 token 401;有效 token 放行
+    // ====================================================================
+
+    @Test
+    public void loginRequiredPath_无token_401() throws Exception {
+        // family-side 角色切换(SEC-20261031-01 强制登录族)
+        assertLoginRequired401("/api/family/user/switch-role");
+    }
+
+    @Test
+    public void loginRequiredAiHealthCoach_无token_401() throws Exception {
+        // AI 健康教练:耗 AI 配额 + 家庭上下文,必须登录
+        assertLoginRequired401("/api/ai/health-coach/send");
+    }
+
+    @Test
+    public void loginRequiredAuthSwitchRole_无token_401() throws Exception {
+        // 角色切换(可重签 token),必须登录
+        assertLoginRequired401("/api/auth/switch-role");
+    }
+
+    @Test
+    public void loginRequiredPath_有效token_放行() throws Exception {
+        // 登录必需路径携有效 token 时不再拦截(401 仅针对无 token/无效 token)
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/user/switch-role");
+        request.addHeader("Authorization", "Bearer valid-token");
+
+        Claims claims = mock(Claims.class);
+        when(claims.getSubject()).thenReturn("9001");
+        when(claims.get("role")).thenReturn("parent");
+        when(claims.get("roles")).thenReturn(Collections.singletonList("parent"));
+        when(jwtConfig.parseToken("valid-token")).thenReturn(claims);
+
+        User user = new User();
+        user.setId(9001L);
+        user.setRole("parent");
+        user.setFamilyId(90001L);
+        when(userMapper.selectById(9001L)).thenReturn(user);
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "LOGIN_REQUIRED 路径携有效 token 应放行");
+        assertEquals(9001L, request.getAttribute("userId"));
+    }
+
+    // ====================================================================
+    // 私有 helper
+    // ====================================================================
+
+    private void assertLoginRequired401(String path) throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(path);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, path + " 无 token 必须被拦(LOGIN_REQUIRED)");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), path + " 应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("请先登录"), path + " 应返回统一 401 提示: " + body);
+        assertFalse(body.contains("Exception"), path + " 不应泄露内部异常: " + body);
+    }
+
+    private boolean hasAuthority(Authentication auth, String role) {
+        return auth.getAuthorities().stream()
+                .map(GrantedAuthority::getAuthority)
+                .collect(Collectors.toList())
+                .contains(role);
+    }
+}

+ 122 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorGrowthPolicyTest.java

@@ -0,0 +1,122 @@
+package com.etotem.cfc.config;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+/**
+ * 成长板块鉴权策略不变量(回归守卫):2026-11-12 fix(auth) 1d8bd5267 把
+ * {@code /api/growth/**} 从 {@code JwtInterceptor.PUBLIC_PATHS} 收窄为 4 个精确公开子端点,
+ * 并在 {@code LOGIN_REQUIRED_PATHS} 补 {@code /api/growth/record/}、{@code /api/growth/plan/}。
+ *
+ * <p>本次收窄修正了「record/plan 匿名直通 → userId 永不注入 → 500」的缺陷,
+ * 但同时引入两个新的回归风险,此前无任何用例守卫:
+ * <ol>
+ *   <li><b>过拦</b>:公开子端点(recommendations / ai-classify / external-sync)若被误删出
+ *       白名单,小程序成长页匿名访问会整体 401,而既有 {@code GrowthAuthContractTest}
+ *       只断言 record/plan 应 401,抓不到这个方向;</li>
+ *   <li><b>通配符回潮</b>:任何人把 {@code /api/growth/**} 加回 PUBLIC_PATHS,原 500 缺陷即复发。</li>
+ * </ol>
+ *
+ * <p>本用例只读取常量(反射),不启动 Spring 上下文、不触发 controller、无数据库与网络副作用,
+ * 可在任意环境确定性执行。
+ */
+class JwtInterceptorGrowthPolicyTest {
+
+    private static List<String> pathsOf(String fieldName) throws Exception {
+        Field f = JwtInterceptor.class.getDeclaredField(fieldName);
+        f.setAccessible(true);
+        String[] arr = (String[]) f.get(null);
+        return Arrays.asList(arr);
+    }
+
+    private static List<String> publicPaths() throws Exception {
+        return pathsOf("PUBLIC_PATHS");
+    }
+
+    private static List<String> loginRequiredPaths() throws Exception {
+        return pathsOf("LOGIN_REQUIRED_PATHS");
+    }
+
+    @Test
+    @DisplayName("TC-GA-P01 PUBLIC_PATHS 不得再出现 /api/growth/** 通配符(原 500 缺陷复发守卫)")
+    void publicPaths_不得再含growth通配符() throws Exception {
+        List<String> pub = publicPaths();
+        assertFalse(pub.contains("/api/growth/**"),
+                "PUBLIC_PATHS 重新包含 /api/growth/** 会让 record/plan 匿名放行,"
+                        + "userId 永不注入导致 500 缺陷复发");
+        assertFalse(pub.contains("/api/growth/*"),
+                "PUBLIC_PATHS 不得包含 /api/growth/* 单层通配符");
+        for (String p : pub) {
+            if (p != null && p.startsWith("/api/growth/")) {
+                assertFalse(p.contains("*"),
+                        "PUBLIC_PATHS 中 /api/growth/ 前缀项必须为精确端点,实际为: " + p);
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("TC-GA-P02 成长 4 个公开子端点必须保留在 PUBLIC_PATHS(过拦守卫)")
+    void publicPaths_应保留成长公开子端点() throws Exception {
+        List<String> pub = publicPaths();
+        String[] expected = {
+                "/api/growth/recommendations",
+                "/api/growth/articles/ai-classify",
+                "/api/growth/products/ai-classify",
+                "/api/growth/external/sync",
+        };
+        for (String p : expected) {
+            assertTrue(pub.contains(p),
+                    "公开子端点 " + p + " 已从 PUBLIC_PATHS 移除,小程序匿名访问将被 401 拦截");
+        }
+    }
+
+    @Test
+    @DisplayName("TC-GA-P03 LOGIN_REQUIRED_PATHS 必须覆盖成长记录(record/)")
+    void loginRequiredPaths_应覆盖成长记录() throws Exception {
+        assertTrue(loginRequiredPaths().contains("/api/growth/record/"),
+                "LOGIN_REQUIRED_PATHS 缺少 /api/growth/record/,成员私有成长记录会退回匿名放行");
+    }
+
+    @Test
+    @DisplayName("TC-GA-P04 LOGIN_REQUIRED_PATHS 必须覆盖成长方案(plan/)")
+    void loginRequiredPaths_应覆盖成长方案() throws Exception {
+        assertTrue(loginRequiredPaths().contains("/api/growth/plan/"),
+                "LOGIN_REQUIRED_PATHS 缺少 /api/growth/plan/,成员私有成长方案会退回匿名放行");
+    }
+
+    @Test
+    @DisplayName("TC-GA-P05 公开子端点与登录必需清单不得重叠(拦截顺序为公开优先,重叠即静默放行)")
+    void 成长公开子端点_不应同时出现在登录必需清单() throws Exception {
+        List<String> pub = publicPaths();
+        List<String> required = loginRequiredPaths();
+        String[] publicGrowth = {
+                "/api/growth/recommendations",
+                "/api/growth/articles/ai-classify",
+                "/api/growth/products/ai-classify",
+                "/api/growth/external/sync",
+        };
+        for (String p : publicGrowth) {
+            assertTrue(pub.contains(p), "前置条件不成立:" + p + " 不在 PUBLIC_PATHS");
+        }
+        // 拦截器先判公开、后判登录必需:同一路径同时出现在两处时"公开"胜出,
+        // 因此公开子端点绝不能以相等或前缀形式命中登录必需项,否则鉴权语义会静默漂移。
+        for (String requiredPath : required) {
+            if (requiredPath == null || !requiredPath.startsWith("/api/growth/")) {
+                continue;
+            }
+            for (String p : publicGrowth) {
+                boolean overlap = p.equals(requiredPath) || p.startsWith(requiredPath);
+                assertFalse(overlap,
+                        "公开子端点 " + p + " 被登录必需前缀 " + requiredPath + " 覆盖,"
+                                + "因公开判定优先,该端点将被静默匿名放行");
+            }
+        }
+    }
+}

+ 129 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorLoginRequiredPathTest.java

@@ -0,0 +1,129 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * B-22 鉴权清单参数化契约:遍历 {@link JwtInterceptor#LOGIN_REQUIRED_PATHS} 全部条目,
+ * 无 token 时一律 401(安全拦截),无 token 时不得匿名放行(防业务 500)。
+ *
+ * <p>与 {@link JwtInterceptorLoginRequiredTest} 互补:后者只覆盖历史已修复的个别路径;
+ * 本类对清单做全量参数化覆盖,防止新增路由时鉴权漂移再次漏测(SC-G-06 返工根因)。
+ */
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class JwtInterceptorLoginRequiredPathTest {
+
+    @Mock
+    private UserMapper userMapper;
+
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 主断言:全部 LOGIN_REQUIRED_PATHS 无 token → 401
+    // ====================================================================
+
+    static Stream<String[]> loginRequiredCases() throws Exception {
+        String[] paths = readLoginRequiredPaths();
+        return Arrays.stream(paths).map(p -> new String[]{p});
+    }
+
+    @ParameterizedTest(name = "[{index}] {0} 无 token → 401")
+    @MethodSource("loginRequiredCases")
+    @Order(1)
+    void 无token_一律返回401(String entry) throws Exception {
+        // 前缀路径(以 / 结尾)取一个子路径作为 uri;精确路径原样测试
+        String uri = entry.endsWith("/") ? entry + "action" : entry;
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(uri);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, uri + " 无 token 必须被拦(LOGIN_REQUIRED)");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), uri + " 应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("请先登录"), uri + " 应返回统一 401 提示: " + body);
+        assertFalse(body.contains("Exception"), uri + " 不应泄露内部异常: " + body);
+    }
+
+    @Test
+    @Order(2)
+    void 清单全量_统计条目数非空() throws Exception {
+        String[] paths = readLoginRequiredPaths();
+        assertFalse(paths.length == 0, "LOGIN_REQUIRED_PATHS 不得为空");
+        // 覆盖已知高危条目:reward/estimate、share/qrcode、health/report 族等
+        List<String> all = Arrays.asList(paths);
+        assertTrue(all.contains("/api/reward/estimate"), "SC-X-22 预估接口必须要求登录");
+        assertTrue(all.contains("/api/share/qrcode"), "海报小程序码必须要求登录(防微信 quota 耗尽)");
+        assertTrue(all.contains("/api/health/report/"), "健康报告族必须要求登录");
+        assertTrue(all.contains("/api/tasks/"), "任务族必须要求登录");
+        assertTrue(all.contains("/api/family/member/"), "家庭成员族必须要求登录");
+    }
+
+    // ====================================================================
+    // 反向验证:公开路径(PUBLIC_PATHS)无 token 仍放行,不被 LOGIN_REQUIRED 误拦
+    // ====================================================================
+
+    @Test
+    void 公开路径_noToken_仍放行() throws Exception {
+        // 取一条已知公开路径,证明 LOGIN_REQUIRED 不影响公开路径
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/product/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "/api/product/list 公开路径无 token 必须放行");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+    }
+
+    // ====================================================================
+    // 私有辅助
+    // ====================================================================
+
+    private static String[] readLoginRequiredPaths() throws Exception {
+        Field f = JwtInterceptor.class.getDeclaredField("LOGIN_REQUIRED_PATHS");
+        f.setAccessible(true);
+        List<String> raw = Arrays.asList((String[]) f.get(null));
+        // 去除带注释的行(以 // 开头)
+        return raw.stream()
+                .map(s -> s.trim())
+                .filter(s -> !s.isEmpty() && !s.startsWith("//"))
+                .collect(Collectors.toList())
+                .toArray(new String[0]);
+    }
+}

+ 106 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorLoginRequiredTest.java

@@ -0,0 +1,106 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * B2-5:代传报告接口(/api/health/report/proxy-parse、proxy-confirm)无 token → 401。
+ *
+ * 修复前:无 token 时被设为匿名(userId=-1)放行到 controller,代传接口返回业务 500;
+ * 修复后:进入 LOGIN_REQUIRED_PATHS,无 token 直接 401(清理前端登录态并引导重新登录)。
+ */
+public class JwtInterceptorLoginRequiredTest {
+
+    @Mock
+    private UserMapper userMapper;
+
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    @Test
+    public void testProxyParseWithoutTokenIs401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/proxy-parse");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertTrue(response.getContentAsString().contains("请先登录"));
+    }
+
+    @Test
+    public void testProxyConfirmWithoutTokenIs401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/proxy-confirm");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertTrue(response.getContentAsString().contains("请先登录"));
+    }
+
+    @Test
+    public void testHealthReportListWithoutTokenIs401() throws Exception {
+        // SC-G-06:/api/health/report/* 为家庭私有健康数据,
+        // 修复前无 token 被匿名(userId=-1)放行返回 200(泄露结构),
+        // 修复后无 token 直接 401。
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertTrue(response.getContentAsString().contains("请先登录"));
+    }
+
+    @Test
+    public void testIndicatorFavoriteWithoutTokenIs401() throws Exception {
+        // T04 方案A:指标收藏后端化——收藏写接口强制登录,无 token 直接 401(防匿名 userId=-1 污染)
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/indicator/favorite/toggle");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+    }
+
+    @Test
+    public void testIndicatorFavoriteListWithoutTokenIs401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/indicator/favorite/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+    }
+}

+ 130 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorWechatLoginTest.java

@@ -0,0 +1,130 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import io.jsonwebtoken.Claims;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * SC-G-02 微信一键登录 权限流(TC-G-02-P / TC-G-06)JwtInterceptor 鉴权行为契约测试。
+ *
+ * <p>口径(tests/user-scenarios/01-guest.md 场景 G-5/G-6、API_REFERENCE 白名单):
+ * <ol>
+ *   <li>{@code POST /api/auth/wechat-login} 是公开路径:游客无 token 可匿名触达(正常流前置)。</li>
+ *   <li>受保护接口({@code /api/family/member/list} 属 LOGIN_REQUIRED_PATHS)无 token → 统一 401
+ *       「请先登录」,不泄露内部错误堆栈。</li>
+ *   <li>携带有效 token → 放行并注入 userId/role/familyId/currentMemberId(供下游家庭数据访问)。</li>
+ *   <li>携带无效/过期 token → 统一 401。</li>
+ * </ol>
+ */
+public class JwtInterceptorWechatLoginTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        SecurityContextHolder.clearContext();
+    }
+
+    private MockHttpServletRequest post(String uri) {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(uri);
+        return request;
+    }
+
+    /** 权限流-1:微信登录是公开路径,游客无 token 匿名放行(不 401) */
+    @Test
+    public void wechatLogin公开路径_无token匿名放行() throws Exception {
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(post("/api/auth/wechat-login"), response, null);
+        assertTrue(result);
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+        assertNull(response.getHeader("X-User-Id"));
+    }
+
+    /** 权限流-2:受保护接口(家庭成员列表)无 token → 统一 401「请先登录」 */
+    @Test
+    public void 受保护接口无token_统一401() throws Exception {
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(post("/api/family/member/list"), response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertTrue(response.getContentAsString().contains("请先登录"));
+    }
+
+    /** 权限流-3:携带有效 token 访问受保护接口 → 放行并注入 userId/role/familyId/currentMemberId */
+    @Test
+    public void 携带有效token访问受保护接口_放行并注入用户上下文() throws Exception {
+        MockHttpServletRequest request = post("/api/family/member/list");
+        request.addHeader("Authorization", "Bearer valid-token");
+
+        Claims claims = mock(Claims.class);
+        when(claims.getSubject()).thenReturn("5001");
+        when(claims.get("role")).thenReturn("parent");
+        when(claims.get("roles")).thenReturn(Collections.singletonList("parent"));
+        when(jwtConfig.parseToken("valid-token")).thenReturn(claims);
+
+        User user = new User();
+        user.setId(5001L);
+        user.setRole("parent");
+        user.setFamilyId(20001L);
+        when(userMapper.selectById(5001L)).thenReturn(user);
+
+        FamilyMember member = new FamilyMember();
+        member.setId(8888L);
+        member.setFamilyId(20001L);
+        member.setUserId(5001L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertTrue(result);
+        assertEquals(5001L, request.getAttribute("userId"));
+        assertEquals("parent", request.getAttribute("role"));
+        assertEquals(20001L, request.getAttribute("familyId"));
+        assertEquals(8888L, request.getAttribute("currentMemberId"));
+    }
+
+    /** 权限流-4:携带无效/过期 token → 统一 401,不降级匿名放行 */
+    @Test
+    public void 携带无效token访问受保护接口_401() throws Exception {
+        MockHttpServletRequest request = post("/api/family/member/list");
+        request.addHeader("Authorization", "Bearer garbage-token");
+        when(jwtConfig.parseToken("garbage-token")).thenThrow(new RuntimeException("JWT 过期"));
+
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+    }
+}

+ 33 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/MyBatisPlusOptimisticLockerContractTest.java

@@ -0,0 +1,33 @@
+package com.etotem.cfc.config;
+
+import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
+import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 回归(2026-11-17):EnergyBalance 带 {@code @Version}(SC-X-21,d39aa5282),但
+ * MybatisPlusInterceptor 只注册了 PaginationInnerInterceptor,未注册
+ * {@link OptimisticLockerInnerInterceptor} —— MyBatis-Plus 3.5.x 对 @Version 实体的
+ * updateById 会静态生成 {@code AND version = #{MP_OPTLOCK_VERSION_ORIGINAL}},该参数
+ * 仅由乐观锁拦截器注入;缺注册则任何有积/能量发放的 updateById 抛
+ * BindingException(GitHub issue #3121 逐字一致),并因异常穿过
+ * {@code @Transactional awardEnergy} 代理边界把整笔打卡事务标记 rollback-only →
+ * UnexpectedRollbackException → 500,打卡整体回滚。
+ *
+ * <p>纯单元(无 Spring 上下文/DB),任何环境可跑。
+ */
+class MyBatisPlusOptimisticLockerContractTest {
+
+    @Test
+    void 拦截器链_应注册乐观锁拦截器() {
+        MybatisPlusInterceptor interceptor = new MyBatisPlusConfig().mybatisPlusInterceptor();
+        boolean hasOptimisticLocker = interceptor.getInterceptors().stream()
+                .anyMatch(i -> i instanceof OptimisticLockerInnerInterceptor);
+        assertTrue(hasOptimisticLocker,
+                "RED[mybatis.optimistic.locker]:MybatisPlusInterceptor 未注册 OptimisticLockerInnerInterceptor。"
+                        + "EnergyBalance 的 @Version(SC-X-21)将导致所有能量发放 updateById 抛"
+                        + " BindingException[MP_OPTLOCK_VERSION_ORIGINAL not found],打卡 500 整体回滚。");
+    }
+}

+ 303 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/ScG06JwtGuardTest.java

@@ -0,0 +1,303 @@
+package com.etotem.cfc.config;
+
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
+/**
+ * SC-G-06 越权接口拦截 — 三类用例(对应 tests/test-cases/guest.md TC-G-06 / TC-G-06-E / TC-G-06-P)。
+ *
+ * 正常流 TC-G-06    :游客无 token 直调受保护接口 → 401,响应为统一 Result 结构,不泄露内部堆栈。
+ * 异常流 TC-G-06-E  :缺 token / 过期&非法 token → 统一 401;公开白名单路径不被误拦,正常放行。
+ * 权限流 TC-G-06-P  :横向越权(携带本人 token 访问他人 familyId)→ 403,不泄露他人数据。
+ *
+ * 纯单元测试:MockServlet 容器 + Mockito,不依赖数据库,保证可执行性与确定性。
+ */
+public class ScG06JwtGuardTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+
+    @Mock
+    private UserMapper userMapper;
+
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @Mock
+    private UserService userService;
+
+    @InjectMocks
+    private FamilyAccessInterceptor familyAccessInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-06:受保护接口无 token → 401,统一 JSON,不泄露内部结构
+    // ====================================================================
+
+    @Test
+    public void testProtectedFamilyMemberListWithoutTokenIs401() throws Exception {
+        assertProtected401("/api/family/member/list");
+    }
+
+    @Test
+    public void testProtectedHealthReportListWithoutTokenIs401() throws Exception {
+        // 修复前:匿名 userId=-1 放行,返回 200 data:[](泄露结构)
+        assertProtected401("/api/health/report/list");
+    }
+
+    @Test
+    public void testProtectedTasksTodayWithoutTokenIs401() throws Exception {
+        // 修复前:匿名放行返回 200 data:[](泄露结构)
+        assertProtected401("/api/tasks/today");
+    }
+
+    @Test
+    public void testProtectedEnergySandboxWithoutTokenIs401() throws Exception {
+        // 修复前:匿名放行到 controller 返回 500「用户不存在」(泄露内部错误)
+        assertProtected401("/api/energy/sandbox");
+    }
+
+    @Test
+    public void testProtectedWishesListWithoutTokenIs401() throws Exception {
+        assertProtected401("/api/wishes/list");
+    }
+
+    @Test
+    public void testProtectedUserInfoWithoutTokenIs401() throws Exception {
+        // 修复前:匿名返回 200 data:null(泄露结构)
+        assertProtected401("/api/user/info");
+    }
+
+    @Test
+    public void testProtectedFamilyPlatformBalanceWithoutTokenIs401() throws Exception {
+        assertProtected401("/api/family-platform/balance");
+    }
+
+    @Test
+    public void testProtectedHealthCheckinListWithoutTokenIs401() throws Exception {
+        assertProtected401("/api/health/checkin/list");
+    }
+
+    /**
+     * 断言:无 token 访问受保护路径 → 拦截(false)+ HTTP 401 + 统一 Result 结构;
+     * 响应体唯一内容为 401 提示,绝不包含内部异常/堆栈(不泄露内部错误)。
+     */
+    private void assertProtected401(String path) throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(path);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, path + " 无 token 必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(),
+                path + " 应返回 HTTP 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), path + " 响应应含统一 code=401,实际: " + body);
+        assertTrue(body.contains("请先登录"), path + " 响应应含统一 message,实际: " + body);
+        assertFalse(body.contains("Exception"), path + " 响应不应泄露内部异常: " + body);
+        assertFalse(body.contains("at com.etotem"), path + " 响应不应泄露调用堆栈: " + body);
+        assertTrue(body.contains("\"data\":null"), path + " 响应应含统一 data:null,实际: " + body);
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-06-E:缺 token / 过期&非法 token → 401;公开路径不误拦
+    // ====================================================================
+
+    @Test
+    public void testInvalidTokenOnProtectedPathIs401() throws Exception {
+        // 过期/被篡改 token:非公开受保护路径一律 401
+        when(jwtConfig.parseToken(anyString()))
+                .thenThrow(new io.jsonwebtoken.ExpiredJwtException(null, null, "token expired"));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        request.addHeader("Authorization", "Bearer expired.token.here");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        String body = response.getContentAsString();
+        assertTrue(body.contains("请先登录"));
+        assertFalse(body.contains("ExpiredJwtException"), "异常信息不得泄露到响应体: " + body);
+    }
+
+    @Test
+    public void testGarbageTokenOnProtectedPathIs401() throws Exception {
+        when(jwtConfig.parseToken(anyString())).thenThrow(new RuntimeException("jjwt parse failure"));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/tasks/today");
+        request.addHeader("Authorization", "Bearer not-a-jwt");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result);
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        assertFalse(response.getContentAsString().contains("jjwt"), "内部异常不得泄露: " + response.getContentAsString());
+    }
+
+    @Test
+    public void testPublicProductListWithoutTokenNotBlocked() throws Exception {
+        assertPublicPassThrough("/api/product/list");
+    }
+
+    @Test
+    public void testPublicArticlesListWithoutTokenNotBlocked() throws Exception {
+        assertPublicPassThrough("/api/articles/list");
+    }
+
+    @Test
+    public void testPublicInviteValidateWithoutTokenNotBlocked() throws Exception {
+        // 邀请落地页校验令牌:游客注册前即可调用,属公开路径,不得误拦
+        assertPublicPassThrough("/api/family/invite/validate");
+    }
+
+    @Test
+    public void testPublicInviteValidateFamilyCodeWithoutTokenNotBlocked() throws Exception {
+        assertPublicPassThrough("/api/family/invite/validate-family-code");
+    }
+
+    @Test
+    public void testPublicAuthLoginWithoutTokenNotBlocked() throws Exception {
+        assertPublicPassThrough("/api/auth/wechat-login");
+    }
+
+    @Test
+    public void testPublicPathWithInvalidTokenDowngradedAnonymous() throws Exception {
+        // 公开路径带无效/过期 token:不 401、降级匿名放行,游客可继续浏览(既有契约保持)
+        when(jwtConfig.parseToken(anyString()))
+                .thenThrow(new io.jsonwebtoken.ExpiredJwtException(null, null, "expired"));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/product/list");
+        request.addHeader("Authorization", "Bearer expired.token");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开路径无效 token 应降级匿名放行");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+    }
+
+    private void assertPublicPassThrough(String path) throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(path);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, path + " 公开路径不应被拦截");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus(), path + " 不应写入 401/403");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-06-P:横向越权 → 403;同家庭访问放行;不泄露他人数据
+    // ====================================================================
+
+    @Test
+    public void testHorizontalPrivilegeEscalationIs403() throws Exception {
+        // 本人有效家庭集 {1},请求携带他人 familyId=999 → 403
+        Long userId = 100L;
+        User user = mockUser(userId, 1L, "parent");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(1L));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        request.setParameter("familyId", "999");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "parent");
+        request.setAttribute("roles", Collections.singletonList("parent"));
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "访问他人家庭数据应被拦截");
+        assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus(), "横向越权应返回 403");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("无权访问"), "应返回统一 403 提示,实际: " + body);
+        assertTrue(body.contains("\"data\":null"), "越权响应 data 必须为 null(不携带业务数据),实际: " + body);
+    }
+
+    @Test
+    public void testHorizontalPrivilegeEscalationDoesNotLeakBodyData() throws Exception {
+        Long userId = 200L;
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(2L));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/tasks/today");
+        request.setParameter("familyId", "777");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "child");
+        request.setAttribute("roles", Collections.singletonList("child"));
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        familyAccessInterceptor.preHandle(request, response, null);
+
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":403"), "越权响应应含统一 code=403,实际: " + body);
+        assertTrue(body.contains("\"data\":null"), "越权响应 data 必须为 null(不携带任何业务数据),实际: " + body);
+    }
+
+    @Test
+    public void testSameFamilyAccessIsAllowed() throws Exception {
+        Long userId = 300L;
+        User user = mockUser(userId, 1L, "parent");
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(1L));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/health/report/list");
+        request.setParameter("familyId", "1");
+        request.setAttribute("userId", userId);
+        request.setAttribute("role", "parent");
+        request.setAttribute("roles", Collections.singletonList("parent"));
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = familyAccessInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "同家庭数据访问应放行");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+    }
+
+    private User mockUser(Long id, Long familyId, String role) {
+        User user = new User();
+        user.setId(id);
+        user.setFamilyId(familyId);
+        user.setRole(role);
+        return user;
+    }
+}

+ 37 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/TasksFamilyCreatedIndexMigrationTest.java

@@ -0,0 +1,37 @@
+package com.etotem.cfc.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.verify;
+
+/**
+ * FamilyWorkbench 2026-11-13:tasks 必须有 (family_id, created_at) 复合索引,
+ * 支撑「单家庭工作台」按家庭聚合计数与近 30 天逐日趋势(GROUP BY DATE(created_at))。
+ * 无此索引时该分桶在 tasks 大表上为全表扫描。
+ */
+@ExtendWith(MockitoExtension.class)
+class TasksFamilyCreatedIndexMigrationTest {
+
+    @Mock
+    private JdbcTemplate jdbcTemplate;
+
+    @InjectMocks
+    private DatabaseInitializer initializer;
+
+    @Test
+    void 迁移为tasks添加家庭维度趋势索引() {
+        initializer.addTasksFamilyCreatedIndex();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).execute(sql.capture());
+        assertTrue(sql.getValue().contains("ADD INDEX idx_family_created (family_id, created_at)"),
+                "tasks 表必须有 (family_id, created_at) 索引以支撑工作台趋势/计数分桶");
+    }
+}

+ 103 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/WebConfigGrowthExcludeRemovedTest.java

@@ -0,0 +1,103 @@
+package com.etotem.cfc.config;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.handler.MappedInterceptor;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * WebConfig 注册链契约(回归 2026-11-12):/api/growth/** 不得再出现在
+ * jwtInterceptor 的 excludePathPatterns 中 —— 否则拦截器对 growth 整族不执行,
+ * GrowthRecordController.record/** 的 @RequestAttribute("userId") 永不注入,
+ * 无 token(甚至带 token)一律 500 "Missing request attribute 'userId'"。
+ *
+ * <p>纯单元(无 DB/Spring 上下文),任何环境可跑;与端到端
+ * {@link com.etotem.cfc.controller.growth.GrowthAuthContractTest} 互补。
+ */
+class WebConfigGrowthExcludeRemovedTest {
+
+    @Mock
+    private JwtInterceptor jwtInterceptor;
+
+    @Mock
+    private FamilyAccessInterceptor familyAccessInterceptor;
+
+    @Mock
+    private OperationLogInterceptor operationLogInterceptor;
+
+    @Mock
+    private RateLimitInterceptor rateLimitInterceptor;
+
+    @InjectMocks
+    private WebConfig webConfig;
+
+    private List<MappedInterceptor> mapped;
+
+    @BeforeEach
+    @SuppressWarnings("unchecked")
+    void setUp() throws Exception {
+        MockitoAnnotations.openMocks(this);
+        InterceptorRegistry registry = new InterceptorRegistry();
+        webConfig.addInterceptors(registry);
+        Method getInterceptors = InterceptorRegistry.class.getDeclaredMethod("getInterceptors");
+        getInterceptors.setAccessible(true);
+        List<Object> raw = (List<Object>) getInterceptors.invoke(registry);
+        assertNotNull(raw, "注册列表不应为空");
+        mapped = new ArrayList<>();
+        for (Object o : raw) {
+            mapped.add((MappedInterceptor) o);
+        }
+    }
+
+    private MappedInterceptor findMapped(HandlerInterceptor ic) {
+        return mapped.stream()
+                .filter(m -> m.getInterceptor() == ic)
+                .findFirst()
+                .orElseThrow(() -> new AssertionError("拦截器未注册: " + ic));
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<String> excludePatterns(MappedInterceptor mi) throws Exception {
+        Field f = MappedInterceptor.class.getDeclaredField("excludePatterns");
+        f.setAccessible(true);
+        Object[] arr = (Object[]) f.get(mi);
+        List<String> res = new ArrayList<>();
+        if (arr != null) {
+            for (Object pa : arr) {
+                Method g = pa.getClass().getMethod("getPatternString");
+                g.setAccessible(true); // 类包私有(org.springframework.web.servlet.handler),方法虽 public 亦需放行
+                res.add((String) g.invoke(pa));
+            }
+        }
+        return res;
+    }
+
+    @Test
+    void jwtInterceptor_不得再将growth_排除出拦截链() throws Exception {
+        MappedInterceptor m = findMapped(jwtInterceptor);
+        List<String> excludes = excludePatterns(m);
+        assertFalse(excludes.contains("/api/growth/**"),
+                "jwtInterceptor excludes 不得包含 /api/growth/**(否则 growth 无 userId 注入,恒 500)。当前=" + excludes);
+        assertTrue(Arrays.asList(m.getPathPatterns()).contains("/api/**"), "jwtInterceptor 应覆盖 /api/**");
+    }
+
+    @Test
+    void familyAccessInterceptor_保持原有growth_排除不变() throws Exception {
+        MappedInterceptor m = findMapped(familyAccessInterceptor);
+        assertTrue(excludePatterns(m).contains("/api/growth/**"),
+                "familyAccessInterceptor excludes 应保持 /api/growth/**(本次只动 jwtInterceptor)");
+    }
+}

+ 145 - 0
cfc-backend/src/test/java/com/etotem/cfc/context/MiniAppContextResolverTest.java

@@ -0,0 +1,145 @@
+package com.etotem.cfc.context;
+
+import com.etotem.cfc.entity.MiniAppConfig;
+import com.etotem.cfc.service.MiniAppConfigService;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.impl.DefaultClaims;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
+/**
+ * T02 三路解析验收:Header X-MP-Code / JWT mpCode claim / 回调 URL 路径变量 → default 兜底。
+ *
+ * <p>能力键:wechat.multiapp.context.resolve / wechat.multiapp.context.fallback-default。</p>
+ */
+public class MiniAppContextResolverTest {
+
+    @Mock
+    private MiniAppConfigService configService;
+
+    @InjectMocks
+    private MiniAppContextResolver resolver;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    private MiniAppConfig cfg(String code, String appId) {
+        MiniAppConfig c = new MiniAppConfig();
+        c.setMpCode(code);
+        c.setAppId(appId);
+        return c;
+    }
+
+    private DefaultClaims claimsWith(String mpCode) {
+        Map<String, Object> m = new HashMap<>();
+        if (mpCode != null) {
+            m.put("mpCode", mpCode);
+        }
+        return new DefaultClaims(m);
+    }
+
+    @Test
+    public void testResolveFromHeader() {
+        when(configService.getByCode("xiaoyi")).thenReturn(cfg("xiaoyi", "wx_xiaoyi"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.addHeader("X-MP-Code", "xiaoyi");
+
+        MiniAppContext ctx = resolver.resolve(req, null);
+        assertEquals("xiaoyi", ctx.getMpCode());
+        assertEquals("wx_xiaoyi", ctx.getAppId());
+        assertTrue(ctx.isExplicit());
+    }
+
+    @Test
+    public void testResolveFromJwtClaim() {
+        when(configService.getByCode("zhishao")).thenReturn(cfg("zhishao", "wx_zhishao"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+
+        MiniAppContext ctx = resolver.resolve(req, claimsWith("zhishao"));
+        assertEquals("zhishao", ctx.getMpCode());
+        assertEquals("wx_zhishao", ctx.getAppId());
+        assertTrue(ctx.isExplicit());
+    }
+
+    @Test
+    public void testResolveFromCallbackPath() {
+        when(configService.getByCode("xiaoyi")).thenReturn(cfg("xiaoyi", "wx_xiaoyi"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.setRequestURI("/api/payment/wechat/v3-notify/xiaoyi");
+
+        MiniAppContext ctx = resolver.resolve(req, null);
+        assertEquals("xiaoyi", ctx.getMpCode());
+    }
+
+    @Test
+    public void testResolveFromVirtualPayPath() {
+        when(configService.getByCode("zhishao")).thenReturn(cfg("zhishao", "wx_zhishao"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.setRequestURI("/api/internal/virtual-pay/notify/zhishao");
+
+        MiniAppContext ctx = resolver.resolve(req, null);
+        assertEquals("zhishao", ctx.getMpCode());
+    }
+
+    @Test
+    public void testResolveFromParam() {
+        when(configService.getByCode("xiaoyi")).thenReturn(cfg("xiaoyi", "wx_xiaoyi"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.setParameter("mpCode", "xiaoyi");
+
+        MiniAppContext ctx = resolver.resolve(req, null);
+        assertEquals("xiaoyi", ctx.getMpCode());
+    }
+
+    @Test
+    public void testHeaderPriorityOverJwtAndParam() {
+        when(configService.getByCode("xiaoyi")).thenReturn(cfg("xiaoyi", "wx_xiaoyi"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.addHeader("X-MP-Code", "xiaoyi");
+        req.setParameter("mpCode", "zhishao");
+
+        MiniAppContext ctx = resolver.resolve(req, claimsWith("zhishao"));
+        assertEquals("xiaoyi", ctx.getMpCode());
+    }
+
+    @Test
+    public void testFallbackToDefaultWhenNoIdentifiers() {
+        when(configService.getDefaultCode()).thenReturn("default");
+        when(configService.getByCode("default")).thenReturn(cfg("default", "wx_default"));
+        MockHttpServletRequest req = new MockHttpServletRequest();
+
+        MiniAppContext ctx = resolver.resolve(req, null);
+        assertEquals("default", ctx.getMpCode());
+        assertFalse(ctx.isExplicit());
+    }
+
+    @Test
+    public void testUnknownExplicitCodeThrows() {
+        when(configService.getByCode(anyString())).thenReturn(null);
+        when(configService.getDefaultCode()).thenReturn("default");
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        req.addHeader("X-MP-Code", "ghost");
+
+        assertThrows(IllegalArgumentException.class, () -> resolver.resolve(req, null));
+    }
+
+    @Test
+    public void testExtractPathMpCodeHelper() {
+        assertEquals("xiaoyi", MiniAppContextResolver.extractPathMpCode("/api/payment/wechat/v3-notify/xiaoyi"));
+        assertEquals("zhishao", MiniAppContextResolver.extractPathMpCode("/api/internal/virtual-pay/notify/zhishao"));
+        assertNull(MiniAppContextResolver.extractPathMpCode("/api/user/info"));
+    }
+}

+ 40 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/AttributionControllerTest.java

@@ -0,0 +1,40 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AttributionInput;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * {@link AttributionController} E12 合规开关 gate() 单测(ATT-S2-O7)。
+ *
+ * <p>E12 合规后置:{@code app.attribution.enabled} 默认 false(仅测试/mock 数据环境开启)。
+ * 开关关闭时,闭环入口 {@code /api/attribution/*} 应被 gate() 统一拦截,
+ * 返回 code=4001「家庭归因功能未开放(E12 合规后置…)」,且不触达下层 service。
+ *
+ * @author 家庭归因阶段二(ATT-S2-O7)
+ */
+class AttributionControllerTest {
+
+    @Test
+    void 开关关闭时analyze返回4001家庭归因功能未开放() {
+        AttributionController controller = new AttributionController();
+        // 显式置 false 断言「关闭态」(@Value 默认即 false,此处明确意图,防未来默认值漂移)
+        ReflectionTestUtils.setField(controller, "attributionEnabled", false);
+
+        AttributionInput input = new AttributionInput();
+        input.setFamilyId(1L);
+
+        // gate() 短路,service 不会触达;仍以非空入参走真实入口路径
+        Result<?> result = controller.analyze(input, 1L, 1L);
+
+        assertNotNull(result, "开关关闭时不应返回 null");
+        assertEquals(4001, result.getCode(), "开关关闭时应返回 code=4001(权限/放行类)");
+        assertNotNull(result.getMessage(), "应返回错误消息");
+        assertTrue(result.getMessage().contains("家庭归因功能未开放"),
+                "消息应含「家庭归因功能未开放」:" + result.getMessage());
+        System.out.println("✅ O7 验收:开关关闭 → /analyze 被 gate() 拦截,code=4001「家庭归因功能未开放」");
+    }
+}

+ 161 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/AttributionSurveyRoutingTest.java

@@ -0,0 +1,161 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.dto.ConfirmQuestionVO;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.SurveyTemplate;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.SurveyTemplateMapper;
+import com.etotem.cfc.service.ConditionEvaluatorService;
+import com.etotem.cfc.service.impl.ConditionEvaluatorServiceImpl;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * 家庭归因 B2 动态确认问卷条件路由 Mock 测试(ATT-S2-B2)。
+ *
+ * <p>验收:女儿成员 → Q10-Q13(riskLevel=high);铁低(ironLow)→ Q4a/Q4b;
+ * 无 DAN(hasDan=false)→ Q9;对象级题目只下发给该对象(对象路由)。\u200b
+ */
+class AttributionSurveyRoutingTest {
+
+    private SurveyController controller;
+    private SurveyTemplateMapper surveyTemplateMapper;
+    private FamilyMemberMapper familyMemberMapper;
+    private ObjectMapper objectMapper = new ObjectMapper();
+
+    private static final String TEMPLATE_JSON;
+
+    static {
+        String json;
+        try (InputStream in = AttributionSurveyRoutingTest.class
+                .getResourceAsStream("/survey/family_attribution_questions.json")) {
+            json = org.springframework.util.StreamUtils.copyToString(in, StandardCharsets.UTF_8);
+        } catch (Exception e) {
+            throw new IllegalStateException("读取 family_attribution_questions.json 失败", e);
+        }
+        TEMPLATE_JSON = json;
+    }
+
+    @BeforeEach
+    void setUp() {
+        controller = new SurveyController();
+        surveyTemplateMapper = mock(SurveyTemplateMapper.class);
+        familyMemberMapper = mock(FamilyMemberMapper.class);
+        ReflectionTestUtils.setField(controller, "surveyTemplateMapper", surveyTemplateMapper);
+        ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(controller, "objectMapper", objectMapper);
+        ReflectionTestUtils.setField(controller, "conditionEvaluatorService", new FixedContextEvaluator());
+    }
+
+    /** 固定中间态的 ConditionEvaluator:由测试显式注入(等价于 attribution_reports.intermediate_state) */
+    static class FixedContextEvaluator extends ConditionEvaluatorServiceImpl {
+        private final Map<String, Object> ctx = new LinkedHashMap<>();
+
+        FixedContextEvaluator() {
+            ctx.put("ironLow", true);
+            ctx.put("hasDan", false);
+            ctx.put("hasDiabetes", false);
+            ctx.put("l.reuteriAbnormal", true);
+            ctx.put("isFemaleTeen", true);
+        }
+
+        @Override
+        public Map<String, Object> buildContext(Long familyId, Long memberId, Long attributionId) {
+            return new LinkedHashMap<>(ctx);
+        }
+    }
+
+    private SurveyTemplate template() {
+        SurveyTemplate t = new SurveyTemplate();
+        t.setId(101L);
+        t.setTitle("家庭归因确认问卷(第八章)");
+        t.setDimension("family_attribution");
+        t.setQuestionsJson(TEMPLATE_JSON);
+        return t;
+    }
+
+    private FamilyMember member(Long id, String name, String gender, int age, int gen, boolean spouse) {
+        FamilyMember fm = new FamilyMember();
+        fm.setId(id);
+        fm.setNickname(name);
+        fm.setGender(gender);
+        fm.setAge(age);
+        fm.setGeneration(gen);
+        fm.setIsSpouse(spouse);
+        return fm;
+    }
+
+    @Test
+    void 女儿下发Q10到Q13且高风险题带riskLevelHigh() {
+        FamilyMember daughter = member(3L, "马昕源", "female", 14, -1, false);
+        when(familyMemberMapper.selectById(3L)).thenReturn(daughter);
+
+        ConfirmQuestionVO vo = controller.routeQuestions(template(), 1L, 3L, 7L, null);
+
+        Set<String> ids = new LinkedHashSet<>();
+        for (ConfirmQuestionVO.ConfirmQuestion q : vo.getQuestions()) {
+            ids.add(q.getId());
+        }
+        // Q10-Q13 全量下发(10a/10b/11a-d/12a-c/13a-b)
+        assertTrue(ids.contains("Q10a") && ids.contains("Q10b"), "Q10 应下发");
+        assertTrue(ids.contains("Q11a") && ids.contains("Q11b") && ids.contains("Q11c") && ids.contains("Q11d"), "Q11 应下发");
+        assertTrue(ids.contains("Q12a") && ids.contains("Q12b") && ids.contains("Q12c"), "Q12 应下发");
+        assertTrue(ids.contains("Q13a") && ids.contains("Q13b"), "Q13 应下发");
+        // 对象路由:女儿不应收到妈妈的 Q4(对象级题目只下发给该对象)
+        assertFalse(ids.contains("Q4a"), "Q4(孟凡锐=妈妈)不应下发女儿");
+        assertFalse(ids.contains("Q2"), "Q2(孟凡锐=妈妈)不应下发女儿");
+        // 家庭级恒发
+        assertTrue(ids.contains("Q1a") && ids.contains("Q16"), "家庭级题目(四人/全家)恒发");
+        // Q11-Q13 高风险
+        assertTrue(vo.isHasHighRisk());
+        for (ConfirmQuestionVO.ConfirmQuestion q : vo.getQuestions()) {
+            if (q.getId().startsWith("Q11") || q.getId().startsWith("Q12") || q.getId().startsWith("Q13")) {
+                assertEquals("high", q.getRiskLevel(), q.getId() + " 应为 high");
+            }
+        }
+        assertEquals(Arrays.asList("Q11a","Q11b","Q11c","Q11d","Q12a","Q12b","Q12c","Q13a","Q13b"),
+                vo.getHighRiskQuestionIds());
+        System.out.println("✅ B2 验收:女儿下发 Q10-Q13,Q11-Q13 riskLevel=high");
+    }
+
+    @Test
+    void 铁低时妈妈下发Q4() {
+        FamilyMember mom = member(1L, "孟凡锐", "female", 38, 0, false);
+        when(familyMemberMapper.selectById(1L)).thenReturn(mom);
+
+        ConfirmQuestionVO vo = controller.routeQuestions(template(), 1L, 1L, 7L, null);
+        Set<String> ids = new LinkedHashSet<>();
+        for (ConfirmQuestionVO.ConfirmQuestion q : vo.getQuestions()) {
+            ids.add(q.getId());
+        }
+        assertTrue(ids.contains("Q4a") && ids.contains("Q4b"), "ironLow=true → Q4a/Q4b 应下发(孟凡锐=妈妈)");
+        assertTrue(ids.contains("Q2"), "l.reuteriAbnormal=true → Q2 应下发");
+        assertFalse(ids.contains("Q10a"), "妈妈不应收到女儿 Q10");
+        System.out.println("✅ B2 验收:铁低 → 妈妈下发 Q4");
+    }
+
+    @Test
+    void 无DAN时爸爸下发Q9() {
+        FamilyMember dad = member(2L, "马智强", "male", 41, 0, true);
+        when(familyMemberMapper.selectById(2L)).thenReturn(dad);
+
+        ConfirmQuestionVO vo = controller.routeQuestions(template(), 1L, 2L, 7L, null);
+        Set<String> ids = new LinkedHashSet<>();
+        for (ConfirmQuestionVO.ConfirmQuestion q : vo.getQuestions()) {
+            ids.add(q.getId());
+        }
+        assertTrue(ids.contains("Q9"), "hasDan=false → Q9 应下发(马智强=爸爸)");
+        assertFalse(ids.contains("Q5a"), "hasDiabetes=false → Q5 不应下发");
+        System.out.println("✅ B2 验收:无 DAN → 爸爸下发 Q9");
+    }
+}

+ 520 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/AuthSessionMutexContractTest.java

@@ -0,0 +1,520 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.dto.LoginResultDTO;
+import io.jsonwebtoken.Claims;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import javax.servlet.http.HttpServletRequest;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 契约级单测:多端登录 / 会话互斥(能力键 {@code auth.session.mutex})。
+ *
+ * <p><b>溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-85 —— 「多端登录/会话互斥」:
+ *       同账号多设备场景下,新设备登录 → 旧设备踢下线 / 二次验证;边界:异常设备风控;退出清 token。
+ *       模块载体 {@code AuthController}。</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.1 认证与用户({@code /api/auth} 登录/登出
+ *       token 生命周期);缺口定义见 {@code docs/superpowers/specs/2026-11-07-parent-rest-contract.md}
+ *       §4 缺口 G-5 与 {@code docs/superpowers/specs/2026-11-07-cross-role-contract.md} §3 缺口 X-G-2:
+ *       「JWT 为无状态(JwtInterceptor 仅校验签名/过期),无会话注册表、无旧 token 吊销/踢出逻辑;
+ *       建议后端新增会话注册(user → 唯一 token/sessionId 映射,新登录失效旧 token)+
+ *       {@code POST /api/auth/logout}」。</li>
+ * </ul>
+ *
+ * <p><b>契约 AC(本类断言面)</b></p>
+ * <ol>
+ *   <li>AC-1 正常流:{@code POST /api/auth/logout} 存在(登出载体),返回 {@code Result},
+ *       能取到当前请求以定位待吊销 token。</li>
+ *   <li>AC-2 正常流:登录签发 token 携带会话标识 claim({@code sid}),且每次登录唯一
+ *       —— 无会话标识则无法区分设备、无法实现单端互斥。</li>
+ *   <li>AC-3 正常流:存在会话注册表组件(user → 唯一 sid 映射,见 AC-5 候选类名),
+ *       并被 {@code AuthController} 注入用于登录登记。</li>
+ *   <li>AC-4 边界流(互斥):注册表提供「按 userId 绑定唯一会话」+「按 (userId, sid) 校验活跃」两类方法
+ *       —— 新设备登录覆盖旧 sid → 旧设备 token 校验失败(踢下线)。</li>
+ *   <li>AC-5 边界流(踢出执行点):{@code JwtInterceptor} 注入会话校验组件,解析 token 后校验 sid 是否活跃,
+ *       失效 → 401(前端据此清登录态并回登录页)。</li>
+ *   <li>AC-6 边界流(异常设备风控):登录结果暴露「需二次验证」标记,供前端对异常设备走二次验证。</li>
+ *   <li>AC-7 异常流(退出清 token):注册表提供吊销/清除会话方法(登出后旧 token 立即失效)。</li>
+ *   <li>AC-8 权限流:登出接口必须登录 —— 不得列入 {@code PUBLIC_PATHS},且须列入
+ *       {@code LOGIN_REQUIRED_PATHS}(无 token 匿名请求直接 401,不得降级为匿名 userId=-1 放行)。</li>
+ * </ol>
+ *
+ * <p><b>实现现状(RED 依据,2026-11-15 实测 origin/cfclub)</b>:{@code AuthController} 无 {@code /logout};
+ * {@code JwtConfig} 仅写 {@code userId}/{@code role}/{@code roles}/{@code mpCode},无会话标识;
+ * 全仓无 tokenVersion / kickout / blacklist / 会话注册表;{@code JwtInterceptor} 无会话校验依赖;
+ * {@code LoginResultDTO} 无二次验证标记;{@code LOGIN_REQUIRED_PATHS} 无 {@code /api/auth/logout}
+ * (无 token 时该路径走「匿名放行」分支,实测 preHandle 返回 true)。故本类断言在实现补齐前应红。</p>
+ *
+ * <p><b>GREEN 落地清单(本类断言的最小契约面,命名可按此对齐)</b></p>
+ * <ol>
+ *   <li>{@code AuthController}:{@code @PostMapping("/logout") public Result<?> logout(HttpServletRequest request)},
+ *       从 {@code Authorization: Bearer} 取 token → 吊销当前会话。</li>
+ *   <li>{@code JwtConfig.generateToken(...)}:写入 claim {@code sid}(每次登录新生成,唯一标识一次登录会话)。</li>
+ *   <li>新增会话注册表组件,推荐类名 {@code com.etotem.cfc.service.UserSessionService}
+ *       (候选:{@code SessionRegistryService} / {@code TokenSessionService} / {@code AuthSessionService}),
+ *       提供 {@code bindSession(Long userId, String sid)} / {@code isActive(Long userId, String sid)} /
+ *       {@code revoke(Long userId, String sid)}(或语义等价命名)。</li>
+ *   <li>{@code JwtInterceptor}:注入该注册表,token 解析后校验 sid 活跃,失效 → 401(body 含 {@code "code":401})。</li>
+ *   <li>{@code LoginResultDTO}:暴露异常设备二次验证标记({@code needSecondVerify} 等)。</li>
+ *   <li>{@code JwtInterceptor.LOGIN_REQUIRED_PATHS}:加入 {@code "/api/auth/logout"}。</li>
+ * </ol>
+ *
+ * <p><b>测试手法</b>:纯反射 / Mockito,无 Spring 容器、无 DB、无 Redis、无外部服务;
+ * 与同批 RED 契约测试({@code TeamProfitHookContractTest} / {@code FamilyJoinValidationRulesContractTest})风格一致。</p>
+ */
+class AuthSessionMutexContractTest {
+
+    private static final String AUTH_CONTROLLER = "com.etotem.cfc.controller.auth.AuthController";
+
+    /** 会话注册表组件候选类名(第一个为推荐命名,GREEN 阶段任选其一即可) */
+    private static final String[] SESSION_REGISTRY_CANDIDATES = {
+            "com.etotem.cfc.service.UserSessionService",
+            "com.etotem.cfc.service.SessionRegistryService",
+            "com.etotem.cfc.service.TokenSessionService",
+            "com.etotem.cfc.service.AuthSessionService",
+            "com.etotem.cfc.security.UserSessionRegistry"
+    };
+
+    /** 登录族端点(多端登录入口,Signing side 需登记会话) */
+    private static final String[] LOGIN_PATHS = {
+            "/phone-login", "/wechat-login", "/silent-login", "/auto-login", "/sso-login"
+    };
+
+    private static final String LOGOUT_PATH = "/logout";
+
+    /** 会话标识 claim 候选键(契约取 sid,兼容 jti) */
+    private static final String[] SESSION_ID_CLAIMS = {"sid", "jti", "sessionId", "session_id"};
+
+    /** 异常设备风控二次验证标记候选字段 */
+    private static final String[] SECOND_VERIFY_FIELDS = {
+            "needSecondVerify", "needsSecondVerify", "secondVerifyRequired",
+            "verifyRequired", "needVerify", "needDeviceVerify", "deviceVerifyRequired"
+    };
+
+    @Mock
+    private JwtConfig jwtConfig;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ==================================================================
+    // 正常流 AC-1:登出端点存在(token 生命周期收口)
+    // ==================================================================
+
+    @Test
+    @DisplayName("正常流-1:AuthController 应提供 POST /api/auth/logout 登出端点")
+    void normal_logoutEndpoint_declared() {
+        Class<?> controller = loadClass(AUTH_CONTROLLER);
+        assertNotNull(controller, "[auth.session.mutex] AuthController 类不存在:" + AUTH_CONTROLLER);
+
+        Method logout = findMethodByPostPath(controller, LOGOUT_PATH);
+        if (logout == null) {
+            fail("[auth.session.mutex] AuthController 缺少 @PostMapping(\"" + LOGOUT_PATH + "\") 登出端点:"
+                    + "SC-P-85 要求「退出清 token」,契约设计(缺口 G-5 / X-G-2)明确需新增 POST /api/auth/logout。"
+                    + "已声明映射:" + describedPostPaths(controller));
+        }
+        assertEquals(Result.class, logout.getReturnType(),
+                "[auth.session.mutex] /api/auth/logout 应返回统一 Result(code/message/data)。");
+        boolean takesRequest = false;
+        for (Class<?> p : logout.getParameterTypes()) {
+            if (HttpServletRequest.class.isAssignableFrom(p)) {
+                takesRequest = true;
+                break;
+            }
+        }
+        assertTrue(takesRequest,
+                "[auth.session.mutex] /api/auth/logout 应接收 HttpServletRequest,以便从 Authorization Header "
+                        + "取出当前 token 并吊销该会话(登出清 token)。");
+    }
+
+    // ==================================================================
+    // 正常流 AC-2:token 会话标识(互斥/踢出的判定依据)
+    // ==================================================================
+
+    @Test
+    @DisplayName("正常流-2:登录 token 应携带会话标识 claim(sid),且每次登录唯一")
+    void normal_loginToken_carriesUniqueSessionIdClaim() {
+        JwtConfig config = newJwtConfig("contract-test-secret-key-0123456789abcdef", 7200_000L);
+
+        String first = config.generateToken(1001L, "parent");
+        String second = config.generateToken(1001L, "parent");
+
+        Claims firstClaims = config.parseToken(first);
+        String firstSid = firstSessionId(firstClaims);
+        assertNotNull(firstSid,
+                "[auth.session.mutex] token claims 缺少会话标识(sid):当前 claims=" + claimKeys(firstClaims)
+                        + "。无会话标识则无法区分设备会话,无法实现「新设备登录 → 旧设备踢下线」"
+                        + "(缺口 G-5 / X-G-2:会话注册 user → 唯一 token/sessionId 映射)。");
+
+        String secondSid = firstSessionId(config.parseToken(second));
+        assertNotNull(secondSid,
+                "[auth.session.mutex] 第二次登录 token 同样应携带会话标识(sid)。");
+        assertFalse(firstSid.equals(secondSid),
+                "[auth.session.mutex] 同一 userId 的两次登录必须生成不同 sid(每次登录代表一个独立会话),"
+                        + "否则无法判定哪一端是被踢下线的旧会话;实际两次均为 sid=" + firstSid);
+    }
+
+    // ==================================================================
+    // 正常流 AC-3:会话注册表组件存在,且登录侧注入使用
+    // ==================================================================
+
+    @Test
+    @DisplayName("正常流-3:会话注册表组件应存在并被 AuthController 注入(登录登记会话)")
+    void normal_sessionRegistry_existsAndInjectedByLoginController() {
+        Class<?> registry = findSessionRegistryClass();
+        assertNotNull(registry,
+                "[auth.session.mutex] 会话注册表组件不存在:契约要求 user → 唯一 token/sessionId 映射"
+                        + "(新登录失效旧 token),推荐类名 com.etotem.cfc.service.UserSessionService,"
+                        + "候选:" + Arrays.toString(SESSION_REGISTRY_CANDIDATES)
+                        + "。当前仓库无任何会话注册/吊销载体(缺口 G-5 / X-G-2)。");
+
+        Class<?> controller = loadClass(AUTH_CONTROLLER);
+        assertNotNull(controller, "[auth.session.mutex] AuthController 类不存在:" + AUTH_CONTROLLER);
+        assertTrue(hasFieldOfType(controller, registry) || hasSessionLikeField(controller),
+                "[auth.session.mutex] AuthController 未注入会话注册表(" + registry.getSimpleName() + "):"
+                        + "登录成功签发 token 时必须登记会话(user → sid),否则互斥无判定依据。"
+                        + "当前字段:" + describedFieldTypes(controller));
+    }
+
+    // ==================================================================
+    // 边界流 AC-4:注册表「覆盖式绑定 + 活跃校验」= 新设备踢旧设备
+    // ==================================================================
+
+    @Test
+    @DisplayName("边界流-1:注册表应支持按 userId 绑定唯一会话并按 sid 校验活跃(新登录覆盖旧会话)")
+    void boundary_registry_singleSessionPerUser() {
+        Class<?> registry = findSessionRegistryClass();
+        if (registry == null) {
+            fail("[auth.session.mutex] 会话注册表组件不存在,无法验证单端互斥语义"
+                    + "(同一 userId 仅保留一个活跃 sid;新登录覆盖旧会话 → 旧设备踢下线)。"
+                    + "推荐类名 com.etotem.cfc.service.UserSessionService。");
+        }
+
+        assertTrue(hasBindMethod(registry),
+                "[auth.session.mutex] " + registry.getSimpleName()
+                        + " 缺少「按 userId 绑定会话」方法(推荐 bindSession(Long userId, String sid)):"
+                        + "同一 userId 只保留一个活跃 sid,新登录覆盖旧会话。当前方法:"
+                        + describedMethodNames(registry));
+        assertTrue(hasActiveCheckMethod(registry),
+                "[auth.session.mutex] " + registry.getSimpleName()
+                        + " 缺少「按 (userId, sid) 校验会话活跃」方法(推荐 isActive(Long userId, String sid)):"
+                        + "JwtInterceptor 需据此判定旧设备 token 是否已被踢下线。当前方法:"
+                        + describedMethodNames(registry));
+    }
+
+    // ==================================================================
+    // 边界流 AC-5:踢下线执行点(JwtInterceptor 会话校验)
+    // ==================================================================
+
+    @Test
+    @DisplayName("边界流-2:JwtInterceptor 应注入会话校验组件(旧设备被踢 token → 401)")
+    void boundary_jwtInterceptor_enforcesSessionMutex() {
+        Class<?> registry = findSessionRegistryClass();
+        assertNotNull(registry,
+                "[auth.session.mutex] 会话注册表组件不存在:JwtInterceptor 无从校验 token 所属会话是否仍活跃,"
+                        + "「旧设备踢下线」无法生效(当前 JwtInterceptor 仅校验签名/过期)。");
+
+        Class<?> interceptor = JwtInterceptor.class;
+        boolean injected = hasFieldOfType(interceptor, registry) || hasSessionLikeField(interceptor);
+        assertTrue(injected,
+                "[auth.session.mutex] JwtInterceptor 未注入会话注册表(" + registry.getSimpleName() + "):"
+                        + "token 解析成功后必须校验 sid 是否活跃,失效 → 401 并返回统一 code=401"
+                        + "(前端据此清登录态回登录页)。当前字段:" + describedFieldTypes(interceptor));
+    }
+
+    // ==================================================================
+    // 边界流 AC-6:异常设备风控(二次验证)
+    // ==================================================================
+
+    @Test
+    @DisplayName("边界流-3:异常设备登录应暴露二次验证标记(风控边界)")
+    void boundary_abnormalDevice_requiresSecondVerification() {
+        boolean declared = false;
+        List<String> actual = new ArrayList<>();
+        for (Field f : LoginResultDTO.class.getDeclaredFields()) {
+            actual.add(f.getName());
+            for (String candidate : SECOND_VERIFY_FIELDS) {
+                if (f.getName().equalsIgnoreCase(candidate)) {
+                    declared = true;
+                }
+            }
+        }
+        assertTrue(declared,
+                "[auth.session.mutex] SC-P-85 边界「异常设备风控」无载体:LoginResultDTO 应暴露"
+                        + "二次验证标记(推荐 needSecondVerify:Boolean),供前端对异常设备走二次验证后再放行登录。"
+                        + "当前字段:" + actual);
+    }
+
+    // ==================================================================
+    // 异常流 AC-7:退出清 token(吊销接口)
+    // ==================================================================
+
+    @Test
+    @DisplayName("异常流-1:注册表应提供吊销/清除会话方法(登出后旧 token 立即失效)")
+    void exception_logout_revokesSession() {
+        Class<?> registry = findSessionRegistryClass();
+        if (registry == null) {
+            fail("[auth.session.mutex] 会话注册表组件不存在,无法验证「退出清 token」:"
+                    + "SC-P-85 要求登出后旧 token 立即失效(服务端吊销,而非仅前端清本地缓存)。"
+                    + "推荐类名 com.etotem.cfc.service.UserSessionService。");
+        }
+        assertTrue(hasRevokeMethod(registry),
+                "[auth.session.mutex] " + registry.getSimpleName()
+                        + " 缺少吊销/清除会话方法(推荐 revoke(Long userId, String sid)):"
+                        + "POST /api/auth/logout 必须服务端吊销当前会话,登出后旧 token 再来请求应 401。"
+                        + "当前方法:" + describedMethodNames(registry));
+    }
+
+    // ==================================================================
+    // 权限流 AC-8:登出必须登录(不得匿名放行)
+    // ==================================================================
+
+    @Test
+    @DisplayName("权限流-1:/api/auth/logout 不得列入公开白名单(无 token 匿名请求必须 401)")
+    void permission_logout_mustRequireLogin() throws Exception {
+        String[] publicPaths = readStaticStringArray(JwtInterceptor.class, "PUBLIC_PATHS");
+        assertFalse(Arrays.asList(publicPaths).contains("/api/auth/logout"),
+                "[auth.session.mutex] /api/auth/logout 不得列入 JwtInterceptor.PUBLIC_PATHS:"
+                        + "登出属凭证操作,必须携带有效 token 才能吊销对应会话。");
+
+        String[] loginRequiredPaths = readStaticStringArray(JwtInterceptor.class, "LOGIN_REQUIRED_PATHS");
+        assertTrue(Arrays.asList(loginRequiredPaths).contains("/api/auth/logout"),
+                "[auth.session.mutex] /api/auth/logout 应列入 JwtInterceptor.LOGIN_REQUIRED_PATHS:"
+                        + "否则无 token 请求会被降级为匿名(userId=-1)放行到 controller,"
+                        + "「退出清 token」对未登录态无意义且口径漂移。"
+                        + "当前 LOGIN_REQUIRED_PATHS=" + Arrays.toString(loginRequiredPaths));
+    }
+
+    @Test
+    @DisplayName("权限流-2:无 token 调用 /api/auth/logout 应直接 401(不得匿名放行)")
+    void permission_logout_withoutToken_returns401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/auth/logout");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result,
+                "[auth.session.mutex] 无 token 调用 /api/auth/logout 必须被拦截:当前 preHandle 返回 true"
+                        + "(匿名 userId=-1 放行),登出接口对未登录请求无意义且会污染匿名上下文。");
+        assertEquals(401, response.getStatus(),
+                "[auth.session.mutex] 无 token 调用登出接口应返回 401。");
+        assertTrue(response.getContentAsString().contains("\"code\":401"),
+                "[auth.session.mutex] 应返回统一 code=401,实际: " + response.getContentAsString());
+    }
+
+    // ==================================================================
+    // 反射 / 静态辅助
+    // ==================================================================
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private Class<?> findSessionRegistryClass() {
+        for (String candidate : SESSION_REGISTRY_CANDIDATES) {
+            Class<?> clazz = loadClass(candidate);
+            if (clazz != null) {
+                return clazz;
+            }
+        }
+        return null;
+    }
+
+    /** 找到 @PostMapping 值命中指定路径的方法 */
+    private Method findMethodByPostPath(Class<?> clazz, String path) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            PostMapping mapping = m.getAnnotation(PostMapping.class);
+            if (mapping == null) {
+                continue;
+            }
+            for (String value : mapping.value()) {
+                if (normalize(value).equals(normalize(path))) {
+                    return m;
+                }
+            }
+        }
+        return null;
+    }
+
+    private String normalize(String path) {
+        if (path == null) {
+            return "";
+        }
+        String p = path.trim();
+        return p.startsWith("/") ? p : "/" + p;
+    }
+
+    private List<String> describedPostPaths(Class<?> clazz) {
+        List<String> paths = new ArrayList<>();
+        for (Method m : clazz.getDeclaredMethods()) {
+            PostMapping mapping = m.getAnnotation(PostMapping.class);
+            if (mapping != null) {
+                paths.addAll(Arrays.asList(mapping.value()));
+            }
+        }
+        return paths;
+    }
+
+    private boolean hasFieldOfType(Class<?> clazz, Class<?> type) {
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType().equals(type)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 宽松探测:字段类型或字段名带会话互斥语义(允许实现者自命名组件) */
+    private boolean hasSessionLikeField(Class<?> clazz) {
+        for (Field f : clazz.getDeclaredFields()) {
+            String typeName = f.getType().getSimpleName().toLowerCase();
+            String name = f.getName().toLowerCase();
+            boolean typeHit = (typeName.contains("session") || typeName.contains("token"))
+                    && (typeName.contains("registry") || typeName.contains("store") || typeName.contains("guard")
+                    || typeName.contains("mutex") || typeName.contains("valid") || typeName.contains("revoke")
+                    || typeName.contains("blacklist"));
+            boolean nameHit = name.contains("session") && (name.contains("valid") || name.contains("guard")
+                    || name.contains("registry") || name.contains("mutex"));
+            if (typeHit || nameHit) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private List<String> describedFieldTypes(Class<?> clazz) {
+        List<String> types = new ArrayList<>();
+        for (Field f : clazz.getDeclaredFields()) {
+            types.add(f.getType().getSimpleName() + " " + f.getName());
+        }
+        return types;
+    }
+
+    private List<String> describedMethodNames(Class<?> clazz) {
+        List<String> names = new ArrayList<>();
+        for (Method m : clazz.getDeclaredMethods()) {
+            names.add(m.getName());
+        }
+        return names;
+    }
+
+    /** 绑定方法:名称含 bind/register/create/open/activate/issue 语义,且至少 (userId, sid) 两个入参 */
+    private boolean hasBindMethod(Class<?> clazz) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            String name = m.getName().toLowerCase();
+            boolean nameHit = name.contains("bind") || name.contains("register") || name.contains("create")
+                    || name.contains("open") || name.contains("activate") || name.contains("issue");
+            if (!nameHit) {
+                continue;
+            }
+            Class<?>[] params = m.getParameterTypes();
+            if (params.length >= 2 && (params[0].equals(Long.class) || params[0].equals(long.class))
+                    && params[1].equals(String.class)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 活跃校验方法:名称含 isActive/valid/check/exists 语义,返回 boolean */
+    private boolean hasActiveCheckMethod(Class<?> clazz) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            String name = m.getName().toLowerCase();
+            boolean nameHit = name.contains("isactive") || name.contains("active") || name.contains("valid")
+                    || name.contains("alive") || name.contains("check") || name.contains("exists")
+                    || name.contains("match");
+            if (!nameHit) {
+                continue;
+            }
+            Class<?> ret = m.getReturnType();
+            if ((ret.equals(boolean.class) || ret.equals(Boolean.class)) && m.getParameterTypes().length >= 1) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 吊销方法:名称含 revoke/invalidate/clear/remove/delete/kill/logout 语义 */
+    private boolean hasRevokeMethod(Class<?> clazz) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            String name = m.getName().toLowerCase();
+            if (name.contains("revoke") || name.contains("invalidate") || name.contains("clear")
+                    || name.contains("remove") || name.contains("delete") || name.contains("kill")
+                    || name.contains("logout") || name.contains("expire")) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private String firstSessionId(Claims claims) {
+        for (String key : SESSION_ID_CLAIMS) {
+            Object value = claims.get(key);
+            if (value != null && value.toString().trim().length() > 0) {
+                return value.toString().trim();
+            }
+        }
+        return null;
+    }
+
+    private List<String> claimKeys(Claims claims) {
+        return new ArrayList<>(claims.keySet());
+    }
+
+    private String[] readStaticStringArray(Class<?> clazz, String fieldName) throws Exception {
+        Field field = clazz.getDeclaredField(fieldName);
+        field.setAccessible(true);
+        return (String[]) field.get(null);
+    }
+
+    private JwtConfig newJwtConfig(String secret, long expirationMillis) {
+        JwtConfig config = new JwtConfig();
+        setField(config, "secret", secret);
+        setField(config, "expiration", expirationMillis);
+        return config;
+    }
+
+    private void setField(Object target, String name, Object value) {
+        try {
+            Field field = target.getClass().getDeclaredField(name);
+            field.setAccessible(true);
+            field.set(target, value);
+        } catch (Exception e) {
+            throw new IllegalStateException("无法注入测试字段 " + name + ":" + e.getMessage(), e);
+        }
+    }
+}

+ 270 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/AuthWechatLoginContractTest.java

@@ -0,0 +1,270 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.controller.auth.AuthController;
+import com.etotem.cfc.dto.LoginResultDTO;
+import com.etotem.cfc.dto.WechatLoginDTO;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.lang.reflect.Method;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * SC-G-02 微信一键登录 — 契约级单测(能力键 {@code auth.guest.wechatLogin})。
+ *
+ * <p>对应 {@code tests/user-scenarios/01-guest.md} 场景 G-2 与 {@code tests/test-cases/guest.md}:
+ * <ul>
+ *   <li><b>TC-G-02 正常流</b>:{@code POST /api/auth/wechat-login} → {@code Result} 含 token + 用户信息;
+ *       角色默认 {@code parent};首次登录建号({@code isNewUser=true})。</li>
+ *   <li><b>TC-G-02a 边界</b>:同一微信二次登录应返回已有账号,不重复建号({@code isNewUser=false})。</li>
+ *   <li><b>TC-G-02-E 异常流</b>:微信授权失败 / 服务异常 → {@code Result.error}(code=500),
+ *       只透传业务 message,绝不泄露内部堆栈/异常类名。</li>
+ *   <li><b>TC-G-02-P 权限流</b>:登录端点在 {@code JwtInterceptor} 公开白名单内,游客无 token
+ *       可正常触达(匿名放行、不误拦 401)。</li>
+ * </ul>
+ *
+ * <p>纯单元测试:Mockito 直接调用 handler + {@code MockHttpServletRequest/Response},
+ * 不依赖数据库 / 真实微信 / Spring 容器,保证可执行性与确定性。
+ */
+public class AuthWechatLoginContractTest {
+
+    @Mock
+    private UserService userService;
+
+    @InjectMocks
+    private AuthController controller;
+
+    // ---- JwtInterceptor(权限流:公开白名单放行)----
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-02:登录成功 → Result 含 token + 用户信息(角色默认 parent)
+    // ====================================================================
+
+    @Test
+    public void wechatLogin_Success_ReturnsTokenAndUserInfo() {
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("wx-code");
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setToken("jwt-token-abc");
+        login.setUserId(88L);
+        login.setRole("parent");
+        login.setFamilyId(1001L);
+        login.setNickname("微信用户");
+        login.setPhone("13800000001");
+        login.setIsNewUser(true);
+        login.setOpenid("openid-abc");
+        login.setNeedsRoleSelect(true);
+        login.setNeedsFamily(false);
+        when(userService.wechatLogin(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        assertEquals(200, result.getCode(), "正常登录应返回 code=200");
+        assertEquals("success", result.getMessage());
+        assertNotNull(result.getData(), "应返回 LoginResultDTO");
+        assertEquals("jwt-token-abc", result.getData().getToken());
+        assertEquals(88L, result.getData().getUserId());
+        assertEquals("parent", result.getData().getRole(), "角色应默认 parent");
+        assertEquals(1001L, result.getData().getFamilyId());
+        assertEquals("微信用户", result.getData().getNickname());
+        assertEquals("13800000001", result.getData().getPhone());
+        assertTrue(result.getData().getIsNewUser(), "首次登录应 isNewUser=true");
+        assertEquals("openid-abc", result.getData().getOpenid());
+        assertTrue(result.getData().getNeedsRoleSelect(), "新用户应 needsRoleSelect=true");
+        assertFalse(result.getData().getNeedsFamily(), "已绑定家庭则 needsFamily=false");
+        verify(userService, times(1)).wechatLogin(dto);
+    }
+
+    @Test
+    public void wechatLogin_NewUser_IsDefaultParentAndNeedsRoleSelect() {
+        // TC-G-02 契约:新用户默认成为家长(role=parent),需选择角色
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("wx-code");
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setRole("parent");
+        login.setIsNewUser(true);
+        login.setNeedsRoleSelect(true);
+        when(userService.wechatLogin(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        assertEquals(200, result.getCode());
+        assertEquals("parent", result.getData().getRole());
+        assertTrue(result.getData().getIsNewUser());
+        assertTrue(result.getData().getNeedsRoleSelect());
+    }
+
+    // ====================================================================
+    // 边界 TC-G-02a:同一微信二次登录返回已有账号,不重复建号(isNewUser=false)
+    // ====================================================================
+
+    @Test
+    public void wechatLogin_ExistingOpenid_ReturnsExistingAccountNoNewCreation() {
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("wx-code");
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setUserId(88L);
+        login.setRole("parent");
+        login.setIsNewUser(false);
+        login.setNeedsRoleSelect(false);
+        login.setOpenid("openid-abc");
+        when(userService.wechatLogin(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        assertEquals(200, result.getCode());
+        assertEquals(88L, result.getData().getUserId(), "应返回已有账号的 userId,不新建");
+        assertFalse(result.getData().getIsNewUser(), "老用户重登 isNewUser 必须为 false");
+        assertFalse(result.getData().getNeedsRoleSelect(), "老用户不再要求选择角色");
+        assertEquals("openid-abc", result.getData().getOpenid());
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-02-E:微信授权失败/服务异常 → Result.error,不泄露内部堆栈
+    // ====================================================================
+
+    @Test
+    public void wechatLogin_ServiceThrowsRuntimeException_ReturnsBusinessError() {
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("bad-code");
+
+        when(userService.wechatLogin(dto)).thenThrow(new RuntimeException("微信登录失败"));
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        assertEquals(500, result.getCode(), "服务异常应映射为 code=500");
+        assertEquals("微信登录失败", result.getMessage(), "应透传业务 message,不吞掉");
+        assertNull(result.getData(), "异常时不携带业务数据");
+    }
+
+    @Test
+    public void wechatLogin_ServiceThrows_ErrorMessageDoesNotLeakStack() {
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("bad-code");
+
+        when(userService.wechatLogin(dto))
+                .thenThrow(new RuntimeException("获取openid失败,请重试"));
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        String msg = result.getMessage();
+        assertNotNull(msg);
+        // 契约:错误信息只含业务文案,绝不含异常类名/堆栈帧(不泄露内部结构)
+        assertFalse(msg.contains("RuntimeException"), "不得泄露异常类名: " + msg);
+        assertFalse(msg.contains("at com."), "不得泄露堆栈帧: " + msg);
+        assertFalse(msg.contains("\n"), "错误信息应单行业务文案: " + msg);
+    }
+
+    @Test
+    public void wechatLogin_Code2SessionFailure_ReturnsErrorNoDirtyAccount() {
+        // TC-G-02-E:授权失败 → 返回业务错误,控制器层面不透传 openid/不建号
+        WechatLoginDTO dto = new WechatLoginDTO();
+        dto.setCode("invalid-wx-code");
+
+        when(userService.wechatLogin(dto))
+                .thenThrow(new RuntimeException("获取openid失败,请重试"));
+
+        Result<LoginResultDTO> result = controller.wechatLogin(dto);
+
+        assertEquals(500, result.getCode());
+        assertEquals("获取openid失败,请重试", result.getMessage());
+        assertNull(result.getData());
+        verify(userService, times(1)).wechatLogin(dto);
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-02-P:登录端点在公开白名单内,游客无 token 可放行(不误拦 401)
+    // ====================================================================
+
+    @Test
+    public void wechatLogin_PublicPath_NoToken_AnonymousAllowed() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/auth/wechat-login");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开登录端点无 token 必须放行(游客可触达)");
+        assertEquals(200, response.getStatus(), "公开端点不应被写 401");
+    }
+
+    @Test
+    public void wechatLogin_PublicPath_InvalidToken_DowngradedAnonymous() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/auth/wechat-login");
+        request.addHeader("Authorization", "Bearer expired-token");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        // jwtConfig.parseToken 默认返回 null → 解析 NPE → 公开路径降级匿名放行
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开端点 token 失效应降级匿名放行,不 401 拦截");
+        assertEquals(200, response.getStatus());
+    }
+
+    @Test
+    public void wechatLogin_IsNotInLoginRequiredPaths() throws Exception {
+        // 契约:/api/auth/wechat-login 属登录入口,不得落入「必须登录」路径族(否则游客被 401)
+        java.lang.reflect.Field field = JwtInterceptor.class.getDeclaredField("LOGIN_REQUIRED_PATHS");
+        field.setAccessible(true);
+        String[] loginRequired = (String[]) field.get(jwtInterceptor);
+        assertNotNull(loginRequired);
+        for (String p : loginRequired) {
+            assertFalse("/api/auth/wechat-login".equals(p),
+                    "登录入口不应被列入必须登录路径: " + p);
+        }
+    }
+
+    // ====================================================================
+    // 结构契约:端点映射为 POST /api/auth/wechat-login(统一 @PostMapping + 公开)
+    // ====================================================================
+
+    @Test
+    public void wechatLogin_MappedToPostApiAuthWechatLogin() throws Exception {
+        RestController rest = AuthController.class.getAnnotation(RestController.class);
+        assertNotNull(rest, "AuthController 应为 @RestController");
+        RequestMapping classMapping = AuthController.class.getAnnotation(RequestMapping.class);
+        assertNotNull(classMapping);
+        assertEquals("/api/auth", classMapping.value()[0], "类映射应为 /api/auth");
+
+        Method m = AuthController.class.getMethod("wechatLogin", WechatLoginDTO.class);
+        PostMapping postMapping = m.getAnnotation(PostMapping.class);
+        assertNotNull(postMapping, "wechatLogin 必须为 @PostMapping(AGENTS.md 禁止 GET/PUT/DELETE)");
+        assertEquals("/wechat-login", postMapping.value()[0]);
+    }
+}

+ 384 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/BadgeControllerGetMemberBadgesTest.java

@@ -0,0 +1,384 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Badge;
+import com.etotem.cfc.entity.MemberBadge;
+import com.etotem.cfc.service.BadgeService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-cfc-32 · achievement.grid.fiveCol — BadgeController.getMemberBadges 契约级单测(RED 阶段补齐)。
+ *
+ * <p>覆盖 {@link BadgeController#getMemberBadges(Map, Long)}:
+ * <ol>
+ *   <li><b>正常路径</b>:有效 memberId(或 currentMemberId 兜底)→ 返回 memberBadge+badge 聚合列表;</li>
+ *   <li><b>关键边界</b>:memberId 为空且无 currentMemberId → 400/统一错误;</li>
+ *   <li><b>角色/权限</b>:parent/teacher/admin 均可访问(无额外角色限制,仅需登录上下文)。</li>
+ * </ol>
+ *
+ * 纯单元测试:MockMvc standalone + Mockito,不依赖数据库/微信/外部服务。
+ */
+public class BadgeControllerGetMemberBadgesTest {
+
+    @Mock
+    private BadgeService badgeService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        BadgeController controller = new BadgeController();
+        ReflectionTestUtils.setField(controller, "badgeService", badgeService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ====================================================================
+    // 正常路径
+    // ====================================================================
+
+    @Test
+    public void getMemberBadges_显式传memberId_返回聚合列表() throws Exception {
+        Long memberId = 1001L;
+        Long badgeId = 10L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(1L);
+        mb.setMemberId(memberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setIsFavorite(false);
+        mb.setStatus(1);
+
+        Badge badge = new Badge();
+        badge.setId(badgeId);
+        badge.setBadgeId("b_test_001");
+        badge.setName("连续打卡达人");
+        badge.setIcon("🏅");
+        badge.setCategory("streak");
+        badge.setLevel("gold");
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(badge);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":1001}")
+                        .requestAttr("userId", 1L)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].memberBadge.id").value(1))
+                .andExpect(jsonPath("$.data[0].badge.badgeId").value("b_test_001"))
+                .andExpect(jsonPath("$.data[0].badge.name").value("连续打卡达人"))
+                .andExpect(jsonPath("$.data[0].badge.category").value("streak"));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+        verify(badgeService).getBadgeById(badgeId);
+    }
+
+    @Test
+    public void getMemberBadges_不传memberId_回退currentMemberId() throws Exception {
+        Long currentMemberId = 2002L;
+        Long badgeId = 20L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(2L);
+        mb.setMemberId(currentMemberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setIsFavorite(true);
+        mb.setStatus(1);
+
+        Badge badge = new Badge();
+        badge.setId(badgeId);
+        badge.setBadgeId("b_test_002");
+        badge.setName("任务完成者");
+        badge.setIcon("✅");
+        badge.setCategory("task");
+        badge.setLevel("silver");
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(currentMemberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(badge);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 2L)
+                        .requestAttr("currentMemberId", currentMemberId)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].memberBadge.id").value(2))
+                .andExpect(jsonPath("$.data[0].badge.name").value("任务完成者"))
+                .andExpect(jsonPath("$.data[0].memberBadge.isFavorite").value(true));
+
+        verify(badgeService).getActiveMemberBadges(currentMemberId);
+    }
+
+    @Test
+    public void getMemberBadges_多枚勋章_按收藏与获得时间排序() throws Exception {
+        Long memberId = 3003L;
+        Long badgeId1 = 30L;
+        Long badgeId2 = 31L;
+
+        // mb2: 收藏=true, 获得时间=今天 → 应排在前面
+        MemberBadge mb2 = new MemberBadge();
+        mb2.setId(4L);
+        mb2.setMemberId(memberId);
+        mb2.setBadgeId(badgeId2);
+        mb2.setEarnedAt(new Date()); // 今天
+        mb2.setIsFavorite(true); // 收藏优先
+        mb2.setStatus(1);
+
+        // mb1: 收藏=false, 获得时间=昨天 → 排在后面
+        MemberBadge mb1 = new MemberBadge();
+        mb1.setId(3L);
+        mb1.setMemberId(memberId);
+        mb1.setBadgeId(badgeId1);
+        mb1.setEarnedAt(new Date(System.currentTimeMillis() - 86400000L)); // 昨天
+        mb1.setIsFavorite(false);
+        mb1.setStatus(1);
+
+        Badge badge1 = new Badge();
+        badge1.setId(badgeId1);
+        badge1.setBadgeId("b_test_003");
+        badge1.setName("成长记录者");
+        badge1.setCategory("growth");
+
+        Badge badge2 = new Badge();
+        badge2.setId(badgeId2);
+        badge2.setBadgeId("b_test_004");
+        badge2.setName("挑战参与者");
+        badge2.setCategory("challenge");
+
+        // Mock 返回已按 service 排序规则(isFavorite DESC, earnedAt DESC)排好序的列表
+        List<MemberBadge> memberBadges = Arrays.asList(mb2, mb1);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId1)).thenReturn(badge1);
+        when(badgeService.getBadgeById(badgeId2)).thenReturn(badge2);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":3003}")
+                        .requestAttr("userId", 3L)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(2))
+                // 收藏优先:mb2 (挑战参与者) 应在前
+                .andExpect(jsonPath("$.data[0].badge.name").value("挑战参与者"))
+                .andExpect(jsonPath("$.data[1].badge.name").value("成长记录者"));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+    }
+
+    @Test
+    public void getMemberBadges_空列表_返回空数组() throws Exception {
+        Long memberId = 4004L;
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":4004}")
+                        .requestAttr("userId", 4L)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(0));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+        verify(badgeService, never()).getBadgeById(anyLong());
+    }
+
+    // ====================================================================
+    // 关键边界
+    // ====================================================================
+
+    @Test
+    public void getMemberBadges_无memberId且无currentMemberId_返回空列表() throws Exception {
+        // 既不传 memberId,也没有 currentMemberId 请求属性 → memberId 为 null
+        // 实际行为:service 查询 WHERE member_id = NULL 返回空,controller 返回 200 + 空数组
+        when(badgeService.getActiveMemberBadges(null)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 5L)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(0));
+
+        verify(badgeService).getActiveMemberBadges(null);
+    }
+
+    @Test
+    public void getMemberBadges_memberBadge存在但Badge定义丢失_跳过该项() throws Exception {
+        Long memberId = 6006L;
+        Long badgeId = 60L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(5L);
+        mb.setMemberId(memberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setStatus(1);
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(null); // Badge 定义被删/丢失
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":6006}")
+                        .requestAttr("userId", 6L)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(0)); // 该项被过滤
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+        verify(badgeService).getBadgeById(badgeId);
+    }
+
+    // ====================================================================
+    // 角色/权限:parent/teacher/admin 均可访问(仅需登录上下文)
+    // ====================================================================
+
+    @Test
+    public void getMemberBadges_teacher角色_可访问() throws Exception {
+        Long memberId = 7007L;
+        Long badgeId = 70L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(6L);
+        mb.setMemberId(memberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setStatus(1);
+
+        Badge badge = new Badge();
+        badge.setId(badgeId);
+        badge.setBadgeId("b_teacher_001");
+        badge.setName("规划师认证");
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(badge);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":7007}")
+                        .requestAttr("userId", 7L)
+                        .requestAttr("currentMemberId", memberId)
+                        .requestAttr("role", "teacher")
+                        .requestAttr("roles", Collections.singletonList("teacher")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].badge.name").value("规划师认证"));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+    }
+
+    @Test
+    public void getMemberBadges_admin角色_可访问() throws Exception {
+        Long memberId = 8008L;
+        Long badgeId = 80L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(7L);
+        mb.setMemberId(memberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setStatus(1);
+
+        Badge badge = new Badge();
+        badge.setId(badgeId);
+        badge.setBadgeId("b_admin_001");
+        badge.setName("平台管理员徽章");
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(badge);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":8008}")
+                        .requestAttr("userId", 8L)
+                        .requestAttr("currentMemberId", memberId)
+                        .requestAttr("role", "admin")
+                        .requestAttr("roles", Collections.singletonList("admin")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].badge.name").value("平台管理员徽章"));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+    }
+
+    @Test
+    public void getMemberBadges_child角色_可访问自身勋章() throws Exception {
+        // 直接登录的孩子端(role=child,memberType=login)也可查看自己的勋章
+        Long memberId = 9009L;
+        Long badgeId = 90L;
+
+        MemberBadge mb = new MemberBadge();
+        mb.setId(8L);
+        mb.setMemberId(memberId);
+        mb.setBadgeId(badgeId);
+        mb.setEarnedAt(new Date());
+        mb.setStatus(1);
+
+        Badge badge = new Badge();
+        badge.setId(badgeId);
+        badge.setBadgeId("b_child_001");
+        badge.setName("小小达人");
+
+        List<MemberBadge> memberBadges = Collections.singletonList(mb);
+        when(badgeService.getActiveMemberBadges(memberId)).thenReturn(memberBadges);
+        when(badgeService.getBadgeById(badgeId)).thenReturn(badge);
+
+        mockMvc.perform(post("/api/badges/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}") // 孩子端通常不传 memberId,靠 currentMemberId
+                        .requestAttr("userId", 9L)
+                        .requestAttr("currentMemberId", memberId)
+                        .requestAttr("role", "child")
+                        .requestAttr("roles", Collections.singletonList("child")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].badge.name").value("小小达人"));
+
+        verify(badgeService).getActiveMemberBadges(memberId);
+    }
+}

+ 90 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/DanAssessmentControllerGetActiveMaterialTest.java

@@ -0,0 +1,90 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.entity.AssessmentMaterial;
+import com.etotem.cfc.service.AssessmentService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约级单测:{@link DanAssessmentController#getActiveMaterial}(能力键 dan.assessment.getActiveMaterial)。
+ *
+ * 端点:POST /api/dan-assessment/material/active
+ *
+ * 契约要点(按实体 + 控制器 + AGENTS.md):
+ *  - 统一 @PostMapping(GET 应 405);
+ *  - 统一 Result<T> 包装(code=200 / message=success / data=当前启用材料);
+ *  - AssessmentMaterial 实体字段为 title(无 name),data 序列化含 id/title/status。
+ *
+ * 测试隔离:MockMvc standalone + mock AssessmentService,无 Spring 上下文 / 无 DB。
+ * 注意:实体字段是 {@code title} 而非 {@code name}——历史编译阻断即因误用 setName 触发,
+ *       本测试以 setTitle 为准(对齐 AssessmentMaterial.java 真实字段)。
+ */
+class DanAssessmentControllerGetActiveMaterialTest {
+
+    private static final String URL = "/api/dan-assessment/material/active";
+
+    @Mock
+    private AssessmentService assessmentService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        DanAssessmentController controller = new DanAssessmentController();
+        ReflectionTestUtils.setField(controller, "assessmentService", assessmentService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private AssessmentMaterial material(long id, String title, String status) {
+        AssessmentMaterial m = new AssessmentMaterial();
+        m.setId(id);
+        m.setTitle(title);   // 实体字段为 title(非 name),与 AssessmentMaterial.java 一致
+        m.setStatus(status);
+        return m;
+    }
+
+    @Test
+    void getActiveMaterial_返回当前启用材料() throws Exception {
+        AssessmentMaterial active = material(1L, "2026 春季测评", "active");
+        when(assessmentService.getActiveMaterial()).thenReturn(active);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data.id").value(1))
+                .andExpect(jsonPath("$.data.title").value("2026 春季测评"))
+                .andExpect(jsonPath("$.data.status").value("active"));
+    }
+
+    @Test
+    void getActiveMaterial_无启用材料_返回空data() throws Exception {
+        when(assessmentService.getActiveMaterial()).thenReturn(null);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").doesNotExist());
+    }
+
+    @Test
+    void getActiveMaterial_仅允许POST_GET请求返回405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+}

+ 98 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/EnergyControllerGrantEnergyTest.java

@@ -0,0 +1,98 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.EnergyLog;
+import com.etotem.cfc.service.EnergyService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * CFC-EN-001:/api/energy/grant 成功路径 Controller 层回归测试。
+ *
+ * <p>补齐 Controller 层覆盖:grantEnergy 成功时返回 {@code Result.success(energyLog)}
+ * (code=200 且 data 有值);缺参/无家庭时返回错误提示。</p>
+ */
+class EnergyControllerGrantEnergyTest {
+
+    private EnergyController controller;
+    private EnergyService energyService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new EnergyController();
+        energyService = mock(EnergyService.class);
+        inject(controller, "energyService", energyService);
+    }
+
+    @Test
+    @DisplayName("CFC-EN-001:grant 成功返回 code=200 且 data 有值")
+    void grantEnergy_success_returns200WithData() {
+        EnergyLog log = new EnergyLog();
+        log.setMemberId(50L);
+        log.setDimensionId(5L);
+        log.setAmount(10);
+        log.setSourceType("task");
+        log.setSourceId(8888L);
+        when(energyService.grantEnergy(eq(50L), eq(8888L), eq(10L), eq("body"))).thenReturn(log);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", 50L);
+        params.put("taskId", 8888L);
+        params.put("amount", 10L);
+        params.put("dimensionCode", "body");
+
+        Result<EnergyLog> result = controller.grantEnergy(params, 100L, 50L);
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(10, result.getData().getAmount());
+        assertEquals(8888L, result.getData().getSourceId());
+    }
+
+    @Test
+    @DisplayName("CFC-EN-001:缺参返回错误提示而非 500")
+    void grantEnergy_missingParam_returnsError() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", 50L);
+        // 缺 taskId / amount
+
+        Result<EnergyLog> result = controller.grantEnergy(params, 100L, 50L);
+
+        assertEquals(500, result.getCode());
+        assertNotNull(result.getMessage());
+        assertEquals("memberId、taskId和amount不能为空", result.getMessage());
+    }
+
+    @Test
+    @DisplayName("CFC-EN-001:无家庭返回 noFamily 错误提示")
+    void grantEnergy_noFamily_returnsNoFamilyError() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", 50L);
+        params.put("taskId", 8888L);
+        params.put("amount", 10L);
+        params.put("dimensionCode", "body");
+
+        Result<EnergyLog> result = controller.grantEnergy(params, null, 50L);
+
+        assertNotNull(result.getMessage());
+        assertEquals(5001, result.getCode());
+        assertEquals("请先创建或加入家庭", result.getMessage());
+    }
+
+    private void inject(Object target, String fieldName, Object value) throws Exception {
+        Field field = EnergyController.class.getDeclaredField(fieldName);
+        field.setAccessible(true);
+        field.set(target, value);
+    }
+}

+ 194 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/FamilyEarningsAdminRoleGateTest.java

@@ -0,0 +1,194 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyEarningsService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 需求变更 b9cf2d20b「财富中心贡献榜管理员口径以 role 为准」契约级单测。
+ * 锁定 FamilyEarningsController 的管理员判定口径:role ∈ {parent, teacher} 才放行,
+ * 其余角色(如 child / member)一律视为无权限(返回 code=500, message=无权限操作)。
+ * 仅校验「管理员口径」逻辑,不依赖 Spring 上下文(mock UserMapper / FamilyEarningsService)。
+ *
+ * 对应生产实现:FamilyEarningsController.isFamilyAdmin(userId) 以 user.getRole() 判定。
+ */
+public class FamilyEarningsAdminRoleGateTest {
+
+    private FamilyEarningsController controller;
+    private UserMapper userMapper;
+    private FamilyEarningsService familyEarningsService;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new FamilyEarningsController();
+        userMapper = mock(UserMapper.class);
+        familyEarningsService = mock(FamilyEarningsService.class);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        ReflectionTestUtils.setField(controller, "familyEarningsService", familyEarningsService);
+    }
+
+    private void givenUser(Long userId, String role, Long familyId) {
+        User u = new User();
+        u.setId(userId);
+        u.setRole(role);
+        u.setFamilyId(familyId);
+        when(userMapper.selectById(userId)).thenReturn(u);
+    }
+
+    // ---- /admin/distribute ----
+
+    @Test
+    public void distribute_parentRole_isAllowed_andDelegatesToService() {
+        Long adminId = 1L, familyId = 10L, memberId = 2L, amount = 100L;
+        givenUser(adminId, "parent", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", memberId.intValue());
+        params.put("amount", amount.intValue());
+
+        Result<String> r = controller.distribute(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(200, r.getCode(), "parent 角色应放行 distribute");
+        verify(familyEarningsService, times(1))
+                .distribute(eq(familyId), eq(memberId), eq(amount), eq(adminId));
+    }
+
+    @Test
+    public void distribute_teacherRole_isAllowed() {
+        Long adminId = 4L, familyId = 11L, memberId = 5L, amount = 50L;
+        givenUser(adminId, "teacher", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", memberId.intValue());
+        params.put("amount", amount.intValue());
+
+        Result<String> r = controller.distribute(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(200, r.getCode(), "teacher 角色应放行 distribute");
+        verify(familyEarningsService, times(1))
+                .distribute(eq(familyId), eq(memberId), eq(amount), eq(adminId));
+    }
+
+    @Test
+    public void distribute_childRole_isForbidden() {
+        Long adminId = 3L, familyId = 10L;
+        givenUser(adminId, "child", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", 2);
+        params.put("amount", 100);
+
+        Result<String> r = controller.distribute(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(500, r.getCode(), "非 parent/teacher 角色应被拒绝");
+        assertEquals("无权限操作", r.getMessage());
+        verify(familyEarningsService, never()).distribute(anyLong(), anyLong(), anyLong(), anyLong());
+    }
+
+    @Test
+    public void distribute_memberRole_isForbidden() {
+        Long adminId = 6L, familyId = 10L;
+        givenUser(adminId, "member", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", 2);
+        params.put("amount", 100);
+
+        Result<String> r = controller.distribute(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(500, r.getCode(), "非 parent/teacher 角色应被拒绝");
+        assertEquals("无权限操作", r.getMessage());
+        verify(familyEarningsService, never()).distribute(anyLong(), anyLong(), anyLong(), anyLong());
+    }
+
+    // ---- /admin/toggle-member ----
+
+    @Test
+    public void toggleMember_parentRole_isAllowed() {
+        Long adminId = 1L, familyId = 10L, memberId = 2L;
+        givenUser(adminId, "parent", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", memberId.intValue());
+        params.put("enabled", Boolean.TRUE);
+
+        Result<String> r = controller.toggleMember(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(200, r.getCode());
+        verify(familyEarningsService, times(1))
+                .toggleMemberAccess(eq(familyId), eq(memberId), eq(Boolean.TRUE));
+    }
+
+    @Test
+    public void toggleMember_childRole_isForbidden() {
+        Long adminId = 3L, familyId = 10L;
+        givenUser(adminId, "child", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("userId", 2);
+        params.put("enabled", Boolean.TRUE);
+
+        Result<String> r = controller.toggleMember(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(500, r.getCode());
+        assertEquals("无权限操作", r.getMessage());
+        verify(familyEarningsService, never()).toggleMemberAccess(anyLong(), anyLong(), anyBoolean());
+    }
+
+    // ---- /admin/withdraw ----
+
+    @Test
+    public void withdraw_parentRole_isAllowed() {
+        Long adminId = 1L, familyId = 10L, amount = 200L;
+        givenUser(adminId, "parent", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("amount", amount.intValue());
+
+        Result<String> r = controller.withdraw(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(200, r.getCode());
+        verify(familyEarningsService, times(1)).withdraw(eq(familyId), eq(amount), eq(adminId));
+    }
+
+    @Test
+    public void withdraw_memberRole_isForbidden() {
+        Long adminId = 6L, familyId = 10L;
+        givenUser(adminId, "member", familyId);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("amount", 200);
+
+        Result<String> r = controller.withdraw(adminId, params);
+
+        assertNotNull(r);
+        assertEquals(500, r.getCode());
+        assertEquals("无权限操作", r.getMessage());
+        verify(familyEarningsService, never()).withdraw(anyLong(), anyLong(), anyLong());
+    }
+}

+ 32 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/FamilyWorkbenchContractTest.java

@@ -0,0 +1,32 @@
+package com.etotem.cfc.controller;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.web.servlet.MockMvc;
+
+/**
+ * 单家庭工作台-端到端鉴权契约(CI 跑,需 dev 库):
+ * 匿名访问 /api/admin/families/{id}/workbench 必须由 JwtInterceptor 返回 HTTP 401 + {"code":401}
+ * (/api/admin/** 在 LOGIN_REQUIRED_PATHS);非 admin 由 @PreAuthorize → GlobalExceptionHandler 回 200+{code:403},
+ * 由 AdminWorkbenchAuthContractTest 的 @PreAuthorize 断言覆盖(本类只断言匿名 401,仿 GrowthAuthContractTest)。
+ */
+@SpringBootTest
+@AutoConfigureMockMvc
+class FamilyWorkbenchContractTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @Test
+    void 匿名访问家庭工作台_应401() throws Exception {
+        mockMvc.perform(post("/api/admin/families/1/workbench"))
+                .andExpect(status().isUnauthorized())
+                .andExpect(jsonPath("$.code").value(401));
+    }
+}

+ 231 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthCheckinCfEarnCallSiteTest.java

@@ -0,0 +1,231 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DailyHealthCheckin;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthMealRecord;
+import com.etotem.cfc.entity.HealthWaterRecord;
+import com.etotem.cfc.mapper.DailyCheckinMapper;
+import com.etotem.cfc.mapper.EmotionCheckinMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.FoodRecommendIndexMapper;
+import com.etotem.cfc.mapper.HealthMealRecordMapper;
+import com.etotem.cfc.mapper.HealthWaterRecordMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.CfGrowthPathwayEarnService;
+import com.etotem.cfc.service.ChallengeService;
+import com.etotem.cfc.service.DailyCheckinService;
+import com.etotem.cfc.service.ProfileComputeService;
+import com.etotem.cfc.service.TaskService;
+import com.etotem.cfc.util.IdempotencyUtil;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.sql.Date;
+import java.time.LocalDate;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * F-3b2 健康打卡类调用点单测(F14 喝水 / F15 饮食 / F16 每日健康打卡):
+ *  - 打卡创建成功后改投统一入口 earnByRule(经 CfGrowthPathwayEarnService 收口),
+ *    数量不再由调用点传入(旧 PointsService.awardCheckinPoints(memberId, 5/10) 直写旧账本已移除);
+ *  - 幂等 ref_id 统一取打卡记录 ID(health_water_records / health_meal_records / daily_health_checkin);
+ *  - 饮食打卡补打(isBackfill=1)不发放,维持既有业务口径。
+ */
+class HealthCheckinCfEarnCallSiteTest {
+
+    private static final long MEMBER_ID = 1L;
+    private static final long USER_ID = 100L;
+
+    @Mock
+    private HealthWaterRecordMapper healthWaterRecordMapper;
+    @Mock
+    private HealthMealRecordMapper healthMealRecordMapper;
+    @Mock
+    private FoodRecommendIndexMapper foodRecommendIndexMapper;
+    @Mock
+    private TaskMapper taskMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @Mock
+    private TaskService taskService;
+    @Mock
+    private CfGrowthPathwayEarnService cfGrowthPathwayEarnService;
+    @Mock
+    private ProfileComputeService profileComputeService;
+    @Mock
+    private DailyCheckinMapper dailyCheckinMapper;
+    @Mock
+    private EmotionCheckinMapper emotionCheckinMapper;
+    @Mock
+    private ChallengeService challengeService;
+    @Mock
+    private IdempotencyUtil idempotencyUtil;
+
+    private HealthWaterController waterController;
+    private HealthMealController mealController;
+    private DailyCheckinService dailyCheckinService;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        waterController = new HealthWaterController();
+        ReflectionTestUtils.setField(waterController, "healthWaterRecordMapper", healthWaterRecordMapper);
+        ReflectionTestUtils.setField(waterController, "taskMapper", taskMapper);
+        ReflectionTestUtils.setField(waterController, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(waterController, "cfGrowthPathwayEarnService", cfGrowthPathwayEarnService);
+        ReflectionTestUtils.setField(waterController, "taskService", taskService);
+
+        mealController = new HealthMealController();
+        ReflectionTestUtils.setField(mealController, "healthMealRecordMapper", healthMealRecordMapper);
+        ReflectionTestUtils.setField(mealController, "foodRecommendIndexMapper", foodRecommendIndexMapper);
+        ReflectionTestUtils.setField(mealController, "cfGrowthPathwayEarnService", cfGrowthPathwayEarnService);
+        ReflectionTestUtils.setField(mealController, "taskService", taskService);
+        ReflectionTestUtils.setField(mealController, "taskMapper", taskMapper);
+        ReflectionTestUtils.setField(mealController, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(mealController, "profileComputeService", profileComputeService);
+
+        dailyCheckinService = new DailyCheckinService();
+        ReflectionTestUtils.setField(dailyCheckinService, "dailyCheckinMapper", dailyCheckinMapper);
+        ReflectionTestUtils.setField(dailyCheckinService, "cfGrowthPathwayEarnService", cfGrowthPathwayEarnService);
+        ReflectionTestUtils.setField(dailyCheckinService, "emotionCheckinMapper", emotionCheckinMapper);
+        ReflectionTestUtils.setField(dailyCheckinService, "challengeService", challengeService);
+        ReflectionTestUtils.setField(dailyCheckinService, "idempotencyUtil", idempotencyUtil);
+    }
+
+    // ---------- F14 喝水打卡 ----------
+
+    @Test
+    void F14_创建喝水打卡_改投统一入口_refId为记录ID() {
+        HealthWaterRecord record = new HealthWaterRecord();
+        record.setMemberId(MEMBER_ID);
+        record.setAmountMl(500);
+        when(healthWaterRecordMapper.insert(any())).thenAnswer(inv -> {
+            HealthWaterRecord r = inv.getArgument(0);
+            r.setId(1001L);
+            return 1;
+        });
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(member(MEMBER_ID, USER_ID));
+
+        Result<HealthWaterRecord> result = waterController.create(record, MEMBER_ID);
+
+        assertEquals(200, result.getCode());
+        verify(cfGrowthPathwayEarnService).earnWaterCheckinCf(MEMBER_ID, 1001L);
+    }
+
+    @Test
+    void F14_发放失败不影响打卡主流程() {
+        HealthWaterRecord record = new HealthWaterRecord();
+        record.setMemberId(MEMBER_ID);
+        when(healthWaterRecordMapper.insert(any())).thenAnswer(inv -> {
+            HealthWaterRecord r = inv.getArgument(0);
+            r.setId(1002L);
+            return 1;
+        });
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(null);
+        org.mockito.Mockito.doThrow(new RuntimeException("db down"))
+                .when(cfGrowthPathwayEarnService).earnWaterCheckinCf(anyLong(), anyLong());
+
+        Result<HealthWaterRecord> result = waterController.create(record, MEMBER_ID);
+
+        assertEquals(200, result.getCode());
+        assertEquals(1002L, result.getData().getId());
+    }
+
+    // ---------- F15 饮食打卡 ----------
+
+    @Test
+    void F15_创建饮食打卡_改投统一入口_refId为记录ID() {
+        HealthMealRecord record = new HealthMealRecord();
+        record.setMemberId(MEMBER_ID);
+        record.setMealType("breakfast");
+        record.setFoodItems("苹果,牛奶");
+        when(healthMealRecordMapper.insert(any())).thenAnswer(inv -> {
+            HealthMealRecord r = inv.getArgument(0);
+            r.setId(2001L);
+            return 1;
+        });
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(member(MEMBER_ID, USER_ID));
+
+        Result<HealthMealRecord> result = mealController.create(record, MEMBER_ID);
+
+        assertEquals(200, result.getCode());
+        verify(cfGrowthPathwayEarnService).earnMealCheckinCf(MEMBER_ID, 2001L);
+    }
+
+    @Test
+    void F15_补打不打积分_不发CF() {
+        HealthMealRecord record = new HealthMealRecord();
+        record.setMemberId(MEMBER_ID);
+        record.setMealType("breakfast");
+        record.setFoodItems("鸡蛋");
+        record.setIsBackfill(1);
+        record.setRecordDate(Date.valueOf(LocalDate.now()));
+        when(healthMealRecordMapper.insert(any())).thenAnswer(inv -> {
+            HealthMealRecord r = inv.getArgument(0);
+            r.setId(2002L);
+            return 1;
+        });
+
+        Result<HealthMealRecord> result = mealController.create(record, MEMBER_ID);
+
+        assertEquals(200, result.getCode());
+        verify(cfGrowthPathwayEarnService, never()).earnMealCheckinCf(any(), any());
+    }
+
+    // ---------- F16 每日健康打卡 ----------
+
+    @Test
+    void F16_每日健康打卡_改投统一入口_refId为打卡记录ID() {
+        DailyHealthCheckin checkin = new DailyHealthCheckin();
+        checkin.setMemberId(MEMBER_ID);
+        checkin.setDietScore(8);
+        when(idempotencyUtil.tryAcquire(anyString(), anyLong())).thenReturn(true);
+        when(dailyCheckinMapper.insert(any())).thenAnswer(inv -> {
+            DailyHealthCheckin c = inv.getArgument(0);
+            c.setId(3001L);
+            return 1;
+        });
+
+        DailyHealthCheckin created = dailyCheckinService.createCheckin(checkin);
+
+        assertEquals(3001L, created.getId());
+        verify(cfGrowthPathwayEarnService).earnDailyHealthCheckinCf(MEMBER_ID, 3001L);
+    }
+
+    @Test
+    void F16_发放失败不影响打卡主流程() {
+        DailyHealthCheckin checkin = new DailyHealthCheckin();
+        checkin.setMemberId(MEMBER_ID);
+        when(idempotencyUtil.tryAcquire(anyString(), anyLong())).thenReturn(true);
+        when(dailyCheckinMapper.insert(any())).thenAnswer(inv -> {
+            DailyHealthCheckin c = inv.getArgument(0);
+            c.setId(3002L);
+            return 1;
+        });
+        org.mockito.Mockito.doThrow(new RuntimeException("cf service down"))
+                .when(cfGrowthPathwayEarnService).earnDailyHealthCheckinCf(anyLong(), anyLong());
+
+        DailyHealthCheckin created = dailyCheckinService.createCheckin(checkin);
+
+        assertEquals(3002L, created.getId());
+    }
+
+    private FamilyMember member(long memberId, long userId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(memberId);
+        m.setUserId(userId);
+        return m;
+    }
+}

+ 371 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthDimensionControllerUploadContractTest.java

@@ -0,0 +1,371 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.dto.DimensionUploadVO;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.service.DimensionScoreService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.math.BigDecimal;
+
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-19 / 能力键 health.report.upload,原始阶段 GREEN → 补齐契约级单测):
+ * HealthDimensionController POST /api/dimension/upload(手动录入维度评分)HTTP 契约级单测。
+ *
+ * 与既有 {@code integration/controller/HealthDimensionControllerTest} 的区别:后者是
+ * {@code @SpringBootTest} 直接调用 controller 方法(不经 HTTP 层,discovery 记为 direct),
+ * 本类走 MockMvc standalone 真实请求链路,钉住「JSON 绑定 + @RequestAttribute 注入 +
+ * Result 信封序列化 + 路由方法约束」这些控制器契约。
+ *
+ * 溯源说明(务必同步编排侧):
+ * - 任务卡引用「docs/tdd/SRS.md §5.5 health.report.upload」,但当前 checkout 的 SRS.md 只有
+ *   一/二/三/四/五章,无 §5.5,也无 health.report.upload 字样(契约仍为 ⏳未契约化,P0 用例 0)。
+ *   因此本测试的契约以「现有实现 + DimensionUploadVO + Result 信封 + AGENTS.md 约定」为准,
+ *   并在下方逐条记录缺口,不擅自新增规格。
+ * - 能力键 health.report.upload 在 discovery 中是按方法名 upload 命中的;该 handler 实际语义是
+ *   「维度评分录入」,PDF 报告上传对应 HealthReportController POST /api/health/report/upload
+ *   (已由 S-cfc-18 HealthReportControllerUploadTest 覆盖,本类不重复)。
+ *
+ * 契约(HealthDimensionController.upload:118-128):
+ * - 请求:application/json,body 为 DimensionUploadVO(memberId / dimension / score 必填,
+ *   sourceType / confidence / recordDate 可选);userId 由 JwtInterceptor 注入
+ *   @RequestAttribute("userId")(本层只接收、不参与业务判断)。
+ * - 正常路径:三必填齐全 → dimensionScoreService.uploadScore(vo) → Result.success(null),
+ *   envelope code=200 / message="success" / data=null。
+ * - 边界:三个必填任一为 null → Result.error("memberId, dimension, score不能为空"),
+ *   且不得调用 Service(先校验后落库)。
+ * - 角色/权限:本层不读 @RequestAttribute("role"),家长/规划师(teacher)/管理员(admin) 同一路径;
+ *   授权由 JwtInterceptor(有效 token → userId)+ FamilyAccessInterceptor(familyId 归属)承担。
+ * - 路由约定:统一 @PostMapping;GET 同路径必须 405。
+ *
+ * 缺陷观察(只记录、不改 src/main,交编排侧转 GREEN 决策):
+ * D1【无分值区间校验】score 只判 null:-1、1000 均原样进入 Service;Service 侧
+ *   BigDecimal.intValue() 会截断小数(80.9 → 80),区间与精度契约未定义。
+ * D2【无维度白名单】dimension 只判 null:空串 ""、任意未注册维度(如 not_a_dimension)均放行。
+ * D3【无日期格式校验】recordDate 原样透传,非法格式在 Service 的 java.sql.Date.valueOf 抛
+ *   IllegalArgumentException,Controller 层不转 Result.error。
+ * D4【无成员归属校验】body 的 memberId 未与当前 userId 家庭比对(FamilyAccessInterceptor 仅校验
+ *   familyId,不校验 memberId),任意登录用户可对任意 memberId 写评分 → 水平越权风险。
+ * D5【错误码非 4xx】必填缺失返回 Result.error(String) → envelope code=500(B-3 同类口径要求 400),
+ *   HTTP 状态恒 200(项目统一 Result 包装)。
+ * D6【框架级 400/415 无信封】缺 body / JSON 语法错误 / score 非数字 / Content-Type 不支持 /
+ *   缺失 @RequestAttribute("userId")(ServletRequestBindingException)均由 Spring MVC 直接返回
+ *   400/415,无 Result 信封(生产环境另有 GlobalExceptionHandler 归一,但 standalone 不加载,
+ *   此处钉住 MVC 层原始行为)。
+ *
+ * 测试隔离:MockMvc standalone + mock DimensionScoreService / FamilyMemberMapper,
+ * 无 Spring 上下文、无 DB、无微信/LangGraph 等外部服务。
+ */
+public class HealthDimensionControllerUploadContractTest {
+
+    private static final String URL = "/api/dimension/upload";
+    private static final long USER_ID = 1L;
+
+    @Mock
+    private DimensionScoreService dimensionScoreService;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        HealthDimensionController controller = new HealthDimensionController();
+        ReflectionTestUtils.setField(controller, "dimensionScoreService", dimensionScoreService);
+        ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ==================== 夹具 ====================
+
+    private static String validBody() {
+        return "{"
+                + "\"memberId\":10,"
+                + "\"dimension\":\"sleep\","
+                + "\"score\":80.5,"
+                + "\"sourceType\":\"VOICE\","
+                + "\"confidence\":0.8,"
+                + "\"recordDate\":\"2026-11-06\""
+                + "}";
+    }
+
+    private ResultActions postJson(String json) throws Exception {
+        return mockMvc.perform(post(URL)
+                .contentType(MediaType.APPLICATION_JSON)
+                .content(json)
+                .requestAttr("userId", USER_ID));
+    }
+
+    private DimensionUploadVO captureUploadedVo() {
+        ArgumentCaptor<DimensionUploadVO> captor = ArgumentCaptor.forClass(DimensionUploadVO.class);
+        verify(dimensionScoreService).uploadScore(captor.capture());
+        return captor.getValue();
+    }
+
+    // ==================== 正常路径 ====================
+
+    @Test
+    public void upload_validPayload_returnsEnvelopeSuccess_andForwardsAllFields() throws Exception {
+        postJson(validBody())
+                .andExpect(status().isOk())
+                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data").value(nullValue()));
+
+        DimensionUploadVO forwarded = captureUploadedVo();
+        assertEquals(Long.valueOf(10L), forwarded.getMemberId());
+        assertEquals("sleep", forwarded.getDimension());
+        assertNotNull(forwarded.getScore());
+        assertEquals(0, new BigDecimal("80.5").compareTo(forwarded.getScore()));
+        assertEquals("VOICE", forwarded.getSourceType());
+        assertNotNull(forwarded.getConfidence());
+        assertEquals(0, new BigDecimal("0.8").compareTo(forwarded.getConfidence()));
+        assertEquals("2026-11-06", forwarded.getRecordDate());
+    }
+
+    @Test
+    public void upload_minimalPayload_forwardsNullOptionalFieldsWithoutDefaults() throws Exception {
+        // 可选字段默认值(sourceType=MANUAL / tier / assessDate=今天)由 Service 承担,
+        // Controller 只做透传,不得在 DTO 层补默认值。
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        DimensionUploadVO forwarded = captureUploadedVo();
+        assertNull(forwarded.getSourceType());
+        assertNull(forwarded.getConfidence());
+        assertNull(forwarded.getRecordDate());
+    }
+
+    @Test
+    public void upload_decimalScore_notTruncatedAtController() throws Exception {
+        // 截断只允许发生在 Service(intValue),Controller 必须保留原始精度与 scale
+        postJson("{\"memberId\":10,\"dimension\":\"growth\",\"score\":80.9}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        DimensionUploadVO forwarded = captureUploadedVo();
+        assertEquals(0, new BigDecimal("80.9").compareTo(forwarded.getScore()));
+        assertEquals(1, forwarded.getScore().scale());
+    }
+
+    // ==================== 关键边界:必填校验 ====================
+
+    @Test
+    public void upload_missingMemberId_rejectedBeforeServiceCall() throws Exception {
+        postJson("{\"dimension\":\"sleep\",\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("memberId, dimension, score不能为空"));
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_missingDimension_rejectedBeforeServiceCall() throws Exception {
+        postJson("{\"memberId\":10,\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("memberId, dimension, score不能为空"));
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_missingScore_rejectedBeforeServiceCall() throws Exception {
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\"}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("memberId, dimension, score不能为空"));
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_allFieldsAbsent_rejected() throws Exception {
+        postJson("{}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("memberId, dimension, score不能为空"));
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_blankDimensionString_accepted_pinsObservedGap() throws Exception {
+        // D2:dimension 只判 null,空串同样放行入库
+        postJson("{\"memberId\":10,\"dimension\":\"\",\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        assertEquals("", captureUploadedVo().getDimension());
+    }
+
+    @Test
+    public void upload_unknownDimension_accepted_pinsObservedGap() throws Exception {
+        // D2:无维度白名单,未注册维度直接入库
+        postJson("{\"memberId\":10,\"dimension\":\"not_a_dimension\",\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        assertEquals("not_a_dimension", captureUploadedVo().getDimension());
+    }
+
+    // ==================== 关键边界:分值区间 ====================
+
+    @Test
+    public void upload_zeroScore_acceptedBoundary() throws Exception {
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":0}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        assertEquals(0, BigDecimal.ZERO.compareTo(captureUploadedVo().getScore()));
+    }
+
+    @Test
+    public void upload_hundredScore_acceptedBoundary() throws Exception {
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":100}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        assertEquals(0, new BigDecimal("100").compareTo(captureUploadedVo().getScore()));
+    }
+
+    @Test
+    public void upload_outOfRangeScores_notRejected_pinsObservedGap() throws Exception {
+        // D1:score 无 [0,100] 区间校验,负数与超上限均原样透传
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":-1}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":1000}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(dimensionScoreService, times(2)).uploadScore(any());
+    }
+
+    // ==================== 关键边界:请求形态(框架层) ====================
+
+    @Test
+    public void upload_nonNumericScore_rejectedByJackson() throws Exception {
+        postJson("{\"memberId\":10,\"dimension\":\"sleep\",\"score\":\"abc\"}")
+                .andExpect(status().isBadRequest());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_malformedJson_rejected() throws Exception {
+        postJson("{\"memberId\":10,")
+                .andExpect(status().isBadRequest());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_missingBody_rejected() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", USER_ID))
+                .andExpect(status().isBadRequest());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_unsupportedContentType_rejected() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.TEXT_PLAIN)
+                        .content(validBody())
+                        .requestAttr("userId", USER_ID))
+                .andExpect(status().isUnsupportedMediaType());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_getMethod_notAllowed() throws Exception {
+        // AGENTS.md:接口统一 @PostMapping,同路径 GET 必须 405
+        mockMvc.perform(get(URL).requestAttr("userId", USER_ID))
+                .andExpect(status().isMethodNotAllowed());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    // ==================== 角色 / 权限 ====================
+
+    @Test
+    public void upload_missingUserIdAttribute_failsClosedWithoutServiceCall() throws Exception {
+        // userId 由 JwtInterceptor 注入;缺失即说明未过认证链路(生产环境会被拦截器提前 401)。
+        // MVC 层把缺失的 @RequestAttribute 归为 ServletRequestBindingException → HTTP 400,不落业务。
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(validBody()))
+                .andExpect(status().isBadRequest());
+
+        verify(dimensionScoreService, never()).uploadScore(any());
+    }
+
+    @Test
+    public void upload_teacherRole_notGatedByRoleAttribute() throws Exception {
+        // 规划师(teacher) 与本层无角色分流,走同一 handler;授权在 JwtInterceptor + 家庭归属层
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(validBody())
+                        .requestAttr("userId", USER_ID)
+                        .requestAttr("role", "teacher"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(dimensionScoreService).uploadScore(any());
+    }
+
+    @Test
+    public void upload_adminRole_notGatedByRoleAttribute() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(validBody())
+                        .requestAttr("userId", USER_ID)
+                        .requestAttr("role", "admin"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(dimensionScoreService).uploadScore(any());
+    }
+
+    @Test
+    public void upload_arbitraryMemberId_noOwnershipCheck_pinsObservedGap() throws Exception {
+        // D4:memberId 取自 body,Controller 未与当前 userId 的家庭做归属比对;
+        // FamilyAccessInterceptor 只校验 body/query/path 中的 familyId,本请求不带 familyId 即直通。
+        postJson("{\"memberId\":999,\"dimension\":\"sleep\",\"score\":80}")
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        assertEquals(Long.valueOf(999L), captureUploadedVo().getMemberId());
+    }
+}

+ 158 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanControllerPlanTasksPermissionTest.java

@@ -0,0 +1,158 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.HealthPlan;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.service.HealthPlanService;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.PurchaseService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 18211a546 窗口权限流:非家庭成员越权读取他人健康方案实例(HealthPlanController.planTasks IDOR 防护)。
+ *
+ * <p>契约(源码 {@code HealthPlanController.planTasks} 实测,MockMvc standalone + mock HealthPlanService,
+ * 无 Spring 上下文 / 无 DB):</p>
+ * <ul>
+ *   <li>正常流:JWT 注入的 familyId 与方案归属 familyId 一致 → 返回方案任务列表(code=200, data=任务数组)。</li>
+ *   <li>权限流·越权读取:familyId 与方案归属 familyId 不一致(非家庭成员/跨家庭)→ 拒绝
+ *       code=500「无权查看该方案任务」,且 <b>不调用</b> {@code getPlanTasks}(服务层不泄露他人实例数据)。</li>
+ *   <li>异常流·参数/存在性:planId 为空 → 「planId不能为空」;方案不存在 → 「方案不存在」(均 code=500)。</li>
+ * </ul>
+ *
+ * <p>观察(不在此造绿):{@code planTasks} 在 familyId==null 时跳过归属校验直接返回任务
+ * (JwtInterceptor 为已登录用户注入 familyId,匿名/未登录场景由鉴权层口径约束——该 handler 是否列入
+ * LOGIN_REQUIRED_PATHS 属鉴权配置范畴,不在本控制器契约内判定)。</p>
+ *
+ * <p>运行:cd cfc-backend &amp;&amp; mvn test -Dtest=HealthPlanControllerPlanTasksPermissionTest</p>
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+public class HealthPlanControllerPlanTasksPermissionTest {
+
+    private static final String URL = "/api/health/plan/tasks";
+
+    @Mock
+    private HealthPlanService healthPlanService;
+
+    @Mock
+    private PurchaseService purchaseService;
+
+    @Mock
+    private MembershipService membershipService;
+
+    @InjectMocks
+    private HealthPlanController controller;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private HealthPlan plan(Long id, Long familyId) {
+        HealthPlan p = new HealthPlan();
+        p.setId(id);
+        p.setFamilyId(familyId);
+        return p;
+    }
+
+    private Task task(Long id, String title) {
+        Task t = new Task();
+        t.setId(id);
+        t.setTitle(title);
+        t.setSourceType("health_plan");
+        return t;
+    }
+
+    /** 正常流:归属家庭读自己的方案任务列表。 */
+    @Test
+    public void 归属家庭读取自身方案任务_返回任务列表() throws Exception {
+        Long familyId = 111L;
+        Long planId = 200L;
+        HealthPlan plan = plan(planId, familyId);
+        List<Task> tasks = Arrays.asList(task(1L, "晨起喝水"), task(2L, "晚间拉伸"));
+        when(healthPlanService.getPlanDetail(eq(planId))).thenReturn(plan);
+        when(healthPlanService.getPlanTasks(eq(planId))).thenReturn(tasks);
+
+        mockMvc.perform(post(URL)
+                        .requestAttr("familyId", familyId)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":200}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data.length()").value(2));
+        verify(healthPlanService).getPlanTasks(eq(planId));
+    }
+
+    /** 权限流:非家庭成员(跨家庭)读取他人方案实例 → 拒绝「无权查看该方案任务」。 */
+    @Test
+    public void 非家庭成员越权读取他人方案实例_拒绝且不泄露() throws Exception {
+        Long ownerFamily = 111L;   // 方案归属家庭
+        Long attackerFamily = 999L; // 越权用户所在家庭(非成员)
+        Long planId = 200L;
+        when(healthPlanService.getPlanDetail(eq(planId))).thenReturn(plan(planId, ownerFamily));
+
+        mockMvc.perform(post(URL)
+                        .requestAttr("familyId", attackerFamily)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":200}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("无权查看该方案任务"));
+        // 越权时服务层不读取方案任务(不泄露他人实例数据)
+        verify(healthPlanService, never()).getPlanTasks(any());
+    }
+
+    /** 异常流:planId 为空 → 参数缺失拒绝。 */
+    @Test
+    public void planId为空_拒绝参数缺失() throws Exception {
+        mockMvc.perform(post(URL)
+                        .requestAttr("familyId", 111L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("planId不能为空"));
+        verify(healthPlanService, never()).getPlanDetail(any());
+    }
+
+    /** 异常流:方案不存在 → 拒绝。 */
+    @Test
+    public void 方案不存在_拒绝() throws Exception {
+        when(healthPlanService.getPlanDetail(eq(300L))).thenReturn(null);
+
+        mockMvc.perform(post(URL)
+                        .requestAttr("familyId", 111L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":300}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("方案不存在"));
+        verify(healthPlanService, never()).getPlanTasks(any());
+    }
+}

+ 95 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanDeleteControllerTest.java

@@ -0,0 +1,95 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.admin.AdminHealthPlanController;
+import com.etotem.cfc.service.HealthPlanService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * 健康方案删除端点 §4.3 错误处理契约:
+ * - planId 为空 → Result.error("planId不能为空")
+ * - 方案不存在(Service 抛 IllegalStateException)→ Result.error("方案不存在")
+ * - 归属不匹配(Service 返回 null)→ Result.error("无权删除该方案")
+ * - 删除成功 → Result.success({planId, taskCount})
+ */
+class HealthPlanDeleteControllerTest {
+
+    private HealthPlanController userController;
+    private AdminHealthPlanController adminController;
+    private HealthPlanService planService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        userController = new HealthPlanController();
+        adminController = new AdminHealthPlanController();
+        planService = mock(HealthPlanService.class);
+        set("healthPlanService", userController, planService);
+        set("healthPlanService", adminController, planService);
+    }
+
+    private void set(String name, Object target, Object v) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, v);
+    }
+
+    private Map<String, Object> params(Object planId) {
+        Map<String, Object> p = new HashMap<>();
+        p.put("planId", planId);
+        return p;
+    }
+
+    @Test
+    void 用户端_planId为空返回错误() {
+        Result<?> r = userController.deletePlan(params(null), 1L, 10L);
+        assertEquals("planId不能为空", r.getMessage());
+        verify(planService, never()).deletePlanCascade(any(), any());
+    }
+
+    @Test
+    void 用户端_方案不存在返回方案不存在() {
+        when(planService.deletePlanCascade(99L, 10L)).thenThrow(new IllegalStateException("方案不存在"));
+        Result<?> r = userController.deletePlan(params(99L), 1L, 10L);
+        assertEquals("方案不存在", r.getMessage());
+    }
+
+    @Test
+    void 用户端_归属不匹配返回无权删除() {
+        when(planService.deletePlanCascade(99L, 20L)).thenReturn(null);
+        Result<?> r = userController.deletePlan(params(99L), 1L, 20L);
+        assertEquals("无权删除该方案", r.getMessage());
+    }
+
+    @Test
+    void 用户端_删除成功返回taskCount() {
+        Map<String, Object> data = new HashMap<>();
+        data.put("planId", 99L);
+        data.put("taskCount", 5);
+        when(planService.deletePlanCascade(99L, 10L)).thenReturn(data);
+        Result<?> r = userController.deletePlan(params(99L), 1L, 10L);
+        assertEquals(200, r.getCode());
+        assertEquals(5, ((Map<?, ?>) r.getData()).get("taskCount"));
+    }
+
+    @Test
+    void 管理端_方案不存在返回方案不存在() {
+        when(planService.deletePlanCascade(99L, null)).thenThrow(new IllegalStateException("方案不存在"));
+        Result<?> r = adminController.deletePlan(params(99L), "admin", null);
+        assertEquals("方案不存在", r.getMessage());
+    }
+
+    @Test
+    void 管理端_planId为空返回错误() {
+        Result<?> r = adminController.deletePlan(params(null), "admin", null);
+        assertEquals("planId不能为空", r.getMessage());
+        verify(planService, never()).deletePlanCascade(any(), any());
+    }
+}

+ 249 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthPlanProductSelectionContractTest.java

@@ -0,0 +1,249 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.HealthPlanService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * HL-05/R5+R6 产品多选一购买任务契约测试(B-114 覆盖缺口闭环):
+ * - POST /api/health-plan/product-options(productOptions)
+ * - POST /api/health-plan/product-select(productSelect)
+ * - POST /api/health-plan/purchase-complete(purchaseComplete)
+ *
+ * 覆盖:参数校验 / familyId 归属校验 / Service 异常映射 / 成功分支 / 幂等复用。
+ * 与既有 HealthPlanDeleteControllerTest 风格一致(mock Service + 反射注入)。
+ */
+class HealthPlanProductSelectionContractTest {
+
+    private HealthPlanController userController;
+    private HealthPlanService planService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        userController = new HealthPlanController();
+        planService = mock(HealthPlanService.class);
+        set("healthPlanService", userController, planService);
+    }
+
+    private void set(String name, Object target, Object v) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, v);
+    }
+
+    private Map<String, Object> params(Object planId, Object familyId) {
+        Map<String, Object> p = new HashMap<>();
+        if (planId != null) p.put("planId", planId);
+        if (familyId != null) p.put("familyId", familyId);
+        return p;
+    }
+
+    // ==================== product-options ====================
+
+    @Test
+    void productOptions_planId为空返回错误() {
+        Result<?> r = userController.productOptions(params(null, 10L), 1L, 10L);
+        assertEquals("planId不能为空", r.getMessage());
+        verify(planService, never()).getPlanProductGroups(any(), any(), any());
+    }
+
+    @Test
+    void productOptions_familyId为空返回错误() {
+        Result<?> r = userController.productOptions(params(99L, null), 1L, null);
+        assertEquals("familyId不能为空", r.getMessage());
+        verify(planService, never()).getPlanProductGroups(any(), any(), any());
+    }
+
+    @Test
+    void productOptions_service抛异常映射为业务错误() {
+        when(planService.getPlanProductGroups(99L, 10L, 1L))
+                .thenThrow(new IllegalStateException("方案不存在"));
+        Result<?> r = userController.productOptions(params(99L, 10L), 1L, 10L);
+        assertEquals(500, r.getCode());
+        assertEquals("方案不存在", r.getMessage());
+    }
+
+    @Test
+    void productOptions_归属不匹配返回无权查看() {
+        when(planService.getPlanProductGroups(99L, 20L, 1L)).thenReturn(null);
+        Result<?> r = userController.productOptions(params(99L, 20L), 1L, 20L);
+        assertEquals("无权查看该方案产品", r.getMessage());
+    }
+
+    @Test
+    void productOptions_成功返回产品分组() {
+        List<Map<String, Object>> groups = new ArrayList<>();
+        Map<String, Object> g = new HashMap<>();
+        g.put("category", "营养补充");
+        g.put("dimensionCode", "body");
+        List<Map<String, Object>> options = new ArrayList<>();
+        Map<String, Object> o = new HashMap<>();
+        o.put("productId", 1001L);
+        o.put("name", "蛋白粉");
+        options.add(o);
+        g.put("options", options);
+        groups.add(g);
+        when(planService.getPlanProductGroups(99L, 10L, 1L)).thenReturn(groups);
+
+        Result<?> r = userController.productOptions(params(99L, 10L), 1L, 10L);
+        assertEquals(200, r.getCode());
+        @SuppressWarnings("unchecked")
+        List<Map<String, Object>> data = (List<Map<String, Object>>) r.getData();
+        assertEquals(1, data.size());
+        assertEquals("营养补充", data.get(0).get("category"));
+        assertEquals(1, ((List<?>) data.get(0).get("options")).size());
+        // 每类多选一:选项数上限 3(PRODUCT_OPTIONS_PER_GROUP 契约)
+        assertTrue(((List<?>) data.get(0).get("options")).size() <= 3,
+                "每个品类最多给出 3 个候选(多选一契约)");
+    }
+
+    // ==================== product-select ====================
+
+    @Test
+    void productSelect_planId为空返回错误() {
+        Result<?> r = userController.productSelect(params(null, 10L), 1L, 10L);
+        assertEquals("planId不能为空", r.getMessage());
+        verify(planService, never()).confirmProductSelection(any(), any(), any(), any());
+    }
+
+    @Test
+    void productSelect_selections为空返回错误() {
+        Map<String, Object> p = params(99L, 10L);
+        p.put("selections", new ArrayList<>());
+        Result<?> r = userController.productSelect(p, 1L, 10L);
+        assertEquals("selections不能为空", r.getMessage());
+        verify(planService, never()).confirmProductSelection(any(), any(), any(), any());
+    }
+
+    @Test
+    void productSelect_service抛异常映射为业务错误() {
+        Map<String, Object> sel = new HashMap<>();
+        sel.put("category", "营养补充");
+        sel.put("productId", 1001L);
+        sel.put("quantity", 1);
+        Map<String, Object> p = params(99L, 10L);
+        List<Map<String, Object>> selections = new ArrayList<>();
+        selections.add(sel);
+        p.put("selections", selections);
+        when(planService.confirmProductSelection(99L, 10L, 1L, selections))
+                .thenThrow(new IllegalStateException("请先为每类产品选择一项"));
+        Result<?> r = userController.productSelect(p, 1L, 10L);
+        assertEquals(500, r.getCode());
+        assertEquals("请先为每类产品选择一项", r.getMessage());
+    }
+
+    @Test
+    void productSelect_归属不匹配返回无权操作() {
+        Map<String, Object> sel = new HashMap<>();
+        sel.put("category", "营养补充");
+        Map<String, Object> p = params(99L, 20L);
+        List<Map<String, Object>> selections = new ArrayList<>();
+        selections.add(sel);
+        p.put("selections", selections);
+        when(planService.confirmProductSelection(99L, 20L, 1L, selections)).thenReturn(null);
+        Result<?> r = userController.productSelect(p, 1L, 20L);
+        assertEquals("无权操作该方案", r.getMessage());
+    }
+
+    @Test
+    void productSelect_成功返回购买任务与购物车() {
+        Map<String, Object> sel = new HashMap<>();
+        sel.put("category", "营养补充");
+        sel.put("productId", 1001L);
+        sel.put("quantity", 2);
+        Map<String, Object> p = params(99L, 10L);
+        List<Map<String, Object>> selections = new ArrayList<>();
+        selections.add(sel);
+        p.put("selections", selections);
+
+        Map<String, Object> task = new HashMap<>();
+        task.put("id", 5001L);
+        task.put("title", "购买:蛋白粉");
+        task.put("category", "购买任务");
+        Map<String, Object> data = new HashMap<>();
+        data.put("planId", 99L);
+        List<Map<String, Object>> purchaseTasks = new ArrayList<>();
+        purchaseTasks.add(task);
+        data.put("purchaseTasks", purchaseTasks);
+        Map<String, Object> cart = new HashMap<>();
+        cart.put("productId", 1001L);
+        cart.put("quantity", 2);
+        List<Map<String, Object>> cartItems = new ArrayList<>();
+        cartItems.add(cart);
+        data.put("cartItems", cartItems);
+        data.put("cartAddCount", 1);
+
+        when(planService.confirmProductSelection(99L, 10L, 1L, selections)).thenReturn(data);
+        Result<?> r = userController.productSelect(p, 1L, 10L);
+        assertEquals(200, r.getCode());
+        @SuppressWarnings("unchecked")
+        Map<String, Object> d = (Map<String, Object>) r.getData();
+        assertEquals(99L, d.get("planId"));
+        assertEquals(1, ((List<?>) d.get("purchaseTasks")).size());
+        assertEquals("购买:蛋白粉", ((Map<?, ?>) ((List<?>) d.get("purchaseTasks")).get(0)).get("title"));
+        assertEquals(1, d.get("cartAddCount"));
+    }
+
+    // ==================== purchase-complete ====================
+
+    @Test
+    void purchaseComplete_planId为空返回错误() {
+        Result<?> r = userController.purchaseComplete(params(null, 10L), 1L, 10L);
+        assertEquals("planId不能为空", r.getMessage());
+        verify(planService, never()).completePurchaseAndGenerateTasks(any(), any(), any());
+    }
+
+    @Test
+    void purchaseComplete_购买任务不属于该方案抛异常() {
+        Map<String, Object> p = params(99L, 10L);
+        p.put("purchaseTaskId", 777L);
+        when(planService.completePurchaseAndGenerateTasks(99L, 10L, 777L))
+                .thenThrow(new IllegalStateException("购买任务不存在或不属于该方案"));
+        Result<?> r = userController.purchaseComplete(p, 1L, 10L);
+        assertEquals(500, r.getCode());
+        assertEquals("购买任务不存在或不属于该方案", r.getMessage());
+    }
+
+    @Test
+    void purchaseComplete_归属不匹配返回无权操作() {
+        Map<String, Object> p = params(99L, 20L);
+        p.put("purchaseTaskId", 5001L);
+        when(planService.completePurchaseAndGenerateTasks(99L, 20L, 5001L)).thenReturn(null);
+        Result<?> r = userController.purchaseComplete(p, 1L, 20L);
+        assertEquals("无权操作该方案", r.getMessage());
+    }
+
+    @Test
+    void purchaseComplete_成功生成执行任务() {
+        Map<String, Object> task = new HashMap<>();
+        task.put("id", 6001L);
+        task.put("title", "执行:每日补剂");
+        task.put("category", "执行任务");
+        Map<String, Object> data = new HashMap<>();
+        data.put("planId", 99L);
+        List<Map<String, Object>> executionTasks = new ArrayList<>();
+        executionTasks.add(task);
+        data.put("executionTasks", executionTasks);
+        data.put("generatedCount", 1);
+
+        Map<String, Object> p = params(99L, 10L);
+        p.put("purchaseTaskId", 5001L);
+        when(planService.completePurchaseAndGenerateTasks(99L, 10L, 5001L)).thenReturn(data);
+        Result<?> r = userController.purchaseComplete(p, 1L, 10L);
+        assertEquals(200, r.getCode());
+        @SuppressWarnings("unchecked")
+        Map<String, Object> d = (Map<String, Object>) r.getData();
+        assertEquals(1, ((List<?>) d.get("executionTasks")).size());
+        assertEquals(1, d.get("generatedCount"));
+    }
+}

+ 162 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerCreateReportTest.java

@@ -0,0 +1,162 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.PurchaseService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-be-1 / 能力键 health.report.createReport):
+ * POST /api/health/report/create 创建健康报告 的契约级单测。
+ *
+ * 契约(对应 HealthReportController.createReport):
+ * - 未购计划:purchaseService.checkPurchase 返回 isActive=false → Result.error(4001, "请先购买健康启航计划体验包")
+ * - 未建家庭:familyId 缺省 → Result.noFamily("请先创建或加入家庭")
+ * - memberId 空(params 无 memberId 且 currentMemberId 缺省)→ Result.error("memberId不能为空")
+ * - reportType 空 → Result.error("reportType不能为空: physical_exam / gut_flora")
+ * - 正常路径:校验全过 → healthReportService.createReport(report, indicators) → Result.success(created)
+ *
+ * 测试不依赖数据库/外部服务:healthReportService / purchaseService 全 mock;不启 Spring 上下文。
+ */
+public class HealthReportControllerCreateReportTest {
+
+    @Mock private HealthReportService healthReportService;
+    @Mock private PurchaseService purchaseService;
+
+    private MockMvc mockMvc;
+    private HealthReportController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new HealthReportController();
+        // 仅注入本方法使用的两个依赖(其余 @Resource 字段本方法不触碰,保持 null 无碍)
+        ReflectionTestUtils.setField(controller, "healthReportService", healthReportService);
+        ReflectionTestUtils.setField(controller, "purchaseService", purchaseService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private Map<String, Object> purchaseActive(boolean active) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("isActive", active);
+        return m;
+    }
+
+    private static final String BASE_BODY = "{"
+            + "\"memberId\":5,"
+            + "\"reportType\":\"physical_exam\","
+            + "\"overallScore\":88,"
+            + "\"indicators\":[{\"category\":\"blood\",\"indicatorName\":\"WBC\",\"indicatorValue\":\"6.1\",\"unit\":\"10^9/L\"}]"
+            + "}";
+
+    @Test
+    public void createReport_success_returnsCreated() throws Exception {
+        Long userId = 1L;
+        Long familyId = 7L;
+        when(purchaseService.checkPurchase(userId)).thenReturn(purchaseActive(true));
+        HealthReport created = new HealthReport();
+        created.setId(100L);
+        when(healthReportService.createReport(any(HealthReport.class), anyList())).thenReturn(created);
+
+        mockMvc.perform(post("/api/health/report/create")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(BASE_BODY)
+                        .requestAttr("userId", userId)
+                        .requestAttr("familyId", familyId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.id").value(100));
+
+        verify(healthReportService).createReport(any(HealthReport.class), anyList());
+    }
+
+    @Test
+    public void createReport_notPurchased_returns4001() throws Exception {
+        Long userId = 1L;
+        Long familyId = 7L;
+        when(purchaseService.checkPurchase(userId)).thenReturn(purchaseActive(false));
+
+        mockMvc.perform(post("/api/health/report/create")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(BASE_BODY)
+                        .requestAttr("userId", userId)
+                        .requestAttr("familyId", familyId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(4001))
+                .andExpect(jsonPath("$.message").value("请先购买健康启航计划体验包"));
+
+        verify(healthReportService, never()).createReport(any(HealthReport.class), anyList());
+    }
+
+    @Test
+    public void createReport_noFamily_returnsNoFamily() throws Exception {
+        Long userId = 1L;
+        when(purchaseService.checkPurchase(userId)).thenReturn(purchaseActive(true));
+
+        mockMvc.perform(post("/api/health/report/create")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(BASE_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("请先创建或加入家庭"));
+
+        verify(healthReportService, never()).createReport(any(HealthReport.class), anyList());
+    }
+
+    @Test
+    public void createReport_missingMemberId_returnsError() throws Exception {
+        Long userId = 1L;
+        Long familyId = 7L;
+        when(purchaseService.checkPurchase(userId)).thenReturn(purchaseActive(true));
+        String body = "{\"reportType\":\"physical_exam\"}";
+
+        mockMvc.perform(post("/api/health/report/create")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId)
+                        .requestAttr("familyId", familyId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("memberId不能为空"));
+
+        verify(healthReportService, never()).createReport(any(HealthReport.class), anyList());
+    }
+
+    @Test
+    public void createReport_missingReportType_returnsError() throws Exception {
+        Long userId = 1L;
+        Long familyId = 7L;
+        when(purchaseService.checkPurchase(userId)).thenReturn(purchaseActive(true));
+        String body = "{\"memberId\":5}";
+
+        mockMvc.perform(post("/api/health/report/create")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId)
+                        .requestAttr("familyId", familyId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("reportType不能为空: physical_exam / gut_flora"));
+
+        verify(healthReportService, never()).createReport(any(HealthReport.class), anyList());
+    }
+}

+ 313 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerDeleteAuthzTest.java

@@ -0,0 +1,313 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.ReportMemberPermissionService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import javax.servlet.http.HttpServletRequest;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * E09 越权修复契约单测:健康报告 删除/编辑/下载 三个端点的归属/权限校验。
+ *
+ * 契约(对应 HealthReportController 的 deleteReport / editReport / downloadReport):
+ * - userId 未注入 → Result.error("用户未登录")
+ * - reportId 不存在 → Result.error("报告不存在"),不触发底层写/删操作
+ * - 上传者本人(report.userId == userId 且 subjectId 为空)→ 允许
+ * - 家庭管理员(report.familyId 匹配且 isFamilyAdmin=true 且 subjectId 为空)→ 允许
+ * - 被授权成员(subjectId 非空且 canViewMemberReports=true)→ 允许
+ * - 其他登录用户(非本人、非管理员、未被授权)→ Result.error("无权..."),不触发底层操作
+ * - familyId 与 report.familyId 均为空 → 拒绝(edit/download;delete 由成员级判定兜底仅限本人)
+ * - deleteReport:请求方家庭与报告家庭不一致 → 403(SC-P-24-P 跨家庭横向越权)
+ * - deleteReport:报告已关联成长方案(service 抛 IllegalStateException)→ 409 透传,不吞异常
+ *
+ * 测试不依赖数据库/外部服务:healthReportService / reportMemberPermissionService 全 mock;
+ * 不启 Spring 上下文,沿用 HealthPlanDeleteControllerTest 的直接调用模式。
+ */
+class HealthReportControllerDeleteAuthzTest {
+
+    private HealthReportController controller;
+    private HealthReportService healthReportService;
+    private ReportMemberPermissionService reportMemberPermissionService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new HealthReportController();
+        healthReportService = mock(HealthReportService.class);
+        reportMemberPermissionService = mock(ReportMemberPermissionService.class);
+        inject("healthReportService", healthReportService);
+        inject("reportMemberPermissionService", reportMemberPermissionService);
+    }
+
+    private void inject(String name, Object value) throws Exception {
+        Field f = controller.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(controller, value);
+    }
+
+    private Map<String, Object> params(Object reportId) {
+        Map<String, Object> p = new HashMap<>();
+        p.put("reportId", reportId);
+        return p;
+    }
+
+    private HealthReport report(Long reportId, Long ownerUserId, Long familyId) {
+        HealthReport r = new HealthReport();
+        r.setId(reportId);
+        r.setUserId(ownerUserId);
+        r.setFamilyId(familyId);
+        return r;
+    }
+
+    @Test
+    void 未登录_返回用户未登录不触发删除() {
+        Result<?> r = controller.deleteReport(params(1L), null, null);
+        assertEquals("用户未登录", r.getMessage());
+        verify(healthReportService, never()).deleteReport(anyLong());
+    }
+
+    @Test
+    void 报告不存在_返回报告不存在不触发删除() {
+        when(healthReportService.getReportById(99L)).thenReturn(null);
+        Result<?> r = controller.deleteReport(params(99L), 1L, null);
+        assertEquals("报告不存在", r.getMessage());
+        verify(healthReportService, never()).deleteReport(anyLong());
+    }
+
+    @Test
+    void 上传者本人_可删除自己报告() {
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        Result<?> r = controller.deleteReport(params(100L), 10L, null);
+        assertEquals(200, r.getCode());
+        assertEquals("已删除", r.getData());
+        verify(healthReportService).deleteReport(100L);
+    }
+
+    @Test
+    void 家庭管理员_可删除家庭内报告() {
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        when(reportMemberPermissionService.isFamilyAdmin(20L, 7L)).thenReturn(true);
+        Result<?> r = controller.deleteReport(params(100L), 20L, null);
+        assertEquals(200, r.getCode());
+        assertEquals("已删除", r.getData());
+        verify(healthReportService).deleteReport(100L);
+        verify(reportMemberPermissionService).isFamilyAdmin(20L, 7L);
+    }
+
+    @Test
+    void 非本人非管理员_拒绝删除() {
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        when(reportMemberPermissionService.isFamilyAdmin(30L, 7L)).thenReturn(false);
+        Result<?> r = controller.deleteReport(params(100L), 30L, null);
+        assertEquals("无权删除该报告", r.getMessage());
+        assertNotEquals(200, r.getCode());
+        verify(healthReportService, never()).deleteReport(anyLong());
+    }
+
+    @Test
+    void 跨家庭_拒绝删除_403() {
+        // 本人 userId=10 也无权删他家庭(7)的报告:请求方家庭 8 ≠ 报告家庭 7,先于成员级判定拦截
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        Result<?> r = controller.deleteReport(params(100L), 10L, 8L);
+        assertEquals("无权删除该报告", r.getMessage());
+        assertEquals(403, r.getCode());
+        verify(healthReportService, never()).deleteReport(anyLong());
+    }
+
+    @Test
+    void 报告已关联成长方案_拒绝删除_409不吞异常() {
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        doThrow(new IllegalStateException("报告已关联成长方案,请先解除关联")).when(healthReportService).deleteReport(100L);
+        Result<?> r = controller.deleteReport(params(100L), 10L, 7L);
+        assertEquals("报告已关联成长方案,请先解除关联", r.getMessage());
+        assertEquals(409, r.getCode());
+        // 守卫异常被捕获转 409,但 deleteReport 确已调用(不是被静默吞掉)
+        verify(healthReportService).deleteReport(100L);
+    }
+
+    /* ============ editReport:越权编辑 ============ */
+
+    private HealthReport reportWithSubject(Long reportId, Long ownerUserId, Long familyId, Long subjectId) {
+        HealthReport r = report(reportId, ownerUserId, familyId);
+        r.setSubjectId(subjectId);
+        return r;
+    }
+
+    private Map<String, Object> editParams(Object reportId, Object subjectId) {
+        Map<String, Object> p = params(reportId);
+        p.put("subjectId", subjectId);
+        p.put("payload", new HashMap<String, Object>());
+        return p;
+    }
+
+    @Test
+    void 编辑_未登录_返回用户未登录() {
+        Result<?> r = controller.editReport(editParams(100L, null), null, null);
+        assertEquals("用户未登录", r.getMessage());
+        verify(healthReportService, never()).updateReportFromPayload(any(), any(), any(), any());
+    }
+
+    @Test
+    void 编辑_报告不存在_返回报告不存在() {
+        when(healthReportService.getReportById(99L)).thenReturn(null);
+        Result<?> r = controller.editReport(editParams(99L, null), 1L, null);
+        assertEquals("报告不存在", r.getMessage());
+        verify(healthReportService, never()).updateReportFromPayload(any(), any(), any(), any());
+    }
+
+    @Test
+    void 编辑_本人可编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, 7L, null));
+        Result<?> r = controller.editReport(editParams(100L, null), 10L, 7L);
+        assertEquals(200, r.getCode());
+        assertEquals("已保存", r.getData());
+        verify(healthReportService).updateReportFromPayload(eq(100L), any(), any(), eq(10L));
+    }
+
+    @Test
+    void 编辑_管理员可编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, 7L, null));
+        when(reportMemberPermissionService.isFamilyAdmin(20L, 7L)).thenReturn(true);
+        Result<?> r = controller.editReport(editParams(100L, null), 20L, 7L);
+        assertEquals(200, r.getCode());
+        assertEquals("已保存", r.getData());
+        verify(healthReportService).updateReportFromPayload(eq(100L), any(), any(), eq(20L));
+    }
+
+    @Test
+    void 编辑_被授权成员可编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, 7L, 50L));
+        when(reportMemberPermissionService.canViewMemberReports(30L, 50L, 7L)).thenReturn(true);
+        Result<?> r = controller.editReport(editParams(100L, null), 30L, 7L);
+        assertEquals(200, r.getCode());
+        assertEquals("已保存", r.getData());
+        verify(healthReportService).updateReportFromPayload(eq(100L), any(), any(), eq(30L));
+    }
+
+    @Test
+    void 编辑_非本人非管理员_拒绝编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, 7L, null));
+        when(reportMemberPermissionService.isFamilyAdmin(30L, 7L)).thenReturn(false);
+        Result<?> r = controller.editReport(editParams(100L, null), 30L, 7L);
+        assertEquals("无权编辑该报告", r.getMessage());
+        verify(healthReportService, never()).updateReportFromPayload(any(), any(), any(), any());
+    }
+
+    @Test
+    void 编辑_授权成员但不可见_拒绝编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, 7L, 50L));
+        when(reportMemberPermissionService.canViewMemberReports(30L, 50L, 7L)).thenReturn(false);
+        Result<?> r = controller.editReport(editParams(100L, null), 30L, 7L);
+        assertEquals("无权编辑该报告", r.getMessage());
+        verify(healthReportService, never()).updateReportFromPayload(any(), any(), any(), any());
+    }
+
+    @Test
+    void 编辑_家庭缺失_拒绝编辑() {
+        when(healthReportService.getReportById(100L)).thenReturn(reportWithSubject(100L, 10L, null, null));
+        Result<?> r = controller.editReport(editParams(100L, null), 10L, null);
+        assertEquals("无权编辑该报告", r.getMessage());
+        verify(healthReportService, never()).updateReportFromPayload(any(), any(), any(), any());
+    }
+
+    /* ============ downloadReport:越权下载 ============ */
+
+    private static final String FILE_URL = "https://cdn.example.com/report.pdf";
+
+    private HealthReport downloadReportData(Long reportId, Long ownerUserId, Long familyId, Long subjectId) {
+        HealthReport r = report(reportId, ownerUserId, familyId);
+        r.setSubjectId(subjectId);
+        r.setFileUrl(FILE_URL);
+        return r;
+    }
+
+    private HttpServletRequest mockRequest() {
+        return mock(HttpServletRequest.class);
+    }
+
+    @Test
+    void 下载_未登录_返回用户未登录() {
+        Result<?> r = controller.downloadReport(params(100L), null, null, mockRequest());
+        assertEquals("用户未登录", r.getMessage());
+    }
+
+    @Test
+    void 下载_报告不存在_返回报告不存在() {
+        when(healthReportService.getReportById(99L)).thenReturn(null);
+        Result<?> r = controller.downloadReport(params(99L), 1L, null, mockRequest());
+        assertEquals("报告不存在", r.getMessage());
+    }
+
+    @Test
+    void 下载_本人可下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, 7L, null));
+        Result<Map<String, Object>> r = controller.downloadReport(params(100L), 10L, 7L, mockRequest());
+        assertEquals(200, r.getCode());
+        assertEquals(FILE_URL, r.getData().get("fileUrl"));
+        assertEquals("report.pdf", r.getData().get("fileName"));
+    }
+
+    @Test
+    void 下载_管理员可下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, 7L, null));
+        when(reportMemberPermissionService.isFamilyAdmin(20L, 7L)).thenReturn(true);
+        Result<Map<String, Object>> r = controller.downloadReport(params(100L), 20L, 7L, mockRequest());
+        assertEquals(200, r.getCode());
+        assertEquals(FILE_URL, r.getData().get("fileUrl"));
+    }
+
+    @Test
+    void 下载_被授权成员可下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, 7L, 50L));
+        when(reportMemberPermissionService.canViewMemberReports(30L, 50L, 7L)).thenReturn(true);
+        Result<Map<String, Object>> r = controller.downloadReport(params(100L), 30L, 7L, mockRequest());
+        assertEquals(200, r.getCode());
+        assertEquals(FILE_URL, r.getData().get("fileUrl"));
+    }
+
+    @Test
+    void 下载_非授权_拒绝下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, 7L, null));
+        when(reportMemberPermissionService.isFamilyAdmin(30L, 7L)).thenReturn(false);
+        Result<?> r = controller.downloadReport(params(100L), 30L, 7L, mockRequest());
+        assertEquals("无权下载该报告", r.getMessage());
+    }
+
+    @Test
+    void 下载_授权成员但不可见_拒绝下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, 7L, 50L));
+        when(reportMemberPermissionService.canViewMemberReports(30L, 50L, 7L)).thenReturn(false);
+        Result<?> r = controller.downloadReport(params(100L), 30L, 7L, mockRequest());
+        assertEquals("无权下载该报告", r.getMessage());
+    }
+
+    @Test
+    void 下载_家庭缺失_拒绝下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(downloadReportData(100L, 10L, null, null));
+        Result<?> r = controller.downloadReport(params(100L), 10L, null, mockRequest());
+        assertEquals("无权下载该报告", r.getMessage());
+    }
+
+    @Test
+    void 下载_无文件_返回无文件可下载() {
+        when(healthReportService.getReportById(100L)).thenReturn(report(100L, 10L, 7L));
+        Result<?> r = controller.downloadReport(params(100L), 10L, 7L, mockRequest());
+        assertEquals("该报告无文件可下载", r.getMessage());
+    }
+}

+ 151 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerListPaginationTest.java

@@ -0,0 +1,151 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.service.DanReportUploadService;
+import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.ReportMemberPermissionService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+/**
+ * T29-B3-4:/report/list 分页修复。
+ *
+ * 兼容性约束:page 不传时返回 List(小程序端既有调用依赖);
+ * page 传时返回分页结构 {records, total, current, size, pages}(teacher 代传历史页依赖)。
+ */
+public class HealthReportControllerListPaginationTest {
+
+    @Mock
+    private HealthReportService healthReportService;
+    @Mock
+    private ReportMemberPermissionService reportMemberPermissionService;
+    @Mock
+    private DanReportUploadService danReportUploadService;
+
+    private HealthReportController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new HealthReportController();
+        ReflectionTestUtils.setField(controller, "healthReportService", healthReportService);
+        ReflectionTestUtils.setField(controller, "reportMemberPermissionService", reportMemberPermissionService);
+        ReflectionTestUtils.setField(controller, "danReportUploadService", danReportUploadService);
+    }
+
+    private List<HealthReport> buildReports(int count) {
+        List<HealthReport> list = new ArrayList<>();
+        for (int i = 1; i <= count; i++) {
+            HealthReport r = new HealthReport();
+            r.setId((long) i);
+            r.setReportType("gut_flora");
+            r.setFamilyId(10L);
+            r.setSubjectId((long) i);
+            r.setUserId(1L);
+            r.setCreatedAt(new Date());
+            r.setStatus("active");
+            list.add(r);
+        }
+        return list;
+    }
+
+    private Map<String, Object> params(Object page, Object size) {
+        Map<String, Object> p = new HashMap<>();
+        if (page != null) {
+            p.put("page", page);
+        }
+        if (size != null) {
+            p.put("size", size);
+        }
+        return p;
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testPageProvidedReturnsPaginatedStructure() {
+        when(reportMemberPermissionService.visibleIdentityIds(eq(1L), eq(10L))).thenReturn(null);
+        when(healthReportService.getFamilyReports(10L)).thenReturn(buildReports(25));
+        when(danReportUploadService.listConfirmedForReportList(isNull(), eq(10L), isNull()))
+                .thenReturn(new ArrayList<>());
+        doNothing().when(healthReportService).fillSubjectAndProxyNames(any());
+
+        Result<Object> result = controller.listReports(params(1, 20), 1L, 10L);
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData() instanceof Map, "page 传时返回分页结构");
+        Map<String, Object> pageResult = (Map<String, Object>) result.getData();
+        List<HealthReport> records = (List<HealthReport>) pageResult.get("records");
+        assertEquals(20, records.size());
+        assertEquals(25, pageResult.get("total"));
+        assertEquals(1, pageResult.get("current"));
+        assertEquals(20, pageResult.get("size"));
+        assertEquals(2, pageResult.get("pages"));
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testPageBeyondTotalReturnsEmptyRecords() {
+        when(reportMemberPermissionService.visibleIdentityIds(eq(1L), eq(10L))).thenReturn(null);
+        when(healthReportService.getFamilyReports(10L)).thenReturn(buildReports(25));
+        when(danReportUploadService.listConfirmedForReportList(isNull(), eq(10L), isNull()))
+                .thenReturn(new ArrayList<>());
+
+        Result<Object> result = controller.listReports(params(99, 20), 1L, 10L);
+        Map<String, Object> pageResult = (Map<String, Object>) result.getData();
+        assertEquals(0, ((List<?>) pageResult.get("records")).size());
+        assertEquals(25, pageResult.get("total"));
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testNoPageReturnsListCompatWithMiniProgram() {
+        when(reportMemberPermissionService.visibleIdentityIds(eq(1L), eq(10L))).thenReturn(null);
+        when(healthReportService.getFamilyReports(10L)).thenReturn(buildReports(25));
+        when(danReportUploadService.listConfirmedForReportList(isNull(), eq(10L), isNull()))
+                .thenReturn(new ArrayList<>());
+
+        // 不传 page 只传 size:返回 List(截取前 N 条),行为与现一致
+        Result<Object> result = controller.listReports(params(null, 3), 1L, 10L);
+        assertTrue(result.getData() instanceof List, "page 不传时返回 List");
+        assertEquals(3, ((List<?>) result.getData()).size());
+
+        // 都不传:返回完整 List
+        result = controller.listReports(params(null, null), 1L, 10L);
+        assertTrue(result.getData() instanceof List);
+        assertEquals(25, ((List<?>) result.getData()).size());
+    }
+
+    @Test
+    public void testMarkParseMethodFlags() throws Exception {
+        // B3-3:markParseMethod 正确标注本地兜底标记(私有方法,反射调用)
+        Map<String, Object> data = new HashMap<>();
+        java.lang.reflect.Method method =
+                HealthReportController.class.getDeclaredMethod("markParseMethod", Map.class, boolean.class, String.class);
+        method.setAccessible(true);
+        method.invoke(controller, data, true, "local");
+        assertEquals(Boolean.TRUE, data.get("parseFallback"));
+        assertEquals("local", data.get("parseMethod"));
+
+        Map<String, Object> data2 = new HashMap<>();
+        method.invoke(controller, data2, false, "langgraph");
+        assertEquals(Boolean.FALSE, data2.get("parseFallback"));
+        assertEquals("langgraph", data2.get("parseMethod"));
+    }
+}

+ 82 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerProxyParseBindingTest.java

@@ -0,0 +1,82 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * B2-2:proxyParsePreview familyId 绑定校验(代传)。B2-6 权限编排层 ②。
+ *
+ * canProxyForFamily:平台角色(admin/operator/finance)直接放行;否则 familyId 必位于
+ * 调用者有效家庭集内(getEffectiveFamilyIds:own family / teacher_family_ids /
+ * family_members 反查 / guide_family 绑定)。
+ */
+public class HealthReportControllerProxyParseBindingTest {
+
+    @Mock
+    private UserService userService;
+
+    private HealthReportController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new HealthReportController();
+        ReflectionTestUtils.setField(controller, "userService", userService);
+    }
+
+    @Test
+    public void testAdminAllowedForAnyFamily() {
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.emptySet());
+        assertTrue(controller.canProxyForFamily(1L, "admin", Arrays.asList("admin"), 999L));
+        // 平台角色直通:永远不查 effective set
+        verify(userService, never()).getEffectiveFamilyIds(anyLong());
+    }
+
+    @Test
+    public void testOperatorAllowed() {
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.emptySet());
+        assertTrue(controller.canProxyForFamily(1L, "operator", Arrays.asList("operator"), 999L));
+        verify(userService, never()).getEffectiveFamilyIds(anyLong());
+    }
+
+    @Test
+    public void testTeacherBoundFamilyAllowed() {
+        Long familyId = 5L;
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.singleton(familyId));
+        assertTrue(controller.canProxyForFamily(1L, "teacher", Arrays.asList("teacher"), familyId));
+        verify(userService).getEffectiveFamilyIds(1L);
+    }
+
+    @Test
+    public void testTeacherUnboundFamilyDenied() {
+        Long familyId = 99L;
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.singleton(5L));
+        assertFalse(controller.canProxyForFamily(1L, "teacher", Arrays.asList("teacher"), familyId));
+    }
+
+    @Test
+    public void testTeacherEmptyEffectiveDenied() {
+        // B2-4 B2-2 融合:effective 为空且请求带 familyId → false(拦截器前就拦截,不建草稿)
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.emptySet());
+        assertFalse(controller.canProxyForFamily(1L, "teacher", Arrays.asList("teacher"), 1L));
+    }
+
+    @Test
+    public void testNonProxyRoleDeniedWithoutBinding() {
+        when(userService.getEffectiveFamilyIds(1L)).thenReturn(Collections.singleton(5L));
+        // role 非平台,familyId 在集合内 → allowed(binding 检查只关心集合归属)
+        assertTrue(controller.canProxyForFamily(1L, "parent", Arrays.asList("parent"), 5L));
+    }
+}

+ 454 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerUploadTest.java

@@ -0,0 +1,454 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.dto.ParsedDiseaseRisk;
+import com.etotem.cfc.dto.ParsedFoodSuitability;
+import com.etotem.cfc.dto.ParsedGutFlora;
+import com.etotem.cfc.dto.ParsedIndicator;
+import com.etotem.cfc.dto.ParsedReportResult;
+import com.etotem.cfc.entity.Food;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.HealthReportDraft;
+import com.etotem.cfc.service.DimensionScoreService;
+import com.etotem.cfc.service.FoodRecommendService;
+import com.etotem.cfc.service.FoodService;
+import com.etotem.cfc.service.HealthReportDraftService;
+import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.OnboardingService;
+import com.etotem.cfc.service.PdfParseService;
+import com.etotem.cfc.service.StorageService;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-18 / 能力键 health.report.upload,原始阶段 RED → 补齐契约级单测):
+ * HealthReportController POST /api/health/report/upload(兼容接口:上传 + 解析 + 自动确认)契约级单测。
+ *
+ * 契约(对应 docs/tdd/test/blockers.md B-3「R6 · 报告上传」,实现位于 HealthReportController:818):
+ * - 请求:multipart/form-data,字段名 file;userId 由 JwtInterceptor 注入 @RequestAttribute("userId");
+ *   familyId 可选(@RequestAttribute required=false)。
+ * - 正常路径:合法 PDF → PdfParseService 解析 → 存储 → 建草稿 → 建报告(含指标/菌群/疾病风险/食材)
+ *   → payload 快照 → 标记草稿已确认 → 新手任务 REPORT_UPLOAD → 返回 Result&lt;Map&gt; code=200,
+ *   含 needBind / matchedMemberId / extractedName 等字段。
+ * - 边界:空文件拒绝;非 PDF 扩展名且非 application/pdf MIME 拒绝;两者任一命中即放行(当前实现为 OR 语义,
+ *   非 AND 三重校验);解析结果无总分/无菌群分视为不可解析;解析抛 IOException 返回解析失败。
+ * - 角色/权限:本 handler 不读取 @RequestAttribute("role"),家长/规划师(teacher)/管理员(admin) 走同一路径,
+ *   授权由 JwtInterceptor(有效 token 注入 userId)+ Service 层数据归属承担;本层不做角色分流。
+ *
+ * 缺陷观察(B-3,不修实现,交编排侧转 GREEN 决策):
+ * 1) 【MIME/扩展名 OR 语义】只校验「扩展名 .pdf」或「contentType=application/pdf」任一成立即放行:
+ *    - report.jpg + application/pdf 通过校验(扩展名不合法仍进解析链);
+ *    - report.pdf + image/jpeg 通过校验(MIME 不合法仍进解析链)。
+ *    契约要求 MIME / 扩展名 / 内容三重校验,应为 AND 语义。
+ * 2) 【无内容(魔数)校验】文件名为 .pdf 且 MIME 为 application/pdf、但内容并非 PDF 时,handler 不校验
+ *    %PDF 魔数,直接交给 PdfParseService;本测试钉住当前观测行为(调用 parse 后才失败)。
+ * 3) 【错误码非 4xx】非法文件走 Result.error(String) → envelope code=500(非 400/415),
+ *    HTTP 状态恒 200(项目统一 Result 包装)。B-3 要求「返回 4xx」,当前未满足。
+ *
+ * 测试隔离:MockMvc standalone + mock 全部下游 Service(PdfParseService/StorageService/HealthReportService/
+ * HealthReportDraftService/FoodService/DimensionScoreService/FoodRecommendService/OnboardingService),
+ * 无 Spring 上下文、无 DB、无外部服务(微信/LangGraph 等)。
+ */
+public class HealthReportControllerUploadTest {
+
+    private static final String URL = "/api/health/report/upload";
+
+    private static final byte[] PDF_BYTES = "%PDF-1.4\n%mock pdf body\n".getBytes();
+
+    @Mock
+    private PdfParseService pdfParseService;
+    @Mock
+    private StorageService storageService;
+    @Mock
+    private HealthReportDraftService healthReportDraftService;
+    @Mock
+    private HealthReportService healthReportService;
+    @Mock
+    private FoodService foodService;
+    @Mock
+    private DimensionScoreService dimensionScoreService;
+    @Mock
+    private FoodRecommendService foodRecommendService;
+    @Mock
+    private OnboardingService onboardingService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        HealthReportController controller = new HealthReportController();
+        ReflectionTestUtils.setField(controller, "pdfParseService", pdfParseService);
+        ReflectionTestUtils.setField(controller, "storageService", storageService);
+        ReflectionTestUtils.setField(controller, "healthReportDraftService", healthReportDraftService);
+        ReflectionTestUtils.setField(controller, "healthReportService", healthReportService);
+        ReflectionTestUtils.setField(controller, "foodService", foodService);
+        ReflectionTestUtils.setField(controller, "dimensionScoreService", dimensionScoreService);
+        ReflectionTestUtils.setField(controller, "foodRecommendService", foodRecommendService);
+        ReflectionTestUtils.setField(controller, "onboardingService", onboardingService);
+        ReflectionTestUtils.setField(controller, "objectMapper", new ObjectMapper());
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ==================== 夹具 ====================
+
+    private static MockMultipartFile pdf(String filename, String contentType, byte[] content) {
+        return new MockMultipartFile("file", filename, contentType, content);
+    }
+
+    private static ParsedReportResult parsedResult(String personName) {
+        ParsedReportResult parsed = new ParsedReportResult();
+        parsed.setOverallScore(82);
+        parsed.setGutHealthScore(76);
+        parsed.setChronicDiseaseScore(88);
+        parsed.setReportNumber("MJ20261001001");
+        parsed.setReportDate("2026-10-01");
+        parsed.setPersonName(personName);
+        parsed.setGender("female");
+        parsed.setAge(36);
+        parsed.setGutAge("32");
+        parsed.setGutType("B型");
+
+        ParsedIndicator indicator = new ParsedIndicator();
+        indicator.setCategory("炎症");
+        indicator.setIndicatorName("C反应蛋白");
+        indicator.setIndicatorValue("1.2");
+        indicator.setRefRange("0-3");
+        indicator.setStatus("正常");
+        parsed.setIndicators(new ArrayList<>(Collections.singletonList(indicator)));
+
+        ParsedGutFlora flora = new ParsedGutFlora();
+        flora.setBacteriaName("双歧杆菌");
+        flora.setBacteriaValue("3.5%");
+        flora.setNormalRange("1%-10%");
+        flora.setCategory("核心菌属");
+        flora.setLevel("属");
+        parsed.setGutFlora(new ArrayList<>(Collections.singletonList(flora)));
+
+        ParsedDiseaseRisk risk = new ParsedDiseaseRisk();
+        risk.setDiseaseName("肠道炎症风险");
+        risk.setRiskValue("0.21");
+        risk.setRiskLevel("低");
+        parsed.setDiseaseRisks(new ArrayList<>(Collections.singletonList(risk)));
+
+        ParsedFoodSuitability food = new ParsedFoodSuitability();
+        food.setFoodName("燕麦");
+        food.setCategory("谷物");
+        food.setScore(88);
+        parsed.setFoodSuitability(new ArrayList<>(Collections.singletonList(food)));
+        return parsed;
+    }
+
+    /** 打桩「存储 → 草稿 → 报告 → 快照 → 确认」全链路,返回 reportId=88 / draftId=55。 */
+    private void stubPersistChain() {
+        when(storageService.storeFile(any(), eq("health-reports"))).thenReturn("/uploads/health-reports/report.pdf");
+
+        HealthReportDraft draft = new HealthReportDraft();
+        draft.setId(55L);
+        when(healthReportDraftService.createDraft(any(), any(), anyString(), anyString(), anyString(), anyString()))
+                .thenReturn(draft);
+
+        HealthReport created = new HealthReport();
+        created.setId(88L);
+        when(healthReportService.createReport(any(HealthReport.class), anyList(), anyList(), anyList()))
+                .thenReturn(created);
+
+        // getReportDetail 返回的 Map 会被 handler 就地 put,需每次返回可写实例
+        doAnswer(invocation -> new HashMap<String, Object>()).when(healthReportService).getReportDetail(anyLong());
+    }
+
+    // ==================== 正常路径 ====================
+
+    @Test
+    public void upload_validPdf_returnsReportDetail_andRunsFullPersistenceChain() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+        // 家庭成员中无同名成员(Mockito 对 Long 包装类型的默认空值为 0,需显式打桩为 null)
+        when(healthReportService.matchFamilyMemberByName("李小雨", 1L)).thenReturn(null);
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L)
+                        .requestAttr("familyId", 1L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.needBind").value(true))
+                .andExpect(jsonPath("$.data.extractedName").value("李小雨"))
+                .andExpect(jsonPath("$.data.extractedReportNumber").value("MJ20261001001"));
+
+        // 上传人 userId / familyId 原样透传到草稿(数据归属口径)
+        verify(healthReportDraftService).createDraft(
+                eq(9L), eq(1L), eq("gut_flora"),
+                eq("/uploads/health-reports/report.pdf"),
+                eq("肠道菌群报告.pdf"), anyString());
+        verify(healthReportService).createReport(any(HealthReport.class), anyList(), anyList(), anyList());
+        verify(healthReportService).savePayloadSnapshot(eq(88L), eq(9L), eq("create"), isNull(), anyString());
+        verify(healthReportDraftService).markConfirmed(55L, 88L);
+        verify(onboardingService).completeTask(9L, "REPORT_UPLOAD");
+
+        // 解析出的 1 条食材 → 落食材推荐
+        @SuppressWarnings("unchecked")
+        ArgumentCaptor<List<Food>> foods = ArgumentCaptor.forClass(List.class);
+        verify(foodService).saveFoodsForReport(eq(88L), foods.capture());
+        assertEquals(1, foods.getValue().size());
+        assertEquals("燕麦", foods.getValue().get(0).getName());
+        assertEquals("recommended", foods.getValue().get(0).getStatus());
+
+        // 有 familyId 且解析出姓名 → 尝试匹配家庭成员;未匹配到(null)不触发评分/食材推荐刷新
+        verify(healthReportService).matchFamilyMemberByName("李小雨", 1L);
+        verify(dimensionScoreService, never()).refreshFromGutReport(anyLong(), anyLong());
+        verify(foodRecommendService, never()).recalculateForUser(anyLong());
+    }
+
+    @Test
+    public void upload_familyIdAndMatchingName_autoBindsMemberAndRefreshesScores() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+        when(healthReportService.matchFamilyMemberByName("李小雨", 1L)).thenReturn(77L);
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L)
+                        .requestAttr("familyId", 1L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.needBind").value(false))
+                .andExpect(jsonPath("$.data.matchedMemberId").value(77))
+                .andExpect(jsonPath("$.data.matchedMemberName").value("李小雨"));
+
+        verify(dimensionScoreService).refreshFromGutReport(77L, 88L);
+        verify(foodRecommendService).recalculateForUser(77L);
+    }
+
+    @Test
+    public void upload_withoutFamilyId_skipsMemberMatch() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.needBind").value(true));
+
+        verify(healthReportService, never()).matchFamilyMemberByName(anyString(), anyLong());
+        verify(healthReportDraftService).createDraft(
+                eq(9L), isNull(), eq("gut_flora"), anyString(), anyString(), anyString());
+    }
+
+    // ==================== 关键边界:空文件 / 非 PDF ====================
+
+    @Test
+    public void upload_emptyFile_rejectedBeforeParse() throws Exception {
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("empty.pdf", "application/pdf", new byte[0]))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("文件不能为空"));
+
+        verify(pdfParseService, never()).parse(any(InputStream.class));
+        verify(storageService, never()).storeFile(any(), anyString());
+    }
+
+    @Test
+    public void upload_nonPdfExtensionAndNonPdfMime_rejected() throws Exception {
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("报告.jpg", "image/jpeg", "not a pdf".getBytes()))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("仅支持PDF文件"));
+
+        verify(pdfParseService, never()).parse(any(InputStream.class));
+        verify(storageService, never()).storeFile(any(), anyString());
+    }
+
+    @Test
+    public void upload_wrongMimeOnly_rejected() throws Exception {
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("报告.txt", "text/plain", "hello".getBytes()))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("仅支持PDF文件"));
+
+        verify(pdfParseService, never()).parse(any(InputStream.class));
+    }
+
+    @Test
+    public void upload_uppercasePdfExtension_acceptedBoundary() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("REPORT.PDF", "application/octet-stream", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(pdfParseService).parse(any(InputStream.class));
+    }
+
+    // ==================== B-3 缺陷:MIME / 扩展名 / 内容校验缺口(钉住观测行为) ====================
+
+    @Test
+    public void upload_nonPdfExtensionWithPdfMime_pinsObservedOrSemanticsBypass() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        // 扩展名 .jpg 不合法,但 MIME=application/pdf 即被放行 → OR 语义(缺陷观察 1)
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("报告.jpg", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(pdfParseService).parse(any(InputStream.class));
+    }
+
+    @Test
+    public void upload_pdfExtensionWithNonPdfMime_pinsObservedOrSemanticsBypass() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        // MIME=image/jpeg 不合法,但扩展名 .pdf 即被放行 → OR 语义(缺陷观察 1)
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("报告.pdf", "image/jpeg", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(pdfParseService).parse(any(InputStream.class));
+    }
+
+    @Test
+    public void upload_fakePdfContent_noMagicByteCheck_pinsObservedParsePath() throws Exception {
+        // 伪 PDF:名称 .pdf + MIME application/pdf,但内容不含 %PDF 魔数 → handler 不校验内容(缺陷观察 2)
+        ParsedReportResult unparseable = new ParsedReportResult(); // 无总分/无菌群分
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(unparseable);
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("伪造报告.pdf", "application/pdf", "definitely not a pdf".getBytes()))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("无法解析PDF文件,请确认是募极生物肠道菌群报告"));
+
+        // 内容校验缺口:文件已进入解析链,且未落盘(解析先行)
+        verify(pdfParseService).parse(any(InputStream.class));
+        verify(storageService, never()).storeFile(any(), anyString());
+    }
+
+    @Test
+    public void upload_parseReturnsNoScores_rejectedBeforeStore() throws Exception {
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(new ParsedReportResult());
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("无法解析PDF文件,请确认是募极生物肠道菌群报告"));
+
+        verify(storageService, never()).storeFile(any(), anyString());
+        verify(healthReportService, never()).createReport(any(HealthReport.class), anyList(), anyList(), anyList());
+    }
+
+    @Test
+    public void upload_parseThrowsIoException_returnsParseFailure() throws Exception {
+        when(pdfParseService.parse(any(InputStream.class))).thenThrow(new IOException("bad xref"));
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("PDF解析失败: bad xref"));
+
+        verify(storageService, never()).storeFile(any(), anyString());
+        verify(healthReportDraftService, never())
+                .createDraft(any(), any(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    // ==================== 角色/权限(本层无角色分流) ====================
+
+    @Test
+    public void upload_teacherRole_notGatedByRoleAttribute() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        // 规划师(teacher)与家长走同一 handler,本层不读 role;授权由 JwtInterceptor + Service 承担
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L)
+                        .requestAttr("role", "teacher"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+    }
+
+    @Test
+    public void upload_adminRole_notGatedByRoleAttribute() throws Exception {
+        stubPersistChain();
+        when(pdfParseService.parse(any(InputStream.class))).thenReturn(parsedResult("李小雨"));
+
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("肠道菌群报告.pdf", "application/pdf", PDF_BYTES))
+                        .requestAttr("userId", 9L)
+                        .requestAttr("role", "admin"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+    }
+
+    // ==================== 路由契约(统一 @PostMapping) ====================
+
+    @Test
+    public void upload_getMethod_notAllowed() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    // ==================== 缺陷复现断言(供编排侧 GREEN 决策复核) ====================
+
+    @Test
+    public void upload_defectEnvelopeCodeIs500_not4xx() throws Exception {
+        // 缺陷观察 3:非法文件返回 envelope code=500,B-3 要求 4xx(400/415);
+        // 若实现按 B-3 改为 400/415,本断言会失败,提示同步更新契约。
+        mockMvc.perform(multipart(URL)
+                        .file(pdf("报告.jpg", "image/jpeg", "not a pdf".getBytes()))
+                        .requestAttr("userId", 9L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500));
+    }
+}

+ 282 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/HealthSleepControllerContractTest.java

@@ -0,0 +1,282 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthSleepRecord;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.HealthSleepRecordMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.ProfileComputeService;
+import com.etotem.cfc.service.TaskService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * S-cfc-31 · sleep.config.tags —— {@link HealthSleepController} 契约级单测(RED 阶段补齐)。
+ *
+ * <p>设计溯源:{@code HealthSleepController}(/api/health/sleep/list|create,已合入 origin/cfclub)
+ * + {@code sys_config} 机制 + {@code AdminGuideConfigController} get/save 模式
+ * (需求变更 C:睡眠情况选项由后台配置驱动)。契约以「已合入 origin/cfclub 的接口契约」为准。
+ *
+ * <p>覆盖:正常路径 + 关键边界 + 任务回写钩子(每日进度型 / 一次性 / 无 taskId / 成员归属修正)
+ * + 画像重算触发。纯单元测试:直接调用 Controller + Mockito mock mapper/service,
+ * 不依赖数据库/微信/外部服务。
+ */
+public class HealthSleepControllerContractTest {
+
+    private HealthSleepController controller;
+    private HealthSleepRecordMapper healthSleepRecordMapper;
+    private TaskService taskService;
+    private TaskMapper taskMapper;
+    private FamilyMemberMapper familyMemberMapper;
+    private ProfileComputeService profileComputeService;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new HealthSleepController();
+        healthSleepRecordMapper = mock(HealthSleepRecordMapper.class);
+        taskService = mock(TaskService.class);
+        taskMapper = mock(TaskMapper.class);
+        familyMemberMapper = mock(FamilyMemberMapper.class);
+        profileComputeService = mock(ProfileComputeService.class);
+        ReflectionTestUtils.setField(controller, "healthSleepRecordMapper", healthSleepRecordMapper);
+        ReflectionTestUtils.setField(controller, "taskService", taskService);
+        ReflectionTestUtils.setField(controller, "taskMapper", taskMapper);
+        ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(controller, "profileComputeService", profileComputeService);
+    }
+
+    // ====================================================================
+    // POST /api/health/sleep/list —— 正常路径 + 关键边界
+    // ====================================================================
+
+    @Test
+    public void list_byParamsMemberId_returnsRecords() {
+        HealthSleepRecord r = new HealthSleepRecord();
+        r.setId(1L);
+        r.setMemberId(10L);
+        r.setRemark("入睡困难,正常");
+        when(healthSleepRecordMapper.selectList(any())).thenReturn(Collections.singletonList(r));
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", "10");
+
+        Result<List<HealthSleepRecord>> res = controller.list(params, null);
+
+        assertEquals(200, res.getCode());
+        assertEquals(1, res.getData().size());
+        assertEquals(10L, res.getData().get(0).getMemberId());
+        assertEquals("入睡困难,正常", res.getData().get(0).getRemark(), "存储的 remark(含所选睡眠标签)应原样随记录返回");
+        verify(healthSleepRecordMapper).selectList(any());
+    }
+
+    @Test
+    public void list_memberIdFallsBackToCurrentMemberAttribute() {
+        when(healthSleepRecordMapper.selectList(any())).thenReturn(Collections.emptyList());
+
+        Result<List<HealthSleepRecord>> res = controller.list(new HashMap<>(), 10L);
+
+        assertEquals(200, res.getCode());
+        assertNotNull(res.getData());
+        verify(healthSleepRecordMapper).selectList(any());
+    }
+
+    @Test
+    public void list_noMemberIdAnywhere_returnsError() {
+        Result<List<HealthSleepRecord>> res = controller.list(new HashMap<>(), null);
+
+        assertEquals(500, res.getCode(), "无 memberId 应返回错误而非成功");
+        assertTrue(res.getMessage().contains("memberId"), "message 应指明缺失的 memberId");
+        verify(healthSleepRecordMapper, never()).selectList(any());
+    }
+
+    // ====================================================================
+    // POST /api/health/sleep/create —— 正常路径
+    // ====================================================================
+
+    @Test
+    public void create_validRecord_noTaskId_persistsAndAccumulatesDailyProgress() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        rec.setRemark("入睡困难,正常");
+        FamilyMember fm = new FamilyMember();
+        fm.setId(10L);
+        fm.setUserId(100L);
+        when(familyMemberMapper.selectById(10L)).thenReturn(fm);
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(200, res.getCode());
+        assertEquals(10L, res.getData().getMemberId());
+        assertNotNull(rec.getCreatedAt(), "create 必须写入 createdAt");
+        ArgumentCaptor<HealthSleepRecord> captor = ArgumentCaptor.forClass(HealthSleepRecord.class);
+        verify(healthSleepRecordMapper).insert(captor.capture());
+        assertEquals("入睡困难,正常", captor.getValue().getRemark(), "记录 remark(含所选睡眠标签)必须原样落库");
+        // 无 taskId → 累计今日每日睡眠打卡任务进度
+        verify(taskService).updateProgress(100L, 10L, "SLEEP", 1);
+        // 触发画像重算(fire-and-forget 线程)
+        verify(profileComputeService, timeout(2000)).computeAndSave(10L);
+    }
+
+    @Test
+    public void create_memberIdFromAttribute_whenBodyOmitsIt() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        FamilyMember fm = new FamilyMember();
+        fm.setId(7L);
+        fm.setUserId(70L);
+        when(familyMemberMapper.selectById(7L)).thenReturn(fm);
+
+        Result<HealthSleepRecord> res = controller.create(rec, 7L);
+
+        assertEquals(200, res.getCode());
+        assertEquals(7L, rec.getMemberId(), "body 缺 memberId 时应取 currentMemberId 属性");
+        verify(taskService).updateProgress(70L, 7L, "SLEEP", 1);
+    }
+
+    @Test
+    public void create_taskId_oneTimeTask_completesTask() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        rec.setTaskId(5L);
+        Task linkedTask = new Task();
+        linkedTask.setId(5L);
+        linkedTask.setFamilyMemberId(10L);
+        linkedTask.setIsDailyProgress(0); // 一次性任务
+        when(taskMapper.selectById(5L)).thenReturn(linkedTask);
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(200, res.getCode());
+        verify(taskService).completeTask(5L, 10L, "", "睡眠打卡", "text");
+        verify(taskService, never()).updateCheckinTaskProgress(anyLong(), anyLong(), anyLong(), anyInt());
+    }
+
+    @Test
+    public void create_taskId_dailyProgressTask_accumulatesTaskProgress() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        rec.setTaskId(5L);
+        Task linkedTask = new Task();
+        linkedTask.setId(5L);
+        linkedTask.setFamilyMemberId(10L);
+        linkedTask.setIsDailyProgress(1); // 每日进度型
+        FamilyMember fm = new FamilyMember();
+        fm.setId(10L);
+        fm.setUserId(100L);
+        when(taskMapper.selectById(5L)).thenReturn(linkedTask);
+        when(familyMemberMapper.selectById(10L)).thenReturn(fm);
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(200, res.getCode());
+        verify(taskService).updateCheckinTaskProgress(5L, 100L, 10L, 1);
+        verify(taskService, never()).completeTask(anyLong(), anyLong(), any(), any(), any());
+    }
+
+    @Test
+    public void create_memberMismatchWithLinkedTask_correctsMemberOwnership() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(99L); // 与任务归属不符(家庭主账号切成员视角场景)
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        rec.setTaskId(5L);
+        Task linkedTask = new Task();
+        linkedTask.setId(5L);
+        linkedTask.setFamilyMemberId(10L);
+        linkedTask.setIsDailyProgress(0);
+        when(taskMapper.selectById(5L)).thenReturn(linkedTask);
+
+        Result<HealthSleepRecord> res = controller.create(rec, 99L);
+
+        assertEquals(200, res.getCode());
+        assertEquals(10L, rec.getMemberId(), "以任务归属为准修正记录成员,避免打卡记录与任务串号");
+        verify(taskService).completeTask(5L, 10L, "", "睡眠打卡", "text");
+    }
+
+    @Test
+    public void create_taskWritebackFailure_doesNotBreakMainFlow() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+        rec.setTaskId(5L); // 必须携带 taskId,才能进入任务回写分支以验证其故障隔离
+        when(taskMapper.selectById(5L)).thenThrow(new RuntimeException("taskMapper 故障"));
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(200, res.getCode(), "任务回写失败不应影响打卡主流程");
+        verify(healthSleepRecordMapper).insert(rec);
+    }
+
+    // ====================================================================
+    // POST /api/health/sleep/create —— 关键边界(校验)
+    // ====================================================================
+
+    @Test
+    public void create_noMemberIdAndNoAttribute_returnsError() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setSleepTime(new Date());
+        rec.setWakeTime(new Date());
+
+        Result<HealthSleepRecord> res = controller.create(rec, null);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("memberId"));
+        verify(healthSleepRecordMapper, never()).insert(any());
+    }
+
+    @Test
+    public void create_missingSleepTime_returnsError() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setWakeTime(new Date());
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("入睡时间"));
+        verify(healthSleepRecordMapper, never()).insert(any());
+    }
+
+    @Test
+    public void create_missingWakeTime_returnsError() {
+        HealthSleepRecord rec = new HealthSleepRecord();
+        rec.setMemberId(10L);
+        rec.setSleepTime(new Date());
+
+        Result<HealthSleepRecord> res = controller.create(rec, 10L);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("醒来时间"));
+        verify(healthSleepRecordMapper, never()).insert(any());
+    }
+}

+ 108 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/IndicatorControllerTest.java

@@ -0,0 +1,108 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.service.IndicatorChangeService;
+import com.etotem.cfc.service.IndicatorCorrelationService;
+import com.etotem.cfc.service.IndicatorTimelineService;
+import com.etotem.cfc.service.IndicatorTrendService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 仅做 API 边界契约单测(无 Spring 上下文):
+ * <ul>
+ *   <li>验收 #3:scope=pair 缺 fromReportDate/toReportDate → 400 明确错误码,不触及 service</li>
+ *   <li>验收 #8:健康报告指标对照接口返回 Result(权限校验由控制器负责,此处只验证参数校验短路)</li>
+ * </ul>
+ */
+@ExtendWith(MockitoExtension.class)
+class IndicatorControllerTest {
+
+    @Mock
+    private IndicatorTrendService indicatorTrendService;
+
+    @Mock
+    private IndicatorTimelineService indicatorTimelineService;
+
+    @Mock
+    private IndicatorCorrelationService indicatorCorrelationService;
+
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+
+    @InjectMocks
+    private IndicatorController controller;
+
+    private static Map<String, Object> bodyWith(Long subjectId, Object... kv) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("subjectId", subjectId);
+        if (kv != null) {
+            for (int i = 0; i + 1 < kv.length; i += 2) {
+                m.put(String.valueOf(kv[i]), kv[i + 1]);
+            }
+        }
+        return m;
+    }
+
+    @Test
+    void changeRanking_scopePairMissingDates_returns400AndDoesNotCallService() {
+        FamilyMember member = new FamilyMember();
+        member.setId(88L);
+        member.setFamilyId(7L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        Map<String, Object> params = bodyWith(88L, "scope", "pair"); // 缺 fromReportDate/toReportDate
+
+        Result<?> result = controller.changeRanking(params, 7L);
+
+        assertEquals(Integer.valueOf(400), result.getCode());
+        assertTrue(result.getMessage().contains("scope=pair"));
+        assertTrue(result.getMessage().contains("fromReportDate"));
+        assertTrue(result.getMessage().contains("toReportDate"));
+        verify(indicatorTrendService, never()).changeRanking(any(), any(), any(),
+                anyString(), anyString(), any(), any(), any(), any(), any(), any(), any());
+    }
+
+    @Test
+    void changeRanking_scopePairAllParams_ok() {
+        FamilyMember member = new FamilyMember();
+        member.setId(88L);
+        member.setFamilyId(7L);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member);
+
+        Map<String, Object> params = bodyWith(88L,
+                "scope", "pair",
+                "fromReportDate", "2026-01-01",
+                "toReportDate", "2026-10-01",
+                "orderBy", "magnitude",
+                "filter", "all",
+                "page", 1,
+                "pageSize", 50);
+        when(indicatorTrendService.changeRanking(any(), any(), any(), eq("pair"), anyString(), any(),
+                any(), anyString(), anyString(), anyString(), any(), any()))
+                .thenReturn(new HashMap<>());
+
+        Result<?> result = controller.changeRanking(params, 7L);
+
+        assertEquals(Integer.valueOf(200), result.getCode());
+        verify(indicatorTrendService).changeRanking(eq(88L), any(), any(), eq("pair"),
+                eq("magnitude"), eq(50), eq(7L), eq("2026-01-01"), eq("2026-10-01"), eq("all"), eq(1), eq(50));
+    }
+}

+ 171 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/IndicatorFavoriteControllerTest.java

@@ -0,0 +1,171 @@
+package com.etotem.cfc.controller;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.service.IndicatorFavoriteService;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 指标收藏控制器单测(T03 · §6),覆盖验收要点:
+ * <ul>
+ *   <li>toggle/list/remove:正常路径透传 Service 结果</li>
+ *   <li>参数缺失(memberId/definitionId/sourceType)→ 400</li>
+ *   <li>memberId 不属当前家庭 → 400(越权拦截)</li>
+ * </ul>
+ */
+class IndicatorFavoriteControllerTest {
+
+    private IndicatorFavoriteController controller;
+    private IndicatorFavoriteService indicatorFavoriteService;
+    private FamilyMemberMapper familyMemberMapper;
+
+    @BeforeAll
+    static void initMybatisPlusTableInfo() {
+        // 初始化 MP TableInfo 缓存,使 LambdaQueryWrapper 在无 Spring 上下文可用
+        TableInfoHelper.initTableInfo(
+                new MapperBuilderAssistant(new MybatisConfiguration(), ""), FamilyMember.class);
+    }
+
+    @BeforeEach
+    void setUp() {
+        controller = new IndicatorFavoriteController();
+        indicatorFavoriteService = mock(IndicatorFavoriteService.class);
+        familyMemberMapper = mock(FamilyMemberMapper.class);
+        ReflectionTestUtils.setField(controller, "indicatorFavoriteService", indicatorFavoriteService);
+        ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+    }
+
+    private FamilyMember member(Long id, Long familyId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(id);
+        m.setFamilyId(familyId);
+        return m;
+    }
+
+    private Map<String, Object> params(String memberId, String sourceType, String definitionId) {
+        Map<String, Object> p = new HashMap<>();
+        if (memberId != null) p.put("memberId", memberId);
+        if (sourceType != null) p.put("sourceType", sourceType);
+        if (definitionId != null) p.put("definitionId", definitionId);
+        return p;
+    }
+
+    // ==================== toggle ====================
+
+    @Test
+    void toggle_正常() {
+        when(familyMemberMapper.selectOne(any())).thenReturn(member(42L, 9L));
+        Map<String, Object> data = new HashMap<>();
+        data.put("definitionId", 456L);
+        data.put("added", true);
+        when(indicatorFavoriteService.toggle(7L, 9L, 42L, "gut_flora", 456L)).thenReturn(data);
+
+        Result<?> r = controller.toggle(params("42", "gut_flora", "456"), 7L, 9L);
+
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+        assertEquals(456L, ((Map<?, ?>) r.getData()).get("definitionId"));
+    }
+
+    @Test
+    void toggle_缺memberId_400() {
+        Result<?> r = controller.toggle(params(null, "gut_flora", "456"), 7L, 9L);
+        assertEquals(400, r.getCode());
+        verify(indicatorFavoriteService, never()).toggle(any(), any(), any(), any(), any());
+    }
+
+    @Test
+    void toggle_缺sourceType_400() {
+        Result<?> r = controller.toggle(params("42", "", "456"), 7L, 9L);
+        assertEquals(400, r.getCode());
+        verify(indicatorFavoriteService, never()).toggle(any(), any(), any(), any(), any());
+    }
+
+    @Test
+    void toggle_缺definitionId_400() {
+        Result<?> r = controller.toggle(params("42", "gut_flora", null), 7L, 9L);
+        assertEquals(400, r.getCode());
+        verify(indicatorFavoriteService, never()).toggle(any(), any(), any(), any(), any());
+    }
+
+    @Test
+    void toggle_成员不属家庭_400() {
+        when(familyMemberMapper.selectOne(any())).thenReturn(null);
+
+        Result<?> r = controller.toggle(params("42", "gut_flora", "456"), 7L, 9L);
+
+        assertEquals(400, r.getCode());
+        verify(indicatorFavoriteService, never()).toggle(any(), any(), any(), any(), any());
+    }
+
+    // ==================== list ====================
+
+    @Test
+    void list_正常() {
+        when(familyMemberMapper.selectOne(any())).thenReturn(member(42L, 9L));
+        Map<String, Object> data = new HashMap<>();
+        data.put("memberId", 42L);
+        data.put("sourceType", "gut_flora");
+        data.put("definitionIds", new long[]{456L, 789L});
+        when(indicatorFavoriteService.list(7L, 9L, 42L, "gut_flora")).thenReturn(data);
+
+        Result<?> r = controller.list(params("42", "gut_flora", null), 7L, 9L);
+
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+    }
+
+    @Test
+    void list_缺sourceType_400() {
+        Result<?> r = controller.list(params("42", null, null), 7L, 9L);
+        assertEquals(400, r.getCode());
+    }
+
+    @Test
+    void list_成员不属家庭_400() {
+        when(familyMemberMapper.selectOne(any())).thenReturn(null);
+        Result<?> r = controller.list(params("42", "gut_flora", null), 7L, 9L);
+        assertEquals(400, r.getCode());
+    }
+
+    // ==================== remove ====================
+
+    @Test
+    void remove_正常() {
+        when(familyMemberMapper.selectOne(any())).thenReturn(member(42L, 9L));
+        Map<String, Object> data = new HashMap<>();
+        data.put("definitionId", 456L);
+        data.put("removed", true);
+        when(indicatorFavoriteService.remove(7L, 9L, 42L, "gut_flora", 456L)).thenReturn(data);
+
+        Result<?> r = controller.remove(params("42", "gut_flora", "456"), 7L, 9L);
+
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+        assertEquals(true, ((Map<?, ?>) r.getData()).get("removed"));
+    }
+
+    @Test
+    void remove_缺参_400() {
+        Result<?> r = controller.remove(params("42", "gut_flora", null), 7L, 9L);
+        assertEquals(400, r.getCode());
+    }
+}

+ 85 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/MembershipControllerPlansLevelOrderTest.java

@@ -0,0 +1,85 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.dto.MembershipLevelDTO;
+import com.etotem.cfc.service.MembershipService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约级单测:POST /api/membership/plans 必须返回 levelOrder。
+ *
+ * <p>背景(2026-11-05 付费页显示 ¥0.00):升级页 upgrade.vue 自 dbd94c59b
+ * 起按接口返回的 {@code levelOrder} 比较等级高低({@code getLevelOrder})。
+ * 但 {@code getPricingPlans()} 手工组装 Map 时遗漏了 levelOrder,导致所有档位
+ * levelOrder 均为 undefined/0:免费用户 applyDefaultLevel 无法找到更高档位,
+ * selectedLevel 回落为 FREE,下一步进入 pay 页时按 FREE 取价 = 0 分,
+ * 付费页显示 ¥0.00,下单被后端以「该会员方案暂未开放购买」拒绝。</p>
+ *
+ * <p>测试隔离:MockMvc standalone + mock MembershipService,无 Spring 上下文 / 无 DB。</p>
+ */
+class MembershipControllerPlansLevelOrderTest {
+
+    private static final String URL = "/api/membership/plans";
+
+    @Mock
+    private MembershipService membershipService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        MembershipController controller = new MembershipController();
+        ReflectionTestUtils.setField(controller, "membershipService", membershipService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private MembershipLevelDTO level(String code, int levelOrder, int monthly, int yearly) {
+        MembershipLevelDTO dto = new MembershipLevelDTO();
+        dto.setLevelCode(code);
+        dto.setLevelName(code + "-name");
+        dto.setLevelOrder(levelOrder);
+        dto.setPriceMonthly(monthly);
+        dto.setPriceQuarterly(0);
+        dto.setPriceYearly(yearly);
+        return dto;
+    }
+
+    @Test
+    void plans_返回每个可购档位的levelOrder() throws Exception {
+        List<MembershipLevelDTO> levels = Arrays.asList(
+                level("FREE", 1, 0, 0),
+                level("FAMILY", 3, 19800, 198000),
+                level("PREMIUM", 4, 131400, 1316800),
+                level("BASIC", 2, 990, 0),
+                level("LIFETIME", 5, 0, 0),
+                level("PROVIDER", 1, 13140, 131400)
+        );
+        when(membershipService.getAllLevels()).thenReturn(levels);
+
+        mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                // LIFETIME / PROVIDER 不可购,仍应被过滤
+                .andExpect(jsonPath("$.data.length()").value(4))
+                // 免费用户升级页依赖该字段判断下一档;缺失会导致选档回落 FREE、付费页显示 0
+                .andExpect(jsonPath("$.data[0].levelOrder").value(1))   // FREE
+                .andExpect(jsonPath("$.data[1].levelOrder").value(3))   // FAMILY
+                .andExpect(jsonPath("$.data[2].levelOrder").value(4))   // PREMIUM
+                .andExpect(jsonPath("$.data[3].levelOrder").value(2));  // BASIC
+    }
+}

+ 156 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ReportParserTypeLinksTest.java

@@ -0,0 +1,156 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ReportTypeRegistry;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * /api/report-parser/types/links 契约测试(小程序上传页「支持的报告类型」配置化)。
+ *
+ * 目标行为:
+ * 1) 返回所有 is_active=1 的类型(不再过滤 linked_product_id 非空);
+ * 2) 返回字段含 typeId/displayName/description/icon/sortOrder/linkedProductId/productName;
+ *    无商品时 linkedProductId 与 productName 为 null;
+ * 3) 按 sortOrder 升序排序,sortOrder 相等时按 id 升序稳定排序;
+ * 4) is_active=0 的类型不返回。
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class ReportParserTypeLinksTest {
+
+    @Mock
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @Mock
+    private ProductMapper productMapper;
+
+    @InjectMocks
+    private ReportParserController controller;
+
+    private ReportTypeRegistry type(Long id, String typeId, String displayName, String description,
+                                    String icon, Integer sortOrder, Long linkedProductId, boolean active) {
+        ReportTypeRegistry t = new ReportTypeRegistry();
+        t.setId(id);
+        t.setTypeId(typeId);
+        t.setDisplayName(displayName);
+        t.setDescription(description);
+        t.setIcon(icon);
+        t.setSortOrder(sortOrder);
+        t.setLinkedProductId(linkedProductId);
+        t.setIsActive(active);
+        return t;
+    }
+
+    private Product product(Long id, String name) {
+        Product p = new Product();
+        p.setId(id);
+        p.setName(name);
+        return p;
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Map<String, Object>> invoke() {
+        Result<List<Map<String, Object>>> r = controller.listTypeLinks();
+        assertEquals(200, r.getCode(), "接口应返回成功");
+        return (List<Map<String, Object>>) r.getData();
+    }
+
+    /** 契约1:返回所有激活类型,包含未配置商品链接(linked_product_id 为 null)的类型 */
+    @Test
+    void returnsAllActiveTypesIncludingOnesWithoutProductLink() {
+        ReportTypeRegistry withLink = type(1L, "gut_flora", "菌群检测报告", "肠道菌群 PDF", "📄", 1, 101L, true);
+        ReportTypeRegistry noLink = type(2L, "physical_exam", "体检报告", "血常规、尿常规等", "📋", 3, null, true);
+        when(typeRegistryMapper.selectList(any())).thenReturn(new ArrayList<>(Arrays.asList(withLink, noLink)));
+        when(productMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(product(101L, "菌群检测服务")));
+
+        List<Map<String, Object>> data = invoke();
+
+        assertEquals(2, data.size(), "未配置商品链接的激活类型也应返回");
+        assertTrue(data.stream().anyMatch(m -> "physical_exam".equals(m.get("typeId"))),
+                "linked_product_id 为 null 的类型应出现在结果中");
+    }
+
+    /** 契约2:返回字段齐全;无商品时 linkedProductId 与 productName 为 null */
+    @Test
+    void responseContainsAllFieldsAndNullProductWhenMissing() {
+        ReportTypeRegistry withLink = type(1L, "gut_flora", "菌群检测报告", "肠道菌群 PDF", "📄", 1, 101L, true);
+        ReportTypeRegistry noLink = type(2L, "tongue", "舌象照片", "拍摄舌象照片,AI 辅助舌诊分析", "👅", 4, null, true);
+        when(typeRegistryMapper.selectList(any())).thenReturn(new ArrayList<>(Arrays.asList(withLink, noLink)));
+        when(productMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(product(101L, "菌群检测服务")));
+
+        List<Map<String, Object>> data = invoke();
+        Map<String, Object> linked = data.stream().filter(m -> "gut_flora".equals(m.get("typeId"))).findFirst().get();
+        assertTrue(linked.containsKey("typeId"), "应含 typeId");
+        assertTrue(linked.containsKey("displayName"), "应含 displayName");
+        assertTrue(linked.containsKey("description"), "应含 description");
+        assertTrue(linked.containsKey("icon"), "应含 icon");
+        assertTrue(linked.containsKey("sortOrder"), "应含 sortOrder");
+        assertTrue(linked.containsKey("linkedProductId"), "应含 linkedProductId");
+        assertTrue(linked.containsKey("productName"), "应含 productName");
+        assertEquals("菌群检测报告", linked.get("displayName"));
+        assertEquals("肠道菌群 PDF", linked.get("description"));
+        assertEquals("📄", linked.get("icon"));
+        assertEquals(1, linked.get("sortOrder"));
+        assertEquals(101L, linked.get("linkedProductId"));
+        assertEquals("菌群检测服务", linked.get("productName"));
+
+        Map<String, Object> unlinked = data.stream().filter(m -> "tongue".equals(m.get("typeId"))).findFirst().get();
+        assertNull(unlinked.get("linkedProductId"), "无商品时 linkedProductId 应为 null");
+        assertNull(unlinked.get("productName"), "无商品时 productName 应为 null");
+    }
+
+    /** 契约3:按 sortOrder 升序排序,sortOrder 相等时按 id 升序稳定排序 */
+    @Test
+    void sortedBySortOrderAscThenIdAsc() {
+        ReportTypeRegistry a = type(3L, "body_fat", "体脂秤报告", "d5", "⚖️", 5, null, true);
+        ReportTypeRegistry b = type(1L, "gut_flora", "菌群检测报告", "d1", "📄", 1, null, true);
+        ReportTypeRegistry c = type(2L, "physical_exam", "体检报告", "d3", "📋", 3, null, true);
+        ReportTypeRegistry d = type(10L, "dan_a2", "素质测评A2", "d2b", "🧠", 2, null, true);
+        ReportTypeRegistry e = type(5L, "dan_a1", "素质测评A1", "d2a", "🧠", 2, null, true);
+        // 乱序 + 两组 sortOrder=2(id 5 < 10)
+        when(typeRegistryMapper.selectList(any()))
+                .thenReturn(new ArrayList<>(Arrays.asList(a, b, c, d, e)));
+
+        List<Map<String, Object>> data = invoke();
+
+        List<String> order = new ArrayList<>();
+        for (Map<String, Object> m : data) order.add((String) m.get("typeId"));
+        assertEquals(Arrays.asList("gut_flora", "dan_a1", "dan_a2", "physical_exam", "body_fat"), order,
+                "应按 sortOrder 升序,相等时按 id 升序(dan_a1 id=5 先于 dan_a2 id=10)");
+    }
+
+    /** 契约4:is_active=0 的类型不返回 */
+    @Test
+    void inactiveTypeIsNotReturned() {
+        ReportTypeRegistry active = type(1L, "gut_flora", "菌群检测报告", "肠道菌群 PDF", "📄", 1, 101L, true);
+        ReportTypeRegistry inactive = type(2L, "dan_b6", "素质测评B6", "已停用", "🧠", 6, null, false);
+        when(typeRegistryMapper.selectList(any())).thenReturn(new ArrayList<>(Arrays.asList(active, inactive)));
+        when(productMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(product(101L, "菌群检测服务")));
+
+        List<Map<String, Object>> data = invoke();
+
+        assertEquals(1, data.size(), "is_active=0 的类型不应返回");
+        assertEquals("gut_flora", data.get(0).get("typeId"));
+    }
+}

+ 143 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG01LandingContractTest.java

@@ -0,0 +1,143 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.testutil.FrontendSourceLocator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-01 首次进入小程序/落地页 契约级单测(能力键 auth.guest.landing)
+ * ================================================================
+ * 覆盖:
+ * - 正常流 (TC-G-01):冷启动进入 splash → 落地页(config.js 存在默认 API 地址);页面不自动进入业务页。
+ * - 异常流 (TC-G-01-E):弱网/微信授权失败 → config.js try/catch 回退默认地址,不白屏(前端源契约)。
+ * - 权限流 (TC-G-01-P):游客无 token 访问公开路径放行(/api/product/list、/api/articles/list);
+ *   业务接口(/api/family/member/list)被 JwtInterceptor 拦截 → 401。
+ *
+ * 溯源:SC-G-01 · tests/user-scenarios/01-guest.md 场景 G-1 · tests/test-cases/guest.md TC-G-01/TC-G-01-E/TC-G-01-P
+ *
+ * 纯单元测试:Mockito + MockHttpServletRequest/Response(权限流走真实 JwtInterceptor 契约),
+ * 不依赖数据库 / 真实微信 / Spring 容器,保证可执行性与确定性。
+ */
+public class ScG01LandingContractTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-01:前端落地页链路存在(splash + 首页 + config.js 默认地址)
+    // ====================================================================
+
+    @Test
+    public void frontend_landingPagesExist() {
+        // 冷启动进入 splash,2 秒后 reLaunch 到 index-home —— 前端页面必须存在
+        assertTrue(FrontendSourceLocator.frontendSourceExists("pages/splash/index.vue"),
+                "启动页 pages/splash/index.vue 必须存在");
+        assertTrue(FrontendSourceLocator.frontendSourceExists("pages/index-home/index.vue"),
+                "落地页 pages/index-home/index.vue 必须存在");
+        String splash = FrontendSourceLocator.readFrontendSource("pages/splash/index.vue");
+        assertTrue(splash.contains("reLaunch"), "splash 应在展示后跳转落地页");
+        assertTrue(splash.contains("/pages/index-home/index"), "splash 应跳转 index-home 落地页");
+    }
+
+    @Test
+    public void frontend_configHasDefaultApiBaseUrl() {
+        // 落地页依赖 config.js 提供 API_BASE_URL;默认地址必须存在(非空)
+        String config = FrontendSourceLocator.readFrontendSource("config.js");
+        assertTrue(config.contains("API_BASE_URL"), "config.js 必须定义 API_BASE_URL");
+        assertTrue(config.contains("cfc"), "config.js 默认地址应含 cfc 域名");
+        assertTrue(config.contains("export default"), "config.js 必须导出配置对象");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-01-E:弱网/授权失败有兜底(config.js try/catch 回退默认地址,不白屏)
+    // ====================================================================
+
+    @Test
+    public void frontend_configFallsBackOnEnvDetectionFailure() {
+        // 环境探测失败(getAccountInfoSync 抛异常)→ catch 回退默认 API_BASE_URL,不崩溃不白屏
+        String config = FrontendSourceLocator.readFrontendSource("config.js");
+        assertTrue(config.contains("try {"), "config.js 必须用 try 包裹环境探测");
+        assertTrue(config.contains("catch"), "config.js 必须捕获环境探测异常(弱网/非微信)");
+        assertTrue(config.contains("getAccountInfoSync"), "环境探测须调用 getAccountInfoSync");
+    }
+
+    @Test
+    public void frontend_splashHasLoginEntryNotAutoEnterBusiness() {
+        // 落地页/首页不自动进入业务页(家庭/任务/能量)——splash 只 reLaunch 到 index-home
+        String splash = FrontendSourceLocator.readFrontendSource("pages/splash/index.vue");
+        assertFalse(splash.contains("/pages/family/index"), "splash 不应直接进家庭业务页");
+        assertFalse(splash.contains("/pages/tasks/index"), "splash 不应直接进任务业务页");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-01-P:游客无 token 公开路径放行;业务接口 401(不泄露内部结构)
+    // ====================================================================
+
+    @Test
+    public void permission_publicProductList_anonymousAllowed() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/product/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开商品列表路径无 token 应放行(游客可浏览)");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "公开路径不应写 401");
+    }
+
+    @Test
+    public void permission_publicArticlesList_anonymousAllowed() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/articles/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开文章列表路径无 token 应放行");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+    }
+
+    @Test
+    public void permission_protectedFamilyMemberList_is401NoLeak() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "业务接口无 token 必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), "应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), "应含统一 code=401,实际: " + body);
+        assertTrue(body.contains("请先登录"), "应含统一 message,实际: " + body);
+        assertFalse(body.contains("Exception"), "不得泄露内部异常: " + body);
+        assertFalse(body.contains("at com.etotem"), "不得泄露调用堆栈: " + body);
+    }
+}

+ 312 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG03LoginMethodContractTest.java

@@ -0,0 +1,312 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.controller.admin.AdminAuthController;
+import com.etotem.cfc.controller.auth.AuthController;
+import com.etotem.cfc.dto.AdminLoginDTO;
+import com.etotem.cfc.dto.LoginResultDTO;
+import com.etotem.cfc.dto.PhoneLoginDTO;
+import com.etotem.cfc.dto.SendCodeDTO;
+import com.etotem.cfc.dto.WechatPhoneLoginDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.LoginAttemptService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import com.etotem.cfc.service.WechatWebLoginService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+/**
+ * SC-G-03 登录方式口径契约级单测(能力键 auth.guest.loginMethod)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-3、tests/test-cases/guest.md TC-G-03):
+ * - 小程序端:微信一键登录(wechat-login,SC-G-02 已覆盖)、微信手机号快捷登录(wechat-phone-login)、
+ *   验证码登录(phone-login / send-code,API 兼容保留:小程序端无入口,服务端能力保留)。
+ * - Web 管理后台:密码登录(login-by-password)、验证码登录(send-code + login)。
+ * - 异常流 (TC-G-03-E):验证码错误/过期 → 明确失败且不产生会话;手机号格式非法 → 400;不泄露堆栈。
+ * - 权限流 (TC-G-03-P):全部登录端点在 JwtInterceptor 公开白名单内,游客无 token 可触达(不误拦 401)。
+ *
+ * 溯源:SC-G-03 · tests/user-scenarios/01-guest.md 场景 G-3 · tests/test-cases/guest.md TC-G-03/TC-G-03-E
+ *
+ * 纯单元测试:Mockito 直接调用 handler + MockHttpServletRequest/Response,不依赖数据库/真实微信/Spring 容器。
+ */
+public class ScG03LoginMethodContractTest {
+
+    @Mock
+    private UserService userService;
+    @Mock
+    private VerificationCodeService verificationCodeService;
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private AuthController authController;
+
+    @Mock
+    private LoginAttemptService loginAttemptService;
+    @Mock
+    private WechatWebLoginService wechatWebLoginService;
+    @InjectMocks
+    private AdminAuthController adminAuthController;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-03:验证码登录(API 兼容保留:服务端能力)
+    // ====================================================================
+
+    @Test
+    public void sendCode_ValidPhone_GeneratesCode() {
+        SendCodeDTO dto = new SendCodeDTO();
+        dto.setPhone("13800000001");
+        dto.setType("login");
+
+        Result<Boolean> result = authController.sendCode(dto);
+
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData(), "发送验证码应返回 true");
+        verify(verificationCodeService, times(1)).generateCode("13800000001", "login");
+    }
+
+    @Test
+    public void phoneLogin_ValidCode_ReturnsToken() {
+        PhoneLoginDTO dto = new PhoneLoginDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("123456");
+
+        when(verificationCodeService.verifyCode("13800000001", "123456", "login")).thenReturn(true);
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setToken("jwt-token");
+        login.setUserId(99L);
+        login.setRole("parent");
+        when(userService.phoneLogin(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = authController.phoneLogin(dto);
+
+        assertEquals(200, result.getCode());
+        assertEquals("jwt-token", result.getData().getToken());
+        assertEquals("parent", result.getData().getRole());
+        verify(verificationCodeService, times(1)).verifyCode("13800000001", "123456", "login");
+        verify(userService, times(1)).phoneLogin(dto);
+    }
+
+    @Test
+    public void wechatPhoneLogin_ValidInput_ReturnsToken() {
+        WechatPhoneLoginDTO dto = new WechatPhoneLoginDTO();
+        dto.setCode("wx-code");
+        dto.setPhoneCode("phone-code");
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setToken("wxtoken");
+        login.setUserId(77L);
+        login.setRole("parent");
+        when(userService.wechatPhoneLogin(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = authController.wechatPhoneLogin(dto);
+
+        assertEquals(200, result.getCode());
+        assertEquals("wxtoken", result.getData().getToken());
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-03:Web 管理后台密码登录(login-by-password)
+    // ====================================================================
+
+    @Test
+    public void adminLoginByPassword_ValidCredential_ReturnsToken() {
+        AdminLoginDTO dto = new AdminLoginDTO();
+        dto.setPhone("13800000001");
+        dto.setPassword("password123");
+
+        // 预置后台角色用户,密码以 BCrypt 存储(兼容逻辑,verifyLoginPassword 支持 MD5+BCrypt)
+        User admin = new User();
+        admin.setId(5L);
+        admin.setPhone("13800000001");
+        admin.setRole("admin");
+        admin.setPassword("{bcrypt}" + "$2a$10$abcdefghijklmnopqrstuv");
+        when(userMapper.selectOne(any())).thenReturn(admin);
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(userService.getUserRoles(5L)).thenReturn(java.util.Collections.singletonList("admin"));
+        when(jwtConfig.generateToken(eq(5L), anyList())).thenReturn("admin-jwt");
+
+        // 密码用正确哈希后验证:直接构造 BCrypt 匹配
+        org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder =
+                new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();
+        admin.setPassword(encoder.encode("password123"));
+
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        Result<java.util.Map<String, Object>> result = adminAuthController.loginByPassword(dto, req);
+
+        // 若 mock 链完整则 200 + token
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals("admin-jwt", result.getData().get("token"));
+    }
+
+    @Test
+    public void adminLoginByPassword_EmptyBody_Is400() {
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        Result<java.util.Map<String, Object>> result = adminAuthController.loginByPassword(null, req);
+        assertEquals(400, result.getCode(), "空 body 应返回业务码 400");
+        assertNull(result.getData());
+    }
+
+    @Test
+    public void adminLoginByPassword_MissingFields_Is400() {
+        AdminLoginDTO dto = new AdminLoginDTO();
+        dto.setPhone("13800000001");
+        dto.setPassword(null);
+        MockHttpServletRequest req = new MockHttpServletRequest();
+        Result<java.util.Map<String, Object>> result = adminAuthController.loginByPassword(dto, req);
+        assertEquals(400, result.getCode(), "缺密码应返回业务码 400");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-03-E:验证码错误/手机号非法 → 明确失败且不产生会话
+    // ====================================================================
+
+    @Test
+    public void sendCode_InvalidPhone_ReturnsError() {
+        SendCodeDTO dto = new SendCodeDTO();
+        dto.setPhone("123"); // 非法格式
+        Result<Boolean> result = authController.sendCode(dto);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("格式不正确"), "手机号非法应提示格式错误,实际: " + result.getMessage());
+        verify(verificationCodeService, never()).generateCode(anyString(), anyString());
+    }
+
+    @Test
+    public void sendCode_EmptyPhone_ReturnsError() {
+        SendCodeDTO dto = new SendCodeDTO();
+        dto.setPhone("");
+        Result<Boolean> result = authController.sendCode(dto);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("不能为空"), "空手机号应提示,实际: " + result.getMessage());
+    }
+
+    @Test
+    public void phoneLogin_WrongCode_ReturnsErrorNoToken() {
+        PhoneLoginDTO dto = new PhoneLoginDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("000000");
+
+        when(verificationCodeService.verifyCode("13800000001", "000000", "login")).thenReturn(false);
+
+        Result<LoginResultDTO> result = authController.phoneLogin(dto);
+
+        assertEquals(500, result.getCode(), "验证码错误应返回业务码 500");
+        assertTrue(result.getMessage().contains("验证码错误"), "实际: " + result.getMessage());
+        assertNull(result.getData(), "验证码错误绝不产生会话(data 必须为 null)");
+        verify(userService, never()).phoneLogin(any());
+    }
+
+    @Test
+    public void phoneLogin_ServiceFailure_ErrorMessageDoesNotLeakStack() {
+        PhoneLoginDTO dto = new PhoneLoginDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("123456");
+        when(verificationCodeService.verifyCode(anyString(), anyString(), anyString())).thenReturn(true);
+        when(userService.phoneLogin(dto)).thenThrow(new RuntimeException("登录失败"));
+
+        Result<LoginResultDTO> result = authController.phoneLogin(dto);
+
+        String msg = result.getMessage();
+        assertNotNull(msg);
+        assertFalse(msg.contains("RuntimeException"), "不得泄露异常类名: " + msg);
+        assertFalse(msg.contains("at com."), "不得泄露堆栈: " + msg);
+    }
+
+    @Test
+    public void wechatPhoneLogin_MissingParams_ReturnsError() {
+        WechatPhoneLoginDTO dto = new WechatPhoneLoginDTO();
+        dto.setCode(null);
+        dto.setPhoneCode(null);
+        Result<LoginResultDTO> result = authController.wechatPhoneLogin(dto);
+        assertEquals(500, result.getCode());
+        assertNull(result.getData());
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-03-P:全部登录端点在公开白名单内(游客无 token 可触达)
+    // ====================================================================
+
+    @Test
+    public void permission_loginEndpoints_arePublicNotBlocked() throws Exception {
+        String[] publicPaths = {
+                "/api/auth/send-code",
+                "/api/auth/phone-login",
+                "/api/auth/wechat-phone-login",
+                "/api/auth/wechat-login",
+                "/api/auth/register-with-invite",
+                "/api/admin-auth/send-code",
+                "/api/admin-auth/login",
+                "/api/admin-auth/login-by-password",
+                "/api/admin-auth/account-roles",
+                "/api/admin-auth/wechat-scan-qr",
+                "/api/admin-auth/wechat-scan-poll",
+        };
+        for (String path : publicPaths) {
+            MockHttpServletRequest request = new MockHttpServletRequest();
+            request.setMethod("POST");
+            request.setRequestURI(path);
+            MockHttpServletResponse response = new MockHttpServletResponse();
+            boolean allowed = jwtInterceptor.preHandle(request, response, null);
+            assertTrue(allowed, "登录端点应为公开路径,游客可触达: " + path);
+            assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "公开登录端点不应写 401: " + path);
+        }
+    }
+
+    // ====================================================================
+    // 结构契约:统一 POST
+    // ====================================================================
+
+    @Test
+    public void structure_loginEndpointsUsePostMapping() throws Exception {
+        // 小程序端
+        for (String m : new String[]{"sendCode", "phoneLogin", "wechatPhoneLogin"}) {
+            for (Method method : AuthController.class.getDeclaredMethods()) {
+                if (method.getName().equals(m)) {
+                    assertNotNull(method.getAnnotation(org.springframework.web.bind.annotation.PostMapping.class),
+                            "AuthController." + m + " 必须为 @PostMapping");
+                }
+            }
+        }
+        // 管理端
+        for (String m : new String[]{"sendCode", "login", "loginByPassword", "wechatScanQr", "wechatScanPoll"}) {
+            for (Method method : AdminAuthController.class.getDeclaredMethods()) {
+                if (method.getName().equals(m)) {
+                    assertNotNull(method.getAnnotation(org.springframework.web.bind.annotation.PostMapping.class),
+                            "AdminAuthController." + m + " 必须为 @PostMapping");
+                }
+            }
+        }
+    }
+}

+ 246 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG04InviteRegisterContractTest.java

@@ -0,0 +1,246 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.controller.auth.AuthController;
+import com.etotem.cfc.controller.family.FamilyInviteController;
+import com.etotem.cfc.dto.InviteValidateDTO;
+import com.etotem.cfc.dto.LoginResultDTO;
+import com.etotem.cfc.dto.RegisterWithInviteCodeDTO;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyInvitationService;
+import com.etotem.cfc.service.FamilyJoinRequestService;
+import com.etotem.cfc.service.QrCodeService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import com.etotem.cfc.service.WechatService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * SC-G-04 邀请码注册加入家庭 契约级单测(能力键 family.invite.register)
+ * ================================================================
+ * 覆盖:
+ * - 正常流 (TC-G-04):POST /api/auth/register-with-invite 携带有效邀请令牌 + 正确验证码
+ *   → 注册成功并返回 token + 归属家庭(userService.registerWithInviteCode 被调用)。
+ * - 异常流 (TC-G-04-E):邀请码失效/验证码错误/手机号已注册 → 明确拒绝(不串家庭);
+ *   邀请令牌为空 → 提示「邀请令牌不能为空」。
+ * - 权限流 (TC-G-04-P):register-with-invite / invite/validate / validate-family-code 在公开白名单;
+ *   /api/family/invite/generate 需登录(游客 401)。
+ *
+ * 溯源:SC-G-04 · tests/user-scenarios/01-guest.md 场景 G-4 · tests/test-cases/guest.md TC-G-04/TC-G-04-E/TC-G-04-P
+ *
+ * 纯单元测试:Mockito 直接调用 handler,不依赖数据库/真实微信/Spring 容器。
+ */
+public class ScG04InviteRegisterContractTest {
+
+    @Mock
+    private UserService userService;
+    @Mock
+    private VerificationCodeService verificationCodeService;
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private AuthController authController;
+
+    @Mock
+    private FamilyMapper familyMapper;
+    @Mock
+    private QrCodeService qrCodeService;
+    @Mock
+    private FamilyInvitationService familyInvitationService;
+    @Mock
+    private FamilyJoinRequestService familyJoinRequestService;
+    @Mock
+    private WechatService wechatService;
+    @Mock
+    private UnlockGateService unlockGateService;
+    @InjectMocks
+    private FamilyInviteController familyInviteController;
+
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-04:register-with-invite 有效令牌+验证码 → 注册成功归属家庭
+    // ====================================================================
+
+    @Test
+    public void registerWithInvite_ValidInput_ReturnsTokenAndFamily() {
+        RegisterWithInviteCodeDTO dto = new RegisterWithInviteCodeDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("123456");
+        dto.setInviteCode("INVITE-ABC-123");
+        dto.setRole("parent");
+        dto.setNickname("新用户");
+        dto.setCodeId("code-id-1");
+
+        when(verificationCodeService.verifyCode("13800000001", "123456", "code-id-1")).thenReturn(true);
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(false);
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setToken("invite-jwt");
+        login.setUserId(101L);
+        login.setRole("parent");
+        login.setFamilyId(202L);
+        login.setIsNewUser(true);
+        when(userService.registerWithInviteCode(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = authController.registerWithInvite(dto);
+
+        assertEquals(200, result.getCode(), "邀请注册成功应返回 code=200");
+        assertEquals("invite-jwt", result.getData().getToken());
+        assertEquals(202L, result.getData().getFamilyId(), "注册后应归属对应家庭");
+        assertTrue(result.getData().getIsNewUser());
+        verify(userService, times(1)).registerWithInviteCode(dto);
+    }
+
+    @Test
+    public void validateInvite_ValidToken_ReturnsFamilyInfo() {
+        Map<String, String> body = new HashMap<>();
+        body.put("token", "VALID-TOKEN");
+
+        InviteValidateDTO dto = new InviteValidateDTO();
+        dto.setFamilyId(202L);
+        dto.setFamilyName("测试家庭");
+        dto.setInviterName("家长");
+        dto.setMemberCount(3);
+        when(familyInvitationService.validateInvitation("VALID-TOKEN")).thenReturn(dto);
+
+        Result<InviteValidateDTO> result = familyInviteController.validateInvite(body);
+
+        assertEquals(200, result.getCode());
+        assertEquals("测试家庭", result.getData().getFamilyName());
+        assertEquals(202L, result.getData().getFamilyId());
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-04-E:令牌失效/验证码错/已注册 → 明确拒绝
+    // ====================================================================
+
+    @Test
+    public void registerWithInvite_InvalidCode_ReturnsErrorNoSession() {
+        RegisterWithInviteCodeDTO dto = new RegisterWithInviteCodeDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("wrong");
+        dto.setInviteCode("INVITE-ABC-123");
+        dto.setCodeId("code-id-1");
+
+        when(verificationCodeService.verifyCode(anyString(), anyString(), anyString())).thenReturn(false);
+
+        Result<LoginResultDTO> result = authController.registerWithInvite(dto);
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("验证码错误"), "实际: " + result.getMessage());
+        assertNull(result.getData(), "验证码错误不产生会话");
+        verify(userService, never()).registerWithInviteCode(any());
+    }
+
+    @Test
+    public void registerWithInvite_AlreadyRegistered_ReturnsError() {
+        RegisterWithInviteCodeDTO dto = new RegisterWithInviteCodeDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("123456");
+        dto.setInviteCode("INVITE-ABC-123");
+        dto.setCodeId("code-id-1");
+
+        when(verificationCodeService.verifyCode(anyString(), anyString(), anyString())).thenReturn(true);
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(true);
+
+        Result<LoginResultDTO> result = authController.registerWithInvite(dto);
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("已注册"), "实际: " + result.getMessage());
+        verify(userService, never()).registerWithInviteCode(any());
+    }
+
+    @Test
+    public void registerWithInvite_MissingInviteCode_ReturnsError() {
+        RegisterWithInviteCodeDTO dto = new RegisterWithInviteCodeDTO();
+        dto.setPhone("13800000001");
+        dto.setCode("123456");
+        dto.setInviteCode(null);
+
+        Result<LoginResultDTO> result = authController.registerWithInvite(dto);
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("邀请码不能为空"), "实际: " + result.getMessage());
+    }
+
+    @Test
+    public void registerWithInvite_MissingPhone_ReturnsError() {
+        RegisterWithInviteCodeDTO dto = new RegisterWithInviteCodeDTO();
+        dto.setPhone(null);
+        dto.setCode("123456");
+        dto.setInviteCode("INVITE-ABC-123");
+        Result<LoginResultDTO> result = authController.registerWithInvite(dto);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("手机号不能为空"), "实际: " + result.getMessage());
+    }
+
+    @Test
+    public void validateInvite_EmptyToken_ReturnsError() {
+        Map<String, String> body = new HashMap<>();
+        body.put("token", "");
+        Result<InviteValidateDTO> result = familyInviteController.validateInvite(body);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("邀请令牌不能为空"), "实际: " + result.getMessage());
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-04-P:register/invite-validate 公开;invite/generate 需登录
+    // ====================================================================
+
+    @Test
+    public void permission_publicInviteEndpoints_anonymousAllowed() throws Exception {
+        String[] publicPaths = {
+                "/api/auth/register-with-invite",
+                "/api/family/invite/validate",
+                "/api/family/invite/validate-family-code",
+        };
+        for (String path : publicPaths) {
+            MockHttpServletRequest request = new MockHttpServletRequest();
+            request.setMethod("POST");
+            request.setRequestURI(path);
+            MockHttpServletResponse response = new MockHttpServletResponse();
+            boolean allowed = jwtInterceptor.preHandle(request, response, null);
+            assertTrue(allowed, "邀请相关公开端点游客应可触达: " + path);
+            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+        }
+    }
+
+    @Test
+    public void permission_generateInvite_requiresLogin() {
+        // 无 token 调用 generate(通过 JwtInterceptor 判定 /api/family/invite/generate 不在公开白名单,
+        // 且 generateInvite 控制器内 userId==null → 返回「请先登录」)
+        Result<com.etotem.cfc.dto.InviteGenerateDTO> result = familyInviteController.generateInvite(null);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("请先登录"), "实际: " + result.getMessage());
+    }
+}

+ 193 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG05AnonymousBrowseContractTest.java

@@ -0,0 +1,193 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.controller.content.ArticleController;
+import com.etotem.cfc.controller.product.ProductController;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import io.jsonwebtoken.Claims;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.*;
+
+/**
+ * SC-G-05 未登录访问业务页被拦截;浏览商城/文章可被放行 契约级单测(能力键 auth.guest.browse)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-5、tests/test-cases/guest.md TC-G-05/TC-G-05-E):
+ * - 正常流 (TC-G-05):游客无 token 可匿名浏览 `/api/product/list`、`/api/articles/list`(公开白名单);
+ *   两个列表端点结构契约均为 @PostMapping(统一 POST)。
+ * - 异常流 (TC-G-05-E):未登录直接访问受保护业务接口(家庭成员列表)→ 401;公开路径携带无效/过期 token
+ *   → 降级匿名放行、不误拦 401(保持游客可浏览)。
+ * - 权限流 (TC-G-05-P):登录用户访问公开路径享受登录上下文(X-User-Id 注入,不误拦);未登录受保护接口
+ *   统一 401 且响应体不泄露内部异常/堆栈。
+ *
+ * 溯源:SC-G-05 · tests/user-scenarios/01-guest.md 场景 G-5 · tests/test-cases/guest.md TC-G-05/TC-G-05-E/
+ *
+ * 纯单元测试:Mockito + MockHttpServletRequest/Response(权限流走真实 JwtInterceptor 契约),
+ * 不依赖数据库 / 真实微信 / Spring 容器。
+ */
+public class ScG05AnonymousBrowseContractTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-05:公开浏览路径匿名放行
+    // ====================================================================
+
+    @Test
+    public void normal_publicProductList_anonymousAllowed() throws Exception {
+        assertPublicAllowed("/api/product/list");
+    }
+
+    @Test
+    public void normal_publicArticlesList_anonymousAllowed() throws Exception {
+        assertPublicAllowed("/api/articles/list");
+    }
+
+    @Test
+    public void normal_productList_isPostMapping() {
+        assertPostMapping(ProductController.class, "list");
+    }
+
+    @Test
+    public void normal_articlesList_isPostMapping() {
+        assertPostMapping(ArticleController.class, "list");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-05-E:未登录受保护接口 401;公开路径无效 token 降级匿名放行
+    // ====================================================================
+
+    @Test
+    public void exception_protectedFamilyMemberList_noToken_401() throws Exception {
+        assertProtected401("/api/family/member/list");
+    }
+
+    @Test
+    public void exception_publicPath_invalidToken_degradedAnonymous() throws Exception {
+        when(jwtConfig.parseToken(anyString()))
+                .thenThrow(new io.jsonwebtoken.ExpiredJwtException(null, null, "expired"));
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/product/list");
+        request.addHeader("Authorization", "Bearer expired.token");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "公开路径无效 token 应降级匿名放行,不误拦 401");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "公开路径不应写 401");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-05-P:登录用户公开路径享受上下文;未登录业务接口统一 401 不泄露
+    // ====================================================================
+
+    @Test
+    public void permission_loggedInUser_onPublicPath_getsUserIdContext() throws Exception {
+        Claims claims = mock(Claims.class);
+        when(jwtConfig.parseToken(anyString())).thenReturn(claims);
+        when(claims.getSubject()).thenReturn("100");
+        when(claims.get("role")).thenReturn("parent");
+        when(claims.get("roles")).thenReturn(null);
+
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/product/list");
+        request.addHeader("Authorization", "Bearer valid.token");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, "登录用户访问公开路径应放行(不误拦)");
+        assertEquals("100", response.getHeader("X-User-Id"), "公开路径应注入登录用户上下文");
+        assertEquals(Long.valueOf(100L), (Long) request.getAttribute("userId"));
+    }
+
+    @Test
+    public void permission_protected_noToken_401_unifiedResult() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "受保护接口无 token 必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), "应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), "应含统一 code=401,实际: " + body);
+        assertTrue(body.contains("请先登录"), "应含统一 message,实际: " + body);
+        assertFalse(body.contains("Exception"), "不得泄露内部异常: " + body);
+        assertFalse(body.contains("at com.etotem"), "不得泄露调用堆栈: " + body);
+    }
+
+    // ====================================================================
+    // 断言辅助
+    // ====================================================================
+
+    private void assertPublicAllowed(String path) throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(path);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertTrue(result, path + " 公开路径应匿名放行");
+        assertEquals(HttpServletResponse.SC_OK, response.getStatus(), path + " 不应写 401/403");
+    }
+
+    private void assertProtected401(String path) throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI(path);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, path + " 无 token 必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), path + " 应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), path + " 应含统一 code=401,实际: " + body);
+        assertFalse(body.contains("Exception"), path + " 不得泄露内部异常: " + body);
+    }
+
+    private void assertPostMapping(Class<?> controllerClass, String methodName) {
+        boolean found = false;
+        for (Method method : controllerClass.getDeclaredMethods()) {
+            if (method.getName().equals(methodName)) {
+                found = true;
+                assertNotNull(method.getAnnotation(PostMapping.class),
+                        controllerClass.getSimpleName() + "." + methodName + " 必须为 @PostMapping(统一 POST 规范)");
+            }
+        }
+        assertTrue(found, controllerClass.getSimpleName() + "." + methodName + " 方法必须存在");
+    }
+}

+ 95 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG07TestModeContractTest.java

@@ -0,0 +1,95 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.service.WechatService;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-07 微信测试模式跳过授权 契约级单测(能力键 auth.guest.testMode)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-7、tests/test-cases/guest.md TC-G-07/TC-G-07-E/TC-G-07-P):
+ * - 正常流 (TC-G-07):测试模式开 → code2Session 返回模拟 openid(test_openid_ 前缀),不触网、不依赖真实微信。
+ * - 异常流 (TC-G-07-E):生产环境误开 test-mode → 启动即抛 IllegalStateException(生产强制真实微信授权)。
+ * - 权限流 (TC-G-07-P):test-mode 关闭时 isTestMode()=false;生产环境未开 test-mode 正常启动;
+ *   非生产环境开启 test-mode 仅告警、不崩溃(测试模式仅测试环境生效)。
+ *
+ * 溯源:SC-G-07 · tests/user-scenarios/01-guest.md 场景 G-7 · tests/test-cases/guest.md TC-G-07/TC-G-07-E/TC-G-07-P
+ *
+ * 纯单元测试:直接 new WechatService() + 反射注入 @Value 字段(testMode/activeProfile),
+ * 不依赖数据库 / 真实微信网络 / Spring 容器,保证确定性。
+ */
+public class ScG07TestModeContractTest {
+
+    /**
+     * 构造测试模式可控的 WechatService(反射注入 @Value 私有字段)。
+     */
+    private WechatService newService(boolean testMode, String activeProfile) {
+        WechatService service = new WechatService();
+        ReflectionTestUtils.setField(service, "testMode", testMode);
+        ReflectionTestUtils.setField(service, "activeProfile", activeProfile);
+        return service;
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-07:测试模式开 → code2Session 返回模拟 openid,不触网
+    // ====================================================================
+
+    @Test
+    public void normal_testMode_code2Session_returnsMockOpenid() {
+        WechatService service = newService(true, "dev");
+
+        assertTrue(service.isTestMode(), "测试模式开启后 isTestMode 应为 true");
+        Map<String, String> result = service.code2Session("wx-code");
+
+        assertNotNull(result, "测试模式应返回非空会话结果");
+        assertNotNull(result.get("openid"), "应返回模拟 openid");
+        assertTrue(result.get("openid").startsWith("test_openid_"),
+                "模拟 openid 应以 test_openid_ 前缀标识,实际: " + result.get("openid"));
+        assertEquals("test_session_key", result.get("session_key"), "应返回模拟 session_key");
+        assertEquals("", result.get("unionid"), "模拟 unionid 应为空串");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-07-E:生产环境误开 test-mode → 启动拒绝
+    // ====================================================================
+
+    @Test
+    public void exception_prodProfile_withTestMode_throwsAtStartup() {
+        WechatService service = newService(true, "prod");
+
+        assertThrows(IllegalStateException.class, service::checkTestModeAtStartup,
+                "生产环境开启测试模式必须拒绝启动(强制真实微信授权)");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-07-P:测试模式仅在非生产生效;生产未开正常启动
+    // ====================================================================
+
+    @Test
+    public void permission_prodProfile_withoutTestMode_startsNormally() {
+        WechatService service = newService(false, "prod");
+
+        assertFalse(service.isTestMode(), "生产环境未开测试模式");
+        assertDoesNotThrow(service::checkTestModeAtStartup,
+                "生产环境未开测试模式应正常启动");
+    }
+
+    @Test
+    public void permission_nonProdProfile_withTestMode_warnsButDoesNotThrow() {
+        WechatService service = newService(true, "dev");
+
+        assertDoesNotThrow(service::checkTestModeAtStartup,
+                "非生产环境开启测试模式仅告警,不应崩溃");
+    }
+
+    @Test
+    public void permission_testModeOff_code2SessionNotMocked() {
+        // 测试模式关闭:isTestMode=false,走真实微信授权分支(不返回 mock openid 前缀)
+        WechatService service = newService(false, "dev");
+        assertFalse(service.isTestMode(), "测试模式关闭时不应返回模拟数据");
+    }
+}

+ 82 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG08EnvAdaptiveContractTest.java

@@ -0,0 +1,82 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.testutil.FrontendSourceLocator;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-08 环境自适应切换 契约级单测(能力键 env.adaptive.switch)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-8、tests/test-cases/guest.md TC-G-08/TC-G-08-E):
+ * - 正常流 (TC-G-08):启动时经 uni.getAccountInfoSync().miniProgram.envVersion 判定环境;
+ *   develop/trial/release 三环境映射到对应 API 地址(当前实现统一 https://cfc.etotem.com.cn)。
+ * - 异常流 (TC-G-08-E):环境识别失败(getAccountInfoSync 异常/空)→ try/catch 回退默认地址,功能可用。
+ * - 权限流 (TC-G-08-P):api.js 统一从 config.js 取 API_BASE_URL(单一地址源,禁止页面内联硬编码导致错连)。
+ *
+ * 溯源:SC-G-08 · tests/user-scenarios/01-guest.md 场景 G-8 · tests/test-cases/guest.md TC-G-08/TC-G-08-E
+ *
+ * 前端源契约:读取 cfc-frontend/config.js 与 utils/api.js 源码做静态断言(不依赖运行时/微信环境)。
+ */
+public class ScG08EnvAdaptiveContractTest {
+
+    private String config() {
+        return FrontendSourceLocator.readFrontendSource("config.js");
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-08:环境判定 + 三环境映射 + 默认地址
+    // ====================================================================
+
+    @Test
+    public void normal_envDetection_usesGetAccountInfoSyncEnvVersion() {
+        String c = config();
+        assertTrue(c.contains("uni.getAccountInfoSync()"), "环境判定必须调用 uni.getAccountInfoSync()");
+        assertTrue(c.contains("envVersion"), "必须读取 miniProgram.envVersion 判定当前环境");
+    }
+
+    @Test
+    public void normal_threeEnv_mappedToConfiguredApiBase() {
+        String c = config();
+        assertTrue(c.contains("case 'develop'"), "应配置 develop 环境分支");
+        assertTrue(c.contains("case 'trial'"), "应配置 trial 环境分支");
+        assertTrue(c.contains("case 'release'"), "应配置 release 环境分支");
+        assertTrue(c.contains("https://cfc.etotem.com.cn"), "应配置线上统一 API 地址(当前三环境同址)");
+    }
+
+    @Test
+    public void normal_defaultBaseFixed_andExported() {
+        String c = config();
+        assertTrue(c.contains("API_BASE_URL"), "config.js 必须定义 API_BASE_URL");
+        assertTrue(c.contains("http://cfc.iwintrue.com"), "应内置默认(兜底)地址 http://cfc.iwintrue.com");
+        assertTrue(c.contains("export default"), "config.js 必须默认导出配置对象");
+        assertTrue(c.contains("api(path)"), "应导出 api(path) 拼接方法供请求层使用");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-08-E:环境识别失败 → 回退默认地址,不崩溃
+    // ====================================================================
+
+    @Test
+    public void exception_envDetectionFailure_fallsBackToDefault() {
+        String c = config();
+        assertTrue(c.contains("try {"), "环境探测必须包裹在 try 内");
+        assertTrue(c.contains("catch"), "环境探测失败必须被 catch 捕获(弱网/非微信环境)");
+        assertTrue(c.contains("默认地址"), "catch 分支必须回退默认地址,避免白屏/错连");
+        assertTrue(c.contains("API_BASE_URL = 'http://cfc.iwintrue.com'"),
+                "默认地址必须存在(回退后仍可请求)");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-08-P:统一 API 地址源(防页面内联错连环境)
+    // ====================================================================
+
+    @Test
+    public void permission_apiRequests_useUnifiedConfigBase() {
+        String api = FrontendSourceLocator.readFrontendSource("utils/api.js");
+        assertTrue(api.contains("import config from '@/config.js'"),
+                "api.js 必须统一引用 config.js 作为地址源");
+        assertTrue(api.contains("config.API_BASE_URL"),
+                "请求 base 必须来自 config 统一配置,禁止页面内联硬编码 API 地址(防跨环境错连)");
+    }
+}

+ 131 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG09LogoutContractTest.java

@@ -0,0 +1,131 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.testutil.FrontendSourceLocator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-09 退出登录 契约级单测(能力键 auth.guest.logout)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-9、tests/test-cases/guest.md TC-G-09/TC-G-09-E/TC-G-09-P):
+ * - 正常流 (TC-G-09):个人中心「退出登录」入口 → 确认后提交 store logout mutation → 清除登录态并回首页。
+ * - 异常流 (TC-G-09-E):退出/会话过期后本地敏感缓存(token/userId/openid/userInfo/currentChildId 等)清除;
+ *   退出后(无 token)访问受保护接口 → 统一 401。
+ * - 权限流 (TC-G-09-P):401 分流统一走 _clearAuthAndRedirect 清登录态并跳转登录页;受保护接口 401 响应
+ *   不泄露内部异常/堆栈。
+ *
+ * 溯源:SC-G-09 · tests/user-scenarios/01-guest.md 场景 G-9 · tests/test-cases/guest.md TC-G-09/TC-G-09-E/TC-G-09-P
+ *
+ * 前端源契约(FrontendSourceLocator 读 cfc-frontend 源码做静态断言)+ JwtInterceptor 契约(Mockito,不依赖 DB/容器)。
+ */
+public class ScG09LogoutContractTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-09:个人中心退出登录 → 清登录态 + 回首页
+    // ====================================================================
+
+    @Test
+    public void normal_profileLogoutEntry_clearsAuthAndRedirects() {
+        String profileMenu = FrontendSourceLocator.readFrontendSource("pages/profile/components/ProfileMenu.vue");
+        assertTrue(profileMenu.contains("退出登录"), "个人中心必须提供退出登录入口");
+        assertTrue(profileMenu.contains("this.$store.commit('logout')"), "退出确认后必须提交 logout mutation");
+        assertTrue(profileMenu.contains("uni.reLaunch({ url: '/pages/index-home/index' })"),
+                "退出后应回到首页/引导页");
+    }
+
+    @Test
+    public void normal_storeLogoutMutation_clearsLoginKeys() {
+        String store = FrontendSourceLocator.readFrontendSource("store/index.js");
+        assertTrue(store.contains("logout(state)"), "store 必须定义 logout mutation");
+        for (String key : new String[]{"token", "userId", "role", "openid", "userInfo", "currentChildId"}) {
+            assertTrue(store.contains("uni.removeStorageSync('" + key + "')"),
+                    "logout mutation 必须清除本地登录态: " + key);
+        }
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-09-E:敏感缓存清除;退出后受保护接口 401
+    // ====================================================================
+
+    @Test
+    public void exception_logout_clearsSensitiveLocalCache() {
+        String api = FrontendSourceLocator.readFrontendSource("utils/api.js");
+        assertTrue(api.contains("_clearAuthAndRedirect"), "401/退出必须走统一清理登录态逻辑");
+        for (String key : new String[]{"token", "userId", "currentRole", "role", "nickname", "userName", "currentChildId"}) {
+            assertTrue(api.contains("removeStorageSync('" + key + "')"),
+                    "会话清理必须清除本地敏感缓存: " + key);
+        }
+    }
+
+    @Test
+    public void exception_afterLogout_noToken_protectedIs401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "退出后无 token 访问受保护接口必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), "退出后应返回 401 需重新登录");
+        assertTrue(response.getContentAsString().contains("\"code\":401"), "应返回统一 code=401");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-09-P:401 分流统一清理;异常不泄露
+    // ====================================================================
+
+    @Test
+    public void permission_401Handling_clearsAndRedirectsToLogin() {
+        String api = FrontendSourceLocator.readFrontendSource("utils/api.js");
+        assertTrue(api.contains("statusCode === 401 || res.data.code === 401"),
+                "请求层应统一识别 HTTP 401 与业务 code=401");
+        assertTrue(api.contains("uni.removeStorageSync('token')"), "401 处理必须先清 token");
+        assertTrue(api.contains("uni.reLaunch({ url: '/pages/login/login' })"),
+                "非启动窗口的 401 应跳转登录页");
+    }
+
+    @Test
+    public void permission_noToken_protected_unified401_noStackLeak() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/tasks/today");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "受保护接口无 token 必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), "应含统一 code=401,实际: " + body);
+        assertFalse(body.contains("Exception"), "不得泄露内部异常: " + body);
+        assertFalse(body.contains("at com.etotem"), "不得泄露调用堆栈: " + body);
+    }
+}

+ 174 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG10RegisterGuideContractTest.java

@@ -0,0 +1,174 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.controller.auth.AuthController;
+import com.etotem.cfc.dto.CheckPhoneDTO;
+import com.etotem.cfc.dto.DirectRegisterDTO;
+import com.etotem.cfc.dto.LoginResultDTO;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.SsoService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+/**
+ * SC-G-10 账号不存在引导注册 契约级单测(能力键 auth.guest.registerGuide)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-10、tests/test-cases/guest.md TC-G-10/TC-G-10-E/TC-G-10-P):
+ * - 正常流 (TC-G-10):check-phone 返回未注册(false)→ 引导注册;direct-register 未注册 → 建档成功返回 token。
+ * - 异常流 (TC-G-10-E):已注册手机号 check-phone=true、direct-register 拒绝「已注册请用验证码登录」(不重复建档);
+ *   手机号格式非法 → 明确提示,不建档。
+ * - 权限流 (TC-G-10-P):check-phone / direct-register 端点在公开白名单,游客无 token 可触达(不误拦 401)。
+ *
+ * 溯源:SC-G-10 · tests/user-scenarios/01-guest.md 场景 G-10 · tests/test-cases/guest.md TC-G-10/TC-G-10-E/TC-G-10-P
+ *
+ * 纯单元测试:Mockito 直接调用 handler + MockHttpServletRequest/Response,不依赖数据库/真实微信/Spring 容器。
+ */
+public class ScG10RegisterGuideContractTest {
+
+    @Mock
+    private UserService userService;
+    @Mock
+    private VerificationCodeService verificationCodeService;
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private SsoService ssoService;
+    @InjectMocks
+    private AuthController authController;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-10:未注册 → 引导注册;direct-register 建档成功
+    // ====================================================================
+
+    @Test
+    public void normal_checkPhone_unregistered_returnsFalse_guideRegister() {
+        CheckPhoneDTO dto = new CheckPhoneDTO();
+        dto.setPhone("13800000001");
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(false);
+
+        Result<Boolean> result = authController.checkPhone(dto);
+
+        assertEquals(200, result.getCode(), "check-phone 成功应返回 code=200");
+        assertFalse(result.getData(), "未注册手机号应返回 false,引导进入注册流程");
+    }
+
+    @Test
+    public void normal_directRegister_unregistered_createsAccount() {
+        DirectRegisterDTO dto = new DirectRegisterDTO();
+        dto.setPhone("13800000001");
+        dto.setNickname("新用户");
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(false);
+
+        LoginResultDTO login = new LoginResultDTO();
+        login.setToken("reg-jwt");
+        login.setUserId(55L);
+        login.setRole("parent");
+        login.setIsNewUser(true);
+        when(userService.directRegister(dto)).thenReturn(login);
+
+        Result<LoginResultDTO> result = authController.directRegister(dto);
+
+        assertEquals(200, result.getCode(), "未注册建档成功应返回 code=200");
+        assertEquals("reg-jwt", result.getData().getToken(), "应下发登录 token");
+        assertTrue(result.getData().getIsNewUser(), "应标记为新用户");
+        verify(userService, times(1)).directRegister(dto);
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-10-E:已注册不重复建档;格式非法明确提示
+    // ====================================================================
+
+    @Test
+    public void exception_checkPhone_registered_returnsTrue() {
+        CheckPhoneDTO dto = new CheckPhoneDTO();
+        dto.setPhone("13800000001");
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(true);
+
+        Result<Boolean> result = authController.checkPhone(dto);
+
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData(), "已注册手机号应返回 true(引导直接登录)");
+    }
+
+    @Test
+    public void exception_directRegister_alreadyRegistered_rejectedNoRebuild() {
+        DirectRegisterDTO dto = new DirectRegisterDTO();
+        dto.setPhone("13800000001");
+        when(userService.isPhoneRegistered("13800000001")).thenReturn(true);
+
+        Result<LoginResultDTO> result = authController.directRegister(dto);
+
+        assertEquals(500, result.getCode(), "已注册应拒绝建档");
+        assertTrue(result.getMessage().contains("已注册"), "应提示已注册请用验证码登录,实际: " + result.getMessage());
+        assertNull(result.getData(), "已注册不产生新会话");
+        verify(userService, never()).directRegister(any());
+    }
+
+    @Test
+    public void exception_directRegister_invalidPhoneFormat_returnsError() {
+        DirectRegisterDTO dto = new DirectRegisterDTO();
+        dto.setPhone("123");
+
+        Result<LoginResultDTO> result = authController.directRegister(dto);
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("格式不正确"), "手机号格式非法应提示,实际: " + result.getMessage());
+        verify(userService, never()).directRegister(any());
+    }
+
+    @Test
+    public void exception_checkPhone_emptyPhone_returnsError() {
+        CheckPhoneDTO dto = new CheckPhoneDTO();
+        dto.setPhone("");
+
+        Result<Boolean> result = authController.checkPhone(dto);
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("不能为空"), "空手机号应提示,实际: " + result.getMessage());
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-10-P:注册引导端点公开(游客无 token 可触达)
+    // ====================================================================
+
+    @Test
+    public void permission_registerGuideEndpoints_publicNotBlocked() throws Exception {
+        String[] publicPaths = {"/api/auth/check-phone", "/api/auth/direct-register"};
+        for (String path : publicPaths) {
+            MockHttpServletRequest request = new MockHttpServletRequest();
+            request.setMethod("POST");
+            request.setRequestURI(path);
+            MockHttpServletResponse response = new MockHttpServletResponse();
+
+            boolean allowed = jwtInterceptor.preHandle(request, response, null);
+
+            assertTrue(allowed, "注册引导端点应为公开路径,游客可触达: " + path);
+            assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "注册引导端点不应误拦 401: " + path);
+        }
+    }
+}

+ 118 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG11AgreementContractTest.java

@@ -0,0 +1,118 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.testutil.FrontendSourceLocator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-11 隐私政策 / 用户协议查看 契约级单测(能力键 policy.agreement.view)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-11、tests/test-cases/guest.md TC-G-11/TC-G-11-E/TC-G-11-P):
+ * - 正常流 (TC-G-11):用户协议页与隐私政策页存在,可查看全文;协议含平台名称、运营主体与微信授权注册说明
+ *   (合规告知)。
+ * - 异常流 (TC-G-11-E):协议内容为静态内置文本、不依赖网络请求加载(不因弱网白屏);未同意/未登录不可
+ *   绕过鉴权进入核心流程。
+ * - 权限流 (TC-G-11-P):未登录(未同意前)直调受保护业务接口(家庭成员/五维能量)→ 统一 401,不泄露内部
+ *   错误与结构。
+ *
+ * 溯源:SC-G-11 · tests/user-scenarios/01-guest.md 场景 G-11 · tests/test-cases/guest.md TC-G-11/TC-G-11-E/TC-G-11-P
+ *
+ * 前端源契约(FrontendSourceLocator 读 cfc-frontend 源码做静态断言)+ JwtInterceptor 契约(Mockito,不依赖 DB/容器)。
+ */
+public class ScG11AgreementContractTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-11:协议/隐私政策页存在且可查看全文
+    // ====================================================================
+
+    @Test
+    public void normal_agreementAndPrivacyPagesExist() {
+        assertTrue(FrontendSourceLocator.frontendSourceExists("pages/policy/agreement.vue"),
+                "用户协议页 pages/policy/agreement.vue 必须存在");
+        assertTrue(FrontendSourceLocator.frontendSourceExists("pages/policy/privacy.vue"),
+                "隐私政策页 pages/policy/privacy.vue 必须存在");
+    }
+
+    @Test
+    public void normal_agreementContent_complianceInfo() {
+        String a = FrontendSourceLocator.readFrontendSource("pages/policy/agreement.vue");
+        assertTrue(a.contains("用户协议"), "协议页应展示「用户协议」标题");
+        assertTrue(a.contains("浠艾福"), "协议应含平台名称(浠艾福)");
+        assertTrue(a.contains("亿图腾"), "协议应含运营主体(亿图腾)");
+        assertTrue(a.contains("微信"), "协议应说明微信授权登录注册方式");
+        assertTrue(a.contains("同意"), "协议应包含同意/确认条款");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-11-E:静态内置内容(不依赖网络,防白屏)
+    // ====================================================================
+
+    @Test
+    public void exception_agreementContent_isStaticNoNetworkDependency() {
+        String a = FrontendSourceLocator.readFrontendSource("pages/policy/agreement.vue");
+        assertTrue(a.contains("policy-section"), "协议内容应内联为静态条款块");
+        assertFalse(a.contains("uni.request"), "协议内容不应依赖 uni.request 远程加载(内联静态,防白屏)");
+        assertFalse(a.contains("wx.request"), "协议内容不应依赖 wx.request 远程加载");
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-11-P:未同意/未登录不得绕过鉴权进入核心流程
+    // ====================================================================
+
+    @Test
+    public void permission_unapprovedGuest_protectedApi_401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "未登录直调家庭成员接口必须被拦截");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), "应返回 401");
+        assertTrue(response.getContentAsString().contains("\"code\":401"), "应返回统一 code=401");
+    }
+
+    @Test
+    public void permission_guest_protectedApi_noStackLeak() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/energy/overview");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result);
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), "应含统一 code=401,实际: " + body);
+        assertFalse(body.contains("Exception"), "不得泄露内部异常: " + body);
+        assertFalse(body.contains("at com.etotem"), "不得泄露调用堆栈: " + body);
+    }
+}

+ 126 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ScG12H5FallbackContractTest.java

@@ -0,0 +1,126 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.testutil.FrontendSourceLocator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * SC-G-12 非微信环境 H5 兜底 契约级单测(能力键 env.h5Fallback)
+ * ================================================================
+ * 覆盖(对应 tests/user-scenarios/01-guest.md 场景 G-12、tests/test-cases/guest.md TC-G-12/TC-G-12-E/TC-G-12-P):
+ * - 正常流 (TC-G-12):非微信环境(H5/dev)→ 环境探测走 catch 回退默认地址(http://cfc.iwintrue.com),
+ *   API_BASE_URL 仍导出供请求层使用,功能可用。
+ * - 异常流 (TC-G-12-E):环境探测(uni.getAccountInfoSync)包裹在 try 内,异常被 catch 捕获不崩溃;
+ *   H5 降级仍可匿名浏览公开内容(商品/文章),不因无微信 SDK 误拦。
+ * - 权限流 (TC-G-12-P):H5 兜底不诱导下载/安装;受保护业务接口仍统一 401(不因降级而放开鉴权)。
+ *
+ * 溯源:SC-G-12 · tests/user-scenarios/01-guest.md 场景 G-12 · tests/test-cases/guest.md TC-G-12/TC-G-12-E/TC-G-12-P
+ *
+ * 前端源契约(FrontendSourceLocator 读 cfc-frontend/config.js 源码做静态断言)+ JwtInterceptor 契约(Mockito)。
+ */
+public class ScG12H5FallbackContractTest {
+
+    @Mock
+    private JwtConfig jwtConfig;
+    @Mock
+    private UserMapper userMapper;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @InjectMocks
+    private JwtInterceptor jwtInterceptor;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ====================================================================
+    // 正常流 TC-G-12:非微信环境回退默认地址,仍可请求
+    // ====================================================================
+
+    @Test
+    public void normal_nonWechatEnv_fallsBackToDefaultBase() {
+        String c = FrontendSourceLocator.readFrontendSource("config.js");
+        assertTrue(c.contains("catch"), "非微信/H5 环境应走 catch 回退分支");
+        assertTrue(c.contains("默认地址"), "catch 应回退默认地址(不白屏)");
+        assertTrue(c.contains("http://cfc.iwintrue.com"), "H5 默认地址应为 http://cfc.iwintrue.com");
+    }
+
+    @Test
+    public void normal_defaultBase_exportedForApiUse() {
+        String c = FrontendSourceLocator.readFrontendSource("config.js");
+        assertTrue(c.contains("API_BASE_URL"), "应定义并导出 API_BASE_URL");
+        assertTrue(c.contains("export default"), "应默认导出配置对象");
+        assertTrue(c.contains("api(path)"), "应导出 api(path) 供请求层使用");
+    }
+
+    // ====================================================================
+    // 异常流 TC-G-12-E:环境探测异常不崩溃;H5 降级仍可浏览公开内容
+    // ====================================================================
+
+    @Test
+    public void exception_envProbe_wrappedInTryCatch() {
+        String c = FrontendSourceLocator.readFrontendSource("config.js");
+        int tryIdx = c.indexOf("try {");
+        assertTrue(tryIdx >= 0, "config.js 必须包含 try 块");
+        // 注释里也可能出现 uni.getAccountInfoSync()(JSDoc 说明),须锚定 try 之后查找实际调用
+        int probeIdx = c.indexOf("uni.getAccountInfoSync()", tryIdx);
+        assertTrue(probeIdx > tryIdx, "环境探测 uni.getAccountInfoSync() 必须在 try 内(异常不崩溃)");
+        assertTrue(c.contains("catch"), "环境探测失败必须被 catch 捕获");
+    }
+
+    @Test
+    public void exception_h5Fallback_publicBrowseStillAllowed() throws Exception {
+        for (String path : new String[]{"/api/product/list", "/api/articles/list"}) {
+            MockHttpServletRequest request = new MockHttpServletRequest();
+            request.setMethod("POST");
+            request.setRequestURI(path);
+            MockHttpServletResponse response = new MockHttpServletResponse();
+
+            boolean result = jwtInterceptor.preHandle(request, response, null);
+
+            assertTrue(result, "H5 降级仍应可匿名浏览公开内容: " + path);
+            assertEquals(HttpServletResponse.SC_OK, response.getStatus(), "公开内容不应被误拦: " + path);
+        }
+    }
+
+    // ====================================================================
+    // 权限流 TC-G-12-P:不诱导下载/安装;受保护接口仍 401
+    // ====================================================================
+
+    @Test
+    public void permission_h5Fallback_noInstallInducement() {
+        String c = FrontendSourceLocator.readFrontendSource("config.js");
+        assertFalse(c.contains("download"), "H5 兜底不应诱导下载/安装");
+        assertFalse(c.contains("install"), "H5 兜底不应诱导安装");
+    }
+
+    @Test
+    public void permission_h5Fallback_protectedApi_401() throws Exception {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setMethod("POST");
+        request.setRequestURI("/api/family/member/list");
+        MockHttpServletResponse response = new MockHttpServletResponse();
+
+        boolean result = jwtInterceptor.preHandle(request, response, null);
+
+        assertFalse(result, "H5 降级不得放开受保护接口鉴权");
+        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(), "应返回 401");
+        String body = response.getContentAsString();
+        assertTrue(body.contains("\"code\":401"), "应返回统一 code=401,实际: " + body);
+        assertFalse(body.contains("Exception"), "不得泄露内部异常: " + body);
+    }
+}

+ 229 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/SurveyHealthReviewContractTest.java

@@ -0,0 +1,229 @@
+package com.etotem.cfc.controller;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.SurveyRecord;
+import com.etotem.cfc.entity.SurveyTemplate;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.SurveyRecordMapper;
+import com.etotem.cfc.mapper.SurveyTemplateMapper;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.SurveyService;
+import com.etotem.cfc.service.impl.SurveyServiceImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * HL-01 健康阅卷契约测试(source 参数 + health-review/last 接口)。
+ *
+ * <p>验收:
+ * <ul>
+ *   <li>source=health_review 提交时不校验模板/周期,可缺省 templateId,source 落库为 health_review;</li>
+ *   <li>source 缺省/periodic 提交时 templateId 必填(缺省拒绝);</li>
+ *   <li>source=health_review 且带 templateId 时按模板查询(向后兼容);</li>
+ *   <li>getLastHealthReview 按 memberId+source=health_review 取最近一条,无记录返回 null;</li>
+ *   <li>Controller /api/survey/health-review/last 端点把 params.memberId 透传给 service。</li>
+ * </ul>
+ *
+ * <p>纯 Mock 单元测试,不启动 Spring 上下文。
+ */
+class SurveyHealthReviewContractTest {
+
+    private SurveyServiceImpl service;
+    private SurveyController controller;
+    private SurveyTemplateMapper surveyTemplateMapper;
+    private SurveyRecordMapper surveyRecordMapper;
+    private FamilyMemberMapper familyMemberMapper;
+
+    @BeforeEach
+    void setUp() {
+        service = new SurveyServiceImpl();
+        surveyTemplateMapper = mock(SurveyTemplateMapper.class);
+        surveyRecordMapper = mock(SurveyRecordMapper.class);
+        familyMemberMapper = mock(FamilyMemberMapper.class);
+        ReflectionTestUtils.setField(service, "surveyTemplateMapper", surveyTemplateMapper);
+        ReflectionTestUtils.setField(service, "surveyRecordMapper", surveyRecordMapper);
+        ReflectionTestUtils.setField(service, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(service, "aiGateway", mock(AiGateway.class));
+
+        controller = new SurveyController();
+        ReflectionTestUtils.setField(controller, "surveyService", service);
+    }
+
+    private FamilyMember member(Long id, Long familyId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(id);
+        m.setFamilyId(familyId);
+        return m;
+    }
+
+    private SurveyTemplate template(Long id, String cycleType) {
+        SurveyTemplate t = new SurveyTemplate();
+        t.setId(id);
+        t.setCycleType(cycleType);
+        t.setEnabled(1);
+        return t;
+    }
+
+    /** 捕获实际插入的 record(Mockito 传入的实参),insert 回填 id 后 selectById 返回同一实例 */
+    private SurveyRecord stubInsertAndCapture() {
+        final SurveyRecord[] holder = new SurveyRecord[1];
+        doAnswer(inv -> {
+            SurveyRecord r = inv.getArgument(0);
+            r.setId(999L);
+            holder[0] = r;
+            return 1;
+        }).when(surveyRecordMapper).insert(any(SurveyRecord.class));
+        when(surveyRecordMapper.selectById(999L)).thenAnswer(inv -> holder[0]);
+        return null; // 调用方通过 captureLastInserted() 取实际对象
+    }
+
+    /** 返回最近一次 insert 捕获到的实际 record 实例 */
+    private SurveyRecord captureLastInserted() {
+        org.mockito.ArgumentCaptor<SurveyRecord> cap = org.mockito.ArgumentCaptor.forClass(SurveyRecord.class);
+        verify(surveyRecordMapper, atLeastOnce()).insert(cap.capture());
+        return cap.getValue();
+    }
+
+    @Test
+    void submitHealthReview_withoutTemplate_ok() {
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+
+        // source=health_review 且 templateId 缺省 → 不校验模板,直接落库
+        SurveyRecord result = service.submitSurvey(1L, 7L, null, "{\"q1\":\"a\"}",
+                null, null, null, "health_review");
+
+        assertNotNull(result);
+        verify(surveyTemplateMapper, never()).selectById(any());
+        // 记录应落 source=health_review
+        SurveyRecord inserted = captureLastInserted();
+        assertEquals("health_review", inserted.getSource());
+        // 不应有模板周期计算
+        assertNull(inserted.getPeriodStart());
+        assertNull(inserted.getPeriodEnd());
+    }
+
+    @Test
+    void submitHealthReview_withTemplate_stillQueriesTemplate() {
+        // health_review 但显式传 templateId:按旧逻辑查模板(向后兼容)
+        when(surveyTemplateMapper.selectById(5L)).thenReturn(template(5L, "weekly"));
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+
+        SurveyRecord result = service.submitSurvey(1L, 7L, 5L, "{}",
+                null, null, null, "health_review");
+
+        assertNotNull(result);
+        verify(surveyTemplateMapper).selectById(5L);
+        SurveyRecord inserted = captureLastInserted();
+        assertEquals("health_review", inserted.getSource());
+        // 有模板则按周期计算
+        assertNotNull(inserted.getPeriodStart());
+        assertNotNull(inserted.getPeriodEnd());
+    }
+
+    @Test
+    void submitPeriodic_withoutTemplate_rejected() {
+        // source 缺省(periodic)且 templateId 缺省 → 拒绝
+        assertThrows(IllegalArgumentException.class,
+                () -> service.submitSurvey(1L, 7L, null, "{}", null, null, null, null),
+                "periodic 缺模板应拒绝");
+    }
+
+    @Test
+    void submitPeriodic_withTemplate_ok() {
+        when(surveyTemplateMapper.selectById(5L)).thenReturn(template(5L, "weekly"));
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+
+        SurveyRecord result = service.submitSurvey(1L, 7L, 5L, "{}",
+                null, null, null, "periodic");
+
+        assertNotNull(result);
+        SurveyRecord inserted = captureLastInserted();
+        assertEquals("periodic", inserted.getSource());
+        assertNotNull(inserted.getPeriodStart());
+        assertNotNull(inserted.getPeriodEnd());
+    }
+
+    @Test
+    void getLastHealthReview_returnsLatestHealthReview() {
+        SurveyRecord latest = new SurveyRecord();
+        latest.setId(11L);
+        latest.setMemberId(7L);
+        latest.setSource("health_review");
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        when(surveyRecordMapper.selectList(any(LambdaQueryWrapper.class)))
+                .thenReturn(Collections.singletonList(latest));
+
+        SurveyRecord result = service.getLastHealthReview(1L, 7L);
+
+        assertNotNull(result);
+        assertEquals(11L, result.getId());
+        assertEquals("health_review", result.getSource());
+    }
+
+    @Test
+    void getLastHealthReview_noRecord_returnsNull() {
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        when(surveyRecordMapper.selectList(any(LambdaQueryWrapper.class)))
+                .thenReturn(new ArrayList<>());
+
+        SurveyRecord result = service.getLastHealthReview(1L, 7L);
+
+        assertNull(result);
+    }
+
+    @Test
+    void getLastHealthReview_noMember_returnsNull() {
+        // memberId 缺省且 userId 反查不到 → resolveMemberId 返回 null → null
+        when(familyMemberMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
+
+        SurveyRecord result = service.getLastHealthReview(1L, null);
+
+        assertNull(result);
+    }
+
+    @Test
+    void controllerLastHealthReview_passesMemberId() {
+        SurveyService spyService = spy(service);
+        ReflectionTestUtils.setField(controller, "surveyService", spyService);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", 7L);
+
+        Result<SurveyRecord> result = controller.lastHealthReview(params, 1L, null);
+
+        assertNotNull(result);
+        assertEquals(200, result.getCode());
+        verify(spyService).getLastHealthReview(1L, 7L);
+    }
+
+    @Test
+    void controllerLastHealthReview_defaultsToCurrentMemberId() {
+        SurveyService spyService = spy(service);
+        ReflectionTestUtils.setField(controller, "surveyService", spyService);
+
+        Map<String, Object> params = new HashMap<>();
+
+        Result<SurveyRecord> result = controller.lastHealthReview(params, 1L, 42L);
+
+        assertNotNull(result);
+        assertEquals(200, result.getCode());
+        verify(spyService).getLastHealthReview(1L, 42L);
+    }
+}

+ 182 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/TeamInvitationCreateContractTest.java

@@ -0,0 +1,182 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.DistributionService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-40 / 能力键 {@code team.invitation.create},单元 team)—— RED 阶段契约级单测。
+ *
+ * <p>契约来源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * <ul>
+ *   <li>§5.1/5.2:团队负责人/成员生成邀请 → 返回 {@code inviteCode + 小程序码(wxacode, 落地页)},复用
+ *       {@code distribution_relations.invite_code};</li>
+ *   <li>§7.7:团队邀请不新建表,复用 {@code distribution_relations.invite_code} + 现有分销服务
+ *       {@code DistributionService.generateInviteCode};</li>
+ *   <li>§11-#11(已拍板):团队邀请落地页为独立页(团队场景信息不同),复用 {@code POST /api/team-invite/generate}
+ *       约定的生成入口语义;</li>
+ *   <li>§12-T1:场景 A 注册链路补推荐人绑定钩子 + 场景 B 幂等入团接口 + 落地页/小程序码(参照家庭邀请)。</li>
+ * </ul>
+ *
+ * <p>被测:{@link DistributionInviteController#generate}({@code POST /api/distribution/invite/generate},
+ * 当前唯一的「创建团队邀请」入口;设计落地时其响应须满足 §5.2 契约)。
+ *
+ * <p>AC 断言(RED 期:实现未落地 / 边界未覆盖):
+ * <ol>
+ *   <li>正常流:code=200 且 {@code data} 为对象,必须包含 {@code inviteCode} / {@code wxacode}(小程序码,
+ *       指向独立团队落地页)/ {@code systemId} / {@code teamName} / {@code inviterId};
+ *       —— 现实现只返回 {@code Result&lt;String&gt;}(裸邀请码),无 wxacode/团队预览 → <b>红</b>。</li>
+ *   <li>边界流:systemId 缺失 → "systemId不能为空";体系不存在 / 体系未启用 / 用户不在该体系 → 明确错误透传。</li>
+ *   <li>权限流:未登录(无 userId 绑定属性)→ 400;非团队成员不可为他人团队生成邀请。</li>
+ * </ol>
+ *
+ * <p>MockMvc standalone + Mockito:全 service 打桩,不依赖数据库 / 真实微信 / 外部服务,不启 Spring 上下文。
+ */
+public class TeamInvitationCreateContractTest {
+
+    private static final String URL = "/api/distribution/invite/generate";
+
+    @Mock
+    private DistributionService distributionService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        DistributionInviteController controller = new DistributionInviteController();
+        ReflectionTestUtils.setField(controller, "distributionService", distributionService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常-1:生成团队邀请成功,data 必须为邀请对象(含 inviteCode/systemId/teamName/inviterId)——当前只返回裸字符串 → RED")
+    public void generate_success_dataMustBeInvitationObject() throws Exception {
+        String code = "ABC23456";
+        when(distributionService.generateInviteCode(eq(10L), eq(7L))).thenReturn(Result.success(code));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":10}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isMap())
+                .andExpect(jsonPath("$.data.inviteCode").value(code))
+                .andExpect(jsonPath("$.data.systemId").value(10))
+                .andExpect(jsonPath("$.data.teamName").isString())
+                .andExpect(jsonPath("$.data.inviterId").value(7));
+
+        verify(distributionService).generateInviteCode(eq(10L), eq(7L));
+    }
+
+    @Test
+    @DisplayName("正常-2:生成团队邀请必须返回小程序码(wxacode,独立团队落地页)——当前无 wxacode → RED")
+    public void generate_success_mustReturnWxacodeForLandingPage() throws Exception {
+        when(distributionService.generateInviteCode(eq(10L), eq(7L)))
+                .thenReturn(Result.success("ABC23456"));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":10}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.wxacode").isNotEmpty());
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界-1:systemId 缺失 → 明确错误且不触达 service")
+    public void generate_missingSystemId_returnsError() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("systemId不能为空"));
+
+        verify(distributionService, never()).generateInviteCode(anyLong(), anyLong());
+    }
+
+    @Test
+    @DisplayName("边界-2:销售体系不存在 → 错误透传")
+    public void generate_systemNotFound_returnsError() throws Exception {
+        when(distributionService.generateInviteCode(eq(999L), eq(7L)))
+                .thenReturn(Result.error("销售体系不存在"));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":999}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("销售体系不存在"));
+    }
+
+    @Test
+    @DisplayName("边界-3:销售体系未启用 → 错误透传")
+    public void generate_systemDisabled_returnsError() throws Exception {
+        when(distributionService.generateInviteCode(eq(10L), eq(7L)))
+                .thenReturn(Result.error("销售体系未启用"));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":10}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("销售体系未启用"));
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限-1:用户不在该销售体系中 → 拒绝生成(团队成员专属权限)")
+    public void generate_notTeamMember_returnsError() throws Exception {
+        when(distributionService.generateInviteCode(eq(10L), eq(7L)))
+                .thenReturn(Result.error("用户不在该销售体系中"));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":10}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("用户不在该销售体系中"));
+    }
+
+    @Test
+    @DisplayName("权限-2:未登录(无 userId 绑定属性)→ 400 且不触达 service")
+    public void generate_anonymous_returns400() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"systemId\":10}"))
+                .andExpect(status().isBadRequest());
+
+        verify(distributionService, never()).generateInviteCode(anyLong(), anyLong());
+    }
+}

+ 376 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleAuditContractTest.java

@@ -0,0 +1,376 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.service.ArticleService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:管理端文章审核动作(能力键 {@code admin.article.audit},
+ * {@code POST /api/admin/articles/audit})。
+ *
+ * <p><b>溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code docs/tdd/SRS.md}「三、未覆盖控制器」——
+ *       {@code AdminArticleController}(22 方法,0 覆盖),{@code audit} 位于未覆盖方法清单</li>
+ *   <li>设计:{@code AdminArticleController#audit}({@code @PostMapping("/audit")},类级
+ *       {@code /api/admin/articles})+ {@code ArticleService#auditArticle(articleId, auditStatus,
+ *       auditReason, auditorId)} 审核状态机(pending→approved→published / rejected)</li>
+ *   <li>契约:{@code docs/superpowers/api/API_REFERENCE.md} §4.60.4(SC-A-03 文章发布-审核流,
+ *       含 {@code /audit})+ §4.60.13(SC-A-13 内容安全审核:
+ *       {@code POST /api/admin/articles/audit} 文章审核动作);权限流按契约核对结论
+ *       (admin-ops-contract §5)TR-13:「补 admin 端点 MockMvc 契约 JUnit +
+ *       <b>非 admin token → 403 权限流</b>」</li>
+ * </ul>
+ *
+ * <p><b>实现现状(origin/cfclub @ 0b7ba4ecb 实测)</b></p>
+ * <ul>
+ *   <li>正常流/边界流已实现:audit 解析 {@code id / auditStatus / auditReason} → 参数门禁
+ *       (auditStatus 仅 {@code approved / rejected},拒审必填原因)→ 委托
+ *       {@code articleService.auditArticle} → {@code Result.success("审核完成")};
+ *       service 层状态机(文章不存在 / 非 pending 拒绝;approved→published、rejected→rejected)
+ *       亦已落地。</li>
+ *   <li><b>权限流未落地(本测试的红)</b>:{@link JwtInterceptor#LOGIN_REQUIRED_PATHS} 未收口
+ *       {@code /api/admin/} 前缀(仅 {@code /api/admin-auth/*} 登录端点走 PUBLIC_PATHS),匿名
+ *       (userId=-1, role=anonymous)被放行至 controller;{@code audit} 亦无
+ *       {@code @RequestAttribute("role")} 角色守卫(参照同控制器 {@code /move} 的「无权限」
+ *       守卫惯例)。对应缺陷台账 <b>B-142-1</b>(P1 安全:{@code /api/admin/**} 整族鉴权门缺失,
+ *       R152~R154 延续未修;S-cfc-143 admin.article.create 同批已锁定该缺口,
+ *       {@code AdminArticleCreateContractTest} 权限流 3 红)。</li>
+ * </ul>
+ *
+ * <p><b>三流划分</b></p>
+ * <ul>
+ *   <li>正常流(已实现 → 绿锁定契约):approved/rejected 原样委托 service 并返回「审核完成」;</li>
+ *   <li>边界流(已实现 → 绿锁定契约):非法审核状态 / 驳回缺原因 → 参数门禁错误,不触达 service;
+ *       service RuntimeException 透传 error message;</li>
+ *   <li>权限流(契约缺口 → <b>预期红</b>):匿名请求应 401;{@code LOGIN_REQUIRED_PATHS} 应覆盖
+ *       {@code /api/admin/};非 admin 角色应被拒绝且不执行审核。</li>
+ * </ul>
+ *
+ * <p><b>RED 预期</b>:权限流 3 例失败(红),断言原文含「RED[admin.article.audit]」,失败原因
+ * 可贴(匿名放行 / LOGIN_REQUIRED_PATHS 缺 /api/admin/ / audit 无角色守卫)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:按 B-142-1 处置——① {@code JwtInterceptor.LOGIN_REQUIRED_PATHS} 追加
+ * {@code "/api/admin/"}(保留 {@code /api/admin-auth/*} 例外在 PUBLIC_PATHS),匿名 → 401;
+ * ② {@code audit} 增加 {@code @RequestAttribute("role") String role} 参数并在入口拒绝非 admin
+ * ({@code !"admin".equals(role) → Result.error("无权限")},与 {@code /move} 守卫一致)。
+ * 实现后本测试权限流 3 例自动转绿。</p>
+ *
+ * <p><b>测试范围</b>:纯契约级单测(Mockito + 反射),无 Spring 上下文 / 无 DB / 无真实微信 /
+ * 无外部服务;{@code JwtInterceptor} 直接 new(匿名分支不触达其 @Resource 字段)。</p>
+ */
+class AdminArticleAuditContractTest {
+
+    /** 契约端点:管理端文章审核 */
+    private static final String ENDPOINT = "/api/admin/articles/audit";
+
+    private static final Long ARTICLE_ID = 100L;
+    private static final Long AUDITOR_ID = 88L;
+
+    private AdminArticleController controller;
+    private ArticleService articleService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminArticleController();
+        articleService = mock(ArticleService.class);
+        setField("articleService", articleService);
+    }
+
+    // ==================== 正常流:参数门禁通过后原样委托 service,返回「审核完成」 ====================
+
+    @Test
+    @DisplayName("正常流-1:审核通过(approved)→ 委托 auditArticle(id, approved, null, adminId),返回审核完成")
+    void audit_审核通过_委托service并返回审核完成() throws Exception {
+        Result<String> r = callAudit(validBody("approved", null), AUDITOR_ID, "admin");
+
+        assertEquals(200, r.getCode());
+        assertEquals("审核完成", r.getData());
+        verify(articleService).auditArticle(ARTICLE_ID, "approved", null, AUDITOR_ID);
+    }
+
+    @Test
+    @DisplayName("正常流-2:审核驳回(rejected,含原因)→ 原因原样转发 service,返回审核完成")
+    void audit_审核驳回_原因原样转发service() throws Exception {
+        Result<String> r = callAudit(validBody("rejected", "内容涉嫌夸大"), AUDITOR_ID, "admin");
+
+        assertEquals(200, r.getCode());
+        assertEquals("审核完成", r.getData());
+        verify(articleService).auditArticle(ARTICLE_ID, "rejected", "内容涉嫌夸大", AUDITOR_ID);
+    }
+
+    // ==================== 边界流:参数门禁 / service 异常透传 ====================
+
+    @Test
+    @DisplayName("边界流-1:非法审核状态(非 approved/rejected)→ 审核状态不正确,不触达 service")
+    void audit_非法审核状态_返回审核状态不正确() throws Exception {
+        for (String bad : new String[]{"unknown", "pending", "APPROVED", ""}) {
+            Result<String> r = callAudit(validBody(bad, null), AUDITOR_ID, "admin");
+            assertEquals(500, r.getCode());
+            assertEquals("审核状态不正确", r.getMessage(), "auditStatus=" + bad + " 应被拒");
+        }
+        verify(articleService, never()).auditArticle(any(), any(), any(), any());
+    }
+
+    @Test
+    @DisplayName("边界流-2:驳回但原因缺失/全空白 → 驳回时必须填写原因,不触达 service")
+    void audit_驳回缺原因_返回驳回必须填写原因() throws Exception {
+        // 原因缺失
+        Result<String> noReason = callAudit(validBody("rejected", null), AUDITOR_ID, "admin");
+        assertEquals(500, noReason.getCode());
+        assertEquals("驳回时必须填写原因", noReason.getMessage());
+        // 原因全空白(trim 后为空)
+        Result<String> blankReason = callAudit(validBody("rejected", "   \t  "), AUDITOR_ID, "admin");
+        assertEquals(500, blankReason.getCode());
+        assertEquals("驳回时必须填写原因", blankReason.getMessage());
+        verify(articleService, never()).auditArticle(any(), any(), any(), any());
+    }
+
+    @Test
+    @DisplayName("边界流-3:service 运行时异常 → Result.error 透传 message(如「仅待审核状态可审核」)")
+    void audit_service运行时异常_返回error透传message() throws Exception {
+        doThrow(new RuntimeException("仅待审核状态可审核"))
+                .when(articleService)
+                .auditArticle(eq(ARTICLE_ID), eq("rejected"), eq("原因"), eq(AUDITOR_ID));
+
+        Result<String> r = callAudit(validBody("rejected", "原因"), AUDITOR_ID, "admin");
+
+        assertEquals(500, r.getCode());
+        assertEquals("仅待审核状态可审核", r.getMessage());
+    }
+
+    // ==================== 权限流(契约缺口,预期红,B-142-1 / TR-13) ====================
+
+    @Test
+    @DisplayName("权限流-1:匿名(无 token)POST /api/admin/articles/audit 应被 JwtInterceptor 401 拒绝")
+    void audit_匿名请求_应401拒绝() throws Exception {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        HttpServletResponse response = mock(HttpServletResponse.class);
+        when(request.getMethod()).thenReturn("POST");
+        when(request.getRequestURI()).thenReturn(ENDPOINT);
+        when(request.getHeader("Authorization")).thenReturn(null);
+        when(request.getParameter("token")).thenReturn(null);
+        when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+
+        JwtInterceptor interceptor = new JwtInterceptor(); // @Resource 字段留空:匿名分支不触达 DB
+
+        boolean allowed = interceptor.preHandle(request, response, null);
+
+        assertFalse(allowed,
+                "RED[admin.article.audit] 匿名(无 token)POST " + ENDPOINT
+                        + " 应被 JwtInterceptor 拒绝(401);当前 LOGIN_REQUIRED_PATHS 未收口 /api/admin/,"
+                        + "匿名被放行至 controller,且 audit 无角色守卫,匿名(userId=-1, role=anonymous)"
+                        + "可直接审核文章(B-142-1 P1:/api/admin/** 整族鉴权门缺失,TR-13 权限流要求匿名→401/403)。");
+        verify(response).setStatus(401);
+    }
+
+    @Test
+    @DisplayName("权限流-2:JwtInterceptor.LOGIN_REQUIRED_PATHS 应覆盖 /api/admin/ 前缀")
+    void loginRequiredPaths_应覆盖apiAdmin前缀() throws Exception {
+        Field f = JwtInterceptor.class.getDeclaredField("LOGIN_REQUIRED_PATHS");
+        f.setAccessible(true);
+        String[] paths = (String[]) f.get(null);
+
+        boolean covered = false;
+        for (String p : paths) {
+            if (ENDPOINT.startsWith(p)) {
+                covered = true;
+                break;
+            }
+        }
+        assertTrue(covered,
+                "RED[admin.article.audit] JwtInterceptor.LOGIN_REQUIRED_PATHS 应含 /api/admin/ 前缀条目,"
+                        + "使匿名 POST " + ENDPOINT + " → 401;当前仅收口 /api/admin-auth/* 登录端点"
+                        + "且它们走 PUBLIC_PATHS 例外,admin 业务族整体缺失(B-142-1-Update,R152~R154 延续未修)。");
+    }
+
+    @Test
+    @DisplayName("权限流-3:audit 应按项目 admin 守卫惯例声明 role 参数并拒绝非 admin(不执行审核)")
+    void audit_非admin角色_应拒绝且不审核() throws Exception {
+        Method m = findAuditWithRole();
+        assertNotNull(m,
+                "RED[admin.article.audit] 契约方法 audit 应声明 role 参数"
+                        + "(@RequestAttribute(\"role\") String role),按项目 admin 守卫惯例拒绝非 admin"
+                        + "(参照 AdminArticleController#move 的「无权限」守卫);"
+                        + "当前仅 audit(Map, Long) 两参数、无角色校验,登录 C 端用户(parent/child)"
+                        + "即可越权审核文章(B-142-1,TR-13 权限流)。");
+        m.setAccessible(true);
+
+        Result<?> r = (Result<?>) m.invoke(controller, validBody("approved", null), AUDITOR_ID, "parent");
+
+        assertEquals("无权限", r.getMessage());
+        verify(articleService, never()).auditArticle(any(), any(), any(), any());
+    }
+
+    // ==================== Service 状态机(auditArticle 契约,纯 Mockito) ====================
+
+    private ArticleService service;
+    private ArticleMapper articleMapper;
+    private ThreadPoolTaskExecutor taskExecutor;
+
+    @BeforeEach
+    void setUpService() throws Exception {
+        service = new ArticleService();
+        articleMapper = mock(ArticleMapper.class);
+        taskExecutor = mock(ThreadPoolTaskExecutor.class);
+        injectIntoService("articleMapper", articleMapper);
+        injectIntoService("taskExecutor", taskExecutor);
+    }
+
+    private void injectIntoService(String field, Object value) throws Exception {
+        Field f = ArticleService.class.getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(service, value);
+    }
+
+    private Article pendingArticle() {
+        Article a = new Article();
+        a.setId(ARTICLE_ID);
+        a.setStatus("draft");
+        a.setAuditStatus("pending");
+        a.setTitle("契约测试文章");
+        a.setContent("<p>正文</p>");
+        return a;
+    }
+
+    @Test
+    @DisplayName("service-1:审核通过 → status=published、清空驳回原因、记录审核人/时间")
+    void service_审核通过_置published并清空驳回原因() {
+        Article a = pendingArticle();
+        when(articleMapper.selectById(ARTICLE_ID)).thenReturn(a);
+
+        service.auditArticle(ARTICLE_ID, "approved", null, AUDITOR_ID);
+
+        assertEquals("published", a.getStatus(), "approved → status 应置 published");
+        assertEquals("approved", a.getAuditStatus(), "approved → auditStatus 应置 approved");
+        assertNull(a.getAuditReason(), "approved → 驳回原因应清空");
+        assertNotNull(a.getPublishedAt(), "approved → 应记录发布/通过时间");
+        assertNotNull(a.getAuditedAt(), "approved → 应记录审核时间");
+        assertEquals(AUDITOR_ID, a.getAuditorId(), "approved → 应记录审核人 ID");
+        verify(articleMapper).updateById(a);
+    }
+
+    @Test
+    @DisplayName("service-2:审核驳回 → status=rejected、保留驳回原因、记录审核人/时间")
+    void service_审核拒绝_置rejected并保留驳回原因() {
+        Article a = pendingArticle();
+        when(articleMapper.selectById(ARTICLE_ID)).thenReturn(a);
+
+        service.auditArticle(ARTICLE_ID, "rejected", "内容涉嫌夸大", AUDITOR_ID);
+
+        assertEquals("rejected", a.getStatus(), "rejected → status 应置 rejected");
+        assertEquals("rejected", a.getAuditStatus(), "rejected → auditStatus 应置 rejected");
+        assertEquals("内容涉嫌夸大", a.getAuditReason(), "rejected → 驳回原因应保留");
+        assertNull(a.getPublishedAt(), "rejected → 不应有发布/通过时间");
+        assertNotNull(a.getAuditedAt(), "rejected → 应记录审核时间");
+        assertEquals(AUDITOR_ID, a.getAuditorId(), "rejected → 应记录审核人 ID");
+        verify(articleMapper).updateById(a);
+    }
+
+    @Test
+    @DisplayName("service-3:文章不存在 → 抛「文章不存在」,不写库")
+    void service_文章不存在_抛文章不存在_不写库() {
+        when(articleMapper.selectById(ARTICLE_ID)).thenReturn(null);
+
+        RuntimeException ex = assertThrows(RuntimeException.class,
+                () -> service.auditArticle(ARTICLE_ID, "approved", null, AUDITOR_ID));
+
+        assertEquals("文章不存在", ex.getMessage());
+        verify(articleMapper, never()).updateById(any(Article.class));
+    }
+
+    @Test
+    @DisplayName("service-4:非 pending 审核态 → 抛「仅待审核状态可审核」,不写库")
+    void service_非pending审核态_抛仅待审核状态可审核_不写库() {
+        Article a = pendingArticle();
+        a.setAuditStatus("approved"); // 已审核过的文章不允许重复审核
+        when(articleMapper.selectById(ARTICLE_ID)).thenReturn(a);
+
+        RuntimeException ex = assertThrows(RuntimeException.class,
+                () -> service.auditArticle(ARTICLE_ID, "approved", null, AUDITOR_ID));
+
+        assertEquals("仅待审核状态可审核", ex.getMessage());
+        verify(articleMapper, never()).updateById(any(Article.class));
+    }
+
+    // ==================== 辅助 ====================
+
+    private Map<String, Object> validBody(String auditStatus, String auditReason) {
+        Map<String, Object> body = new HashMap<>();
+        body.put("id", ARTICLE_ID);
+        body.put("auditStatus", auditStatus);
+        if (auditReason != null) {
+            body.put("auditReason", auditReason);
+        }
+        return body;
+    }
+
+    private void setField(String name, Object value) throws Exception {
+        Field f = AdminArticleController.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(controller, value);
+    }
+
+    /**
+     * 反射派发 audit:兼容当前 2 参数签名(RED 现状)与契约 3 参数签名(GREEN 后
+     * audit(Map, Long, String role)),避免 GREEN 阶段改签名导致本测试编译失败。
+     */
+    @SuppressWarnings("unchecked")
+    private Result<String> callAudit(Map<String, Object> body, Long adminId, String role)
+            throws Exception {
+        for (Method m : AdminArticleController.class.getDeclaredMethods()) {
+            if (m.getName().equals("audit")) {
+                m.setAccessible(true);
+                if (m.getParameterCount() == 3) {
+                    return (Result<String>) m.invoke(controller, body, adminId, role);
+                }
+                if (m.getParameterCount() == 2) {
+                    return (Result<String>) m.invoke(controller, body, adminId);
+                }
+            }
+        }
+        fail("契约方法 audit 不存在");
+        throw new IllegalStateException("unreachable");
+    }
+
+    /** 契约签名:audit(Map body, Long adminId, String role)——role 承载 admin 角色守卫。 */
+    private Method findAuditWithRole() {
+        for (Method m : AdminArticleController.class.getDeclaredMethods()) {
+            if (m.getName().equals("audit") && m.getParameterCount() == 3) {
+                return m;
+            }
+        }
+        return null;
+    }
+}

+ 285 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleCreateContractTest.java

@@ -0,0 +1,285 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.service.ArticleService;
+import com.etotem.cfc.service.api.WechatServiceInterface;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:管理端文章创建(能力键 {@code admin.article.create},{@code POST /api/admin/articles/create})。
+ *
+ * <p><b>溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code docs/tdd/SRS.md}「三、未覆盖控制器」——
+ *       {@code AdminArticleController}(22 方法,0 覆盖)</li>
+ *   <li>设计:{@code AdminArticleController#create}({@code @PostMapping("/create")},类级
+ *       {@code /api/admin/articles})+ {@code ArticleService#create(Article, Long)}</li>
+ *   <li>契约:{@code docs/superpowers/api/API_REFERENCE.md} §4.60.4(SC-A-03 文章 CRUD);
+ *       权限流按契约核对结论(admin-ops-contract §5)TR-13:「补 admin 端点 MockMvc 契约
+ *       JUnit + <b>非 admin token → 403 权限流</b>」</li>
+ * </ul>
+ *
+ * <p><b>实现现状(origin/cfclub @ 0a95662a8 实测)</b></p>
+ * <ul>
+ *   <li>正常流/边界流已实现:create 解析请求体 → 文本安全检测(fail-open)→
+ *       {@code articleService.create} → 返回 {@code {id}};重复标题异常透传 error。</li>
+ *   <li><b>权限流未落地(本测试的红)</b>:{@link JwtInterceptor#LOGIN_REQUIRED_PATHS} 未收口
+ *       {@code /api/admin/} 前缀(仅 {@code /api/admin-auth/*} 登录端点走 PUBLIC_PATHS),匿名
+ *       (userId=-1, role=anonymous)被放行至 controller;{@code create} 亦无
+ *       {@code @RequestAttribute("role")} 角色守卫(参照同控制器 {@code /move} 与
+ *       {@code AdminReferralController#summary} 的「无权限」守卫惯例)。对应缺陷台账
+ *       <b>B-142-1</b>(P1 安全:{@code /api/admin/**} 整族鉴权门缺失,R152~R154 延续未修)。</li>
+ * </ul>
+ *
+ * <p><b>三流划分</b></p>
+ * <ul>
+ *   <li>正常流(已实现 → 绿锁定契约):创建委托 service、回源新 id、字段落位;
+ *       内容安全检测不通过 → 拒绝且不落库。</li>
+ *   <li>边界流(已实现 → 绿锁定契约):重复标题异常透传 error。</li>
+ *   <li>权限流(契约缺口 → <b>预期红</b>):匿名请求应 401;{@code LOGIN_REQUIRED_PATHS} 应覆盖
+ *       {@code /api/admin/};非 admin 角色应被拒绝且不落库。</li>
+ * </ul>
+ *
+ * <p><b>RED 预期</b>:权限流 3 例失败(红),断言原文含「RED[admin.article.create]」,失败原因
+ * 可贴(匿名放行 / LOGIN_REQUIRED_PATHS 缺 /api/admin/ / create 无角色守卫)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:按 B-142-1 处置——① {@code JwtInterceptor.LOGIN_REQUIRED_PATHS} 追加
+ * {@code "/api/admin/"}(保留 {@code /api/admin-auth/*} 例外在 PUBLIC_PATHS),匿名 → 401;
+ * ② {@code create} 增加 {@code @RequestAttribute("role") String role} 参数并在入口拒绝非 admin
+ * ({@code !"admin".equals(role) → Result.error("无权限")})。实现后本测试自动转绿。</p>
+ *
+ * <p><b>测试范围</b>:纯契约级单测(Mockito + 反射),无 Spring 上下文 / 无 DB / 无真实微信 /
+ * 无外部服务;{@code JwtInterceptor} 直接 new(匿名分支不触达其 @Resource 字段)。</p>
+ */
+class AdminArticleCreateContractTest {
+
+    /** 契约端点:管理端文章创建 */
+    private static final String ENDPOINT = "/api/admin/articles/create";
+
+    private AdminArticleController controller;
+    private ArticleService articleService;
+    private ThreadPoolTaskExecutor taskExecutor;
+    private WechatServiceInterface wechatService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminArticleController();
+        articleService = mock(ArticleService.class);
+        taskExecutor = mock(ThreadPoolTaskExecutor.class);
+        wechatService = mock(WechatServiceInterface.class);
+        setField("articleService", articleService);
+        setField("taskExecutor", taskExecutor);
+        setField("wechatService", wechatService);
+    }
+
+    // ==================== 正常流:创建委托 service、回源新 id、字段落位 ====================
+
+    @Test
+    @DisplayName("正常流-1:create 解析请求体字段并委托 articleService.create(article, adminId),返回新 id")
+    void create_委托service并返回新id() throws Exception {
+        stubTextSafety(true);
+        doAnswer(inv -> {
+            ((Article) inv.getArgument(0)).setId(999L);
+            return null;
+        }).when(articleService).create(any(Article.class), anyLong());
+
+        Result<Map<String, Object>> r = callCreate(validBody(), 1L, "admin");
+
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData(), "成功响应应携带 {id}");
+        assertEquals(999L, r.getData().get("id"), "应返回新文章 id");
+
+        ArgumentCaptor<Article> cap = ArgumentCaptor.forClass(Article.class);
+        verify(articleService).create(cap.capture(), eq(1L));
+        Article saved = cap.getValue();
+        assertEquals("契约测试文章", saved.getTitle());
+        assertEquals("<p>契约正文</p>", saved.getContent());
+        assertEquals("契约摘要", saved.getSummary());
+        assertEquals(5L, saved.getCategoryId().longValue());
+        assertEquals("运营管理员", saved.getAuthor());
+        assertEquals(Integer.valueOf(3), saved.getReadTime());
+        assertEquals("article", saved.getContentType());
+        assertEquals("published", saved.getStatus());
+    }
+
+    @Test
+    @DisplayName("正常流-2:文本内容安全检测不通过 → 拒绝且不落库")
+    void create_内容安全不通过_拒绝且不落库() throws Exception {
+        stubTextSafety(false);
+        Map<String, Object> body = validBody();
+        body.put("title", "标题含敏感词");
+
+        Result<Map<String, Object>> r = callCreate(body, 1L, "admin");
+
+        assertEquals("文章标题包含敏感信息,发布失败", r.getMessage());
+        verify(articleService, never()).create(any(Article.class), anyLong());
+    }
+
+    // ==================== 边界流:重复标题 / service 异常透传 ====================
+
+    @Test
+    @DisplayName("边界流-1:重复标题 → service 异常透传 error,不吞错")
+    void create_重复标题_异常透传error() throws Exception {
+        stubTextSafety(true);
+        doThrow(new RuntimeException("标题「契约测试文章」已存在,请勿重复创建"))
+                .when(articleService).create(any(Article.class), anyLong());
+
+        Result<Map<String, Object>> r = callCreate(validBody(), 1L, "admin");
+
+        assertEquals("标题「契约测试文章」已存在,请勿重复创建", r.getMessage());
+    }
+
+    // ==================== 权限流(契约缺口,预期红,B-142-1 / TR-13) ====================
+
+    @Test
+    @DisplayName("权限流-1:匿名(无 token)POST /api/admin/articles/create 应被 JwtInterceptor 401 拒绝")
+    void create_匿名请求_应401拒绝() throws Exception {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        HttpServletResponse response = mock(HttpServletResponse.class);
+        when(request.getMethod()).thenReturn("POST");
+        when(request.getRequestURI()).thenReturn(ENDPOINT);
+        when(request.getHeader("Authorization")).thenReturn(null);
+        when(request.getParameter("token")).thenReturn(null);
+        when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+
+        JwtInterceptor interceptor = new JwtInterceptor(); // @Resource 字段留空:匿名分支不触达 DB
+
+        boolean allowed = interceptor.preHandle(request, response, null);
+
+        assertFalse(allowed,
+                "RED[admin.article.create] 匿名(无 token)POST " + ENDPOINT
+                        + " 应被 JwtInterceptor 拒绝(401);当前 LOGIN_REQUIRED_PATHS 未收口 /api/admin/,"
+                        + "匿名被放行至 controller,且 create 无角色守卫,匿名(userId=-1, role=anonymous)"
+                        + "可直接建文章(B-142-1 P1:/api/admin/** 整族鉴权门缺失,TR-13 权限流要求匿名→401/403)。");
+        verify(response).setStatus(401);
+    }
+
+    @Test
+    @DisplayName("权限流-2:JwtInterceptor.LOGIN_REQUIRED_PATHS 应覆盖 /api/admin/ 前缀")
+    void loginRequiredPaths_应覆盖apiAdmin前缀() throws Exception {
+        Field f = JwtInterceptor.class.getDeclaredField("LOGIN_REQUIRED_PATHS");
+        f.setAccessible(true);
+        String[] paths = (String[]) f.get(null);
+
+        boolean covered = false;
+        for (String p : paths) {
+            if (ENDPOINT.startsWith(p)) {
+                covered = true;
+                break;
+            }
+        }
+        assertTrue(covered,
+                "RED[admin.article.create] JwtInterceptor.LOGIN_REQUIRED_PATHS 应含 /api/admin/ 前缀条目,"
+                        + "使匿名 POST " + ENDPOINT + " → 401;当前仅收口 /api/admin-auth/* 登录端点"
+                        + "且它们走 PUBLIC_PATHS 例外,admin 业务族整体缺失(B-142-1-Update,R152~R154 延续未修)。");
+    }
+
+    @Test
+    @DisplayName("权限流-3:create 应按项目 admin 守卫惯例声明 role 参数并拒绝非 admin(不落库)")
+    void create_非admin角色_应拒绝且不落库() throws Exception {
+        Method m = findCreateWithRole();
+        assertNotNull(m,
+                "RED[admin.article.create] 契约方法 create 应声明 role 参数"
+                        + "(@RequestAttribute(\"role\") String role),按项目 admin 守卫惯例拒绝非 admin"
+                        + "(参照 AdminArticleController#move 与 AdminReferralController#summary 的「无权限」守卫);"
+                        + "当前仅 create(Map, Long) 两参数、无角色校验,登录 C 端用户(parent/child)"
+                        + "即可越权建文章(B-142-1,TR-13 权限流)。");
+        m.setAccessible(true);
+
+        Result<?> r = (Result<?>) m.invoke(controller, validBody(), 1L, "parent");
+
+        assertEquals("无权限", r.getMessage());
+        verify(articleService, never()).create(any(Article.class), anyLong());
+    }
+
+    // ==================== 辅助 ====================
+
+    private Map<String, Object> validBody() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("title", "契约测试文章");
+        body.put("content", "<p>契约正文</p>");
+        body.put("summary", "契约摘要");
+        body.put("categoryId", 5L);
+        body.put("author", "运营管理员");
+        body.put("readTime", 3);
+        body.put("contentType", "article");
+        body.put("status", "published");
+        return body;
+    }
+
+    /** 文本安全检测:stub taskExecutor.submit 返回指定结果(true=fail-open 放行,false=检测不通过)。 */
+    private void stubTextSafety(boolean safe) {
+        when(taskExecutor.submit(any(Callable.class)))
+                .thenReturn(CompletableFuture.completedFuture(safe));
+    }
+
+    private void setField(String name, Object value) throws Exception {
+        Field f = AdminArticleController.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(controller, value);
+    }
+
+    /**
+     * 反射派发 create:兼容当前 2 参数签名(RED 现状)与契约 3 参数签名(GREEN 后
+     * create(Map, Long, String role)),避免 GREEN 阶段改签名导致本测试编译失败。
+     */
+    @SuppressWarnings("unchecked")
+    private Result<Map<String, Object>> callCreate(Map<String, Object> body, Long adminId, String role)
+            throws Exception {
+        for (Method m : AdminArticleController.class.getDeclaredMethods()) {
+            if (m.getName().equals("create")) {
+                m.setAccessible(true);
+                if (m.getParameterCount() == 3) {
+                    return (Result<Map<String, Object>>) m.invoke(controller, body, adminId, role);
+                }
+                if (m.getParameterCount() == 2) {
+                    return (Result<Map<String, Object>>) m.invoke(controller, body, adminId);
+                }
+            }
+        }
+        fail("契约方法 create 不存在");
+        throw new IllegalStateException("unreachable");
+    }
+
+    /** 契约签名:create(Map body, Long adminId, String role)——role 承载 admin 角色守卫。 */
+    private Method findCreateWithRole() {
+        for (Method m : AdminArticleController.class.getDeclaredMethods()) {
+            if (m.getName().equals("create") && m.getParameterCount() == 3) {
+                return m;
+            }
+        }
+        return null;
+    }
+}

+ 229 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminArticleListContractTest.java

@@ -0,0 +1,229 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.service.ArticleService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:后台文章列表(能力键 {@code admin.article.list},S-cfc-142)。
+ *
+ * <p><b>契约锚点</b></p>
+ * <ul>
+ *   <li>需求:{@code docs/tdd/SRS.md}「三、未覆盖控制器」{@code AdminArticleController}
+ *       (/api/admin/articles,22 方法);</li>
+ *   <li>设计:{@code AdminArticleController#list(Map)}({@code @PostMapping("/list")});
+ *       {@code ArticleService#getAdminList(...)}(11 参:status/categoryId/keyword/contentType/
+ *       difficultyLevel/dimensionCode/tagId/auditStatus/page/size/sortSpecs);</li>
+ *   <li>契约:{@code docs/superpowers/api/API_REFERENCE.md} §4.60.4
+ *       {@code POST /api/admin/articles/list}(文章 CRUD + 排序,SC-A-03);</li>
+ *   <li>调用方:{@code cfc-web/src/api/article.js#adminArticleList} +
+ *       {@code views/admin/ArticleManage.vue#loadList}(page/size/status/categoryId/
+ *       contentType/difficultyLevel/dimensionCode/tagId/keyword/sort)、
+ *       {@code views/admin/review/ArticleAudit.vue}(status/auditStatus/keyword/sort)。</li>
+ * </ul>
+ *
+ * <p><b>被校验的契约行为</b></p>
+ * <ul>
+ *   <li>未传 {@code page}/{@code size} 时默认 1/20;</li>
+ *   <li>8 个过滤参数(status/categoryId/keyword/contentType/difficultyLevel/dimensionCode/
+ *       tagId/auditStatus)解析后透传 {@code ArticleService.getAdminList};</li>
+ *   <li>{@code sort} 排序规格(长列表 {@code [{field, order}]})透传;</li>
+ *   <li>返回 {@code Result.success(Page<Article>)} 信封(HTTP 200 信封 + 业务码 200)。</li>
+ * </ul>
+ *
+ * <p><b>测试隔离</b>:{@code new AdminArticleController()} + 反射注入 mock
+ * {@code ArticleService},直接调 {@code list(Map)},无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ *
+ * <p><b>RED 预期说明</b>:本键为契约新增能力。实测 worktree 基底
+ * {@code origin/cfclub} 上 {@code AdminArticleController#list} 与
+ * {@code ArticleService#getAdminList} 已存在(实现已落地),因此本契约测试首次运行
+ * 预期即绿(既成行为的回归契约);若后续实现对上述契约行为(默认分页/过滤透传/排序透传/
+ * 响应信封)发生回归,本类将转红。按编排约定:实现已存在 → 转测试登记,不私改 src/main。</p>
+ */
+class AdminArticleListContractTest {
+
+    private static final String ARTICLES_BASE_PATH = "/api/admin/articles";
+
+    private AdminArticleController controller;
+    private ArticleService articleService;
+
+    /** 每次调用记录 getAdminList 的实际入参,供断言 */
+    private final List<Object[]> calls = new ArrayList<>();
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminArticleController();
+        articleService = mock(ArticleService.class);
+        inject(controller, "articleService", articleService);
+        calls.clear();
+    }
+
+    // ==================== 正常流:默认分页 / 过滤透传 ====================
+
+    @Test
+    @DisplayName("list:空 body → 默认 page=1 size=20,全部过滤参数为 null")
+    void list_空body_默认分页与空过滤() {
+        Object[] args = callList(new HashMap<>());
+
+        assertEquals(1, args[8], "page 缺省默认 1");
+        assertEquals(20, args[9], "size 缺省默认 20");
+        assertEquals(null, args[0], "status 未传为 null");
+        assertEquals(null, args[1], "categoryId 未传为 null");
+        assertEquals(null, args[2], "keyword 未传为 null");
+        assertEquals(null, args[3], "contentType 未传为 null");
+        assertEquals(null, args[4], "difficultyLevel 未传为 null");
+        assertEquals(null, args[5], "dimensionCode 未传为 null");
+        assertEquals(null, args[6], "tagId 未传为 null");
+        assertEquals(null, args[7], "auditStatus 未传为 null");
+        assertEquals(null, args[10], "sort 未传为 null");
+    }
+
+    @Test
+    @DisplayName("list:全量过滤参数 + 显式分页 + sort → 解析后原样透传 getAdminList")
+    void list_全量过滤参数_透传解析() {
+        List<Map<String, String>> sortSpecs = Collections.singletonList(
+                Collections.singletonMap("field", "createdAt"));
+
+        Map<String, Object> body = new HashMap<>();
+        body.put("status", "published");
+        body.put("categoryId", 5);
+        body.put("keyword", "亲子");
+        body.put("contentType", "article");
+        body.put("difficultyLevel", 3);
+        body.put("dimensionCode", "mind");
+        body.put("tagId", 7);
+        body.put("auditStatus", "approved");
+        body.put("page", 2);
+        body.put("size", 10);
+        body.put("sort", sortSpecs);
+
+        Object[] args = callList(body);
+
+        assertEquals("published", args[0], "status 应透传");
+        assertEquals(5L, args[1], "categoryId 应解析为 Long");
+        assertEquals("亲子", args[2], "keyword 应透传");
+        assertEquals("article", args[3], "contentType 应透传");
+        assertEquals(3, args[4], "difficultyLevel 应解析为 Integer");
+        assertEquals("mind", args[5], "dimensionCode 应透传");
+        assertEquals(7L, args[6], "tagId 应解析为 Long");
+        assertEquals("approved", args[7], "auditStatus 应透传");
+        assertEquals(2, args[8], "page 应透传");
+        assertEquals(10, args[9], "size 应透传");
+        assertEquals(sortSpecs, args[10], "sort 排序规格应原样透传");
+    }
+
+    @Test
+    @DisplayName("list:数字字符串参数(前端常见传法)→ 正常解析为 Long/Integer")
+    void list_数字字符串参数_正常解析() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("categoryId", "5");
+        body.put("difficultyLevel", "3");
+        body.put("tagId", "7");
+        body.put("page", "2");
+        body.put("size", "10");
+
+        Object[] args = callList(body);
+
+        assertEquals(5L, args[1], "字符串 categoryId 应解析为 Long");
+        assertEquals(3, args[4], "字符串 difficultyLevel 应解析为 Integer");
+        assertEquals(7L, args[6], "字符串 tagId 应解析为 Long");
+        assertEquals(2, args[8], "字符串 page 应解析为 int");
+        assertEquals(10, args[9], "字符串 size 应解析为 int");
+    }
+
+    // ==================== 边界流:非法数字参数 ====================
+
+    @Test
+    @DisplayName("list:非数字 categoryId/tagId → 解析为 null(ParamUtils 语义),不抛异常")
+    void list_非数字过滤参数_安全解析为null() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("categoryId", "abc");
+        body.put("tagId", "");
+
+        Object[] args = callList(body);
+
+        assertEquals(null, args[1], "非数字 categoryId 应安全解析为 null");
+        assertEquals(null, args[6], "空字符串 tagId 应安全解析为 null");
+    }
+
+    // ==================== 响应信封 ====================
+
+    @Test
+    @DisplayName("list:成功 → Result.success 包装 Page<Article>(业务码 200)")
+    void list_成功_返回success信封() {
+        Page<Article> page = new Page<>(1, 20);
+        page.setTotal(42);
+        when(articleService.getAdminList(any(), any(), any(), any(), any(), any(), any(), any(),
+                anyInt(), anyInt(), any())).thenReturn(page);
+
+        Result<Page<Article>> result = controller.list(new HashMap<>());
+
+        assertNotNull(result, "list 必须返回 Result 信封");
+        assertEquals(200, result.getCode(), "成功业务码应为 200");
+        assertEquals(page, result.getData(), "data 应为 getAdminList 返回的 Page");
+    }
+
+    // ==================== 契约结构:路由映射 ====================
+
+    @Test
+    @DisplayName("契约:AdminArticleController 类级映射 /api/admin/articles + list 方法级 /list")
+    void 契约_路由映射_POST_api_admin_articles_list() throws Exception {
+        RequestMapping classMapping = AdminArticleController.class.getAnnotation(RequestMapping.class);
+        assertNotNull(classMapping, "控制器必须有类级 @RequestMapping");
+        assertEquals(ARTICLES_BASE_PATH, classMapping.value()[0],
+                "类级路径应为 " + ARTICLES_BASE_PATH);
+
+        Method list = AdminArticleController.class.getMethod("list", Map.class);
+        PostMapping postMapping = list.getAnnotation(PostMapping.class);
+        assertNotNull(postMapping, "list 方法必须有 @PostMapping");
+        assertEquals("/list", postMapping.value()[0]);
+        // POST 语义由 @PostMapping 注解类型本身保证(组合注解固定 method=POST),无需再断言 method()
+    }
+
+    // ==================== 辅助 ====================
+
+    /** 调用 controller.list(body),返回 getAdminList 的实际入参数组(含 11 个参数) */
+    @SuppressWarnings("unchecked")
+    private Object[] callList(Map<String, Object> body) {
+        Page<Article> page = new Page<>(1, 20);
+        when(articleService.getAdminList(any(), any(), any(), any(), any(), any(), any(), any(),
+                anyInt(), anyInt(), any()))
+                .thenAnswer(inv -> {
+                    calls.add(inv.getArguments());
+                    return page;
+                });
+
+        Result<Page<Article>> result = controller.list(body);
+
+        assertNotNull(result, "list 必须返回 Result 信封");
+        assertEquals(1, calls.size(), "list 恰调用一次 getAdminList");
+        return calls.get(0);
+    }
+
+    private static void inject(Object target, String field, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+}

+ 372 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthControllerLoginContractTest.java

@@ -0,0 +1,372 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.dto.AdminLoginDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.LoginAttemptService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import com.etotem.cfc.service.WechatWebLoginService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-cfc-17 / admin.auth.login 契约级单测(RED 阶段:补齐「未覆盖」能力键的最小闭环)。
+ *
+ * <p>与 {@link AdminAuthControllerLoginStatusTest}(B-2/R5:空 body/缺参 → 400 语义)互补,
+ * 本类聚焦 {@code POST /api/admin-auth/login} 的完整登录契约:
+ * <ul>
+ *   <li>正常路径:admin / teacher / 遗留角色归一化(activity_admin→activity_manager,
+ *       supplier_admin→supplier)/ 多角色 loginRole 身份选择 / 无 roles 列表回退主角色;</li>
+ *   <li>关键边界:用户不存在、验证码错误(记录失败)、登录锁定、skipCaptcha 跳过校验、
+ *       X-Forwarded-For IP 取数口径、nickname 为空回退手机号;</li>
+ *   <li>角色与权限:parent/child 等 C 端账号拒绝、非法 loginRole 拒绝。</li>
+ * </ul>
+ *
+ * <p>契约口径(对齐项目惯例:控制器签名 {@code Result<T>} + HTTP 200 信封、业务码表达语义;
+ * 真实 HTTP 401 由 {@code JwtInterceptor} 对受保护路径负责,{@code /api/admin-auth/login}
+ * 为公开路径):
+ * <ul>
+ *   <li>参数校验(空 body / 缺 phone / 缺 code)→ 业务码 400;</li>
+ *   <li>业务拒绝(验证码错误 / 登录锁定 / 用户不存在 / 无后台角色 / 非法登录身份)
+ *       → 业务码 500 + 明确 message —— 对应 blockers.md B-2 / test_blockers.md R5 期望的
+ *       401/403 语义,当前实现仍以业务码 500 表达(HTTP 200 信封),如实入测并登记缺陷,不改 src/main;</li>
+ *   <li>成功 → 业务码 200 + token/adminId/role/roles。</li>
+ * </ul>
+ * 测试隔离:MockMvc standalone + 全 mock 依赖,无 Spring 上下文 / 无 DB / 无外部服务。
+ */
+class AdminAuthControllerLoginContractTest {
+
+    private static final String PHONE = "13800000001";
+    private static final String CODE = "123456";
+
+    private AdminAuthController controller;
+    private MockMvc mockMvc;
+    private UserMapper userMapper;
+    private UserService userService;
+    private VerificationCodeService verificationCodeService;
+    private JwtConfig jwtConfig;
+    private LoginAttemptService loginAttemptService;
+
+    @BeforeEach
+    void setUp() {
+        controller = new AdminAuthController();
+        userMapper = mock(UserMapper.class);
+        userService = mock(UserService.class);
+        verificationCodeService = mock(VerificationCodeService.class);
+        jwtConfig = mock(JwtConfig.class);
+        loginAttemptService = mock(LoginAttemptService.class);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        ReflectionTestUtils.setField(controller, "userService", userService);
+        ReflectionTestUtils.setField(controller, "verificationCodeService", verificationCodeService);
+        ReflectionTestUtils.setField(controller, "jwtConfig", jwtConfig);
+        ReflectionTestUtils.setField(controller, "loginAttemptService", loginAttemptService);
+        ReflectionTestUtils.setField(controller, "wechatWebLoginService", mock(WechatWebLoginService.class));
+        // @Value 默认 false;skip-captcha 路径由专门 case 打开
+        ReflectionTestUtils.setField(controller, "skipCaptcha", false);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ================================================================
+    // 正常路径
+    // ================================================================
+
+    @Test
+    @DisplayName("login:admin 验证码登录成功 → 200 + token/adminId/role/roles")
+    void login_admin_成功签发token与角色() throws Exception {
+        successStubs(user(100L, "admin", list("admin"), "nick100", "管理员100"), list("admin"));
+
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"" + PHONE + "\",\"code\":\"" + CODE + "\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.token").value("jwt-token"))
+                .andExpect(jsonPath("$.data.adminId").value(100))
+                .andExpect(jsonPath("$.data.username").value("nick100"))
+                .andExpect(jsonPath("$.data.realName").value("管理员100"))
+                .andExpect(jsonPath("$.data.role").value("admin"))
+                .andExpect(jsonPath("$.data.roles[0]").value("admin"));
+
+        verify(verificationCodeService).verifyCode(PHONE, CODE, "admin_login");
+        verify(loginAttemptService).isBlocked(PHONE + ":127.0.0.1");
+        verify(loginAttemptService).clearSuccess(PHONE + ":127.0.0.1");
+    }
+
+    @Test
+    @DisplayName("login:teacher 登录成功 → role=teacher(成长规划师可登录后台)")
+    void login_teacher_成功() {
+        Result<Map<String, Object>> r = loginSuccess(user(200L, "teacher", list("teacher"), "规划师2", null), list("teacher"));
+
+        assertEquals(200, r.getCode());
+        assertEquals("teacher", r.getData().get("role"));
+        assertEquals("规划师2", r.getData().get("username"));
+    }
+
+    @Test
+    @DisplayName("login:遗留角色 activity_admin 归一化为 activity_manager 登录成功")
+    void login_遗留角色_归一化为新角色() {
+        Result<Map<String, Object>> r = loginSuccess(user(300L, "activity_admin", list("activity_admin"), "旧活动", null), list("activity_admin"));
+
+        assertEquals(200, r.getCode());
+        assertEquals("activity_manager", r.getData().get("role"));
+    }
+
+    @Test
+    @DisplayName("login:遗留角色 supplier_admin 归一化为 supplier 登录成功")
+    void login_供应商遗留角色_归一化() {
+        Result<Map<String, Object>> r = loginSuccess(user(1100L, "supplier_admin", list("supplier_admin"), "旧供应商", null), list("supplier_admin"));
+
+        assertEquals(200, r.getCode());
+        assertEquals("supplier", r.getData().get("role"));
+    }
+
+    @Test
+    @DisplayName("login:无 roles 列表时回退主角色 role 字段(teacher)")
+    void login_无roles列表_回退主角色() {
+        User teacher = user(400L, "teacher", null, "回退", null);
+        successStubs(teacher, Collections.<String>emptyList());
+
+        Result<Map<String, Object>> r = loginDirect(dto());
+
+        assertEquals(200, r.getCode());
+        assertEquals("teacher", r.getData().get("role"));
+        // getUserRoles 为空时回退为选中身份列表
+        assertEquals(list("teacher"), r.getData().get("roles"));
+    }
+
+    @Test
+    @DisplayName("login:多角色 + loginRole 选择 → 以指定身份登录,token roles 选中身份置顶去重")
+    void login_多角色loginRole合法_选中身份置顶() {
+        User multi = user(500L, "admin", list("admin", "teacher"), "双角色", null);
+        successStubs(multi, list("admin", "teacher"));
+
+        Result<Map<String, Object>> r = loginDirect(dtoWithLoginRole("teacher"));
+
+        assertEquals(200, r.getCode());
+        assertEquals("teacher", r.getData().get("role"));
+        assertEquals(list("admin", "teacher"), r.getData().get("roles"));
+
+        ArgumentCaptor<List<String>> rolesCaptor = ArgumentCaptor.forClass(List.class);
+        verify(jwtConfig).generateToken(eq(500L), rolesCaptor.capture());
+        // selected=teacher 置顶,其余角色(去重后)随后
+        assertEquals(list("teacher", "admin"), rolesCaptor.getValue());
+    }
+
+    // ================================================================
+    // 关键边界
+    // ================================================================
+
+    @Test
+    @DisplayName("login:用户不存在 → 业务拒绝,不签发 token 不清锁定")
+    void login_用户不存在_拒绝() {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode(PHONE, CODE, "admin_login")).thenReturn(true);
+        when(userMapper.selectOne(any())).thenReturn(null);
+
+        Result<Map<String, Object>> r = loginDirect(dto());
+
+        assertEquals(500, r.getCode());
+        assertEquals("用户不存在", r.getMessage());
+        verify(loginAttemptService, never()).clearSuccess(anyString());
+        verify(jwtConfig, never()).generateToken(any(), anyList());
+    }
+
+    @Test
+    @DisplayName("login:验证码错误 → 拒绝并记录失败尝试")
+    void login_验证码错误_记录失败() {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode(PHONE, CODE, "admin_login")).thenReturn(false);
+
+        Result<Map<String, Object>> r = loginDirect(dto());
+
+        assertEquals(500, r.getCode());
+        assertEquals("验证码错误或已过期", r.getMessage());
+        verify(loginAttemptService).recordFailure(anyString());
+        verify(userMapper, never()).selectOne(any());
+        verify(jwtConfig, never()).generateToken(any(), anyList());
+    }
+
+    @Test
+    @DisplayName("login:登录锁定 → 拒绝且不触达验证码与用户查询(含剩余分钟提示)")
+    void login_登录锁定_拒绝() {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(true);
+        // 剩余 900s=15min → 提示「15+1」分钟
+        when(loginAttemptService.getLockRemainingTime(anyString())).thenReturn(900_000L);
+
+        Result<Map<String, Object>> r = loginDirect(dto());
+
+        assertEquals(500, r.getCode());
+        assertEquals("登录尝试过多,请16分钟后重试", r.getMessage());
+        verify(verificationCodeService, never()).verifyCode(anyString(), anyString(), anyString());
+        verify(userMapper, never()).selectOne(any());
+    }
+
+    @Test
+    @DisplayName("login:skipCaptcha=true 时跳过验证码校验直接登录")
+    void login_skipCaptcha_跳过验证码() throws Exception {
+        ReflectionTestUtils.setField(controller, "skipCaptcha", true);
+        successStubs(user(600L, "admin", list("admin"), "免码", null), list("admin"));
+
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"" + PHONE + "\",\"code\":\"wrong-code\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(verificationCodeService, never()).verifyCode(anyString(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("login:X-Forwarded-For 作为锁键 IP 口径(防绕过锁定)")
+    void login_IP取数_优先XForwardedFor() throws Exception {
+        successStubs(user(700L, "admin", list("admin"), "ip", null), list("admin"));
+
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .header("X-Forwarded-For", "203.0.113.5")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"" + PHONE + "\",\"code\":\"" + CODE + "\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(loginAttemptService).isBlocked(PHONE + ":203.0.113.5");
+        verify(loginAttemptService).clearSuccess(PHONE + ":203.0.113.5");
+    }
+
+    @Test
+    @DisplayName("login:nickname 为空时 username 回退手机号,realName 保留")
+    void login_nickname为空_回退手机号() {
+        Result<Map<String, Object>> r = loginSuccess(user(800L, "admin", list("admin"), null, "实名张"), list("admin"));
+
+        assertEquals(200, r.getCode());
+        assertEquals(PHONE, r.getData().get("username"));
+        assertEquals("实名张", r.getData().get("realName"));
+        assertEquals(800L, r.getData().get("adminId"));
+    }
+
+    // ================================================================
+    // 角色 / 权限
+    // ================================================================
+
+    @Test
+    @DisplayName("login:parent 无后台角色 → 拒绝(该账号没有管理权限),HTTP 200 信封 + 业务码表达")
+    void login_parent无后台角色_拒绝() throws Exception {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode(PHONE, CODE, "admin_login")).thenReturn(true);
+        when(userMapper.selectOne(any())).thenReturn(user(900L, "parent", list("parent"), "家长", null));
+
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"" + PHONE + "\",\"code\":\"" + CODE + "\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("该账号没有管理权限"));
+
+        verify(jwtConfig, never()).generateToken(any(), anyList());
+    }
+
+    @Test
+    @DisplayName("login:roles 仅含 child(C 端)→ 拒绝")
+    void login_child角色_拒绝() {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode(PHONE, CODE, "admin_login")).thenReturn(true);
+        when(userMapper.selectOne(any())).thenReturn(user(901L, "child", list("child"), "孩子", null));
+
+        Result<Map<String, Object>> r = loginDirect(dto());
+
+        assertEquals(500, r.getCode());
+        assertEquals("该账号没有管理权限", r.getMessage());
+        verify(jwtConfig, never()).generateToken(any(), anyList());
+    }
+
+    @Test
+    @DisplayName("login:登录身份不在账号后台角色内 → 拒绝(该账号没有【X】身份)")
+    void login_loginRole非法_拒绝() {
+        successStubs(user(1000L, "admin", list("admin"), "仅管理", null), list("admin"));
+
+        Result<Map<String, Object>> r = loginDirect(dtoWithLoginRole("finance"));
+
+        assertEquals(500, r.getCode());
+        assertEquals("该账号没有【财务】身份", r.getMessage());
+        verify(jwtConfig, never()).generateToken(any(), anyList());
+    }
+
+    // ================================================================
+    // helpers
+    // ================================================================
+
+    /** 成功路径标准打桩:未锁定、验证码通过、用户命中、角色列表、token 固定值 */
+    private void successStubs(User user, List<String> roles) {
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode(PHONE, CODE, "admin_login")).thenReturn(true);
+        when(userMapper.selectOne(any())).thenReturn(user);
+        when(userService.getUserRoles(user.getId())).thenReturn(roles);
+        when(jwtConfig.generateToken(eq(user.getId()), anyList())).thenReturn("jwt-token");
+    }
+
+    /** 成功路径便捷入口:打桩 + 直接调用 login */
+    private Result<Map<String, Object>> loginSuccess(User user, List<String> roles) {
+        successStubs(user, roles);
+        return loginDirect(dto());
+    }
+
+    /** 直接调用 login(调用方自行打桩;request 为全 mock → 无转发头、remoteAddr 为 null) */
+    private Result<Map<String, Object>> loginDirect(AdminLoginDTO dto) {
+        return controller.login(dto, mock(HttpServletRequest.class));
+    }
+
+    private AdminLoginDTO dto() {
+        return dtoWithLoginRole(null);
+    }
+
+    private AdminLoginDTO dtoWithLoginRole(String loginRole) {
+        AdminLoginDTO dto = new AdminLoginDTO();
+        dto.setPhone(PHONE);
+        dto.setCode(CODE);
+        dto.setLoginRole(loginRole);
+        return dto;
+    }
+
+    private static User user(Long id, String role, List<String> roles, String nickname, String realName) {
+        User user = new User();
+        user.setId(id);
+        user.setRole(role);
+        user.setRoles(roles);
+        user.setNickname(nickname);
+        user.setRealName(realName);
+        user.setPhone(PHONE);
+        return user;
+    }
+
+    private static List<String> list(String... items) {
+        return new ArrayList<>(Arrays.asList(items));
+    }
+}

+ 250 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthControllerLoginStatusTest.java

@@ -0,0 +1,250 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.dto.AdminLoginDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.LoginAttemptService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import com.etotem.cfc.service.WechatWebLoginService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 研发负责人 B-2 / R5:POST /api/admin-auth/login 未授权/空 body/缺参不得暴露 500。
+ *
+ * <p>缺陷:空 body / 缺参原走 {@code Result.error(...)}(业务码 500,且 dto==null 会 NPE);</p>
+ *
+ * <p>契约口径(对齐项目既有惯例:控制器签名 {@code Result<T>} + HTTP 200 信封、
+ * 业务码表达语义;真实 HTTP 401 由 {@code JwtInterceptor} 对受保护路径负责,
+ * {@code /api/admin-auth/login} 为公开路径):
+ * <ul>
+ *   <li>空 body(dto==null)→ 业务码 400,无 NPE;</li>
+ *   <li>缺 code / 缺 phone / 空对象 {} → 业务码 400(参数校验);</li>
+ *   <li>正常验证码登录成功 → 业务码 200 + token/adminId/role/roles(成功路径行为不变);</li>
+ *   <li>同面公开端点 {@code send-code} / {@code login-by-password} 空 body / 缺参 → 400(同类 R5 暴露)。</li>
+ * </ul>
+ * 测试隔离:MockMvc standalone + 全 mock 依赖,无 Spring 上下文 / 无 DB。
+ */
+class AdminAuthControllerLoginStatusTest {
+
+    private AdminAuthController controller;
+    private MockMvc mockMvc;
+    private UserMapper userMapper;
+    private UserService userService;
+    private VerificationCodeService verificationCodeService;
+    private JwtConfig jwtConfig;
+    private LoginAttemptService loginAttemptService;
+    private WechatWebLoginService wechatWebLoginService;
+
+    @BeforeEach
+    void setUp() {
+        controller = new AdminAuthController();
+        userMapper = mock(UserMapper.class);
+        userService = mock(UserService.class);
+        verificationCodeService = mock(VerificationCodeService.class);
+        jwtConfig = mock(JwtConfig.class);
+        loginAttemptService = mock(LoginAttemptService.class);
+        wechatWebLoginService = mock(WechatWebLoginService.class);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        ReflectionTestUtils.setField(controller, "userService", userService);
+        ReflectionTestUtils.setField(controller, "verificationCodeService", verificationCodeService);
+        ReflectionTestUtils.setField(controller, "jwtConfig", jwtConfig);
+        ReflectionTestUtils.setField(controller, "loginAttemptService", loginAttemptService);
+        ReflectionTestUtils.setField(controller, "wechatWebLoginService", wechatWebLoginService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ---------------------------------------------------------------
+    // (a) 空 body(dto==null)→ 非 5xx / 400,无 NPE
+    // ---------------------------------------------------------------
+
+    @Test
+    @DisplayName("login:直接调用 null dto(空 body)→ 业务码 400,无 NPE,且不触达业务依赖")
+    void login_nullDto_directCall_returns400WithoutNpe() {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+
+        Result<Map<String, Object>> result = controller.login(null, request);
+
+        assertEquals(400, result.getCode());
+        assertNotNull(result.getMessage());
+        // 参数校验前置:未触达验证码/锁定/用户查询等业务依赖
+        verify(loginAttemptService, never()).isBlocked(anyString());
+        verify(verificationCodeService, never()).verifyCode(anyString(), anyString(), anyString());
+        verify(userMapper, never()).selectOne(any());
+    }
+
+    @Test
+    @DisplayName("login HTTP:空请求体 → 非 5xx(允许 200+业务码400 或框架 400),绝无 500")
+    void login_emptyBody_http_not5xx() throws Exception {
+        MvcResult mvcResult = mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON))
+                .andReturn();
+
+        int httpStatus = mvcResult.getResponse().getStatus();
+        assertTrue(httpStatus >= 200 && httpStatus < 500,
+                "空 body 不得返回 5xx,实际 HTTP " + httpStatus);
+
+        // 若返回了业务 JSON,业务码也不得为 500
+        String body = mvcResult.getResponse().getContentAsString();
+        if (body != null && !body.isEmpty()) {
+            assertFalse(body.contains("\"code\":500"), "空 body 业务码不得为 500: " + body);
+        }
+    }
+
+    // ---------------------------------------------------------------
+    // (a/b) 空对象 {} 与缺 code → 400(参数校验,非 500)
+    // ---------------------------------------------------------------
+
+    @Test
+    @DisplayName("login HTTP:空对象 {}(历史实测触发 500 的 payload)→ 业务码 400")
+    void login_emptyObject_returns400() throws Exception {
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.message").value("手机号和验证码不能为空"));
+    }
+
+    @Test
+    @DisplayName("login HTTP:缺 code → 业务码 400(参数校验)")
+    void login_missingCode_returns400() throws Exception {
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"13800000001\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.message").value("手机号和验证码不能为空"));
+    }
+
+    @Test
+    @DisplayName("login HTTP:缺 phone → 业务码 400(参数校验)")
+    void login_missingPhone_returns400() throws Exception {
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"code\":\"123456\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.message").value("手机号和验证码不能为空"));
+    }
+
+    // ---------------------------------------------------------------
+    // (c) 正常登录成功路径不受影响
+    // ---------------------------------------------------------------
+
+    @Test
+    @DisplayName("login HTTP:合法验证码登录 → 业务码 200 + token/adminId/role/roles")
+    void login_success_returnsToken() throws Exception {
+        User admin = adminUser(100L);
+        when(loginAttemptService.isBlocked(anyString())).thenReturn(false);
+        when(verificationCodeService.verifyCode("13800000001", "123456", "admin_login")).thenReturn(true);
+        when(userMapper.selectOne(any())).thenReturn(admin);
+        when(userService.getUserRoles(100L)).thenReturn(Collections.singletonList("admin"));
+        when(jwtConfig.generateToken(eq(100L), anyList())).thenReturn("jwt-token");
+
+        mockMvc.perform(post("/api/admin-auth/login")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"phone\":\"13800000001\",\"code\":\"123456\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.token").value("jwt-token"))
+                .andExpect(jsonPath("$.data.adminId").value(100))
+                .andExpect(jsonPath("$.data.username").value("nick100"))
+                .andExpect(jsonPath("$.data.role").value("admin"));
+
+        // 成功路径仍完整走验证码校验与登录尝试清零(业务逻辑不变;lockKey 格式为 phone:ip)
+        verify(verificationCodeService).verifyCode("13800000001", "123456", "admin_login");
+        verify(loginAttemptService).clearSuccess("13800000001:127.0.0.1");
+    }
+
+    // ---------------------------------------------------------------
+    // 同面公开端点:send-code / login-by-password 同类 R5 暴露(空 body/缺参 → 400)
+    // ---------------------------------------------------------------
+
+    @Test
+    @DisplayName("login-by-password:空 body(dto==null)→ 400,无 NPE")
+    void loginByPassword_nullDto_returns400() {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+
+        Result<Map<String, Object>> result = controller.loginByPassword(null, request);
+
+        assertEquals(400, result.getCode());
+        assertNotNull(result.getMessage());
+    }
+
+    @Test
+    @DisplayName("login-by-password:缺密码 → 业务码 400(参数校验)")
+    void loginByPassword_missingPassword_returns400() {
+        AdminLoginDTO dto = new AdminLoginDTO();
+        dto.setPhone("13800000001");
+
+        Result<Map<String, Object>> result = controller.loginByPassword(dto, mock(HttpServletRequest.class));
+
+        assertEquals(400, result.getCode());
+        assertEquals("用户名和密码不能为空", result.getMessage());
+    }
+
+    @Test
+    @DisplayName("send-code:空 body(dto==null)→ 400,无 NPE")
+    void sendCode_nullDto_returns400() {
+        Result<Boolean> result = controller.sendCode(null);
+
+        assertEquals(400, result.getCode());
+        assertNotNull(result.getMessage());
+    }
+
+    @Test
+    @DisplayName("send-code:缺手机号 → 业务码 400(参数校验)")
+    void sendCode_missingPhone_returns400() {
+        Result<Boolean> result = controller.sendCode(new com.etotem.cfc.dto.SendCodeDTO());
+
+        assertEquals(400, result.getCode());
+        assertEquals("手机号不能为空", result.getMessage());
+    }
+
+    // ---------------------------------------------------------------
+    // helpers
+    // ---------------------------------------------------------------
+
+    private static User adminUser(Long id) {
+        User user = new User();
+        user.setId(id);
+        user.setRole("admin");
+        user.setRoles(new ArrayList<>(Collections.singletonList("admin")));
+        user.setNickname("nick" + id);
+        user.setRealName("管理员" + id);
+        user.setPhone("13800000001");
+        return user;
+    }
+}

+ 249 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminAuthWechatScanTest.java

@@ -0,0 +1,249 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.WechatWebLoginService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 后台管理端微信扫码登录(复用小程序码扫码 SSO 的 state 机制)。
+ *
+ * <p>覆盖:二维码生成、待扫码/过期轮询、成功后签发管理端 JWT 并清除 state(防重放)、
+ * 无后台角色(parent/child)拒绝、身份不匹配拒绝。</p>
+ */
+class AdminAuthWechatScanTest {
+
+    private AdminAuthController controller;
+    private WechatWebLoginService wechatWebLoginService;
+    private UserMapper userMapper;
+    private UserService userService;
+    private JwtConfig jwtConfig;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminAuthController();
+        wechatWebLoginService = mock(WechatWebLoginService.class);
+        userMapper = mock(UserMapper.class);
+        userService = mock(UserService.class);
+        jwtConfig = mock(JwtConfig.class);
+        inject("wechatWebLoginService", wechatWebLoginService);
+        inject("userMapper", userMapper);
+        inject("userService", userService);
+        inject("jwtConfig", jwtConfig);
+    }
+
+    @Test
+    @DisplayName("wechat-scan-qr:返回非空 state,test-mode 下 qrImage 为空串")
+    void scanQr_returnsStateAndQrImage() {
+        when(wechatWebLoginService.generateQrImage(anyString())).thenReturn("");
+
+        Result<Map<String, Object>> result = controller.wechatScanQr();
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        Object state = result.getData().get("state");
+        assertNotNull(state);
+        assertTrue(state.toString().length() > 0);
+        assertEquals("", result.getData().get("qrImage"));
+        verify(wechatWebLoginService).putState(state.toString(), "P");
+    }
+
+    @Test
+    @DisplayName("wechat-scan-qr:generateQrImage 异常时清 state 并返回错误")
+    void scanQr_qrImageFailure_removesStateAndErrors() {
+        when(wechatWebLoginService.generateQrImage(anyString()))
+                .thenThrow(new RuntimeException("微信接口不可用"));
+
+        Result<Map<String, Object>> result = controller.wechatScanQr();
+
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("微信接口不可用"));
+        verify(wechatWebLoginService).removeState(anyString());
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:state=null 返回 expired")
+    void poll_stateMissing_returnsExpired() {
+        when(wechatWebLoginService.getState("s1")).thenReturn(null);
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body("s1"));
+
+        assertEquals(200, result.getCode());
+        assertEquals("expired", result.getData().get("status"));
+        verify(wechatWebLoginService, never()).removeState(anyString());
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:state=P 返回 pending")
+    void poll_pending_returnsPending() {
+        when(wechatWebLoginService.getState("s2")).thenReturn("P");
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body("s2"));
+
+        assertEquals("pending", result.getData().get("status"));
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:有后台角色 → success,返回 token/adminId/role/roles")
+    void poll_backendRole_returnsSuccessWithToken() {
+        User user = user(9L, "admin", Collections.singletonList("admin"));
+        when(wechatWebLoginService.getState("s3")).thenReturn("U9");
+        when(userMapper.selectById(9L)).thenReturn(user);
+        when(userService.getUserRoles(9L)).thenReturn(Collections.singletonList("admin"));
+        when(jwtConfig.generateToken(eq(9L), anyList())).thenReturn("jwt-token");
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body("s3"));
+
+        assertEquals(200, result.getCode());
+        Map<String, Object> data = result.getData();
+        assertEquals("success", data.get("status"));
+        assertEquals("jwt-token", data.get("token"));
+        assertEquals(9L, data.get("adminId"));
+        assertEquals("admin", data.get("role"));
+        assertEquals(Collections.singletonList("admin"), data.get("roles"));
+        assertEquals("管理员9", data.get("realName"));
+        // 成功后 state 清除,防重放
+        verify(wechatWebLoginService).removeState("s3");
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:parent 无后台角色 → error 且不签发 token")
+    void poll_clientRole_returnsError() {
+        User user = user(18L, "parent", Collections.singletonList("parent"));
+        when(wechatWebLoginService.getState("s4")).thenReturn("U18");
+        when(userMapper.selectById(18L)).thenReturn(user);
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body("s4"));
+
+        Map<String, Object> data = result.getData();
+        assertEquals("error", data.get("status"));
+        assertEquals("该账号没有管理权限", data.get("message"));
+        assertNull(data.get("token"));
+        verify(jwtConfig, never()).generateToken(any(Long.class), anyList());
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:child 无后台角色(roles 为空)→ error")
+    void poll_childRole_returnsError() {
+        User user = user(19L, "child", null);
+        when(wechatWebLoginService.getState("s5")).thenReturn("U19");
+        when(userMapper.selectById(19L)).thenReturn(user);
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body("s5"));
+
+        assertEquals("error", result.getData().get("status"));
+        assertEquals("该账号没有管理权限", result.getData().get("message"));
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:指定 loginRole 命中多角色 → token role 为选中身份")
+    void poll_multiRoleWithSelectedRole_usesSelected() {
+        User user = user(20L, "teacher", Arrays.asList("teacher", "org_admin"));
+        when(wechatWebLoginService.getState("s6")).thenReturn("U20");
+        when(userMapper.selectById(20L)).thenReturn(user);
+        when(userService.getUserRoles(20L)).thenReturn(Arrays.asList("teacher", "org_admin"));
+        when(jwtConfig.generateToken(eq(20L), anyList())).thenReturn("jwt-org");
+
+        Map<String, String> body = body("s6");
+        body.put("loginRole", "org_admin");
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body);
+
+        assertEquals("success", result.getData().get("status"));
+        assertEquals("org_admin", result.getData().get("role"));
+        assertEquals("jwt-org", result.getData().get("token"));
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:指定 loginRole 不在账号角色内 → error")
+    void poll_selectedRoleNotOwned_returnsError() {
+        User user = user(21L, "teacher", Collections.singletonList("teacher"));
+        when(wechatWebLoginService.getState("s7")).thenReturn("U21");
+        when(userMapper.selectById(21L)).thenReturn(user);
+
+        Map<String, String> body = body("s7");
+        body.put("loginRole", "admin");
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body);
+
+        assertEquals("error", result.getData().get("status"));
+        assertEquals("该账号没有【超级管理员】身份", result.getData().get("message"));
+        verify(jwtConfig, never()).generateToken(any(Long.class), anyList());
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:成功后再次轮询同 state → expired(防重放)")
+    void poll_afterSuccess_stateCleared() {
+        User user = user(22L, "admin", Collections.singletonList("admin"));
+        when(wechatWebLoginService.getState("s8")).thenReturn("U22").thenReturn(null);
+        when(userMapper.selectById(22L)).thenReturn(user);
+        when(userService.getUserRoles(22L)).thenReturn(Collections.singletonList("admin"));
+        when(jwtConfig.generateToken(eq(22L), anyList())).thenReturn("jwt-2");
+
+        Result<Map<String, Object>> first = controller.wechatScanPoll(body("s8"));
+        Result<Map<String, Object>> second = controller.wechatScanPoll(body("s8"));
+
+        assertEquals("success", first.getData().get("status"));
+        assertEquals("expired", second.getData().get("status"));
+        verify(wechatWebLoginService).removeState("s8");
+    }
+
+    @Test
+    @DisplayName("wechat-scan-poll:缺少 state 返回错误提示")
+    void poll_blankState_returnsError() {
+        Map<String, String> body = new HashMap<>();
+        body.put("state", " ");
+
+        Result<Map<String, Object>> result = controller.wechatScanPoll(body);
+
+        assertEquals(500, result.getCode());
+        assertEquals("缺少 state", result.getMessage());
+    }
+
+    private static Map<String, String> body(String state) {
+        Map<String, String> body = new HashMap<>();
+        body.put("state", state);
+        return body;
+    }
+
+    private static User user(Long id, String role, List<String> roles) {
+        User user = new User();
+        user.setId(id);
+        user.setRole(role);
+        user.setRoles(roles == null ? null : new ArrayList<>(roles));
+        user.setNickname("nick" + id);
+        user.setRealName("管理员" + id);
+        user.setPhone("1380000" + id);
+        return user;
+    }
+
+    private void inject(String fieldName, Object value) throws Exception {
+        Field field = AdminAuthController.class.getDeclaredField(fieldName);
+        field.setAccessible(true);
+        field.set(controller, value);
+    }
+}

+ 139 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminButlerControllerEnvelopeTest.java

@@ -0,0 +1,139 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ButlerCommissionSettlement;
+import com.etotem.cfc.entity.ButlerProfile;
+import com.etotem.cfc.entity.ButlerServiceRecord;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ButlerCommissionSettlementMapper;
+import com.etotem.cfc.mapper.ButlerProfileMapper;
+import com.etotem.cfc.mapper.ButlerServiceRecordMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * B-4/F1 契约级单测:管理端管家列表 envelope 必须为 data.records(与其他管理端列表统一),
+ * 不再返回 data.list。覆盖 user-list / list / service-records / settlements 四个列表方法。
+ *
+ * 背景:自动化测试断言 j.data.records,butler 接口此前返回 data.list 导致取空崩溃(F1)。
+ */
+public class AdminButlerControllerEnvelopeTest {
+
+    private AdminButlerController controller;
+    private ButlerService butlerService;
+    private ButlerProfileMapper butlerProfileMapper;
+    private ButlerServiceRecordMapper butlerServiceRecordMapper;
+    private ButlerCommissionSettlementMapper butlerCommissionSettlementMapper;
+    private UserMapper userMapper;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new AdminButlerController();
+        butlerService = mock(ButlerService.class);
+        butlerProfileMapper = mock(ButlerProfileMapper.class);
+        butlerServiceRecordMapper = mock(ButlerServiceRecordMapper.class);
+        butlerCommissionSettlementMapper = mock(ButlerCommissionSettlementMapper.class);
+        userMapper = mock(UserMapper.class);
+        ReflectionTestUtils.setField(controller, "butlerService", butlerService);
+        ReflectionTestUtils.setField(controller, "butlerProfileMapper", butlerProfileMapper);
+        ReflectionTestUtils.setField(controller, "butlerServiceRecordMapper", butlerServiceRecordMapper);
+        ReflectionTestUtils.setField(controller, "butlerCommissionSettlementMapper", butlerCommissionSettlementMapper);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+    }
+
+    private Map<String, Object> baseParams() {
+        Map<String, Object> p = new HashMap<>();
+        p.put("page", 1);
+        p.put("size", 10);
+        return p;
+    }
+
+    private void assertRecordsEnvelope(Result<Map<String, Object>> r, int expectTotal) {
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData(), "data 不能为 null");
+        assertNotNull(r.getData().get("records"), "列表 envelope 必须包含 data.records");
+        assertNull(r.getData().get("list"), "列表 envelope 不得再返回 data.list(契约统一为 records)");
+        assertEquals(expectTotal, ((Number) r.getData().get("total")).longValue());
+    }
+
+    @Test
+    public void userList_returnsRecordsEnvelope() {
+        Page<User> page = new Page<>(1, 10);
+        User u = new User();
+        u.setId(1001L);
+        u.setNickname("管家A");
+        u.setButlerStatus("pending");
+        page.setRecords(java.util.Collections.singletonList(u));
+        page.setTotal(1);
+        when(userMapper.selectPage(any(Page.class), any())).thenReturn(page);
+
+        Map<String, Object> params = baseParams();
+        params.put("status", "pending");
+        Result<Map<String, Object>> r = controller.userList(params, "admin");
+        assertRecordsEnvelope(r, 1);
+    }
+
+    @Test
+    public void list_returnsRecordsEnvelope() {
+        Page<ButlerProfile> page = new Page<>(1, 10);
+        ButlerProfile bp = new ButlerProfile();
+        bp.setId(2001L);
+        bp.setUserId(1001L);
+        bp.setTier("L1");
+        bp.setStatus("pending");
+        page.setRecords(java.util.Collections.singletonList(bp));
+        page.setTotal(1);
+        when(butlerProfileMapper.selectPage(any(Page.class), any())).thenReturn(page);
+
+        Map<String, Object> params = baseParams();
+        params.put("status", "pending");
+        Result<Map<String, Object>> r = controller.list(params, "admin");
+        assertRecordsEnvelope(r, 1);
+        assertEquals(1, ((Number) r.getData().get("page")).intValue());
+        assertEquals(10, ((Number) r.getData().get("size")).intValue());
+    }
+
+    @Test
+    public void serviceRecords_returnsRecordsEnvelope() {
+        Page<ButlerServiceRecord> page = new Page<>(1, 10);
+        ButlerServiceRecord rec = new ButlerServiceRecord();
+        rec.setId(3001L);
+        rec.setServiceType("annual");
+        rec.setCreatedAt(new Date());
+        page.setRecords(java.util.Collections.singletonList(rec));
+        page.setTotal(1);
+        when(butlerServiceRecordMapper.selectPage(any(Page.class), any())).thenReturn(page);
+
+        Result<Map<String, Object>> r = controller.serviceRecords(baseParams(), "admin");
+        assertRecordsEnvelope(r, 1);
+    }
+
+    @Test
+    public void settlements_returnsRecordsEnvelope() {
+        Page<ButlerCommissionSettlement> page = new Page<>(1, 10);
+        ButlerCommissionSettlement s = new ButlerCommissionSettlement();
+        s.setId(4001L);
+        s.setStatus("settled");
+        page.setRecords(java.util.Collections.singletonList(s));
+        page.setTotal(1);
+        when(butlerCommissionSettlementMapper.selectPage(any(Page.class), any())).thenReturn(page);
+
+        Result<Map<String, Object>> r = controller.settlements(baseParams(), "admin");
+        assertRecordsEnvelope(r, 1);
+    }
+}

+ 128 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminCommissionConfigControllerTest.java

@@ -0,0 +1,128 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.RebateCommissionConfig;
+import com.etotem.cfc.mapper.RebateCommissionConfigMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+/**
+ * B-4/F2 契约级单测:POST /api/admin/commission/config/update
+ *  - 合法 body(必填 name 齐全)→ 200 且真实落库(insert/updateById 被调用、时间戳写入)
+ *  - 缺必填(name 缺失/空白)→ 400 且 message 有解释(绝不 500)
+ *  - 空请求体 → 400 且 message 有解释
+ *
+ * 背景:E2E 曾返回 400 —— payload 字段与实体不匹配(percent/ratio/label/status 非实体字段),
+ * 导致 name(表 NOT NULL)缺失 → 插入触发数据完整性异常返回 400。修复后:
+ * 先明确校验必填字段给出业务 400;合法 body 才走 insert/updateById。
+ */
+public class AdminCommissionConfigControllerTest {
+
+    private AdminCommissionConfigController controller;
+    private RebateCommissionConfigMapper rebateCommissionConfigMapper;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new AdminCommissionConfigController();
+        rebateCommissionConfigMapper = mock(RebateCommissionConfigMapper.class);
+        ReflectionTestUtils.setField(controller, "rebateCommissionConfigMapper", rebateCommissionConfigMapper);
+    }
+
+    @Test
+    public void updateConfig_validBodyWithoutId_insertsAndReturns200() {
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        config.setName("e2e-佣金配置");
+        config.setRate(10);
+        config.setRateType(1);
+        config.setRemark("up");
+
+        Result<String> r = controller.updateConfig(config);
+
+        assertEquals(200, r.getCode());
+        ArgumentCaptor<RebateCommissionConfig> captor = ArgumentCaptor.forClass(RebateCommissionConfig.class);
+        verify(rebateCommissionConfigMapper, times(1)).insert(captor.capture());
+        assertEquals("e2e-佣金配置", captor.getValue().getName());
+        assertEquals(10, captor.getValue().getRate());
+        assertNotNull(captor.getValue().getCreatedAt(), "insert 必须写入 createdAt");
+        assertNotNull(captor.getValue().getUpdatedAt(), "insert 必须写入 updatedAt");
+        verify(rebateCommissionConfigMapper, never()).updateById(any());
+    }
+
+    @Test
+    public void updateConfig_validBodyWithId_updatesAndReturns200() {
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        config.setId(42L);
+        config.setName("e2e-更新配置");
+        config.setRate(15);
+
+        Result<String> r = controller.updateConfig(config);
+
+        assertEquals(200, r.getCode());
+        ArgumentCaptor<RebateCommissionConfig> captor = ArgumentCaptor.forClass(RebateCommissionConfig.class);
+        verify(rebateCommissionConfigMapper, times(1)).updateById(captor.capture());
+        assertEquals(42L, captor.getValue().getId());
+        assertEquals(15, captor.getValue().getRate());
+        assertNotNull(captor.getValue().getUpdatedAt(), "update 必须写入 updatedAt");
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+    }
+
+    @Test
+    public void updateConfig_missingRequiredName_returns400WithMessage() {
+        // id 为空 → insert 分支;name 为必填缺失 → 400 业务提示,绝不可 500
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        Result<String> r = controller.updateConfig(config);
+
+        assertEquals(400, r.getCode());
+        assertNotNull(r.getMessage());
+        assertFalse(r.getMessage().isEmpty());
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+        verify(rebateCommissionConfigMapper, never()).updateById(any());
+
+        // 空白 name 同样拒绝
+        RebateCommissionConfig blank = new RebateCommissionConfig();
+        blank.setName("   ");
+        Result<String> r2 = controller.updateConfig(blank);
+        assertEquals(400, r2.getCode());
+        assertNotNull(r2.getMessage());
+        assertFalse(r2.getMessage().isEmpty());
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+        verify(rebateCommissionConfigMapper, never()).updateById(any());
+    }
+
+    @Test
+    public void updateConfig_nullBody_returns400WithMessage() {
+        Result<String> r = controller.updateConfig(null);
+
+        assertEquals(400, r.getCode());
+        assertNotNull(r.getMessage());
+        assertFalse(r.getMessage().isEmpty());
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+        verify(rebateCommissionConfigMapper, never()).updateById(any());
+    }
+
+    @Test
+    public void updateConfig_ignoredUnknownFields_reverseContractPinned() {
+        // 固定反面契约:与实体不匹配的历史 payload(label/percent 等)序列化进实体时
+        // 只映射实体字段,其余被忽略;name 缺失仍被业务校验拦截为 400(这正是线上 400 的根因形态)。
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        config.setRate(10);
+        config.setRemark("up");
+        // 模拟旧 E2E payload 只填 remark/rate、缺 name 的情况
+        Result<String> r = controller.updateConfig(config);
+        assertEquals(400, r.getCode());
+        assertTrue(r.getMessage().contains("name"), "message 应指明缺失的必填字段 name");
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+    }
+}

+ 69 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminCommissionConfigPartialUpdateTest.java

@@ -0,0 +1,69 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.RebateCommissionConfig;
+import com.etotem.cfc.mapper.RebateCommissionConfigMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+/**
+ * B-4/F2 契约级单测:POST /api/admin/commission/config/update 局部更新语义。
+ *
+ * <p>name 是 rebate_commission_config.name 的 NOT NULL 列,只在新增(id 为空)时必填;
+ * 按 id 更新走 updateById(null 字段不参与 SET),因此仅提交 rate/remark 的局部更新
+ * 必须返回 200,而不是 400。
+ */
+public class AdminCommissionConfigPartialUpdateTest {
+
+    private AdminCommissionConfigController controller;
+    private RebateCommissionConfigMapper rebateCommissionConfigMapper;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new AdminCommissionConfigController();
+        rebateCommissionConfigMapper = mock(RebateCommissionConfigMapper.class);
+        ReflectionTestUtils.setField(controller, "rebateCommissionConfigMapper", rebateCommissionConfigMapper);
+    }
+
+    @Test
+    public void updateConfig_idWithoutName_partialUpdateReturns200() {
+        // 旧管理端局部更新 payload:只带 id + rate + remark,不含 name
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        config.setId(42L);
+        config.setRate(12);
+        config.setRemark("仅调整比例");
+
+        Result<String> r = controller.updateConfig(config);
+
+        assertEquals(200, r.getCode(), "按 id 局部更新不应因缺 name 返回 400");
+        ArgumentCaptor<RebateCommissionConfig> captor = ArgumentCaptor.forClass(RebateCommissionConfig.class);
+        verify(rebateCommissionConfigMapper, times(1)).updateById(captor.capture());
+        assertEquals(42L, captor.getValue().getId());
+        assertEquals(12, captor.getValue().getRate());
+        assertNotNull(captor.getValue().getUpdatedAt(), "update 必须写入 updatedAt");
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+    }
+
+    @Test
+    public void updateConfig_idWithBlankName_stillRejectedAs400() {
+        RebateCommissionConfig config = new RebateCommissionConfig();
+        config.setId(42L);
+        config.setName("   ");
+
+        Result<String> r = controller.updateConfig(config);
+
+        assertEquals(400, r.getCode());
+        verify(rebateCommissionConfigMapper, never()).updateById(any());
+        verify(rebateCommissionConfigMapper, never()).insert(any());
+    }
+}

+ 93 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminFamilyOverviewControllerTest.java

@@ -0,0 +1,93 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.dto.FamilyOverviewDTO;
+import com.etotem.cfc.service.FamilyAdminOverviewService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约单测:家庭运营工作台后端接口(需求 FAMILY-WB-2026-11-13-V1 §S3-1)。
+ * 仅校验 {@link AdminFamilyOverviewController} 的路由 / 权限门 / 委派,不依赖数据库
+ * (standalone MockMvc + mock service,可在无 DB 的 review 档离线运行)。
+ *
+ * <p><b>R206 装置对齐(B-206-3)</b>:原用例把 {@code cfService(CfBalanceService)} /
+ * {@code messageService(TeacherMessageService)} 注入控制器,并断言
+ * {@code /families/{id}/cf-summary}、{@code /families/{id}/messages} 两个端点。
+ * 实测控制器已重构为单一依赖 {@code service(FamilyAdminOverviewService)},端点只剩
+ * {@code /families/{id}/overview} 与 {@code /families/{id}/tasks} ——
+ * 原 3 例全部 {@code IllegalArgumentException: Could not find field 'cfService'},
+ * 即「家庭运营工作台契约」自合入起<b>从未真正执行过</b>(假覆盖)。
+ * 本版按当前控制器契约重写,并把「越权不委派」作为断言重点。
+ */
+public class AdminFamilyOverviewControllerTest {
+
+    @Mock
+    private FamilyAdminOverviewService service;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        AdminFamilyOverviewController controller = new AdminFamilyOverviewController();
+        ReflectionTestUtils.setField(controller, "service", service);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    @DisplayName("TC-FW-B01 admin 调用 /overview 委派 buildOverview 并返回 code=200")
+    public void overview_adminRole_delegatesToService() throws Exception {
+        FamilyOverviewDTO dto = new FamilyOverviewDTO();
+        when(service.buildOverview(12L)).thenReturn(dto);
+
+        mockMvc.perform(post("/api/admin/families/12/overview")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(service).buildOverview(12L);
+    }
+
+    @Test
+    @DisplayName("TC-FW-B02 非 admin 调用 /overview 返回「无权限」且不委派(防越权读单家庭数据)")
+    public void overview_nonAdminRole_rejected() throws Exception {
+        mockMvc.perform(post("/api/admin/families/12/overview")
+                        .requestAttr("role", "teacher")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("无权限"));
+
+        verify(service, never()).buildOverview(anyLong());
+    }
+
+    @Test
+    @DisplayName("TC-FW-B03 非 admin 调用 /tasks 返回「无权限」且不委派")
+    public void tasks_nonAdminRole_rejected() throws Exception {
+        mockMvc.perform(post("/api/admin/families/12/tasks")
+                        .requestAttr("role", "parent")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"page\":1,\"size\":10}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("无权限"));
+
+        verify(service, never()).pageTasks(anyLong(), anyLong(), anyLong());
+    }
+}

+ 150 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminFamilyStatsContractTest.java

@@ -0,0 +1,150 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.FamilyAdminStatsDTO;
+import com.etotem.cfc.service.FamilyAdminStatsService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * R142 SRS 变更契约测试:窗口合入新增接口 {@code POST /api/admin/families/stats}
+ * (家庭运营工作台全局聚合统计,AdminFamilyStatsController,提交 8f9b29a42/cbe6dae1b)。
+ *
+ * <p>SRS 口径(API_REFERENCE.md §4.60 家庭运营段):
+ * <ol>
+ *   <li>仅平台角色(hasAnyPlatformRole / admin / operator / finance,与 /families 的 platform 判定一致)
+ *       返回全局聚合;</li>
+ *   <li>非平台角色返回 {@code Result.success(null)}(非 error,前端降级「本页合计」);</li>
+ *   <li>返回 {@code Result<FamilyAdminStatsDTO>}:familyCount/memberCount(active)/reportCount/planCount/
+ *       taskCount/couponCount/monthReportCount/earningsAmount(null)。</li>
+ * </ol>
+ *
+ * <p>风格与 AdminFamilyOverviewControllerTest / AdminReferralContractTest 一致:mock Service + 反射注入,直接调用。
+ * 无 Spring 上下文、无数据库依赖,离线可跑。
+ */
+class AdminFamilyStatsContractTest {
+
+    private AdminFamilyStatsController controller;
+    private FamilyAdminStatsService svc;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminFamilyStatsController();
+        svc = mock(FamilyAdminStatsService.class);
+        Field f = AdminFamilyStatsController.class.getDeclaredField("familyAdminStatsService");
+        f.setAccessible(true);
+        f.set(controller, svc);
+    }
+
+    private static FamilyAdminStatsDTO dto() {
+        FamilyAdminStatsDTO d = new FamilyAdminStatsDTO();
+        d.setFamilyCount(100L);
+        d.setMemberCount(300L);
+        d.setReportCount(500L);
+        d.setPlanCount(200L);
+        d.setTaskCount(400L);
+        d.setCouponCount(50L);
+        d.setMonthReportCount(30L);
+        d.setEarningsAmount(null);
+        return d;
+    }
+
+    // ==================== 权限门:非平台角色一律 success(null),不得越权取数 ====================
+
+    @Test
+    void stats_纯C端角色parent返回successNull() {
+        Result<FamilyAdminStatsDTO> r = controller.stats("parent", Collections.singletonList("parent"));
+        assertEquals(200, r.getCode());
+        assertNull(r.getData());
+        verify(svc, never()).buildStats();
+    }
+
+    @Test
+    void stats_roleList含child且role为null返回successNull() {
+        Result<FamilyAdminStatsDTO> r = controller.stats(null, Collections.singletonList("child"));
+        assertEquals(200, r.getCode());
+        assertNull(r.getData());
+        verify(svc, never()).buildStats();
+    }
+
+    @Test
+    void stats_匿名双null返回successNull() {
+        Result<FamilyAdminStatsDTO> r = controller.stats(null, null);
+        assertEquals(200, r.getCode());
+        assertNull(r.getData());
+        verify(svc, never()).buildStats();
+    }
+
+    @Test
+    void stats_非平台后台角色teacher返回successNull() {
+        Result<FamilyAdminStatsDTO> r = controller.stats("teacher", Collections.singletonList("teacher"));
+        assertEquals(200, r.getCode());
+        assertNull(r.getData());
+        verify(svc, never()).buildStats();
+    }
+
+    // ==================== 平台角色:返回聚合且调用 buildStats ====================
+
+    @Test
+    void stats_roleAdmin返回聚合() {
+        when(svc.buildStats()).thenReturn(dto());
+        Result<FamilyAdminStatsDTO> r = controller.stats("admin", Collections.singletonList("admin"));
+        assertEquals(200, r.getCode());
+        FamilyAdminStatsDTO d = r.getData();
+        assertNotNull(d);
+        assertEquals(100L, d.getFamilyCount());
+        assertEquals(300L, d.getMemberCount());
+        assertEquals(500L, d.getReportCount());
+        assertEquals(200L, d.getPlanCount());
+        assertEquals(400L, d.getTaskCount());
+        assertEquals(50L, d.getCouponCount());
+        assertEquals(30L, d.getMonthReportCount());
+        assertNull(d.getEarningsAmount()); // SRS:本轮恒为 null(家庭总收益口径未定)
+        verify(svc).buildStats();
+    }
+
+    @Test
+    void stats_roleList含operator返回聚合() {
+        when(svc.buildStats()).thenReturn(dto());
+        List<String> roles = Arrays.asList("operator", "parent");
+        Result<FamilyAdminStatsDTO> r = controller.stats("operator", roles);
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+        verify(svc).buildStats();
+    }
+
+    @Test
+    void stats_roleList含finance返回聚合() {
+        when(svc.buildStats()).thenReturn(dto());
+        Result<FamilyAdminStatsDTO> r = controller.stats("finance", Collections.singletonList("finance"));
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+        verify(svc).buildStats();
+    }
+
+    @Test
+    void stats_roleList含platform角色但role为null仍放行() {
+        when(svc.buildStats()).thenReturn(dto());
+        // hasAnyPlatformRole(roles) 为 true 即放行(controller 用 `||` 组合,platform 优先)
+        Result<FamilyAdminStatsDTO> r = controller.stats(null, Collections.singletonList("admin"));
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+        verify(svc).buildStats();
+    }
+
+    // ==================== 服务层异常透传(不吞错) ====================
+
+    @Test
+    void stats_服务异常向上抛出() {
+        when(svc.buildStats()).thenThrow(new RuntimeException("db down"));
+        assertThrows(RuntimeException.class, () -> controller.stats("admin", Collections.singletonList("admin")));
+    }
+}

+ 548 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminOrderManualContractTest.java

@@ -0,0 +1,548 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.dto.ProductOrderDTO;
+import com.etotem.cfc.entity.AfterSalesRequest;
+import com.etotem.cfc.service.AfterSalesService;
+import com.etotem.cfc.service.ProductOrderService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentMatchers;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:订单/退款人工处理(能力键 {@code admin.order.manual},SC-A-12)。
+ *
+ * <p><b>溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-A-12(订单/退款人工处理——
+ *       查订单 → 手动退款/补发,边界:重复退款拦截、留审计)</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.13(管理员接口需 {@code role=admin})与
+ *       §4.60.12(`AdminProductOrderController` `/api/admin/product/order`:list/detail/ship/
+ *       update-express/close/refund/approve|reject;`AdminAfterSalesController`
+ *       `/api/admin/shop/after-sales`:list/detail/review/complete)</li>
+ *   <li>契约补建:{@code docs/tdd/orchestration/admin-ops-kickoff-20261107.md} TR-13 /
+ *       {@code docs/superpowers/specs/2026-11-07-admin-ops-contract.md} §2 能力键映射
+ *       {@code admin.order.manual}(✅ 端点存在)+ §5:「补 admin 端点 MockMvc 契约 JUnit +
+ *       <b>非 admin token → 403 权限流</b>(重点)」;任务登记 S-cfc-202
+ *       (sc-key-map.md,RED / 未跑通)</li>
+ * </ul>
+ *
+ * <p><b>实现现状(origin/cfclub @ 7558d8cf4 实测)</b></p>
+ * <ul>
+ *   <li>正常流/边界流已实现:两个控制器端点齐全并委托 service;service 层已含
+ *       重复退款拦截、售后状态守卫(仅 pending 可审核 / 仅 approved 可完成)。</li>
+ *   <li><b>权限流未落地(本测试的红)</b>:参照 B-142-1 惯例({@code AdminArticleController#create}
+ *       的「无权限」守卫),管理端端点应声明 {@code @RequestAttribute("role")} 并在入口拒绝非 admin
+ *       ({@code !"admin".equals(role) → Result.error("无权限")});当前
+ *       {@code AdminProductOrderController}(除 list 外 6 个端点)与
+ *       {@code AdminAfterSalesController}(全部 4 个端点)均<em>无角色守卫</em>,登录的
+ *       parent/child/teacher 可越权发货/关单/审批退款/处理售后。框架层(JwtInterceptor
+ *       LOGIN_REQUIRED_PATHS 已收口 {@code /api/admin/})仅保证「匿名→401」,不区分角色。</li>
+ * </ul>
+ *
+ * <p><b>三流划分</b></p>
+ * <ul>
+ *   <li>正常流(已实现 → 绿锁定契约):端点映射齐全 + 委托 service(list/detail/ship/
+ *       update-express/close/refund-approve/refund-reject;售后 list/detail/review/complete)。</li>
+ *   <li>边界流(已实现 → 绿锁定契约):售后 review 状态守卫(非 pending 拒绝、无效 action 拒绝)、
+ *       complete 状态守卫(仅 approved 可完成);订单重复退款拦截既有契约覆盖见
+ *       {@code OrderRefundScP56ScA12ContractTest}。</li>
+ *   <li>权限流(契约缺口 → <b>预期红</b>):订单 6 端点 + 售后 4 端点缺 admin 角色守卫;
+ *       list 非 admin(roles=[parent])应 403 且不委托;refund/approve、售后 review
+ *       非 admin 应「无权限」且不委托。</li>
+ * </ul>
+ *
+ * <p><b>RED 预期</b>:权限流 5 例失败(红),断言原文含「RED[admin.order.manual]」,失败原因可贴
+ * (角色守卫参数缺失 / list 被非 admin 放行 / refund/approve 与 review 被非 admin 执行)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:按 B-142-1 惯例为上述 10 个端点增加
+ * {@code @RequestAttribute("role") String role}(list 保留 {@code @RequestAttribute("roles")}
+ * 并放行平台角色/供应商),入口 {@code !"admin".equals(role) → Result.error("无权限")};
+ * 实现后本测试自动转绿。</p>
+ *
+ * <p><b>测试范围</b>:纯契约级单测(Mockito + 反射),无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class AdminOrderManualContractTest {
+
+    /** 订单人工处理全端点(相对 {@code /api/admin/product/order}) */
+    private static final List<String> ORDER_ENDPOINTS = Arrays.asList(
+            "list", "detail", "ship", "update-express", "close", "refund/approve", "refund/reject");
+
+    /** 订单端点上应声明角色守卫参数的端点(list 已有 @RequestAttribute("roles"),属既有载体) */
+    private static final List<String> ORDER_ENDPOINTS_NEED_ROLE_GUARD = Arrays.asList(
+            "detail", "ship", "update-express", "close", "refund/approve", "refund/reject");
+
+    /** 售后人工处理全端点(相对 {@code /api/admin/shop/after-sales}) */
+    private static final List<String> AFTER_SALES_ENDPOINTS = Arrays.asList(
+            "list", "detail", "review", "complete");
+
+    private AdminProductOrderController orderController;
+    private AdminAfterSalesController afterSalesController;
+    private ProductOrderService orderService;
+    private AfterSalesService afterSalesService;
+
+    /** 边界流:真实 AfterSalesService + mock mapper(售后状态守卫绿锚点) */
+    private AfterSalesService realAfterSalesService;
+    private com.etotem.cfc.mapper.AfterSalesRequestMapper afterSalesRequestMapper;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        orderController = new AdminProductOrderController();
+        afterSalesController = new AdminAfterSalesController();
+        orderService = mock(ProductOrderService.class);
+        afterSalesService = mock(AfterSalesService.class);
+        setField(orderController, "orderService", orderService);
+        setField(afterSalesController, "afterSalesService", afterSalesService);
+
+        realAfterSalesService = new AfterSalesService();
+        afterSalesRequestMapper = mock(com.etotem.cfc.mapper.AfterSalesRequestMapper.class);
+        setField(realAfterSalesService, "afterSalesRequestMapper", afterSalesRequestMapper);
+        setField(realAfterSalesService, "productOrderMapper",
+                mock(com.etotem.cfc.mapper.ProductOrderMapper.class));
+
+        // 正常流委托桩:各 service 方法返回成功
+        // 注意:list 的 keyword/buyerKeyword/startDate/endDate 可为 null,
+        // 桩须用 any()(可匹配 null)而非 anyString(),否则返回 null → 断言 NPE
+        when(orderService.adminOrderPage(anyInt(), anyInt(), any(), any(),
+                any(), any(), any(), any(), any()))
+                .thenReturn(Result.success(new HashMap<String, Object>()));
+        when(orderService.adminOrderDetail(anyString()))
+                .thenReturn(Result.success(new ProductOrderDTO()));
+        when(orderService.ship(anyString(), anyString(), anyString(), anyString(), anyInt(), anyString()))
+                .thenReturn(Result.success("已发货"));
+        when(orderService.updateExpress(anyString(), anyString(), anyString(), anyInt()))
+                .thenReturn(Result.success("快递信息已更新"));
+        when(orderService.adminClose(anyString(), anyLong()))
+                .thenReturn(Result.success("订单已关闭"));
+        when(orderService.approveRefund(anyString(), anyLong()))
+                .thenReturn(Result.success("退款已处理"));
+        when(orderService.rejectRefund(anyString(), anyLong(), anyString()))
+                .thenReturn(Result.success("已拒绝退款申请"));
+        when(afterSalesService.adminList(any()))
+                .thenReturn(Result.success(new ArrayList<AfterSalesRequest>()));
+        when(afterSalesService.adminDetail(any()))
+                .thenReturn(Result.success(new AfterSalesRequest()));
+        when(afterSalesService.review(any(), any(), any(), anyLong()))
+                .thenReturn(Result.success("操作成功"));
+        when(afterSalesService.complete(any()))
+                .thenReturn(Result.success("已完成"));
+    }
+
+    // ==================== 正常流:端点映射齐全(绿锚点) ====================
+
+    @Test
+    @DisplayName("正常流-1:订单人工处理 7 端点映射齐全(list/detail/ship/update-express/close/refund/approve|reject)")
+    void 正常流_订单端点映射齐全() {
+        Set<String> paths = endpointPaths(AdminProductOrderController.class);
+        assertTrue(paths.containsAll(ORDER_ENDPOINTS),
+                "[admin.order.manual] AdminProductOrderController 应提供契约端点映射:"
+                        + ORDER_ENDPOINTS + ",实际:" + paths);
+    }
+
+    @Test
+    @DisplayName("正常流-2:售后人工处理 4 端点映射齐全(list/detail/review/complete)")
+    void 正常流_售后端点映射齐全() {
+        Set<String> paths = endpointPaths(AdminAfterSalesController.class);
+        assertTrue(paths.containsAll(AFTER_SALES_ENDPOINTS),
+                "[admin.order.manual] AdminAfterSalesController 应提供契约端点映射:"
+                        + AFTER_SALES_ENDPOINTS + ",实际:" + paths);
+    }
+
+    // ==================== 正常流:订单端点委托 service(绿锚点) ====================
+
+    @Test
+    @DisplayName("正常流-3:order/list 委托 orderService.adminOrderPage(分页/筛选/供应商行级隔离参数)")
+    void 正常流_订单list_委托adminOrderPage() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("status", "paid");
+        body.put("page", 1);
+        body.put("size", 20);
+        Result<Map<String, Object>> r =
+                orderController.list(body, 1L, Collections.singletonList("admin"));
+        assertEquals(200, r.getCode());
+        // 注意:keyword/buyerKeyword/startDate/endDate 为 null,verify 须用 any()(可匹配 null)
+        verify(orderService).adminOrderPage(anyInt(), anyInt(), any(), any(),
+                any(), any(), any(), any(), any());
+    }
+
+    @Test
+    @DisplayName("正常流-4:order/detail 委托 orderService.adminOrderDetail(orderNo)")
+    void 正常流_订单detail_委托adminOrderDetail() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO1");
+        Result<ProductOrderDTO> r = orderController.detail(body);
+        assertEquals(200, r.getCode());
+        verify(orderService).adminOrderDetail("PO1");
+    }
+
+    @Test
+    @DisplayName("正常流-5:order/ship 委托 orderService.ship(发货方式/单号/公司/快递费/联系人六参)")
+    void 正常流_订单ship_委托ship() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO1");
+        body.put("shipType", "express");
+        body.put("trackingNumber", "SF123456");
+        body.put("expressCompany", "顺丰速运");
+        body.put("shippingCost", 1000);
+        body.put("receiverContact", "13800000000");
+        Result<String> r = orderController.ship(body, 1L);
+        assertEquals(200, r.getCode());
+        verify(orderService).ship("PO1", "express", "SF123456", "顺丰速运", 1000, "13800000000");
+    }
+
+    @Test
+    @DisplayName("正常流-6:order/update-express 委托 orderService.updateExpress")
+    void 正常流_订单updateExpress_委托() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO1");
+        body.put("trackingNumber", "YT111");
+        body.put("expressCompany", "圆通速递");
+        body.put("shippingCost", 800);
+        Result<String> r = orderController.updateExpress(body);
+        assertEquals(200, r.getCode());
+        verify(orderService).updateExpress("PO1", "YT111", "圆通速递", 800);
+    }
+
+    @Test
+    @DisplayName("正常流-7:order/close 委托 orderService.adminClose(orderNo, adminId)")
+    void 正常流_订单close_委托adminClose() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO9");
+        Result<String> r = orderController.close(body, 1L);
+        assertEquals(200, r.getCode());
+        verify(orderService).adminClose("PO9", 1L);
+    }
+
+    @Test
+    @DisplayName("正常流-8:order/refund/approve 委托 orderService.approveRefund")
+    void 正常流_退款approve_委托() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO7");
+        Result<String> r = orderController.approveRefund(body, 1L);
+        assertEquals(200, r.getCode());
+        verify(orderService).approveRefund("PO7", 1L);
+    }
+
+    @Test
+    @DisplayName("正常流-9:order/refund/reject 委托 orderService.rejectRefund")
+    void 正常流_退款reject_委托() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO7");
+        body.put("reason", "证据不足");
+        Result<String> r = orderController.rejectRefund(body, 1L);
+        assertEquals(200, r.getCode());
+        verify(orderService).rejectRefund("PO7", 1L, "证据不足");
+    }
+
+    // ==================== 正常流:售后端点委托 service(绿锚点) ====================
+
+    @Test
+    @DisplayName("正常流-10:after-sales/list 委托 afterSalesService.adminList(status)")
+    void 正常流_售后list_委托adminList() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("status", "pending");
+        Result<List<AfterSalesRequest>> r = afterSalesController.list(body);
+        assertEquals(200, r.getCode());
+        verify(afterSalesService).adminList("pending");
+    }
+
+    @Test
+    @DisplayName("正常流-11:after-sales/detail 委托 afterSalesService.adminDetail(id)")
+    void 正常流_售后detail_委托adminDetail() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("id", 1L);
+        Result<AfterSalesRequest> r = afterSalesController.detail(body);
+        assertEquals(200, r.getCode());
+        verify(afterSalesService).adminDetail(1L);
+    }
+
+    @Test
+    @DisplayName("正常流-12:after-sales/review 委托 afterSalesService.review(approve/reject)")
+    void 正常流_售后review_委托() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("id", 1L);
+        body.put("action", "approve");
+        Result<String> r = afterSalesController.review(body, 1L);
+        assertEquals(200, r.getCode());
+        verify(afterSalesService).review(1L, "approve", null, 1L);
+    }
+
+    @Test
+    @DisplayName("正常流-13:after-sales/complete 委托 afterSalesService.complete(id)")
+    void 正常流_售后complete_委托() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("id", 1L);
+        Result<String> r = afterSalesController.complete(body);
+        assertEquals(200, r.getCode());
+        verify(afterSalesService).complete(1L);
+    }
+
+    // ==================== 边界流:售后状态守卫已实现(绿锚点) ====================
+
+    @Test
+    @DisplayName("边界流-1:售后 review 仅待审核(pending)可处理——已批准申请再次审核被拒且不落库")
+    void 边界流_售后review_非pending拒绝() {
+        when(afterSalesRequestMapper.selectById(1L)).thenReturn(requestWithStatus("approved"));
+        Result<String> r = realAfterSalesService.review(1L, "approve", null, 9L);
+        assertEquals("仅待审核的申请可处理", r.getMessage());
+        verify(afterSalesRequestMapper, never()).updateById(any(AfterSalesRequest.class));
+    }
+
+    @Test
+    @DisplayName("边界流-2:售后 review 无效 action 被拒且不落库")
+    void 边界流_售后review_无效action拒绝() {
+        when(afterSalesRequestMapper.selectById(1L)).thenReturn(requestWithStatus("pending"));
+        Result<String> r = realAfterSalesService.review(1L, "bogus", null, 9L);
+        assertEquals("无效操作", r.getMessage());
+        verify(afterSalesRequestMapper, never()).updateById(any(AfterSalesRequest.class));
+    }
+
+    @Test
+    @DisplayName("边界流-3:售后 review 申请不存在 → 拒绝")
+    void 边界流_售后review_申请不存在() {
+        when(afterSalesRequestMapper.selectById(1L)).thenReturn(null);
+        Result<String> r = realAfterSalesService.review(1L, "approve", null, 9L);
+        assertEquals("售后申请不存在", r.getMessage());
+    }
+
+    @Test
+    @DisplayName("边界流-4:售后 complete 仅已批准可完成——pending 拒绝且不落库")
+    void 边界流_售后complete_非approved拒绝() {
+        when(afterSalesRequestMapper.selectById(1L)).thenReturn(requestWithStatus("pending"));
+        Result<String> r = realAfterSalesService.complete(1L);
+        assertEquals("仅已批准的申请可完成", r.getMessage());
+        verify(afterSalesRequestMapper, never()).updateById(any(AfterSalesRequest.class));
+    }
+
+    @Test
+    @DisplayName("边界流-5:售后 complete 对 approved 申请成功闭环(approved→completed)")
+    void 边界流_售后complete_approved闭环成功() {
+        AfterSalesRequest request = requestWithStatus("approved");
+        when(afterSalesRequestMapper.selectById(1L)).thenReturn(request);
+        Result<String> r = realAfterSalesService.complete(1L);
+        assertEquals(200, r.getCode());
+        assertEquals("已完成", r.getData());
+        assertEquals("completed", request.getStatus());
+        verify(afterSalesRequestMapper).updateById(request);
+    }
+
+    // ==================== 权限流(契约缺口,预期红 ×5,B-142-1 / TR-13) ====================
+
+    @Test
+    @DisplayName("权限流-框架层:JwtInterceptor.LOGIN_REQUIRED_PATHS 已收口 /api/admin/(匿名→401,框架层已落地)")
+    void 权限流_框架层_登录门已收口apiAdmin() throws Exception {
+        Field f = JwtInterceptor.class.getDeclaredField("LOGIN_REQUIRED_PATHS");
+        f.setAccessible(true);
+        String[] paths = (String[]) f.get(null);
+        boolean covered = false;
+        for (String p : paths) {
+            if ("/api/admin/".equals(p)) {
+                covered = true;
+                break;
+            }
+        }
+        assertTrue(covered,
+                "[admin.order.manual] JwtInterceptor.LOGIN_REQUIRED_PATHS 应含 \"/api/admin/\","
+                        + "使匿名请求 admin 订单/售后端点 → 401(B-142-1 框架层;本契约关注的是框架层之下"
+                        + " controller 角色的 403 守卫,见下方 RED 用例)。");
+    }
+
+    @Test
+    @DisplayName("权限流-R1:订单人工处理 6 端点应声明 admin 角色守卫参数(缺守卫 → 红)")
+    void 权限流_订单端点_缺角色守卫() {
+        List<String> missing = new ArrayList<>();
+        for (String ep : ORDER_ENDPOINTS_NEED_ROLE_GUARD) {
+            if (!hasRoleGuardParam(AdminProductOrderController.class, methodOf(ep))) {
+                missing.add(ep);
+            }
+        }
+        assertTrue(missing.isEmpty(),
+                "RED[admin.order.manual] 订单人工处理端点应声明角色守卫参数"
+                        + "(@RequestAttribute(\"role\")/@RequestAttribute(\"roles\"),B-142-1 惯例,"
+                        + "参照 AdminArticleController#create 的「无权限」守卫),非 admin(parent/child/teacher)"
+                        + "应被拒绝且不触达 service;当前缺守卫的端点:" + missing
+                        + "。GREEN:增加 @RequestAttribute(\"role\") String role 并在入口"
+                        + " !\"admin\".equals(role) → Result.error(\"无权限\")。");
+    }
+
+    @Test
+    @DisplayName("权限流-R2:售后人工处理 4 端点应声明 admin 角色守卫参数(缺守卫 → 红)")
+    void 权限流_售后端点_缺角色守卫() {
+        List<String> missing = new ArrayList<>();
+        for (String ep : AFTER_SALES_ENDPOINTS) {
+            if (!hasRoleGuardParam(AdminAfterSalesController.class, ep)) {
+                missing.add(ep);
+            }
+        }
+        assertTrue(missing.isEmpty(),
+                "RED[admin.order.manual] 售后人工处理端点应声明角色守卫参数"
+                        + "(@RequestAttribute(\"role\"),B-142-1 惯例),非 admin(parent/child/teacher)"
+                        + "应被拒绝且不触达 service;当前缺守卫的端点:" + missing
+                        + "。GREEN:增加 @RequestAttribute(\"role\") String role 并在入口"
+                        + " !\"admin\".equals(role) → Result.error(\"无权限\")。");
+    }
+
+    @Test
+    @DisplayName("权限流-R3:order/list 非 admin 角色(roles=[parent])应 403 拒绝且不委托(→ 红)")
+    void 权限流_订单list_非admin应403拒绝() {
+        Map<String, Object> body = new HashMap<>();
+        body.put("status", "paid");
+        Result<Map<String, Object>> r =
+                orderController.list(body, 1L, Collections.singletonList("parent"));
+        assertEquals(403, r.getCode(),
+                "RED[admin.order.manual] order/list 由非 admin 角色(roles=[parent],无供应商/平台角色)"
+                        + "调用时应返回 403 无权访问,不得委托 orderService.adminOrderPage 泄漏全量订单;"
+                        + "当前被放行(B-142-1 角色守卫缺失,TR-13 权限流)。");
+        verify(orderService, never()).adminOrderPage(anyInt(), anyInt(), any(), any(),
+                any(), any(), any(), any(), any());
+    }
+
+    @Test
+    @DisplayName("权限流-R4:order/refund/approve 非 admin 角色应「无权限」拒绝且不委托(→ 红)")
+    void 权限流_退款approve_非admin拒绝() throws Exception {
+        Map<String, Object> body = new HashMap<>();
+        body.put("orderNo", "PO7");
+        Result<?> r = invokeWithRole(orderController, "approveRefund", body, 1L, "parent");
+        assertNotNull(r, "RED[admin.order.manual] refund/approve 应返回无权结果而非 null。");
+        assertEquals("无权限", r.getMessage(),
+                "RED[admin.order.manual] refund/approve 由非 admin 角色调用时应按 B-142-1 惯例返回"
+                        + "「无权限」;当前方法无角色守卫参数(@RequestAttribute(\"role\")),parent/child"
+                        + "可直接审批退款(TR-13 权限流)。GREEN:增加 role 参数并在入口守卫。");
+        verify(orderService, never()).approveRefund(anyString(), anyLong());
+    }
+
+    @Test
+    @DisplayName("权限流-R5:after-sales/review 非 admin 角色应「无权限」拒绝且不委托(→ 红)")
+    void 权限流_售后review_非admin拒绝() throws Exception {
+        Map<String, Object> body = new HashMap<>();
+        body.put("id", 1L);
+        body.put("action", "approve");
+        Result<?> r = invokeWithRole(afterSalesController, "review", body, 1L, "parent");
+        assertNotNull(r, "RED[admin.order.manual] 售后 review 应返回无权结果而非 null。");
+        assertEquals("无权限", r.getMessage(),
+                "RED[admin.order.manual] 售后 review 由非 admin 角色调用时应按 B-142-1 惯例返回"
+                        + "「无权限」;当前方法无角色守卫参数(@RequestAttribute(\"role\")),parent/child"
+                        + "可直接处理售后单(TR-13 权限流)。GREEN:增加 role 参数并在入口守卫。");
+        verify(afterSalesService, never()).review(anyLong(), any(), any(), anyLong());
+    }
+
+    // ==================== 辅助 ====================
+
+    private static void setField(Object target, String name, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    /** 采集类上所有 @PostMapping 方法映射的相对路径(归一化:去掉前导斜杠) */
+    private static Set<String> endpointPaths(Class<?> clazz) {
+        Set<String> paths = new LinkedHashSet<>();
+        for (Method m : clazz.getDeclaredMethods()) {
+            PostMapping pm = m.getAnnotation(PostMapping.class);
+            if (pm != null) {
+                for (String p : pm.value()) {
+                    paths.add(p.replaceFirst("^/+", ""));
+                }
+            }
+        }
+        return paths;
+    }
+
+    /** 该方法是否声明了 admin 角色承载参数(@RequestAttribute value = "role" 或 "roles") */
+    private static boolean hasRoleGuardParam(Class<?> clazz, String methodName) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (!m.getName().equals(methodName)) {
+                continue;
+            }
+            for (Annotation[] anns : m.getParameterAnnotations()) {
+                for (Annotation a : anns) {
+                    if (a instanceof RequestAttribute) {
+                        String v = ((RequestAttribute) a).value();
+                        if ("role".equals(v) || "roles".equals(v)) {
+                            return true;
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 反射派发任一 admin 端点方法并携带角色:兼容当前签名(RED 现状,如 refund/approve 为
+     * {@code (Map, Long)}、review 为 {@code (Map, Long)})与契约签名(GREEN 后为
+     * {@code (Map, Long, String role)}),避免 GREEN 阶段改签名导致本测试编译失败。
+     */
+    private static Result<?> invokeWithRole(Object controller, String methodName,
+                                            Map<String, Object> body, Long adminId, String role)
+            throws Exception {
+        for (Method m : controller.getClass().getDeclaredMethods()) {
+            if (!m.getName().equals(methodName)) {
+                continue;
+            }
+            Class<?>[] pts = m.getParameterTypes();
+            m.setAccessible(true);
+            if (pts.length == 3 && pts[0] == Map.class && pts[1] == Long.class
+                    && pts[2] == String.class) {
+                return (Result<?>) m.invoke(controller, body, adminId, role);
+            }
+            if (pts.length == 2 && pts[0] == Map.class && pts[1] == Long.class) {
+                return (Result<?>) m.invoke(controller, body, adminId);
+            }
+        }
+        fail("契约方法不存在: " + methodName);
+        return null;
+    }
+
+    /** 端点路径 → 控制器方法名(仅非同名路径需要映射) */
+    private static String methodOf(String endpoint) {
+        if ("refund/approve".equals(endpoint)) {
+            return "approveRefund";
+        }
+        if ("refund/reject".equals(endpoint)) {
+            return "rejectRefund";
+        }
+        if ("update-express".equals(endpoint)) {
+            return "updateExpress";
+        }
+        return endpoint;
+    }
+
+    private static AfterSalesRequest requestWithStatus(String status) {
+        AfterSalesRequest r = new AfterSalesRequest();
+        r.setId(1L);
+        r.setOrderNo("PO1");
+        r.setUserId(7L);
+        r.setStatus(status);
+        return r;
+    }
+}

+ 117 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminProductControllerBatchShelveTest.java

@@ -0,0 +1,117 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.ProductService;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+/**
+ * 批量商品上下架(/api/admin/product/batch-shelve)类型安全回归测试。
+ *
+ * 故障:批量下架时抛 ClassCastException: Integer cannot be cast to Long。
+ * 根因:@RequestBody Map<String, Object> 使 Jackson 把 JSON 数字数组反序列化为
+ *      List<Integer>;控制器旧写法 (List<Long>) params.get("productIds") 为擦除强转,
+ *      编译通过,到服务层 for (Long id : list) 才在运行期对元素做 Integer->Long 转换而失败。
+ *
+ * 约定:productIds 必须是 Number 或数字字符串均可;解析后的 List<Long> 交给服务层。
+ * 用 ObjectMapper 反序列化真实 JSON 复现线上报文(与控制器收到的对象一致)。
+ */
+public class AdminProductControllerBatchShelveTest {
+
+    private static final ObjectMapper OM = new ObjectMapper();
+
+    private AdminProductController controller;
+    private ProductService productService;
+
+    @BeforeEach
+    public void setUp() throws Exception {
+        controller = new AdminProductController();
+        productService = mock(ProductService.class);
+        ReflectionTestUtils.setField(controller, "productService", productService);
+    }
+
+    @Test
+    public void batchShelve_jsonIntegerIds_convertedToLong() throws Exception {
+        // 复现线上报文:Jackson 对 JSON 数字产出 Integer
+        @SuppressWarnings("unchecked")
+        Map<String, Object> params = OM.readValue(
+                "{\"productIds\":[1,2,3],\"shelve\":false}", Map.class);
+        @SuppressWarnings("unchecked")
+        List<?> raw = (List<?>) params.get("productIds");
+        assertEquals(Integer.class, raw.get(0).getClass(),
+                "前置条件:Jackson 将 JSON 数字反序列化为 Integer(即本缺陷的诱因)");
+
+        when(productService.batchAdminShelve(any(), eq(false)))
+                .thenReturn(Result.success("批量下架成功"));
+
+        Result<String> result = controller.batchShelve(params);
+
+        assertEquals(200, result.getCode());
+        assertEquals("批量下架成功", result.getData());
+
+        ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
+        verify(productService, times(1)).batchAdminShelve(captor.capture(), eq(false));
+        for (Object id : captor.getValue()) {
+            assertEquals(Long.class, id.getClass(),
+                    "传给服务层的元素必须是 Long,实际为 " + id.getClass());
+        }
+        assertEquals(3, captor.getValue().size());
+    }
+
+    @Test
+    public void batchShelve_largeValueAndStringNumberAccepted() throws Exception {
+        // 大数值(超出 Integer 范围,Jackson 产出 Long)与字符串数字都应安全解析
+        @SuppressWarnings("unchecked")
+        Map<String, Object> params = OM.readValue(
+                "{\"productIds\":[3000000000,\"42\"],\"shelve\":true}", Map.class);
+
+        when(productService.batchAdminShelve(any(), eq(true)))
+                .thenReturn(Result.success("批量上架成功"));
+
+        Result<String> result = controller.batchShelve(params);
+
+        assertEquals(200, result.getCode());
+        verify(productService, times(1))
+                .batchAdminShelve(eq(java.util.Arrays.asList(3000000000L, 42L)), eq(true));
+    }
+
+    @Test
+    public void batchShelve_missingOrEmptyIds_returnsCleanError() throws Exception {
+        // Result.error(msg) 约定:body code=500(HTTP 200)。要点是干净的业务错误,
+        // 而不是抛 ClassCastException / 崩溃。
+        @SuppressWarnings("unchecked")
+        Map<String, Object> absent = OM.readValue("{\"shelve\":false}", Map.class);
+        Result<String> r1 = controller.batchShelve(absent);
+        assertEquals(500, r1.getCode());
+        assertEquals("productIds不能为空", r1.getMessage());
+
+        @SuppressWarnings("unchecked")
+        Map<String, Object> empty = OM.readValue("{\"productIds\":[],\"shelve\":false}", Map.class);
+        Result<String> r2 = controller.batchShelve(empty);
+        assertEquals(500, r2.getCode());
+        assertEquals("productIds不能为空", r2.getMessage());
+
+        verify(productService, never()).batchAdminShelve(any(), any());
+    }
+
+    @Test
+    public void batchShelve_missingShelve_returnsCleanError() throws Exception {
+        @SuppressWarnings("unchecked")
+        Map<String, Object> params = OM.readValue("{\"productIds\":[1]}", Map.class);
+        Result<String> result = controller.batchShelve(params);
+        assertEquals(500, result.getCode());
+        assertEquals("shelve不能为空", result.getMessage());
+        verify(productService, never()).batchAdminShelve(any(), any());
+    }
+}

+ 224 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminReferralContractTest.java

@@ -0,0 +1,224 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AdminReferralTreeService;
+import com.etotem.cfc.service.CommissionService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * TR-25 用户管理「推荐团队」查看契约测试(研发 → 测试送测,2026-11-10 22:4x 错峰轮)。
+ * <p>对象:{@link AdminReferralController}(实现 6c0f05701 已合入 origin/cfclub 但零契约/零场景覆盖)。
+ * <p>风格与既有 HealthPlanProductSelectionContractTest 一致:mock Service/Mapper + 反射注入,直接调用(无 Spring 上下文)。
+ * <p>覆盖:/api/admin/referral/{summary,members,tree} 三端点 ——
+ * 无权限(匿名/非后台角色)拒绝 · userId 参数校验 · 用户不存在 · 成功分支字段形态 ·
+ * level 归一化(L1/L2/默认 ALL)· maxLevel 默认 3 · 幂等参数透传。
+ */
+class AdminReferralContractTest {
+
+    private AdminReferralController controller;
+    private CommissionService commissionService;
+    private UserMapper userMapper;
+    private AdminReferralTreeService adminReferralTreeService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AdminReferralController();
+        commissionService = mock(CommissionService.class);
+        userMapper = mock(UserMapper.class);
+        adminReferralTreeService = mock(AdminReferralTreeService.class);
+        set("commissionService", controller, commissionService);
+        set("userMapper", controller, userMapper);
+        set("adminReferralTreeService", controller, adminReferralTreeService);
+    }
+
+    private void set(String name, Object target, Object v) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, v);
+    }
+
+    private Map<String, Object> params(Long userId, String extraKey, Object extraVal) {
+        Map<String, Object> p = new HashMap<>();
+        if (userId != null) p.put("userId", userId);
+        if (extraKey != null) p.put(extraKey, extraVal);
+        return p;
+    }
+
+    private User user(Long id) {
+        User u = new User();
+        u.setId(id);
+        u.setNickname("测试用户");
+        u.setPhone("13800000000");
+        u.setReferralCode("R" + id);
+        u.setCreatedAt(new Date(1700000000000L));
+        return u;
+    }
+
+    // ==================== 权限门(无权限一律拒绝) ====================
+
+    @Test
+    void summary_匿名无角色返回无权限() {
+        Result<?> r = controller.summary(params(1L, null, null), null, null);
+        assertEquals("无权限", r.getMessage());
+        assertEquals(500, r.getCode());
+        verify(commissionService, never()).getMyReferrer(any(), any());
+    }
+
+    @Test
+    void summary_C端角色parent返回无权限() {
+        Result<?> r = controller.summary(params(1L, null, null), "parent", null);
+        assertEquals("无权限", r.getMessage());
+    }
+
+    @Test
+    void members_非后台角色child返回无权限() {
+        Result<?> r = controller.members(params(1L, null, null), "child", null);
+        assertEquals("无权限", r.getMessage());
+    }
+
+    @Test
+    void tree_匿名返回无权限() {
+        Result<?> r = controller.tree(params(1L, null, null), null, null);
+        assertEquals("无权限", r.getMessage());
+    }
+
+    // ==================== summary:参数校验 / 用户不存在 / 成功 ====================
+
+    @Test
+    void summary_userId为空返回错误() {
+        Result<?> r = controller.summary(params(null, null, null), "admin", null);
+        assertEquals("userId不能为空", r.getMessage());
+        verify(userMapper, never()).selectById(any());
+    }
+
+    @Test
+    void summary_用户不存在返回错误() {
+        when(userMapper.selectById(99L)).thenReturn(null);
+        Result<?> r = controller.summary(params(99L, null, null), "admin", null);
+        assertEquals("用户不存在", r.getMessage());
+    }
+
+    @Test
+    void summary_成功返回推荐关系概览字段形态() {
+        when(userMapper.selectById(10L)).thenReturn(user(10L));
+        Map<String, Object> upstream = new HashMap<>();
+        upstream.put("hasReferrer", true);
+        upstream.put("referrerId", 3L);
+        upstream.put("nickname", "上级");
+        when(commissionService.getMyReferrer(10L, null)).thenReturn(upstream);
+        Map<String, Object> stats = new HashMap<>();
+        stats.put("l1Count", 2);
+        stats.put("l2Count", 5);
+        stats.put("totalCommission", 128.5);
+        when(commissionService.getTeamStats(10L)).thenReturn(stats);
+
+        Result<Map<String, Object>> r = controller.summary(params(10L, null, null), "admin", null);
+        assertEquals(200, r.getCode());
+        Map<String, Object> d = r.getData();
+        assertNotNull(d);
+        assertEquals(10L, d.get("userId"));
+        assertEquals("测试用户", d.get("nickname"));
+        assertEquals("R10", d.get("referralCode"));
+        assertEquals(true, d.get("hasReferrer"));
+        assertEquals(3L, d.get("referrerId"));
+        assertEquals(2, d.get("l1Count"));
+        assertEquals(5, d.get("l2Count"));
+        assertEquals(128.5, d.get("totalCommission"));
+    }
+
+    @Test
+    void summary_无推荐人边界() {
+        when(userMapper.selectById(20L)).thenReturn(user(20L));
+        Map<String, Object> upstream = new HashMap<>();
+        upstream.put("hasReferrer", false);
+        upstream.put("referrerId", null);
+        upstream.put("nickname", null);
+        when(commissionService.getMyReferrer(20L, null)).thenReturn(upstream);
+        when(commissionService.getTeamStats(20L)).thenReturn(new HashMap<>());
+
+        Result<Map<String, Object>> r = controller.summary(params(20L, null, null), "admin", null);
+        assertEquals(false, r.getData().get("hasReferrer"));
+    }
+
+    // ==================== members:level 归一化 / 参数透传 ====================
+
+    @Test
+    void members_level非法归一化为ALL() {
+        when(commissionService.getTeamList(10L, "ALL", 1, 20)).thenReturn(new HashMap<>());
+        Result<?> r = controller.members(params(10L, "level", "L3"), "admin", null);
+        assertEquals(200, r.getCode());
+        verify(commissionService).getTeamList(10L, "ALL", 1, 20);
+    }
+
+    @Test
+    void members_levelL1直传() {
+        when(commissionService.getTeamList(10L, "L1", 1, 20)).thenReturn(new HashMap<>());
+        Result<?> r = controller.members(params(10L, "level", "L1"), "admin", null);
+        verify(commissionService).getTeamList(10L, "L1", 1, 20);
+    }
+
+    @Test
+    void members_userId为空返回错误() {
+        Result<?> r = controller.members(params(null, null, null), "admin", null);
+        assertEquals("userId不能为空", r.getMessage());
+    }
+
+    // ==================== tree:maxLevel 默认 3 / 传值 / 空树 ====================
+
+    @Test
+    void tree_maxLevel默认3() {
+        when(adminReferralTreeService.buildTree(10L, 3)).thenReturn(new HashMap<>());
+        Result<?> r = controller.tree(params(10L, null, null), "admin", null);
+        assertEquals(200, r.getCode());
+        verify(adminReferralTreeService).buildTree(10L, 3);
+    }
+
+    @Test
+    void tree_maxLevel8上限透传() {
+        when(adminReferralTreeService.buildTree(10L, 8)).thenReturn(new HashMap<>());
+        Result<?> r = controller.tree(params(10L, "maxLevel", 8), "admin", null);
+        verify(adminReferralTreeService).buildTree(10L, 8);
+    }
+
+    @Test
+    void tree_userId不存在返回错误() {
+        Result<?> r = controller.tree(params(99L, null, null), "admin", null);
+        assertEquals(200, r.getCode()); // tree 不校验用户存在,只按 userId 建树(空树由 Service 返回)
+        verify(adminReferralTreeService).buildTree(99L, 3);
+    }
+
+    // ==================== roles 列表形式(hasAnyBackendRole) ====================
+
+    @Test
+    void summary_roleList含backend角色放行() {
+        when(userMapper.selectById(10L)).thenReturn(user(10L));
+        Map<String, Object> upstream = new HashMap<>();
+        upstream.put("hasReferrer", false);
+        when(commissionService.getMyReferrer(10L, null)).thenReturn(upstream);
+        when(commissionService.getTeamStats(10L)).thenReturn(new HashMap<>());
+        List<String> roles = Arrays.asList("operator");
+        Result<?> r = controller.summary(params(10L, null, null), null, roles);
+        assertEquals(200, r.getCode());
+    }
+
+    @Test
+    void summary_roleList纯C端角色拒绝() {
+        List<String> roles = Collections.singletonList("parent");
+        Result<?> r = controller.summary(params(10L, null, null), null, roles);
+        assertEquals("无权限", r.getMessage());
+    }
+}

+ 50 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminWorkbenchAuthContractTest.java

@@ -0,0 +1,50 @@
+package com.etotem.cfc.controller.admin;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 单家庭工作台-鉴权契约:家庭维度(路径以 /families/{id}/ 开头)POST 端点必须
+ * @PreAuthorize("hasRole(admin)"),familyId 一律来自 URL。
+ * 覆盖:AdminFamilyWorkbenchController(聚合/消息/报告)、AdminFamilyTaskController(任务写)、
+ * AdminHealthPlanController 中新增的 family 写方法(其遗留 list/detail/delete 保持多角色行为,不在本契约内)。
+ * 无 token 由 JwtInterceptor(LOGIN_REQUIRED_PATHS 含 /api/admin/**) 回 401;
+ * 非 admin 由 @PreAuthorize → GlobalExceptionHandler 回 200+{code:403}。
+ * 纯反射(无 Spring/DB),任何环境可跑。
+ */
+class AdminWorkbenchAuthContractTest {
+
+    private static final List<Class<?>> CONTROLLERS = Arrays.asList(
+            AdminFamilyWorkbenchController.class,
+            AdminFamilyTaskController.class,
+            AdminFamilyPlanController.class,
+            AdminHealthPlanController.class);
+
+    @Test
+    void 家庭维度POST端点必须admin鉴权且familyId来自URL() {
+        int checked = 0;
+        for (Class<?> clazz : CONTROLLERS) {
+            for (Method m : clazz.getDeclaredMethods()) {
+                PostMapping pm = m.getAnnotation(PostMapping.class);
+                if (pm == null || pm.value().length == 0) continue;
+                String path = pm.value()[0];
+                if (!path.startsWith("/families/")) continue;
+                checked++;
+                PreAuthorize pa = m.getAnnotation(PreAuthorize.class);
+                assertNotNull(pa, clazz.getSimpleName() + "." + m.getName() + " 必须带 @PreAuthorize");
+                assertTrue(pa.value().contains("admin"),
+                        clazz.getSimpleName() + "." + m.getName() + " 必须要求 admin 角色");
+                assertTrue(path.matches("/families/\\{.*\\}/.*"), m.getName() + " 路径必须含 {id} 变量: " + path);
+            }
+        }
+        assertTrue(checked >= 8, "应至少覆盖 8 个家庭维度端点,实际 " + checked);
+    }
+}

+ 104 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/ReportParserAdminControllerTest.java

@@ -0,0 +1,104 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ReportTypeRegistry;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+@ExtendWith(MockitoExtension.class)
+class ReportParserAdminControllerTest {
+
+    @Mock
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @InjectMocks
+    private ReportParserAdminController controller;
+
+    private ReportTypeRegistry baseType() {
+        ReportTypeRegistry t = new ReportTypeRegistry();
+        t.setId(1L);
+        t.setTypeId("dan_a1");
+        t.setDisplayName("素质测评A1");
+        return t;
+    }
+
+    @Test
+    void saveType_rejectsInvalidJsonArray() {
+        ReportTypeRegistry t = baseType();
+        t.setExpectedIndicators("not-json");
+
+        Result<Void> r = controller.saveType(t);
+
+        assertEquals(500, r.getCode());
+        assertTrue(r.getMessage().contains("expectedIndicators"));
+        verifyNoInteractions(typeRegistryMapper);
+    }
+
+    @Test
+    void saveType_rejectsJsonArrayWithNonStringElement() {
+        ReportTypeRegistry t = baseType();
+        t.setExpectedIndicators("[1,2,3]");
+
+        Result<Void> r = controller.saveType(t);
+
+        assertEquals(500, r.getCode());
+        verify(typeRegistryMapper, never()).updateById(t);
+    }
+
+    @Test
+    void saveType_acceptsValidJsonArray() {
+        ReportTypeRegistry t = baseType();
+        t.setExpectedIndicators("[\"总分\",\"百分位\"]");
+
+        Result<Void> r = controller.saveType(t);
+
+        assertEquals(200, r.getCode());
+        verify(typeRegistryMapper).updateById(t);
+    }
+
+    /** 契约①(update 路径):updateById 收到含 icon/sortOrder 的实体,字段非空即可持久化 */
+    @Test
+    void saveType_updatePathPersistsIconAndSortOrder() {
+        ReportTypeRegistry t = baseType();
+        t.setLinkedProductId(50L); // 非空,聚焦 updateById 分支
+        t.setIcon("🧪");
+        t.setSortOrder(7);
+
+        Result<Void> r = controller.saveType(t);
+
+        assertEquals(200, r.getCode());
+        ArgumentCaptor<ReportTypeRegistry> captor = ArgumentCaptor.forClass(ReportTypeRegistry.class);
+        verify(typeRegistryMapper).updateById(captor.capture());
+        assertEquals("🧪", captor.getValue().getIcon());
+        assertEquals(7, captor.getValue().getSortOrder());
+        assertEquals(50L, captor.getValue().getLinkedProductId());
+    }
+
+    /** 契约③:icon 空串应归一化为 null,避免把 "" 写库覆盖默认 */
+    @Test
+    void saveType_emptyIconNormalizedToNull() {
+        ReportTypeRegistry t = baseType();
+        t.setLinkedProductId(50L);
+        t.setIcon("   ");
+
+        Result<Void> r = controller.saveType(t);
+
+        assertEquals(200, r.getCode());
+        ArgumentCaptor<ReportTypeRegistry> captor = ArgumentCaptor.forClass(ReportTypeRegistry.class);
+        verify(typeRegistryMapper).updateById(captor.capture());
+        assertNull(captor.getValue().getIcon(), "icon 空串应转 null,不写库覆盖默认");
+    }
+}

+ 167 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/SupplyTeamControllerInviteTest.java

@@ -0,0 +1,167 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.service.SupplySystemService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(T38 邀请功能 / 能力键 team.invite.*):
+ * POST /api/admin/supply-team/invite-code、/invite/info、/invite/join 的契约级单测。
+ *
+ * 契约(对应 SupplyTeamController):
+ * - invite-code:systemId 空 → error("systemId不能为空");非成员/管理员 → error("无权操作该团队");
+ *   正常 → generateInviteCode 返回码 + getById 拼装团队信息 → success(data)
+ * - invite/info:inviteCode 空 → error("邀请码不能为空");正常 → getInviteInfo 返回 info → success
+ * - invite/join:inviteCode 空 → error("邀请码不能为空");正常 → joinByInviteCode(code,userId) → success
+ *
+ * 测试不依赖数据库/外部服务:supplySystemService 全 mock;不启 Spring 上下文。
+ */
+public class SupplyTeamControllerInviteTest {
+
+    @Mock private SupplySystemService supplySystemService;
+
+    private MockMvc mockMvc;
+    private SupplyTeamController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new SupplyTeamController();
+        ReflectionTestUtils.setField(controller, "supplySystemService", supplySystemService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ---------- invite-code ----------
+    @Test
+    public void inviteCode_missingSystemId_returnsError() throws Exception {
+        Long userId = 1L;
+        String body = "{}";
+        mockMvc.perform(post("/api/admin/supply-team/invite-code")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("systemId不能为空"));
+        verify(supplySystemService, never()).generateInviteCode(anyLong(), anyLong(), anyBoolean());
+    }
+
+    @Test
+    public void inviteCode_notMember_returnsForbidden() throws Exception {
+        Long userId = 1L;
+        Long systemId = 10L;
+        when(supplySystemService.isMemberOrAdmin(systemId, userId)).thenReturn(false);
+        String body = "{\"systemId\":10}";
+        mockMvc.perform(post("/api/admin/supply-team/invite-code")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("无权操作该团队"));
+        verify(supplySystemService, never()).generateInviteCode(anyLong(), anyLong(), anyBoolean());
+    }
+
+    @Test
+    public void inviteCode_success_returnsCodeAndTeam() throws Exception {
+        Long userId = 1L;
+        Long systemId = 10L;
+        when(supplySystemService.isMemberOrAdmin(systemId, userId)).thenReturn(true);
+        when(supplySystemService.generateInviteCode(eq(systemId), eq(userId), anyBoolean())).thenReturn("ABC123");
+        SupplySystem system = mock(SupplySystem.class);
+        when(system.getName()).thenReturn("成长团队A");
+        when(supplySystemService.getById(systemId)).thenReturn(system);
+        String body = "{\"systemId\":10}";
+        mockMvc.perform(post("/api/admin/supply-team/invite-code")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.inviteCode").value("ABC123"))
+                .andExpect(jsonPath("$.data.systemId").value(10))
+                .andExpect(jsonPath("$.data.teamName").value("成长团队A"));
+        verify(supplySystemService).generateInviteCode(eq(systemId), eq(userId), anyBoolean());
+    }
+
+    // ---------- invite/info ----------
+    @Test
+    public void inviteInfo_missingCode_returnsError() throws Exception {
+        String body = "{}";
+        mockMvc.perform(post("/api/admin/supply-team/invite/info")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("邀请码不能为空"));
+        verify(supplySystemService, never()).getInviteInfo(anyString());
+    }
+
+    @Test
+    public void inviteInfo_success_returnsInfo() throws Exception {
+        Map<String, Object> info = new HashMap<>();
+        info.put("teamName", "成长团队A");
+        info.put("inviterNickname", "老师小王");
+        when(supplySystemService.getInviteInfo("ABC123")).thenReturn(info);
+        String body = "{\"inviteCode\":\"ABC123\"}";
+        mockMvc.perform(post("/api/admin/supply-team/invite/info")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.teamName").value("成长团队A"));
+        verify(supplySystemService).getInviteInfo("ABC123");
+    }
+
+    // ---------- invite/join ----------
+    @Test
+    public void inviteJoin_missingCode_returnsError() throws Exception {
+        Long userId = 1L;
+        String body = "{}";
+        mockMvc.perform(post("/api/admin/supply-team/invite/join")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("邀请码不能为空"));
+        verify(supplySystemService, never()).joinByInviteCode(anyString(), anyLong());
+    }
+
+    @Test
+    public void inviteJoin_success_callsJoin() throws Exception {
+        Long userId = 1L;
+        Map<String, Object> result = new HashMap<>();
+        result.put("ok", Boolean.TRUE);
+        result.put("systemId", 10);
+        when(supplySystemService.joinByInviteCode("ABC123", userId)).thenReturn(result);
+        String body = "{\"inviteCode\":\"ABC123\"}";
+        mockMvc.perform(post("/api/admin/supply-team/invite/join")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.ok").value(true));
+        verify(supplySystemService).joinByInviteCode("ABC123", userId);
+    }
+}

+ 315 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ai/AIChatControllerGateTest.java

@@ -0,0 +1,315 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AiGateResult;
+import com.etotem.cfc.enums.AiGateStatus;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.PortraitService;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+/**
+ * AI 使用会员门禁单元测试(AIChatController,任务书 2026-11-02-ai-member-gate-design §3.1)。
+ *
+ * <p>门禁判定本身在 MembershipService(见 MembershipServiceAiGateTest),
+ * 本测试聚焦控制器接线与错误码/响应结构:</p>
+ * <ul>
+ *   <li>开关关闭(gate.enabled=false → ALLOW)→ 所有登录用户放行</li>
+ *   <li>BASIC / FAMILY / PREMIUM 有效 → 放行</li>
+ *   <li>FREE(UPGRADE_REQUIRED)→ 46003</li>
+ *   <li>曾付费过期(MEMBER_EXPIRED)→ 46004</li>
+ *   <li>/chat/send、/nutrition/send、/health-coach/send、/butler/send 同一门禁</li>
+ *   <li>/api/ai/gate 返回 features 明细;/health-coach/gate 兼容保留</li>
+ * </ul>
+ */
+class AIChatControllerGateTest {
+
+    private AIChatController controller;
+    private MembershipService membershipService;
+    private UserService userService;
+    private AiGateway aiGateway;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new AIChatController();
+        membershipService = mock(MembershipService.class);
+        userService = mock(UserService.class);
+        aiGateway = mock(AiGateway.class);
+        inject("membershipService", membershipService);
+        inject("userService", userService);
+        inject("portraitService", mock(PortraitService.class));
+        inject("aiGateway", aiGateway);
+        // aiGateway.chat 在放行路径会被调用,提供最小 stub
+        when(aiGateway.chat(anyString(), anyLong(), any(), anyMap()))
+                .thenReturn(chatResponse());
+    }
+
+    private void inject(String name, Object v) throws Exception {
+        Field f = AIChatController.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(controller, v);
+    }
+
+    private Map<String, Object> sendMessageParams(String query) {
+        Map<String, Object> p = new LinkedHashMap<>();
+        p.put("query", query);
+        return p;
+    }
+
+    private Map<String, String> sendStringParams(String query) {
+        Map<String, String> p = new LinkedHashMap<>();
+        p.put("query", query);
+        return p;
+    }
+
+    private Map<String, Object> chatResponse() {
+        Map<String, Object> resp = new LinkedHashMap<>();
+        resp.put("answer", "OK");
+        resp.put("conversationId", "");
+        return resp;
+    }
+
+    /** 构造门禁结果 */
+    private AiGateResult gate(boolean enabled, AiGateStatus status, boolean canUse,
+                              boolean canViewHistory, String level) {
+        AiGateResult g = new AiGateResult();
+        g.setEnabled(enabled);
+        g.setStatus(status);
+        g.setCanUse(canUse);
+        g.setCanViewHistory(canViewHistory);
+        g.setMemberLevel(level);
+        g.setIsActive(status == AiGateStatus.ALLOW && enabled);
+        g.setDaysRemaining(0L);
+        g.setReason(status == AiGateStatus.ALLOW ? null : status.name());
+        return g;
+    }
+
+    private AiGateResult allow(String level) {
+        return gate(true, AiGateStatus.ALLOW, true, true, level);
+    }
+
+    private AiGateResult upgradeRequired() {
+        return gate(true, AiGateStatus.UPGRADE_REQUIRED, false, false, "FREE");
+    }
+
+    private AiGateResult expired() {
+        return gate(true, AiGateStatus.MEMBER_EXPIRED, false, true, "FREE");
+    }
+
+    // ── health-coach/send ──
+
+    @Test
+    void 开关关闭_FREE用户也可用() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(gate(false, AiGateStatus.ALLOW, true, true, "FREE"));
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(200, r.getCode());
+        verify(aiGateway).chat(anyString(), eq(1L), any(), anyMap());
+    }
+
+    @Test
+    void 开关开启_BASIC用户放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("BASIC"));
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(200, r.getCode());
+        verify(aiGateway).chat(anyString(), eq(1L), any(), anyMap());
+    }
+
+    @Test
+    void 开关开启_FAMILY用户放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("FAMILY"));
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(200, r.getCode());
+        verify(aiGateway).chat(anyString(), eq(1L), any(), anyMap());
+    }
+
+    @Test
+    void 开关开启_PREMIUM用户放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("PREMIUM"));
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(200, r.getCode());
+        verify(aiGateway).chat(anyString(), eq(1L), any(), anyMap());
+    }
+
+    @Test
+    void 开关开启_FREE用户被拦截返回46003() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(upgradeRequired());
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(46003, r.getCode());
+        assertEquals("该功能为会员专享,请先开通会员", r.getMessage());
+        verify(aiGateway, never()).chat(anyString(), anyLong(), any(), anyMap());
+    }
+
+    @Test
+    void 开关开启_过期会员返回46004() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(expired());
+        Result<?> r = controller.sendHealthCoachMessage(1L, sendMessageParams("你好"));
+        assertEquals(46004, r.getCode());
+        assertEquals("会员已过期,请续费后继续使用", r.getMessage());
+        verify(aiGateway, never()).chat(anyString(), anyLong(), any(), anyMap());
+    }
+
+    // ── chat/send · nutrition/send · butler/send 同门禁 ──
+
+    @Test
+    void chat_send_FREE被拦截返回46003() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(upgradeRequired());
+        Result<?> r = controller.sendMessage(1L, sendStringParams("你好"));
+        assertEquals(46003, r.getCode());
+        verifyNoInteractions(aiGateway);
+    }
+
+    @Test
+    void chat_send_过期会员返回46004() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(expired());
+        Result<?> r = controller.sendMessage(1L, sendStringParams("你好"));
+        assertEquals(46004, r.getCode());
+        verifyNoInteractions(aiGateway);
+    }
+
+    @Test
+    void nutrition_send_过期会员返回46004() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(expired());
+        Map<String, String> p = sendStringParams("分析这份报告");
+        p.put("reportId", "99");
+        Result<?> r = controller.sendNutritionMessage(1L, p);
+        assertEquals(46004, r.getCode());
+        verifyNoInteractions(aiGateway);
+    }
+
+    @Test
+    void butler_send_FREE被拦截返回46003() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(upgradeRequired());
+        Result<?> r = controller.sendHealthButlerMessage(1L, sendMessageParams("帮我安排一下"));
+        assertEquals(46003, r.getCode());
+        verifyNoInteractions(aiGateway);
+    }
+
+    @Test
+    void butler_send_有效会员放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("FAMILY"));
+        Result<?> r = controller.sendHealthButlerMessage(1L, sendMessageParams("帮我安排一下"));
+        assertEquals(200, r.getCode());
+        verify(aiGateway).chat(anyString(), eq(1L), any(), anyMap());
+    }
+
+    // ── /api/ai/gate ──
+
+    @Test
+    void gate接口_过期会员_返回全量features() {
+        AiGateResult g = expired();
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(g);
+        Result<AiGateResult> r = controller.aiGateStatus(1L);
+        assertEquals(200, r.getCode());
+        AiGateResult d = r.getData();
+        assertEquals(AiGateStatus.MEMBER_EXPIRED, d.getStatus());
+        assertEquals(true, d.isEnabled());
+        assertEquals(false, d.isCanUse());
+        assertEquals(true, d.isCanViewHistory());
+        assertEquals("MEMBER_EXPIRED", d.getReason());
+
+        Map<String, AiGateResult.FeatureGate> features = d.getFeatures();
+        assertNotNull(features);
+        assertEquals(8, features.size());
+        assertFalse(features.get("chat").isCanUse());
+        assertFalse(features.get("nutrition").isCanUse());
+        assertFalse(features.get("healthCoach").isCanUse());
+        assertFalse(features.get("butler").isCanUse());
+        assertEquals("MEMBER_EXPIRED", features.get("chat").getReason());
+        // 不纳入门禁的 4 项固定放行(保留 FREE 引流钩子)
+        assertTrue(features.get("reportAnalyze").isCanUse());
+        assertTrue(features.get("emotion").isCanUse());
+        assertTrue(features.get("tongue").isCanUse());
+        assertTrue(features.get("diet").isCanUse());
+        assertNull(features.get("reportAnalyze").getReason());
+    }
+
+    @Test
+    void gate接口_有效会员_全部放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("BASIC"));
+        Result<AiGateResult> r = controller.aiGateStatus(1L);
+        assertEquals(200, r.getCode());
+        AiGateResult d = r.getData();
+        assertEquals(AiGateStatus.ALLOW, d.getStatus());
+        assertEquals(true, d.isCanUse());
+        assertTrue(d.getFeatures().get("chat").isCanUse());
+        assertNull(d.getFeatures().get("chat").getReason());
+    }
+
+    @Test
+    void gate接口_开关关闭_全部放行() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(gate(false, AiGateStatus.ALLOW, true, true, "FREE"));
+        Result<AiGateResult> r = controller.aiGateStatus(1L);
+        assertEquals(200, r.getCode());
+        assertEquals(false, r.getData().isEnabled());
+        assertEquals(true, r.getData().isCanUse());
+        assertTrue(r.getData().getFeatures().get("butler").isCanUse());
+    }
+
+    @Test
+    void gate接口_JSON字段名符合契约() throws Exception {
+        AiGateResult g = expired();
+        g.setMemberExpireTime(new java.util.Date(1767225600000L));
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(g);
+        Result<AiGateResult> r = controller.aiGateStatus(1L);
+
+        String json = new com.fasterxml.jackson.databind.ObjectMapper()
+                .writeValueAsString(r.getData());
+        assertTrue(json.contains("\"status\":\"MEMBER_EXPIRED\""), json);
+        assertTrue(json.contains("\"enabled\":true"), json);
+        assertTrue(json.contains("\"canUse\":false"), json);
+        assertTrue(json.contains("\"canViewHistory\":true"), json);
+        assertTrue(json.contains("\"isActive\":false"), json);
+        assertTrue(json.contains("\"memberExpireTime\":"), json);
+        assertTrue(json.contains("\"reason\":\"MEMBER_EXPIRED\""), json);
+        assertTrue(json.contains("\"features\":{"), json);
+        assertTrue(json.contains("\"healthCoach\":{"), json);
+    }
+
+    // ── 兼容接口 /health-coach/gate ──
+
+    @Test
+    void gateStatus_开关关闭返回enabledFalse_canUseTrue() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(gate(false, AiGateStatus.ALLOW, true, true, "FREE"));
+        Result<?> r = controller.aiCoachGateStatus(1L);
+        assertEquals(200, r.getCode());
+        Map<?, ?> d = (Map<?, ?>) r.getData();
+        assertEquals(false, d.get("enabled"));
+        assertEquals(true, d.get("canUse"));
+        assertEquals("FREE", d.get("memberLevel"));
+    }
+
+    @Test
+    void gateStatus_开关开启_FREE用户canUseFalse() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(upgradeRequired());
+        Result<?> r = controller.aiCoachGateStatus(1L);
+        assertEquals(200, r.getCode());
+        Map<?, ?> d = (Map<?, ?>) r.getData();
+        assertEquals(true, d.get("enabled"));
+        assertEquals(false, d.get("canUse"));
+        assertEquals("FREE", d.get("memberLevel"));
+    }
+
+    @Test
+    void gateStatus_开关开启_FAMILY用户canUseTrue() {
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow("FAMILY"));
+        Result<?> r = controller.aiCoachGateStatus(1L);
+        assertEquals(200, r.getCode());
+        Map<?, ?> d = (Map<?, ?>) r.getData();
+        assertEquals(true, d.get("enabled"));
+        assertEquals(true, d.get("canUse"));
+        assertEquals("FAMILY", d.get("memberLevel"));
+    }
+}

+ 161 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/ai/ButlerControllerGateTest.java

@@ -0,0 +1,161 @@
+package com.etotem.cfc.controller.ai;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AiGateResult;
+import com.etotem.cfc.entity.ButlerSession;
+import com.etotem.cfc.enums.AiGateStatus;
+import com.etotem.cfc.service.ButlerSessionService;
+import com.etotem.cfc.service.MembershipService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * AI 管家门禁单元测试(T-B2,任务书 §3.2)。
+ *
+ * <p>/sessions/create 纳入门禁(FREE → 46003,过期 → 46004);
+ * list/detail/archive/delete/update-conversation 保持开放(决策 3:过期可查看/删除/归档历史)。</p>
+ */
+class ButlerControllerGateTest {
+
+    private ButlerController controller;
+    private ButlerSessionService butlerSessionService;
+    private MembershipService membershipService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new ButlerController();
+        butlerSessionService = mock(ButlerSessionService.class);
+        membershipService = mock(MembershipService.class);
+        inject("butlerSessionService", butlerSessionService);
+        inject("membershipService", membershipService);
+    }
+
+    private void inject(String name, Object value) throws Exception {
+        Field f = ButlerController.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(controller, value);
+    }
+
+    private AiGateResult gate(AiGateStatus status, boolean canUse, boolean canViewHistory) {
+        AiGateResult g = new AiGateResult();
+        g.setEnabled(true);
+        g.setStatus(status);
+        g.setCanUse(canUse);
+        g.setCanViewHistory(canViewHistory);
+        g.setMemberLevel("FREE");
+        g.setIsActive(status == AiGateStatus.ALLOW);
+        g.setReason(status == AiGateStatus.ALLOW ? null : status.name());
+        return g;
+    }
+
+    private Map<String, String> createParams() {
+        Map<String, String> p = new HashMap<>();
+        p.put("title", "新会话");
+        return p;
+    }
+
+    @Test
+    void create_FREE用户返回46003() {
+        when(membershipService.checkAiFeatureGate(1L))
+                .thenReturn(gate(AiGateStatus.UPGRADE_REQUIRED, false, false));
+        Result<Map<String, Object>> r = controller.createSession(1L, createParams());
+        assertEquals(46003, r.getCode());
+        verify(butlerSessionService, never()).createSession(anyLong(), anyString(), any());
+    }
+
+    @Test
+    void create_过期会员返回46004() {
+        when(membershipService.checkAiFeatureGate(1L))
+                .thenReturn(gate(AiGateStatus.MEMBER_EXPIRED, false, true));
+        Result<Map<String, Object>> r = controller.createSession(1L, createParams());
+        assertEquals(46004, r.getCode());
+        assertEquals("会员已过期,请续费后继续使用", r.getMessage());
+        verify(butlerSessionService, never()).createSession(anyLong(), anyString(), any());
+    }
+
+    @Test
+    void create_有效会员放行() {
+        when(membershipService.checkAiFeatureGate(1L))
+                .thenReturn(gate(AiGateStatus.ALLOW, true, true));
+        when(butlerSessionService.createSession(1L, "新会话", null)).thenReturn(99L);
+        Result<Map<String, Object>> r = controller.createSession(1L, createParams());
+        assertEquals(200, r.getCode());
+        assertEquals(99L, r.getData().get("sessionId"));
+    }
+
+    @Test
+    void create_开关关闭时FREE放行() {
+        AiGateResult allow = gate(AiGateStatus.ALLOW, true, true);
+        allow.setEnabled(false);
+        when(membershipService.checkAiFeatureGate(1L)).thenReturn(allow);
+        when(butlerSessionService.createSession(anyLong(), anyString(), any())).thenReturn(5L);
+        Result<Map<String, Object>> r = controller.createSession(1L, createParams());
+        assertEquals(200, r.getCode());
+    }
+
+    // ── 历史会话 CRUD 保持开放:不触发门禁 ──
+
+    @Test
+    void list_过期会员放行_不触发门禁() {
+        when(butlerSessionService.getSessionsByUser(1L, 1, 20, null)).thenReturn(new Page<>());
+        Result<?> r = controller.listSessions(1L, Collections.emptyMap());
+        assertEquals(200, r.getCode());
+        verifyNoInteractions(membershipService);
+    }
+
+    @Test
+    void detail_过期会员放行_不触发门禁() {
+        ButlerSession session = new ButlerSession();
+        session.setId(7L);
+        when(butlerSessionService.getSession(7L, 1L)).thenReturn(session);
+        Map<String, Object> p = new HashMap<>();
+        p.put("sessionId", 7L);
+        Result<?> r = controller.sessionDetail(1L, p);
+        assertEquals(200, r.getCode());
+        verifyNoInteractions(membershipService);
+    }
+
+    @Test
+    void archive_过期会员放行_不触发门禁() {
+        Map<String, Object> p = new HashMap<>();
+        p.put("sessionId", 7L);
+        Result<?> r = controller.archiveSession(1L, p);
+        assertEquals(200, r.getCode());
+        verify(butlerSessionService).archiveSession(7L, 1L);
+        verifyNoInteractions(membershipService);
+    }
+
+    @Test
+    void delete_过期会员放行_不触发门禁() {
+        when(butlerSessionService.deleteSession(7L, 1L)).thenReturn(true);
+        Map<String, Object> p = new HashMap<>();
+        p.put("sessionId", 7L);
+        Result<?> r = controller.deleteSession(1L, p);
+        assertEquals(200, r.getCode());
+        verifyNoInteractions(membershipService);
+    }
+
+    @Test
+    void updateConversation_过期会员放行_不触发门禁() {
+        ButlerSession session = new ButlerSession();
+        session.setId(7L);
+        when(butlerSessionService.getSession(7L, 1L)).thenReturn(session);
+        Map<String, Object> p = new HashMap<>();
+        p.put("sessionId", 7L);
+        p.put("conversationId", "conv-1");
+        Result<?> r = controller.updateConversationId(1L, p);
+        assertEquals(200, r.getCode());
+        verify(butlerSessionService).updateConversationId(7L, "conv-1");
+        verifyNoInteractions(membershipService);
+    }
+}

+ 65 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/butler/ButlerControllerEnvelopeTest.java

@@ -0,0 +1,65 @@
+package com.etotem.cfc.controller.butler;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerService;
+import com.etotem.cfc.service.RealNameBackfillService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * B-4/F1 契约级单测:管家端分页列表(POST /api/butler/members)envelope 统一为 data.records,
+ * 与活动/管理端列表一致,不再返回 data.list。
+ */
+public class ButlerControllerEnvelopeTest {
+
+    private ButlerController controller;
+    private UserMapper userMapper;
+
+    @BeforeEach
+    public void setUp() {
+        controller = new ButlerController();
+        userMapper = mock(UserMapper.class);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        ReflectionTestUtils.setField(controller, "butlerService", mock(ButlerService.class));
+        ReflectionTestUtils.setField(controller, "realNameBackfillService", mock(RealNameBackfillService.class));
+    }
+
+    @Test
+    public void members_returnsRecordsEnvelope() {
+        Page<User> page = new Page<>(1, 10);
+        User u = new User();
+        u.setId(7L);
+        u.setNickname("成员A");
+        page.setRecords(Collections.singletonList(u));
+        page.setTotal(1);
+        when(userMapper.selectPage(any(Page.class), any())).thenReturn(page);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("page", 1);
+        params.put("size", 10);
+        Result<Map<String, Object>> r = controller.getMembers(params, 1L);
+
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData(), "data 不能为 null");
+        assertNotNull(r.getData().get("records"), "分页 envelope 必须包含 data.records");
+        assertNull(r.getData().get("list"), "分页 envelope 不得再返回 data.list");
+        assertEquals(1, ((Number) r.getData().get("total")).longValue());
+        assertEquals(1, ((Number) r.getData().get("page")).intValue());
+        assertEquals(10, ((Number) r.getData().get("size")).intValue());
+    }
+}

+ 180 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/config/SleepConfigTagsMechanismContractTest.java

@@ -0,0 +1,180 @@
+package com.etotem.cfc.controller.config;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.SysConfigService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * S-cfc-31 · sleep.config.tags —— 后台配置读取/维护机制契约级单测(RED 阶段补齐)。
+ *
+ * <p>设计溯源:{@code PublicConfigController /api/config/public/value}(小程序端拉取
+ * {@code sleep.quality.tags} 配置值)+ {@code AdminGuideConfigController} get/save 模式
+ * (管理端维护配置的参考实现,见需求变更 C「后台维护睡眠情况选项」)。契约以
+ * 「已合入 origin/cfclub 的接口契约」为准。
+ *
+ * <p>覆盖:正常路径(配置值读取 / 解析返回 / 保存落库)+ 关键边界(key 缺失、
+ * 配置未配置返回 null、configValue 空拒绝、body 空拒绝)。纯单元测试:直接调用
+ * Controller + Mockito mock {@code SysConfigService},不依赖数据库/微信/外部服务。
+ */
+public class SleepConfigTagsMechanismContractTest {
+
+    private PublicConfigController publicConfigController;
+    private com.etotem.cfc.controller.admin.AdminGuideConfigController adminGuideConfigController;
+    private SysConfigService sysConfigService;
+
+    @BeforeEach
+    public void setUp() {
+        publicConfigController = new PublicConfigController();
+        adminGuideConfigController = new com.etotem.cfc.controller.admin.AdminGuideConfigController();
+        sysConfigService = mock(SysConfigService.class);
+        ReflectionTestUtils.setField(publicConfigController, "sysConfigService", sysConfigService);
+        ReflectionTestUtils.setField(adminGuideConfigController, "sysConfigService", sysConfigService);
+    }
+
+    // ====================================================================
+    // POST /api/config/public/value —— 小程序端拉取 sleep.quality.tags 配置值
+    // ====================================================================
+
+    @Test
+    public void publicValue_keyPresent_returnsStoredConfigValue() {
+        when(sysConfigService.getValue("sleep.quality.tags"))
+                .thenReturn("[\"入睡困难\",\"夜醒\",\"多梦\",\"打鼾\",\"早醒\",\"赖床\",\"熬夜\",\"午睡过长\",\"正常\"]");
+        Map<String, String> params = new HashMap<>();
+        params.put("key", "sleep.quality.tags");
+
+        Result<String> res = publicConfigController.getValue(params);
+
+        assertEquals(200, res.getCode());
+        assertNotNull(res.getData());
+        assertTrue(res.getData().contains("正常"), "默认 9 项配置必须包含「正常」");
+        assertTrue(res.getData().contains("午睡过长"), "默认配置应保留原 8 项");
+    }
+
+    @Test
+    public void publicValue_unconfiguredKey_returnsNullData_contractForFrontendFallback() {
+        // 配置缺失:返回 success(null),前端据此回退默认 9 项(不报错)
+        when(sysConfigService.getValue("sleep.quality.tags")).thenReturn(null);
+        Map<String, String> params = new HashMap<>();
+        params.put("key", "sleep.quality.tags");
+
+        Result<String> res = publicConfigController.getValue(params);
+
+        assertEquals(200, res.getCode(), "配置缺失不得报错(前端回退默认)");
+        assertNull(res.getData());
+    }
+
+    @Test
+    public void publicValue_missingKey_returnsError() {
+        Result<String> res = publicConfigController.getValue(new HashMap<>());
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("key"), "message 应指明缺失的 key");
+        verify(sysConfigService, never()).getValue(any());
+    }
+
+    @Test
+    public void publicValue_blankKey_returnsError() {
+        Map<String, String> params = new HashMap<>();
+        params.put("key", "   ");
+
+        Result<String> res = publicConfigController.getValue(params);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("key"));
+        verify(sysConfigService, never()).getValue(any());
+    }
+
+    // ====================================================================
+    // POST /api/admin/guide-config/get —— 管理端读取配置(未配置→null,前端用默认)
+    // ====================================================================
+
+    @Test
+    public void guideConfigGet_notConfigured_returnsNullData() {
+        when(sysConfigService.getValue("onboarding_guide_config")).thenReturn(null);
+
+        Result<Map<String, Object>> res = adminGuideConfigController.get();
+
+        assertEquals(200, res.getCode());
+        assertNull(res.getData(), "未配置时返回 null,前端使用默认值");
+    }
+
+    @Test
+    public void guideConfigGet_configured_returnsParsedMap() throws Exception {
+        when(sysConfigService.getValue("onboarding_guide_config"))
+                .thenReturn("{\"show\":true,\"items\":[{\"id\":\"a\",\"text\":\"引导A\"}]}");
+
+        Result<Map<String, Object>> res = adminGuideConfigController.get();
+
+        assertEquals(200, res.getCode());
+        assertNotNull(res.getData());
+        assertEquals(true, res.getData().get("show"));
+    }
+
+    @Test
+    public void guideConfigGet_malformedValue_returnsParseError() {
+        when(sysConfigService.getValue("onboarding_guide_config")).thenReturn("{not-json");
+
+        Result<Map<String, Object>> res = adminGuideConfigController.get();
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("解析失败"), "非法 JSON 应给出解析失败提示");
+    }
+
+    // ====================================================================
+    // POST /api/admin/guide-config/save —— 管理端保存配置(写语义)
+    // ====================================================================
+
+    @Test
+    public void guideConfigSave_validConfigValue_persists() {
+        Map<String, String> body = new HashMap<>();
+        body.put("configValue", "{\"show\":true}");
+        when(sysConfigService.update(any(), any(), any())).thenReturn(Result.success("ok"));
+
+        Result<String> res = adminGuideConfigController.save(body);
+
+        assertEquals(200, res.getCode());
+        ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
+        ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
+        verify(sysConfigService).update(keyCaptor.capture(), valueCaptor.capture(), eq("首页引导浮层配置"));
+        assertEquals("onboarding_guide_config", keyCaptor.getValue());
+        assertEquals("{\"show\":true}", valueCaptor.getValue());
+    }
+
+    @Test
+    public void guideConfigSave_emptyConfigValue_returnsError() {
+        Map<String, String> body = new HashMap<>();
+        body.put("configValue", "");
+
+        Result<String> res = adminGuideConfigController.save(body);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("configValue"), "message 应指明缺失的 configValue");
+        verify(sysConfigService, never()).update(any(), any(), any());
+    }
+
+    @Test
+    public void guideConfigSave_nullBody_returnsError() {
+        Result<String> res = adminGuideConfigController.save(null);
+
+        assertEquals(500, res.getCode());
+        assertTrue(res.getMessage().contains("configValue"));
+        verify(sysConfigService, never()).update(any(), any(), any());
+    }
+}

+ 159 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyInviteApproveRequestTest.java

@@ -0,0 +1,159 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.dto.JoinApproveDTO;
+import com.etotem.cfc.service.FamilyJoinRequestService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TC-FA-18~23 · 家庭加入「身份由邀请人审批时指定」契约.
+ *
+ * <p>场景来源:SRS 2026-11-07-family-join-dynamic-identity.md(e2eb3617d / 6567acc33 / 5bd559b6f)。
+ * 契约:{@code POST /api/family/invite/approve-request}
+ * 必须携带 {@code generationLevel}(辈分),{@code generationLevel=peer} 时还必须携带 {@code peerType};
+ * 缺参一律拒绝且不触达 service。</p>
+ *
+ * <p>MockMvc standalone + Mockito,不依赖数据库/微信/外部服务。</p>
+ */
+public class FamilyInviteApproveRequestTest {
+
+    @Mock
+    private FamilyJoinRequestService familyJoinRequestService;
+
+    private MockMvc mockMvc;
+
+    private static final String URL = "/api/family/invite/approve-request";
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        FamilyInviteController controller = new FamilyInviteController();
+        ReflectionTestUtils.setField(controller, "familyJoinRequestService", familyJoinRequestService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private String body(String requestId, String generationLevel, String peerType) {
+        StringBuilder sb = new StringBuilder("{");
+        if (requestId != null) {
+            sb.append("\"requestId\":").append(requestId).append(",");
+        }
+        if (generationLevel != null) {
+            sb.append("\"generationLevel\":\"").append(generationLevel).append("\",");
+        }
+        if (peerType != null) {
+            sb.append("\"peerType\":\"").append(peerType).append("\",");
+        }
+        if (sb.charAt(sb.length() - 1) == ',') {
+            sb.setLength(sb.length() - 1);
+        }
+        return sb.append("}").toString();
+    }
+
+    @Test
+    @DisplayName("TC-FA-18 未登录审批(无 userId 属性):400 绑定层拒绝且不触达 service")
+    public void anonymousApproveIsRejected() throws Exception {
+        mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON)
+                        .content(body("1", "parent", null)))
+                .andExpect(status().isBadRequest());
+
+        verify(familyJoinRequestService, never())
+                .approveJoinRequest(anyLong(), anyLong(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("TC-FA-19 requestId 缺失:拒绝且不触达 service")
+    public void missingRequestIdIsRejected() throws Exception {
+        mockMvc.perform(post(URL).requestAttr("userId", 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body(null, "parent", null)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("请求ID不能为空"));
+
+        verify(familyJoinRequestService, never())
+                .approveJoinRequest(anyLong(), anyLong(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("TC-FA-20 generationLevel 缺失:拒绝(身份必须由邀请人指定)")
+    public void missingGenerationLevelIsRejected() throws Exception {
+        mockMvc.perform(post(URL).requestAttr("userId", 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body("10", null, null)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("请选择辈分关系"));
+
+        verify(familyJoinRequestService, never())
+                .approveJoinRequest(anyLong(), anyLong(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("TC-FA-21 peer 辈分缺 peerType:拒绝(同辈类型必填)")
+    public void peerWithoutPeerTypeIsRejected() throws Exception {
+        mockMvc.perform(post(URL).requestAttr("userId", 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body("10", "peer", null)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("请选择同辈关系类型"));
+
+        verify(familyJoinRequestService, never())
+                .approveJoinRequest(anyLong(), anyLong(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("TC-FA-22 正常审批(parent):参数完整下传 service")
+    public void validParentApproveIsDelegated() throws Exception {
+        mockMvc.perform(post(URL).requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body("10", "parent", null)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(familyJoinRequestService, times(1))
+                .approveJoinRequest(eq(10L), eq(7L), eq(""), eq("parent"), any());
+    }
+
+    @Test
+    @DisplayName("TC-FA-23 正常审批(peer+sibling):同辈类型下传 service")
+    public void validPeerApproveIsDelegated() throws Exception {
+        mockMvc.perform(post(URL).requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body("11", "peer", "sibling")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(familyJoinRequestService, times(1))
+                .approveJoinRequest(eq(11L), eq(7L), eq(""), eq("peer"), eq("sibling"));
+    }
+
+    @Test
+    @DisplayName("TC-FA-24 service 抛异常:错误信息透传,不 5xx")
+    public void serviceFailureReturnsErrorResult() throws Exception {
+        doThrow(new RuntimeException("该申请已被处理")).when(familyJoinRequestService)
+                .approveJoinRequest(anyLong(), anyLong(), anyString(), anyString(), any());
+
+        mockMvc.perform(post(URL).requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body("12", "child", null)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("该申请已被处理"));
+    }
+}

+ 223 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerAddMemberTest.java

@@ -0,0 +1,223 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.dto.AddFamilyMemberDTO;
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-1 / 能力键 family.familyMembers.addMember):
+ * POST /api/family/member/add 添加家庭成员 的契约级单测。
+ *
+ * 契约(对应 API_REFERENCE.md §4.2 与 FamilyMembersController.addMember):
+ * - userId == null → Result code=500 message=「请先登录」,不触达 Service
+ * - 正常路径:Service 返回 VO → Result code=200 data=VO;若当前用户有家庭(userMapper.selectById 返回非空且 familyId 非空)
+ *   则额外触发 unlockGateService.refreshFamilyGates(familyId, userId)(创建家人成功后的通关解锁刷新)
+ * - 正常路径但用户查询为空 / 用户无家庭:仍 code=200,但不触发 refreshFamilyGates
+ * - Service 抛 IllegalArgumentException → code=500 message=异常信息
+ * - Service 抛 RuntimeException → code=500 message=异常信息
+ *
+ * 角色/权限口径:addMember 处理器无 @RequestAttribute("role"/"roles"),授权交由 Service 层
+ * (familyId=登录用户所属家庭)与 JwtInterceptor(匿名注入 userId=-1 被 401 拦截)承担;
+ * 本控制器唯一鉴权边界是 userId 空守卫,故本测试覆盖该守卫而非角色分支。
+ * 测试不依赖真实微信/外部服务:FamilyMemberService/UserMapper/UnlockGateService 全 mock。
+ */
+public class FamilyMembersControllerAddMemberTest {
+
+    @Mock private FamilyMemberService familyMemberService;
+    @Mock private UserService userService;
+    @Mock private UnlockGateService unlockGateService;
+    @Mock private UserMapper userMapper;
+
+    private MockMvc mockMvc;
+    private FamilyMembersController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new FamilyMembersController();
+        ReflectionTestUtils.setField(controller, "familyMemberService", familyMemberService);
+        ReflectionTestUtils.setField(controller, "unlockGateService", unlockGateService);
+        ReflectionTestUtils.setField(controller, "userService", userService);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private User user(Long id, Long familyId) {
+        User u = new User();
+        u.setId(id);
+        u.setFamilyId(familyId);
+        return u;
+    }
+
+    private static final String VALID_BODY = "{"
+            + "\"nickname\":\"小明\","
+            + "\"generationLevel\":\"child\","
+            + "\"relativeMemberId\":5,"
+            + "\"peerType\":null,"
+            + "\"phone\":\"13800001111\","
+            + "\"gender\":\"male\","
+            + "\"birthday\":\"2018-01-01\","
+            + "\"birthWeight\":3200,"
+            + "\"isAdmin\":0"
+            + "}";
+
+    @Test
+    public void addMember_success_userHasFamily_triggersGateRefresh() throws Exception {
+        Long userId = 1L;
+        Long familyId = 7L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(100L);
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class))).thenReturn(vo);
+        when(userMapper.selectById(userId)).thenReturn(user(userId, familyId));
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.id").value(100));
+
+        verify(unlockGateService).refreshFamilyGates(familyId, userId);
+    }
+
+    @Test
+    public void addMember_success_userNotFound_doesNotRefresh() throws Exception {
+        Long userId = 1L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(101L);
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class))).thenReturn(vo);
+        when(userMapper.selectById(userId)).thenReturn(null);
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.id").value(101));
+
+        verify(unlockGateService, never()).refreshFamilyGates(anyLong(), anyLong());
+    }
+
+    @Test
+    public void addMember_success_userWithoutFamily_doesNotRefresh() throws Exception {
+        Long userId = 1L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(102L);
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class))).thenReturn(vo);
+        when(userMapper.selectById(userId)).thenReturn(user(userId, null));
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.id").value(102));
+
+        verify(unlockGateService, never()).refreshFamilyGates(anyLong(), anyLong());
+    }
+
+    @Test
+    public void addMember_illegalArgument_returnsErrorMessage() throws Exception {
+        Long userId = 1L;
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class)))
+                .thenThrow(new IllegalArgumentException("成员昵称不能为空"));
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("成员昵称不能为空"));
+
+        verify(unlockGateService, never()).refreshFamilyGates(anyLong(), anyLong());
+    }
+
+    @Test
+    public void addMember_runtimeException_returnsErrorMessage() throws Exception {
+        Long userId = 1L;
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class)))
+                .thenThrow(new RuntimeException("用户未加入家庭,请先创建或加入家庭"));
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("用户未加入家庭,请先创建或加入家庭"));
+
+        verify(unlockGateService, never()).refreshFamilyGates(anyLong(), anyLong());
+    }
+
+    @Test
+    public void addMember_dtoDeserializedAndPassedToService() throws Exception {
+        Long userId = 1L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(103L);
+        when(familyMemberService.addMember(eq(userId), any(AddFamilyMemberDTO.class))).thenReturn(vo);
+
+        mockMvc.perform(post("/api/family/member/add")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(VALID_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        ArgumentCaptor<AddFamilyMemberDTO> captor = ArgumentCaptor.forClass(AddFamilyMemberDTO.class);
+        verify(familyMemberService).addMember(eq(userId), captor.capture());
+        AddFamilyMemberDTO dto = captor.getValue();
+        assertNotNull(dto);
+        assertEquals("小明", dto.getNickname());
+        assertEquals("child", dto.getGenerationLevel());
+        assertEquals(Long.valueOf(5L), dto.getRelativeMemberId());
+        assertEquals("13800001111", dto.getPhone());
+        assertEquals("male", dto.getGender());
+        assertEquals("2018-01-01", dto.getBirthday());
+        assertEquals(Integer.valueOf(3200), dto.getBirthWeight());
+        assertEquals(Integer.valueOf(0), dto.getIsAdmin());
+    }
+
+    /**
+     * userId 空守卫:MockMvc 的 @RequestAttribute 缺省 required=true 无法注入 null,
+     * 故按 FamilyControllerTest 先例直接调用控制器方法验证该守卫分支。
+     */
+    @Test
+    public void addMember_nullUserId_returnsLoginRequired() {
+        AddFamilyMemberDTO dto = new AddFamilyMemberDTO();
+        dto.setNickname("小明");
+        dto.setGenerationLevel("child");
+
+        com.etotem.cfc.common.Result<FamilyMemberVO> result = controller.addMember(dto, null);
+        assertEquals(Integer.valueOf(500), result.getCode());
+        assertEquals("请先登录", result.getMessage());
+
+        verify(familyMemberService, never()).addMember(anyLong(), any(AddFamilyMemberDTO.class));
+    }
+}

+ 147 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerListTest.java

@@ -0,0 +1,147 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * B2-1:family/member/list 支持 params.familyId + 行级隔离 + 删除 ensureUserFamily 兜底建家庭。
+ *
+ * 契约:
+ * - 传 familyId 且调用者在有效家庭集内(own family / teacher_family_ids / guide_families 绑定)→ 返回该家庭全部成员
+ * - 传 familyId 但调用者无权(platform 角色除外)→ Result code=403
+ * - 平台角色(admin/operator/finance)传任意 familyId → 放行
+ * - 不传 familyId → 返回本人家庭成员;绝不静默调用 ensureUserFamily 建家庭
+ */
+public class FamilyMembersControllerListTest {
+
+    @Mock
+    private FamilyMemberService familyMemberService;
+
+    @Mock
+    private UserService userService;
+
+    @Mock
+    private UnlockGateService unlockGateService;
+
+    @Mock
+    private UserMapper userMapper;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        FamilyMembersController controller = new FamilyMembersController();
+        ReflectionTestUtils.setField(controller, "familyMemberService", familyMemberService);
+        ReflectionTestUtils.setField(controller, "unlockGateService", unlockGateService);
+        ReflectionTestUtils.setField(controller, "userService", userService);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    public void listMembers_withFamilyId_andAccess_returnsMembersOfThatFamily() throws Exception {
+        Long userId = 1L;
+        Long familyId = 5L;
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(familyId));
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(11L);
+        when(familyMemberService.listMembersOfFamily(familyId, userId)).thenReturn(Arrays.asList(vo));
+
+        mockMvc.perform(post("/api/family/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"familyId\":5}")
+                        .requestAttr("userId", userId)
+                        .requestAttr("role", "teacher")
+                        .requestAttr("roles", Collections.singletonList("teacher")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].id").value(11));
+
+        verify(familyMemberService).listMembersOfFamily(familyId, userId);
+        verify(userService, never()).ensureUserFamily(any());
+    }
+
+    @Test
+    public void listMembers_withFamilyId_noAccess_returns403() throws Exception {
+        Long userId = 1L;
+        Long targetFamilyId = 99L;
+        when(userService.getEffectiveFamilyIds(userId)).thenReturn(Collections.singleton(5L));
+
+        mockMvc.perform(post("/api/family/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"familyId\":99}")
+                        .requestAttr("userId", userId)
+                        .requestAttr("role", "teacher")
+                        .requestAttr("roles", Collections.singletonList("teacher")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value("无权访问该家庭数据"));
+
+        verify(familyMemberService, never()).listMembersOfFamily(anyLong(), anyLong());
+    }
+
+    @Test
+    public void listMembers_withPlatformRole_anyFamilyAllowed() throws Exception {
+        Long userId = 1L;
+        Long familyId = 999L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(22L);
+        when(familyMemberService.listMembersOfFamily(familyId, userId)).thenReturn(Arrays.asList(vo));
+
+        mockMvc.perform(post("/api/family/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"familyId\":999}")
+                        .requestAttr("userId", userId)
+                        .requestAttr("role", "admin")
+                        .requestAttr("roles", Collections.singletonList("admin")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].id").value(22));
+
+        verify(familyMemberService).listMembersOfFamily(familyId, userId);
+        verify(userService, never()).getEffectiveFamilyIds(any());
+    }
+
+    @Test
+    public void listMembers_withoutFamilyId_usesOwnList_noAutoCreate() throws Exception {
+        Long userId = 1L;
+        FamilyMemberVO vo = new FamilyMemberVO();
+        vo.setId(33L);
+        when(familyMemberService.listMembers(userId)).thenReturn(Arrays.asList(vo));
+
+        mockMvc.perform(post("/api/family/member/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", userId)
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Collections.singletonList("parent")))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].id").value(33));
+
+        verify(familyMemberService).listMembers(userId);
+        verify(userService, never()).ensureUserFamily(any());
+    }
+}

+ 69 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/family/FamilyMembersControllerRenameFamilyTest.java

@@ -0,0 +1,69 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.service.UserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+public class FamilyMembersControllerRenameFamilyTest {
+
+    @Mock private FamilyMemberService familyMemberService;
+    @Mock private UserService userService;
+    @Mock private UnlockGateService unlockGateService;
+    @Mock private UserMapper userMapper;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        FamilyMembersController controller = new FamilyMembersController();
+        ReflectionTestUtils.setField(controller, "familyMemberService", familyMemberService);
+        ReflectionTestUtils.setField(controller, "unlockGateService", unlockGateService);
+        ReflectionTestUtils.setField(controller, "userService", userService);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    public void renameFamily_success() throws Exception {
+        when(familyMemberService.renameFamily(1L, "新家庭")).thenReturn("新家庭");
+
+        mockMvc.perform(post("/api/family/member/rename-family")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"name\":\"新家庭\"}")
+                        .requestAttr("userId", 1L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").value("新家庭"));
+
+        verify(familyMemberService).renameFamily(1L, "新家庭");
+    }
+
+    @Test
+    public void renameFamily_notAdmin_returnsError() throws Exception {
+        when(familyMemberService.renameFamily(1L, "新家庭"))
+                .thenThrow(new IllegalArgumentException("仅家庭管理员可修改家庭名称"));
+
+        mockMvc.perform(post("/api/family/member/rename-family")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"name\":\"新家庭\"}")
+                        .requestAttr("userId", 1L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("仅家庭管理员可修改家庭名称"));
+    }
+}

+ 210 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/growth/ChildGrowthArchiveContractTest.java

@@ -0,0 +1,210 @@
+package com.etotem.cfc.controller.growth;
+
+import com.etotem.cfc.entity.GrowthRecord;
+import com.etotem.cfc.service.GrowthRecordService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-cfc-217 / 能力键 {@code child.growth.archive} 契约级单测(TDD RED 阶段:契约新增、实现未落地,预期红)。
+ *
+ * <p>溯源·需求:`tests/user-scenarios/应用场景总览.md` SC-C-11(成长记录查看-孩子视角)、SC-C-20(成长档案查看/家长代导出)。
+ * <br>溯源·设计:`docs/superpowers/api/API_REFERENCE.md` §4.6 §4.61.9 G-11;
+ * `docs/superpowers/specs/2026-11-07-child-zone-contract.md` §5 G-11(跨切面:无归属校验)。
+ *
+ * <p>契约锚点(G-11):成长档案读端点 {@code POST /api/growth/record/child/{memberId}}、
+ * {@code POST /api/growth/record/child-records} 与 {@code POST /api/growth/record/{id}} 必须做
+ * 家庭归属校验(参考 {@code HealthPlanController /tasks} 的 familyId 校验口径)——任一登录用户不得
+ * 按 id 读取他人(跨家庭)的成长档案;越权访问应以业务码 <b>403</b> 拒绝,而不是返回他人数据。
+ *
+ * <p>RED 预期:{@link GrowthRecordController#getChildRecords(Long)} / {@code getRecordsByChild} /
+ * {@code getRecordDetail} 当前均无归属校验(方法签名未读取 familyId 请求属性),跨家庭读取会
+ * 直接返回 200+他人数据 → 本类「跨家庭拒绝」用例失败(红);同家庭正常路径用例为守住不误伤的
+ * 绿锚(当前无校验时可通过,GREEN 实现后仍须通过)。
+ *
+ * <p>测试隔离:MockMvc standalone + 仅 mock {@link GrowthRecordService},无 Spring 上下文 / 无 DB / 无外部服务。
+ */
+class ChildGrowthArchiveContractTest {
+
+    private static final Long PARENT_USER_ID = 1001L;
+    private static final Long MY_FAMILY_ID = 5001L;
+    private static final Long MY_MEMBER_ID = 2001L;
+    /** 跨家庭(他人家族)成员 id:不属于当前登录用户所在家庭 */
+    private static final Long FOREIGN_MEMBER_ID = 9001L;
+    private static final Long FOREIGN_RECORD_ID = 90001L;
+
+    private static final String MSG_MEMBER_FORBIDDEN = "无权访问该成员成长档案";
+    private static final String MSG_RECORD_FORBIDDEN = "无权访问该成长档案";
+
+    private GrowthRecordController controller;
+    private MockMvc mockMvc;
+    private GrowthRecordService growthRecordService;
+
+    @BeforeEach
+    void setUp() {
+        controller = new GrowthRecordController();
+        growthRecordService = mock(GrowthRecordService.class);
+        ReflectionTestUtils.setField(controller, "growthRecordService", growthRecordService);
+        // 归属校验实现(GREEN)需要注入的家族成员归属查询依赖不在本契约测试范围内,由 GREEN 阶段接线
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ================================================================
+    // G-11 契约一:POST /api/growth/record/child/{memberId} —— 成员归属校验
+    // ================================================================
+
+    @Test
+    @DisplayName("getChildRecords:跨家庭成员 - 必须 403 拒绝,不得返回他人档案(当前无校验 → 红)")
+    void childRecords_跨家庭成员_应拒绝读取_403() throws Exception {
+        // Given:他人家族成员即使存在档案,本用户也无权读取
+        List<GrowthRecord> foreignRecords = Collections.singletonList(
+                buildGrowthRecord(1L, FOREIGN_MEMBER_ID, "2026-06-15", "他人档案")
+        );
+        when(growthRecordService.getRecordsByChild(eq(FOREIGN_MEMBER_ID))).thenReturn(foreignRecords);
+
+        // When:携带本家庭 familyId/currentMemberId 请求属性(模拟 JwtInterceptor 注入)读取跨家庭成员档案
+        mockMvc.perform(post("/api/growth/record/child/" + FOREIGN_MEMBER_ID)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID)
+                        .requestAttr("familyId", MY_FAMILY_ID)
+                        .requestAttr("currentMemberId", MY_MEMBER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value(MSG_MEMBER_FORBIDDEN));
+
+        // Then:归属门禁应先于 Service 查询生效,绝不允许按他人 memberId 放行
+        verify(growthRecordService, never()).getRecordsByChild(eq(FOREIGN_MEMBER_ID));
+    }
+
+    @Test
+    @DisplayName("getChildRecords:同家庭成员 - 正常返回档案列表(绿锚,防归属校验误伤)")
+    void childRecords_同家庭成员_正常返回_200() throws Exception {
+        List<GrowthRecord> myRecords = Arrays.asList(
+                buildGrowthRecord(1L, MY_MEMBER_ID, "2026-06-15", "我的档案1"),
+                buildGrowthRecord(2L, MY_MEMBER_ID, "2026-03-01", "我的档案2")
+        );
+        when(growthRecordService.getRecordsByChild(eq(MY_MEMBER_ID))).thenReturn(myRecords);
+
+        mockMvc.perform(post("/api/growth/record/child/" + MY_MEMBER_ID)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID)
+                        .requestAttr("familyId", MY_FAMILY_ID)
+                        .requestAttr("currentMemberId", MY_MEMBER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(2))
+                .andExpect(jsonPath("$.data[0].childId").value(MY_MEMBER_ID));
+
+        verify(growthRecordService).getRecordsByChild(eq(MY_MEMBER_ID));
+    }
+
+    // ================================================================
+    // G-11 契约二:POST /api/growth/record/child-records —— 裸 memberId body 同受归属校验
+    // ================================================================
+
+    @Test
+    @DisplayName("getRecordsByChild(body):跨家庭成员 - 必须 403 拒绝(body 路径同受归属校验 → 红)")
+    void childRecordsByBody_跨家庭成员_应拒绝读取_403() throws Exception {
+        // Given:body 传裸 Long memberId(API 口径),目标成员属于其他家庭
+        List<GrowthRecord> foreignRecords = Collections.singletonList(
+                buildGrowthRecord(3L, FOREIGN_MEMBER_ID, "2026-06-15", "他人档案")
+        );
+        when(growthRecordService.getRecordsByChild(eq(FOREIGN_MEMBER_ID))).thenReturn(foreignRecords);
+
+        mockMvc.perform(post("/api/growth/record/child-records")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(String.valueOf(FOREIGN_MEMBER_ID))
+                        .requestAttr("userId", PARENT_USER_ID)
+                        .requestAttr("familyId", MY_FAMILY_ID)
+                        .requestAttr("currentMemberId", MY_MEMBER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value(MSG_MEMBER_FORBIDDEN));
+
+        // Then:归属门禁应拦截,不允许跨家庭按 memberId 放行
+        verify(growthRecordService, never()).getRecordsByChild(eq(FOREIGN_MEMBER_ID));
+    }
+
+    // ================================================================
+    // G-11 契约三:POST /api/growth/record/{id} —— 档案明细归属校验
+    // ================================================================
+
+    @Test
+    @DisplayName("getRecordDetail:跨家庭档案 - 必须 403 拒绝,不得按 id 读他人档案(当前无校验 → 红)")
+    void recordDetail_跨家庭档案_应拒绝读取_403() throws Exception {
+        // Given:档案存在但属于他人家族成员(memberId=FOREIGN_MEMBER_ID)
+        GrowthRecord foreignRecord = buildGrowthRecord(FOREIGN_RECORD_ID, FOREIGN_MEMBER_ID, "2026-06-15", "他人档案详情");
+        when(growthRecordService.getRecordById(eq(FOREIGN_RECORD_ID))).thenReturn(foreignRecord);
+
+        mockMvc.perform(post("/api/growth/record/" + FOREIGN_RECORD_ID)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID)
+                        .requestAttr("familyId", MY_FAMILY_ID)
+                        .requestAttr("currentMemberId", MY_MEMBER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value(MSG_RECORD_FORBIDDEN));
+
+        // Then:归属门禁生效——响应必须是 403 且不得把档案内容下发给调用方。
+        // R206 修正(B-206-4):原断言为 `verify(never().getRecordById(...))`,与实现自相矛盾——
+        // 归属门禁必须先读到 record 才能拿到 memberId 做 familyId 比对,因此 getRecordById
+        // 必然被调用 1 次。never() 使本用例成为**永久假红**(code=403 已绿,仅 never() 恒失败),
+        // 反而掩盖了「G-11 归属门禁已真实生效」这一事实。改为断言「只读 1 次且绝不返回数据」。
+        verify(growthRecordService, times(1)).getRecordById(eq(FOREIGN_RECORD_ID));
+    }
+
+    @Test
+    @DisplayName("getRecordDetail:同家庭档案 - 正常返回明细(绿锚,防归属校验误伤)")
+    void recordDetail_同家庭档案_正常返回_200() throws Exception {
+        GrowthRecord myRecord = buildGrowthRecord(4L, MY_MEMBER_ID, "2026-06-15", "我的档案详情");
+        when(growthRecordService.getRecordById(eq(4L))).thenReturn(myRecord);
+
+        mockMvc.perform(post("/api/growth/record/4")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID)
+                        .requestAttr("familyId", MY_FAMILY_ID)
+                        .requestAttr("currentMemberId", MY_MEMBER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.childId").value(MY_MEMBER_ID))
+                .andExpect(jsonPath("$.data.recordTitle").value("我的档案详情"));
+
+        verify(growthRecordService).getRecordById(eq(4L));
+    }
+
+    // ================================================================
+    // Helpers
+    // ================================================================
+
+    private GrowthRecord buildGrowthRecord(Long id, Long memberId, String dateStr, String title) {
+        GrowthRecord r = new GrowthRecord();
+        r.setId(id);
+        r.setMemberId(memberId);
+        r.setRecordTitle(title);
+        try {
+            r.setCreatedAt(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
+        } catch (Exception ignored) {
+        }
+        return r;
+    }
+}

+ 44 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/growth/GrowthAuthContractTest.java

@@ -0,0 +1,44 @@
+package com.etotem.cfc.controller.growth;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.web.servlet.MockMvc;
+
+/**
+ * 成长板块鉴权契约(回归):/api/growth/record/** 与 /api/growth/plan/** 为成员私有数据,
+ * 匿名(无 token)访问必须由 JwtInterceptor 直接返回 HTTP 401(writeUnauthorized 写 401 + {"code":401}),
+ * 而非匿名(userId=-1 / userId 缺失)放行到 controller 后走"业务 500"口径漂移。
+ *
+ * <p>回归根因:/api/growth/** 此前同时存在于 WebConfig 的 jwtInterceptor excludePathPatterns
+ * (拦截器对 growth 整族从不执行 → @RequestAttribute("userId") 永不注入)与
+ * JwtInterceptor.PUBLIC_PATHS(匿名放行)中,导致 GET /api/growth/record/list 带不带 token 一律
+ * 500 "Missing request attribute 'userId'"。本测试走完整 WebConfig→JwtInterceptor 注册链,
+ * 能同时捕捉两处缺陷(若 WebConfig 仍排除 growth,请求将穿透到 controller 返回 500 而非 401)。
+ */
+@SpringBootTest
+@AutoConfigureMockMvc
+class GrowthAuthContractTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @Test
+    void 匿名访问成长记录列表_应401() throws Exception {
+        mockMvc.perform(post("/api/growth/record/list"))
+                .andExpect(status().isUnauthorized())
+                .andExpect(jsonPath("$.code").value(401));
+    }
+
+    @Test
+    void 匿名访问成长方案列表_应401() throws Exception {
+        mockMvc.perform(post("/api/growth/plan/list"))
+                .andExpect(status().isUnauthorized())
+                .andExpect(jsonPath("$.code").value(401));
+    }
+}

+ 291 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/growth/GrowthHistoryViewContractTest.java

@@ -0,0 +1,291 @@
+package com.etotem.cfc.controller.growth;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.GrowthRecord;
+import com.etotem.cfc.service.GrowthRecordService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-cfc-30 / growth.history.view 契约级单测(RED 阶段:补齐「未覆盖」能力键的最小闭环)。
+ *
+ * <p>目标端点({@link GrowthRecordController},@RequestMapping("/api/growth")):
+ * <ul>
+ *   <li>{@code POST /record/list} → {@link GrowthRecordController#getRecordList(Long)} —— 查询当前登录用户的成长档案列表(父视角)</li>
+ *   <li>{@code POST /record/child/{memberId}} → {@link GrowthRecordController#getChildRecords(Long)} —— 查询指定家庭成员的成长档案列表</li>
+ *   <li>{@code POST /record/{id}} → {@link GrowthRecordController#getRecordDetail(Long)} —— 查询单条档案明细(回链)</li>
+ *   <li>{@code POST /record/{id}/supplements} → {@link GrowthRecordController#getSupplements(Long)} —— 查询某条档案的全部补充记录</li>
+ * </ul>
+ *
+ * <p>覆盖维度:
+ * <ul>
+ *   <li>正常路径:返回 200 + data(数组/对象),验证业务字段完整性</li>
+ *   <li>关键边界:空列表、单条不存在(404 语义以业务码 500+message 表达)、空补充记录</li>
+ *   <li>角色/权限:仅有登录拦截器(JwtInterceptor)层面的鉴权;控制器内无 teacher/admin 区分,
+ *       所有读端点按 {@code userId}/{@code currentMemberId} 请求属性做用户级隔离,客户端不可通过请求体/查询参数越权。
+ *       <br>成长历史记录属 C 端(家长/孩子视角)能力,teacher 以同一口径访问自己的记录即可,admin 无特殊路径。
+ * </ul>
+ *
+ * <p>契约口径(对齐项目惯例:控制器签名 {@code Result<T>} + HTTP 200 信封、业务码表达语义):
+ * <ul>
+ *   <li>成功 → 业务码 200 + data(数组或对象)</li>
+ *   <li>资源不存在(getRecordDetail 找不到记录) → 业务码 500 + message "档案不存在"(HTTP 200 信封)</li>
+ *   <li>空列表/空补充记录 → 业务码 200 + 空数组 []</li>
+ * </ul>
+ * 测试隔离:MockMvc standalone + 仅 mock {@link GrowthRecordService},无 Spring 上下文 / 无 DB / 无外部服务。
+ */
+class GrowthHistoryViewContractTest {
+
+    private static final Long PARENT_USER_ID = 1001L;
+    private static final Long CHILD_MEMBER_ID = 2001L;
+    private static final Long RECORD_ID_1 = 1L;
+    private static final Long RECORD_ID_2 = 2L;
+    private static final Long RECORD_ID_3 = 3L;
+
+    private GrowthRecordController controller;
+    private MockMvc mockMvc;
+    private GrowthRecordService growthRecordService;
+
+    @BeforeEach
+    void setUp() {
+        controller = new GrowthRecordController();
+        growthRecordService = mock(GrowthRecordService.class);
+        ReflectionTestUtils.setField(controller, "growthRecordService", growthRecordService);
+        // 其他依赖不被读端点使用,无需打桩
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ================================================================
+    // POST /api/growth/record/list —— 查询当前用户的成长档案列表
+    // ================================================================
+
+    @Test
+    @DisplayName("getRecordList:正常路径 - 有多条档案记录,按创建时间倒序返回")
+    void getRecordList_正常路径_返回档案列表() throws Exception {
+        // Given:父视角下有 3 条档案
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                buildGrowthRecord(RECORD_ID_1, CHILD_MEMBER_ID, "2026-06-15", "本学期体测报告"),
+                buildGrowthRecord(RECORD_ID_2, CHILD_MEMBER_ID, "2026-03-01", "期中测评记录"),
+                buildGrowthRecord(RECORD_ID_3, CHILD_MEMBER_ID, "2025-12-20", "年度综合评价")
+        );
+        when(growthRecordService.getRecordsByParent(eq(PARENT_USER_ID))).thenReturn(mockRecords);
+
+        // When:携带 userId 请求属性(模拟 JwtInterceptor 注入)调用列表端点
+        mockMvc.perform(post("/api/growth/record/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(3))
+                .andExpect(jsonPath("$.data[0].id").value(RECORD_ID_1))
+                .andExpect(jsonPath("$.data[0].childId").value(CHILD_MEMBER_ID))
+                .andExpect(jsonPath("$.data[0].recordTitle").value("本学期体测报告"))
+                .andExpect(jsonPath("$.data[1].id").value(RECORD_ID_2))
+                .andExpect(jsonPath("$.data[2].id").value(RECORD_ID_3));
+
+        // Then:Service 按 userId 查询,体现用户级隔离
+        verify(growthRecordService).getRecordsByParent(eq(PARENT_USER_ID));
+    }
+
+    @Test
+    @DisplayName("getRecordList:边界 - 无档案记录,返回空数组(空态合理)")
+    void getRecordList_空列表_返回空数组() throws Exception {
+        when(growthRecordService.getRecordsByParent(eq(PARENT_USER_ID))).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post("/api/growth/record/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(0));
+
+        verify(growthRecordService).getRecordsByParent(eq(PARENT_USER_ID));
+    }
+
+    @Test
+    @DisplayName("getRecordList:权限边界 - 客户端请求体/查询参数携带 userId 无法覆盖服务端 userId 属性(数据隔离契约)")
+    void getRecordList_数据隔离_仅读服务端userId属性() throws Exception {
+        // Given:只有属性 userId=1001 会被读取;body 中即使传 userId=999 也无效
+        List<GrowthRecord> mockRecords = Collections.singletonList(
+                buildGrowthRecord(RECORD_ID_1, CHILD_MEMBER_ID, "2026-06-15", "仅自己可见")
+        );
+        when(growthRecordService.getRecordsByParent(eq(PARENT_USER_ID))).thenReturn(mockRecords);
+
+        // When:发送 JSON body 试图覆盖 userId,实际 handler 只读 @RequestAttribute("userId")
+        mockMvc.perform(post("/api/growth/record/list")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"userId\": 999}") // 被忽略
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(1));
+
+        // Then:Service 仍按属性 userId=1001 查询,未被 body 影响
+        ArgumentCaptor<Long> userIdCaptor = ArgumentCaptor.forClass(Long.class);
+        verify(growthRecordService).getRecordsByParent(userIdCaptor.capture());
+        assertEquals(PARENT_USER_ID, userIdCaptor.getValue());
+    }
+
+    // ================================================================
+    // POST /api/growth/record/child/{memberId} —— 查询指定家庭成员的档案列表
+    // ================================================================
+
+    @Test
+    @DisplayName("getChildRecords:正常路径 - 指定成员有档案,返回列表")
+    void getChildRecords_正常路径_返回成员档案列表() throws Exception {
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                buildGrowthRecord(RECORD_ID_1, CHILD_MEMBER_ID, "2026-06-15", "孩子档案1"),
+                buildGrowthRecord(RECORD_ID_2, CHILD_MEMBER_ID, "2026-03-01", "孩子档案2")
+        );
+        when(growthRecordService.getRecordsByChild(eq(CHILD_MEMBER_ID))).thenReturn(mockRecords);
+
+        mockMvc.perform(post("/api/growth/record/child/" + CHILD_MEMBER_ID)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(2))
+                .andExpect(jsonPath("$.data[0].childId").value(CHILD_MEMBER_ID));
+
+        verify(growthRecordService).getRecordsByChild(eq(CHILD_MEMBER_ID));
+    }
+
+    @Test
+    @DisplayName("getChildRecords:边界 - 成员无档案,返回空数组")
+    void getChildRecords_空列表_返回空数组() throws Exception {
+        when(growthRecordService.getRecordsByChild(eq(CHILD_MEMBER_ID))).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post("/api/growth/record/child/" + CHILD_MEMBER_ID)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(0));
+
+        verify(growthRecordService).getRecordsByChild(eq(CHILD_MEMBER_ID));
+    }
+
+    // ================================================================
+    // POST /api/growth/record/{id} —— 查询单条档案明细(回链)
+    // ================================================================
+
+    @Test
+    @DisplayName("getRecordDetail:正常路径 - 档案存在,返回完整对象")
+    void getRecordDetail_正常路径_返回档案明细() throws Exception {
+        GrowthRecord record = buildGrowthRecord(RECORD_ID_1, CHILD_MEMBER_ID, "2026-06-15", "体测报告详情");
+        record.setOverallScore(85);
+        record.setAssessmentSummary("综合评分优秀");
+        record.setGrowthSuggestions("建议加强体能训练");
+        when(growthRecordService.getRecordById(eq(RECORD_ID_1))).thenReturn(record);
+
+        mockMvc.perform(post("/api/growth/record/" + RECORD_ID_1)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.id").value(RECORD_ID_1))
+                .andExpect(jsonPath("$.data.childId").value(CHILD_MEMBER_ID))
+                .andExpect(jsonPath("$.data.recordTitle").value("体测报告详情"))
+                .andExpect(jsonPath("$.data.overallScore").value(85))
+                .andExpect(jsonPath("$.data.assessmentSummary").value("综合评分优秀"))
+                .andExpect(jsonPath("$.data.growthSuggestions").value("建议加强体能训练"));
+
+        verify(growthRecordService).getRecordById(eq(RECORD_ID_1));
+    }
+
+    @Test
+    @DisplayName("getRecordDetail:边界 - 档案不存在,返回业务码 500 + message")
+    void getRecordDetail_不存在_返回错误信息() throws Exception {
+        when(growthRecordService.getRecordById(eq(RECORD_ID_1))).thenReturn(null);
+
+        mockMvc.perform(post("/api/growth/record/" + RECORD_ID_1)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("档案不存在"));
+
+        verify(growthRecordService).getRecordById(eq(RECORD_ID_1));
+    }
+
+    // ================================================================
+    // POST /api/growth/record/{id}/supplements —— 查询某条档案的全部补充记录
+    // ================================================================
+
+    @Test
+    @DisplayName("getSupplements:正常路径 - 有补充记录,返回列表")
+    void getSupplements_正常路径_返回补充记录列表() throws Exception {
+        List<GrowthRecord> supplements = Arrays.asList(
+                buildGrowthRecord(101L, CHILD_MEMBER_ID, "2026-07-01", "补充记录:复测报告"),
+                buildGrowthRecord(102L, CHILD_MEMBER_ID, "2026-08-15", "补充记录:医生回访")
+        );
+        when(growthRecordService.getSupplements(eq(RECORD_ID_1))).thenReturn(supplements);
+
+        mockMvc.perform(post("/api/growth/record/" + RECORD_ID_1 + "/supplements")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(2))
+                .andExpect(jsonPath("$.data[0].recordTitle").value("补充记录:复测报告"))
+                .andExpect(jsonPath("$.data[1].recordTitle").value("补充记录:医生回访"));
+
+        verify(growthRecordService).getSupplements(eq(RECORD_ID_1));
+    }
+
+    @Test
+    @DisplayName("getSupplements:边界 - 无补充记录,返回空数组")
+    void getSupplements_空列表_返回空数组() throws Exception {
+        when(growthRecordService.getSupplements(eq(RECORD_ID_1))).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post("/api/growth/record/" + RECORD_ID_1 + "/supplements")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("userId", PARENT_USER_ID))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data.length()").value(0));
+
+        verify(growthRecordService).getSupplements(eq(RECORD_ID_1));
+    }
+
+    // ================================================================
+    // Helpers
+    // ================================================================
+
+    private GrowthRecord buildGrowthRecord(Long id, Long memberId, String dateStr, String title) {
+        GrowthRecord r = new GrowthRecord();
+        r.setId(id);
+        r.setMemberId(memberId);
+        r.setRecordTitle(title);
+        try {
+            r.setCreatedAt(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
+        } catch (Exception ignored) {
+        }
+        return r;
+    }
+}

+ 61 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TeacherMessageControllerMyTest.java

@@ -0,0 +1,61 @@
+package com.etotem.cfc.controller.guide;
+
+import com.etotem.cfc.entity.TeacherMessage;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.TeacherMessageService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Date;
+
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+public class TeacherMessageControllerMyTest {
+
+    @Mock private TeacherMessageService teacherMessageService;
+    @Mock private UserMapper userMapper;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        TeacherMessageController controller = new TeacherMessageController();
+        ReflectionTestUtils.setField(controller, "teacherMessageService", teacherMessageService);
+        ReflectionTestUtils.setField(controller, "userMapper", userMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    public void myMessages_enrichesTeacherName() throws Exception {
+        TeacherMessage msg = new TeacherMessage();
+        msg.setId(1L); msg.setParentId(10L); msg.setTeacherId(5L);
+        msg.setContent("孩子最近注意力不集中"); msg.setReplyContent("建议增加运动量");
+        msg.setStatus("replied"); msg.setCreatedAt(new Date());
+        when(teacherMessageService.getMessagesByParent(10L)).thenReturn(Arrays.asList(msg));
+
+        User teacher = new User(); teacher.setId(5L); teacher.setNickname("王规划师");
+        when(userMapper.selectById(5L)).thenReturn(teacher);
+
+        mockMvc.perform(post("/api/guide/messages/my")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 10L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].teacherName").value("王规划师"));
+
+        verify(teacherMessageService).getMessagesByParent(10L);
+    }
+}

+ 200 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TrainingPlanControllerGetPlanDetailTest.java

@@ -0,0 +1,200 @@
+package com.etotem.cfc.controller.guide;
+
+import com.etotem.cfc.entity.TrainingPlan;
+import com.etotem.cfc.entity.TrainingPlanItem;
+import com.etotem.cfc.service.TrainingPlanService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约级单测:{@link TrainingPlanController#getPlanDetail}(能力键 guide.trainingPlan.getPlanDetail,
+ * 任务 S-cfc-6,应 TR-1 请求由测试角色补写)。
+ *
+ * 端点:POST /api/guide/training-plans/detail
+ *
+ * 契约要点(按 AGENTS.md 与 TR-1 详情):
+ *  - 统一 @PostMapping(GET 应 405);
+ *  - 统一 Result<T> 包装(成功 code=200;业务拒绝走 Result.error → code=500 + message);
+ *  - planId 解析:body.planId 经 ParamUtils.getLong,null/空串/非数字均视为"未传" →
+ *    Result.error("planId不能为空");
+ *  - 方案不存在:getPlanById 返回 null → Result.error("方案不存在");
+ *  - 成功响应:data 为 LinkedHashMap,含 plan(TrainingPlan)与 items(List<TrainingPlanItem>)两键;
+ *    items 为空集合时返回空数组而非 null。
+ *
+ * 角色/权限说明(缺陷观察,不在本测试断言为红灯):
+ *  - 本 handler 在控制器层不读取 @RequestAttribute("role"),也无 @RequestAttribute("userId"),
+ *    且未列入 JwtInterceptor 的 LOGIN_REQUIRED_PATHS;
+ *  - "规划师角色约束"名义上成立,实际任何已认证角色(乃至匿名 userId=-1)均可到达 handler,
+ *    属潜在越权/鉴权缺口(与同文件 getPlanList 既有观察一致),已按 TR-1 要求记录并回写研发侧。
+ *
+ * 测试隔离:MockMvc standalone + mock TrainingPlanService,无 Spring 上下文 / 无 DB。
+ */
+class TrainingPlanControllerGetPlanDetailTest {
+
+    private static final String URL = "/api/guide/training-plans/detail";
+
+    @Mock
+    private TrainingPlanService trainingPlanService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        TrainingPlanController controller = new TrainingPlanController();
+        ReflectionTestUtils.setField(controller, "trainingPlanService", trainingPlanService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private TrainingPlan plan(long id, long guideId, Long memberId, String title, String status) {
+        TrainingPlan p = new TrainingPlan();
+        p.setId(id);
+        p.setGuideId(guideId);
+        p.setMemberId(memberId);
+        p.setTitle(title);
+        p.setStatus(status);
+        return p;
+    }
+
+    private TrainingPlanItem item(long id, long planId, int sequence, String taskTitle) {
+        TrainingPlanItem i = new TrainingPlanItem();
+        i.setId(id);
+        i.setPlanId(planId);
+        i.setSequence(sequence);
+        i.setTaskTitle(taskTitle);
+        return i;
+    }
+
+    // ==================== 正常路径 ====================
+
+    @Test
+    void getPlanDetail_planId有效_返回plan与items() throws Exception {
+        TrainingPlan plan = plan(9L, 7L, 20L, "暑期认知训练", "published");
+        TrainingPlanItem i1 = item(101L, 9L, 1, "舒尔特方格");
+        TrainingPlanItem i2 = item(102L, 9L, 2, "数字记忆");
+        when(trainingPlanService.getPlanById(9L)).thenReturn(plan);
+        when(trainingPlanService.getPlanItems(9L)).thenReturn(Arrays.asList(i1, i2));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":9}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data.plan.id").value(9))
+                .andExpect(jsonPath("$.data.plan.title").value("暑期认知训练"))
+                .andExpect(jsonPath("$.data.plan.status").value("published"))
+                .andExpect(jsonPath("$.data.items.length()").value(2))
+                .andExpect(jsonPath("$.data.items[0].id").value(101))
+                .andExpect(jsonPath("$.data.items[0].taskTitle").value("舒尔特方格"))
+                .andExpect(jsonPath("$.data.items[1].sequence").value(2));
+
+        verify(trainingPlanService).getPlanById(9L);
+        verify(trainingPlanService).getPlanItems(9L);
+    }
+
+    // ==================== planId 解析边界 ====================
+
+    @Test
+    void getPlanDetail_planId缺失_返回planId不能为空() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("planId不能为空"));
+
+        verify(trainingPlanService, never()).getPlanById(org.mockito.ArgumentMatchers.anyLong());
+        verify(trainingPlanService, never()).getPlanItems(org.mockito.ArgumentMatchers.anyLong());
+    }
+
+    @Test
+    void getPlanDetail_planId为null_返回planId不能为空() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":null}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("planId不能为空"));
+    }
+
+    @Test
+    void getPlanDetail_planId空字符串视为未传() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":\"\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("planId不能为空"));
+    }
+
+    @Test
+    void getPlanDetail_planId非数字视为未传() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":\"abc\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("planId不能为空"));
+    }
+
+    // ==================== 方案不存在 ====================
+
+    @Test
+    void getPlanDetail_方案不存在_返回方案不存在() throws Exception {
+        when(trainingPlanService.getPlanById(999L)).thenReturn(null);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":999}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("方案不存在"));
+
+        verify(trainingPlanService).getPlanById(999L);
+        verify(trainingPlanService, never()).getPlanItems(org.mockito.ArgumentMatchers.anyLong());
+    }
+
+    // ==================== 响应契约 ====================
+
+    @Test
+    void getPlanDetail_空项目列表_items为空数组而非null() throws Exception {
+        TrainingPlan plan = plan(5L, 7L, null, "空方案", "draft");
+        when(trainingPlanService.getPlanById(5L)).thenReturn(plan);
+        when(trainingPlanService.getPlanItems(5L)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"planId\":5}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.plan.id").value(5))
+                .andExpect(jsonPath("$.data.items").isArray())
+                .andExpect(jsonPath("$.data.items").isEmpty());
+    }
+
+    // ==================== 传输层契约 ====================
+
+    @Test
+    void getPlanDetail_仅允许POST_GET请求返回405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+}

+ 230 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/guide/TrainingPlanControllerGetPlanListTest.java

@@ -0,0 +1,230 @@
+package com.etotem.cfc.controller.guide;
+
+import com.etotem.cfc.entity.TrainingPlan;
+import com.etotem.cfc.service.TrainingPlanService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约级单测:{@link TrainingPlanController#getPlanList}(能力键 guide.trainingPlan.getPlanList)。
+ *
+ * 端点:POST /api/guide/training-plans/list
+ *
+ * 契约要点(按 AGENTS.md):
+ *  - 统一 @PostMapping(GET 应 405);
+ *  - 统一 Result<T> 包装(code=200 / message=success / data=方案列表);
+ *  - memberId 解析:body.memberId 优先,其次 @RequestAttribute currentMemberId 回退,
+ *    两者皆无时查规划师全部方案;null/空串/非数字均视为"未传"(ParamUtils 语义)。
+ *
+ * 角色/权限说明(缺陷观察,不在此断言为绿灯):
+ *  - 本 handler 在控制器层不做角色校验(不读 @RequestAttribute("role")),
+ *    也未列入 JwtInterceptor 的 LOGIN_REQUIRED_PATHS;
+ *  - 因此"受规划师角色调用约束"仅在名义上成立,实际任何已认证角色(甚至匿名
+ *    userId=-1)都可到达 handler,属潜在越权/鉴权缺口,已记录并交编排侧决策。
+ *
+ * 测试隔离:MockMvc standalone + mock TrainingPlanService,无 Spring 上下文 / 无 DB。
+ */
+class TrainingPlanControllerGetPlanListTest {
+
+    private static final String URL = "/api/guide/training-plans/list";
+
+    @Mock
+    private TrainingPlanService trainingPlanService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        TrainingPlanController controller = new TrainingPlanController();
+        ReflectionTestUtils.setField(controller, "trainingPlanService", trainingPlanService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private TrainingPlan plan(long id, long guideId, Long memberId, String title, String status) {
+        TrainingPlan p = new TrainingPlan();
+        p.setId(id);
+        p.setGuideId(guideId);
+        p.setMemberId(memberId);
+        p.setTitle(title);
+        p.setStatus(status);
+        return p;
+    }
+
+    // ==================== 正常路径 ====================
+
+    @Test
+    void getPlanList_未传memberId_按规划师查全部方案() throws Exception {
+        TrainingPlan plan = plan(1L, 7L, null, "暑期认知训练", "draft");
+        when(trainingPlanService.getPlansByGuide(7L)).thenReturn(Collections.singletonList(plan));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data[0].id").value(1))
+                .andExpect(jsonPath("$.data[0].title").value("暑期认知训练"));
+
+        verify(trainingPlanService).getPlansByGuide(7L);
+        verify(trainingPlanService, never()).getPlansByGuideAndChild(eq(7L), eq(null));
+    }
+
+    @Test
+    void getPlanList_body传memberId_按成员查方案() throws Exception {
+        TrainingPlan plan = plan(2L, 7L, 20L, "注意力专项", "published");
+        when(trainingPlanService.getPlansByGuideAndChild(7L, 20L))
+                .thenReturn(Collections.singletonList(plan));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":20}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].id").value(2))
+                .andExpect(jsonPath("$.data[0].status").value("published"));
+
+        verify(trainingPlanService).getPlansByGuideAndChild(7L, 20L);
+        verify(trainingPlanService, never()).getPlansByGuide(7L);
+    }
+
+    // ==================== memberId 解析边界 ====================
+
+    @Test
+    void getPlanList_无bodymemberId回退currentMemberId属性() throws Exception {
+        when(trainingPlanService.getPlansByGuideAndChild(7L, 77L))
+                .thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 7L)
+                        .requestAttr("currentMemberId", 77L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data").isEmpty());
+
+        verify(trainingPlanService).getPlansByGuideAndChild(7L, 77L);
+        verify(trainingPlanService, never()).getPlansByGuide(7L);
+    }
+
+    @Test
+    void getPlanList_bodymemberId优先于currentMemberId() throws Exception {
+        when(trainingPlanService.getPlansByGuideAndChild(7L, 20L))
+                .thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":20}")
+                        .requestAttr("userId", 7L)
+                        .requestAttr("currentMemberId", 77L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(trainingPlanService).getPlansByGuideAndChild(7L, 20L);
+        verify(trainingPlanService, never()).getPlansByGuide(7L);
+    }
+
+    @Test
+    void getPlanList_memberId空字符串视为未传() throws Exception {
+        when(trainingPlanService.getPlansByGuide(7L)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":\"\"}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(trainingPlanService).getPlansByGuide(7L);
+    }
+
+    @Test
+    void getPlanList_memberId非数字视为未传() throws Exception {
+        when(trainingPlanService.getPlansByGuide(7L)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":\"abc\"}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(trainingPlanService).getPlansByGuide(7L);
+    }
+
+    // ==================== 响应契约 ====================
+
+    @Test
+    void getPlanList_空列表返回空data() throws Exception {
+        when(trainingPlanService.getPlansByGuide(7L)).thenReturn(Collections.emptyList());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data").isArray())
+                .andExpect(jsonPath("$.data").isEmpty());
+    }
+
+    @Test
+    void getPlanList_返回完整方案列表() throws Exception {
+        TrainingPlan a = plan(1L, 7L, null, "方案A", "draft");
+        TrainingPlan b = plan(2L, 7L, 20L, "方案B", "published");
+        when(trainingPlanService.getPlansByGuide(7L)).thenReturn(Arrays.asList(a, b));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}")
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(2))
+                .andExpect(jsonPath("$.data[0].id").value(1))
+                .andExpect(jsonPath("$.data[1].id").value(2))
+                .andExpect(jsonPath("$.data[1].childId").value(20));
+    }
+
+    // ==================== 传输层契约 ====================
+
+    @Test
+    void getPlanList_仅允许POST_GET请求返回405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    @Test
+    void getPlanList_缺userId属性_请求被拒400() throws Exception {
+        // @RequestAttribute("userId") 为必需:handler 依赖 JwtInterceptor 注入该属性。
+        // 缺失时 Spring 抛 ServletRequestBindingException,由 DefaultHandlerExceptionResolver 映射为 400。
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isBadRequest());
+    }
+}

+ 267 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/reward/RewardEstimateControllerEstimateTest.java

@@ -0,0 +1,267 @@
+package com.etotem.cfc.controller.reward;
+
+import com.etotem.cfc.dto.RewardDisplayVO;
+import com.etotem.cfc.dto.RewardEstimateRequest;
+import com.etotem.cfc.dto.RewardEstimateVO;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.RewardMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.RewardRuleService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约级单测:{@link RewardEstimateController#estimate}(SC-X-22 CF 值获取预估,预估专用端点
+ * {@code POST /api/reward/estimate},应本轮 SRS 变更由测试角色补写)。
+ *
+ * 关联需求:docs/superpowers/specs/2026-11-05-sc-x22-cf-estimate-contract.md(v1.0,commit 6141c43a2)。
+ *
+ * 覆盖契约要点:
+ *  - §4.1/§4.3 正常流:POST 返回 code=200,data 含 expectedCf / currency="CF" / display.type / display.template;
+ *  - §4.2 参数校验:operationType/resourceType/resourceId 任一为空 → 400(badRequest);
+ *  - §7 权限:未登录(无 member 解析)→ 401;成员不存在 → 401;孩子 token 调家长侧 PURCHASE → 403;
+ *    跨家庭资源(TASK_COMPLETE 任务属其他家庭)→ 403;
+ *  - §2.2 防伪造:请求体 DTO 不含 expectedCf 字段,服务端计算值不受客户端影响(本测试断言 DTO 结构层面无解字段);
+ *  - §8 降级:服务返回降级 VO(expectedCf=null, display.type=DEGRADED)→ 仍 200,不 500;
+ *  - 传输层契约(AGENTS.md):仅 @PostMapping,GET → 405。
+ *
+ * 测试隔离:MockMvc standalone + mock RewardRuleService / FamilyMemberMapper / TaskMapper / RewardMapper,
+ * 无 Spring 上下文 / 无 DB(绕过 127.0.0.1:3306 环境红)。
+ */
+class RewardEstimateControllerEstimateTest {
+
+    private static final String URL = "/api/reward/estimate";
+
+    @Mock
+    private RewardRuleService rewardRuleService;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @Mock
+    private TaskMapper taskMapper;
+    @Mock
+    private RewardMapper rewardMapper;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        RewardEstimateController controller = new RewardEstimateController();
+        org.springframework.test.util.ReflectionTestUtils.setField(controller, "rewardRuleService", rewardRuleService);
+        org.springframework.test.util.ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+        org.springframework.test.util.ReflectionTestUtils.setField(controller, "taskMapper", taskMapper);
+        org.springframework.test.util.ReflectionTestUtils.setField(controller, "rewardMapper", rewardMapper);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private FamilyMember member(Long id, Long familyId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(id);
+        m.setFamilyId(familyId);
+        return m;
+    }
+
+    private RewardEstimateVO earnVo(int cf) {
+        RewardEstimateVO vo = new RewardEstimateVO();
+        vo.setExpectedCf(cf);
+        vo.setActualCf(null);
+        // 真实服务会回显原始请求字段(契约 §4.3);此处按成功用例的请求回填,模拟服务端行为
+        vo.setOperationType("CHECKIN");
+        vo.setResourceType("ACTIVITY_CHECKIN");
+        vo.setResourceId("1");
+        vo.setIdempotencyKey("k-1");
+        RewardDisplayVO d = new RewardDisplayVO();
+        d.setType(RewardRuleService.DISPLAY_EARN);
+        d.setTemplate("本操作预计获得 " + cf + " CF");
+        d.setCfValue(cf);
+        vo.setDisplay(d);
+        vo.setCurrency("CF");
+        return vo;
+    }
+
+    private RewardEstimateVO degradedVo() {
+        RewardEstimateVO vo = new RewardEstimateVO();
+        vo.setExpectedCf(null);
+        RewardDisplayVO d = new RewardDisplayVO();
+        d.setType(RewardRuleService.DISPLAY_DEGRADED);
+        d.setTemplate("CF 奖励以实际为准");
+        d.setCfValue(0);
+        vo.setDisplay(d);
+        vo.setCurrency("CF");
+        return vo;
+    }
+
+    // ==================== 正常流(§4.1 / §4.3) ====================
+
+    @Test
+    void estimate_正常打卡预估_返回expectedCf与统一文案() throws Exception {
+        when(familyMemberMapper.selectById(5L)).thenReturn(member(5L, 10L));
+        when(rewardRuleService.estimate(eq(5L), eq("CHECKIN"), eq("ACTIVITY_CHECKIN"), eq("1"), any()))
+                .thenReturn(earnVo(20));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .requestAttr("role", "parent")
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\",\"idempotencyKey\":\"k-1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.expectedCf").value(20))
+                .andExpect(jsonPath("$.data.currency").value("CF"))
+                .andExpect(jsonPath("$.data.operationType").value("CHECKIN"))
+                .andExpect(jsonPath("$.data.resourceId").value("1"))
+                .andExpect(jsonPath("$.data.idempotencyKey").value("k-1"))
+                .andExpect(jsonPath("$.data.actualCf").value(org.hamcrest.Matchers.nullValue()))
+                .andExpect(jsonPath("$.data.display.type").value("EARN"))
+                .andExpect(jsonPath("$.data.display.template").value("本操作预计获得 20 CF"))
+                .andExpect(jsonPath("$.data.display.cfValue").value(20));
+    }
+
+    // ==================== 参数校验(§4.2) ====================
+
+    @Test
+    void estimate_缺参_operationType为空_返回400() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .content("{\"operationType\":\"\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("均不能为空")));
+    }
+
+    @Test
+    void estimate_缺参_resourceId缺失_返回400() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400));
+    }
+
+    @Test
+    void estimate_请求体为空_返回400() throws Exception {
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(400));
+    }
+
+    // ==================== 权限(§7) ====================
+
+    @Test
+    void estimate_未登录_无member解析_返回401() throws Exception {
+        // 不设置 userId / currentMemberId → 服务端解析不到家庭成员
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(401));
+    }
+
+    @Test
+    void estimate_成员不存在_返回401() throws Exception {
+        when(familyMemberMapper.selectById(5L)).thenReturn(null);
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("未找到")));
+    }
+
+    @Test
+    void estimate_孩子token调家长侧PURCHASE_返回403() throws Exception {
+        when(familyMemberMapper.selectById(5L)).thenReturn(member(5L, 10L));
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .requestAttr("role", "child")
+                        .content("{\"operationType\":\"PURCHASE\",\"resourceType\":\"PRODUCT_ORDER\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403));
+    }
+
+    @Test
+    void estimate_跨家庭任务_返回403() throws Exception {
+        when(familyMemberMapper.selectById(5L)).thenReturn(member(5L, 10L));
+        Task task = new Task();
+        task.setId(999L);
+        task.setFamilyId(99L); // 属其他家庭
+        when(taskMapper.selectById(999L)).thenReturn(task);
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .requestAttr("role", "parent")
+                        .content("{\"operationType\":\"TASK_COMPLETE\",\"resourceType\":\"TASK\",\"resourceId\":\"999\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("其他家庭")));
+    }
+
+    // ==================== 防伪造(§2.2) ====================
+
+    @Test
+    void estimate_请求体不含expectedCf_完全由服务端计算() throws Exception {
+        // RewardEstimateRequest 仅含 idempotencyKey/operationType/resourceType/resourceId,
+        // 不含 expectedCf 字段(客户端无法注入)。此处断言服务端返回值与 rewardRuleService 计算的 20 一致,
+        // 印证「预估责任在服务端、客户端不传」的契约。
+        when(familyMemberMapper.selectById(5L)).thenReturn(member(5L, 10L));
+        when(rewardRuleService.estimate(eq(5L), any(), any(), any(), any())).thenReturn(earnVo(20));
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .requestAttr("role", "parent")
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.expectedCf").value(20))
+                .andExpect(jsonPath("$.data.currency").value("CF"));
+    }
+
+    // ==================== 降级(§8) ====================
+
+    @Test
+    void estimate_服务降级_返回200且displayTypeDEGRADED不500() throws Exception {
+        when(familyMemberMapper.selectById(5L)).thenReturn(member(5L, 10L));
+        when(rewardRuleService.estimate(eq(5L), any(), any(), any(), any())).thenReturn(degradedVo());
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .requestAttr("currentMemberId", 5L)
+                        .requestAttr("role", "parent")
+                        .content("{\"operationType\":\"CHECKIN\",\"resourceType\":\"ACTIVITY_CHECKIN\",\"resourceId\":\"1\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.display.type").value("DEGRADED"))
+                .andExpect(jsonPath("$.data.display.template").value("CF 奖励以实际为准"));
+    }
+
+    // ==================== 传输层契约(AGENTS.md) ====================
+
+    @Test
+    void estimate_仅允许POST_GET返回405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+}

+ 321 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/reward/RewardEstimateControllerTest.java

@@ -0,0 +1,321 @@
+package com.etotem.cfc.controller.reward;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.RewardDisplayVO;
+import com.etotem.cfc.dto.RewardEstimateRequest;
+import com.etotem.cfc.dto.RewardEstimateVO;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.Reward;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.RewardMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.RewardRuleService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * SC-X-22 · {@code reward.cfEstimate.expectedCf} 控制器契约测试({@link RewardEstimateController},
+ * 直接调用级,统一 Result&lt;T&gt; 形状断言)。
+ *
+ * <p>对应契约 docs/superpowers/specs/2026-11-05-sc-x22-cf-estimate-contract.md:
+ * <ul>
+ *   <li>§4 端点 POST /api/reward/estimate:请求体校验(缺字段 400);</li>
+ *   <li>§7 权限:未登录 401、孩子调家长侧 403、跨家庭资源 403(任务/心愿);</li>
+ *   <li>§2.2 防伪造:请求 DTO 不含 expectedCf 字段,客户端传入被忽略;</li>
+ *   <li>§4.1 统一 @PostMapping;memberId 由服务端从 JWT 解析(userId/currentMemberId)。</li>
+ * </ul>
+ * 纯 Mockito 单测:不依赖 DB / 真实微信 / Spring 容器;不改 src/main。
+ * 溯源:TC-X-22-P(tests/test-cases/cross-role-e2e.md)。
+ */
+class RewardEstimateControllerTest {
+
+    private static final long USER_ID = 100L;
+    private static final long MEMBER_ID = 7L;
+    private static final long FAMILY_ID = 1L;
+
+    @Mock
+    private RewardRuleService rewardRuleService;
+    @Mock
+    private FamilyMemberMapper familyMemberMapper;
+    @Mock
+    private TaskMapper taskMapper;
+    @Mock
+    private RewardMapper rewardMapper;
+
+    private RewardEstimateController controller;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new RewardEstimateController();
+        ReflectionTestUtils.setField(controller, "rewardRuleService", rewardRuleService);
+        ReflectionTestUtils.setField(controller, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(controller, "taskMapper", taskMapper);
+        ReflectionTestUtils.setField(controller, "rewardMapper", rewardMapper);
+
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(member(MEMBER_ID, FAMILY_ID));
+        when(rewardRuleService.estimate(anyLong(), anyString(), anyString(), anyString(), anyString()))
+                .thenReturn(vo(20));
+    }
+
+    // ==================== 一、正常路径(TC-X-22 第 5 步:expectedCf 与页面一致) ====================
+
+    @Test
+    void estimate_正常请求_200并透传服务端预估且回显请求字段() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "101", "key-1");
+        when(taskMapper.selectById(101L)).thenReturn(task(101L, FAMILY_ID, 20));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(20, result.getData().getExpectedCf());
+        assertEquals("本操作预计获得 20 CF", result.getData().getDisplay().getTemplate());
+        verify(rewardRuleService).estimate(eq(MEMBER_ID), eq("TASK_COMPLETE"), eq("TASK"), eq("101"), eq("key-1"));
+    }
+
+    @Test
+    void estimate_无currentMemberId_由userId反查成员再预估() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "101", null);
+        when(familyMemberMapper.selectOne(any())).thenReturn(member(MEMBER_ID, FAMILY_ID));
+        when(taskMapper.selectById(101L)).thenReturn(task(101L, FAMILY_ID, 20));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, null, "parent", req);
+
+        assertEquals(200, result.getCode());
+        verify(rewardRuleService).estimate(eq(MEMBER_ID), eq("TASK_COMPLETE"), eq("TASK"), eq("101"), eq(null));
+    }
+
+    // ==================== 二、参数校验(契约 §4.2) ====================
+
+    @Test
+    void estimate_请求体为空_400() {
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", null);
+
+        assertEquals(400, result.getCode());
+        assertTrue(result.getMessage().contains("请求体不能为空"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    void estimate_缺必填字段_400() {
+        RewardEstimateRequest req = request("", "TASK", "101", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(400, result.getCode());
+        assertTrue(result.getMessage().contains("均不能为空"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    // ==================== 三、未登录 / 成员归属(契约 §7 第 1 行) ====================
+
+    @Test
+    void estimate_未登录且无currentMemberId_401() {
+        RewardEstimateRequest req = request("PURCHASE", "PRODUCT", "77", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(null, null, null, req);
+
+        assertEquals(401, result.getCode());
+        assertTrue(result.getMessage().contains("未登录"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    void estimate_成员不存在_401() {
+        RewardEstimateRequest req = request("PURCHASE", "PRODUCT", "77", null);
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(401, result.getCode());
+        assertTrue(result.getMessage().contains("家庭成员"));
+    }
+
+    // ==================== 四、角色校验(契约 §7 第 2 行,孩子 vs 家长侧) ====================
+
+    @Test
+    void estimate_孩子调家长侧PURCHASE_403不返回预估() {
+        RewardEstimateRequest req = request("PURCHASE", "PRODUCT", "77", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "child", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("无权预估家长侧产出点"));
+        assertNull(result.getData());
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    void estimate_孩子调任务完成类_不拦截() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "101", null);
+        when(taskMapper.selectById(101L)).thenReturn(task(101L, FAMILY_ID, 20));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "child", req);
+
+        assertEquals(200, result.getCode());
+    }
+
+    @Test
+    void estimate_教师角色调PURCHASE_放行() {
+        RewardEstimateRequest req = request("PURCHASE", "PRODUCT", "77", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "teacher", req);
+
+        assertEquals(200, result.getCode());
+        verify(rewardRuleService).estimate(eq(MEMBER_ID), eq("PURCHASE"), eq("PRODUCT"), eq("77"), eq(null));
+    }
+
+    // ==================== 五、资源归属 / 防跨家庭泄露(契约 §7 第 3 行) ====================
+
+    @Test
+    void estimate_跨家庭任务_403不返回他人expectedCf() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "101", null);
+        when(taskMapper.selectById(101L)).thenReturn(task(101L, 9L, 20));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("其他家庭的任务"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    void estimate_任务不存在_403() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "404", null);
+        when(taskMapper.selectById(404L)).thenReturn(null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("任务不存在"));
+    }
+
+    @Test
+    void estimate_任务资源ID非数字_403参数无效() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "not-a-number", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("资源ID无效"));
+    }
+
+    @Test
+    void estimate_跨家庭心愿_403() {
+        RewardEstimateRequest req = request("WISH", "REWARD", "9", null);
+        when(rewardMapper.selectById(9L)).thenReturn(reward(9L, 9L, 50));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("其他家庭的心愿"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    @Test
+    void estimate_心愿正常_200() {
+        RewardEstimateRequest req = request("WISH", "REWARD", "9", null);
+        when(rewardMapper.selectById(9L)).thenReturn(reward(9L, FAMILY_ID, 50));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(200, result.getCode());
+        verify(rewardRuleService).estimate(eq(MEMBER_ID), eq("WISH"), eq("REWARD"), eq("9"), eq(null));
+    }
+
+    @Test
+    void estimate_商品购买_公开资源不校验归属_200() {
+        RewardEstimateRequest req = request("PURCHASE", "PRODUCT", "sku-abc", null);
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(200, result.getCode());
+        verify(rewardRuleService).estimate(eq(MEMBER_ID), eq("PURCHASE"), eq("PRODUCT"), eq("sku-abc"), eq(null));
+    }
+
+    @Test
+    void estimate_资源校验异常_降级403资源校验失败不越权() {
+        RewardEstimateRequest req = request("TASK_COMPLETE", "TASK", "101", null);
+        when(taskMapper.selectById(101L)).thenThrow(new RuntimeException("db down"));
+
+        Result<RewardEstimateVO> result = controller.estimate(USER_ID, MEMBER_ID, "parent", req);
+
+        assertEquals(403, result.getCode());
+        assertTrue(result.getMessage().contains("资源校验失败"));
+        verify(rewardRuleService, never()).estimate(anyLong(), anyString(), anyString(), anyString(), anyString());
+    }
+
+    // ==================== 六、防伪造(契约 §2.2 / TC-X-22-P 第 5 步) ====================
+
+    @Test
+    void 请求DTO不包含expectedCf字段_客户端无法伪造预估() {
+        Exception e = assertThrows(NoSuchFieldException.class,
+                () -> RewardEstimateRequest.class.getDeclaredField("expectedCf"));
+        assertTrue(e.getMessage().contains("expectedCf"), "DTO 不应声明 expectedCf(服务端计算,客户端传了也忽略)");
+    }
+
+    // ==================== 构造辅助 ====================
+
+    private RewardEstimateRequest request(String operationType, String resourceType, String resourceId, String key) {
+        RewardEstimateRequest req = new RewardEstimateRequest();
+        req.setOperationType(operationType);
+        req.setResourceType(resourceType);
+        req.setResourceId(resourceId);
+        req.setIdempotencyKey(key);
+        return req;
+    }
+
+    private RewardEstimateVO vo(int expectedCf) {
+        RewardEstimateVO vo = new RewardEstimateVO();
+        vo.setExpectedCf(expectedCf);
+        vo.setCurrency("CF");
+        RewardDisplayVO display = new RewardDisplayVO();
+        display.setType(expectedCf > 0 ? "EARN" : "ZERO");
+        display.setTemplate(expectedCf > 0 ? "本操作预计获得 " + expectedCf + " CF" : null);
+        display.setCfValue(expectedCf);
+        vo.setDisplay(display);
+        return vo;
+    }
+
+    private FamilyMember member(long id, long familyId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(id);
+        m.setFamilyId(familyId);
+        m.setUserId(USER_ID);
+        return m;
+    }
+
+    private Task task(long id, long familyId, int points) {
+        Task t = new Task();
+        t.setId(id);
+        t.setFamilyId(familyId);
+        t.setPoints(points);
+        return t;
+    }
+
+    private Reward reward(long id, long familyId, int pointsRequired) {
+        Reward r = new Reward();
+        r.setId(id);
+        r.setFamilyId(familyId);
+        r.setPointsRequired(pointsRequired);
+        return r;
+    }
+}

+ 85 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/shop/AfterSalesCancelControllerTest.java

@@ -0,0 +1,85 @@
+package com.etotem.cfc.controller.shop;
+
+import com.etotem.cfc.service.AfterSalesService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * 契约单测:售后取消退款端点(需求 SHOP-AFTERSALES-2026-11-13-V1 §S1-5)。
+ * 仅校验 AfterSalesController.cancel 的路由 / 参数解析 / 委派,不依赖数据库
+ * (standalone MockMvc + mock service,可在无 DB 的 review 档离线运行)。
+ *
+ * 关键契约:
+ *  - 携带 orderId → 委派 afterSalesService.cancelByOrderId(orderId, userId)
+ *  - 携带 requestId → 委派 afterSalesService.cancel(requestId, userId)
+ *  - 二者皆缺 → 返回「请提供 requestId 或 orderId」
+ */
+public class AfterSalesCancelControllerTest {
+
+    @Mock
+    private AfterSalesService afterSalesService;
+
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        AfterSalesController controller = new AfterSalesController();
+        ReflectionTestUtils.setField(controller, "afterSalesService", afterSalesService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    public void cancel_byOrderId_delegatesToCancelByOrderId() throws Exception {
+        when(afterSalesService.cancelByOrderId(99L, 7L)).thenReturn(com.etotem.cfc.common.Result.success("ok"));
+
+        mockMvc.perform(post("/api/shop/after-sales/cancel")
+                        .requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"orderId\":99}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(afterSalesService).cancelByOrderId(99L, 7L);
+        verify(afterSalesService, never()).cancel(anyLong(), anyLong());
+    }
+
+    @Test
+    public void cancel_byRequestId_delegatesToCancel() throws Exception {
+        when(afterSalesService.cancel(5L, 7L)).thenReturn(com.etotem.cfc.common.Result.success("ok"));
+
+        mockMvc.perform(post("/api/shop/after-sales/cancel")
+                        .requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"requestId\":5}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(afterSalesService).cancel(5L, 7L);
+    }
+
+    @Test
+    public void cancel_missingBoth_returnsError() throws Exception {
+        mockMvc.perform(post("/api/shop/after-sales/cancel")
+                        .requestAttr("userId", 7L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.message").value("请提供 requestId 或 orderId"));
+
+        verify(afterSalesService, never()).cancel(anyLong(), anyLong());
+        verify(afterSalesService, never()).cancelByOrderId(anyLong(), anyLong());
+    }
+}

+ 138 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/stats/StatsControllerDashboardContractTest.java

@@ -0,0 +1,138 @@
+package com.etotem.cfc.controller.stats;
+
+import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.stats.StatsController;
+import com.etotem.cfc.mapper.*;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * TDD 契约:/api/stats/dashboard 返回「新/总」统计(有效口径 + 近7天新增)。
+ * 纯 Mockito 单测(@SpringBootTest 需连库,本地不可用),不启动 Spring/DB。
+ * 存根用 argThat 按「状态参数 + created_at 边界」区分 total/new;若实现漏掉任一条件,
+ * 该存根不匹配 -> 返回 0 -> 断言失败。RED:新 key 未实现 -> 值缺失/失败;GREEN:全通过。
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+public class StatsControllerDashboardContractTest {
+
+    @Mock private ThreadPoolTaskExecutor taskExecutor;
+    @Mock private FamilyMapper familyMapper;
+    @Mock private UserMapper userMapper;
+    @Mock private FamilyMemberMapper familyMemberMapper;
+    @Mock private GuidePackageMapper guidePackageMapper;
+    @Mock private TaskMapper taskMapper;
+    @Mock private AfterSalesRequestMapper afterSalesRequestMapper;
+    @Mock private ProductMapper productMapper;
+    @Mock private ProductOrderMapper productOrderMapper;
+    @Mock private ArticleMapper articleMapper;
+    @Mock private ActivityMapper activityMapper;
+
+    @InjectMocks private StatsController controller;
+
+    // —— wrapper 辅助判断(QueryWrapper 在 controller 中构造)——
+    private static boolean hasCreatedAt(Object w) {
+        return w != null && ((AbstractWrapper) w).getSqlSegment().toUpperCase().contains("CREATED_AT");
+    }
+    private static boolean hasParam(Object w, Object v) {
+        if (w == null) return false;
+        AbstractWrapper aw = (AbstractWrapper) w;
+        aw.getSqlSegment(); // MyBatis-Plus: 参数在渲染 SQL 时才物化到 paramNameValuePairs
+        return aw.getParamNameValuePairs().containsValue(v);
+    }
+    private static boolean hasSql(Object w, String frag) {
+        return w != null && ((AbstractWrapper) w).getSqlSegment().toUpperCase().contains(frag);
+    }
+
+    @BeforeEach
+    void setUp() {
+        // 让 CompletableFuture.supplyAsync(supplier, taskExecutor) 内联同步执行
+        doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
+                .when(taskExecutor).execute(any(Runnable.class));
+
+        // 家庭:total=selectCount(null)=120,weekNew=带 created_at=12
+        when(familyMapper.selectCount(isNull())).thenReturn(120L);
+        when(familyMapper.selectCount(argThat(w -> hasCreatedAt(w)))).thenReturn(12L);
+        // 用户(家长账号):total(无created_at)=300,weekNew(带created_at)=30;teacher/pending 复用 total 存根
+        when(userMapper.selectCount(argThat(w -> !hasCreatedAt(w)))).thenReturn(300L);
+        when(userMapper.selectCount(argThat(w -> hasCreatedAt(w)))).thenReturn(30L);
+        // 非用户(userId IS NULL):total=88,weekNew=8
+        when(familyMemberMapper.selectCount(isNull())).thenReturn(0L); // 总孩子数(childFuture,null查询)
+        when(familyMemberMapper.selectCount(argThat(w -> hasSql(w, "IS NULL") && !hasCreatedAt(w)))).thenReturn(88L);
+        when(familyMemberMapper.selectCount(argThat(w -> hasSql(w, "IS NULL") && hasCreatedAt(w)))).thenReturn(8L);
+        // 规划师相关:任一 guidePackage/售后
+        when(guidePackageMapper.selectCount(any())).thenReturn(7L);
+        when(afterSalesRequestMapper.selectCount(any())).thenReturn(3L);
+        // 商品(有效=on_shelf):total=45,weekNew=5
+        when(productMapper.selectCount(argThat(w -> hasParam(w, "on_shelf") && !hasCreatedAt(w)))).thenReturn(45L);
+        when(productMapper.selectCount(argThat(w -> hasParam(w, "on_shelf") && hasCreatedAt(w)))).thenReturn(5L);
+        when(productMapper.selectCount(argThat(w -> hasParam(w, "pending")))).thenReturn(9L); // 待审核商品
+        // 商品订单(有效=排除 cancelled/closed/refunded):total=210,weekNew=21
+        when(productOrderMapper.selectCount(argThat(w -> hasSql(w, "NOT IN") && !hasCreatedAt(w)))).thenReturn(210L);
+        when(productOrderMapper.selectCount(argThat(w -> hasSql(w, "NOT IN") && hasCreatedAt(w)))).thenReturn(21L);
+        when(productOrderMapper.selectCount(argThat(w -> hasParam(w, "paid") && hasParam(w, "refunding")))).thenReturn(15L); // 待发货+待售后
+        // 文章(有效=published):total=60,weekNew=6
+        when(articleMapper.selectCount(argThat(w -> hasParam(w, "published") && !hasCreatedAt(w)))).thenReturn(60L);
+        when(articleMapper.selectCount(argThat(w -> hasParam(w, "published") && hasCreatedAt(w)))).thenReturn(6L);
+        when(articleMapper.selectCount(argThat(w -> hasParam(w, "pending")))).thenReturn(7L); // 待审核文章
+        // 活动(有效=published):total=25,weekNew=2
+        when(activityMapper.selectCount(argThat(w -> hasParam(w, "published") && !hasCreatedAt(w)))).thenReturn(25L);
+        when(activityMapper.selectCount(argThat(w -> hasParam(w, "published") && hasCreatedAt(w)))).thenReturn(2L);
+        when(activityMapper.selectCount(argThat(w -> hasParam(w, "pending")))).thenReturn(4L); // 待审核活动
+        // 任务列表(最近任务):空
+        when(taskMapper.selectList(any())).thenReturn(Collections.emptyList());
+    }
+
+    private Map<String, Object> call() {
+        Result<Map<String, Object>> r = controller.getDashboardSummary();
+        assertNotNull(r, "返回 Result 不能为 null");
+        assertEquals(200, r.getCode(), "业务码应为200");
+        return r.getData();
+    }
+
+    @Test
+    void dashboard_returns_newtotal_counts_with_valid_filters() {
+        Map<String, Object> d = call();
+        // 家庭:新/总
+        assertEquals(120L, d.get("totalFamilies"), "家庭总数");
+        assertEquals(12L, d.get("weekNewFamilies"), "近7天新增家庭");
+        // 用户(家长账号):新/总
+        assertEquals(300L, d.get("totalParents"), "用户总数");
+        assertEquals(30L, d.get("weekNewParents"), "近7天新增用户");
+        // 非用户(userId为空成员):新/总
+        assertEquals(88L, d.get("totalNonUsers"), "非用户总数");
+        assertEquals(8L, d.get("weekNewNonUsers"), "近7天新增非用户");
+        // 商品(有效=on_shelf):新/总
+        assertEquals(45L, d.get("totalProducts"), "商品总数(仅上架)");
+        assertEquals(5L, d.get("weekNewProducts"), "近7天新增商品");
+        // 订单(有效=排除已取消/关闭/退款):新/总
+        assertEquals(210L, d.get("totalOrders"), "订单总数(仅有效)");
+        assertEquals(21L, d.get("weekNewOrders"), "近7天新增订单");
+        // 文章(有效=published):新/总
+        assertEquals(60L, d.get("totalArticles"), "文章总数(仅已发布)");
+        assertEquals(6L, d.get("weekNewArticles"), "近7天新增文章");
+        // 活动(有效=published):新/总
+        assertEquals(25L, d.get("totalActivities"), "活动总数(仅发布中)");
+        assertEquals(2L, d.get("weekNewActivities"), "近7天新增活动");
+        // 前置数:待审核商品 / 待发货+待售后订单 / 待审核文章 / 待审核活动
+        assertEquals(9L, d.get("pendingReviewProducts"), "待审核商品");
+        assertEquals(15L, d.get("pendingReviewOrders"), "待发货+待售后订单");
+        assertEquals(7L, d.get("pendingReviewArticles"), "待审核文章");
+        assertEquals(4L, d.get("pendingReviewActivities"), "待审核活动");
+    }
+}

+ 221 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerCreateTaskTest.java

@@ -0,0 +1,221 @@
+package com.etotem.cfc.controller.task;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CreateTaskDTO;
+import com.etotem.cfc.service.TaskService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-12 / 能力键 task.parent.createTask):
+ * POST /api/tasks/create 创建任务并下发(家长给孩子布置习惯任务)的契约级单测。
+ *
+ * 契约(对应 SC-P-10「创建任务+下发」、API_REFERENCE.md §4.3 任务、TaskController.createTask):
+ * - 正常路径:家长填 标题/成员(B)/积分/频率 → POST /api/tasks/create → 统一 Result&lt;Long&gt; code=200
+ *   data=任务ID;userId(JwtInterceptor 注入)与 DTO 原样转交 taskService.createTask
+ * - DTO 反序列化:title/description/category/memberId/points/duration/taskType/frequency/needReview/
+ *   executorType/dimensionCode 正确映射进 CreateTaskDTO
+ * - 多成员下发边界:body.memberIds=[B1,B2] 原样传 Service(Service 层为每个成员建独立任务实例)
+ * - 统一 @PostMapping:GET 同路径 → 405
+ * - userId 属性缺失(@RequestAttribute required=true):400(该属性由 JwtInterceptor 注入,缺失即未认证)
+ * - Service 拒绝边界:handler 不含 try/catch,业务校验异常(家庭不足2人/成员不属于本家庭/频率或参数非法等)
+ *   直接上抛,由生产 @RestControllerAdvice GlobalExceptionHandler 统一转 Result.error(400, message)
+ *   (与 TC-P-05-E「频率非法 400」口径一致;区别于 addMember 的控制器内 try/catch 契约)
+ *
+ * 角色/权限口径:createTask handler 无 @RequestAttribute("role"/"roles"),角色不在本层判定;
+ * 授权由 JwtInterceptor(有效 token 才注入真实 userId)与 Service 层家庭归属/执行者校验承担,
+ * 故本测试覆盖 userId 注入与传递正确性而非角色分支(teacher|admin 不适用本 handler)。
+ * 缺陷观察(不在此断言为绿灯,交编排侧决策):/api/tasks/create 未列入
+ * JwtInterceptor.LOGIN_REQUIRED_PATHS,匿名(无 token→userId=-1)可到达 handler 走业务 500,
+ * 与 SEC-20261031-01 已修复的"匿名走到 controller 而非安全 401"口径漂移同类。
+ *
+ * 测试隔离:MockMvc standalone + mock TaskService,无 Spring 上下文 / 无 DB / 无外部服务(微信等)。
+ */
+public class TaskControllerCreateTaskTest {
+
+    private static final String URL = "/api/tasks/create";
+
+    @Mock
+    private TaskService taskService;
+
+    private MockMvc mockMvc;
+    private TaskController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new TaskController();
+        // createTask 仅依赖 taskService;其余 @Resource 字段本方法不触碰,保持 null 无碍
+        ReflectionTestUtils.setField(controller, "taskService", taskService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private static final String CHILD_BODY = "{"
+            + "\"title\":\"每天读书30分钟\","
+            + "\"description\":\"培养阅读习惯\","
+            + "\"category\":\"学习类\","
+            + "\"memberId\":11,"
+            + "\"points\":10,"
+            + "\"duration\":30,"
+            + "\"taskType\":\"recurring\","
+            + "\"frequency\":\"daily\","
+            + "\"needReview\":1,"
+            + "\"executorType\":\"child\","
+            + "\"dimensionCode\":\"wisdom\""
+            + "}";
+
+    // ==================== 正常路径 ====================
+
+    @Test
+    public void createTask_success_returnsTaskId() throws Exception {
+        Long userId = 1L;
+        when(taskService.createTask(eq(userId), any(CreateTaskDTO.class))).thenReturn(42L);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(CHILD_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data").value(42));
+
+        verify(taskService).createTask(eq(userId), any(CreateTaskDTO.class));
+    }
+
+    // ==================== DTO 字段映射 ====================
+
+    @Test
+    public void createTask_dtoFieldsMappedToService() throws Exception {
+        Long userId = 1L;
+        when(taskService.createTask(eq(userId), any(CreateTaskDTO.class))).thenReturn(42L);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(CHILD_BODY)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk());
+
+        ArgumentCaptor<CreateTaskDTO> captor = ArgumentCaptor.forClass(CreateTaskDTO.class);
+        verify(taskService).createTask(eq(userId), captor.capture());
+        CreateTaskDTO dto = captor.getValue();
+        assertNotNull(dto);
+        assertEquals("每天读书30分钟", dto.getTitle());
+        assertEquals("培养阅读习惯", dto.getDescription());
+        assertEquals("学习类", dto.getCategory());
+        assertEquals(Long.valueOf(11L), dto.getMemberId());
+        assertEquals(Integer.valueOf(10), dto.getPoints());
+        assertEquals(Integer.valueOf(30), dto.getDuration());
+        assertEquals("recurring", dto.getTaskType());
+        assertEquals("daily", dto.getFrequency());
+        assertEquals(Integer.valueOf(1), dto.getNeedReview());
+        assertEquals("child", dto.getExecutorType());
+        assertEquals("wisdom", dto.getDimensionCode());
+    }
+
+    // ==================== 关键边界:多成员下发 ====================
+
+    @Test
+    public void createTask_multiMember_memberIdsForwarded() throws Exception {
+        Long userId = 1L;
+        when(taskService.createTask(eq(userId), any(CreateTaskDTO.class))).thenReturn(100L);
+        String body = "{\"title\":\"早晚刷牙\",\"memberIds\":[11,12],\"points\":5,"
+                + "\"frequency\":\"daily\",\"executorType\":\"child\"}";
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body)
+                        .requestAttr("userId", userId))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").value(100));
+
+        ArgumentCaptor<CreateTaskDTO> captor = ArgumentCaptor.forClass(CreateTaskDTO.class);
+        verify(taskService).createTask(eq(userId), captor.capture());
+        assertEquals(Arrays.asList(11L, 12L), captor.getValue().getMemberIds());
+    }
+
+    // ==================== 传输层契约 ====================
+
+    @Test
+    public void createTask_onlyPostAllowed_getReturns405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    @Test
+    public void createTask_missingUserIdAttr_rejected400() throws Exception {
+        // @RequestAttribute("userId") required=true:缺失时 Spring 抛 ServletRequestBindingException,
+        // 由 DefaultHandlerExceptionResolver 映射为 400(JwtInterceptor 负责注入该属性,缺失即未认证)。
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(CHILD_BODY))
+                .andExpect(status().isBadRequest());
+
+        verify(taskService, never()).createTask(any(), any());
+    }
+
+    // ==================== 关键边界:Service 业务拒绝(异常不吞) ====================
+
+    @Test
+    public void createTask_serviceRejects_illegalArgumentNotSwallowedByHandler() {
+        // 契约:handler 无 try/catch,Service 校验失败(家庭不足2人 / 成员不属于本家庭 / 频率参数非法等)
+        // 直接上抛,生产环境由 @RestControllerAdvice GlobalExceptionHandler 统一转 Result.error(400, message)。
+        Long userId = 1L;
+        CreateTaskDTO dto = new CreateTaskDTO();
+        dto.setTitle("任务");
+        dto.setMemberId(11L);
+        when(taskService.createTask(eq(userId), any(CreateTaskDTO.class)))
+                .thenThrow(new IllegalArgumentException("该任务需分配给其他家庭成员,当前家庭不足2人"));
+
+        IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
+                () -> controller.createTask(userId, dto));
+        assertEquals("该任务需分配给其他家庭成员,当前家庭不足2人", ex.getMessage());
+
+        verify(taskService).createTask(eq(userId), any(CreateTaskDTO.class));
+    }
+
+    // ==================== 直接调用级:统一 Result<T> ====================
+
+    @Test
+    public void createTask_directCall_uniformResultShape() {
+        Long userId = 1L;
+        CreateTaskDTO dto = new CreateTaskDTO();
+        dto.setTitle("每天读书30分钟");
+        dto.setMemberId(11L);
+        dto.setPoints(10);
+        dto.setFrequency("daily");
+        dto.setExecutorType("child");
+        when(taskService.createTask(userId, dto)).thenReturn(77L);
+
+        Result<Long> result = controller.createTask(userId, dto);
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(200), result.getCode());
+        assertEquals("success", result.getMessage());
+        assertEquals(Long.valueOf(77L), result.getData());
+        verify(taskService).createTask(userId, dto);
+    }
+}

+ 224 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerGetTaskHistoryTest.java

@@ -0,0 +1,224 @@
+package com.etotem.cfc.controller.task;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.service.TaskService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-29 / 能力键 task.history.view):
+ * POST /api/tasks/history 获取任务历史(分页 + 可选 category 过滤)的契约级单测。
+ *
+ * 契约(对应 SC-P-94「我的成就·完成任务 → 历史完成任务页面」、API_REFERENCE.md 任务域、
+ * TaskController.getTaskHistory):
+ * - 正常路径:body.memberId 明确传入 → taskService.getTaskHistory(memberId, page, size) → Result&lt;Page&lt;Task&gt;&gt; code=200
+ * - 正常路径·分类:body.category 非空 → 走 taskService.getTaskHistoryByCategory(memberId, page, size, category)
+ * - 分页边界:body.page/size 显式传入 → 原样传给 Service;不传 → 默认 page=1 / size=10
+ * - 成员边界:body.memberId 缺省时回退 JwtInterceptor 注入的 currentMemberId 属性
+ * - 空态:无完成记录 → 统一 Result code=200 且 data.total=0(前端据此展示「暂无已完成任务」空态)
+ * - 传输层契约:统一 @PostMapping(GET 同路径 → 405); @RequestBody 缺失 → 400
+ * - 角色/权限口径:getTaskHistory handler 无 @RequestAttribute("role"/"roles") 检查,角色不在本层判定;
+ *   授权由 JwtInterceptor(有效 token 注入 currentMemberId)+ Service 层成员归属校验承担,
+ *   故本测试覆盖 memberId 解析与传递正确性而非角色分支(teacher|admin 不适用本 handler)。
+ *
+ * 测试隔离:MockMvc standalone + mock TaskService,无 Spring 上下文 / 无 DB / 无外部服务(微信等)。
+ */
+public class TaskControllerGetTaskHistoryTest {
+
+    private static final String URL = "/api/tasks/history";
+
+    @Mock
+    private TaskService taskService;
+
+    private MockMvc mockMvc;
+    private TaskController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new TaskController();
+        // getTaskHistory 仅依赖 taskService;其余 @Resource 字段本方法不触碰,保持 null 无碍
+        ReflectionTestUtils.setField(controller, "taskService", taskService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    // ==================== 正常路径:默认分页 + 空态 ====================
+
+    @Test
+    public void getTaskHistory_success_defaultPageSize_returnsPage() throws Exception {
+        Long memberId = 11L;
+        Page<Task> mockPage = new Page<>();
+        mockPage.setTotal(0); // 空态:无完成任务
+        when(taskService.getTaskHistory(eq(memberId), eq(1), eq(10))).thenReturn(mockPage);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", memberId);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(jsonBody(params)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data.total").value(0));
+
+        verify(taskService).getTaskHistory(eq(memberId), eq(1), eq(10));
+        verify(taskService, never()).getTaskHistoryByCategory(any(), any(), any(), any());
+    }
+
+    // ==================== 正常路径:显式分页 ====================
+
+    @Test
+    public void getTaskHistory_success_explicitPageSize_forwardedToService() throws Exception {
+        Long memberId = 11L;
+        Page<Task> mockPage = new Page<>();
+        mockPage.setTotal(2);
+        when(taskService.getTaskHistory(eq(memberId), eq(2), eq(20))).thenReturn(mockPage);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", memberId);
+        params.put("page", 2);
+        params.put("size", 20);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(jsonBody(params)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.total").value(2));
+
+        verify(taskService).getTaskHistory(eq(memberId), eq(2), eq(20));
+    }
+
+    // ==================== 正常路径:category 过滤 ====================
+
+    @Test
+    public void getTaskHistory_success_withCategory_usesByCategory() throws Exception {
+        Long memberId = 11L;
+        String category = "学习类";
+        Page<Task> mockPage = new Page<>();
+        mockPage.setTotal(5);
+        when(taskService.getTaskHistoryByCategory(eq(memberId), eq(1), eq(10), eq(category))).thenReturn(mockPage);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", memberId);
+        params.put("category", category);
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(jsonBody(params)))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.total").value(5));
+
+        verify(taskService).getTaskHistoryByCategory(eq(memberId), eq(1), eq(10), eq(category));
+        verify(taskService, never()).getTaskHistory(any(), any(), any());
+    }
+
+    // ==================== 关键边界:memberId 回退 currentMemberId ====================
+
+    @Test
+    public void getTaskHistory_memberIdMissing_fallsBackToCurrentMemberId() throws Exception {
+        Long currentMemberId = 99L;
+        Page<Task> mockPage = new Page<>();
+        mockPage.setTotal(1);
+        when(taskService.getTaskHistory(eq(currentMemberId), eq(1), eq(10))).thenReturn(mockPage);
+
+        Map<String, Object> params = new HashMap<>(); // 不传 memberId
+
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(jsonBody(params))
+                        .requestAttr("currentMemberId", currentMemberId)) // JwtInterceptor 注入
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200));
+
+        verify(taskService).getTaskHistory(eq(currentMemberId), eq(1), eq(10));
+    }
+
+    // ==================== 传输层契约 ====================
+
+    @Test
+    public void getTaskHistory_onlyPostAllowed_getReturns405() throws Exception {
+        mockMvc.perform(get(URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    @Test
+    public void getTaskHistory_missingBody_returns400() throws Exception {
+        // @RequestBody Map 默认 required=true:无 Body → HttpMessageNotReadableException → 400
+        mockMvc.perform(post(URL)
+                        .contentType(MediaType.APPLICATION_JSON))
+                .andExpect(status().isBadRequest());
+
+        verify(taskService, never()).getTaskHistory(any(), any(), any());
+        verify(taskService, never()).getTaskHistoryByCategory(any(), any(), any(), any());
+    }
+
+    // ==================== 直接调用级:统一 Result<T> ====================
+
+    @Test
+    public void getTaskHistory_directCall_uniformResultShape() {
+        Long memberId = 11L;
+        Page<Task> mockPage = new Page<>();
+        mockPage.setTotal(1);
+        when(taskService.getTaskHistory(memberId, 1, 10)).thenReturn(mockPage);
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("memberId", memberId);
+
+        Result<Page<Task>> result = controller.getTaskHistory(params, 99L);
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(200), result.getCode());
+        assertEquals("success", result.getMessage());
+        assertEquals(mockPage, result.getData());
+        verify(taskService).getTaskHistory(memberId, 1, 10);
+    }
+
+    // ==================== 工具方法 ====================
+
+    private String jsonBody(Map<String, Object> params) {
+        if (params == null || params.isEmpty()) {
+            return "{}";
+        }
+        StringBuilder sb = new StringBuilder("{");
+        boolean first = true;
+        for (Map.Entry<String, Object> entry : params.entrySet()) {
+            if (!first) {
+                sb.append(", ");
+            }
+            first = false;
+            Object value = entry.getValue();
+            sb.append("\"").append(entry.getKey()).append("\": ");
+            if (value instanceof String) {
+                sb.append("\"").append(value).append("\"");
+            } else {
+                sb.append(value);
+            }
+        }
+        return sb.append("}").toString();
+    }
+}

+ 330 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/task/TaskControllerReviewTest.java

@@ -0,0 +1,330 @@
+package com.etotem.cfc.controller.task;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.TaskReviewDTO;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.RewardRuleService;
+import com.etotem.cfc.service.TaskService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * TDD 覆盖驱动(S-cfc-13 / 能力键 task.parent.review):
+ * TaskController 任务审批闭环(SC-P-11「任务审批完成(通过/驳回)」)的契约级单测。
+ *
+ * 契约(对应 SC-P-11、API_REFERENCE.md §4.3 任务、TaskController /review /pending-review /accept /reject):
+ * - 家长审批:B 完成提交(status=pending_review)→ POST /api/tasks/{id}/review
+ *   body {approved:true|false, comment, aiSuggestion, overrideAi} → 统一 Result&lt;Boolean&gt; code=200
+ *   (Service 语义:通过 → 发分并置 completed;驳回 → 置回 pending 可重做)
+ * - 待审批列表:POST /api/tasks/pending-review(userId 由 JwtInterceptor 注入,Service 校验仅 parent 可见)
+ * - 接受/拒绝任务:POST /api/tasks/accept、POST /api/tasks/reject/{id}(memberId 取 body 或 currentMemberId)
+ *
+ * 角色/权限口径(适用时):
+ * - reviewTask 与 accept/reject handler 均无 @RequestAttribute("role"/"roles"),角色不在本层判定;
+ *   授权由 JwtInterceptor(有效 token 才注入 userId/currentMemberId)+ Service 层执行人/家庭校验承担。
+ * - getPendingReviewTasks 的「仅 parent 可见」在 Service 层(user.role==parent),见 TaskServiceReviewTest。
+ *
+ * 缺陷观察(不修实现,交编排侧转 GREEN 决策):
+ * 1) POST /api/tasks/accept 的 HTTP 契约已断:handler 为 @PostMapping("/accept") + @PathVariable Long id,
+ *    路径模板无 {id} → 参数解析抛 MissingPathVariableException(MockMvc 观测 500),且前端
+ *    (cfc-frontend/utils/api.js acceptTask)把 taskId 放在 body {taskId, memberId} 里,handler 从不读取 body.taskId。
+ *    本测试用 acceptTask_httpPath_missingPathVariable_pinsObserved500 钉住当前观测行为;
+ *    修复方向(编排侧定夺):改映射为 /accept/{id}(同时前端改 path 传 id),或 handler 改读 body.taskId。
+ * 2) listen:/api/tasks/{id}/review 无 userId/家庭归属校验(仅凭 taskId 即可审批),
+ *    横向越权风险由前端入口遮挡,Service 层亦未校验审批人与任务归属家庭 → 观察记录,不改实现。
+ *
+ * 测试隔离:MockMvc standalone + mock TaskService / TaskMapper,无 Spring 上下文 / 无 DB / 无外部服务(微信等)。
+ */
+public class TaskControllerReviewTest {
+
+    private static final String REVIEW_URL = "/api/tasks/{id}/review";
+    private static final String PENDING_REVIEW_URL = "/api/tasks/pending-review";
+    private static final String ACCEPT_URL = "/api/tasks/accept";
+    private static final String REJECT_URL = "/api/tasks/reject/{id}";
+
+    @Mock
+    private TaskService taskService;
+
+    @Mock
+    private TaskMapper taskMapper;
+
+    @Mock
+    private RewardRuleService rewardRuleService;
+
+    private MockMvc mockMvc;
+    private TaskController controller;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+        controller = new TaskController();
+        // review/pending-review 仅依赖 taskService;accept/reject 的 handler 内经 checkMemberOnly 触碰 taskMapper
+        ReflectionTestUtils.setField(controller, "taskService", taskService);
+        ReflectionTestUtils.setField(controller, "taskMapper", taskMapper);
+        // SC-X-22 合入后 /pending-review /today-parent 新增 rewardRuleService 挂载预估调用,mock 空实现(旁路估算非本契约关注点)
+        ReflectionTestUtils.setField(controller, "rewardRuleService", rewardRuleService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private static Task taskWithId(long id) {
+        Task t = new Task();
+        t.setId(id);
+        t.setMemberOnly(0); // 非会员任务,checkMemberOnly 不触碰 membershipService
+        return t;
+    }
+
+    // ==================== POST /api/tasks/{id}/review 审核任务(通过/驳回) ====================
+
+    @Test
+    public void reviewTask_approve_http200_returnsTrue() throws Exception {
+        when(taskService.reviewTask(eq(1L), any(TaskReviewDTO.class))).thenReturn(true);
+
+        mockMvc.perform(post(REVIEW_URL, 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"approved\":true,\"comment\":\"完成得很好\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data").value(true));
+
+        verify(taskService).reviewTask(eq(1L), any(TaskReviewDTO.class));
+    }
+
+    @Test
+    public void reviewTask_reject_approvedFalseForwarded() throws Exception {
+        when(taskService.reviewTask(eq(1L), any(TaskReviewDTO.class))).thenReturn(true);
+
+        mockMvc.perform(post(REVIEW_URL, 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"approved\":false,\"comment\":\"照片模糊请重做\"}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").value(true));
+
+        ArgumentCaptor<TaskReviewDTO> captor = ArgumentCaptor.forClass(TaskReviewDTO.class);
+        verify(taskService).reviewTask(eq(1L), captor.capture());
+        assertEquals(Boolean.FALSE, captor.getValue().getApproved());
+        assertEquals("照片模糊请重做", captor.getValue().getComment());
+    }
+
+    @Test
+    public void reviewTask_dtoFieldsMapped() throws Exception {
+        when(taskService.reviewTask(eq(1L), any(TaskReviewDTO.class))).thenReturn(true);
+        String body = "{\"approved\":true,\"aiSuggestion\":\"拍照需清晰\",\"overrideAi\":true,"
+                + "\"comment\":\"表现不错\",\"result\":\"pass\"}";
+
+        mockMvc.perform(post(REVIEW_URL, 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(body))
+                .andExpect(status().isOk());
+
+        ArgumentCaptor<TaskReviewDTO> captor = ArgumentCaptor.forClass(TaskReviewDTO.class);
+        verify(taskService).reviewTask(eq(1L), captor.capture());
+        TaskReviewDTO dto = captor.getValue();
+        assertNotNull(dto);
+        assertEquals(Boolean.TRUE, dto.getApproved());
+        assertEquals("拍照需清晰", dto.getAiSuggestion());
+        assertEquals(Boolean.TRUE, dto.getOverrideAi());
+        assertEquals("表现不错", dto.getComment());
+        assertEquals("pass", dto.getResult());
+    }
+
+    // ==================== 传输层契约 ====================
+
+    @Test
+    public void reviewTask_onlyPostAllowed_getReturns405() throws Exception {
+        mockMvc.perform(get(REVIEW_URL, 1L))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    @Test
+    public void reviewTask_missingBody_rejected400() throws Exception {
+        // @RequestBody 为空 → HttpMessageNotReadableException → 400(与 TC-P-06-E「参数非法统一 400」口径一致)
+        mockMvc.perform(post(REVIEW_URL, 1L)
+                        .contentType(MediaType.APPLICATION_JSON))
+                .andExpect(status().isBadRequest());
+
+        verify(taskService, never()).reviewTask(any(), any());
+    }
+
+    // ==================== POST /api/tasks/pending-review 家长待审批列表 ====================
+
+    @Test
+    public void pendingReview_parent_success_returnsList() throws Exception {
+        Task t1 = taskWithId(1L);
+        Task t2 = taskWithId(2L);
+        when(taskService.getPendingReviewTasks(7L)).thenReturn(Arrays.asList(t1, t2));
+
+        mockMvc.perform(post(PENDING_REVIEW_URL)
+                        .requestAttr("userId", 7L))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].id").value(1))
+                .andExpect(jsonPath("$.data[1].id").value(2));
+
+        verify(taskService).getPendingReviewTasks(7L);
+    }
+
+    @Test
+    public void pendingReview_missingUserIdAttr_rejected400() throws Exception {
+        // userId 由 JwtInterceptor 注入;缺失即未认证(与创建任务口径一致)
+        mockMvc.perform(post(PENDING_REVIEW_URL))
+                .andExpect(status().isBadRequest());
+
+        verify(taskService, never()).getPendingReviewTasks(any());
+    }
+
+    // ==================== POST /api/tasks/accept 接受任务 ====================
+
+    @Test
+    public void acceptTask_httpPath_missingPathVariable_pinsObserved500_defect() throws Exception {
+        // 契约期望:POST /api/tasks/accept(body {taskId, memberId})→ 接受任务成功 code=200 data=true。
+        // 实际观测(钉住当前行为,不改实现):路径模板 /accept 无 {id},而 handler 声明 @PathVariable Long id
+        // → 参数解析阶段抛 MissingPathVariableException → 500;body.taskId 亦从未被 handler 读取。
+        // ——真实缺陷,交编排侧转 GREEN 决策(修复后本用例应翻转为 200 契约断言)。
+        when(taskService.acceptTask(any(), any())).thenReturn(true);
+
+        mockMvc.perform(post(ACCEPT_URL)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"taskId\":1,\"memberId\":11}"))
+                .andExpect(status().isInternalServerError());
+
+        verify(taskService, never()).acceptTask(any(), any());
+    }
+
+    @Test
+    public void acceptTask_directCall_memberIdFromBody_success() {
+        Long id = 1L;
+        Long memberId = 11L;
+        when(taskMapper.selectById(id)).thenReturn(taskWithId(id)); // checkMemberOnly 放行
+        when(taskService.acceptTask(id, memberId)).thenReturn(true);
+
+        HashMap<String, Object> params = new HashMap<>();
+        params.put("memberId", memberId);
+        Result<Boolean> result = controller.acceptTask(id, null, params);
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(200), result.getCode());
+        assertEquals("success", result.getMessage());
+        assertEquals(Boolean.TRUE, result.getData());
+        verify(taskService).acceptTask(id, memberId);
+    }
+
+    @Test
+    public void acceptTask_directCall_currentMemberIdAttrFallback() {
+        Long id = 1L;
+        Long memberId = 11L;
+        when(taskMapper.selectById(id)).thenReturn(taskWithId(id));
+        when(taskService.acceptTask(id, memberId)).thenReturn(true);
+
+        // body 无 memberId → 退化为 @RequestAttribute currentMemberId
+        Result<Boolean> result = controller.acceptTask(id, memberId, new HashMap<>());
+
+        assertEquals(Integer.valueOf(200), result.getCode());
+        verify(taskService).acceptTask(id, memberId);
+    }
+
+    @Test
+    public void acceptTask_directCall_missingMemberId_error500() {
+        // memberId 为空 → 统一 Result.error(code=500,Result.error 默认口径)→ 不触碰 Service
+        Result<Boolean> result = controller.acceptTask(1L, null, new HashMap<>());
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(500), result.getCode());
+        assertEquals("memberId不能为空", result.getMessage());
+        verify(taskService, never()).acceptTask(any(), any());
+    }
+
+    @Test
+    public void acceptTask_onlyPostAllowed_getReturns405() throws Exception {
+        mockMvc.perform(get(ACCEPT_URL))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    // ==================== POST /api/tasks/reject/{id} 拒绝任务 ====================
+
+    @Test
+    public void rejectTask_http_success_returnsTrue() throws Exception {
+        when(taskService.rejectTask(1L, 11L)).thenReturn(true);
+
+        mockMvc.perform(post(REJECT_URL, 1L)
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"memberId\":11}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.message").value("success"))
+                .andExpect(jsonPath("$.data").value(true));
+
+        verify(taskService).rejectTask(1L, 11L);
+    }
+
+    @Test
+    public void rejectTask_directCall_missingMemberId_error500() {
+        Result<Boolean> result = controller.rejectTask(1L, null, new HashMap<>());
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(500), result.getCode());
+        assertEquals("memberId不能为空", result.getMessage());
+        verify(taskService, never()).rejectTask(any(), any());
+    }
+
+    @Test
+    public void rejectTask_onlyPostAllowed_getReturns405() throws Exception {
+        mockMvc.perform(get(REJECT_URL, 1L))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    // ==================== 直接调用级:统一 Result<T> ====================
+
+    @Test
+    public void reviewTask_directCall_uniformResultShape() {
+        TaskReviewDTO dto = new TaskReviewDTO();
+        dto.setApproved(true);
+        when(taskService.reviewTask(1L, dto)).thenReturn(true);
+
+        Result<Boolean> result = controller.reviewTask(1L, dto);
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(200), result.getCode());
+        assertEquals("success", result.getMessage());
+        assertEquals(Boolean.TRUE, result.getData());
+        verify(taskService).reviewTask(1L, dto);
+    }
+
+    @Test
+    public void pendingReview_directCall_uniformResultShape() {
+        when(taskService.getPendingReviewTasks(7L)).thenReturn(Collections.emptyList());
+
+        Result<java.util.List<Task>> result = controller.getPendingReviewTasks(7L);
+
+        assertNotNull(result);
+        assertEquals(Integer.valueOf(200), result.getCode());
+        assertEquals("success", result.getMessage());
+        assertNotNull(result.getData());
+        assertEquals(0, result.getData().size());
+    }
+}

+ 47 - 0
cfc-backend/src/test/java/com/etotem/cfc/dto/ActivityDTOTest.java

@@ -0,0 +1,47 @@
+package com.etotem.cfc.dto;
+
+import com.etotem.cfc.entity.Activity;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * A2 活动费用模型:ActivityDTO.basePrice 必须保留原始普通价,
+ * 不被会员价解析替换(否则会员编辑活动时会把会员价误写成普通价)。
+ */
+class ActivityDTOTest {
+
+    private Activity activity(Integer price, Integer memberPrice) {
+        Activity a = new Activity();
+        a.setId(1L);
+        a.setTitle("测试活动");
+        a.setPrice(price);
+        a.setMemberPrice(memberPrice);
+        return a;
+    }
+
+    /** 非会员看到的是普通价;basePrice 始终为原始普通价 */
+    @Test
+    void basePrice_rawForNonMember() {
+        ActivityDTO dto = ActivityDTO.from(activity(10000, 8000), true, null);
+        assertEquals(10000, dto.getPrice(), "非会员展示普通价");
+        assertEquals(10000, dto.getBasePrice(), "basePrice=原始普通价");
+        assertEquals(8000, dto.getMemberPrice(), "memberPrice 原样返回");
+    }
+
+    /** 会员看到的是会员价,但 basePrice 仍是原始普通价(编辑表单回填的关键) */
+    @Test
+    void basePrice_rawForMember() {
+        ActivityDTO dto = ActivityDTO.from(activity(10000, 8000), false, "FAMILY");
+        assertEquals(8000, dto.getPrice(), "会员展示会员价");
+        assertEquals(10000, dto.getBasePrice(), "basePrice 不被会员价替换,供编辑回填");
+    }
+
+    /** 存量活动(price=0/空)basePrice=0 → 前端兜底历史别名 parentFee */
+    @Test
+    void basePrice_zeroForLegacyPriceNeverSet() {
+        ActivityDTO dto = ActivityDTO.from(activity(0, null), false, "FAMILY");
+        assertEquals(0, dto.getBasePrice(), "price 未写入过 → basePrice=0,前端回退 parentFee");
+        assertNull(dto.getMemberPrice(), "memberPrice 从未写入过 → NULL(走 parentMemberFee 别名)");
+    }
+}

+ 403 - 0
cfc-backend/src/test/java/com/etotem/cfc/e2e/WebAdminpanelRune2eContractTest.java

@@ -0,0 +1,403 @@
+package com.etotem.cfc.e2e;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.admin.AdminController;
+import com.etotem.cfc.controller.admin.AdminEnergyRuleController;
+import com.etotem.cfc.controller.admin.AdminSystemController;
+import com.etotem.cfc.controller.config.SysConfigController;
+import com.etotem.cfc.dto.SysConfigDTO;
+import com.etotem.cfc.entity.EnergyDimension;
+import com.etotem.cfc.entity.EnergyRule;
+import com.etotem.cfc.entity.SysConfig;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.EnergyDimensionMapper;
+import com.etotem.cfc.mapper.EnergyRuleMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.SysConfigService;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-junit-2 / web.adminPanel.runE2E 契约级单测(TDD-RED 阶段:先写会失败的契约测试)。
+ *
+ * <p>能力键 {@code web.adminPanel.runE2E}(单元 web)=「Web 管理端主链路 E2E 可运行」:
+ * 已部署站点(cfc.iwintrue.com)管理后台 5 条只读用例(TC-A-U01~U05)在
+ * 189:4090 节点 5/5 全绿(R407 专题E 实测),但该能力键<b>未契约化</b>
+ * (API_REFERENCE.md 5.5 槽位 ⏳ 待落地):E2E 主链路缺少机器可验证的契约测试,
+ * 且其工具链根因 P-474-1({@code @playwright/test} 双物理副本 → 假红 "No tests found")
+ * 无任何测试守卫,历轮只能靠人工读 R416 守卫报错才定位。
+ *
+ * <p>本类钉住三段契约(测试工作目录为 {@code cfc-backend},仓库根按 user.dir 上溯定位):
+ * <ul>
+ *   <li><b>A 组 · 套件可用契约</b>:{@code tests/e2e-live/admin-live.spec.js}(5 用例)在册、
+ *       {@code tests/playwright.config.live.js} 的 admin-desktop project 与 R416 双副本守卫在位、
+ *       {@code tests/package.json} 的 {@code test:e2e:live:admin} 规范跑法脚本完整;</li>
+ *   <li><b>B 组 · 工具链单副本契约</b>:仓库根与 {@code tests/} 两侧 package.json
+ *       至多一方声明 {@code @playwright/test}(P-474-1:根 1.63.0 + tests ^1.61.1 双副本
+ *       → CLI 与 spec 各拿一份,{@code test.describe()} 无法注册,runner 假红 "No tests found")。
+ *       <b>B1 当前必失败(RED)</b>;</li>
+ *   <li><b>C 组 · 管理端主链路 API 契约</b>:E2E 4 场景页面(用户列表 / 数据看板 / 能量规则 / 系统配置)
+ *       所依赖的后端端点——{@code POST /api/admin/users}、{@code /api/admin/energy-rule/*}、
+ *       {@code /api/admin/config/list}、{@code /api/system/health}——的 {@code Result} 信封与角色门禁。</li>
+ * </ul>
+ *
+ * <p>边界适用性说明(任务派发边界清单逐项落位):
+ * <ul>
+ *   <li>幂等重放 replay=true / 同键异载荷 C4092 / 乐观锁冲突 C422:<b>不适用</b>——
+ *       该能力键是只读 E2E 套件(唯一例外是登录建立会话,无写操作),
+ *       且 C-code 统一错误码体系未在本仓落地(全仓无 C4092/C422 常量);</li>
+ *   <li>越权 C403:适用 → 以业务码 403 语义覆盖(teacher/parent 访问平台端点
+ *       {@code /api/admin/users} → {@code Result.error(403, "无权限访问该接口")});</li>
+ *   <li>不存在 C404:适用 → 以业务错误语义覆盖({@code /api/admin/energy-rule/toggle}
+ *       不存在 id → "规则不存在")。</li>
+ * </ul>
+ *
+ * <p>测试隔离:MockMvc standalone + 全 mock Mapper/Service,无 Spring 上下文 / 无 DB / 无外部服务。
+ * 类为<b>扁平结构(无 @Nested)</b>,保证 surefire {@code -Dtest=*WebAdminpanelRune2e*}
+ * 单类匹配即可运行全部用例。
+ *
+ * <p>GREEN 阶段最小改动:消除双副本(两侧 package.json 至多一方声明 {@code @playwright/test},
+ * 推荐移除根 devDependency、tests/ 留单副本)——不改 src/main 一行。
+ */
+class WebAdminpanelRune2eContractTest {
+
+    // ================================================================
+    // 仓库根定位(测试 CWD = cfc-backend 模块目录;IDE 下可能 = 仓库根)
+    // ================================================================
+
+    /** 定位仓库根:含 {@code tests/e2e-live/} 目录且根有 package.json 的目录。 */
+    private static Path repoRoot() {
+        String userDir = System.getProperty("user.dir", ".");
+        for (String candidate : new String[]{"..", ".", "./"}) {
+            Path root = Paths.get(userDir, candidate).toAbsolutePath().normalize();
+            if (Files.isDirectory(root.resolve("tests").resolve("e2e-live"))
+                    && Files.isRegularFile(root.resolve("package.json"))) {
+                return root;
+            }
+        }
+        throw new IllegalStateException("无法定位仓库根(user.dir=" + userDir + "),请检查测试运行目录");
+    }
+
+    private static String readRepoFile(String relativePath) throws Exception {
+        return new String(Files.readAllBytes(repoRoot().resolve(relativePath)), StandardCharsets.UTF_8);
+    }
+
+    /** 收集 package.json 中指定 section 的 @playwright/test 版本声明(B 组契约用)。 */
+    private static Set<String> playwrightDecls(JsonNode pkg, String... sections) {
+        Set<String> decls = new HashSet<>();
+        for (String section : sections) {
+            JsonNode node = pkg.path(section).path("@playwright/test");
+            if (!node.isMissingNode() && !node.isNull()) {
+                decls.add(node.asText());
+            }
+        }
+        return decls;
+    }
+
+    // ================================================================
+    // C 组 MockMvc 装配(A/B 组不依赖)
+    // ================================================================
+
+    private MockMvc adminApi;
+    private MockMvc energyRuleApi;
+    private MockMvc sysConfigApi;
+    private MockMvc systemApi;
+    private UserMapper userMapper;
+    private EnergyRuleMapper energyRuleMapper;
+    private EnergyDimensionMapper energyDimensionMapper;
+    private SysConfigService sysConfigService;
+
+    @BeforeEach
+    void setUp() {
+        AdminController adminController = new AdminController();
+        userMapper = mock(UserMapper.class);
+        ReflectionTestUtils.setField(adminController, "userMapper", userMapper);
+        adminApi = MockMvcBuilders.standaloneSetup(adminController).build();
+
+        AdminEnergyRuleController energyRuleController = new AdminEnergyRuleController();
+        energyRuleMapper = mock(EnergyRuleMapper.class);
+        energyDimensionMapper = mock(EnergyDimensionMapper.class);
+        ReflectionTestUtils.setField(energyRuleController, "energyRuleMapper", energyRuleMapper);
+        ReflectionTestUtils.setField(energyRuleController, "energyDimensionMapper", energyDimensionMapper);
+        energyRuleApi = MockMvcBuilders.standaloneSetup(energyRuleController).build();
+
+        SysConfigController sysConfigController = new SysConfigController();
+        sysConfigService = mock(SysConfigService.class);
+        ReflectionTestUtils.setField(sysConfigController, "sysConfigService", sysConfigService);
+        sysConfigApi = MockMvcBuilders.standaloneSetup(sysConfigController).build();
+
+        systemApi = MockMvcBuilders.standaloneSetup(new AdminSystemController()).build();
+    }
+
+    // ================================================================
+    // A 组:E2E 套件可用契约(tests/ 树文件断言)
+    // ================================================================
+
+    @Test
+    @DisplayName("A1 admin E2E spec 在册:admin-live.spec.js 注册 test.describe + 5 用例(TC-A-U01~U05)")
+    void adminLiveSpec_五个用例在册() throws Exception {
+        String spec = readRepoFile("tests/e2e-live/admin-live.spec.js");
+        assertTrue(spec.contains("test.describe("),
+                "tests/e2e-live/admin-live.spec.js 缺少 test.describe() 注册——套件无法被 runner 收集(P-474-1 假红的直接信号之一)");
+        for (int i = 1; i <= 5; i++) {
+            String tc = "TC-A-U0" + i;
+            assertTrue(spec.contains(tc), "admin-live.spec.js 缺少用例 " + tc + "(189:4090 基线为 admin 5/5,缺任一即主链路断链)");
+        }
+    }
+
+    @Test
+    @DisplayName("A2 live config 声明 admin-desktop project 并锁定 admin-live.spec.js")
+    void liveConfig_adminDesktopProject在册() throws Exception {
+        String config = readRepoFile("tests/playwright.config.live.js");
+        assertTrue(config.contains("admin-desktop"),
+                "playwright.config.live.js 缺少 admin-desktop project——test:e2e:live:admin 无 project 可跑");
+        assertTrue(config.matches("(?s).*name: 'admin-desktop'.*?testMatch.*?admin-live.*"),
+                "admin-desktop project 未通过 testMatch 锁定 admin-live.spec.js");
+    }
+
+    @Test
+    @DisplayName("A3 live config 携带 R416 双副本工具链守卫(加载时 fail-fast)")
+    void liveConfig_R416工具链守卫在册() throws Exception {
+        String config = readRepoFile("tests/playwright.config.live.js");
+        assertTrue(config.contains("assertSinglePlaywrightCopy"),
+                "playwright.config.live.js 缺少 R416 assertSinglePlaywrightCopy 守卫——双副本时不再 fail-fast,退回加密报错");
+        assertTrue(config.contains("双物理副本"),
+                "R416 守卫的报错文案(双物理副本提示)缺失——误报 'No tests found' 时无自助指引");
+    }
+
+    @Test
+    @DisplayName("A4 tests/package.json 规范跑法脚本 test:e2e:live:admin 完整(spec + 配置 + project 三要素)")
+    void npmScript_testE2eLiveAdmin_规范跑法完整() throws Exception {
+        JsonNode pkg = new ObjectMapper().readTree(
+                repoRoot().resolve("tests").resolve("package.json").toFile());
+        String script = pkg.path("scripts").path("test:e2e:live:admin").asText("");
+        assertFalse(script.isEmpty(),
+                "tests/package.json 缺少 scripts['test:e2e:live:admin']——规范跑法入口缺失");
+        assertTrue(script.contains("e2e-live/admin-live.spec.js"), "脚本未指向 admin-live.spec.js");
+        assertTrue(script.contains("playwright.config.live.js"), "脚本未指定 live 配置(-c)");
+        assertTrue(script.contains("--project=admin-desktop"), "脚本未指定 admin-desktop project");
+    }
+
+    // ================================================================
+    // B 组:工具链单副本契约(P-474-1 · 当前必失败 = RED)
+    // ================================================================
+
+    @Test
+    @DisplayName("B1 仓库根与 tests/ 不得并存两份 @playwright/test 声明(单物理副本契约)")
+    void playwrightTest_双副本声明_违反单副本契约() throws Exception {
+        JsonNode rootPkg = new ObjectMapper()
+                .readTree(repoRoot().resolve("package.json").toFile());
+        JsonNode testsPkg = new ObjectMapper()
+                .readTree(repoRoot().resolve("tests").resolve("package.json").toFile());
+
+        Set<String> rootDecls = playwrightDecls(rootPkg, "devDependencies", "dependencies");
+        Set<String> testsDecls = playwrightDecls(testsPkg, "devDependencies", "dependencies");
+        int declaredSides = (rootDecls.isEmpty() ? 0 : 1) + (testsDecls.isEmpty() ? 0 : 1);
+
+        assertTrue(declaredSides <= 1,
+                "P-474-1 双副本 @playwright/test 声明:根 package.json 声明 " + rootDecls
+                        + ",tests/package.json 声明 " + testsDecls
+                        + " → 两份 node_modules 物理副本各持模块状态,CLI 与 spec 各拿一份,"
+                        + "test.describe() 无法注册,runner 假红 'No tests found'"
+                        + "(tests/playwright.config.live.js 的 R416 守卫仅在运行时 fail-fast,缺陷仍在仓库里)。"
+                        + "修复:根 package.json 移除 @playwright/test devDependency(tests/ 留单副本),"
+                        + "或 tests/package.json 移除声明改走根副本——两侧至多一方声明。");
+    }
+
+    // ================================================================
+    // C 组:管理端主链路 API 契约(E2E 4 场景页面所依赖的后端端点)
+    // ================================================================
+
+    @Test
+    @DisplayName("C1 /api/admin/users:admin 角色 → 200 + Result 信封 + Page 分页字段(E2E 场景1 用户列表)")
+    void users_admin角色_分页信封() throws Exception {
+        User u = new User();
+        u.setId(1L);
+        u.setRole("parent");
+        u.setNickname("家长甲");
+        Page<User> page = new Page<>(1, 10);
+        page.setRecords(Arrays.asList(u));
+        page.setTotal(1L);
+        doReturn(page).when(userMapper).selectPage(any(), any());
+
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "admin")
+                        .requestAttr("roles", Arrays.asList("admin"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.current").value(1))
+                .andExpect(jsonPath("$.data.size").value(10))
+                .andExpect(jsonPath("$.data.total").value(1))
+                .andExpect(jsonPath("$.data.records[0].id").value(1))
+                .andExpect(jsonPath("$.data.records[0].nickname").value("家长甲"));
+    }
+
+    @Test
+    @DisplayName("C2·越权(C403) /api/admin/users:teacher(入驻角色、非平台角色)→ 业务码 403 且不触达 DB")
+    void users_teacher角色_越权拒绝() throws Exception {
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "teacher")
+                        .requestAttr("roles", Arrays.asList("teacher"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value("无权限访问该接口"));
+
+        verify(userMapper, never()).selectPage(any(), any());
+    }
+
+    @Test
+    @DisplayName("C3·越权(C403) /api/admin/users:parent(C端角色)→ 业务码 403")
+    void users_parent角色_越权拒绝() throws Exception {
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Arrays.asList("parent"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value("无权限访问该接口"));
+
+        verify(userMapper, never()).selectPage(any(), any());
+    }
+
+    @Test
+    @DisplayName("C4 /api/admin/energy-rule:list 返回 Page 信封、dimensions 返回列表(E2E 场景3 能量规则管理)")
+    void energyRule_list与dimensions_信封() throws Exception {
+        EnergyRule rule = new EnergyRule();
+        rule.setId(7L);
+        rule.setRuleName("打卡+10");
+        rule.setEventType("checkin");
+        // 控制器原地语义:selectPage(p, null) 的返回值被丢弃,MyBatis-Plus 分页插件
+        // 原地填充传入的 IPage —— 打桩必须同样原地填充 controller 传入的 Page
+        doAnswer(inv -> {
+            com.baomidou.mybatisplus.core.metadata.IPage<EnergyRule> p = inv.getArgument(0);
+            p.setRecords(Arrays.asList(rule));
+            p.setTotal(1L);
+            return p;
+        }).when(energyRuleMapper).selectPage(any(), any());
+
+        EnergyDimension dim = new EnergyDimension();
+        dim.setId(1L);
+        dim.setCode("body");
+        dim.setName("身");
+        when(energyDimensionMapper.selectList(any())).thenReturn(Arrays.asList(dim));
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/list")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{\"page\":1,\"size\":10}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.records[0].ruleName").value("打卡+10"))
+                .andExpect(jsonPath("$.data.total").value(1));
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/dimensions")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].code").value("body"));
+    }
+
+    @Test
+    @DisplayName("C5·不存在(C404) /api/admin/energy-rule/toggle:规则不存在 → 业务拒绝(不产生空指针)")
+    void energyRule_toggle不存在_业务拒绝() throws Exception {
+        when(energyRuleMapper.selectById(eq(99L))).thenReturn(null);
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/toggle")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{\"id\":99}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("规则不存在"));
+    }
+
+    @Test
+    @DisplayName("C6 /api/admin/config/list:返回 SysConfigDTO 列表(E2E 场景4 系统配置页数据源)")
+    void sysConfig_list_dto字段() throws Exception {
+        SysConfig entity = new SysConfig();
+        entity.setConfigKey("wechat.appid");
+        entity.setConfigValue("wx0000000000");
+        SysConfigDTO dto = SysConfigDTO.from(entity);
+        when(sysConfigService.listAll()).thenReturn(Result.success(Arrays.asList(dto)));
+
+        sysConfigApi.perform(post("/api/admin/config/list")
+                            .contentType(MediaType.APPLICATION_JSON)
+                            .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].configKey").value("wechat.appid"))
+                .andExpect(jsonPath("$.data[0].configValue").value("wx0000000000"));
+    }
+
+    @Test
+    @DisplayName("C7 /api/system/health:返回 JVM 运行快照(uptime/memUsagePercent/javaVersion/osName)")
+    void systemHealth_jvm快照字段() throws Exception {
+        systemApi.perform(post("/api/system/health")
+                            .contentType(MediaType.APPLICATION_JSON)
+                            .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.uptime").exists())
+                .andExpect(jsonPath("$.data.memUsagePercent").exists())
+                .andExpect(jsonPath("$.data.javaVersion").exists())
+                .andExpect(jsonPath("$.data.osName").exists());
+    }
+
+    // ================================================================
+    // 边界前提自检
+    // ================================================================
+
+    /**
+     * C4xxx 错误码体系(同键异载荷 C4092 / 乐观锁冲突 C422 / 幂等重放 replay=true)
+     * 在本仓未落地(全仓无 C-code 常量)且本能力键为只读 E2E 套件,不适用;
+     * 此常量为 GREEN 阶段契约化 API_REFERENCE.md §5.5 时预留的边界锚点。
+     */
+    static final List<String> NOT_APPLICABLE_BOUNDARIES =
+            Arrays.asList("replay=true 幂等重放", "同键异载荷 C4092", "乐观锁冲突 C422");
+
+    @Test
+    @DisplayName("C8·平台角色口径自检:admin/operator/finance 可过门禁,teacher/parent 不可(契约前提)")
+    void 平台角色口径_与AdminRoles一致() {
+        assertTrue(AdminRoles.hasAnyPlatformRole(Arrays.asList("admin")), "admin 必须是平台角色");
+        assertTrue(AdminRoles.hasAnyPlatformRole(Arrays.asList("operator", "finance")));
+        assertFalse(AdminRoles.hasAnyPlatformRole(Arrays.asList("teacher")), "teacher(入驻角色)不得越权平台端点");
+        assertFalse(AdminRoles.hasAnyPlatformRole(Arrays.asList("parent")), "parent(C端角色)不得越权平台端点");
+        assertFalse(NOT_APPLICABLE_BOUNDARIES.isEmpty(), "不适用边界清单须随类留存,供 GREEN 阶段 §5.5 契约化引用");
+    }
+}

+ 275 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/ArticleTagFilterContractTest.java

@@ -0,0 +1,275 @@
+package com.etotem.cfc.integration;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.content.ArticleController;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.ArticleReadingRecordMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ArticlePermissionService;
+import com.etotem.cfc.service.ArticleService;
+import com.etotem.cfc.service.ContentDimensionThresholdService;
+import com.etotem.cfc.service.FiveDimensionScoreService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * S-cfc-131(标签订阅缺口键 content.article.listByTag)契约测试。
+ *
+ * <p>规格:{@code docs/superpowers/specs/2026-11-10-article-tag-filter-design.md}(实现 commit 6e9a511e2)。</p>
+ *
+ * <p>锚定条款:</p>
+ * <ul>
+ *   <li>§3.1 {@code getPublicList} 10 参:tag 非空时按 {@code parseCommaOrJsonTags} 解析后内存过滤,
+ *       tags 兼容 JSON 数组({@code ["减脂","睡眠"]})与逗号分隔({@code 减脂,睡眠})两种存储格式;</li>
+ *   <li>§3.1 {@code listTopTags(int limit)}:仅统计已发布且 tags 非空,按频次降序、并列按字典序,
+ *       {@code limit<=0} 默认 20;</li>
+ *   <li>§3.1 {@code POST /api/articles/tags} 返回 {@code Result<List<String>>}(Top 20);</li>
+ *   <li>§3.1 {@code POST /api/articles/list} 读 {@code body.tag} 并透传到 10 参 getPublicList(位置 4)。</li>
+ * </ul>
+ *
+ * <p>口径说明:本类为契约级(Controller↔Service 参数与返回结构),不验 UI 渲染;
+ * 前端 Tab 行为由 cfc-frontend Jest 覆盖。</p>
+ */
+class ArticleTagFilterContractTest {
+
+    private ArticleService articleService;
+    private ArticleController articleController;
+
+    private ArticleMapper articleMapper;
+    private ArticlePermissionService articlePermissionService;
+    private ArticleReadingRecordMapper articleReadingRecordMapper;
+    private FiveDimensionScoreService fiveDimensionScoreService;
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+    private JdbcTemplate jdbcTemplate;
+    private UserMapper userMapper;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        articleService = new ArticleService();
+        articleController = new ArticleController();
+
+        articleMapper = mock(ArticleMapper.class);
+        articlePermissionService = mock(ArticlePermissionService.class);
+        articleReadingRecordMapper = mock(ArticleReadingRecordMapper.class);
+        fiveDimensionScoreService = mock(FiveDimensionScoreService.class);
+        contentDimensionThresholdService = mock(ContentDimensionThresholdService.class);
+        jdbcTemplate = mock(JdbcTemplate.class);
+        userMapper = mock(UserMapper.class);
+
+        injectService("articleMapper", articleMapper);
+        injectService("articlePermissionService", articlePermissionService);
+        injectService("articleReadingRecordMapper", articleReadingRecordMapper);
+        injectService("fiveDimensionScoreService", fiveDimensionScoreService);
+        injectService("contentDimensionThresholdService", contentDimensionThresholdService);
+        injectService("jdbcTemplate", jdbcTemplate);
+        injectService("userMapper", userMapper);
+        injectController("articleService", articleService);
+        injectController("userMapper", userMapper);
+
+        // 权限过滤放行(原样返回)、无家庭得分(阈值过滤 fail-open)、无阅读时长、无已完成记录
+        when(articlePermissionService.filterVisible(any(), any(), any(), any()))
+                .thenAnswer(inv -> inv.getArgument(0));
+        when(fiveDimensionScoreService.getFamilyAverageScores(any())).thenReturn(Collections.emptyMap());
+        when(contentDimensionThresholdService.listByContents(anyString(), any())).thenReturn(Collections.emptyMap());
+        when(jdbcTemplate.queryForList(anyString())).thenReturn(Collections.emptyList());
+        when(articleReadingRecordMapper.selectCompletedArticleIdsByChild(anyLong()))
+                .thenReturn(Collections.emptyList());
+    }
+
+    private void injectService(String field, Object value) throws Exception {
+        Field f = ArticleService.class.getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(articleService, value);
+    }
+
+    private void injectController(String field, Object value) throws Exception {
+        Field f = ArticleController.class.getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(articleController, value);
+    }
+
+    private Article article(Long id, String tags) {
+        Article a = new Article();
+        a.setId(id);
+        a.setStatus("published");
+        a.setTags(tags);
+        a.setTitle("文章" + id);
+        a.setIsFeatured(0);
+        a.setSortOrder(0);
+        a.setPublishedAt(new Date());
+        return a;
+    }
+
+    private void mockAll(List<Article> all) {
+        when(articleMapper.selectList(any())).thenReturn(new ArrayList<>(all));
+    }
+
+    // ---------- TC-AT-01~05:/list 的 tag 过滤语义 ----------
+
+    @Test
+    @DisplayName("TC-AT-01 tag 命中 JSON 数组存法的文章,未命中文章被过滤")
+    void listFiltersByTagJsonArrayStorage() {
+        mockAll(Arrays.asList(
+                article(1L, "[\"减脂\",\"睡眠\"]"),
+                article(2L, "[\"免疫\"]"),
+                article(3L, null)));
+
+        Page<Article> page = articleService.getPublicList(null, null, null, "减脂",
+                1, 10, null, null, null, null);
+
+        assertEquals(1, page.getTotal(), "total 必须是过滤后的真实条数");
+        assertEquals(1, page.getRecords().size());
+        assertEquals(1L, page.getRecords().get(0).getId());
+    }
+
+    @Test
+    @DisplayName("TC-AT-02 tag 命中逗号分隔存法(历史数据兼容)")
+    void listFiltersByTagCommaStorage() {
+        mockAll(Arrays.asList(
+                article(1L, "减脂,睡眠"),
+                article(2L, "免疫")));
+
+        Page<Article> page = articleService.getPublicList(null, null, null, "睡眠",
+                1, 10, null, null, null, null);
+
+        assertEquals(1, page.getTotal());
+        assertEquals(1L, page.getRecords().get(0).getId());
+    }
+
+    @Test
+    @DisplayName("TC-AT-03 tag 为空 → 不做标签过滤,行为与旧版一致")
+    void listWithoutTagKeepsAll() {
+        mockAll(Arrays.asList(article(1L, "[\"减脂\"]"), article(2L, null), article(3L, "免疫")));
+
+        Page<Article> page = articleService.getPublicList(null, null, null, "",
+                1, 10, null, null, null, null);
+
+        assertEquals(3, page.getTotal());
+    }
+
+    @Test
+    @DisplayName("TC-AT-04 tag 无匹配 → 返回空页且 total=0(非 500/异常)")
+    void listWithUnknownTagReturnsEmptyPage() {
+        mockAll(Arrays.asList(article(1L, "[\"减脂\"]")));
+
+        Page<Article> page = articleService.getPublicList(null, null, null, "不存在的标签",
+                1, 10, null, null, null, null);
+
+        assertEquals(0, page.getTotal());
+        assertTrue(page.getRecords().isEmpty());
+    }
+
+    @Test
+    @DisplayName("TC-AT-05 tag 为精确匹配(子串不命中)")
+    void listTagRequiresExactMatch() {
+        mockAll(Arrays.asList(article(1L, "[\"减脂\"]")));
+
+        Page<Article> page = articleService.getPublicList(null, null, null, "减",
+                1, 10, null, null, null, null);
+
+        assertEquals(0, page.getTotal(), "「减」不应命中「减脂」——Tab 语义是全等而非模糊");
+    }
+
+    // ---------- TC-AT-06~09:/tags 聚合语义 ----------
+
+    @Test
+    @DisplayName("TC-AT-06 listTopTags 按出现频次降序")
+    void listTopTagsOrderByFrequencyDesc() {
+        mockAll(Arrays.asList(
+                article(1L, "[\"减脂\",\"睡眠\"]"),
+                article(2L, "[\"减脂\"]"),
+                article(3L, "减脂,免疫")));
+
+        List<String> tags = articleService.listTopTags(20);
+
+        assertEquals(Arrays.asList("减脂", "免疫", "睡眠"), tags);
+    }
+
+    @Test
+    @DisplayName("TC-AT-07 listTopTags 频次并列时按标签字典序")
+    void listTopTagsTieBreakByLexicalOrder() {
+        mockAll(Arrays.asList(
+                article(1L, "[\"睡眠\"]"),
+                article(2L, "[\"免疫\"]"),
+                article(3L, "[\"减脂\"]")));
+
+        List<String> tags = articleService.listTopTags(20);
+
+        // 频次均为 1 → 字典序(按 String.compareTo:免疫 < 减脂 < 睡眠 的码点序)
+        List<String> sorted = new ArrayList<>(Arrays.asList("睡眠", "免疫", "减脂"));
+        Collections.sort(sorted);
+        assertEquals(sorted, tags);
+    }
+
+    @Test
+    @DisplayName("TC-AT-08 listTopTags limit<=0 时默认取 20 条")
+    void listTopTagsDefaultLimit20() {
+        List<Article> all = new ArrayList<>();
+        for (int i = 0; i < 25; i++) {
+            all.add(article((long) i + 1, "[\"tag" + i + "\"]"));
+        }
+        mockAll(all);
+
+        assertEquals(20, articleService.listTopTags(0).size());
+        assertEquals(20, articleService.listTopTags(-5).size());
+        assertEquals(3, articleService.listTopTags(3).size(), "显式 limit 必须生效");
+    }
+
+    @Test
+    @DisplayName("TC-AT-09 listTopTags 忽略空 tags / 空标签项")
+    void listTopTagsSkipsBlankTags() {
+        mockAll(Arrays.asList(
+                article(1L, null),
+                article(2L, "   "),
+                article(3L, "[\"\",\"  \",\"减脂\"]"),
+                article(4L, "减脂,,")));
+
+        assertEquals(Collections.singletonList("减脂"), articleService.listTopTags(20));
+    }
+
+    // ---------- TC-AT-10:Controller 契约 ----------
+
+    @Test
+    @DisplayName("TC-AT-10 POST /api/articles/tags 返回 Top20;/list 透传 body.tag")
+    void controllerExposesTagsEndpointAndPassesTag() {
+        mockAll(Arrays.asList(
+                article(1L, "[\"减脂\"]"),
+                article(2L, "[\"减脂\"]"),
+                article(3L, "[\"免疫\"]")));
+
+        Result<List<String>> tagsResult = articleController.tags();
+        assertEquals(200, tagsResult.getCode());
+        assertNotNull(tagsResult.getData());
+        assertEquals(Arrays.asList("减脂", "免疫"), tagsResult.getData());
+
+        Map<String, Object> body = new HashMap<>();
+        body.put("tag", "免疫");
+        Result<Page<Article>> listResult = articleController.list(body, null, null);
+        assertEquals(200, listResult.getCode());
+        assertEquals(1, listResult.getData().getTotal(),
+                "body.tag 必须透传到 getPublicList 第 4 参(否则标签筛选静默失效)");
+        assertEquals(3L, listResult.getData().getRecords().get(0).getId());
+    }
+}

+ 283 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/DailyCheckinStreakFlowTest.java

@@ -0,0 +1,283 @@
+package com.etotem.cfc.integration;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.DailyCheckinController;
+import com.etotem.cfc.controller.StreakController;
+import com.etotem.cfc.entity.DailyHealthCheckin;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.service.DailyCheckinService;
+import com.etotem.cfc.service.StreakService;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import org.junit.jupiter.api.*;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * ================================================================
+ * 场景:连续签到奖励全流程
+ * ================================================================
+ * 用户故事:作为孩子,我希望每天完成健康打卡,
+ *           保持连续签到记录以获得更多奖励。
+ *
+ * 流程步骤:
+ *   1. 孩子每天完成健康打卡(饮食、运动、睡眠、饮水、心情)
+ *   2. 系统记录打卡并更新连续签到天数
+ *   3. 达到特定天数阈值时发放奖励(积分或能量)
+ *   4. 第二天继续打卡以保持连续
+ *   5. 如果中断,系统重置连续天数为0
+ *
+ * 关键里程碑:
+ *   - [Milestone-1] 打卡记录创建成功
+ *   - [Milestone-2] 连续签到天数正确累计
+ *   - [Milestone-3] 达到奖励阈值,奖励发放
+ *   - [Milestone-4] 中断后重置连续天数
+ * ================================================================
+ */
+@SpringBootTest
+public class DailyCheckinStreakFlowTest {
+
+    @Resource
+    private DailyCheckinController checkinController;
+
+    @Resource
+    private StreakController streakController;
+
+    @MockBean
+    private DailyCheckinService dailyCheckinService;
+
+    @MockBean
+    private StreakService streakService;
+
+    @MockBean
+    private UserMapper userMapper;
+
+    @MockBean
+    private FamilyMemberMapper familyMemberMapper;
+
+    // ========== 测试数据 ==========
+
+    private static final Long USER_ID = 1001L;
+    private static final Long CHILD_ID = 2001L;
+    private static final Long FAMILY_ID = 3001L;
+    private static final Long CHECKIN_ID = 1L;
+
+    // ========== 场景1:每日健康打卡 ==========
+
+    /**
+     * 场景:孩子完成每日健康打卡
+     * 角色:孩子
+     * 触发条件:每天进入打卡页面填写健康数据
+     */
+    @Test
+    @DisplayName("[场景1] 孩子完成每日打卡 - 期望打卡成功")
+    void childDailyCheckin_Success() {
+        // === Given:孩子填写了打卡数据 ===
+        DailyHealthCheckin checkin = new DailyHealthCheckin();
+        checkin.setMemberId(CHILD_ID);
+        checkin.setDietScore(85);
+        checkin.setExerciseScore(90);
+        checkin.setSleepScore(80);
+        checkin.setWaterIntake(2000);
+        checkin.setMoodScore(88);
+
+        DailyHealthCheckin savedCheckin = new DailyHealthCheckin();
+        savedCheckin.setId(CHECKIN_ID);
+        savedCheckin.setMemberId(CHILD_ID);
+        savedCheckin.setDietScore(85);
+
+        when(dailyCheckinService.createCheckin(any(DailyHealthCheckin.class)))
+                .thenReturn(savedCheckin);
+
+        // === When:提交打卡 ===
+        Result<DailyHealthCheckin> result = checkinController.create(checkin, 1L);
+
+        // === Then:Milestone-1 - 打卡成功 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(CHECKIN_ID, result.getData().getId());
+        verify(dailyCheckinService).createCheckin(any(DailyHealthCheckin.class));
+    }
+
+    // ========== 场景2:查看打卡列表 ==========
+
+    /**
+     * 场景:查看历史打卡记录
+     * 角色:孩子或家长
+     * 触发条件:进入打卡历史页面
+     */
+    @Test
+    @DisplayName("[场景2] 查看打卡记录列表 - 期望返回历史记录")
+    void parentViewsCheckinList_Success() {
+        // === Given:有多条打卡记录 ===
+        Map<String, Object> listRequest = new HashMap<>();
+        listRequest.put("memberId", CHILD_ID);
+
+        List<DailyHealthCheckin> mockList = Arrays.asList(
+                createCheckin(1L, CHILD_ID, "2026-07-01", 85),
+                createCheckin(2L, CHILD_ID, "2026-06-30", 82),
+                createCheckin(3L, CHILD_ID, "2026-06-29", 88)
+        );
+
+        when(dailyCheckinService.getCheckinsByMember(CHILD_ID)).thenReturn(mockList);
+
+        // === When:请求打卡列表 ===
+        Result<List<DailyHealthCheckin>> result = checkinController.list(listRequest, 1L);
+
+        // === Then:返回历史记录 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(dailyCheckinService).getCheckinsByMember(CHILD_ID);
+    }
+
+    // ========== 场景3:获取连续签到进度 ==========
+
+    /**
+     * 场景:孩子查看自己的连续签到进度
+     * 角色:孩子
+     * 触发条件:查看签到激励页面
+     */
+    @Test
+    @DisplayName("[场景3] 获取连续签到进度 - 期望返回当前连续天数和奖励状态")
+    void childGetsStreakProgress_Success() {
+        // === Given:孩子已连续打卡多天 ===
+        User user = new User();
+        user.setId(USER_ID);
+        user.setFamilyId(FAMILY_ID);
+
+        FamilyMember child = new FamilyMember();
+        child.setId(CHILD_ID);
+        child.setFamilyId(FAMILY_ID);
+
+        Map<String, Object> mockProgress = new HashMap<>();
+        mockProgress.put("childId", CHILD_ID);
+        mockProgress.put("currentStreak", 7);
+        mockProgress.put("longestStreak", 15);
+        mockProgress.put("todayChecked", true);
+        mockProgress.put("nextRewardDays", 3); // 再连续3天可获奖励
+        mockProgress.put("pendingReward", true); // 有待领取奖励
+
+        when(userMapper.selectById(USER_ID)).thenReturn(user);
+        when(familyMemberMapper.selectById(CHILD_ID)).thenReturn(child);
+        when(streakService.getStreakProgress(CHILD_ID)).thenReturn(mockProgress);
+
+        // === When:请求签到进度 ===
+        Result<Map<String, Object>> result = streakController.getStreakProgress(USER_ID, CHILD_ID);
+
+        // === Then:Milestone-2 - 返回连续天数等信息 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(7, result.getData().get("currentStreak"));
+        assertEquals(15, result.getData().get("longestStreak"));
+        assertTrue((Boolean) result.getData().get("todayChecked"));
+    }
+
+    // ========== 场景5:打卡中断重置 ==========
+
+    /**
+     * 场景:孩子忘记打卡,连续签到中断
+     * 角色:系统(定时任务触发)
+     * 触发条件:凌晨检查发现昨天未打卡
+     */
+    @Test
+    @DisplayName("[场景5] 打卡中断 - 期望连续天数重置")
+    void childMissesCheckin_StreakReset() {
+        // === Given:昨天未打卡 ===
+        doNothing().when(streakService).resetStreakIfNeeded();
+
+        // === When:系统重置中断的签到 ===
+        Result<Boolean> result = streakController.resetStreak();
+
+        // === Then:Milestone-4 - 连续天数重置 ===
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData());
+        verify(streakService).resetStreakIfNeeded();
+    }
+
+    // ========== 场景6:更新打卡记录 ==========
+
+    /**
+     * 场景:孩子补充或修改今天的打卡数据
+     * 角色:孩子
+     * 触发条件:发现打卡数据填错需要修改
+     */
+    @Test
+    @DisplayName("[场景6] 更新打卡记录 - 期望更新成功")
+    void childUpdatesCheckin_Success() {
+        // === Given:需要修改打卡数据 ===
+        Map<String, Object> updateRequest = new HashMap<>();
+        updateRequest.put("id", CHECKIN_ID);
+        updateRequest.put("dietScore", 90); // 原本85,修改为90
+        updateRequest.put("moodScore", 95);
+
+        DailyHealthCheckin updatedCheckin = new DailyHealthCheckin();
+        updatedCheckin.setId(CHECKIN_ID);
+        updatedCheckin.setDietScore(90);
+        updatedCheckin.setMoodScore(95);
+
+        when(dailyCheckinService.updateCheckin(eq(CHECKIN_ID), any(Map.class)))
+                .thenReturn(updatedCheckin);
+
+        // === When:更新打卡记录 ===
+        Result<DailyHealthCheckin> result = checkinController.update(updateRequest);
+
+        // === Then:更新成功 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(90, result.getData().getDietScore());
+        assertEquals(95, result.getData().getMoodScore());
+    }
+
+    // ========== 场景7:删除打卡记录 ==========
+
+    /**
+     * 场景:孩子删除一条错误的打卡记录
+     * 角色:孩子
+     * 触发条件:发现打卡记录有误需要删除
+     */
+    @Test
+    @DisplayName("[场景7] 删除打卡记录 - 期望删除成功")
+    void childDeletesCheckin_Success() {
+        // === Given:需要删除记录 ===
+        Map<String, Object> deleteRequest = new HashMap<>();
+        deleteRequest.put("id", CHECKIN_ID);
+        // 删除打卡的 userId 来自请求体(DailyCheckinController#delete 用 ParamUtils 取 userId),
+        // 不传会以 null 调 service(A 类用例缺陷:原用例漏放 userId 且用 anyLong() 掩盖)
+        deleteRequest.put("userId", CHILD_ID);
+
+        when(dailyCheckinService.deleteCheckin(eq(CHECKIN_ID), eq(CHILD_ID))).thenReturn(true);
+
+        // === When:删除打卡记录 ===
+        Result<String> result = checkinController.delete(deleteRequest);
+
+        // === Then:删除成功 ===
+        assertEquals(200, result.getCode());
+        assertEquals("删除成功", result.getData());
+        verify(dailyCheckinService).deleteCheckin(eq(CHECKIN_ID), eq(CHILD_ID));
+    }
+
+    // ========== Helper Methods ==========
+
+    private DailyHealthCheckin createCheckin(Long id, Long memberId, String checkinDateStr, Integer score) {
+        DailyHealthCheckin checkin = new DailyHealthCheckin();
+        checkin.setId(id);
+        checkin.setMemberId(memberId);
+        try {
+            checkin.setCheckinDate(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(checkinDateStr));
+        } catch (Exception e) { /* ignore */ }
+        checkin.setDietScore(score);
+        checkin.setExerciseScore(score);
+        checkin.setSleepScore(score);
+        checkin.setMoodScore(score);
+        return checkin;
+    }
+}

+ 317 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/EnergySystemFlowTest.java

@@ -0,0 +1,317 @@
+package com.etotem.cfc.integration;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.EnergyController;
+import com.etotem.cfc.entity.EnergyLog;
+import com.etotem.cfc.dto.EnergySandboxDTO;
+import com.etotem.cfc.service.EnergyService;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.entity.User;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import org.junit.jupiter.api.*;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * ================================================================
+ * 场景:能量系统收支全流程
+ * ================================================================
+ * 用户故事:作为家长,我希望了解和管理家庭成员的五维能量收支情况,
+ *           通过完成任务获取能量,用能量兑换奖励。
+ *
+ * 流程步骤:
+ *   1. 查看家庭能量沙盘,了解各维度能量分布
+ *   2. 孩子完成任务,获得能量奖励(收入)
+ *   3. 使用能量兑换心愿或参与活动(支出)
+ *   4. 系统根据收支计算新的维度比例
+ *   5. 综合健康指数更新
+ *
+ * 关键里程碑:
+ *   - [Milestone-1] 获取能量沙盘,了解当前能量状态
+ *   - [Milestone-2] 任务完成,能量发放成功
+ *   - [Milestone-3] 能量兑换,积分扣减
+ *   - [Milestone-4] 维度比例重算
+ *   - [Milestone-5] 健康指数更新
+ * ================================================================
+ */
+@SpringBootTest
+public class EnergySystemFlowTest {
+
+    @Resource
+    private EnergyController energyController;
+
+    @MockBean
+    private EnergyService energyService;
+
+    @MockBean
+    private UserMapper userMapper;
+
+    // ========== 测试数据 ==========
+
+    private static final Long PARENT_USER_ID = 1001L;
+    private static final Long CHILD_ID = 2001L;
+    private static final Long FAMILY_ID = 3001L;
+
+    // ========== 场景1:获取家庭能量沙盘 ==========
+
+    /**
+     * 场景:家长查看家庭的五维能量分布
+     * 角色:家长
+     * 触发条件:进入能量沙盘页面
+     */
+@Disabled("Controller return type changed to Map, test needs update")
+    @Test
+    @DisplayName("[场景1] 获取家庭能量沙盘 - 期望返回五维能量数据")
+    void parentGetsFamilyEnergySandbox_Success() {
+        // === Given:存在家庭能量数据 ===
+        User parent = new User();
+        parent.setId(PARENT_USER_ID);
+        parent.setFamilyId(FAMILY_ID);
+
+        EnergySandboxDTO mockSandbox = createMockEnergySandbox();
+
+        when(userMapper.selectById(PARENT_USER_ID)).thenReturn(parent);
+        when(energyService.calculateFamilyEnergy(FAMILY_ID)).thenReturn(mockSandbox);
+
+        // === When:请求能量沙盘数据 ===
+        Result<?> result = energyController.getFamilyEnergySandbox(PARENT_USER_ID, null);
+
+        // === Then:Milestone-1 - 返回完整能量数据 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertNotNull(result.getData());
+        
+        
+        
+        
+        verify(energyService).calculateFamilyEnergy(FAMILY_ID);
+    }
+
+    /**
+     * 场景:用户未加入任何家庭
+     * 角色:用户
+     * 触发条件:用户尝试查看能量但未加入家庭
+     */
+    @Test
+    @DisplayName("[场景1b] 用户未加入家庭 - 期望返回错误提示")
+    void userWithoutFamily_Fails() {
+        // === Given:用户未加入家庭 ===
+        User user = new User();
+        user.setId(PARENT_USER_ID);
+        user.setFamilyId(null);
+
+        when(userMapper.selectById(PARENT_USER_ID)).thenReturn(user);
+
+        // === When:请求能量沙盘 ===
+        Result<?> result = energyController.getFamilyEnergySandbox(PARENT_USER_ID, null);
+
+        // === Then:返回错误 ===
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("未加入家庭"));
+    }
+
+    // ========== 场景2:任务完成能量发放 ==========
+
+    /**
+     * 场景:孩子完成任务后,系统自动发放能量奖励
+     * 角色:系统(自动触发)
+     * 触发条件:任务状态变更为"已完成"
+     */
+    @Test
+    @DisplayName("[场景2] 任务完成能量发放 - 期望能量增加且流水记录")
+    void taskCompletionGrantsEnergy_Success() {
+        // === Given:任务完成,需要发放能量 ===
+        Long taskId = 1L;
+        Long energyAmount = 100L;
+        String dimensionCode = "action"; // 行
+
+        EnergyLog mockLog = createEnergyLog(CHILD_ID, "income", energyAmount, dimensionCode, "任务奖励");
+
+        when(energyService.grantEnergy(eq(CHILD_ID), eq(taskId), eq(energyAmount), eq(dimensionCode)))
+                .thenReturn(mockLog);
+
+        Map<String, Object> grantParams = new HashMap<>();
+        grantParams.put("childId", CHILD_ID);
+        grantParams.put("taskId", taskId);
+        grantParams.put("amount", energyAmount);
+        grantParams.put("dimensionCode", dimensionCode);
+
+        // === When:触发能量发放 ===
+        Result<EnergyLog> result = energyController.grantEnergy(grantParams, CHILD_ID, null);
+
+        // === Then:Milestone-2 - 能量发放成功 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(energyAmount.intValue(), result.getData().getAmount());
+        verify(energyService).grantEnergy(eq(CHILD_ID), eq(taskId), eq(energyAmount), eq(dimensionCode));
+    }
+
+    // ========== 场景3:能量兑换心愿 ==========
+
+    /**
+     * 场景:孩子使用积累的能量兑换心愿
+     * 角色:孩子
+     * 触发条件:兑换心愿时选择能量支付
+     */
+    @Test
+    @DisplayName("[场景3] 能量兑换心愿 - 期望能量扣减")
+    void childExchangesWishWithEnergy_Success() {
+        // === Given:孩子有足够的能量 ===
+        Long wishId = 1L;
+        Long energyDeduct = 500L;
+
+        when(energyService.deductForWish(eq(CHILD_ID), eq(wishId), eq(energyDeduct)))
+                .thenReturn(true);
+
+        Map<String, Object> deductParams = new HashMap<>();
+        deductParams.put("childId", CHILD_ID);
+        deductParams.put("wishId", wishId);
+        deductParams.put("amount", energyDeduct);
+
+        // === When:使用能量兑换心愿 ===
+        Result<Boolean> result = energyController.deductForWish(deductParams, CHILD_ID, null);
+
+        // === Then:Milestone-3 - 能量扣减成功 ===
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData());
+        verify(energyService).deductForWish(eq(CHILD_ID), eq(wishId), eq(energyDeduct));
+    }
+
+    /**
+     * 场景:能量不足时兑换心愿
+     * 角色:孩子
+     * 触发条件:当前能量不足以支付
+     */
+    @Test
+    @DisplayName("[场景3b] 能量不足时兑换 - 期望返回错误")
+    void childExchangesWithInsufficientEnergy_Fails() {
+        // === Given:能量不足 ===
+        Long wishId = 1L;
+        Long energyDeduct = 5000L; // 超过可用能量
+
+        Map<String, Object> deductRequest = new HashMap<>();
+        deductRequest.put("childId", CHILD_ID);
+        deductRequest.put("wishId", wishId);
+        deductRequest.put("amount", energyDeduct);
+
+        when(energyService.deductForWish(eq(CHILD_ID), eq(wishId), eq(energyDeduct)))
+                .thenThrow(new RuntimeException("能量不足,当前可用:300,需要:5000"));
+
+        // === When:尝试兑换 ===
+        Result<Boolean> result = energyController.deductForWish(deductRequest, CHILD_ID, null);
+
+        // === Then:返回错误 ===
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("能量不足"));
+    }
+
+    // ========== 场景4:查询能量流水 ==========
+
+    /**
+     * 场景:查看能量收支明细
+     * 角色:家长或孩子
+     * 触发条件:进入能量明细页面
+     */
+    @Test
+    @DisplayName("[场景4] 查询能量流水 - 期望返回分页记录")
+    void parentQueriesEnergyLogs_Success() {
+        // === Given:有多条能量流水记录 ===
+        Map<String, Object> request = new HashMap<>();
+        request.put("childId", CHILD_ID);
+        request.put("dimensionCode", "action");
+        request.put("page", 1);
+        request.put("size", 10);
+
+        Page<EnergyLog> mockPage = new Page<>(1, 10);
+        mockPage.setRecords(Arrays.asList(
+                createEnergyLog(CHILD_ID, "income", 100L, "action", "完成任务奖励"),
+                createEnergyLog(CHILD_ID, "expense", 50L, "action", "兑换心愿"),
+                createEnergyLog(CHILD_ID, "income", 80L, "body", "运动打卡")
+        ));
+
+        when(energyService.getLogs(eq(CHILD_ID), eq("action"), eq(1), eq(10)))
+                .thenReturn(mockPage);
+
+        // === When:查询能量流水 ===
+        Result<Page<EnergyLog>> result = energyController.getEnergyLogs(request, CHILD_ID, null);
+
+        // === Then:返回分页数据 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().getRecords().size());
+    }
+
+    // ========== 场景5:获取五维能量概览 ==========
+
+    /**
+     * 场景:查看孩子的五维能量概览
+     * 角色:家长
+     * 触发条件:查看孩子的能量总览
+     */
+    @Test
+    @DisplayName("[场景5] 获取五维能量概览 - 期望返回五维汇总数据")
+    void parentGetsEnergyOverview_Success() {
+        // === Given:请求孩子的能量概览 ===
+        Map<String, Object> request = new HashMap<>();
+        request.put("childId", CHILD_ID);
+
+        Map<String, Object> mockOverview = new HashMap<>();
+        mockOverview.put("childId", CHILD_ID);
+        mockOverview.put("totalEnergy", 12500L);
+        mockOverview.put("bodyEnergy", 2500L);
+        mockOverview.put("mindEnergy", 2200L);
+        mockOverview.put("wisdomEnergy", 2800L);
+        mockOverview.put("actionEnergy", 2500L);
+        mockOverview.put("wealthEnergy", 2500L);
+        mockOverview.put("healthIndex", 87.5);
+        mockOverview.put("trend", "up");
+
+        when(energyService.getOverview(CHILD_ID)).thenReturn(mockOverview);
+
+        // === When:请求能量概览 ===
+        Result<Map<String, Object>> result = energyController.getEnergyOverview(request, CHILD_ID, null);
+
+        // === Then:Milestone-5 - 返回概览数据包含健康指数 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(12500L, result.getData().get("totalEnergy"));
+        assertEquals(87.5, result.getData().get("healthIndex"));
+        assertNotNull(result.getData().get("bodyEnergy"));
+        assertNotNull(result.getData().get("mindEnergy"));
+        assertNotNull(result.getData().get("wisdomEnergy"));
+        assertNotNull(result.getData().get("actionEnergy"));
+        assertNotNull(result.getData().get("wealthEnergy"));
+    }
+
+    // ========== Helper Methods ==========
+
+    private EnergySandboxDTO createMockEnergySandbox() {
+        EnergySandboxDTO dto = new EnergySandboxDTO();
+        dto.setBodyScore(85);
+        dto.setMindScore(80);
+        dto.setWisdomScore(90);
+        dto.setActionScore(75);
+        dto.setWealthScore(88);
+        dto.setOverallScore(83);
+        return dto;
+    }
+
+    private EnergyLog createEnergyLog(Long memberId, String type, Long amount, String dimension, String reason) {
+        EnergyLog log = new EnergyLog();
+        log.setId(1L);
+        log.setMemberId(memberId);
+        log.setSourceType(type);
+        log.setAmount(amount.intValue());
+        log.setDimensionId(1L);
+        log.setDescription(reason);
+        log.setCreatedAt(new Date());
+        return log;
+    }
+}

+ 381 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/GrowthRecordSyncFlowTest.java

@@ -0,0 +1,381 @@
+package com.etotem.cfc.integration;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.growth.GrowthRecordController;
+import com.etotem.cfc.entity.AssessmentOrder;
+import com.etotem.cfc.entity.GrowthRecord;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.dto.ParsedReport;
+import com.etotem.cfc.service.GrowthRecordService;
+import com.etotem.cfc.service.AssessmentOrderService;
+import com.etotem.cfc.service.ReportParseService;
+import com.etotem.cfc.service.StorageService;
+import com.etotem.cfc.mapper.FamilyMapper;
+import org.junit.jupiter.api.*;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.mock.web.MockMultipartFile;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * ================================================================
+ * 场景:成长记录同步全流程
+ * ================================================================
+ * 用户故事:作为家长,我希望记录孩子的成长轨迹,
+ *           上传健康报告并与测评结果关联,获得全面的成长分析。
+ *
+ * 流程步骤:
+ *   1. 家长创建孩子的成长档案(基本信息、学校、年级等)
+ *   2. 家长上传孩子的健康体检报告
+ *   3. 系统解析报告,提取身高、体重、视力等数据
+ *   4. 成长记录与认知测评结果关联
+ *   5. 系统更新孩子的五维能量数据
+ *
+ * 关键里程碑:
+ *   - [Milestone-1] 成长档案创建成功
+ *   - [Milestone-2] 健康报告上传并解析成功
+ *   - [Milestone-3] 成长记录与测评报告关联
+ *   - [Milestone-4] 五维能量数据更新
+ * ================================================================
+ */
+@SpringBootTest
+public class GrowthRecordSyncFlowTest {
+
+    @Resource
+    private GrowthRecordController growthRecordController;
+
+    @MockBean
+    private GrowthRecordService growthRecordService;
+
+    @MockBean
+    private AssessmentOrderService assessmentOrderService;
+
+    @MockBean
+    private ReportParseService reportParseService;
+
+    @MockBean
+    private StorageService storageService;
+
+    @MockBean
+    private FamilyMapper familyMapper;
+
+    // ========== 测试数据 ==========
+
+    private static final Long PARENT_USER_ID = 1001L;
+    private static final Long CHILD_ID = 2001L;
+    private static final Long FAMILY_ID = 3001L;
+    private static final Long RECORD_ID = 1L;
+
+    // ========== 场景1:创建成长档案 ==========
+
+    /**
+     * 场景:家长为孩子创建一个成长档案
+     * 角色:家长
+     * 触发条件:家长首次使用成长记录功能
+     */
+    @Test
+    @DisplayName("[场景1] 创建孩子成长档案 - 期望档案创建成功")
+    void parentCreatesGrowthRecord_Success() {
+        // === Given:家长填写了孩子的基本信息 ===
+        GrowthRecord record = new GrowthRecord();
+        record.setMemberId(CHILD_ID);
+        record.setSchool("北京市第一小学");
+        record.setGrade(3);
+        record.setAcademicPerformance("优秀");
+        record.setSchoolProvince("北京市");
+        record.setSchoolCity("北京市");
+        record.setSchoolDistrict("海淀区");
+
+        GrowthRecord savedRecord = new GrowthRecord();
+        savedRecord.setId(RECORD_ID);
+        savedRecord.setMemberId(CHILD_ID);
+        savedRecord.setSchool("北京市第一小学");
+        savedRecord.setGrade(3);
+
+        when(growthRecordService.createRecord(any(GrowthRecord.class))).thenReturn(savedRecord);
+
+        // === When:家长提交创建成长档案 ===
+        Result<GrowthRecord> result = growthRecordController.createRecord(record, PARENT_USER_ID);
+
+        // === Then:Milestone-1 - 档案创建成功 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(RECORD_ID, result.getData().getId());
+        verify(growthRecordService).createRecord(any(GrowthRecord.class));
+    }
+
+    /**
+     * 场景:家长创建档案时未选择孩子
+     * 角色:家长
+     * 触发条件:表单中孩子ID为空
+     */
+    @Test
+    @DisplayName("[场景1b] 创建档案时未选择孩子 - 期望返回错误")
+    void parentCreatesRecordWithoutChild_Fails() {
+        // === Given:未选择孩子 ===
+        GrowthRecord record = new GrowthRecord();
+        record.setSchool("北京市第一小学");
+        record.setGrade(3);
+        // memberId 为 null
+
+        // === When:尝试创建档案 ===
+        Result<GrowthRecord> result = growthRecordController.createRecord(record, PARENT_USER_ID);
+
+        // === Then:返回错误提示 ===
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("请选择家庭成员"));
+    }
+
+    // ========== 场景2:创建档案并购买测评 ==========
+
+    /**
+     * 场景:家长创建成长档案的同时购买认知测评服务
+     * 角色:家长
+     * 触发条件:勾选"同时购买测评"选项
+     */
+    @Test
+    @DisplayName("[场景2] 创建档案并购买测评任务模板 - 期望档案和订单同时创建")
+    void parentCreatesRecordWithOrder_Success() {
+        // === Given:家长填写档案信息并选择同时购买测评 ===
+        Map<String, Object> request = new HashMap<>();
+        request.put("memberId", CHILD_ID);
+        request.put("familyId", FAMILY_ID);
+        request.put("packageId", 5L);
+        request.put("school", "北京市第一小学");
+        request.put("grade", 3);
+        request.put("alsoPurchaseAssessment", true);
+
+        Family family = new Family();
+        family.setId(FAMILY_ID);
+        family.setTeacherId(4001L);
+
+        GrowthRecord savedRecord = new GrowthRecord();
+        savedRecord.setId(RECORD_ID);
+        savedRecord.setMemberId(CHILD_ID);
+
+        when(familyMapper.selectById(FAMILY_ID)).thenReturn(family);
+        when(growthRecordService.createRecord(any(GrowthRecord.class))).thenReturn(savedRecord);
+
+        // 下单服务返回真实订单对象:控制器会取 orderNo/actualPrice/status,
+        // 返回 null 会在控制器内 NPE(R134 修正)
+        AssessmentOrder order = new AssessmentOrder();
+        order.setOrderNo("AS20261111000001");
+        order.setActualPrice(19900L);
+        order.setStatus("pending");
+        when(assessmentOrderService.createOrder(anyLong(), anyLong(), anyLong(), any(),
+                anyLong(), any(), any(), anyLong(), anyLong())).thenReturn(order);
+
+        // === When:提交创建档案和购买测评 ===
+        Result<Map<String, Object>> result = growthRecordController.createRecordWithOrder(request, PARENT_USER_ID, FAMILY_ID, CHILD_ID);
+
+        // === Then:档案创建成功,订单也创建 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertNotNull(result.getData().get("record"));
+        assertNotNull(result.getData().get("order"));
+        verify(growthRecordService).createRecord(any(GrowthRecord.class));
+    }
+
+    // ========== 场景3:上传健康报告并解析 ==========
+
+    /**
+     * 场景:家长上传孩子的健康体检报告PDF,系统自动解析
+     * 角色:家长
+     * 触发条件:上传体检报告文件
+     */
+    @Test
+    @DisplayName("[场景3] 上传并解析健康报告 - 期望解析出健康数据")
+    void parentUploadsHealthReport_Success() {
+        // === Given:上传了健康报告文件 ===
+        Long reportId = 1L;
+        String fileUrl = "https://storage.example.com/reports/health_2026_06.pdf";
+
+        ParsedReport parsedReport = ParsedReport.builder()
+                .overallScore(85)
+                .attentionScore(88)
+                .focusScore(82)
+                .memoryScore(90)
+                .logicScore(78)
+                .perceptionScore(85)
+                .spatialScore(80)
+                .processingSpeedScore(83)
+                .emotionScore(86)
+                .resilienceScore(84)
+                .build();
+
+        MockMultipartFile file = new MockMultipartFile(
+                "file", "health_2026_06.pdf", "application/pdf", "%PDF-1.4 test".getBytes());
+        when(storageService.storeFile(any())).thenReturn(fileUrl);
+        when(storageService.getFilePath(eq(fileUrl))).thenReturn("D:/tmp/health_2026_06.pdf");
+        when(reportParseService.parseReport(eq("D:/tmp/health_2026_06.pdf"))).thenReturn(parsedReport);
+
+        // === When:系统解析报告 ===
+        Result<Map<String, Object>> result = growthRecordController.uploadAndParse(file);
+
+        // === Then:Milestone-2 - 报告解析成功,返回提取的数据 ===
+        // 当前契约(upload-and-parse Stage 1):{sourceFileUrl, parsed, reportDateStr, hasDate}
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(fileUrl, result.getData().get("sourceFileUrl"));
+        Object parsedObj = result.getData().get("parsed");
+        assertNotNull(parsedObj);
+        assertEquals(85, ((ParsedReport) parsedObj).getOverallScore());
+        assertEquals(Boolean.FALSE, result.getData().get("hasDate"));
+        verify(reportParseService).parseReport(eq("D:/tmp/health_2026_06.pdf"));
+    }
+
+    // ========== 场景4:关联成长记录与测评结果 ==========
+
+    /**
+     * 场景:成长记录与认知测评结果进行关联
+     * 角色:系统(自动关联)
+     * 触发条件:测评报告生成后
+     */
+    @Test
+    @DisplayName("[场景4] 成长记录关联测评报告 - 期望关联成功")
+    void growthRecordAssociatesWithAssessment_Success() {
+        // === Given:存在成长记录和测评结果 ===
+        GrowthRecord record = new GrowthRecord();
+        record.setId(RECORD_ID);
+        record.setMemberId(CHILD_ID);
+
+        when(growthRecordService.associateWithAssessment(eq(RECORD_ID), anyLong())).thenReturn(true);
+
+        // === Then:关联成功(无 controller 端点,直接验证 service) ===
+        assertTrue(growthRecordService.associateWithAssessment(RECORD_ID, 1L));
+        verify(growthRecordService).associateWithAssessment(eq(RECORD_ID), anyLong());
+    }
+
+    // ========== 场景5:查询孩子的成长记录列表 ==========
+
+    /**
+     * 场景:家长查看孩子的历史成长记录
+     * 角色:家长
+     * 触发条件:进入成长记录历史页面
+     */
+    @Test
+    @DisplayName("[场景5] 查询成长记录历史 - 期望返回记录列表")
+    void parentQueriesGrowthHistory_Success() {
+        // === Given:有多条成长记录 ===
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                createGrowthRecord(1L, CHILD_ID, "2026-06-01", "本学期表现优异"),
+                createGrowthRecord(2L, CHILD_ID, "2026-03-01", "体测达标"),
+                createGrowthRecord(3L, CHILD_ID, "2025-12-01", "学习进步明显")
+        );
+
+        when(growthRecordService.getRecordsByChild(CHILD_ID)).thenReturn(mockRecords);
+
+        // === When:家长请求历史记录 ===
+        Result<List<GrowthRecord>> result = growthRecordController.getRecordsByChild(CHILD_ID, null);
+
+        // === Then:返回历史记录列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(growthRecordService).getRecordsByChild(CHILD_ID);
+    }
+
+    @Test
+    @DisplayName("[场景5b] 查询孩子的成长记录历史(新接口) - 期望返回记录列表")
+    void parentQueriesGrowthHistoryWithNewEndpoint_Success() {
+        // === Given:有多条成长记录 ===
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                createGrowthRecord(1L, CHILD_ID, "2026-06-01", "本学期表现优异"),
+                createGrowthRecord(2L, CHILD_ID, "2026-03-01", "体测达标"),
+                createGrowthRecord(3L, CHILD_ID, "2025-12-01", "学习进步明显")
+        );
+
+        when(growthRecordService.getRecordsByChild(CHILD_ID)).thenReturn(mockRecords);
+
+        // === When:家长通过新接口请求历史记录 ===
+        Result<List<GrowthRecord>> result = growthRecordController.getRecordsByChild(CHILD_ID, null);
+
+        // === Then:返回历史记录列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(growthRecordService).getRecordsByChild(CHILD_ID);
+    }
+
+    @Test
+    @DisplayName("[场景5c] 查询孩子的成长记录历史(新接口,请求体) - 期望返回记录列表")
+    void parentQueriesGrowthHistoryWithNewEndpoint_RequestBody_Success() {
+        // === Given:有多条成长记录 ===
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                createGrowthRecord(1L, CHILD_ID, "2026-06-01", "本学期表现优异"),
+                createGrowthRecord(2L, CHILD_ID, "2026-03-01", "体测达标"),
+                createGrowthRecord(3L, CHILD_ID, "2025-12-01", "学习进步明显")
+        );
+
+        when(growthRecordService.getRecordsByChild(CHILD_ID)).thenReturn(mockRecords);
+
+        // === When:家长通过新接口(请求体)请求历史记录 ===
+        Result<List<GrowthRecord>> result = growthRecordController.getRecordsByChild(CHILD_ID, null);
+
+        // === Then:返回历史记录列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(growthRecordService).getRecordsByChild(CHILD_ID);
+    }
+
+    @Test
+    @DisplayName("[场景5d] 查询孩子的成长记录历史(新接口,请求体,测试getRecordsByChild方法) - 期望返回记录列表")
+    void parentQueriesGrowthHistoryWithNewEndpoint_RequestBody_TestGetRecordsByChild_Success() {
+        // === Given:有多条成长记录 ===
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                createGrowthRecord(1L, CHILD_ID, "2026-06-01", "本学期表现优异"),
+                createGrowthRecord(2L, CHILD_ID, "2026-03-01", "体测达标"),
+                createGrowthRecord(3L, CHILD_ID, "2025-12-01", "学习进步明显")
+        );
+
+        when(growthRecordService.getRecordsByChild(CHILD_ID)).thenReturn(mockRecords);
+
+        // === When:家长通过新接口(请求体)请求历史记录 ===
+        Result<List<GrowthRecord>> result = growthRecordController.getRecordsByChild(CHILD_ID, null);
+
+        // === Then:返回历史记录列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(growthRecordService).getRecordsByChild(CHILD_ID);
+    }
+
+    @Test
+    @DisplayName("[场景5e] 查询孩子的成长记录历史(新接口,请求体,测试getRecordsByChild方法) - 期望返回记录列表")
+    void parentQueriesGrowthHistoryWithNewEndpoint_RequestBody_TestGetRecordsByChild_Success2() {
+        // === Given:有多条成长记录 ===
+        List<GrowthRecord> mockRecords = Arrays.asList(
+                createGrowthRecord(1L, CHILD_ID, "2026-06-01", "本学期表现优异"),
+                createGrowthRecord(2L, CHILD_ID, "2026-03-01", "体测达标"),
+                createGrowthRecord(3L, CHILD_ID, "2025-12-01", "学习进步明显")
+        );
+
+        when(growthRecordService.getRecordsByChild(CHILD_ID)).thenReturn(mockRecords);
+
+        // === When:家长通过新接口(请求体)请求历史记录 ===
+        Result<List<GrowthRecord>> result = growthRecordController.getRecordsByChild(CHILD_ID, null);
+
+        // === Then:返回历史记录列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(3, result.getData().size());
+        verify(growthRecordService).getRecordsByChild(CHILD_ID);
+    }
+
+    // ========== Helper Methods ==========
+
+    private GrowthRecord createGrowthRecord(Long id, Long memberId, String recordDate, String note) {
+        GrowthRecord record = new GrowthRecord();
+        record.setId(id);
+        record.setMemberId(memberId);
+        record.setRecordTitle(note);
+        return record;
+    }
+}

+ 172 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/GuideModuleIntegrationTest.java

@@ -0,0 +1,172 @@
+package com.etotem.cfc.integration;
+import javax.annotation.Resource;
+
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.service.*;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import com.etotem.cfc.dto.CreatePackageDTO;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * 成长规划师模块集成测试
+ * 覆盖场景:成长规划师创建任务模板 -> 家庭购买 -> 订单生成 -> 佣金计算
+ */
+@SpringBootTest
+public class GuideModuleIntegrationTest {
+
+    @Resource
+    private ServiceTypeService serviceTypeService;
+
+    @Resource
+    private ServiceContentService serviceContentService;
+
+    @Resource
+    private GuidePackageTemplateService templateService;
+
+    @Resource
+    private GuidePackageService guidePackageService;
+
+    @Resource
+    private TaskTemplatePackageService taskTemplatePackageService;
+
+    @Test
+    public void testGuidePackageCreationFlow() {
+        ServiceType serviceType = new ServiceType();
+        serviceType.setName("DAN测评");
+        serviceType.setIcon("📊");
+        serviceType.setDescription("DAN发展评估服务");
+        serviceType.setStatus("ACTIVE");
+        ServiceType createdType = serviceTypeService.createType(serviceType);
+        assertNotNull(createdType.getId());
+
+        ServiceContent serviceContent = new ServiceContent();
+        serviceContent.setTypeId(createdType.getId());
+        serviceContent.setTitle("1对1 DAN测评");
+        serviceContent.setContent("<h3>服务介绍</h3><p>全面评估孩子发展水平</p>");
+        serviceContent.setDuration(60);
+        serviceContent.setAgeRange("3-12岁");
+        serviceContent.setPrice(80000);
+        serviceContent.setStatus("ACTIVE");
+        ServiceContent createdContent = serviceContentService.createContent(serviceContent);
+        assertNotNull(createdContent.getId());
+
+        CreatePackageDTO dto = new CreatePackageDTO();
+        dto.setName("年度旗舰版");
+        dto.setPrice(198000);
+        dto.setDescription("全年度服务");
+        dto.setCycleDays(365);
+        TaskTemplatePackage createdTaskPackage = taskTemplatePackageService.createPackage(dto, 1L);
+        assertNotNull(createdTaskPackage.getId());
+
+        boolean saved = guidePackageService.addGuidePackage(
+            1L,
+            createdTaskPackage.getId(),
+            168000,
+            10
+        );
+        assertTrue(saved);
+
+        boolean duplicateSaved = guidePackageService.addGuidePackage(
+            1L,
+            createdTaskPackage.getId(),
+            168000,
+            10
+        );
+        assertFalse(duplicateSaved);
+    }
+
+    @Test
+    public void testServiceContentRichText() {
+        // 测试富文本内容存储和读取
+        String richText = "<h3>DAN测评服务</h3>" +
+                "<p>通过<strong>专业</strong>的评估体系,全面了解孩子的发展水平。</p>" +
+                "<ul>" +
+                "<li>注意力发展评估</li>" +
+                "<li>感统协调能力检测</li>" +
+                "<li>情绪管理能力分析</li>" +
+                "</ul>" +
+                "<img src='https://example.com/dan-assessment.jpg'/>" +
+                "<p><em>建议时长:60分钟 | 适用年龄:3-12岁</em></p>";
+
+        ServiceContent content = new ServiceContent();
+        content.setTypeId(1L);
+        content.setTitle("完整DAN测评");
+        content.setContent(richText);
+        content.setDuration(60);
+        content.setAgeRange("3-12岁");
+        content.setPrice(120000);
+        content.setStatus("ACTIVE");
+
+        ServiceContent created = serviceContentService.createContent(content);
+        assertNotNull(created.getId());
+
+        ServiceContent retrieved = serviceContentService.getById(created.getId());
+        assertEquals(richText, retrieved.getContent());
+
+        // 验证HTML标签完整性
+        assertTrue(retrieved.getContent().contains("<h3>"));
+        assertTrue(retrieved.getContent().contains("<strong>"));
+        assertTrue(retrieved.getContent().contains("<ul>"));
+        assertTrue(retrieved.getContent().contains("<img"));
+        System.out.println("富文本内容存储和读取测试通过");
+    }
+
+    @Test
+    public void testTemplatePriceValidation() {
+        // 测试任务模板模板价格逻辑
+        GuidePackageTemplate template = new GuidePackageTemplate();
+        template.setName("测试模板");
+        template.setValidityMonths(3);
+        template.setReferencePrice(58000);
+        template.setMinPrice(38000);
+        template.setStatus("ACTIVE");
+        templateService.createTemplate(template);
+
+        // 验证参考价 > 最低价
+        assertTrue(template.getReferencePrice() > template.getMinPrice());
+
+        // 验证成长规划师定价范围
+        int validPrice = 40000;
+        assertTrue(validPrice >= template.getMinPrice());
+        assertTrue(validPrice <= template.getReferencePrice());
+
+        int invalidPrice = 20000;
+        assertFalse(invalidPrice >= template.getMinPrice());
+        System.out.println("任务模板模板价格验证测试通过");
+    }
+
+    @Test
+    public void testServiceTypeContentRelation() {
+        // 测试服务类型和服务内容的关联关系
+        ServiceType type1 = new ServiceType();
+        type1.setName("咨询服务");
+        type1.setStatus("ACTIVE");
+        ServiceType createdType1 = serviceTypeService.createType(type1);
+
+        ServiceContent content1 = new ServiceContent();
+        content1.setTypeId(createdType1.getId());
+        content1.setTitle("电话咨询");
+        content1.setStatus("ACTIVE");
+        serviceContentService.createContent(content1);
+
+        ServiceContent content2 = new ServiceContent();
+        content2.setTypeId(createdType1.getId());
+        content2.setTitle("视频咨询");
+        content2.setStatus("ACTIVE");
+        serviceContentService.createContent(content2);
+
+        // 按类型查询
+        List<ServiceContent> contents = serviceContentService.getContentsByType(createdType1.getId());
+        assertEquals(2, contents.size());
+
+        for (ServiceContent c : contents) {
+            assertEquals(createdType1.getId(), c.getTypeId());
+        }
+        System.out.println("服务类型-服务内容关联测试通过");
+    }
+}

+ 400 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/PlannerBindInviteFlowTest.java

@@ -0,0 +1,400 @@
+package com.etotem.cfc.integration;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.family.BindController;
+import com.etotem.cfc.controller.family.BindInviteController;
+import com.etotem.cfc.dto.BindGuideDTO;
+import com.etotem.cfc.entity.GuideFamily;
+import com.etotem.cfc.service.BindInviteService;
+import com.etotem.cfc.service.GuideFamilyService;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.TeacherMessageService;
+import com.etotem.cfc.mapper.GuideFamilyMapper;
+import org.junit.jupiter.api.*;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * ================================================================
+ * 场景:规划师绑定邀请全流程
+ * ================================================================
+ * 用户故事:作为成长规划师,我希望邀请家长加入我的服务团队,
+ *           以便建立长期服务关系并管理我的客户家庭。
+ *
+ * 流程步骤:
+ *   1. 规划师登录系统,生成绑定邀请链接
+ *   2. 规划师将邀请链接发送给家长
+ *   3. 家长点击链接,查看邀请详情并确认
+ *   4. 家长授权绑定,成为规划师的客户
+ *   5. 规划师可在客户列表中看到新绑定的家庭
+ *
+ * 关键里程碑:
+ *   - [Milestone-1] 邀请链接生成成功,获得邀请凭证
+ *   - [Milestone-2] 邀请链接验证成功,展示邀请详情
+ *   - [Milestone-3] 家长确认绑定成功,与规划师建立关系
+ *   - [Milestone-4] 规划师客户列表更新,可以看到新家庭
+ *   - [Milestone-5] 解绑成功,关系终止
+ * ================================================================
+ */
+@SpringBootTest
+public class PlannerBindInviteFlowTest {
+
+    @Resource
+    private BindInviteController bindInviteController;
+
+    @Resource
+    private BindController bindController;
+
+    @MockBean
+    private BindInviteService bindInviteService;
+
+    @MockBean
+    private GuideFamilyService guideFamilyService;
+
+    @MockBean
+    private TeacherMessageService teacherMessageService;
+
+    @MockBean
+    private GuideFamilyMapper guideFamilyMapper;
+
+    @MockBean
+    private MembershipService membershipService;
+
+    /** 规划师认证闸门(R4+D6 新增):默认放行,聚焦绑定链路本身 */
+    @MockBean
+    private com.etotem.cfc.service.PlannerCertificationGuard plannerCertificationGuard;
+
+    @BeforeEach
+    void allowCertifiedGuide() {
+        when(plannerCertificationGuard.assertCertified(anyLong(), anyString(), anyBoolean())).thenReturn(null);
+    }
+
+    // ========== 测试数据 ==========
+
+    private static final Long GUIDE_USER_ID = 4001L;
+    private static final Long PARENT_USER_ID = 1001L;
+    private static final Long FAMILY_ID = 3001L;
+    private static final String INVITE_TOKEN = "invite_abc123xyz";
+    private static final Long BINDING_ID = 1L;
+
+    // ========== 场景1:规划师生成邀请 ==========
+
+    /**
+     * 场景:规划师登录后生成一个绑定邀请
+     * 角色:成长规划师
+     * 触发条件:规划师点击"邀请家长"按钮
+     */
+    @Test
+    @DisplayName("[场景1] 规划师生成邀请链接 - 期望返回邀请凭证")
+    void guideGeneratesInvite_Success() {
+        // === Given:规划师请求生成邀请 ===
+        Map<String, Object> mockResult = new HashMap<>();
+        mockResult.put("token", INVITE_TOKEN);
+        mockResult.put("expireTime", "2026-07-15 23:59:59");
+        mockResult.put("guideName", "张规划师");
+        mockResult.put("guideAvatar", "https://example.com/avatar.jpg");
+
+        when(bindInviteService.generateInvite(GUIDE_USER_ID)).thenReturn(mockResult);
+
+        // === When:规划师点击生成邀请 ===
+        Result<Map<String, Object>> result = bindInviteController.generateInvite(GUIDE_USER_ID);
+
+        // === Then:Milestone-1 - 邀请生成成功 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(INVITE_TOKEN, result.getData().get("token"));
+        assertNotNull(result.getData().get("expireTime"));
+        verify(bindInviteService).generateInvite(GUIDE_USER_ID);
+    }
+
+    // ========== 场景2:家长验证邀请 ==========
+
+    /**
+     * 场景:家长点击邀请链接,系统验证邀请有效性
+     * 角色:家长
+     * 触发条件:家长打开邀请链接
+     */
+    @Test
+    @DisplayName("[场景2] 家长验证邀请链接 - 期望展示邀请详情")
+    void parentValidatesInvite_Success() {
+        // === Given:邀请链接有效 ===
+        Map<String, Object> params = new HashMap<>();
+        params.put("token", INVITE_TOKEN);
+
+        Map<String, Object> mockValidation = new HashMap<>();
+        mockValidation.put("valid", true);
+        mockValidation.put("guideId", GUIDE_USER_ID);
+        mockValidation.put("guideName", "张规划师");
+        mockValidation.put("guideAvatar", "https://example.com/avatar.jpg");
+        mockValidation.put("serviceTypes", Arrays.asList("学业规划", "心理辅导", "综合发展"));
+        mockValidation.put("expireTime", "2026-07-15 23:59:59");
+
+        when(bindInviteService.validateToken(INVITE_TOKEN)).thenReturn(mockValidation);
+
+        // === When:家长打开邀请链接 ===
+        Result<Map<String, Object>> result = bindInviteController.validateToken(params);
+
+        // === Then:Milestone-2 - 邀请验证成功,展示详情 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(true, result.getData().get("valid"));
+        assertEquals(GUIDE_USER_ID, result.getData().get("guideId"));
+        assertEquals("张规划师", result.getData().get("guideName"));
+        verify(bindInviteService).validateToken(INVITE_TOKEN);
+    }
+
+    /**
+     * 场景:家长使用过期或无效的邀请链接
+     * 角色:家长
+     * 触发条件:链接已过期或不存在
+     */
+    @Test
+    @DisplayName("[场景2b] 使用无效邀请链接 - 期望返回错误提示")
+    void parentValidatesInvalidInvite_Fails() {
+        // === Given:邀请链接无效 ===
+        Map<String, Object> params = new HashMap<>();
+        params.put("token", "invalid_token_123");
+
+        Map<String, Object> mockValidation = new HashMap<>();
+        mockValidation.put("valid", false);
+        mockValidation.put("error", "邀请链接已过期或不存在");
+
+        when(bindInviteService.validateToken("invalid_token_123")).thenReturn(mockValidation);
+
+        // === When:家长尝试使用无效链接 ===
+        Result<Map<String, Object>> result = bindInviteController.validateToken(params);
+
+        // === Then:返回错误信息 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(false, result.getData().get("valid"));
+        assertNotNull(result.getData().get("error"));
+    }
+
+    // ========== 场景3:家长确认绑定 ==========
+
+    /**
+     * 场景:家长查看邀请详情后,确认绑定该规划师
+     * 角色:家长
+     * 触发条件:家长点击"确认绑定"按钮
+     */
+    @Test
+    @DisplayName("[场景3] 家长确认绑定规划师 - 期望绑定成功")
+    void parentConfirmsBind_Success() {
+        // === Given:家长确认绑定规划师 ===
+        BindGuideDTO bindDTO = new BindGuideDTO();
+        bindDTO.setGuideId(GUIDE_USER_ID);
+        bindDTO.setServiceType("学业规划");
+        bindDTO.setServicePrice(29900);
+
+        when(guideFamilyService.confirmBind(eq(GUIDE_USER_ID), eq(FAMILY_ID), eq("学业规划"), eq(29900)))
+                .thenReturn(true);
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+
+        // === When:家长点击"确认绑定" ===
+        Result<Boolean> result = bindController.acceptBind(
+                PARENT_USER_ID, bindDTO);
+
+        // === Then:Milestone-3 - 绑定成功 ===
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData());
+        verify(guideFamilyService).confirmBind(eq(GUIDE_USER_ID), eq(FAMILY_ID), eq("学业规划"), eq(29900));
+    }
+
+    /**
+     * 场景:家长尝试重复绑定同一个规划师
+     * 角色:家长
+     * 触发条件:已经绑定过该规划师,再次确认绑定
+     */
+    @Test
+    @DisplayName("[场景3b] 重复绑定同一规划师 - 期望返回错误提示")
+    void parentBindsSameGuideTwice_Fails() {
+        // === Given:已经绑定过该规划师 ===
+        BindGuideDTO bindDTO = new BindGuideDTO();
+        bindDTO.setGuideId(GUIDE_USER_ID);
+        bindDTO.setServiceType("学业规划");
+
+        // 注意:servicePrice 未设置时为 null,用 anyInt() 不匹配 null → 桩不生效、默认 false 假通过
+        // (A 类用例缺陷:应使用 any() 以覆盖 null 实参)
+        when(guideFamilyService.confirmBind(eq(GUIDE_USER_ID), eq(FAMILY_ID), anyString(), any()))
+                .thenThrow(new RuntimeException("该规划师已在服务中,无需重复绑定"));
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+
+        // === When:家长尝试再次绑定 ===
+        Result<Boolean> result = bindController.acceptBind(
+                PARENT_USER_ID, bindDTO);
+
+        // === Then:返回错误提示 ===
+        assertEquals(400, result.getCode());
+        assertTrue(result.getMessage().contains("已在服务中") || result.getMessage().contains("重复"));
+    }
+
+    // ========== 场景4:查看绑定规划师列表 ==========
+
+    /**
+     * 场景:家长查看已绑定的规划师列表
+     * 角色:家长
+     * 触发条件:家长进入"我的规划师"页面
+     */
+    @Test
+    @DisplayName("[场景4] 家长查看绑定规划师列表 - 期望返回已绑定的规划师")
+    void parentViewsBoundGuides_Success() {
+        // === Given:家庭已绑定多个规划师 ===
+        List<GuideFamily> mockBindings = Arrays.asList(
+                createGuideFamily(1L, GUIDE_USER_ID, "学业规划", 29900, "active"),
+                createGuideFamily(2L, 4002L, "心理辅导", 19900, "active")
+        );
+
+        when(guideFamilyService.getGuidesByFamily(FAMILY_ID)).thenReturn(mockBindings);
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+
+        // === When:家长请求规划师列表 ===
+        Result<List<Map<String, Object>>> result = bindController.getBoundGuides(PARENT_USER_ID);
+
+        // === Then:Milestone-4 - 返回已绑定规划师列表 ===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(2, result.getData().size());
+        verify(guideFamilyService).getGuidesByFamily(FAMILY_ID);
+    }
+
+    // ========== 场景5:家长解除绑定 ==========
+
+    /**
+     * 场景:家长决定解除与某个规划师的绑定关系
+     * 角色:家长
+     * 触发条件:家长在规划师详情页点击"解除绑定"
+     */
+    @Test
+    @DisplayName("[场景5] 家长解除绑定规划师 - 期望解除成功并发送通知")
+    void parentUnbindsGuide_Success() {
+        // === Given:家长请求解除绑定 ===
+        Map<String, Object> unbindRequest = new HashMap<>();
+        unbindRequest.put("id", BINDING_ID);
+
+        GuideFamily unbindGuide = createGuideFamily(BINDING_ID, GUIDE_USER_ID, "学业规划", 29900, "unbound");
+        when(guideFamilyService.unbindAndGet(eq(BINDING_ID), eq(FAMILY_ID))).thenReturn(unbindGuide);
+        when(teacherMessageService.sendMessage(eq(FAMILY_ID), eq(PARENT_USER_ID), eq(GUIDE_USER_ID), anyString())).thenReturn(1L);
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+
+        // === When:家长确认解除绑定 ===
+        Result<Boolean> result = bindController.unbind(
+                PARENT_USER_ID, unbindRequest);
+
+        // === Then:Milestone-5 - 解绑成功并通知规划师 ===
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData());
+        verify(guideFamilyService).unbindAndGet(eq(BINDING_ID), eq(FAMILY_ID));
+        verify(teacherMessageService).sendMessage(eq(FAMILY_ID), eq(PARENT_USER_ID), eq(GUIDE_USER_ID), anyString());
+    }
+
+    // ========== 场景6:规划师查看已绑定的家庭 ==========
+
+    /**
+     * 场景:规划师查看已绑定的家庭列表
+     * 角色:成长规划师
+     * 触发条件:规划师进入"我的客户"页面
+     */
+    @Test
+    @DisplayName("[场景6] 规划师查看绑定家庭列表 - 期望返回所有客户家庭")
+    void guideViewsBoundFamilies_Success() {
+        // === Given:规划师有多个绑定家庭 ===
+        List<GuideFamily> mockBindings = Arrays.asList(
+                createGuideFamily(1L, GUIDE_USER_ID, "active", FAMILY_ID, 1001L),
+                createGuideFamily(2L, GUIDE_USER_ID, "active", 3002L, 1002L)
+        );
+
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+        when(guideFamilyService.getGuidesByFamily(FAMILY_ID)).thenReturn(mockBindings);
+
+        // === When:家庭侧请求已绑定规划师列表(BindController#getBoundGuides)===
+        Result<List<Map<String, Object>>> result = bindController.getBoundGuides(PARENT_USER_ID);
+
+        // === Then:返回所有已绑定规划师(原用例为占位 assertNotNull(null),属空壳用例)===
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals(2, result.getData().size());
+        verify(guideFamilyService).getGuidesByFamily(FAMILY_ID);
+    }
+
+    // ========== 场景7:完整绑定流程(端到端)============
+
+    /**
+     * 场景:规划师邀请 → 家长验证 → 家长确认绑定的完整流程
+     * 角色:规划师 → 家长
+     * 触发条件:完整的邀请绑定流程
+     */
+    @Test
+    @DisplayName("[场景7] 完整邀请绑定流程 - 期望全流程成功")
+    void completeInviteBindFlow_Success() {
+        // === Step 1:规划师生成邀请 ===
+        Map<String, Object> inviteResult = new HashMap<>();
+        inviteResult.put("token", INVITE_TOKEN);
+        inviteResult.put("expireTime", "2026-07-15 23:59:59");
+
+        when(bindInviteService.generateInvite(GUIDE_USER_ID)).thenReturn(inviteResult);
+
+        Result<Map<String, Object>> step1 = bindInviteController.generateInvite(GUIDE_USER_ID);
+        assertEquals(200, step1.getCode());
+        assertEquals(INVITE_TOKEN, step1.getData().get("token"));
+
+        // === Step 2:家长验证邀请 ===
+        Map<String, Object> validateParams = new HashMap<>();
+        validateParams.put("token", INVITE_TOKEN);
+
+        Map<String, Object> validationResult = new HashMap<>();
+        validationResult.put("valid", true);
+        validationResult.put("guideId", GUIDE_USER_ID);
+        validationResult.put("guideName", "张规划师");
+
+        when(bindInviteService.validateToken(INVITE_TOKEN)).thenReturn(validationResult);
+
+        Result<Map<String, Object>> step2 = bindInviteController.validateToken(validateParams);
+        assertEquals(200, step2.getCode());
+        assertEquals(true, step2.getData().get("valid"));
+
+        // === Step 3:家长确认绑定 ===
+        BindGuideDTO bindDTO = new BindGuideDTO();
+        bindDTO.setGuideId(GUIDE_USER_ID);
+        bindDTO.setServiceType("学业规划");
+        bindDTO.setServicePrice(29900);
+
+        when(guideFamilyService.confirmBind(eq(GUIDE_USER_ID), eq(FAMILY_ID), eq("学业规划"), eq(29900)))
+                .thenReturn(true);
+        when(membershipService.getUserFamilyId(PARENT_USER_ID)).thenReturn(FAMILY_ID);
+
+        Result<Boolean> step3 = bindController.acceptBind(PARENT_USER_ID, bindDTO);
+        assertEquals(200, step3.getCode());
+        assertTrue(step3.getData());
+    }
+
+    // ========== Helper Methods ==========
+
+    private GuideFamily createGuideFamily(Long id, Long guideId, String serviceType, Integer servicePrice, String status) {
+        GuideFamily gf = new GuideFamily();
+        gf.setId(id);
+        gf.setGuideId(guideId);
+        gf.setServiceType(serviceType);
+        gf.setServicePrice(servicePrice);
+        gf.setStatus(status);
+        gf.setBoundAt(new Date());
+        return gf;
+    }
+
+    private GuideFamily createGuideFamily(Long id, Long guideId, String status, Long familyId, Long userId) {
+        GuideFamily gf = new GuideFamily();
+        gf.setId(id);
+        gf.setGuideId(guideId);
+        gf.setFamilyId(familyId);
+        gf.setStatus(status);
+        gf.setBoundAt(new Date());
+        return gf;
+    }
+}

+ 383 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/controller/AIChatControllerTest.java

@@ -0,0 +1,383 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.ai.AIChatController;
+import com.etotem.cfc.dto.AiGateResult;
+import com.etotem.cfc.enums.AiGateStatus;
+import com.etotem.cfc.service.AIService;
+import com.etotem.cfc.service.FamilyContextService;
+import com.etotem.cfc.service.HealthAnalysisService;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.RecommendationService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * P2-AI测试:AI聊天发送/会话列表/消息历史/精准营养/推荐卡片
+ * 覆盖 AIChatController
+ */
+@SpringBootTest
+public class AIChatControllerTest {
+
+    @Resource
+    private AIChatController controller;
+
+    @MockBean
+    private AIService aiService;
+
+    @MockBean
+    private FamilyContextService familyContextService;
+
+    @MockBean
+    private HealthAnalysisService healthAnalysisService;
+
+    @MockBean
+    private RecommendationService recommendationService;
+
+    /**
+     * AI 使用会员门禁(任务书 2026-11-02-ai-member-gate-design):/chat/send 已加显式门禁,
+     * 本集成测试聚焦会话组装/返回结构,统一 mock 为有效会员放行。
+     */
+    @MockBean
+    private MembershipService membershipService;
+
+    @BeforeEach
+    public void allowAiGate() {
+        AiGateResult allow = new AiGateResult();
+        allow.setEnabled(true);
+        allow.setStatus(AiGateStatus.ALLOW);
+        allow.setCanUse(true);
+        allow.setCanViewHistory(true);
+        allow.setMemberLevel("FAMILY");
+        allow.setIsActive(true);
+        allow.setDaysRemaining(30L);
+        when(membershipService.checkAiFeatureGate(anyLong())).thenReturn(allow);
+    }
+
+    // ===== 发送聊天消息 =====
+
+    @Test
+    public void sendMessage_Success() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "孩子注意力不集中怎么办");
+        params.put("conversationId", "conv001");
+
+        Map<String, Object> mockDifyResp = new HashMap<>();
+        mockDifyResp.put("answer", "建议通过舒尔特方格训练注意力...");
+        mockDifyResp.put("conversationId", "conv001");
+
+        when(familyContextService.buildContext(eq(1L)))
+                .thenReturn(new HashMap<>());
+        when(aiService.sendMessage(eq("孩子注意力不集中怎么办"), eq("1"), eq("conv001"), anyMap()))
+                .thenReturn(mockDifyResp);
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+        assertEquals("建议通过舒尔特方格训练注意力...", result.getData().get("answer"));
+        assertEquals("conv001", result.getData().get("conversationId"));
+    }
+
+    @Test
+    public void sendMessage_EmptyQuery() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "");
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(500, result.getCode());
+        assertEquals("消息不能为空", result.getMessage());
+    }
+
+    @Test
+    public void sendMessage_NullQuery() {
+        Map<String, String> params = new HashMap<>();
+        // query not provided
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(500, result.getCode());
+        assertEquals("消息不能为空", result.getMessage());
+    }
+
+    @Test
+    public void sendMessage_WithReportContext() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "分析这份体检报告");
+        params.put("reportId", "5");
+
+        Map<String, Object> mockDifyResp = new HashMap<>();
+        mockDifyResp.put("answer", "从报告来看,孩子铁元素偏低,建议...");
+        mockDifyResp.put("conversationId", "conv002");
+
+        when(familyContextService.buildContext(eq(1L), eq(5L)))
+                .thenReturn(new HashMap<String, Object>() {{
+                    put("reportId", 5L);
+                    put("gutHealthScore", 78);
+                }});
+        when(aiService.sendMessage(anyString(), eq("1"), isNull(), anyMap()))
+                .thenReturn(mockDifyResp);
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertTrue(((String) result.getData().get("answer")).contains("铁元素"));
+    }
+
+    @Test
+    public void sendMessage_WithReportAndSurveyContext() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "综合分析");
+        params.put("reportId", "5");
+        params.put("surveyId", "3");
+
+        Map<String, Object> mockDifyResp = new HashMap<>();
+        mockDifyResp.put("answer", "综合分析结果...");
+        mockDifyResp.put("conversationId", "conv003");
+
+        when(familyContextService.buildContext(eq(1L), eq(5L), eq(3L)))
+                .thenReturn(new HashMap<>());
+        when(aiService.sendMessage(anyString(), eq("1"), isNull(), anyMap()))
+                .thenReturn(mockDifyResp);
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData().get("answer"));
+    }
+
+    @Test
+    public void sendMessage_NullConversationId_CreatesNew() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "你好");
+        // conversationId not provided
+
+        Map<String, Object> mockDifyResp = new HashMap<>();
+        mockDifyResp.put("answer", "你好!有什么可以帮你的?");
+        mockDifyResp.put("conversationId", "new_conv_123");
+
+        when(familyContextService.buildContext(eq(1L)))
+                .thenReturn(new HashMap<>());
+        when(aiService.sendMessage(eq("你好"), eq("1"), isNull(), anyMap()))
+                .thenReturn(mockDifyResp);
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertEquals("new_conv_123", result.getData().get("conversationId"));
+    }
+
+    @Test
+    public void sendMessage_PrecisionNutritionMode() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "今天的营养建议");
+        params.put("conversationId", "nutrition001");
+
+        Map<String, Object> mockDifyResp = new HashMap<>();
+        mockDifyResp.put("answer", "今日精准营养建议:增加膳食纤维摄入...");
+        mockDifyResp.put("conversationId", "nutrition001");
+
+        when(familyContextService.buildContext(eq(1L)))
+                .thenReturn(new HashMap<String, Object>() {{
+                    put("mode", "precision_nutrition");
+                }});
+        when(aiService.sendMessage(anyString(), eq("1"), eq("nutrition001"), anyMap()))
+                .thenReturn(mockDifyResp);
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertTrue(((String) result.getData().get("answer")).contains("营养"));
+    }
+
+    // ===== 获取会话列表 =====
+
+    @Test
+    public void getConversations_Success() {
+        List<Map<String, Object>> mockConversations = Arrays.asList(
+                new LinkedHashMap<String, Object>() {{
+                    put("conversationId", "conv001");
+                    put("title", "注意力训练");
+                    put("lastMessage", "建议通过舒尔特方格...");
+                    put("updatedAt", "2026-06-22 10:00:00");
+                }},
+                new LinkedHashMap<String, Object>() {{
+                    put("conversationId", "conv002");
+                    put("title", "营养建议");
+                    put("lastMessage", "增加膳食纤维...");
+                    put("updatedAt", "2026-06-21 15:30:00");
+                }}
+        );
+
+        when(aiService.getConversations("1")).thenReturn(mockConversations);
+
+        Result<List<Map<String, Object>>> result = controller.getConversations(1L);
+
+        assertEquals(200, result.getCode());
+        assertEquals(2, result.getData().size());
+    }
+
+    @Test
+    public void getConversations_Empty() {
+        when(aiService.getConversations("1")).thenReturn(Collections.emptyList());
+
+        Result<List<Map<String, Object>>> result = controller.getConversations(1L);
+
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData().isEmpty());
+    }
+
+    @Test
+    public void getConversations_MultiplePages() {
+        List<Map<String, Object>> mockConversations = new ArrayList<>();
+        for (int i = 1; i <= 20; i++) {
+            Map<String, Object> conv = new HashMap<>();
+            conv.put("conversationId", "conv" + i);
+            conv.put("title", "会话" + i);
+            mockConversations.add(conv);
+        }
+
+        when(aiService.getConversations("1")).thenReturn(mockConversations);
+
+        Result<List<Map<String, Object>>> result = controller.getConversations(1L);
+
+        assertEquals(200, result.getCode());
+        assertEquals(20, result.getData().size());
+    }
+
+    // ===== 获取消息历史 =====
+
+    @Test
+    public void getMessages_Success() {
+        Map<String, String> params = new HashMap<>();
+        params.put("conversationId", "conv001");
+
+        List<Map<String, Object>> mockMessages = Arrays.asList(
+                new LinkedHashMap<String, Object>() {{
+                    put("id", 1L);
+                    put("role", "user");
+                    put("content", "孩子注意力不集中");
+                    put("createdAt", "2026-06-22 09:00:00");
+                }},
+                new LinkedHashMap<String, Object>() {{
+                    put("id", 2L);
+                    put("role", "assistant");
+                    put("content", "建议通过舒尔特方格训练...");
+                    put("createdAt", "2026-06-22 09:01:00");
+                }}
+        );
+
+        when(aiService.getMessages("conv001", "1")).thenReturn(mockMessages);
+
+        Result<List<Map<String, Object>>> result = controller.getMessages(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertEquals(2, result.getData().size());
+        assertEquals("user", result.getData().get(0).get("role"));
+        assertEquals("assistant", result.getData().get(1).get("role"));
+    }
+
+    @Test
+    public void getMessages_NullConversationId() {
+        Map<String, String> params = new HashMap<>();
+        // conversationId not provided
+
+        Result<List<Map<String, Object>>> result = controller.getMessages(1L, params);
+
+        assertEquals(500, result.getCode());
+        assertEquals("conversationId 不能为空", result.getMessage());
+    }
+
+    @Test
+    public void getMessages_EmptyHistory() {
+        Map<String, String> params = new HashMap<>();
+        params.put("conversationId", "conv999");
+
+        when(aiService.getMessages("1", "conv999")).thenReturn(Collections.emptyList());
+
+        Result<List<Map<String, Object>>> result = controller.getMessages(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertTrue(result.getData().isEmpty());
+    }
+
+    @Test
+    public void getMessages_VerifyRoleAlternation() {
+        Map<String, String> params = new HashMap<>();
+        params.put("conversationId", "conv001");
+
+        List<Map<String, Object>> mockMessages = Arrays.asList(
+                new LinkedHashMap<String, Object>() {{ put("role", "user"); put("content", "Q1"); }},
+                new LinkedHashMap<String, Object>() {{ put("role", "assistant"); put("content", "A1"); }},
+                new LinkedHashMap<String, Object>() {{ put("role", "user"); put("content", "Q2"); }},
+                new LinkedHashMap<String, Object>() {{ put("role", "assistant"); put("content", "A2"); }}
+        );
+
+        when(aiService.getMessages("conv001", "1")).thenReturn(mockMessages);
+
+        Result<List<Map<String, Object>>> result = controller.getMessages(1L, params);
+
+        assertEquals(200, result.getCode());
+        assertEquals(4, result.getData().size());
+    }
+
+    // ===== 边界情况 =====
+
+    @Test
+    public void sendMessage_WhitespaceOnlyQuery() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "   ");
+
+        Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+
+        assertEquals(500, result.getCode());
+    }
+
+    @Test
+    public void sendMessage_DifyServiceDown() {
+        Map<String, String> params = new HashMap<>();
+        params.put("query", "测试");
+        params.put("conversationId", "conv001");
+
+        when(familyContextService.buildContext(eq(1L)))
+                .thenReturn(new HashMap<>());
+        when(aiService.sendMessage(anyString(), anyString(), anyString(), anyMap()))
+                .thenThrow(new RuntimeException("Dify服务不可用"));
+
+        // Should not throw, controller should handle gracefully
+        try {
+            Result<Map<String, Object>> result = controller.sendMessage(1L, params);
+            // Either error response or exception handled
+            assert result.getCode() == 500 || result.getCode() == 200;
+        } catch (Exception e) {
+            // Expected in some error handling patterns
+        }
+    }
+
+    @Test
+    public void getConversations_MalformedData() {
+        List<Map<String, Object>> mockConversations = Arrays.asList(
+                new HashMap<String, Object>() {{
+                    put("conversationId", "conv_bad");
+                    // missing title and lastMessage
+                }}
+        );
+
+        when(aiService.getConversations("1")).thenReturn(mockConversations);
+
+        Result<List<Map<String, Object>>> result = controller.getConversations(1L);
+
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData().get(0).get("conversationId"));
+    }
+}

+ 346 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/controller/ActivityControllerTest.java

@@ -0,0 +1,346 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.ActivityController;
+import com.etotem.cfc.dto.ActivityDTO;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.service.ActivityService;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * 活动管理员 (activity_provider) API 测试
+ *
+ * 角色说明: vendorType = 'activity_provider' 的服务商角色
+ * 可创建/管理五维活动(body/mind/wisdom/action/wealth)
+ *
+ * 核心端点: POST /api/activity/*
+ */
+@SpringBootTest
+public class ActivityControllerTest {
+
+    @Resource
+    private ActivityController controller;
+
+    @MockBean
+    private ActivityService activityService;
+
+    // ==================== mock helpers ====================
+
+    private Activity mockActivity(Long id, String title, String status, String dimensionCode) {
+        Activity a = new Activity();
+        a.setId(id);
+        a.setTitle(title);
+        a.setDescription("活动描述");
+        a.setCoverImage("http://example.com/cover.jpg");
+        a.setDimensionCode(dimensionCode); // body/mind/wisdom/action/wealth
+        a.setActivityType("offline");      // offline/online/campaign
+        a.setStatus(status);               // draft/published/ended
+        a.setMaxParticipants(50);
+        a.setCurrentParticipants(0);
+        a.setVendorId(1L);
+        return a;
+    }
+
+    private ActivityDTO mockDTO(Activity a) {
+        return ActivityDTO.from(a);
+    }
+
+    // ==================== list ====================
+
+    @Test
+    public void list_AllPublished() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("page", 1);
+        params.put("size", 10);
+
+        List<Activity> records = Arrays.asList(
+            mockActivity(1L, "户外徒步", "published", "action"),
+            mockActivity(2L, "营养讲座", "published", "body")
+        );
+        Page<Activity> page = new Page<>(1, 10, 2);
+        page.setRecords(records);
+
+        when(activityService.list(isNull(), eq(1), eq(10), isNull()))
+            .thenReturn(new com.etotem.cfc.common.Result<Map<String, Object>>() {{
+                Map<String, Object> data = new HashMap<>();
+                data.put("records", records.stream().map(ActivityDTO::from).collect(Collectors.toList()));
+                data.put("total", 2L);
+                data.put("page", 1);
+                data.put("size", 10);
+                setData(data);
+                setCode(200);
+            }});
+
+        Result<Map<String, Object>> result = controller.list(params, null);
+        assertEquals(200, result.getCode());
+        assertNotNull(result.getData());
+    }
+
+    @Test
+    public void list_FilterByDimension() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("dimensionCode", "body");
+        params.put("page", 1);
+        params.put("size", 10);
+
+        List<Activity> records = Collections.singletonList(
+            mockActivity(3L, "体质检测", "published", "body")
+        );
+
+        when(activityService.list(eq("body"), eq(1), eq(10), isNull()))
+            .thenReturn(new com.etotem.cfc.common.Result<Map<String, Object>>() {{
+                Map<String, Object> data = new HashMap<>();
+                data.put("records", records.stream().map(ActivityDTO::from).collect(Collectors.toList()));
+                data.put("total", 1L);
+                data.put("page", 1);
+                data.put("size", 10);
+                setData(data);
+                setCode(200);
+            }});
+
+        Result<Map<String, Object>> result = controller.list(params, null);
+        assertEquals(200, result.getCode());
+    }
+
+    @Test
+    public void list_FilterByStatus() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("status", "ended");
+        params.put("page", 1);
+        params.put("size", 10);
+
+        when(activityService.list(isNull(), eq(1), eq(10), isNull()))
+            .thenReturn(new com.etotem.cfc.common.Result<Map<String, Object>>() {{
+                Map<String, Object> data = new HashMap<>();
+                data.put("records", Collections.emptyList());
+                data.put("total", 0L);
+                data.put("page", 1);
+                data.put("size", 10);
+                setData(data);
+                setCode(200);
+            }});
+
+        Result<Map<String, Object>> result = controller.list(params, null);
+        assertEquals(200, result.getCode());
+        assertEquals(0, ((List<?>)result.getData().get("records")).size());
+    }
+
+    @Test
+    public void list_WithVendorId() {
+        Map<String, Object> params = new HashMap<>();
+        params.put("page", 1);
+        params.put("size", 10);
+        params.put("mine", true);
+
+        // 登录用户可看到自己的私有活动(管理员视角:mine=true 时按发布者过滤)
+        List<Activity> records = Collections.singletonList(
+            mockActivity(5L, "内部活动", "draft", "mind")
+        );
+
+        when(activityService.list(isNull(), eq(1), eq(10), eq(99L)))
+            .thenReturn(new com.etotem.cfc.common.Result<Map<String, Object>>() {{
+                Map<String, Object> data = new HashMap<>();
+                data.put("records", records.stream().map(ActivityDTO::from).collect(Collectors.toList()));
+                data.put("total", 1L);
+                data.put("page", 1);
+                data.put("size", 10);
+                setData(data);
+                setCode(200);
+            }});
+
+        Result<Map<String, Object>> result = controller.list(params, 99L);
+        assertEquals(200, result.getCode());
+        assertEquals(1, ((List<?>)result.getData().get("records")).size());
+    }
+
+    // ==================== detail ====================
+
+    @Test
+    public void detail_Exists() {
+        Activity activity = mockActivity(1L, "户外徒步", "published", "action");
+
+        when(activityService.detail(1L, null))
+            .thenReturn(new com.etotem.cfc.common.Result<ActivityDTO>() {{
+                setData(ActivityDTO.from(activity));
+                setCode(200);
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 1);
+
+        Result<ActivityDTO> result = controller.detail(params, null);
+        assertEquals(200, result.getCode());
+        assertEquals("户外徒步", result.getData().getTitle());
+    }
+
+    @Test
+    public void detail_NotFound() {
+        when(activityService.detail(999L, null))
+            .thenReturn(new com.etotem.cfc.common.Result<ActivityDTO>() {{
+                setData(null);
+                setCode(500);
+                setMessage("活动不存在");
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 999);
+
+        Result<ActivityDTO> result = controller.detail(params, null);
+        assertEquals(500, result.getCode());
+    }
+
+    @Test
+    public void detail_MissingId() {
+        Map<String, Object> params = new HashMap<>(); // no id
+        Result<ActivityDTO> result = controller.detail(params, null);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("不能为空"));
+    }
+
+    // ==================== create ====================
+
+    @Test
+    public void create_AsVendor() {
+        Activity activity = mockActivity(null, "新年联欢", "draft", "action");
+        activity.setVendorId(null); // will be set by controller
+
+        when(activityService.create(any(Activity.class), eq(5L)))
+            .thenReturn(new com.etotem.cfc.common.Result<ActivityDTO>() {{
+                activity.setId(10L);
+                setData(ActivityDTO.from(activity));
+                setCode(200);
+            }});
+
+        Result<ActivityDTO> result = controller.create(activity, 5L, "admin", null);
+        assertEquals(200, result.getCode());
+        assertEquals(5L, activity.getVendorId()); // vendorId set from userId
+        assertNotNull(result.getData().getId());
+    }
+
+    @Test
+    public void create_GuestNoVendorId() {
+        Activity activity = mockActivity(null, "公开活动", "draft", "body");
+        activity.setVendorId(null); // 游客创建时不应有 vendorId
+
+        when(activityService.create(any(Activity.class), isNull()))
+            .thenReturn(new com.etotem.cfc.common.Result<ActivityDTO>() {{
+                activity.setId(11L);
+                setData(ActivityDTO.from(activity));
+                setCode(200);
+            }});
+
+        Result<ActivityDTO> result = controller.create(activity, null, "admin", null);
+        assertEquals(200, result.getCode());
+        assertNull(activity.getVendorId());
+    }
+
+    // ==================== update ====================
+
+    @Test
+    public void update_Success() {
+        Activity activity = mockActivity(1L, "更新后的活动", "published", "body");
+
+        when(activityService.update(any(Activity.class)))
+            .thenReturn(new com.etotem.cfc.common.Result<ActivityDTO>() {{
+                setData(ActivityDTO.from(activity));
+                setCode(200);
+            }});
+
+        Result<ActivityDTO> result = controller.update(activity, null, "admin", null);
+        assertEquals(200, result.getCode());
+        assertEquals("更新后的活动", result.getData().getTitle());
+    }
+
+    // ==================== publish ====================
+
+    @Test
+    public void publish_Success() {
+        when(activityService.publish(1L))
+            .thenReturn(new com.etotem.cfc.common.Result<String>() {{
+                setData("发布成功");
+                setCode(200);
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 1);
+
+        Result<String> result = controller.publish(params, "admin", null);
+        assertEquals(200, result.getCode());
+        assertEquals("发布成功", result.getData());
+    }
+
+    @Test
+    public void publish_NotFound() {
+        when(activityService.publish(999L))
+            .thenReturn(new com.etotem.cfc.common.Result<String>() {{
+                setData(null);
+                setCode(500);
+                setMessage("活动不存在");
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 999);
+
+        Result<String> result = controller.publish(params, "admin", null);
+        assertEquals(500, result.getCode());
+    }
+
+    @Test
+    public void publish_MissingId() {
+        Map<String, Object> params = new HashMap<>();
+        Result<String> result = controller.publish(params, "admin", null);
+        assertEquals(500, result.getCode());
+        assertTrue(result.getMessage().contains("不能为空"));
+    }
+
+    // ==================== end ====================
+
+    @Test
+    public void end_Success() {
+        when(activityService.end(1L))
+            .thenReturn(new com.etotem.cfc.common.Result<String>() {{
+                setData("结束成功");
+                setCode(200);
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 1);
+
+        Result<String> result = controller.end(params, null, "admin", null);
+        assertEquals(200, result.getCode());
+    }
+
+    @Test
+    public void end_NotFound() {
+        when(activityService.end(999L))
+            .thenReturn(new com.etotem.cfc.common.Result<String>() {{
+                setData(null);
+                setCode(500);
+                setMessage("活动不存在");
+            }});
+
+        Map<String, Object> params = new HashMap<>();
+        params.put("id", 999);
+
+        Result<String> result = controller.end(params, null, "admin", null);
+        assertEquals(500, result.getCode());
+    }
+
+    @Test
+    public void end_MissingId() {
+        Map<String, Object> params = new HashMap<>();
+        Result<String> result = controller.end(params, null, "admin", null);
+        assertEquals(500, result.getCode());
+    }
+}

+ 45 - 0
cfc-backend/src/test/java/com/etotem/cfc/integration/controller/AdminFamilyOverviewControllerTest.java

@@ -0,0 +1,45 @@
+package com.etotem.cfc.integration.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.admin.AdminFamilyOverviewController;
+import com.etotem.cfc.dto.FamilyOverviewDTO;
+import com.etotem.cfc.service.FamilyAdminOverviewService;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import javax.annotation.Resource;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
+
+/**
+ * 管理端家庭信息查看接口测试。
+ * 注意:@SpringBootTest 需显式指定 datasource URL(生产库 192.168.16.251 不可达),
+ * 使用开发库 MariaDB(192.168.16.251:3306/zxyj)——R90 修正:本机 3306 无监听,改用可达开发库。
+ */
+@SpringBootTest(properties = {
+    "spring.datasource.url=jdbc:mysql://192.168.16.251:3306/zxyj?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true",
+    "spring.datasource.username=zxyj",
+    "spring.datasource.password=zxyj@123"
+})
+public class AdminFamilyOverviewControllerTest {
+    @Resource private AdminFamilyOverviewController ctrl;
+    @MockBean private FamilyAdminOverviewService svc;
+
+    @Test void overview_非admin拒绝() {
+        Result<FamilyOverviewDTO> r = ctrl.getOverview(7L, "parent");
+        assertTrue(r.getCode() != 200);
+    }
+    @Test void overview_成功() {
+        when(svc.buildOverview(7L)).thenReturn(new FamilyOverviewDTO());
+        Result<FamilyOverviewDTO> r = ctrl.getOverview(7L, "admin");
+        assertEquals(200, r.getCode());
+        assertNotNull(r.getData());
+    }
+    @Test void tasks_分页() {
+        when(svc.pageTasks(eq(7L), anyLong(), anyLong())).thenReturn(new Page<>());
+        Result<Page<com.etotem.cfc.dto.TaskItemVO>> r = ctrl.getTasks(7L, null, "admin");
+        assertEquals(200, r.getCode());
+    }
+}

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