Răsfoiți Sursa

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

Agnes Agent 2 ore în urmă
părinte
comite
c95a8a6764
100 a modificat fișierele cu 13654 adăugiri și 0 ștergeri
  1. 99 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminVendorController.java
  2. 103 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminVirtualTeamController.java
  3. 114 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AssessmentAdminController.java
  4. 39 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/BaziConfigController.java
  5. 39 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/BloodTypeConfigController.java
  6. 62 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/CommissionDistController.java
  7. 137 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ContentDimensionThresholdController.java
  8. 34 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DataMigrationController.java
  9. 99 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionAdminController.java
  10. 87 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionConfigController.java
  11. 50 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionRegistryController.java
  12. 107 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionWeightController.java
  13. 49 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/EcomSupplierController.java
  14. 54 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FamilyAttributeController.java
  15. 190 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FamilyMetricAggConfigController.java
  16. 269 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FileRecordController.java
  17. 197 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FoodRuleManagementController.java
  18. 86 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorAdminController.java
  19. 95 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorCorrelationAdminController.java
  20. 74 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorMappingAdminController.java
  21. 50 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/InnatePortraitConfigController.java
  22. 298 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseController.java
  23. 215 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseVectorController.java
  24. 37 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeTagController.java
  25. 69 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MbtiProfileController.java
  26. 111 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MigrationController.java
  27. 48 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MindModelManageController.java
  28. 51 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/NumSoulDetailConfigController.java
  29. 74 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/OperationLogController.java
  30. 68 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/PackageTemplateController.java
  31. 61 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ParseMonitorController.java
  32. 159 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/PpointConfigAdminController.java
  33. 65 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ProductSkuController.java
  34. 131 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParseAdminController.java
  35. 417 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParserAdminController.java
  36. 40 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportSummaryAdminController.java
  37. 68 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportTemplateController.java
  38. 146 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReviewCenterController.java
  39. 106 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ServiceContentController.java
  40. 71 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ServiceTypeController.java
  41. 219 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplierProductController.java
  42. 265 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyHierarchyController.java
  43. 284 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyManageController.java
  44. 95 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplySettlementController.java
  45. 129 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplySystemController.java
  46. 153 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyTeamController.java
  47. 75 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SysMenuController.java
  48. 276 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/TeamProfitAdminController.java
  49. 55 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/VirtualGoodsConfigAdminController.java
  50. 39 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ZodiacConfigController.java
  51. 26 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIBehaviorController.java
  52. 1101 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIChatController.java
  53. 125 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/ButlerController.java
  54. 80 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/CoachFamilyBoardController.java
  55. 89 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/CoachRecommendController.java
  56. 41 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/ContextApiController.java
  57. 77 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/RecommendationController.java
  58. 207 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentAppointmentController.java
  59. 92 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentComparisonController.java
  60. 79 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentQuotaController.java
  61. 218 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentReportController.java
  62. 137 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentResultController.java
  63. 249 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/CognitiveController.java
  64. 412 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/auth/AuthController.java
  65. 130 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/auth/WechatWebAuthController.java
  66. 410 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/butler/ButlerController.java
  67. 46 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/butler/FamilyButlerSelectController.java
  68. 99 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/cart/CartController.java
  69. 57 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/config/GuideConfigController.java
  70. 29 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/config/PublicConfigController.java
  71. 97 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/config/SeedsController.java
  72. 43 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/config/SysConfigController.java
  73. 21 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleCategoryController.java
  74. 329 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleCommentController.java
  75. 355 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleController.java
  76. 46 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/content/ContentRelatedController.java
  77. 86 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/content/ContentSectionController.java
  78. 179 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/dan/DanAssessmentExecutionController.java
  79. 58 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietIngredientController.java
  80. 33 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietMealConfigController.java
  81. 79 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietPreferencesController.java
  82. 108 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecommendationController.java
  83. 62 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecordController.java
  84. 113 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/BindController.java
  85. 101 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/BindInviteController.java
  86. 94 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyController.java
  87. 498 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyInviteController.java
  88. 300 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyMembersController.java
  89. 290 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyUserController.java
  90. 207 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FiveDimensionSelfCheckController.java
  91. 104 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/InteractionLogController.java
  92. 58 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/ManualDimensionScoreController.java
  93. 75 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/MbtiController.java
  94. 144 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/ParentController.java
  95. 78 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/PointsController.java
  96. 128 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/RelationshipQualityController.java
  97. 110 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/RelationshipQuestionnaireController.java
  98. 114 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/TeacherFamilyBindingController.java
  99. 98 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/fatloss/FatDietController.java
  100. 83 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/fatloss/FatExerciseController.java

+ 99 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminVendorController.java

@@ -0,0 +1,99 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+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 org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/vendor")
+public class AdminVendorController {
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 分页查询服务商入驻申请列表
+     * 过滤条件: vendorStatus, vendorType
+     */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String vendorStatus = (String) params.get("vendorStatus");
+        String vendorType = (String) params.get("vendorType");
+
+        Page<User> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
+                .isNotNull(User::getVendorStatus);
+
+        if (vendorStatus != null && !vendorStatus.isEmpty()) {
+            wrapper.eq(User::getVendorStatus, vendorStatus);
+        }
+        if (vendorType != null && !vendorType.isEmpty()) {
+            wrapper.eq(User::getVendorType, vendorType);
+        }
+
+        wrapper.orderByDesc(User::getUpdatedAt);
+        SortUtil.applySort(wrapper);
+        Page<User> result = userMapper.selectPage(pageParam, wrapper);
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("list", result.getRecords());
+        data.put("total", result.getTotal());
+        data.put("page", page);
+        data.put("size", size);
+        return Result.success(data);
+    }
+
+    /**
+     * 审核服务商入驻申请
+     * @param params userId, vendorStatus(approved/rejected), rejectReason
+     */
+    @PostMapping("/review")
+    public Result<String> review(@RequestBody Map<String, Object> params) {
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        String vendorStatus = (String) params.get("vendorStatus");
+        String rejectReason = (String) params.getOrDefault("rejectReason", "");
+
+        // 兼容旧前端(VendorAudit)传 action='approve'/'reject' 的调用方式
+        if (vendorStatus == null) {
+            String action = (String) params.get("action");
+            if ("approve".equals(action)) vendorStatus = "approved";
+            else if ("reject".equals(action)) vendorStatus = "rejected";
+        }
+
+        if (userId == null) {
+            return Result.error("userId不能为空");
+        }
+        if (vendorStatus == null || (!"approved".equals(vendorStatus) && !"rejected".equals(vendorStatus))) {
+            return Result.error("vendorStatus必须为 approved 或 rejected");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        user.setVendorStatus(vendorStatus);
+        if ("rejected".equals(vendorStatus)) {
+            user.setVendorRejectReason(rejectReason);
+        } else {
+            user.setVendorRejectReason(null);
+        }
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        String msg = "approved".equals(vendorStatus) ? "审核通过" : "已拒绝";
+        return Result.success(msg);
+    }
+}

+ 103 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminVirtualTeamController.java

@@ -0,0 +1,103 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DistributionSystem;
+import com.etotem.cfc.service.DistributionService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "管理端-虚拟团队管理")
+@RestController
+@RequestMapping("/api/admin/virtual-team")
+public class AdminVirtualTeamController {
+
+    @Resource
+    private DistributionService distributionService;
+
+    @Operation(summary = "销售体系列表")
+    @PostMapping("/list")
+    public Result<List<DistributionSystem>> list() {
+        return distributionService.listSystems();
+    }
+
+    @Operation(summary = "创建销售体系")
+    @PostMapping("/create")
+    public Result<String> create(@RequestBody DistributionSystem system) {
+        return distributionService.createSystem(system);
+    }
+
+    @Operation(summary = "更新销售体系")
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody DistributionSystem system) {
+        return distributionService.updateSystem(system);
+    }
+
+    @Operation(summary = "启用/禁用销售体系")
+    @PostMapping("/toggle")
+    public Result<String> toggle(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) return Result.error("id不能为空");
+        return distributionService.toggleSystem(id);
+    }
+
+    @Operation(summary = "团队成员列表(含用户信息)")
+    @PostMapping("/members")
+    public Result<List<Map<String, Object>>> members(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) return Result.error("systemId不能为空");
+        return distributionService.getTeamMembers(systemId);
+    }
+
+    @Operation(summary = "添加团队成员")
+    @PostMapping("/add-member")
+    public Result<Void> addMember(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        if (systemId == null) return Result.error("systemId不能为空");
+        if (userId == null) return Result.error("userId不能为空");
+        return distributionService.addRelation(systemId, userId, parentId);
+    }
+
+    @Operation(summary = "移除团队成员")
+    @PostMapping("/remove-member")
+    public Result<String> removeMember(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) return Result.error("id不能为空");
+        return distributionService.removeRelation(id);
+    }
+
+    @Operation(summary = "调整成员位置/上级")
+    @PostMapping("/update-member")
+    public Result<String> updateMember(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        if (id == null) return Result.error("id不能为空");
+        return distributionService.updateMemberTeam(id, params.containsKey("parentId") ? parentId : null);
+    }
+
+    @Operation(summary = "用户所属团队列表")
+    @PostMapping("/user-teams")
+    public Result<List<DistributionSystem>> userTeams(@RequestBody Map<String, Object> params) {
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        if (userId == null) return Result.error("userId不能为空");
+        return distributionService.getUserTeams(userId);
+    }
+
+    @Operation(summary = "团队树形结构")
+    @PostMapping("/tree")
+    public Result<List<Map<String, Object>>> tree(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) return Result.error("systemId不能为空");
+        return distributionService.getTeamTree(systemId);
+    }
+}

+ 114 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AssessmentAdminController.java

@@ -0,0 +1,114 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.AssessmentMaterial;
+import com.etotem.cfc.entity.AssessmentPointsConfig;
+import com.etotem.cfc.service.AssessmentService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "测评管理", description = "管理员测评资料与积分配置")
+@RestController
+@RequestMapping("/api/admin/assessment")
+public class AssessmentAdminController {
+
+    @Resource
+    private AssessmentService assessmentService;
+
+    @Operation(summary = "获取测评资料列表")
+    @PostMapping("/materials")
+    public Result<List<AssessmentMaterial>> getMaterials() {
+        List<AssessmentMaterial> list = assessmentService.getMaterialList();
+        return Result.success(list);
+    }
+
+    @Operation(summary = "获取测评资料详情")
+    @PostMapping("/materials/{id}")
+    public Result<AssessmentMaterial> getMaterial(@PathVariable Long id) {
+        AssessmentMaterial material = assessmentService.getById(id);
+        if (material == null) {
+            return Result.error("资料不存在");
+        }
+        return Result.success(material);
+    }
+
+    @Operation(summary = "创建测评资料")
+    @PostMapping("/materials/create")
+    public Result<AssessmentMaterial> createMaterial(@RequestBody Map<String, String> body) {
+        String title = body.get("title");
+        String content = body.get("content");
+        String coverImage = body.get("coverImage");
+
+        if (title == null || title.isEmpty()) {
+            return Result.error("标题不能为空");
+        }
+
+        AssessmentMaterial material = assessmentService.createMaterial(title, content, coverImage);
+        return Result.success(material);
+    }
+
+    @Operation(summary = "更新测评资料")
+    @PostMapping("/materials/{id}/update")
+    public Result<AssessmentMaterial> updateMaterial(@PathVariable Long id, @RequestBody Map<String, String> body) {
+        AssessmentMaterial material = assessmentService.getById(id);
+        if (material == null) {
+            return Result.error("资料不存在");
+        }
+
+        if (body.get("title") != null) {
+            material.setTitle(body.get("title"));
+        }
+        if (body.get("content") != null) {
+            material.setContent(body.get("content"));
+        }
+        if (body.get("coverImage") != null) {
+            material.setCoverImage(body.get("coverImage"));
+        }
+        if (body.get("status") != null) {
+            material.setStatus(body.get("status"));
+        }
+
+        assessmentService.updateById(material);
+        return Result.success(material);
+    }
+
+    @Operation(summary = "删除测评资料")
+    @PostMapping("/materials/{id}/delete")
+    public Result<Boolean> deleteMaterial(@PathVariable Long id) {
+        AssessmentMaterial material = assessmentService.getById(id);
+        if (material == null) {
+            return Result.error("资料不存在");
+        }
+        material.setStatus("inactive");
+        assessmentService.updateById(material);
+        return Result.success(true);
+    }
+
+    @Operation(summary = "获取积分配置")
+    @PostMapping("/config")
+    public Result<AssessmentPointsConfig> getPointsConfig() {
+        AssessmentPointsConfig config = assessmentService.getPointsConfig();
+        return Result.success(config);
+    }
+
+    @Operation(summary = "更新积分配置")
+    @PostMapping("/config/update")
+    public Result<Boolean> updatePointsConfig(@RequestBody Map<String, Object> body) {
+        Integer pointsValue = (Integer) body.get("pointsValue");
+        // yuan -> fen (元转分, 0.01元=1分)
+        Integer pointsValueYuan = body.get("pointsValueYuan") != null
+            ? (int) (Double.parseDouble(body.get("pointsValueYuan").toString()) * 100) : 1;
+
+        if (pointsValue == null || pointsValue <= 0) {
+            return Result.error("积分值必须大于0");
+        }
+
+        boolean success = assessmentService.updatePointsConfig(pointsValue, pointsValueYuan);
+        return Result.success(success);
+    }
+}

+ 39 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/BaziConfigController.java

@@ -0,0 +1,39 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.BaziConfig;
+import com.etotem.cfc.service.BaziConfigService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/admin/bazi-config")
+public class BaziConfigController {
+
+    @Resource
+    private BaziConfigService baziConfigService;
+
+    @PostMapping("/list")
+    public Result<List<BaziConfig>> list() {
+        return Result.success(baziConfigService.getAll());
+    }
+
+    @PostMapping("/create")
+    public Result<BaziConfig> create(@RequestBody BaziConfig config) {
+        return Result.success(baziConfigService.create(config));
+    }
+
+    @PostMapping("/update")
+    public Result<BaziConfig> update(@RequestBody BaziConfig config) {
+        boolean success = baziConfigService.update(config);
+        return success ? Result.success(config) : Result.error("更新失败");
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        boolean success = baziConfigService.delete(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 39 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/BloodTypeConfigController.java

@@ -0,0 +1,39 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.BloodTypeConfig;
+import com.etotem.cfc.service.BloodTypeConfigService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/admin/blood-type-config")
+public class BloodTypeConfigController {
+
+    @Resource
+    private BloodTypeConfigService bloodTypeConfigService;
+
+    @PostMapping("/list")
+    public Result<List<BloodTypeConfig>> list() {
+        return Result.success(bloodTypeConfigService.getAll());
+    }
+
+    @PostMapping("/create")
+    public Result<BloodTypeConfig> create(@RequestBody BloodTypeConfig config) {
+        return Result.success(bloodTypeConfigService.create(config));
+    }
+
+    @PostMapping("/update")
+    public Result<BloodTypeConfig> update(@RequestBody BloodTypeConfig config) {
+        boolean success = bloodTypeConfigService.update(config);
+        return success ? Result.success(config) : Result.error("更新失败");
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        boolean success = bloodTypeConfigService.delete(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 62 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/CommissionDistController.java

@@ -0,0 +1,62 @@
+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.CommissionDistLog;
+import com.etotem.cfc.service.CommissionDistService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * P点分润记录管理
+ * 管理端接口
+ */
+@RestController
+@RequestMapping("/api/admin/commission-dist")
+public class CommissionDistController {
+
+    @Resource
+    private CommissionDistService commissionDistService;
+
+    /**
+     * 分润记录分页列表
+     */
+    @PostMapping("/list")
+    public Result<Page<CommissionDistLog>> list(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        Long buyerId = ParamUtils.getLong(params.get("buyerId"));
+        Long levelUserId = ParamUtils.getLong(params.get("levelUserId"));
+
+        Page<CommissionDistLog> pageParam = new Page<>(page, size);
+        Page<CommissionDistLog> result = commissionDistService.adminPage(pageParam, buyerId, levelUserId);
+        return Result.success(result);
+    }
+
+    /**
+     * 用户分润记录查询(买家或推荐人)
+     */
+    @PostMapping("/user-logs")
+    public Result<List<CommissionDistLog>> userLogs(@RequestBody Map<String, Object> params) {
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        List<CommissionDistLog> logs = commissionDistService.getUserDistLogs(userId, 1, 50);
+        return Result.success(logs);
+    }
+
+    /**
+     * 用户累计获得P点分润
+     */
+    @PostMapping("/user-total")
+    public Result<Integer> userTotal(@RequestBody Map<String, Object> params) {
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        int total = commissionDistService.getTotalDistributedPpoint(userId);
+        return Result.success(total);
+    }
+}

+ 137 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ContentDimensionThresholdController.java

@@ -0,0 +1,137 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ContentDimensionThreshold;
+import com.etotem.cfc.service.ContentDimensionThresholdService;
+import com.etotem.cfc.util.DimensionCodes;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 管理端-内容维度阈值显隐配置(商品/文章/活动/游戏 五维+子项+自定义指标)。
+ *
+ * <p>显隐规则(OR 逻辑):对某个内容项,若其配置的任一维度上「用户指标值 &lt; 阈值」→ 该内容显示;
+ * 若其配置的全部维度上「用户指标值 ≥ 阈值」→ 该内容不显示(隐藏)。
+ * 阈值 0-100,与 FiveDimensionScore.score 同量纲;家庭维度指标取家庭成员平均值。
+ *
+ * <p>维度选择器复用现有 /api/admin/dimension-config/tree(不新建维度树接口)。
+ * 维度码校验:复用 DimensionCodes 五维码集合做基础校验;子项码/自定义码不在白名单内,放行即可。
+ */
+@Tag(name = "管理端-内容维度阈值", description = "商品/文章/活动/游戏的维度阈值显隐配置")
+@RestController
+@RequestMapping("/api/admin/content-dimension-threshold")
+public class ContentDimensionThresholdController {
+
+    @Resource
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+
+    /** 允许的内容类型 */
+    private static final String[] CONTENT_TYPES = {"PRODUCT", "ARTICLE", "ACTIVITY", "MINIGAME"};
+
+    private boolean isAdmin(String role) {
+        return "admin".equals(role) || "operator".equals(role);
+    }
+
+    private boolean validContentType(String contentType) {
+        if (contentType == null) return false;
+        for (String t : CONTENT_TYPES) {
+            if (t.equals(contentType)) return true;
+        }
+        return false;
+    }
+
+    /**
+     * 校验单个阈值配置:
+     * - dimensionCode 非空;若为五维码必须落在 DimensionCodes 白名单(body/mind/wisdom/action/wealth);
+     *   子项码/自定义码不在白名单内直接放行。
+     * - threshold 必须 0-100。
+     */
+    private ContentDimensionThreshold normalize(Item item) {
+        if (item == null || item.dimensionCode == null || item.dimensionCode.trim().isEmpty()) {
+            throw new IllegalArgumentException("dimensionCode 不能为空");
+        }
+        String code = item.dimensionCode.trim();
+        if (DimensionCodes.isValid(code)) {
+            code = code.toLowerCase();
+        }
+        if (item.threshold == null || item.threshold < 0 || item.threshold > 100) {
+            throw new IllegalArgumentException("threshold 必须在 0-100 之间");
+        }
+        ContentDimensionThreshold t = new ContentDimensionThreshold();
+        t.setDimensionCode(code);
+        t.setDimensionName(item.dimensionName != null ? item.dimensionName : item.customName);
+        t.setThreshold(item.threshold);
+        t.setIsCustom(item.isCustom != null ? item.isCustom : 0);
+        return t;
+    }
+
+    @Operation(summary = "批量保存内容维度阈值(先删旧再插新)")
+    @PostMapping("/batch-save")
+    public Result<List<ContentDimensionThreshold>> batchSave(@RequestBody BatchSaveReq req,
+                                                             @RequestAttribute("role") String role) {
+        if (!isAdmin(role)) {
+            return Result.error("无权限:仅平台管理员可配置维度阈值");
+        }
+        if (req == null || !validContentType(req.contentType) || req.contentId == null) {
+            return Result.error("contentType 必须是 PRODUCT/ARTICLE/ACTIVITY/MINIGAME 且 contentId 不能为空");
+        }
+        List<ContentDimensionThreshold> items = new ArrayList<>();
+        if (req.items != null) {
+            for (Item item : req.items) {
+                items.add(normalize(item));
+            }
+        }
+        return Result.success(contentDimensionThresholdService.batchSave(req.contentType, req.contentId, items));
+    }
+
+    @Operation(summary = "查询某内容项的维度阈值列表")
+    @PostMapping("/list")
+    public Result<List<ContentDimensionThreshold>> list(@RequestParam String contentType,
+                                                        @RequestParam Long contentId,
+                                                        @RequestAttribute("role") String role) {
+        if (!isAdmin(role)) {
+            return Result.error("无权限:仅平台管理员可查看维度阈值");
+        }
+        if (!validContentType(contentType) || contentId == null) {
+            return Result.error("contentType 必须是 PRODUCT/ARTICLE/ACTIVITY/MINIGAME 且 contentId 不能为空");
+        }
+        return Result.success(contentDimensionThresholdService.listByContent(contentType, contentId));
+    }
+
+    @Operation(summary = "删除单条维度阈值")
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id,
+                               @RequestAttribute("role") String role) {
+        if (!isAdmin(role)) {
+            return Result.error("无权限:仅平台管理员可删除维度阈值");
+        }
+        boolean ok = contentDimensionThresholdService.deleteById(id);
+        return ok ? Result.success(null) : Result.error("删除失败");
+    }
+
+    /** 批量保存请求体 */
+    public static class BatchSaveReq {
+        public String contentType;
+        public Long contentId;
+        public List<Item> items;
+    }
+
+    /** 单条阈值配置项 */
+    public static class Item {
+        public String dimensionCode;
+        public String dimensionName;
+        public Integer threshold;
+        public Integer isCustom;
+        public String customName;
+    }
+}

+ 34 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DataMigrationController.java

@@ -0,0 +1,34 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.DataMigrationService;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/migration")
+@ConditionalOnProperty(name = "sfms.datasource.enabled", havingValue = "true", matchIfMissing = false)
+public class DataMigrationController {
+
+    @Resource
+    private DataMigrationService dataMigrationService;
+
+    /**
+     * 从 SFMS 系统迁移数据到当前系统。
+     * 迁移顺序:家庭 → 家庭主账号用户 → 家庭成员用户+详情 → 规划师 → 规划师-家庭关系 → 订单 → 测评结果 → 成长档案 → 成长方案
+     */
+    @PostMapping("/run")
+    public Result<Map<String, Object>> runMigration() {
+        Map<String, Object> result = dataMigrationService.runMigration();
+        if (Boolean.TRUE.equals(result.get("success"))) {
+            return Result.success("迁移完成", result);
+        } else {
+            return Result.success("迁移过程中有部分错误", result);
+        }
+    }
+}

+ 99 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionAdminController.java

@@ -0,0 +1,99 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.HealthDataSourceRecord;
+import com.etotem.cfc.entity.HealthNormReference;
+import com.etotem.cfc.mapper.HealthDataSourceRecordMapper;
+import com.etotem.cfc.mapper.HealthNormReferenceMapper;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import com.etotem.cfc.util.SortUtil;
+
+@Tag(name = "管理端-健康维度配置")
+@RestController
+@RequestMapping("/api/admin/dimension")
+public class DimensionAdminController {
+
+    @Resource
+    private HealthNormReferenceMapper normMapper;
+
+    @Resource
+    private HealthDataSourceRecordMapper dataSourceRecordMapper;
+
+    @Operation(summary = "常模列表")
+    @PostMapping("/norm/list")
+    public Result<List<HealthNormReference>> listNorms() {
+        List<HealthNormReference> list = normMapper.selectList(
+            new LambdaQueryWrapper<HealthNormReference>()
+                .orderByAsc(HealthNormReference::getDimension)
+                .orderByAsc(HealthNormReference::getGender)
+                .orderByAsc(HealthNormReference::getAgeMin)
+        );
+        return Result.success(list);
+    }
+
+    @Operation(summary = "保存常模(新增/更新)")
+    @PostMapping("/norm/save")
+    public Result<String> saveNorm(@RequestBody HealthNormReference norm) {
+        if (norm.getId() == null) {
+            norm.setCreatedAt(new Date());
+            normMapper.insert(norm);
+        } else {
+            normMapper.updateById(norm);
+        }
+        return Result.success("保存成功");
+    }
+
+    @Operation(summary = "删除常模")
+    @PostMapping("/norm/delete")
+    public Result<String> deleteNorm(@RequestBody Long id) {
+        normMapper.deleteById(id);
+        return Result.success("删除成功");
+    }
+
+    @Operation(summary = "数据源列表")
+    @PostMapping("/data-source/list")
+    public Result<Page<HealthDataSourceRecord>> listDataSources(
+            @RequestParam(required = false, defaultValue = "1") Integer page,
+            @RequestParam(required = false, defaultValue = "20") Integer size) {
+        Page<HealthDataSourceRecord> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<HealthDataSourceRecord> wrapper = new LambdaQueryWrapper<HealthDataSourceRecord>()
+            .orderByDesc(HealthDataSourceRecord::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        Page<HealthDataSourceRecord> result = dataSourceRecordMapper.selectPage(pageParam, wrapper);
+        return Result.success(result);
+    }
+
+    @Operation(summary = "数据源详情")
+    @PostMapping("/data-source/detail")
+    public Result<HealthDataSourceRecord> getDataSource(@RequestBody Long id) {
+        HealthDataSourceRecord record = dataSourceRecordMapper.selectById(id);
+        return record != null ? Result.success(record) : Result.error("记录不存在");
+    }
+
+    @Operation(summary = "保存数据源(新增/更新)")
+    @PostMapping("/data-source/save")
+    public Result<String> saveDataSource(@RequestBody HealthDataSourceRecord record) {
+        if (record.getId() == null) {
+            record.setCreatedAt(new Date());
+            dataSourceRecordMapper.insert(record);
+        } else {
+            dataSourceRecordMapper.updateById(record);
+        }
+        return Result.success("保存成功");
+    }
+
+    @Operation(summary = "删除数据源")
+    @PostMapping("/data-source/delete")
+    public Result<String> deleteDataSource(@RequestBody Long id) {
+        dataSourceRecordMapper.deleteById(id);
+        return Result.success("删除成功");
+    }
+}

+ 87 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionConfigController.java

@@ -0,0 +1,87 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ProductDimensionConfig;
+import com.etotem.cfc.service.ProductDimensionConfigService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/dimension-config")
+public class DimensionConfigController {
+
+    @Resource
+    private ProductDimensionConfigService productDimensionConfigService;
+
+    @Resource
+    private com.etotem.cfc.service.DimensionRegistryService dimensionRegistryService;
+
+    /** 维度配置列表(TC-A-25-P:admin 守卫,非 admin → 403) */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        String dimensionType = (String) params.get("dimensionType");
+        Integer enabled = (Integer) params.get("enabled");
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        return Result.success(productDimensionConfigService.list(dimensionType, enabled, page, size));
+    }
+
+    /** 维度配置详情(TC-A-25-P:admin 守卫,非 admin → 403) */
+    @PostMapping("/get")
+    public Result<ProductDimensionConfig> get(@RequestParam Long id,
+                                              @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        ProductDimensionConfig config = productDimensionConfigService.getById(id);
+        if (config == null) {
+            return Result.error("维度配置不存在");
+        }
+        return Result.success(config);
+    }
+
+    /** 保存维度配置(TC-A-25-P:admin 守卫,非 admin → 403) */
+    @PostMapping("/save")
+    public Result<ProductDimensionConfig> save(@RequestBody ProductDimensionConfig config,
+                                               @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        // 统一维度体系 P0-T4(设计文档 §5.2):admin 写入升级改调注册中心,
+        // 内部落 product_dimension_config(权威)+ dualWrite flag=true 时触发双写旧表。
+        return Result.success(dimensionRegistryService.saveConfig(config));
+    }
+
+    /** 删除维度配置(TC-A-25-P:admin 守卫,非 admin → 403;被引用维度由 Service 拒绝删除) */
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id,
+                                @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        boolean success = productDimensionConfigService.deleteConfig(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+
+    /** 维度配置树(TC-A-25-P:admin 守卫,非 admin → 403) */
+    @PostMapping("/tree")
+    public Result<List<ProductDimensionConfig>> tree(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        // 7 body 子节点经 seed(迁移447)入库后,既有 tree() 按 parent_id 自然展开
+        return Result.success(productDimensionConfigService.tree());
+    }
+}

+ 50 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionRegistryController.java

@@ -0,0 +1,50 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.DimensionNode;
+import com.etotem.cfc.service.DimensionRegistryService;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+/**
+ * 统一维度树只读查询接口(设计文档 §5.1)——统一取数入口。
+ *
+ * <p>供小程序/管理端 DimensionProvider 读取;合并维度节点 + 指标节点的统一树。</p>
+ */
+@RestController
+@RequestMapping("/api/dimension-registry")
+public class DimensionRegistryController {
+
+    @Resource
+    private DimensionRegistryService dimensionRegistryService;
+
+    @GetMapping("/tree")
+    public Result<List<DimensionNode>> tree(@RequestParam(required = false) String sourceSystem) {
+        return Result.success(dimensionRegistryService.getTree(sourceSystem));
+    }
+
+    @GetMapping("/roots")
+    public Result<List<DimensionNode>> roots() {
+        return Result.success(dimensionRegistryService.getRoots());
+    }
+
+    @GetMapping("/code/{code}")
+    public Result<DimensionNode> getByCode(@PathVariable String code) {
+        DimensionNode node = dimensionRegistryService.getNodeByCode(code);
+        if (node == null) {
+            return Result.error(404, "维度不存在");
+        }
+        return Result.success(node);
+    }
+
+    @GetMapping("/map")
+    public Result<String> map(@RequestParam String legacy) {
+        return Result.success(dimensionRegistryService.resolveLegacyToUnified(legacy));
+    }
+}

+ 107 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionWeightController.java

@@ -0,0 +1,107 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DimensionWeight;
+import com.etotem.cfc.service.DimensionWeightService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/dimension-weight")
+public class DimensionWeightController {
+
+    @Resource
+    private DimensionWeightService dimensionWeightService;
+
+    /**
+     * 保存权重(admin 端点入口,带 role 守卫,非 admin → 403)。
+     * 1-arg 重载保留供直调/测试,端点统一经本 2-arg 重载暴露。
+     */
+    @PostMapping("/save")
+    public Result<Void> save(@RequestBody Map<String, Object> params,
+                             @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return save(params);
+    }
+
+    /** 保存权重(TC-A-25-E:权重范围 [0,100] 且和=100% → 否则 400 拦截,不落库) */
+    public Result<Void> save(Map<String, Object> params) {
+        Object targetTypeObj = params.get("targetType");
+        Object targetIdObj = params.get("targetId");
+        if (targetTypeObj == null || targetIdObj == null) {
+            return Result.error("targetType 和 targetId 不能为空");
+        }
+        String targetType = targetTypeObj.toString();
+        Long targetId = Long.valueOf(targetIdObj.toString());
+        @SuppressWarnings("unchecked")
+        List<Map<String, Object>> weightMaps = (List<Map<String, Object>>) params.get("weights");
+        if (weightMaps == null || weightMaps.isEmpty()) {
+            return Result.error("weights 不能为空");
+        }
+        // TC-A-25-E 异常流:权重非法(负/超界/和≠100%)→ 400 拦截,不落库
+        int sum = 0;
+        for (Map<String, Object> m : weightMaps) {
+            Object weightObj = m.get("weight");
+            if (weightObj == null) {
+                return Result.badRequest("weight 不能为空");
+            }
+            int weight;
+            try {
+                weight = Integer.parseInt(weightObj.toString());
+            } catch (NumberFormatException e) {
+                return Result.badRequest("weight 必须为整数");
+            }
+            if (weight < 0) {
+                return Result.badRequest("权重不能为负数");
+            }
+            if (weight > 100) {
+                return Result.badRequest("权重不能超过100");
+            }
+            sum += weight;
+        }
+        if (sum != 100) {
+            return Result.badRequest("权重之和必须为100%");
+        }
+        List<DimensionWeight> weights = weightMaps.stream().map(m -> {
+            DimensionWeight w = new DimensionWeight();
+            w.setDimension(m.get("dimension").toString());
+            w.setWeight(Integer.valueOf(m.get("weight").toString()));
+            w.setEnabled(Boolean.valueOf(m.get("enabled").toString()));
+            return w;
+        }).collect(java.util.stream.Collectors.toList());
+        dimensionWeightService.saveWeights(targetType, targetId, weights);
+        return Result.success(null);
+    }
+
+    /** 权重列表(admin 端点入口,带 role 守卫,非 admin → 403) */
+    @PostMapping("/list")
+    public Result<List<DimensionWeight>> list(@RequestBody Map<String, Object> params,
+                                              @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return list(params);
+    }
+
+    /** 权重列表(1-arg 保留供直调/测试) */
+    public Result<List<DimensionWeight>> list(Map<String, Object> params) {
+        Object targetTypeObj = params.get("targetType");
+        Object targetIdObj = params.get("targetId");
+        if (targetTypeObj == null || targetIdObj == null) {
+            return Result.error("targetType 和 targetId 不能为空");
+        }
+        String targetType = targetTypeObj.toString();
+        Long targetId = Long.valueOf(targetIdObj.toString());
+        List<DimensionWeight> list = dimensionWeightService.getByTarget(targetType, targetId);
+        return Result.success(list);
+    }
+}

+ 49 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/EcomSupplierController.java

@@ -0,0 +1,49 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @deprecated 已合并至 /api/admin/supply-system(供应商体系管理)。此接口返回 410。
+ */
+@Deprecated
+@Tag(name = "管理端-电商供应商(已废弃)")
+@RestController
+@RequestMapping("/api/admin/ecom-supplier")
+public class EcomSupplierController {
+
+    @Operation(summary = "【已废弃】供应商列表,请使用 /api/admin/supply-system/list")
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
+        return Result.error(410, "该接口已废弃,请使用 /api/admin/supply-system/list");
+    }
+
+    @Operation(summary = "【已废弃】所有供应商(下拉选择用)")
+    @PostMapping("/all")
+    public Result<List<Object>> all() {
+        return Result.error(410, "该接口已废弃,请使用 /api/admin/supply-system/list-all");
+    }
+
+    @Operation(summary = "【已废弃】创建供应商")
+    @PostMapping("/save")
+    public Result<String> save(@RequestBody Object supplier) {
+        return Result.error(410, "该接口已废弃,请使用 /api/admin/supply-system/create");
+    }
+
+    @Operation(summary = "【已废弃】更新供应商")
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody Object supplier) {
+        return Result.error(410, "该接口已废弃,请使用 /api/admin/supply-system/update");
+    }
+
+    @Operation(summary = "【已废弃】删除供应商")
+    @PostMapping("/delete")
+    public Result<String> delete(@RequestBody Map<String, Object> params) {
+        return Result.error(410, "该接口已废弃,请使用 /api/admin/supply-system/toggle-status");
+    }
+}

+ 54 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FamilyAttributeController.java

@@ -0,0 +1,54 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMemberAttributes;
+import com.etotem.cfc.service.FamilyMemberAttributeService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/family/attributes")
+public class FamilyAttributeController {
+
+    @Resource
+    private FamilyMemberAttributeService familyMemberAttributeService;
+
+    @PostMapping("/update")
+    public Result<FamilyMemberAttributes> update(@RequestBody FamilyMemberAttributes attribute) {
+        FamilyMemberAttributes saved = familyMemberAttributeService.saveOrUpdateAttribute(attribute);
+        return Result.success(saved);
+    }
+
+    @PostMapping("/get")
+    public Result<FamilyMemberAttributes> get(@RequestBody Map<String, Object> params) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"));
+        String memberType = (String) params.get("memberType");
+        FamilyMemberAttributes attr = familyMemberAttributeService.getByMember(memberId, memberType);
+        return Result.success(attr);
+    }
+
+    @PostMapping("/calculate")
+    public Result<FamilyMemberAttributes> calculate(@RequestBody Map<String, Object> params) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"));
+        String memberType = (String) params.get("memberType");
+
+        FamilyMemberAttributes attrs = familyMemberAttributeService.getByMember(memberId, memberType);
+        if (attrs == null) {
+            return Result.error("未找到该成员的属性记录");
+        }
+
+        // Auto-calculate zodiac, BaZi, life number
+        familyMemberAttributeService.autoCalculate(attrs);
+
+        // Calculate innate scores for mind and wisdom dimensions
+        Integer mindScore = familyMemberAttributeService.calcInnateScore(memberId, memberType, "mind");
+        Integer wisdomScore = familyMemberAttributeService.calcInnateScore(memberId, memberType, "wisdom");
+
+        // Reload to get updated values
+        attrs = familyMemberAttributeService.getByMember(memberId, memberType);
+        return Result.success(attrs);
+    }
+}

+ 190 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FamilyMetricAggConfigController.java

@@ -0,0 +1,190 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMetricAggConfig;
+import com.etotem.cfc.mapper.FamilyMetricAggConfigMapper;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 管理端 - 家庭指标聚合方式配置(平台级全局一份)。
+ * <p>
+ * 配置作用域为平台级(不分家庭),供五维能量汇总 / 珍珠图 / 章鱼图汇集使用。
+ * agg_type:SUM=合计 / AVG=平均 / COLLECT=汇集。
+ */
+@Tag(name = "管理端 - 家庭指标聚合方式配置")
+@RestController
+@RequestMapping("/api/admin/family-metric-agg")
+public class FamilyMetricAggConfigController {
+
+    @Resource
+    private FamilyMetricAggConfigMapper familyMetricAggConfigMapper;
+
+    /** 全量配置列表(配置项 < 50,无需分页) */
+    @Operation(summary = "家庭指标聚合方式配置列表")
+    @PostMapping("/list")
+    public Result<List<Map<String, Object>>> list(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        List<FamilyMetricAggConfig> configs = familyMetricAggConfigMapper.selectList(
+                new LambdaQueryWrapper<FamilyMetricAggConfig>()
+                        .orderByAsc(FamilyMetricAggConfig::getSortOrder)
+                        .orderByAsc(FamilyMetricAggConfig::getId));
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (FamilyMetricAggConfig c : configs) {
+            result.add(toMap(c));
+        }
+        return Result.success(result);
+    }
+
+    /** 新增/更新配置(body 带 id 则更新,否则新增) */
+    @Operation(summary = "保存家庭指标聚合方式配置")
+    @PostMapping("/save")
+    public Result<Boolean> save(@RequestBody Map<String, Object> params,
+                                @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String metricKey = str(params.get("metricKey"));
+        String metricName = str(params.get("metricName"));
+        if (metricKey == null || metricKey.trim().isEmpty()) {
+            return Result.error("metricKey不能为空");
+        }
+        if (metricName == null || metricName.trim().isEmpty()) {
+            return Result.error("metricName不能为空");
+        }
+        String aggType = str(params.get("aggType"));
+        String valueType = str(params.get("valueType"));
+        if (aggType == null || aggType.trim().isEmpty()) {
+            return Result.error("aggType不能为空");
+        }
+        if (valueType == null || valueType.trim().isEmpty()) {
+            return Result.error("valueType不能为空");
+        }
+
+        Long id = longVal(params.get("id"));
+        FamilyMetricAggConfig config;
+        if (id != null) {
+            config = familyMetricAggConfigMapper.selectById(id);
+            if (config == null) {
+                return Result.error("配置不存在");
+            }
+        } else {
+            FamilyMetricAggConfig existing = familyMetricAggConfigMapper.selectOne(
+                    new LambdaQueryWrapper<FamilyMetricAggConfig>()
+                            .eq(FamilyMetricAggConfig::getMetricKey, metricKey.trim())
+                            .last("LIMIT 1"));
+            if (existing != null) {
+                return Result.error("metricKey已存在,请直接编辑对应记录");
+            }
+            config = new FamilyMetricAggConfig();
+            config.setCreatedAt(new Date());
+        }
+        config.setMetricKey(metricKey.trim());
+        config.setMetricName(metricName.trim());
+        config.setDimensionCode(str(params.get("dimensionCode")));
+        config.setAggType(aggType.trim().toUpperCase());
+        config.setValueType(valueType.trim().toUpperCase());
+        config.setDisplayMode(str(params.get("displayMode")));
+        config.setSortOrder(intVal(params.get("sortOrder"), 0));
+        config.setStatus(str(params.get("status")) != null ? str(params.get("status")).trim() : "active");
+        config.setRemark(str(params.get("remark")));
+        config.setUpdatedAt(new Date());
+
+        if (id != null) {
+            familyMetricAggConfigMapper.updateById(config);
+        } else {
+            familyMetricAggConfigMapper.insert(config);
+        }
+        return Result.success(Boolean.TRUE);
+    }
+
+    /** 删除配置 */
+    @Operation(summary = "删除家庭指标聚合方式配置")
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> params,
+                                  @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long id = longVal(params.get("id"));
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        familyMetricAggConfigMapper.deleteById(id);
+        return Result.success(Boolean.TRUE);
+    }
+
+    /** 更新状态(active/disabled) */
+    @Operation(summary = "更新家庭指标聚合方式配置状态")
+    @PostMapping("/update-status")
+    public Result<Boolean> updateStatus(@RequestBody Map<String, Object> params,
+                                        @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long id = longVal(params.get("id"));
+        String status = str(params.get("status"));
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        if (status == null || status.trim().isEmpty()) {
+            return Result.error("status不能为空");
+        }
+        FamilyMetricAggConfig config = familyMetricAggConfigMapper.selectById(id);
+        if (config == null) {
+            return Result.error("配置不存在");
+        }
+        config.setStatus(status.trim());
+        config.setUpdatedAt(new Date());
+        familyMetricAggConfigMapper.updateById(config);
+        return Result.success(Boolean.TRUE);
+    }
+
+    private Map<String, Object> toMap(FamilyMetricAggConfig c) {
+        Map<String, Object> m = new java.util.LinkedHashMap<>();
+        m.put("id", c.getId());
+        m.put("metricKey", c.getMetricKey());
+        m.put("metricName", c.getMetricName());
+        m.put("dimensionCode", c.getDimensionCode());
+        m.put("aggType", c.getAggType());
+        m.put("valueType", c.getValueType());
+        m.put("displayMode", c.getDisplayMode());
+        m.put("sortOrder", c.getSortOrder());
+        m.put("status", c.getStatus());
+        m.put("remark", c.getRemark());
+        return m;
+    }
+
+    private String str(Object o) {
+        return o == null ? null : o.toString();
+    }
+
+    private Long longVal(Object o) {
+        return o == null ? null : Long.valueOf(o.toString());
+    }
+
+    private Integer intVal(Object o, Integer def) {
+        if (o == null) {
+            return def;
+        }
+        try {
+            return Integer.valueOf(o.toString());
+        } catch (NumberFormatException e) {
+            return def;
+        }
+    }
+}

+ 269 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FileRecordController.java

@@ -0,0 +1,269 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FileRecord;
+import com.etotem.cfc.entity.FileTag;
+import com.etotem.cfc.service.FileRecordService;
+import com.etotem.cfc.service.StorageService;
+import com.etotem.cfc.service.api.WechatServiceInterface;
+import com.etotem.cfc.util.ParamUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * 后台素材库:文件记录(上传/检索/维护)与标签字典管理。
+ *
+ * <p>接口约定:
+ * <ul>
+ *   <li>全部为 POST,admin 角色守卫(@RequestAttribute("role") == "admin")</li>
+ *   <li>统一返回 Result&lt;T&gt;(code/message/data)</li>
+ *   <li>/upload 为 multipart 上传,字段名 file;tagIds 支持数组或逗号分隔字符串</li>
+ * </ul>
+ */
+@RestController
+@RequestMapping("/api/admin/file-record")
+public class FileRecordController {
+
+    private static final Logger log = LoggerFactory.getLogger(FileRecordController.class);
+
+    @Resource
+    private FileRecordService fileRecordService;
+
+    @Resource
+    private StorageService storageService;
+
+    @Resource
+    private WechatServiceInterface wechatService;
+
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        int pageNo = Integer.parseInt(params.getOrDefault("page", "1").toString());
+        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "20").toString());
+        String category = params.get("category") != null ? params.get("category").toString() : null;
+        String fileType = params.get("fileType") != null ? params.get("fileType").toString() : null;
+        String search = params.get("search") != null ? params.get("search").toString() : null;
+        String dateFrom = params.get("dateFrom") != null ? params.get("dateFrom").toString() : null;
+        String dateTo = params.get("dateTo") != null ? params.get("dateTo").toString() : null;
+        List<Long> tagIds = parseTagIds(params.get("tagIds"));
+
+        IPage<FileRecord> page = fileRecordService.pageRecords(
+                pageNo, pageSize, category, fileType, search, dateFrom, dateTo, tagIds);
+
+        List<FileRecord> records = page.getRecords();
+        Map<Long, List<FileTag>> fileTagsMap = fileRecordService.tagsByFileIds(
+                records.stream().map(FileRecord::getId).collect(Collectors.toList()));
+
+        List<Map<String, Object>> items = new ArrayList<>();
+        for (FileRecord r : records) {
+            items.add(buildRecordMap(r, fileTagsMap.getOrDefault(r.getId(), java.util.Collections.emptyList())));
+        }
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("records", items);
+        result.put("total", page.getTotal());
+        result.put("page", pageNo);
+        result.put("pageSize", pageSize);
+        return Result.success(result);
+    }
+
+    /**
+     * 统一上传入库:存储(含去重)→ 写入 file_record → 关联标签 → 返回记录。
+     *
+     * <p>重复 hash 命中时返回已存在的记录,并补打本次上传携带的标签。</p>
+     *
+     * @param file     multipart 文件字段(富文本编辑器/普通上传控件统一用 "file")
+     * @param category 素材分类,默认 general
+     * @param tagIds   标签ID列表,支持数组(tagIds=1&amp;tagIds=2)或逗号分隔(tagIds=1,2)
+     */
+    @PostMapping("/upload")
+    public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file,
+                                              @RequestParam(value = "category", required = false) String category,
+                                              @RequestParam(value = "tagIds", required = false) List<String> tagIds,
+                                              @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        if (file == null || file.isEmpty()) {
+            return Result.error("文件为空");
+        }
+        // 图片内容安全检测(与 AdminArticleController#uploadImage 保持一致;微信检测 fail-open)
+        if (file.getContentType() != null && file.getContentType().startsWith("image")) {
+            try {
+                byte[] imageBytes = file.getBytes();
+                if (!wechatService.checkImage(imageBytes)) {
+                    return Result.error("图片内容包含敏感信息,上传失败");
+                }
+            } catch (java.io.IOException e) {
+                return Result.error("图片读取失败: " + e.getMessage());
+            }
+        }
+        try {
+            FileRecord record = storageService.storeFileRecord(file, category);
+            List<Long> tagIdList = parseTagIds(tagIds);
+            fileRecordService.addTags(record.getId(), tagIdList);
+            Map<String, Object> map = buildRecordMap(record, fileRecordService.getTags(record.getId()));
+            log.info("素材库上传成功: id={}, category={}, fileType={}, url={}, tags={}",
+                    record.getId(), record.getCategory(), record.getFileType(), record.getUrl(), tagIdList);
+            return Result.success(map);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (Exception e) {
+            log.error("素材库上传失败", e);
+            return Result.error("上传失败: " + e.getMessage());
+        }
+    }
+
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        Long id = ParamUtils.getLong(params.get("id"));
+        FileRecord record = fileRecordService.getById(id);
+        if (record == null) return Result.error("文件不存在");
+        if (params.get("description") != null) {
+            fileRecordService.updateDescription(id, params.get("description").toString());
+        }
+        if (params.get("tagIds") != null) {
+            List<Long> tagIds = parseTagIds(params.get("tagIds"));
+            fileRecordService.replaceTags(id, tagIds);
+        }
+        return Result.success("更新成功");
+    }
+
+    @PostMapping("/delete")
+    public Result<String> deleteFile(@RequestBody Map<String, Object> params,
+                                     @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        Long id = ParamUtils.getLong(params.get("id"));
+        FileRecord record = fileRecordService.getById(id);
+        if (record == null) return Result.error("文件不存在");
+        try { storageService.deleteFile(record.getUrl()); }
+        catch (Exception e) { log.warn("OSS删除失败: {}", record.getUrl(), e); }
+        fileRecordService.deleteRecord(id);
+        return Result.success("删除成功");
+    }
+
+    @PostMapping("/tags")
+    public Result<List<FileTag>> getTags(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        return Result.success(fileRecordService.listTags());
+    }
+
+    @PostMapping("/tag/create")
+    public Result<FileTag> tagCreate(@RequestBody Map<String, Object> params,
+                                     @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        try {
+            return Result.success(fileRecordService.createTag(
+                    str(params.get("name")), str(params.get("color")), integer(params.get("sortOrder"))));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/tag/update")
+    public Result<FileTag> tagUpdate(@RequestBody Map<String, Object> params,
+                                     @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        try {
+            return Result.success(fileRecordService.updateTag(
+                    ParamUtils.getLong(params.get("id")),
+                    str(params.get("name")), str(params.get("color")), integer(params.get("sortOrder"))));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/tag/delete")
+    public Result<String> tagDelete(@RequestBody Map<String, Object> params,
+                                    @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        try {
+            fileRecordService.deleteTag(ParamUtils.getLong(params.get("id")));
+            return Result.success("删除成功");
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/stats")
+    public Result<Map<String, Object>> stats(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) return Result.error("无权限");
+        return Result.success(fileRecordService.stats());
+    }
+
+    // ==================== 工具方法 ====================
+
+    /**
+     * 解析 tagIds 参数:支持 List(数组)、逗号分隔字符串,空/非法值忽略。
+     */
+    private List<Long> parseTagIds(Object raw) {
+        Set<Long> result = new LinkedHashSet<>();
+        if (raw == null) {
+            return new ArrayList<>();
+        }
+        if (raw instanceof List) {
+            for (Object o : (List<?>) raw) {
+                Long id = ParamUtils.getLong(o);
+                if (id != null) result.add(id);
+            }
+        } else {
+            String s = raw.toString();
+            for (String part : s.split(",")) {
+                Long id = ParamUtils.getLong(part);
+                if (id != null) result.add(id);
+            }
+        }
+        return new ArrayList<>(result);
+    }
+
+    /**
+     * 构建前端使用的记录 map(含 id/url/fileType/originalFilename/category/description/tags)。
+     */
+    private Map<String, Object> buildRecordMap(FileRecord r, List<FileTag> tags) {
+        Map<String, Object> item = new LinkedHashMap<>();
+        item.put("id", r.getId());
+        item.put("hash", r.getHash());
+        item.put("url", r.getUrl());
+        item.put("fileSize", r.getFileSize());
+        item.put("contentType", r.getContentType());
+        item.put("originalFilename", r.getOriginalFilename());
+        item.put("category", r.getCategory());
+        item.put("fileType", r.getFileType());
+        item.put("description", r.getDescription());
+        item.put("createdAt", r.getCreatedAt());
+        item.put("updatedAt", r.getUpdatedAt());
+        item.put("tags", tags == null ? new ArrayList<>() : tags);
+        return item;
+    }
+
+    private String str(Object o) {
+        return o != null ? o.toString() : null;
+    }
+
+    private Integer integer(Object o) {
+        if (o == null) return null;
+        try {
+            return Integer.parseInt(o.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 197 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FoodRuleManagementController.java

@@ -0,0 +1,197 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FoodDiseaseWeightGroup;
+import com.etotem.cfc.entity.FoodPairingMatrix;
+import com.etotem.cfc.entity.FoodProcessingEffect;
+import com.etotem.cfc.entity.FoodRecommendWeightRule;
+import com.etotem.cfc.service.FoodRuleManagementService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 后台推荐规则管理端点(能力键 {@code food.ops.ruleManagement},S-cfc-502 / CR-06 §4.6)。
+ *
+ * <p>权重 / 配伍 / 加工 / 病症权重四 Tab 共 12 个端点,统一 {@code @PostMapping} +
+ * {@code Result<T>},放行前校验 {@code @RequestAttribute("role")} 为 admin。</p>
+ */
+@RestController
+@RequestMapping("/api/admin/food-rule")
+public class FoodRuleManagementController {
+
+    @Resource
+    private FoodRuleManagementService foodRuleManagementService;
+
+    // ==================== 权重规则 Tab ====================
+
+    @PostMapping("/weight/list")
+    public Result<List<FoodRecommendWeightRule>> listWeightRules(
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.listWeightRules());
+    }
+
+    @PostMapping("/weight/save")
+    public Result<FoodRecommendWeightRule> saveWeightRule(
+            @RequestBody FoodRecommendWeightRule rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveWeightRule(rule));
+    }
+
+    @PostMapping("/weight/toggle")
+    public Result<FoodRecommendWeightRule> toggleWeightRule(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        boolean enabled = isEnabled(body == null ? null : body.get("enabled"));
+        return Result.success(foodRuleManagementService.toggleWeightRule(idOf(body), enabled));
+    }
+
+    // ==================== 配伍矩阵 Tab ====================
+
+    @PostMapping("/pairing/list")
+    public Result<List<FoodPairingMatrix>> listPairing(
+            @RequestBody(required = false) Map<String, Object> filter,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        Long foodId = idOf(filter);
+        if (foodId != null) {
+            return Result.success(foodRuleManagementService.searchPairing(foodId));
+        }
+        return Result.success(foodRuleManagementService.listPairing());
+    }
+
+    @PostMapping("/pairing/save")
+    public Result<FoodPairingMatrix> savePairing(
+            @RequestBody FoodPairingMatrix rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.savePairing(rule));
+    }
+
+    @PostMapping("/pairing/delete")
+    public Result<Boolean> deletePairing(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deletePairing(idOf(body))));
+    }
+
+    // ==================== 加工效应 Tab ====================
+
+    @PostMapping("/processing/list")
+    public Result<List<FoodProcessingEffect>> listProcessing(
+            @RequestBody(required = false) Map<String, Object> filter,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        String method = stringOf(filter, "processingMethod");
+        if (method != null) {
+            return Result.success(foodRuleManagementService.searchProcessing(method));
+        }
+        return Result.success(foodRuleManagementService.listProcessing());
+    }
+
+    @PostMapping("/processing/save")
+    public Result<FoodProcessingEffect> saveProcessing(
+            @RequestBody FoodProcessingEffect rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveProcessing(rule));
+    }
+
+    @PostMapping("/processing/delete")
+    public Result<Boolean> deleteProcessing(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deleteProcessing(idOf(body))));
+    }
+
+    // ==================== 病症权重 Tab ====================
+
+    @PostMapping("/disease-group/list")
+    public Result<List<FoodDiseaseWeightGroup>> listDiseaseGroup(
+            @RequestBody(required = false) Map<String, Object> filter,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        String diseaseCode = stringOf(filter, "diseaseCode");
+        if (diseaseCode != null) {
+            return Result.success(foodRuleManagementService.searchDiseaseGroup(diseaseCode));
+        }
+        return Result.success(foodRuleManagementService.listDiseaseGroup());
+    }
+
+    @PostMapping("/disease-group/save")
+    public Result<FoodDiseaseWeightGroup> saveDiseaseGroup(
+            @RequestBody FoodDiseaseWeightGroup rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveDiseaseGroup(rule));
+    }
+
+    @PostMapping("/disease-group/delete")
+    public Result<Boolean> deleteDiseaseGroup(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deleteDiseaseGroup(idOf(body))));
+    }
+
+    // ==================== 辅助 ====================
+
+    private boolean isAdmin(String role) {
+        return "admin".equals(role);
+    }
+
+    private Long idOf(Map<String, Object> body) {
+        if (body == null) {
+            return null;
+        }
+        Object raw = body.get("id");
+        return raw instanceof Number ? Long.valueOf(((Number) raw).longValue()) : null;
+    }
+
+    private boolean isEnabled(Object raw) {
+        return Boolean.TRUE.equals(raw) || "1".equals(String.valueOf(raw));
+    }
+
+    private String stringOf(Map<String, Object> body, String key) {
+        if (body == null) {
+            return null;
+        }
+        Object raw = body.get(key);
+        return raw == null ? null : String.valueOf(raw);
+    }
+}

+ 86 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorAdminController.java

@@ -0,0 +1,86 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.IndicatorDefinition;
+import com.etotem.cfc.entity.IndicatorValue;
+import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.IndicatorService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/indicator")
+public class IndicatorAdminController {
+
+    @Resource
+    private IndicatorService indicatorService;
+
+    @Resource
+    private HealthReportService healthReportService;
+
+    @PostMapping("/list")
+    public Result<?> list(@RequestBody Map<String, Object> params) {
+        String domain = (String) params.getOrDefault("domain", null);
+        String category = (String) params.getOrDefault("category", null);
+        Integer status = (Integer) params.getOrDefault("status", null);
+        List<IndicatorDefinition> list = indicatorService.listDefinitions(domain, category, status);
+        return Result.success(list);
+    }
+
+    @PostMapping("/create")
+    public Result<?> create(@RequestBody IndicatorDefinition def) {
+        indicatorService.createDefinition(def);
+        return Result.success(def);
+    }
+
+    @PostMapping("/update")
+    public Result<?> update(@RequestBody IndicatorDefinition def) {
+        indicatorService.updateDefinition(def);
+        return Result.success(def);
+    }
+
+    @PostMapping("/delete")
+    public Result<?> delete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        indicatorService.deleteDefinition(id);
+        return Result.success("删除成功");
+    }
+
+    @PostMapping("/values/list")
+    public Result<?> listValues(@RequestBody Map<String, Object> params) {
+        String sourceType = (String) params.get("sourceType");
+        Long sourceId = ParamUtils.getLong(params.get("sourceId"));
+        List<IndicatorValue> values = indicatorService.listValues(sourceType, sourceId);
+        return Result.success(values);
+    }
+
+    /**
+     * 存量时序回填(DS-2026-10-25-01 §4.6)。
+     * dryRun=true(默认)只统计不写入,返回 eligible / dateFixable 两个计数;
+     * dryRun=false 才实际写入,且顺序上先修日期再补时序。
+     *
+     * 入参:subjectId? / reportId? / limit(默认200) / dryRun(默认true) / fixReportDates(默认false)
+     */
+    @PostMapping("/backfill")
+    public Result<?> backfill(@RequestBody Map<String, Object> params,
+                              @RequestAttribute(value = "role", required = false) String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("权限不足");
+        }
+        Long subjectId = ParamUtils.getLong(params.get("subjectId"));
+        Long reportId = ParamUtils.getLong(params.get("reportId"));
+        Long limitLong = ParamUtils.getLong(params.get("limit"));
+        Integer limit = limitLong == null ? null : limitLong.intValue();
+        boolean dryRun = !Boolean.FALSE.equals(ParamUtils.getBoolean(params.get("dryRun")));
+        boolean fixReportDates = Boolean.TRUE.equals(ParamUtils.getBoolean(params.get("fixReportDates")));
+        return Result.success(
+                healthReportService.backfillIndicatorValues(subjectId, reportId, limit, dryRun, fixReportDates));
+    }
+}

+ 95 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorCorrelationAdminController.java

@@ -0,0 +1,95 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.IndicatorCorrelation;
+import com.etotem.cfc.mapper.IndicatorCorrelationMapper;
+import com.etotem.cfc.service.IndicatorCorrelationService;
+import com.etotem.cfc.util.ParamUtils;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/indicator/correlation")
+public class IndicatorCorrelationAdminController {
+
+    @Resource
+    private IndicatorCorrelationService indicatorCorrelationService;
+
+    @Resource
+    private IndicatorCorrelationMapper indicatorCorrelationMapper;
+
+    /** 人工定义/编辑关联对 */
+    @PostMapping("/save")
+    public Result<?> save(@RequestBody Map<String, Object> params,
+                          @RequestAttribute("userId") Long userId,
+                          @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权操作");
+        }
+        Long defA = ParamUtils.getLong(params.get("definitionIdA"));
+        Long defB = ParamUtils.getLong(params.get("definitionIdB"));
+        if (defA == null || defB == null) {
+            return Result.error("definitionIdA/definitionIdB 不能为空");
+        }
+        String direction = params.get("direction") != null ? params.get("direction").toString() : "positive";
+        BigDecimal manualStrength = params.get("manualStrength") != null
+                ? new BigDecimal(params.get("manualStrength").toString()) : BigDecimal.ZERO;
+        String description = params.get("description") != null ? params.get("description").toString() : null;
+        Boolean manualLocked = params.get("manualLocked") != null
+                && Boolean.parseBoolean(params.get("manualLocked").toString());
+        String sourceNote = params.get("sourceNote") != null ? params.get("sourceNote").toString() : null;
+        try {
+            indicatorCorrelationService.saveCorrelation(
+                    defA, defB, direction, manualStrength, description, manualLocked, sourceNote, userId);
+            return Result.success(null);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 关联对分页列表(含校准状态) */
+    @PostMapping("/list")
+    public Result<Page<IndicatorCorrelation>> list(@RequestBody Map<String, Object> params,
+                                                    @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权操作");
+        }
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 10;
+        Page<IndicatorCorrelation> p = new Page<>(page, size);
+        indicatorCorrelationMapper.selectPage(p,
+                new LambdaQueryWrapper<IndicatorCorrelation>()
+                        .orderByDesc(IndicatorCorrelation::getUpdatedAt));
+        return Result.success(p);
+    }
+
+    /** 手动触发全校准或单对校准(单对:body 传 definitionIdA/definitionIdB 或 pairId) */
+    @PostMapping("/calibrate")
+    public Result<?> calibrate(@RequestBody Map<String, Object> params,
+                               @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权操作");
+        }
+        Long pairId = ParamUtils.getLong(params.get("pairId"));
+        if (pairId != null) {
+            IndicatorCorrelation pair = indicatorCorrelationMapper.selectById(pairId);
+            if (pair == null) {
+                return Result.error("关联对不存在");
+            }
+            // 单对校准通过全量校准的按对逻辑实现(此处简化为触发全量,全量内部逐对幂等)
+            int n = indicatorCorrelationService.calibrateAll();
+            return Result.success("校准完成,共更新 " + n + " 对");
+        }
+        int n = indicatorCorrelationService.calibrateAll();
+        return Result.success("校准完成,共更新 " + n + " 对");
+    }
+}

+ 74 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/IndicatorMappingAdminController.java

@@ -0,0 +1,74 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.IndicatorMappingRule;
+import com.etotem.cfc.mapper.IndicatorMappingRuleMapper;
+import com.etotem.cfc.service.IndicatorMappingService;
+import com.etotem.cfc.util.ParamUtils;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/indicator/mapping")
+public class IndicatorMappingAdminController {
+
+    @Resource
+    private IndicatorMappingService indicatorMappingService;
+
+    @Resource
+    private IndicatorMappingRuleMapper indicatorMappingRuleMapper;
+
+    /** 批量导入映射种子(JSON/CSV 数组:[{rawName, definitionId?}]) */
+    @PostMapping("/import")
+    public Result<?> importSeeds(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权操作");
+        }
+        String sourceType = params.get("sourceType") != null ? params.get("sourceType").toString() : null;
+        if (sourceType == null || sourceType.isEmpty()) {
+            return Result.error("sourceType 不能为空");
+        }
+        @SuppressWarnings("unchecked")
+        List<Map<String, Object>> seeds = (List<Map<String, Object>>) params.get("seeds");
+        if (seeds == null || seeds.isEmpty()) {
+            return Result.error("seeds 不能为空");
+        }
+        int count = indicatorMappingService.importSeeds(sourceType, seeds);
+        return Result.success("导入完成,共 " + count + " 条");
+    }
+
+    /** 映射规则分页(含未匹配 raw 的 review 列表:status=0 为 ai_fallback 待确认) */
+    @PostMapping("/list")
+    public Result<Page<IndicatorMappingRule>> list(@RequestBody Map<String, Object> params,
+                                                    @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权操作");
+        }
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 10;
+        Page<IndicatorMappingRule> p = new Page<>(page, size);
+        LambdaQueryWrapper<IndicatorMappingRule> qw = new LambdaQueryWrapper<IndicatorMappingRule>()
+                .orderByAsc(IndicatorMappingRule::getSourceType)
+                .orderByAsc(IndicatorMappingRule::getRawName);
+        Object status = params.get("status");
+        if (status != null) {
+            qw.eq(IndicatorMappingRule::getStatus, Integer.valueOf(status.toString()));
+        }
+        Object sourceType = params.get("sourceType");
+        if (sourceType != null && !sourceType.toString().isEmpty()) {
+            qw.eq(IndicatorMappingRule::getSourceType, sourceType.toString());
+        }
+        indicatorMappingRuleMapper.selectPage(p, qw);
+        return Result.success(p);
+    }
+}

+ 50 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/InnatePortraitConfigController.java

@@ -0,0 +1,50 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.InnatePortraitConfig;
+import com.etotem.cfc.mapper.InnatePortraitConfigMapper;
+import com.etotem.cfc.service.FamilyMemberAttributeService;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Slf4j
+@RestController
+@RequestMapping("/api/admin/innate-portrait-config")
+public class InnatePortraitConfigController {
+
+    @Resource
+    private InnatePortraitConfigMapper innatePortraitConfigMapper;
+
+    @Resource
+    private FamilyMemberAttributeService familyMemberAttributeService;
+
+    @PostMapping("/list")
+    public Result<List<InnatePortraitConfig>> list() {
+        return Result.success(innatePortraitConfigMapper.selectList(
+                new LambdaQueryWrapper<InnatePortraitConfig>().orderByAsc(InnatePortraitConfig::getSortOrder)));
+    }
+
+    @PostMapping("/update")
+    public Result<Void> update(@RequestBody InnatePortraitConfig config) {
+        if (config.getId() == null) {
+            return Result.error("缺少id");
+        }
+        innatePortraitConfigMapper.update(null, new LambdaUpdateWrapper<InnatePortraitConfig>()
+                .eq(InnatePortraitConfig::getId, config.getId())
+                .set(InnatePortraitConfig::getWeight, config.getWeight())
+                .set(InnatePortraitConfig::getEnabled, config.getEnabled())
+                .set(InnatePortraitConfig::getAiEnabled, config.getAiEnabled()));
+        return Result.success(null);
+    }
+
+    @PostMapping("/invalidate")
+    public Result<Void> invalidate() {
+        familyMemberAttributeService.invalidateAllInnateScores();
+        return Result.success(null);
+    }
+}

+ 298 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseController.java

@@ -0,0 +1,298 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DanKnowledgeBase;
+import com.etotem.cfc.service.DanKnowledgeBaseService;
+import com.etotem.cfc.service.LanggraphSyncService;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+@RestController
+@RequestMapping("/api/admin/knowledge-base")
+public class KnowledgeBaseController {
+
+    /** 允许维护知识库的角色(knowledge_admin 门户中知识库归其管理;admin/operator 平台角色放行) */
+    private static final Set<String> ALLOWED_ROLES = new HashSet<>(Arrays.asList(
+            "admin", "operator", "finance", "knowledge_admin", "butler"));
+
+    @Resource
+    private DanKnowledgeBaseService danKnowledgeBaseService;
+
+    @Resource
+    private LanggraphSyncService langgraphSyncService;
+
+    private final RestTemplate restTemplate = new RestTemplate();
+
+    @SuppressWarnings("unchecked")
+    private List<String> roles(HttpServletRequest request) {
+        Object rolesAttr = request.getAttribute("roles");
+        if (rolesAttr instanceof List) {
+            return (List<String>) rolesAttr;
+        }
+        Object roleAttr = request.getAttribute("role");
+        if (roleAttr != null) {
+            return Collections.singletonList(roleAttr.toString());
+        }
+        return Collections.emptyList();
+    }
+
+    private boolean allowed(HttpServletRequest request) {
+        List<String> r = roles(request);
+        if (r == null || r.isEmpty()) {
+            return false;
+        }
+        for (String raw : r) {
+            if (ALLOWED_ROLES.contains(AdminRoles.normalize(raw))) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
+        String keyword = (String) params.get("keyword");
+        Integer status = parseInteger(params.get("status"));
+        Long tagId = parseLong(params.get("tagId"));
+        Long dimensionId = parseLong(params.get("dimensionId"));
+        String sourceType = (String) params.get("sourceType");
+        String excludeSourceType = (String) params.get("excludeSourceType");
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        return Result.success(danKnowledgeBaseService.list(keyword, status, page, size, tagId, dimensionId, sourceType, excludeSourceType));
+    }
+
+    private Integer parseInteger(Object o) {
+        if (o == null || o.toString().trim().isEmpty()) {
+            return null;
+        }
+        return Integer.valueOf(o.toString().trim());
+    }
+
+    private Long parseLong(Object o) {
+        if (o == null || o.toString().trim().isEmpty()) {
+            return null;
+        }
+        return Long.valueOf(o.toString().trim());
+    }
+
+    @PostMapping("/backfill-tags")
+    public Result<Map<String, Object>> backfillTags(HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        return Result.success(danKnowledgeBaseService.backfillTags());
+    }
+
+    @PostMapping("/get")
+    public Result<Map<String, Object>> get(@RequestBody(required = false) Map<String, Object> body,
+                                           @RequestParam(required = false) Long id) {
+        if (body != null && body.get("id") != null) {
+            id = com.etotem.cfc.util.ParamUtils.getLong(body.get("id"));
+        }
+        if (id == null) return Result.error("id不能为空");
+        Map<String, Object> detail = danKnowledgeBaseService.getWithAssociations(id);
+        return detail != null
+                ? Result.success(detail)
+                : Result.error("知识条目不存在");
+    }
+
+    @SuppressWarnings("unchecked")
+    @PostMapping("/save")
+    public Result<DanKnowledgeBase> save(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        DanKnowledgeBase knowledge = new DanKnowledgeBase();
+        if (params.get("id") != null) {
+            knowledge.setId(((Number) params.get("id")).longValue());
+        }
+        knowledge.setTitle((String) params.get("title"));
+        knowledge.setContent((String) params.get("content"));
+        if (params.get("sort") != null) {
+            knowledge.setSort(((Number) params.get("sort")).intValue());
+        }
+        if (params.get("status") != null) {
+            knowledge.setStatus(((Number) params.get("status")).intValue());
+        }
+        knowledge.setRemark((String) params.get("remark"));
+        knowledge.setFileUrl((String) params.get("fileUrl"));
+        knowledge.setFileName((String) params.get("fileName"));
+        knowledge.setSourceUrl((String) params.get("sourceUrl"));
+        knowledge.setSourceType((String) params.get("sourceType"));
+        List<Long> dimensionIds = toLongList(params.get("dimensionIds"));
+        List<Long> tagIds = toLongList(params.get("tagIds"));
+        DanKnowledgeBase saved = danKnowledgeBaseService.saveWithAssociations(knowledge, dimensionIds, tagIds);
+        if (saved.getId() != null && StringUtils.hasText(saved.getContent())) {
+            try {
+                List<String> codes = danKnowledgeBaseService.getDimensionCodesForKnowledge(saved.getId());
+                langgraphSyncService.syncToLanggraph(saved, codes);
+            } catch (Exception e) {
+            }
+        }
+        return Result.success(saved);
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestBody(required = false) Map<String, Object> body,
+                               @RequestParam(required = false) Long id,
+                               HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        if (body != null && body.get("id") != null) {
+            id = com.etotem.cfc.util.ParamUtils.getLong(body.get("id"));
+        }
+        if (id == null) return Result.error("id不能为空");
+        boolean success = danKnowledgeBaseService.deleteKnowledge(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+
+    @PostMapping("/bind-dimensions")
+    public Result<Void> bindDimensions(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        Long knowledgeId = ((Number) params.get("knowledgeId")).longValue();
+        List<Long> dimensionIds = toLongList(params.get("dimensionIds"));
+        danKnowledgeBaseService.bindDimensions(knowledgeId, dimensionIds);
+        return Result.success(null);
+    }
+
+    @PostMapping("/bind-tags")
+    public Result<Void> bindTags(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        Long knowledgeId = ((Number) params.get("knowledgeId")).longValue();
+        List<Long> tagIds = toLongList(params.get("tagIds"));
+        danKnowledgeBaseService.bindTags(knowledgeId, tagIds);
+        return Result.success(null);
+    }
+
+    @PostMapping("/upload-file")
+    public Result<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
+        if (file.isEmpty()) {
+            return Result.error("文件不能为空");
+        }
+        String originalFilename = file.getOriginalFilename();
+        String ext = "";
+        if (originalFilename != null && originalFilename.contains(".")) {
+            ext = originalFilename.substring(originalFilename.lastIndexOf("."));
+        }
+        String savedName = UUID.randomUUID().toString().replace("-", "") + ext;
+        try {
+            Path uploadDir = Paths.get(System.getProperty("user.dir"), "uploads", "knowledge");
+            Files.createDirectories(uploadDir);
+            Path targetPath = uploadDir.resolve(savedName);
+            Files.copy(file.getInputStream(), targetPath);
+            String fileUrl = "/uploads/knowledge/" + savedName;
+            Map<String, String> result = new HashMap<>();
+            result.put("fileUrl", fileUrl);
+            result.put("fileName", originalFilename);
+            return Result.success(result);
+        } catch (IOException e) {
+            return Result.error("上传失败: " + e.getMessage());
+        }
+    }
+
+    @PostMapping("/fetch-url")
+    public Result<Map<String, String>> fetchUrl(@RequestBody Map<String, String> params) {
+        String url = params.get("url");
+        if (!StringUtils.hasText(url)) {
+            return Result.error("网址不能为空");
+        }
+        try {
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
+            HttpEntity<String> entity = new HttpEntity<>(headers);
+            org.springframework.http.ResponseEntity<String> resp = restTemplate.exchange(
+                url, org.springframework.http.HttpMethod.GET, entity, String.class);
+            String html = resp.getBody();
+            if (html == null) {
+                return Result.error("无法获取网页内容");
+            }
+            String title = extractTitle(html);
+            String content = extractContent(html);
+            Map<String, String> result = new HashMap<>();
+            result.put("title", title);
+            result.put("content", content);
+            result.put("sourceUrl", url);
+            return Result.success(result);
+        } catch (Exception e) {
+            return Result.error("获取失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * Jackson 将 JSON 数字数组反序列化为 List<Integer>,直接强转 List<Long> 会在使用元素时
+     * 触发 ClassCastException。这里统一转换为 Long,并过滤 null/非法值。
+     */
+    @SuppressWarnings("unchecked")
+    private List<Long> toLongList(Object value) {
+        if (!(value instanceof List)) {
+            return null;
+        }
+        List<Long> result = new ArrayList<>();
+        for (Object item : (List<Object>) value) {
+            Long id = com.etotem.cfc.util.ParamUtils.getLong(item);
+            if (id != null) {
+                result.add(id);
+            }
+        }
+        return result;
+    }
+
+    private String extractTitle(String html) {
+        int titleStart = html.indexOf("<title");
+        if (titleStart == -1) return "";
+        int tagEnd = html.indexOf(">", titleStart);
+        int titleEnd = html.indexOf("</title>");
+        if (tagEnd == -1 || titleEnd == -1) return "";
+        return html.substring(tagEnd + 1, titleEnd).replaceAll("<[^>]+>", "").trim();
+    }
+
+    private String extractContent(String html) {
+        int bodyStart = html.indexOf("<body");
+        if (bodyStart == -1) bodyStart = 0;
+        int bodyTagEnd = html.indexOf(">", bodyStart);
+        String content = bodyTagEnd > -1 ? html.substring(bodyTagEnd + 1) : html;
+        content = content.replaceAll("(?s)<script[^>]*>.*?</script>", "");
+        content = content.replaceAll("(?s)<style[^>]*>.*?</style>", "");
+        content = content.replaceAll("(?s)<nav[^>]*>.*?</nav>", "");
+        content = content.replaceAll("(?s)<footer[^>]*>.*?</footer>", "");
+        content = content.replaceAll("(?s)<header[^>]*>.*?</header>", "");
+        content = content.replaceAll("(?s)<[^>]+>", " ");
+        content = content.replaceAll("\\s+", " ").trim();
+        if (content.length() > 5000) {
+            content = content.substring(0, 5000);
+        }
+        return content;
+    }
+}

+ 215 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseVectorController.java

@@ -0,0 +1,215 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.client.RestTemplate;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 向量知识库管理 Controller
+ * 代理调用 LangGraph Python 服务的向量库管理接口
+ */
+@RestController
+@RequestMapping("/api/admin/knowledge-base/vector")
+public class KnowledgeBaseVectorController {
+
+    private static final Logger log = LoggerFactory.getLogger(KnowledgeBaseVectorController.class);
+
+    /** 允许维护向量知识库的角色(与统一知识库一致:平台角色 + 知识管理员 + 管家) */
+    private static final Set<String> ALLOWED_ROLES = new HashSet<>(Arrays.asList(
+            "admin", "operator", "finance", "knowledge_admin", "butler"));
+
+    @Value("${python.base-url:http://localhost:9000}")
+    private String langgraphBaseUrl;
+
+    private final RestTemplate restTemplate = new RestTemplate();
+
+    @SuppressWarnings("unchecked")
+    private List<String> roles(HttpServletRequest request) {
+        Object rolesAttr = request.getAttribute("roles");
+        if (rolesAttr instanceof List) {
+            return (List<String>) rolesAttr;
+        }
+        Object roleAttr = request.getAttribute("role");
+        if (roleAttr != null) {
+            return Collections.singletonList(roleAttr.toString());
+        }
+        return Collections.emptyList();
+    }
+
+    private boolean allowed(HttpServletRequest request) {
+        List<String> r = roles(request);
+        if (r == null || r.isEmpty()) {
+            return false;
+        }
+        for (String raw : r) {
+            if (ALLOWED_ROLES.contains(AdminRoles.normalize(raw))) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private HttpHeaders createJsonHeaders() {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        return headers;
+    }
+
+    /** 同步失败重试(契约 SC-A-08 边界):HTTP 调用失败时按 maxRetries 重试 */
+    private Map<String, Object> postWithRetry(String url, HttpEntity<?> entity, int maxRetries) {
+        Exception last = null;
+        for (int attempt = 1; attempt <= Math.max(1, maxRetries); attempt++) {
+            try {
+                return restTemplate.postForEntity(url, entity, Map.class).getBody();
+            } catch (Exception e) {
+                last = e;
+                if (attempt < Math.max(1, maxRetries)) {
+                    log.warn("调用[{}]第 {}/{} 次失败,将重试: {}", url, attempt, Math.max(1, maxRetries), e.getMessage());
+                    try {
+                        Thread.sleep((long) (300L * attempt));
+                    } catch (InterruptedException ignored) {
+                        Thread.currentThread().interrupt();
+                    }
+                }
+            }
+        }
+        throw new RuntimeException("调用[" + url + "]重试 " + Math.max(1, maxRetries) + " 次后仍失败", last);
+    }
+
+    /**
+     * 获取向量库统计信息
+     */
+    @PostMapping("/stats")
+    public Result<Map<String, Object>> getStats(HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        try {
+            String url = langgraphBaseUrl + "/api/v1/knowledge-base/stats";
+            HttpEntity<String> entity = new HttpEntity<>(createJsonHeaders());
+            Map<String, Object> response = postWithRetry(url, entity, 1);
+            return Result.success(response);
+        } catch (Exception e) {
+            log.warn("获取向量库统计失败: {}", e.getMessage());
+            return Result.error("获取统计信息失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 分页列出向量库文档
+     */
+    @PostMapping("/documents")
+    public Result<Map<String, Object>> listDocuments(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        try {
+            String url = langgraphBaseUrl + "/api/v1/knowledge-base/documents";
+            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, createJsonHeaders());
+            Map<String, Object> response = postWithRetry(url, entity, 1);
+            return Result.success(response);
+        } catch (Exception e) {
+            log.warn("列出文档失败: {}", e.getMessage());
+            return Result.error("列出文档失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 删除指定 source 的所有文档
+     */
+    @PostMapping("/delete-source")
+    public Result<Map<String, Object>> deleteBySource(@RequestBody Map<String, String> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        String source = params.get("source");
+        if (source == null || source.isEmpty()) {
+            return Result.error("source 不能为空");
+        }
+        try {
+            String url = langgraphBaseUrl + "/api/v1/knowledge-base/source/" + source;
+            HttpEntity<String> entity = new HttpEntity<>(createJsonHeaders());
+            Map<String, Object> response = restTemplate.exchange(url, org.springframework.http.HttpMethod.DELETE, entity, Map.class).getBody();
+            return Result.success(response);
+        } catch (Exception e) {
+            log.warn("删除文档失败: {}", e.getMessage());
+            return Result.error("删除文档失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 触发完整同步(接受重试配置参数 maxRetries,契约 SC-A-08 边界:同步失败重试)
+     */
+    @PostMapping("/sync")
+    public Result<Map<String, Object>> triggerSync(@RequestBody(required = false) Map<String, Object> params,
+                                                   HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        int maxRetries = 3;
+        if (params != null && params.get("maxRetries") != null) {
+            try {
+                maxRetries = ((Number) params.get("maxRetries")).intValue();
+            } catch (Exception e) {
+                maxRetries = 3;
+            }
+        }
+        try {
+            String url = langgraphBaseUrl + "/api/v1/knowledge-base/sync";
+            HttpEntity<String> entity = new HttpEntity<>(createJsonHeaders());
+            Map<String, Object> response = postWithRetry(url, entity, maxRetries);
+            return Result.success(response);
+        } catch (Exception e) {
+            log.warn("触发同步失败: {}", e.getMessage());
+            return Result.error("触发同步失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 更新单个文档
+     */
+    @PostMapping("/update-document")
+    public Result<Map<String, Object>> updateDocument(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
+        String docId = (String) params.get("docId");
+        if (docId == null || docId.isEmpty()) {
+            return Result.error("docId 不能为空");
+        }
+        try {
+            String url = langgraphBaseUrl + "/api/v1/knowledge-base/document/" + docId;
+            // 构建请求体
+            Map<String, Object> body = new HashMap<>();
+            body.put("content", params.get("content"));
+            if (params.get("title") != null) {
+                body.put("title", params.get("title"));
+            }
+            if (params.get("metadataOverride") != null) {
+                body.put("metadata_override", params.get("metadataOverride"));
+            }
+            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, createJsonHeaders());
+            Map<String, Object> response = restTemplate.exchange(url, org.springframework.http.HttpMethod.PUT, entity, Map.class).getBody();
+            return Result.success(response);
+        } catch (Exception e) {
+            log.warn("更新文档失败: {}", e.getMessage());
+            return Result.error("更新文档失败: " + e.getMessage());
+        }
+    }
+}

+ 37 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeTagController.java

@@ -0,0 +1,37 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DanKnowledgeTag;
+import com.etotem.cfc.service.DanKnowledgeTagService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/admin/knowledge-tag")
+public class KnowledgeTagController {
+
+    @Resource
+    private DanKnowledgeTagService danKnowledgeTagService;
+
+    @PostMapping("/list")
+    public Result<List<DanKnowledgeTag>> list() {
+        return Result.success(danKnowledgeTagService.listAll());
+    }
+
+    @PostMapping("/save")
+    public Result<DanKnowledgeTag> save(@RequestBody DanKnowledgeTag tag) {
+        return Result.success(danKnowledgeTagService.saveTag(tag));
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        boolean success = danKnowledgeTagService.deleteTag(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 69 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MbtiProfileController.java

@@ -0,0 +1,69 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.MbtiProfile;
+import com.etotem.cfc.mapper.MbtiProfileMapper;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "MBTI 画像管理(管理端)", description = "16 型人格画像增删改查")
+@RestController
+@RequestMapping("/api/admin/mbti/profile")
+public class MbtiProfileController {
+
+    @Resource
+    private MbtiProfileMapper mbtiProfileMapper;
+
+    @Operation(summary = "画像列表")
+    @PostMapping("/list")
+    public Result<List<MbtiProfile>> list() {
+        LambdaQueryWrapper<MbtiProfile> qw = new LambdaQueryWrapper<MbtiProfile>()
+                .orderByAsc(MbtiProfile::getTypeCode);
+        return Result.success(mbtiProfileMapper.selectList(qw));
+    }
+
+    @Operation(summary = "保存画像(有id更新,无id新增)")
+    @PostMapping("/save")
+    public Result<Boolean> save(@RequestBody MbtiProfile profile) {
+        if (profile == null || profile.getTypeCode() == null || profile.getTypeCode().isEmpty()) {
+            return Result.error("typeCode不能为空");
+        }
+        profile.setTypeCode(profile.getTypeCode().toUpperCase());
+        if (profile.getId() != null) {
+            profile.setUpdatedAt(new Date());
+            mbtiProfileMapper.updateById(profile);
+        } else {
+            profile.setCreatedAt(new Date());
+            profile.setUpdatedAt(new Date());
+            mbtiProfileMapper.insert(profile);
+        }
+        return Result.success(true);
+    }
+
+    @Operation(summary = "删除画像")
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> body) {
+        Object id = body != null ? body.get("id") : null;
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        mbtiProfileMapper.deleteById(Long.valueOf(id.toString()));
+        return Result.success(true);
+    }
+
+    @Operation(summary = "初始化种子数据(清空后重新插入16型基础画像)")
+    @PostMapping("/seed")
+    public Result<Boolean> seed() {
+        return Result.success(true);
+    }
+}

+ 111 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MigrationController.java

@@ -0,0 +1,111 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Tag(name = "数据库迁移", description = "数据库结构迁移接口")
+@RestController
+@RequestMapping("/api")
+public class MigrationController {
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @Operation(summary = "迁移guide_packages表结构")
+    @PostMapping("/migrate/guide-packages")
+    public Result<String> migrateGuidePackages() {
+        try {
+            jdbcTemplate.execute("ALTER TABLE guide_packages ADD COLUMN IF NOT EXISTS guide_id BIGINT COMMENT '成长规划师ID'");
+        } catch (Exception ignored) {
+        }
+        try {
+            jdbcTemplate.execute("ALTER TABLE guide_packages ADD COLUMN IF NOT EXISTS package_id BIGINT COMMENT '关联模板'");
+        } catch (Exception ignored) {
+        }
+        try {
+            jdbcTemplate.execute("ALTER TABLE guide_packages ADD COLUMN IF NOT EXISTS commission_rate INT COMMENT '佣金比例(bps,100=1%)'");
+        } catch (Exception ignored) {
+        }
+        return Result.success("迁移完成");
+    }
+
+    @Operation(summary = "迁移dan_knowledge_base到articles(知识库→知识中心)")
+    @PostMapping("/migrate/knowledge-base-to-articles")
+    public Result<String> migrateKnowledgeBaseToArticles() {
+        int migrated = 0;
+        int skipped = 0;
+
+        List<Map<String, Object>> dimRows = jdbcTemplate.queryForList(
+                "SELECT id, dimension_code FROM product_dimension_config WHERE enabled = 1");
+        Map<Long, String> dimCodeMap = dimRows.stream()
+                .collect(Collectors.toMap(
+                        r -> ((Number) r.get("id")).longValue(),
+                        r -> (String) r.get("dimension_code")));
+
+        List<Map<String, Object>> kbList = jdbcTemplate.queryForList(
+                "SELECT id, title, content, sort, remark, created_at, updated_at FROM dan_knowledge_base WHERE status = 1");
+
+        for (Map<String, Object> kb : kbList) {
+            Number kbId = (Number) kb.get("id");
+
+            String title = (String) kb.get("title");
+            Integer existingCount = jdbcTemplate.queryForObject(
+                    "SELECT COUNT(*) FROM articles WHERE title = ? AND content_type = 'knowledge'",
+                    Integer.class, title);
+            if (existingCount != null && existingCount > 0) {
+                skipped++;
+                continue;
+            }
+
+            List<Long> tagIds = jdbcTemplate.queryForList(
+                    "SELECT tag_id FROM dan_knowledge_base_tag WHERE knowledge_id = ?",
+                    Long.class, kbId.longValue());
+
+            List<Map<String, Object>> dimAssocs = jdbcTemplate.queryForList(
+                    "SELECT dimension_id FROM dan_knowledge_base_dimension WHERE knowledge_id = ?",
+                    kbId.longValue());
+            String dimensionCodes = dimAssocs.stream()
+                    .map(r -> dimCodeMap.get(((Number) r.get("dimension_id")).longValue()))
+                    .filter(c -> c != null)
+                    .collect(Collectors.joining(","));
+
+            String content = (String) kb.get("content");
+            String summary = (String) kb.get("remark");
+            Date createdAt = (Date) kb.get("created_at");
+            Date updatedAt = (Date) kb.get("updated_at");
+
+            jdbcTemplate.update(
+                    "INSERT INTO articles (title, content, summary, content_type, difficulty_level, status, is_featured, view_count, created_by, created_at, updated_at, published_at, word_count) VALUES (?, ?, ?, 'knowledge', 0, 'published', 0, 0, 0, ?, ?, ?, ?)",
+                    title, content, summary, createdAt, updatedAt, createdAt, content != null ? content.length() : 0);
+
+            Long articleId = jdbcTemplate.queryForObject(
+                    "SELECT LAST_INSERT_ID()", Long.class);
+
+            if (!dimensionCodes.isEmpty() && articleId != null) {
+                jdbcTemplate.update("UPDATE articles SET dimension_ids = ? WHERE id = ?",
+                        dimensionCodes, articleId);
+            }
+
+            if (!tagIds.isEmpty() && articleId != null) {
+                for (Long tagId : tagIds) {
+                    jdbcTemplate.update(
+                            "INSERT IGNORE INTO article_tags (article_id, tag_id) VALUES (?, ?)",
+                            articleId, tagId);
+                }
+            }
+
+            migrated++;
+        }
+
+        return Result.success("知识库迁移完成: 成功 " + migrated + " 条, 跳过(已存在) " + skipped + " 条");
+    }
+}

+ 48 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/MindModelManageController.java

@@ -0,0 +1,48 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.MindModel;
+import com.etotem.cfc.service.MindModelManageService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 舌诊/情绪模型版本管理(能力键 mind.model.manage · SC-A-21)。
+ *
+ * <p>平台运营内部模型管理:版本列表(list)/ 上线(online)/ 下线(offline,须指定回退版本)。
+ * 所有接口统一 {@code @PostMapping}。</p>
+ */
+@Slf4j
+@RestController
+@RequestMapping("/api/admin/mind-model")
+public class MindModelManageController {
+
+    @Resource
+    private MindModelManageService mindModelManageService;
+
+    /** 版本列表(版控,AC-2)。 */
+    @PostMapping("/list")
+    public Result<List<MindModel>> list() {
+        return mindModelManageService.listAll();
+    }
+
+    /** 上线(AC-2);请求体: { "modelType": "emotion|tongue", "version": "v1" }。 */
+    @PostMapping("/online")
+    public Result<Void> online(@RequestBody Map<String, String> params) {
+        return mindModelManageService.online(params.get("modelType"), params.get("version"));
+    }
+
+    /** 下线(AC-3 须指定回退版本);请求体: { "modelType": "emotion|tongue", "version": "v1", "fallbackVersion": "v1" }。 */
+    @PostMapping("/offline")
+    public Result<Void> offline(@RequestBody Map<String, String> params) {
+        return mindModelManageService.offline(
+                params.get("modelType"), params.get("version"), params.get("fallbackVersion"));
+    }
+}

+ 51 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/NumSoulDetailConfigController.java

@@ -0,0 +1,51 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.NumSoulDetailConfig;
+import com.etotem.cfc.mapper.NumSoulDetailConfigMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Slf4j
+@RestController
+@RequestMapping("/api/admin/numsoul-detail-config")
+public class NumSoulDetailConfigController {
+
+    @Resource
+    private NumSoulDetailConfigMapper numSoulDetailConfigMapper;
+
+    @PostMapping("/list")
+    public Result<List<NumSoulDetailConfig>> list(@RequestBody(required = false) java.util.Map<String, Object> params) {
+        LambdaQueryWrapper<NumSoulDetailConfig> wrapper = new LambdaQueryWrapper<>();
+        if (params != null && params.get("numberType") != null) {
+            wrapper.eq(NumSoulDetailConfig::getNumberType, params.get("numberType").toString());
+        }
+        wrapper.orderByAsc(NumSoulDetailConfig::getNumberType).orderByAsc(NumSoulDetailConfig::getNumberValue);
+        return Result.success(numSoulDetailConfigMapper.selectList(wrapper));
+    }
+
+    @PostMapping("/create")
+    public Result<Void> create(@RequestBody NumSoulDetailConfig config) {
+        numSoulDetailConfigMapper.insert(config);
+        return Result.success(null);
+    }
+
+    @PostMapping("/update")
+    public Result<Void> update(@RequestBody NumSoulDetailConfig config) {
+        if (config.getId() == null) {
+            return Result.error("缺少id");
+        }
+        numSoulDetailConfigMapper.updateById(config);
+        return Result.success(null);
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        numSoulDetailConfigMapper.deleteById(id);
+        return Result.success(null);
+    }
+}

+ 74 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/OperationLogController.java

@@ -0,0 +1,74 @@
+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.UserOperationLog;
+import com.etotem.cfc.service.UserOperationLogService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import javax.annotation.Resource;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "日志管理", description = "操作日志查询接口")
+@RestController
+@RequestMapping("/api/admin/logs")
+public class OperationLogController {
+
+    @Resource
+    private UserOperationLogService logService;
+
+    @Operation(summary = "分页查询操作日志")
+    @PostMapping("/operations")
+    public Result<Page<UserOperationLog>> queryLogs(
+            @RequestAttribute("userId") Long adminId,
+            @RequestBody Map<String, Object> params) {
+        Long userId = params.get("userId") != null ? ((Number) params.get("userId")).longValue() : null;
+        String operationType = (String) params.get("operationType");
+        Integer page = params.get("page") != null ? (Integer) params.get("page") : 1;
+        Integer size = params.get("size") != null ? (Integer) params.get("size") : 20;
+
+        // 解析日期
+        Date startDate = null;
+        Date endDate = null;
+        try {
+            if (params.get("startDate") != null) {
+                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
+                startDate = sdf.parse((String) params.get("startDate"));
+            }
+            if (params.get("endDate") != null) {
+                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
+                endDate = sdf.parse((String) params.get("endDate"));
+            }
+        } catch (Exception e) {
+            // 日期解析失败
+        }
+
+        @SuppressWarnings("unchecked")
+        List<Map<String, String>> sortSpecs = params.get("sort") != null
+                ? (List<Map<String, String>>) params.get("sort")
+                : null;
+
+        Page<UserOperationLog> result = logService.queryLogs(
+                userId, operationType, startDate, endDate, page, size, sortSpecs);
+
+        return Result.success(result);
+    }
+
+    @Operation(summary = "获取用户最近操作记录")
+    @PostMapping("/recent")
+    public Result<List<UserOperationLog>> getRecentLogs(
+            @RequestAttribute("userId") Long adminId,
+            @RequestBody Map<String, Object> params) {
+        Long userId = ((Number) params.get("userId")).longValue();
+        Integer limit = params.get("limit") != null ? (Integer) params.get("limit") : 10;
+
+        List<UserOperationLog> logs = logService.getRecentLogs(userId, limit);
+        return Result.success(logs);
+    }
+}

+ 68 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/PackageTemplateController.java

@@ -0,0 +1,68 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.GuidePackageTemplate;
+import com.etotem.cfc.service.GuidePackageTemplateService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Tag(name = "任务模板模板管理", description = "系统任务模板模板CRUD")
+@RestController
+@RequestMapping("/api/admin/package-templates")
+public class PackageTemplateController {
+
+    @Resource
+    private GuidePackageTemplateService templateService;
+
+    @PostMapping("/list")
+    @Operation(summary = "获取任务模板模板列表")
+    public Result<List<GuidePackageTemplate>> list() {
+        List<GuidePackageTemplate> list = templateService.getActiveTemplates();
+        return Result.success(list);
+    }
+
+    @PostMapping("/all")
+    @Operation(summary = "获取所有任务模板模板(含停用)")
+    public Result<List<GuidePackageTemplate>> listAll() {
+        List<GuidePackageTemplate> list = templateService.list();
+        return Result.success(list);
+    }
+
+    @PostMapping("/{id}")
+    @Operation(summary = "获取任务模板模板详情")
+    public Result<GuidePackageTemplate> getById(@PathVariable Long id) {
+        GuidePackageTemplate template = templateService.getTemplateById(id);
+        return template != null ? Result.success(template) : Result.error("不存在");
+    }
+
+    @PostMapping("/create")
+    @Operation(summary = "创建任务模板模板")
+    public Result<GuidePackageTemplate> create(@RequestBody GuidePackageTemplate template) {
+        template.setStatus("ACTIVE");
+        template.setCreatedAt(new Date());
+        template.setUpdatedAt(new Date());
+        GuidePackageTemplate created = templateService.createTemplate(template);
+        return Result.success(created);
+    }
+
+    @PostMapping("/{id}/update")
+    @Operation(summary = "更新任务模板模板")
+    public Result<GuidePackageTemplate> update(@PathVariable Long id, @RequestBody GuidePackageTemplate template) {
+        template.setId(id);
+        template.setUpdatedAt(new Date());
+        boolean success = templateService.updateTemplate(template);
+        return success ? Result.success(template) : Result.error("更新失败");
+    }
+
+    @PostMapping("/{id}/delete")
+    @Operation(summary = "删除任务模板模板")
+    public Result<Void> delete(@PathVariable Long id) {
+        boolean success = templateService.deleteTemplate(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 61 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ParseMonitorController.java

@@ -0,0 +1,61 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.ParseMonitorService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-健康报告解析监控看板(能力键 {@code health.ops.parseMonitor},SC-A-02 报告解析中台)。
+ *
+ * <p>契约来源:《浠艾福程序-谷禾新版解析与五维归因升级方案 v1.0》§三 P2 运营与监控。看板为管理端能力,
+ * 所有端点均做 admin 角色校验({@code @RequestAttribute("role")} + {@code "admin"} 检查)。
+ */
+@RestController
+@RequestMapping("/api/admin/parse-monitor")
+public class ParseMonitorController {
+
+    @Resource
+    private ParseMonitorService parseMonitorService;
+
+    /** 解析监控总览(P0 命中率 + P1 Top 5 + 解析耗时 + 上游同步锚点) */
+    @PostMapping("/overview")
+    public Result<Map<String, Object>> getParseMonitorOverview(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(parseMonitorService.getMonitorOverview());
+    }
+
+    /** P0 命中率(_解析自检 P0 告警数=0 的草稿占比) */
+    @PostMapping("/p0-hit-rate")
+    public Result<Map<String, Object>> monitorP0HitRate(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(parseMonitorService.getP0HitRate());
+    }
+
+    /** P1 Top 5(健康问题索引五类高频问题排行) */
+    @PostMapping("/p1-top5")
+    public Result<Map<String, Object>> monitorP1Top5(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(parseMonitorService.getP1Top5());
+    }
+
+    /** 解析耗时监控(含 next_retry_at 待重试队列健康度) */
+    @PostMapping("/duration")
+    public Result<Map<String, Object>> monitorDuration(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(parseMonitorService.getParseDurationStats());
+    }
+}

+ 159 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/PpointConfigAdminController.java

@@ -0,0 +1,159 @@
+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.CategoryPpoint;
+import com.etotem.cfc.entity.ProductPpoint;
+import com.etotem.cfc.service.PpointConfigService;
+import com.etotem.cfc.service.PpointService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * P点配置管理(品类级比例 + 商品级固定值)
+ * 管理端接口
+ */
+@RestController
+@RequestMapping("/api/admin/ppoint-config")
+public class PpointConfigAdminController {
+
+    @Resource
+    private PpointConfigService ppointConfigService;
+
+    @Resource
+    private PpointService ppointService;
+
+    // ======================== 品类级P点比例 ========================
+
+    @PostMapping("/category/list")
+    public Result<Map<String, Object>> categoryList(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String keyword = (String) params.get("keyword");
+
+        Page<CategoryPpoint> pageParam = new Page<>(page, size);
+        Map<String, Object> result = ppointConfigService.adminCategoryList(pageParam, keyword);
+        return Result.success(result);
+    }
+
+    @PostMapping("/category/save")
+    public Result<Void> categorySave(@RequestBody Map<String, Object> params) {
+        Long categoryId = ParamUtils.getLong(params.get("categoryId"));
+        Integer ratio = Integer.valueOf(params.get("ratio").toString());
+        String startDateStr = (String) params.get("startDate");
+        String endDateStr = (String) params.get("endDate");
+
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        java.util.Date startDate = null;
+        java.util.Date endDate = null;
+        try {
+            if (startDateStr != null && !startDateStr.isEmpty()) {
+                startDate = sdf.parse(startDateStr);
+            }
+            if (endDateStr != null && !endDateStr.isEmpty()) {
+                endDate = sdf.parse(endDateStr);
+            }
+        } catch (Exception e) {
+            return Result.error("日期格式错误,请使用yyyy-MM-dd");
+        }
+
+        if (ratio < 0 || ratio > 1000) {
+            return Result.error("P点比例取值范围为0-1000(即0%-100%)");
+        }
+
+        ppointConfigService.saveCategoryRatio(categoryId, ratio, startDate, endDate, null);
+        return Result.success(null);
+    }
+
+    @PostMapping("/category/delete")
+    public Result<Void> categoryDelete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        ppointConfigService.deleteCategoryRatio(id);
+        return Result.success(null);
+    }
+
+    @PostMapping("/category/by-category")
+    public Result<List<CategoryPpoint>> categoryByCategory(@RequestBody Map<String, Object> params) {
+        Long categoryId = ParamUtils.getLong(params.get("categoryId"));
+        List<CategoryPpoint> records = ppointConfigService.getByCategoryId(categoryId);
+        return Result.success(records);
+    }
+
+    // ======================== 商品级P点(复用PpointService) ========================
+
+    @PostMapping("/product/list")
+    public Result<Map<String, Object>> productList(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String keyword = (String) params.get("keyword");
+        Long productId = ParamUtils.getLong(params.get("productId"));
+
+        Page<ProductPpoint> pageParam = new Page<>(page, size);
+        Map<String, Object> result = ppointService.adminList(pageParam, keyword, productId, null);
+        return Result.success(result);
+    }
+
+    @PostMapping("/product/save")
+    public Result<Void> productSave(@RequestBody Map<String, Object> params) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        Integer ppoint = Integer.valueOf(params.get("ppoint").toString());
+        String startDateStr = (String) params.get("startDate");
+        String endDateStr = (String) params.get("endDate");
+
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        java.util.Date startDate = null;
+        java.util.Date endDate = null;
+        try {
+            if (startDateStr != null && !startDateStr.isEmpty()) {
+                startDate = sdf.parse(startDateStr);
+            }
+            if (endDateStr != null && !endDateStr.isEmpty()) {
+                endDate = sdf.parse(endDateStr);
+            }
+        } catch (Exception e) {
+            return Result.error("日期格式错误,请使用yyyy-MM-dd");
+        }
+
+        if (ppoint < 0 || ppoint > 10000) {
+            return Result.error("P点取值范围为0-10000(即0%-100%)");
+        }
+
+        ppointService.savePpoint(productId, ppoint, startDate, endDate, null);
+        return Result.success(null);
+    }
+
+    @PostMapping("/product/delete")
+    public Result<Void> productDelete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        ppointService.deleteById(id);
+        return Result.success(null);
+    }
+
+    @PostMapping("/product/by-product")
+    public Result<List<ProductPpoint>> productByProduct(@RequestBody Map<String, Object> params) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        List<ProductPpoint> records = ppointService.getByProductId(productId);
+        return Result.success(records);
+    }
+
+    // ======================== 综合查询 ========================
+
+    /**
+     * 获取商品综合有效的P点值
+     */
+    @PostMapping("/effective")
+    public Result<Integer> getEffectivePpoint(@RequestBody Map<String, Object> params) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        Long categoryId = ParamUtils.getLong(params.get("categoryId"));
+        int ppoint = ppointConfigService.getEffectivePpoint(productId, categoryId);
+        return Result.success(ppoint);
+    }
+}

+ 65 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ProductSkuController.java

@@ -0,0 +1,65 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ProductSkuDTO;
+import com.etotem.cfc.entity.ProductSku;
+import com.etotem.cfc.service.ProductSkuService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@RestController
+@RequestMapping("/api/admin/product/sku")
+public class ProductSkuController {
+
+    @Resource
+    private ProductSkuService skuService;
+
+    @PostMapping("/list")
+    public Result<List<ProductSkuDTO>> listByProduct(@RequestBody Map<String, Object> params) {
+        Object productIdObj = params.get("productId");
+        if (productIdObj == null) return Result.error("productId不能为空");
+        Long productId = Long.parseLong(productIdObj.toString());
+        List<ProductSku> skus = skuService.listByProductIdAll(productId);
+        List<ProductSkuDTO> dtos = skus.stream()
+            .map(ProductSkuDTO::from)
+            .collect(Collectors.toList());
+        return Result.success(dtos);
+    }
+
+    @PostMapping("/get")
+    public Result<ProductSkuDTO> get(@RequestBody Map<String, Object> params) {
+        Long id = Long.parseLong(params.get("id").toString());
+        ProductSku sku = skuService.getById(id);
+        if (sku == null) {
+            return Result.error("SKU不存在");
+        }
+        return Result.success(ProductSkuDTO.from(sku));
+    }
+
+    @PostMapping("/create")
+    public Result<String> create(@RequestBody ProductSku sku) {
+        skuService.create(sku);
+        return Result.success("创建成功");
+    }
+
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody ProductSku sku) {
+        skuService.update(sku);
+        return Result.success("更新成功");
+    }
+
+    @PostMapping("/delete")
+    public Result<String> delete(@RequestBody Map<String, Object> params) {
+        Long id = Long.parseLong(params.get("id").toString());
+        skuService.delete(id);
+        return Result.success("删除成功");
+    }
+}

+ 131 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParseAdminController.java

@@ -0,0 +1,131 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.HealthReportDraft;
+import com.etotem.cfc.mapper.HealthReportDraftMapper;
+import com.etotem.cfc.service.HealthReportDraftService;
+import com.etotem.cfc.service.ReportCollectService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 报告解析进度管理(管理员):草稿解析进度查询、手动重试、食材回填。
+ * 鉴权由 JwtInterceptor 对 /api/** 统一拦截。
+ */
+@RestController
+@RequestMapping("/api/admin/report-parse")
+public class ReportParseAdminController {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportParseAdminController.class);
+
+    @Resource
+    private HealthReportDraftMapper draftMapper;
+
+    @Resource
+    private HealthReportDraftService healthReportDraftService;
+
+    @Resource
+    private ReportCollectService reportCollectService;
+
+    /** 草稿解析进度分页查询 */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String parseStatus = (String) params.get("parseStatus");
+        String reportType = (String) params.get("reportType");
+        String keyword = (String) params.get("keyword");
+
+        Page<HealthReportDraft> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<HealthReportDraft> wrapper = new LambdaQueryWrapper<>();
+        if (parseStatus != null && !parseStatus.isEmpty()) {
+            wrapper.eq(HealthReportDraft::getParseStatus, parseStatus);
+        }
+        if (reportType != null && !reportType.isEmpty()) {
+            wrapper.eq(HealthReportDraft::getReportType, reportType);
+        }
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.and(w -> w.like(HealthReportDraft::getOriginalFilename, keyword)
+                    .or().like(HealthReportDraft::getUserId, keyword));
+        }
+        wrapper.orderByDesc(HealthReportDraft::getUpdatedAt);
+
+        Page<HealthReportDraft> result = draftMapper.selectPage(pageParam, wrapper);
+        List<Map<String, Object>> records = new ArrayList<>();
+        for (HealthReportDraft d : result.getRecords()) {
+            records.add(toRecordMap(d));
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("total", result.getTotal());
+        data.put("records", records);
+        return Result.success(data);
+    }
+
+    /** 手动重试:重置解析进度并重新提交异步采集 */
+    @PostMapping("/retry")
+    public Result<Map<String, Object>> retry(@RequestBody Map<String, Object> params) {
+        Long draftId = params.get("draftId") != null ? ((Number) params.get("draftId")).longValue() : null;
+        if (draftId == null) {
+            return Result.error("draftId 不能为空");
+        }
+        healthReportDraftService.resetForManualRetry(draftId);
+        reportCollectService.submitAsyncCollect(draftId);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("draftId", draftId);
+        data.put("parseStatus", "collecting");
+        return Result.success(data);
+    }
+
+    /** 食材回填:重新解析报告并覆盖写入 foods(失败保留旧载荷) */
+    @PostMapping("/backfill-food")
+    public Result<Map<String, Object>> backfillFood(@RequestBody Map<String, Object> params) {
+        Long reportId = params.get("reportId") != null ? ((Number) params.get("reportId")).longValue() : null;
+        if (reportId == null) {
+            return Result.error("reportId 不能为空");
+        }
+        try {
+            int count = reportCollectService.reparseReportFoods(reportId);
+            Map<String, Object> data = new LinkedHashMap<>();
+            data.put("reportId", reportId);
+            data.put("foodCount", count);
+            return Result.success(data);
+        } catch (IllegalArgumentException | IllegalStateException e) {
+            log.warn("食材回填失败 reportId={}: {}", reportId, e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    private Map<String, Object> toRecordMap(HealthReportDraft d) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("draftId", d.getId());
+        m.put("userId", d.getUserId());
+        m.put("reportType", d.getReportType());
+        m.put("originalFilename", d.getOriginalFilename());
+        m.put("fileHash", d.getFileHash());
+        m.put("parseStatus", d.getParseStatus());
+        m.put("parseMethod", d.getParseMethod());
+        m.put("parseError", d.getParseError());
+        m.put("parseAttempt", d.getParseAttempt());
+        m.put("nextRetryAt", d.getNextRetryAt());
+        m.put("parseStartedAt", d.getParseStartedAt());
+        m.put("parseFinishedAt", d.getParseFinishedAt());
+        m.put("collectValidation", d.getCollectValidation());
+        m.put("draftStatus", d.getStatus());
+        m.put("confirmedReportId", d.getConfirmedReportId());
+        m.put("createdAt", d.getCreatedAt());
+        m.put("updatedAt", d.getUpdatedAt());
+        return m;
+    }
+}

+ 417 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParserAdminController.java

@@ -0,0 +1,417 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import com.etotem.cfc.service.DanReportUploadService;
+import com.etotem.cfc.service.ReportImportService;
+import com.etotem.cfc.service.ReportScriptGeneratorService;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.*;
+import com.etotem.cfc.util.SortUtil;
+
+@RestController
+@RequestMapping("/api/admin/report-parser")
+public class ReportParserAdminController {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportParserAdminController.class);
+
+    @Resource
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @Resource
+    private ReportFingerprintMapper fingerprintMapper;
+
+    @Resource
+    private ReportUnknownClusterMapper unknownClusterMapper;
+
+    @Resource
+    private ReportUnknownUploadMapper unknownUploadMapper;
+
+    @Resource
+    private ReportParserImportMapper importMapper;
+
+    @Resource
+    private ReportImportService reportImportService;
+
+    @Resource
+    private DanReportUploadService danReportUploadService;
+
+    @Resource
+    private ReportScriptGeneratorService reportScriptGeneratorService;
+
+    @Resource
+    private ReportTemplateMapper reportTemplateMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductMapper productMapper;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    // ==================== 报告类型管理 ====================
+
+    @PostMapping("/types")
+    public Result<Page<ReportTypeRegistry>> listTypes(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 999;
+        Page<ReportTypeRegistry> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<ReportTypeRegistry> wrapper = new LambdaQueryWrapper<>();
+        @SuppressWarnings("unchecked")
+        List<Map<String, String>> sortSpecs = params.get("sort") != null
+                ? (List<Map<String, String>>) params.get("sort")
+                : null;
+        if (sortSpecs == null || sortSpecs.isEmpty()) {
+            wrapper.orderByDesc(ReportTypeRegistry::getId);
+        }
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        Page<ReportTypeRegistry> result = typeRegistryMapper.selectPage(pageParam, wrapper);
+        fillProductNames(result.getRecords());
+        return Result.success(result);
+    }
+
+    /** 为报告类型批量回填关联商品名称(linkedProductId 非空者),连同 linkedProductId 一起返回前端 */
+    private void fillProductNames(List<ReportTypeRegistry> types) {
+        if (types == null || types.isEmpty()) return;
+        java.util.Set<Long> productIds = new java.util.HashSet<>();
+        for (ReportTypeRegistry t : types) {
+            if (t.getLinkedProductId() != null) productIds.add(t.getLinkedProductId());
+        }
+        if (productIds.isEmpty()) return;
+        java.util.Map<Long, String> nameMap = new HashMap<>();
+        try {
+            List<com.etotem.cfc.entity.Product> products = productMapper.selectBatchIds(productIds);
+            if (products != null) {
+                for (com.etotem.cfc.entity.Product p : products) {
+                    if (p != null && p.getId() != null) nameMap.put(p.getId(), p.getName());
+                }
+            }
+        } catch (Exception e) {
+            log.warn("填充报告类型商品名失败: {}", e.getMessage());
+        }
+        for (ReportTypeRegistry t : types) {
+            if (t.getLinkedProductId() != null) t.setProductName(nameMap.get(t.getLinkedProductId()));
+        }
+    }
+
+    @PostMapping("/types/save")
+    public Result<Void> saveType(@RequestBody ReportTypeRegistry type) {
+        // 归一化:icon 若为空串视为未填,置 null 走 DB 默认/updateById 非空更新忽略,
+        // 避免把 "" 写库覆盖默认;sortOrder 为数值型,前端不填以 null 提交(DB 默认 100 兜底)
+        if (type.getIcon() != null && type.getIcon().trim().isEmpty()) {
+            type.setIcon(null);
+        }
+        if (type.getTypeId() == null || type.getTypeId().isEmpty()) {
+            return Result.error("typeId 不能为空");
+        }
+        if (type.getDisplayName() == null || type.getDisplayName().isEmpty()) {
+            return Result.error("displayName 不能为空");
+        }
+        if (type.getExpectedIndicators() != null && !type.getExpectedIndicators().trim().isEmpty()
+                && !isValidJsonStringArray(type.getExpectedIndicators())) {
+            return Result.error("expectedIndicators 必须为 JSON 字符串数组");
+        }
+        if (type.getId() != null) {
+            type.setUpdatedAt(new Date());
+            typeRegistryMapper.updateById(type);
+            // MyBatis-Plus updateById 默认忽略 null 字段,linkedProductId 允许清空(=NULL 表示不可链接),需显式置空。
+            // 使用字符串列名版 UpdateWrapper(非 Lambda 版),避免纯 Mockito 单测无 MyBatis-Plus 运行时环境
+            // 构造 LambdaUpdateWrapper 时抛 "can not find lambda cache for this entity"。
+            if (type.getLinkedProductId() == null) {
+                typeRegistryMapper.update(null,
+                        new UpdateWrapper<ReportTypeRegistry>()
+                                .eq("id", type.getId())
+                                .set("linked_product_id", null)
+                                .set("updated_at", type.getUpdatedAt()));
+            }
+        } else {
+            Long exists = typeRegistryMapper.selectCount(
+                    new LambdaQueryWrapper<ReportTypeRegistry>()
+                            .eq(ReportTypeRegistry::getTypeId, type.getTypeId()));
+            if (exists != null && exists > 0) {
+                return Result.error("typeId 已存在");
+            }
+            type.setIsActive(type.getIsActive() != null ? type.getIsActive() : true);
+            type.setSource(type.getSource() != null ? type.getSource() : "prebuilt");
+            type.setReviewStatus(type.getReviewStatus() != null ? type.getReviewStatus() : "approved");
+            type.setVersion(type.getVersion() != null ? type.getVersion() : "1.0");
+            type.setMinConfidence(type.getMinConfidence() != null ? type.getMinConfidence() : 10);
+            type.setCreatedAt(new Date());
+            type.setUpdatedAt(new Date());
+            typeRegistryMapper.insert(type);
+        }
+        return Result.success();
+    }
+
+    /** 校验字符串是否为 JSON 字符串数组,如 ["总分","百分位"] */
+    private boolean isValidJsonStringArray(String json) {
+        try {
+            com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
+            if (node == null || !node.isArray()) {
+                return false;
+            }
+            for (com.fasterxml.jackson.databind.JsonNode el : node) {
+                if (!el.isTextual()) {
+                    return false;
+                }
+            }
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    @PostMapping("/types/toggle")
+    public Result<Void> toggleType(@RequestBody Map<String, Object> params) {
+        String typeId = (String) params.get("typeId");
+        Boolean isActive = params.get("isActive") != null ? (Boolean) params.get("isActive") : false;
+        if (typeId == null) return Result.error("typeId 不能为空");
+        ReportTypeRegistry type = typeRegistryMapper.selectOne(
+                new LambdaQueryWrapper<ReportTypeRegistry>().eq(ReportTypeRegistry::getTypeId, typeId));
+        if (type == null) return Result.error("类型不存在");
+        type.setIsActive(isActive);
+        type.setUpdatedAt(new Date());
+        typeRegistryMapper.updateById(type);
+        return Result.success();
+    }
+
+    @PostMapping("/types/delete")
+    public Result<Void> deleteType(@RequestBody Map<String, Object> params) {
+        String typeId = (String) params.get("typeId");
+        if (typeId == null) return Result.error("typeId 不能为空");
+        typeRegistryMapper.delete(new LambdaQueryWrapper<ReportTypeRegistry>()
+                .eq(ReportTypeRegistry::getTypeId, typeId));
+        fingerprintMapper.delete(new LambdaQueryWrapper<ReportFingerprint>()
+                .eq(ReportFingerprint::getTypeId, typeId));
+        return Result.success();
+    }
+
+    // ==================== 指纹规则管理 ====================
+
+    @PostMapping("/fingerprints/list")
+    public Result<List<ReportFingerprint>> listFingerprints(@RequestBody Map<String, Object> params) {
+        String typeId = (String) params.get("typeId");
+        if (typeId == null) return Result.error("typeId 不能为空");
+        List<ReportFingerprint> list = fingerprintMapper.selectList(
+                new LambdaQueryWrapper<ReportFingerprint>()
+                        .eq(ReportFingerprint::getTypeId, typeId)
+                        .orderByAsc(ReportFingerprint::getSortOrder));
+        return Result.success(list);
+    }
+
+    @PostMapping("/fingerprints/save")
+    public Result<Void> saveFingerprint(@RequestBody ReportFingerprint fp) {
+        if (fp.getTypeId() == null || fp.getPattern() == null) {
+            return Result.error("typeId 和 pattern 不能为空");
+        }
+        fp.setWeight(fp.getWeight() != null ? fp.getWeight() : 10);
+        fp.setIsExclusion(fp.getIsExclusion() != null ? fp.getIsExclusion() : false);
+        fp.setSortOrder(fp.getSortOrder() != null ? fp.getSortOrder() : 0);
+        fp.setCreatedAt(new Date());
+        fingerprintMapper.insert(fp);
+        return Result.success();
+    }
+
+    @PostMapping("/fingerprints/delete")
+    public Result<Void> deleteFingerprint(@RequestBody Map<String, Object> params) {
+        Long id = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        if (id == null) return Result.error("id 不能为空");
+        fingerprintMapper.deleteById(id);
+        return Result.success();
+    }
+
+    // ==================== 导入管理 ====================
+
+    @PostMapping("/imports")
+    public Result<Page<ReportParserImport>> listImports(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        Page<ReportParserImport> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<ReportParserImport> wrapper = new LambdaQueryWrapper<>();
+        @SuppressWarnings("unchecked")
+        List<Map<String, String>> sortSpecs = params.get("sort") != null
+                ? (List<Map<String, String>>) params.get("sort")
+                : null;
+        if (sortSpecs == null || sortSpecs.isEmpty()) {
+            wrapper.orderByDesc(ReportParserImport::getCreatedAt);
+        }
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        return Result.success(importMapper.selectPage(pageParam, wrapper));
+    }
+
+    @PostMapping("/imports/import")
+    public Result<ReportParserImport> uploadImport(@RequestBody Map<String, Object> params) {
+        String jsonContent = (String) params.get("jsonContent");
+        String fileName = (String) params.get("fileName");
+        Long userId = params.get("userId") != null ? ((Number) params.get("userId")).longValue() : null;
+        if (jsonContent == null) return Result.error("jsonContent 不能为空");
+        return reportImportService.importPackage(fileName, jsonContent, userId);
+    }
+
+    @PostMapping("/imports/approve")
+    public Result<Map<String, Object>> approveImport(@RequestBody Map<String, Object> params) {
+        Long importId = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        Long reviewerId = params.get("reviewerId") != null ? ((Number) params.get("reviewerId")).longValue() : null;
+        if (importId == null) return Result.error("id 不能为空");
+        return reportImportService.approveImport(importId, reviewerId);
+    }
+
+    @PostMapping("/imports/reject")
+    public Result<Void> rejectImport(@RequestBody Map<String, Object> params) {
+        Long importId = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        Long reviewerId = params.get("reviewerId") != null ? ((Number) params.get("reviewerId")).longValue() : null;
+        String note = (String) params.get("note");
+        if (importId == null) return Result.error("id 不能为空");
+        return reportImportService.rejectImport(importId, reviewerId, note);
+    }
+
+    // ==================== 未知报告聚类 ====================
+
+    @PostMapping("/unknown-clusters")
+    public Result<Page<ReportUnknownCluster>> listClusters(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String status = (String) params.get("status");
+        Page<ReportUnknownCluster> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<ReportUnknownCluster> wrapper = new LambdaQueryWrapper<>();
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ReportUnknownCluster::getStatus, status);
+        }
+        @SuppressWarnings("unchecked")
+        List<Map<String, String>> sortSpecs = params.get("sort") != null
+                ? (List<Map<String, String>>) params.get("sort")
+                : null;
+        if (sortSpecs == null || sortSpecs.isEmpty()) {
+            wrapper.orderByDesc(ReportUnknownCluster::getReportCount);
+        }
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        return Result.success(unknownClusterMapper.selectPage(pageParam, wrapper));
+    }
+
+    @PostMapping("/unknown-uploads")
+    public Result<List<ReportUnknownUpload>> listUploads(@RequestBody Map<String, Object> params) {
+        Long clusterId = params.get("clusterId") != null ? ((Number) params.get("clusterId")).longValue() : null;
+        if (clusterId == null) return Result.error("clusterId 不能为空");
+        List<ReportUnknownUpload> list = unknownUploadMapper.selectList(
+                new LambdaQueryWrapper<ReportUnknownUpload>()
+                        .eq(ReportUnknownUpload::getClusterId, clusterId)
+                        .orderByDesc(ReportUnknownUpload::getUploadedAt));
+        return Result.success(list);
+    }
+
+    // ==================== 自学习生成 ====================
+
+    @PostMapping("/generate-type")
+    public Result<Map<String, Object>> generateType(@RequestBody Map<String, Object> params) {
+        Long clusterId = params.get("clusterId") != null ? ((Number) params.get("clusterId")).longValue() : null;
+        if (clusterId == null) return Result.error("clusterId 不能为空");
+
+        ReportUnknownCluster cluster = unknownClusterMapper.selectById(clusterId);
+        if (cluster == null) return Result.error("聚类不存在");
+        if (!"ready".equals(cluster.getStatus())) {
+            return Result.error("该聚类不可生成,当前状态: " + cluster.getStatus());
+        }
+
+        try {
+            String clusterKey = cluster.getClusterKey();
+            String typeId = "auto_" + clusterKey.toLowerCase().replaceAll("[^a-z0-9]", "_").replaceAll("_+", "_");
+
+            // 创建报告类型
+            ReportTypeRegistry type = new ReportTypeRegistry();
+            type.setTypeId(typeId);
+            type.setFamily("auto_generated");
+            type.setDisplayName("自动生成 - " + typeId);
+            type.setDescription("由自学习系统自动生成,基于 " + cluster.getReportCount() + " 份同类报告");
+            type.setParserPath(typeId + ".py");
+            type.setMinConfidence(10);
+            type.setIsActive(false);
+            type.setSource(ReportTypeRegistry.SOURCE_AUTO_GENERATED);
+            type.setReviewStatus(ReportTypeRegistry.REVIEW_PENDING);
+            type.setVersion("1.0");
+            type.setCreatedAt(new Date());
+            type.setUpdatedAt(new Date());
+            typeRegistryMapper.insert(type);
+            type.setScriptStatus(ReportTypeRegistry.SCRIPT_STATUS_GENERATING);
+            type.setUpdatedAt(new Date());
+            typeRegistryMapper.updateById(type);
+
+            // 从公共签名生成指纹规则
+            String signatures = cluster.getCommonSignatures();
+            if (signatures != null && !signatures.isEmpty()) {
+                // 提取可能的文本特征作为指纹
+                String[] candidates = signatures.split("[\n\r]+");
+                Set<String> seen = new HashSet<>();
+                int sort = 0;
+                for (String line : candidates) {
+                    String trimmed = line.trim();
+                    if (trimmed.length() >= 4 && trimmed.length() <= 100 && !seen.contains(trimmed)) {
+                        seen.add(trimmed);
+                        ReportFingerprint fp = new ReportFingerprint();
+                        fp.setTypeId(typeId);
+                        fp.setPattern(trimmed);
+                        fp.setWeight(10);
+                        fp.setIsExclusion(false);
+                        fp.setSortOrder(sort++);
+                        fp.setCreatedAt(new Date());
+                        fingerprintMapper.insert(fp);
+                    }
+                }
+            }
+
+            // 更新聚类
+            cluster.setStatus("generated");
+            cluster.setGeneratedTypeId(typeId);
+            cluster.setUpdatedAt(new Date());
+            unknownClusterMapper.updateById(cluster);
+
+            // 自动创建空模板
+            try {
+                com.etotem.cfc.entity.ReportTemplate tpl = new com.etotem.cfc.entity.ReportTemplate();
+                tpl.setReportType(typeId);
+                tpl.setName(type.getDisplayName());
+                tpl.setConfig("{\"fixedBlocks\":[],\"freeDisplay\":{\"enabled\":true,\"groupName\":\"其他指标\"}}");
+                tpl.setIsActive(0);
+                tpl.setCreatedAt(new Date());
+                tpl.setUpdatedAt(new Date());
+                reportTemplateMapper.insert(tpl);
+                log.info("已自动创建空模板 reportType={}", typeId);
+            } catch (Exception e) {
+                log.warn("自动创建模板失败 typeId={}: {}", typeId, e.getMessage());
+            }
+
+            Map<String, Object> result = new LinkedHashMap<>();
+            result.put("typeId", typeId);
+            result.put("displayName", type.getDisplayName());
+            result.put("fingerprintCount", type.getMinConfidence());
+            result.put("reviewStatus", "pending");
+            result.put("scriptStatus", type.getScriptStatus());
+            // 异步触发 opencode 写采集脚本
+            reportScriptGeneratorService.triggerAsyncGenerate(cluster.getId(), typeId);
+            return Result.success(result);
+        } catch (Exception e) {
+            log.error("自学习生成类型失败 clusterId={}", clusterId, e);
+            return Result.error("生成失败: " + e.getMessage());
+        }
+    }
+
+    @PostMapping("/dan/reparse")
+    public Result<Map<String, Object>> reparseDan(@RequestBody Map<String, Object> params) {
+        Object uploadId = params.get("uploadId");
+        Object dimension = params.get("dimension");
+        if (uploadId == null || dimension == null) {
+            return Result.error("uploadId/dimension 必填");
+        }
+        return danReportUploadService.reparseUpload(((Number) uploadId).longValue(), String.valueOf(dimension));
+    }
+}

+ 40 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportSummaryAdminController.java

@@ -0,0 +1,40 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ReportListQueryDTO;
+import com.etotem.cfc.dto.ReportSummaryVO;
+import com.etotem.cfc.dto.ReportSyncResultDTO;
+import com.etotem.cfc.service.ReportSummaryService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+
+@Slf4j
+@RestController
+@RequestMapping("/api/admin/report-summary")
+public class ReportSummaryAdminController {
+
+    @Resource
+    private ReportSummaryService reportSummaryService;
+
+    @PostMapping("/list")
+    public Result<Object> adminList(@RequestBody ReportListQueryDTO query) {
+        Page<ReportSummaryVO> page = reportSummaryService.adminPageList(query);
+        return Result.success(page);
+    }
+
+    @PostMapping("/sync")
+    public Result<ReportSyncResultDTO> sync() {
+        ReportSyncResultDTO result = reportSummaryService.fullSync();
+        String msg = "同步完成: 新增" + result.getNewCount()
+                + "条, 更新" + result.getUpdateCount()
+                + "条, 废弃" + result.getDiscardedCount()
+                + "条, 错误" + result.getErrorCount() + "条";
+        return Result.success(msg, result);
+    }
+}

+ 68 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportTemplateController.java

@@ -0,0 +1,68 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.IndicatorDefinition;
+import com.etotem.cfc.entity.ReportTemplate;
+import com.etotem.cfc.service.ReportTemplateService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/report-template")
+public class ReportTemplateController {
+
+    @Resource
+    private ReportTemplateService reportTemplateService;
+
+    @PostMapping("/list")
+    public Result<List<ReportTemplate>> list(@RequestBody Map<String, Object> params) {
+        String reportType = (String) params.get("reportType");
+        Integer isActive = params.get("isActive") != null ? (Integer) params.get("isActive") : null;
+        return Result.success(reportTemplateService.list(reportType, isActive));
+    }
+
+    @PostMapping("/get")
+    public Result<ReportTemplate> get(@RequestParam String reportType) {
+        ReportTemplate t = reportTemplateService.getByReportType(reportType);
+        return Result.success(t != null ? t : new ReportTemplate());
+    }
+
+    @PostMapping("/save")
+    public Result<ReportTemplate> save(@RequestBody ReportTemplate template) {
+        if (template.getName() == null || template.getName().trim().isEmpty()) {
+            return Result.error("模板名称不能为空");
+        }
+        if (template.getReportType() == null || template.getReportType().trim().isEmpty()) {
+            return Result.error("报告类型不能为空");
+        }
+        return Result.success(reportTemplateService.save(template));
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        reportTemplateService.delete(id);
+        return Result.success(null);
+    }
+
+    @PostMapping("/toggle")
+    public Result<Void> toggle(@RequestBody Map<String, Object> params) {
+        Long id = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        Integer isActive = params.get("isActive") != null ? (Integer) params.get("isActive") : 1;
+        if (id == null) return Result.error("id 不能为空");
+        reportTemplateService.toggle(id, isActive);
+        return Result.success(null);
+    }
+
+    @PostMapping("/indicators")
+    public Result<List<IndicatorDefinition>> indicators(@RequestBody Map<String, Object> params) {
+        String domain = (String) params.get("domain");
+        return Result.success(reportTemplateService.getAvailableIndicators(domain));
+    }
+}

+ 146 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReviewCenterController.java

@@ -0,0 +1,146 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityRegistration;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.ButlerProfile;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.PendingRefund;
+import com.etotem.cfc.entity.ServiceRoleApplication;
+import com.etotem.cfc.entity.SupplyHierarchyChangeRequest;
+import com.etotem.cfc.entity.TaskTemplatePackage;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.entity.WithdrawalRequest;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ActivityRegistrationMapper;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.ButlerProfileMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ServiceRoleApplicationMapper;
+import com.etotem.cfc.mapper.SupplyHierarchyChangeRequestMapper;
+import com.etotem.cfc.mapper.TaskTemplatePackageMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.mapper.WithdrawalRequestMapper;
+import com.etotem.cfc.mapper.PendingRefundMapper;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/review-center")
+public class ReviewCenterController {
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private ActivityRegistrationMapper activityRegistrationMapper;
+
+    @Resource
+    private WithdrawalRequestMapper withdrawalRequestMapper;
+
+    @Resource
+    private TaskTemplatePackageMapper taskTemplatePackageMapper;
+
+    @Resource
+    private ButlerProfileMapper butlerProfileMapper;
+
+    @Resource
+    private SupplyHierarchyChangeRequestMapper supplyHierarchyChangeRequestMapper;
+
+    @Resource
+    private PendingRefundMapper pendingRefundMapper;
+
+    @Resource
+    private ServiceRoleApplicationMapper serviceRoleApplicationMapper;
+
+    /**
+     * 统计待审(status=0)服务角色申请中命中任一目标角色的条数,同一记录只计一次。
+     */
+    public static int countPendingByRoles(List<ServiceRoleApplication> apps, String... roles) {
+        if (apps == null || apps.isEmpty()) {
+            return 0;
+        }
+        int count = 0;
+        for (ServiceRoleApplication app : apps) {
+            if (app == null || app.getStatus() == null || app.getStatus() != 0) {
+                continue;
+            }
+            if (com.etotem.cfc.service.impl.ServiceRoleApplicationServiceImpl.matchesAnyRole(
+                    app.getRoles(), java.util.Arrays.asList(roles))) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @PostMapping("/summary")
+    public Result<Map<String, Integer>> summary() {
+        Map<String, Integer> counts = new HashMap<>();
+
+        counts.put("articlePending", articleMapper.selectCount(
+                new QueryWrapper<Article>().eq("audit_status", "pending")).intValue());
+
+        counts.put("productPending", productMapper.selectCount(
+                new QueryWrapper<Product>().eq("status", "pending")).intValue());
+
+        // 服务角色申请中的待审记录按角色分流合并到各 Tab 计数
+        List<ServiceRoleApplication> pendingApplications = serviceRoleApplicationMapper.selectList(
+                new QueryWrapper<ServiceRoleApplication>().eq("status", 0));
+
+        counts.put("guidePending",
+                userMapper.selectCount(new QueryWrapper<User>().eq("teacher_status", "pending").isNotNull("real_name")).intValue()
+                        + countPendingByRoles(pendingApplications, "planner"));
+
+        counts.put("vendorPending",
+                userMapper.selectCount(new QueryWrapper<User>().eq("vendor_status", "pending")).intValue()
+                        + countPendingByRoles(pendingApplications, "vendor", "activity_provider"));
+
+        counts.put("butlerPending",
+                butlerProfileMapper.selectCount(new QueryWrapper<ButlerProfile>().eq("status", "pending")).intValue()
+                        + userMapper.selectCount(new QueryWrapper<User>().eq("butler_status", "pending")).intValue()
+                        + countPendingByRoles(pendingApplications, "butler"));
+
+        counts.put("packagePending", taskTemplatePackageMapper.selectCount(
+                new QueryWrapper<TaskTemplatePackage>().eq("status", "pending")).intValue());
+
+        counts.put("activityPending", activityMapper.selectCount(
+                new QueryWrapper<Activity>().eq("audit_status", "pending")).intValue());
+
+        counts.put("activityRegistrationPending", activityRegistrationMapper.selectCount(
+                new QueryWrapper<ActivityRegistration>().eq("status", "pending")).intValue());
+
+        counts.put("withdrawPending", withdrawalRequestMapper.selectCount(
+                new QueryWrapper<WithdrawalRequest>().eq("status", "pending")).intValue());
+
+        counts.put("refundPending", pendingRefundMapper.selectCount(
+                new QueryWrapper<PendingRefund>().eq("status", "pending")).intValue());
+
+        counts.put("hierarchyChangePending", supplyHierarchyChangeRequestMapper.selectCount(
+                new QueryWrapper<SupplyHierarchyChangeRequest>().eq("status", "pending")).intValue());
+
+        counts.put("nutritionistPending",
+                userMapper.selectCount(new QueryWrapper<User>().eq("nutritionist_status", "pending").isNotNull("real_name")).intValue()
+                        + countPendingByRoles(pendingApplications, "nutritionist"));
+
+        counts.put("knowledgePending", countPendingByRoles(pendingApplications, "article_admin"));
+
+        return Result.success(counts);
+    }
+}

+ 106 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ServiceContentController.java

@@ -0,0 +1,106 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ServiceContent;
+import com.etotem.cfc.entity.ServiceType;
+import com.etotem.cfc.service.ServiceContentService;
+import com.etotem.cfc.service.ServiceTypeService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "服务内容管理", description = "系统服务内容CRUD")
+@RestController
+@RequestMapping("/api/admin/service-contents")
+public class ServiceContentController {
+
+    @Resource
+    private ServiceContentService serviceContentService;
+
+    @Resource
+    private ServiceTypeService serviceTypeService;
+
+    @PostMapping("/list")
+    @Operation(summary = "获取服务内容列表")
+    public Result<List<ServiceContent>> list(@RequestBody Map<String, Object> params) {
+        Long typeId = ParamUtils.getLong(params.get("typeId"));
+        String status = params.get("status") != null ? params.get("status").toString() : null;
+
+        LambdaQueryWrapper<ServiceContent> wrapper = new LambdaQueryWrapper<>();
+        if (typeId != null) {
+            wrapper.eq(ServiceContent::getTypeId, typeId);
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ServiceContent::getStatus, status);
+        }
+        wrapper.orderByAsc(ServiceContent::getId);
+        List<ServiceContent> list = serviceContentService.list(wrapper);
+
+        for (ServiceContent content : list) {
+            ServiceType type = serviceTypeService.getById(content.getTypeId());
+            if (type != null) {
+                content.setTypeId(type.getId());
+            }
+        }
+        return Result.success(list);
+    }
+
+    @PostMapping("/active")
+    @Operation(summary = "获取所有启用的服务内容")
+    public Result<List<ServiceContent>> listActive() {
+        List<ServiceContent> list = serviceContentService.getActiveContents();
+        return Result.success(list);
+    }
+
+    @PostMapping("/{id}")
+    @Operation(summary = "获取服务内容详情")
+    public Result<ServiceContent> getById(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        ServiceContent content = serviceContentService.getById(id);
+        return content != null ? Result.success(content) : Result.error("不存在");
+    }
+
+    @PostMapping("/create")
+    @Operation(summary = "创建服务内容")
+    public Result<ServiceContent> create(@RequestBody ServiceContent serviceContent) {
+        serviceContent.setStatus("ACTIVE");
+        serviceContent.setCreatedAt(new Date());
+        serviceContent.setUpdatedAt(new Date());
+        ServiceContent created = serviceContentService.createContent(serviceContent);
+        return Result.success(created);
+    }
+
+    @PostMapping("/update")
+    @Operation(summary = "更新服务内容")
+    public Result<ServiceContent> update(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        ServiceContent serviceContent = new ServiceContent();
+        serviceContent.setId(id);
+        serviceContent.setTitle(params.get("title") != null ? params.get("title").toString() : null);
+        serviceContent.setContent(params.get("content") != null ? params.get("content").toString() : null);
+        serviceContent.setDuration(params.get("duration") != null ? Integer.valueOf(params.get("duration").toString()) : null);
+        serviceContent.setAgeRange(params.get("ageRange") != null ? params.get("ageRange").toString() : null);
+        if (params.get("price") != null) {
+            serviceContent.setPrice(Integer.valueOf(params.get("price").toString()));
+        }
+        serviceContent.setUpdatedAt(new Date());
+        boolean success = serviceContentService.updateContent(serviceContent);
+        return success ? Result.success(serviceContent) : Result.error("更新失败");
+    }
+
+    @PostMapping("/delete")
+    @Operation(summary = "删除服务内容")
+    public Result<Void> delete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        boolean success = serviceContentService.deleteContent(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 71 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ServiceTypeController.java

@@ -0,0 +1,71 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ServiceType;
+import com.etotem.cfc.service.ServiceTypeService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Tag(name = "服务类型管理", description = "系统服务类型CRUD")
+@RestController
+@RequestMapping("/api/admin/service-types")
+public class ServiceTypeController {
+
+    @Resource
+    private ServiceTypeService serviceTypeService;
+
+    @PostMapping("/list")
+    @Operation(summary = "获取服务类型列表")
+    public Result<List<ServiceType>> list() {
+        List<ServiceType> list = serviceTypeService.getActiveTypes();
+        return Result.success(list);
+    }
+
+    @PostMapping("/all")
+    @Operation(summary = "获取所有服务类型(含停用)")
+    public Result<List<ServiceType>> listAll() {
+        List<ServiceType> list = serviceTypeService.list();
+        return Result.success(list);
+    }
+
+    @PostMapping("/create")
+    @Operation(summary = "创建服务类型")
+    public Result<ServiceType> create(@RequestBody ServiceType serviceType) {
+        serviceType.setStatus("ACTIVE");
+        serviceType.setCreatedAt(new Date());
+        serviceType.setUpdatedAt(new Date());
+        ServiceType created = serviceTypeService.createType(serviceType);
+        return Result.success(created);
+    }
+
+    @PostMapping("/{id}")
+    @Operation(summary = "更新服务类型")
+    public Result<ServiceType> update(@PathVariable Long id, @RequestBody ServiceType serviceType) {
+        serviceType.setId(id);
+        serviceType.setUpdatedAt(new Date());
+        boolean success = serviceTypeService.updateType(serviceType);
+        return success ? Result.success(serviceType) : Result.error("更新失败");
+    }
+
+    @PostMapping("/{id}/delete")
+    @Operation(summary = "删除服务类型")
+    public Result<Void> delete(@PathVariable Long id) {
+        boolean success = serviceTypeService.deleteType(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+
+    @PostMapping("/{id}/detail")
+    @Operation(summary = "获取服务类型详情")
+    public Result<ServiceType> getById(@PathVariable Long id) {
+        ServiceType serviceType = serviceTypeService.getById(id);
+        if (serviceType == null) {
+            return Result.error("服务类型不存在");
+        }
+        return Result.success(serviceType);
+    }
+}

+ 219 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplierProductController.java

@@ -0,0 +1,219 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ProductCreateRequest;
+import com.etotem.cfc.dto.ProductDTO;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.service.ProductService;
+import com.etotem.cfc.service.SupplySystemService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * 供应商管理员 - 商品管理控制器
+ * 供应商管理员只能管理自己体系内的商品
+ */
+@Tag(name = "供应商-商品管理")
+@RestController
+@RequestMapping("/api/admin/supplier/product")
+public class SupplierProductController {
+
+    @Resource
+    private SupplySystemService supplySystemService;
+
+    @Resource
+    private ProductService productService;
+
+    /**
+     * 获取当前供应商管理员所属的供应体系
+     */
+    private SupplySystem getMySystem(Long userId) {
+        return supplySystemService.getByAdminId(userId);
+    }
+
+    @Operation(summary = "供应商商品列表")
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        String status = (String) params.get("status");
+        String keyword = (String) params.get("keyword");
+        Integer page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        Integer size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+
+        Page<Product> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+                .eq(Product::getDistributionSystemId, system.getId())
+                .orderByAsc(Product::getSortOrder)
+                .orderByDesc(Product::getCreatedAt);
+
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Product::getStatus, status);
+        }
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.like(Product::getName, keyword);
+        }
+
+        Page<Product> result = productService.adminProductList(pageParam, wrapper);
+        List<ProductDTO> records = result.getRecords().stream()
+                .map(ProductDTO::from)
+                .collect(Collectors.toList());
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", records);
+        data.put("total", result.getTotal());
+        data.put("page", result.getCurrent());
+        data.put("size", result.getSize());
+        return Result.success(data);
+    }
+
+    @Operation(summary = "供应商创建商品")
+    @PostMapping("/create")
+    public Result<ProductDTO> create(@RequestBody ProductCreateRequest request,
+                                     @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        Product product = request.getProduct();
+        if (product == null || product.getName() == null || product.getName().isEmpty()) {
+            return Result.error("商品名称不能为空");
+        }
+
+        // 自动绑定到供应商的体系
+        product.setDistributionSystemId(system.getId());
+        product.setVendorName(system.getName());
+
+        return productService.adminCreate(product, request.getAssessmentExt());
+    }
+
+    @Operation(summary = "供应商更新商品")
+    @PostMapping("/update")
+    public Result<ProductDTO> update(@RequestBody ProductCreateRequest request,
+                                     @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        Product product = request.getProduct();
+        if (product == null || product.getId() == null) {
+            return Result.error("商品ID不能为空");
+        }
+
+        // 校验商品是否属于该供应商的体系
+        Product existing = productService.getById(product.getId());
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        if (!system.getId().equals(existing.getDistributionSystemId())) {
+            return Result.error("无权操作该商品");
+        }
+
+        // 不允许修改 distributionSystemId
+        product.setDistributionSystemId(system.getId());
+
+        return productService.adminUpdate(product, request.getAssessmentExt());
+    }
+
+    @Operation(summary = "供应商商品详情")
+    @PostMapping("/detail")
+    public Result<ProductDTO> detail(@RequestBody Map<String, Object> params,
+                                     @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        if (productId == null) {
+            return Result.error("productId不能为空");
+        }
+
+        // 校验商品是否属于该供应商的体系
+        Product existing = productService.getById(productId);
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        if (!system.getId().equals(existing.getDistributionSystemId())) {
+            return Result.error("无权查看该商品");
+        }
+
+        return productService.adminDetail(productId);
+    }
+
+    @Operation(summary = "供应商删除商品")
+    @PostMapping("/delete")
+    public Result<String> delete(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        if (productId == null) {
+            return Result.error("productId不能为空");
+        }
+
+        // 校验商品是否属于该供应商的体系
+        Product existing = productService.getById(productId);
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        if (!system.getId().equals(existing.getDistributionSystemId())) {
+            return Result.error("无权操作该商品");
+        }
+
+        return productService.adminDelete(productId);
+    }
+
+    @Operation(summary = "供应商上下架商品")
+    @PostMapping("/shelve")
+    public Result<String> shelve(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("userId") Long adminId) {
+        SupplySystem system = getMySystem(adminId);
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        Boolean shelve = params.get("shelve") != null
+                ? (Boolean) params.get("shelve")
+                : null;
+
+        if (productId == null) {
+            return Result.error("productId不能为空");
+        }
+        if (shelve == null) {
+            return Result.error("shelve不能为空");
+        }
+
+        // 校验商品是否属于该供应商的体系
+        Product existing = productService.getById(productId);
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        if (!system.getId().equals(existing.getDistributionSystemId())) {
+            return Result.error("无权操作该商品");
+        }
+
+        return productService.adminShelve(productId, shelve);
+    }
+}

+ 265 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyHierarchyController.java

@@ -0,0 +1,265 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.SupplyHierarchy;
+import com.etotem.cfc.entity.SupplyHierarchyChangeRequest;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.entity.SupplySystemMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.SupplySystemMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.SupplyHierarchyService;
+import com.etotem.cfc.service.SupplySystemService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.HashSet;
+import java.util.HashSet;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/supply-hierarchy")
+public class SupplyHierarchyController {
+
+    @Resource
+    private SupplyHierarchyService supplyHierarchyService;
+
+    @Resource
+    private SupplySystemService supplySystemService;
+
+    @Resource
+    private SupplySystemMemberMapper supplySystemMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @PostMapping("/set")
+    public Result<Void> setHierarchy(@RequestBody Map<String, Object> params) {
+        try {
+            Long systemId = ParamUtils.getLong(params.get("systemId"));
+            Long parentId = ParamUtils.getLong(params.get("parentId"));
+            Long memberId = ParamUtils.getLong(params.get("childId"));
+            if (systemId == null || parentId == null || memberId == null) {
+                return Result.error("参数不完整");
+            }
+            supplyHierarchyService.setHierarchy(systemId, parentId, memberId);
+            return Result.success();
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (Exception e) {
+            return Result.error("设置失败");
+        }
+    }
+
+    @PostMapping("/remove")
+    public Result<Void> removeRelation(@RequestBody Map<String, Object> params) {
+        try {
+            Long systemId = ParamUtils.getLong(params.get("systemId"));
+            Long memberId = ParamUtils.getLong(params.get("childId"));
+            if (systemId == null || memberId == null) {
+                return Result.error("参数不完整");
+            }
+            supplyHierarchyService.removeRelation(systemId, memberId);
+            return Result.success();
+        } catch (Exception e) {
+            return Result.error("移除失败");
+        }
+    }
+
+    @PostMapping("/direct-children")
+    public Result<List<User>> getDirectChildren(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        if (systemId == null || parentId == null) {
+            return Result.error("参数不完整");
+        }
+        List<User> children = supplyHierarchyService.getDirectChildren(systemId, parentId);
+        return Result.success(children);
+    }
+
+    @PostMapping("/all-children")
+    public Result<List<User>> getAllChildren(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        if (systemId == null || parentId == null) {
+            return Result.error("参数不完整");
+        }
+        List<User> children = supplyHierarchyService.getAllChildren(systemId, parentId);
+        return Result.success(children);
+    }
+
+    @PostMapping("/parent")
+    public Result<User> getParent(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        if (systemId == null || userId == null) {
+            return Result.error("参数不完整");
+        }
+        User parent = supplyHierarchyService.getParent(systemId, userId);
+        return Result.success(parent);
+    }
+
+    @PostMapping("/parent-chain")
+    public Result<List<User>> getParentChain(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        if (systemId == null || userId == null) {
+            return Result.error("参数不完整");
+        }
+        List<User> chain = supplyHierarchyService.getParentChain(systemId, userId);
+        return Result.success(chain);
+    }
+
+    @PostMapping("/tree")
+    public Result<List<Map<String, Object>>> getTree(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) {
+            return Result.error("systemId 不能为空");
+        }
+
+        List<SupplySystemMember> members = supplySystemService.memberList(systemId);
+        Map<Long, User> userMap = new HashMap<>();
+        for (SupplySystemMember m : members) {
+            User u = userMapper.selectById(m.getUserId());
+            if (u != null) {
+                userMap.put(u.getId(), u);
+            }
+        }
+
+        List<SupplyHierarchy> allRelations = supplyHierarchyService.list(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SupplyHierarchy>()
+                        .eq(SupplyHierarchy::getSystemId, systemId)
+                        .eq(SupplyHierarchy::getStatus, "active"));
+
+        Map<Long, List<SupplyHierarchy>> childrenMap = new HashMap<>();
+        for (SupplyHierarchy r : allRelations) {
+            childrenMap.computeIfAbsent(r.getParentId(), k -> new ArrayList<>()).add(r);
+        }
+
+        SupplySystemMember admin = members.stream().filter(m -> "admin".equals(m.getRole())).findFirst().orElse(null);
+        if (admin == null) {
+            return Result.success(new ArrayList<>());
+        }
+
+        List<Map<String, Object>> root = buildTree(admin.getUserId(), childrenMap, userMap, new HashSet<>());
+        return Result.success(root);
+    }
+
+    private List<Map<String, Object>> buildTree(Long parentId, Map<Long, List<SupplyHierarchy>> childrenMap,
+                                                 Map<Long, User> userMap, HashSet<Long> visited) {
+        List<Map<String, Object>> result = new ArrayList<>();
+        if (visited.contains(parentId)) {
+            return result;
+        }
+        visited.add(parentId);
+
+        List<SupplyHierarchy> children = childrenMap.get(parentId);
+        if (children == null || children.isEmpty()) {
+            return result;
+        }
+
+        for (SupplyHierarchy h : children) {
+            User childUser = userMap.get(h.getMemberId());
+            if (childUser == null) continue;
+
+            Map<String, Object> node = new HashMap<>();
+            node.put("userId", childUser.getId());
+            node.put("nickname", childUser.getNickname());
+            node.put("realName", childUser.getRealName());
+            node.put("phone", childUser.getPhone());
+            node.put("level", h.getLevel());
+            node.put("children", buildTree(h.getMemberId(), childrenMap, userMap, visited));
+            result.add(node);
+        }
+        return result;
+    }
+
+    @PostMapping("/my")
+    public Result<Map<String, Object>> getMyRelation(@RequestBody Map<String, Object> params,
+                                                     @RequestAttribute("userId") Long userId) {
+        if (userId == null || userId < 0) {
+            return Result.error("未登录");
+        }
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        // 缺省取默认团队:优先管理员体系,否则回退到用户所属第一个团队(T31)
+        if (systemId == null) {
+            SupplySystem defaultSystem = supplySystemService.getByAdminId(userId);
+            if (defaultSystem == null) {
+                List<SupplySystem> teams = supplySystemService.getMyTeams(userId);
+                defaultSystem = teams.isEmpty() ? null : teams.get(0);
+            }
+            if (defaultSystem == null) {
+                return Result.error("您没有关联的供应商体系");
+            }
+            systemId = defaultSystem.getId();
+        }
+        // 越权防护:当前用户必须为体系的 admin/成员(T31)
+        if (!supplySystemService.isMemberOrAdmin(systemId, userId)) {
+            return Result.error("无权访问该团队");
+        }
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("systemId", systemId);
+        result.put("parent", supplyHierarchyService.getParent(systemId, userId));
+        List<User> directChildren = supplyHierarchyService.getDirectChildren(systemId, userId);
+        List<User> allChildren = supplyHierarchyService.getAllChildren(systemId, userId);
+        result.put("directChildren", directChildren);
+        result.put("allChildren", allChildren);
+        result.put("parentChain", supplyHierarchyService.getParentChain(systemId, userId));
+        // 团队规模:当前用户在体系内的全部下级(T31 页面「团队规模」统计)
+        result.put("totalChildren", allChildren == null ? 0 : allChildren.size());
+        return Result.success(result);
+    }
+
+    @PostMapping("/change-requests")
+    public Result<List<SupplyHierarchyChangeRequest>> getChangeRequests(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        String status = (String) params.get("status");
+        List<SupplyHierarchyChangeRequest> requests = supplyHierarchyService.getChangeRequests(systemId, status);
+        return Result.success(requests);
+    }
+
+    @PostMapping("/change/apply")
+    public Result<Void> applyChange(@RequestBody Map<String, Object> params) {
+        try {
+            Long systemId = ParamUtils.getLong(params.get("systemId"));
+            Long targetParentId = ParamUtils.getLong(params.get("targetParentId"));
+            String reason = (String) params.get("reason");
+            if (systemId == null || targetParentId == null) {
+                return Result.error("参数不完整");
+            }
+            supplyHierarchyService.applyChange(systemId, targetParentId, targetParentId, reason);
+            return Result.success();
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (Exception e) {
+            return Result.error("申请失败");
+        }
+    }
+
+    @PostMapping("/change/review")
+    public Result<Void> reviewChange(@RequestBody Map<String, Object> params) {
+        try {
+            Long requestId = ParamUtils.getLong(params.get("requestId"));
+            String status = (String) params.get("status");
+            String rejectReason = (String) params.get("rejectReason");
+            if (requestId == null || status == null) {
+                return Result.error("参数不完整");
+            }
+            supplyHierarchyService.reviewChange(requestId, status, rejectReason, null);
+            return Result.success();
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (Exception e) {
+            return Result.error("审核失败");
+        }
+    }
+}

+ 284 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyManageController.java

@@ -0,0 +1,284 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+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.UserService;
+import com.etotem.cfc.service.RealNameBackfillService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+
+/**
+ * 供应商管理控制器 - 供应商管理员角色专用
+ * 管理供应商用户、商品发布、服务商层级调整
+ */
+@RestController
+@RequestMapping("/api/admin/supply-manage")
+public class SupplyManageController {
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private RealNameBackfillService realNameBackfillService;
+
+    /**
+     * 供应商列表(分页+搜索)
+     * 查询拥有 supplier_admin 角色的用户
+     */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+        String keyword = (String) params.get("keyword");
+        String vendorStatus = (String) params.get("vendorStatus");
+
+        Page<User> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
+
+        // 搜索条件:手机号、昵称、真实姓名
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.and(w -> w.like(User::getPhone, keyword)
+                    .or().like(User::getNickname, keyword)
+                    .or().like(User::getRealName, keyword));
+        }
+
+        // 服务商状态筛选
+        if (vendorStatus != null && !vendorStatus.isEmpty()) {
+            wrapper.eq(User::getVendorStatus, vendorStatus);
+        }
+
+        wrapper.orderByDesc(User::getUpdatedAt);
+        SortUtil.applySort(wrapper);
+        Page<User> result = userMapper.selectPage(pageParam, wrapper);
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("list", result.getRecords());
+        data.put("total", result.getTotal());
+        data.put("page", page);
+        data.put("size", size);
+        return Result.success(data);
+    }
+
+    /**
+     * 获取供应商详情
+     */
+    @PostMapping("/detail")
+    public Result<User> detail(@RequestBody Map<String, Object> params) {
+        Object rawId = params.get("id");
+        Long id = null;
+        if (rawId instanceof Number) {
+            id = ((Number) rawId).longValue();
+        } else if (rawId instanceof String) {
+            try { id = Long.parseLong((String) rawId); } catch (NumberFormatException ignored) {}
+        }
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        User user = userMapper.selectById(id);
+        if (user == null) {
+            return Result.error("供应商不存在");
+        }
+        user.setPassword(null);
+        return Result.success(user);
+    }
+
+    /**
+     * 创建供应商
+     */
+    @PostMapping("/create")
+    public Result<User> create(@RequestBody Map<String, Object> params) {
+        String phone = (String) params.get("phone");
+        String nickname = (String) params.get("nickname");
+        String realName = (String) params.get("realName");
+        String vendorType = (String) params.get("vendorType");
+
+        if (phone == null || phone.isEmpty()) {
+            return Result.error("手机号不能为空");
+        }
+
+        // 检查手机号是否已存在
+        User existing = userMapper.selectOne(new LambdaQueryWrapper<User>()
+                .eq(User::getPhone, phone));
+        if (existing != null) {
+            return Result.error("手机号已存在");
+        }
+
+        User user = new User();
+        user.setPhone(phone);
+        user.setNickname(nickname != null ? nickname : "供应商" + phone.substring(7));
+        user.setRealName(realName);
+        user.setRole("supplier_admin");
+        // B-1/B-2:roles 数组写入供应商角色(遗留角色 supplier_admin 由 AdminRoles.normalize 归一化为 supplier)
+        user.setRoles(java.util.Arrays.asList("supplier_admin", "supplier"));
+        user.setVendorStatus("approved"); // 默认通过审核
+        String effectiveVendorType = (vendorType != null && !vendorType.isEmpty()) ? vendorType : "product_supplier";
+        user.setVendorType(effectiveVendorType);
+        if ("activity_provider".equals(effectiveVendorType)) {
+            user.setActivityProviderStatus("approved");
+        }
+        user.setCreatedAt(new Date());
+        user.setUpdatedAt(new Date());
+
+        userMapper.insert(user);
+        // 供应商创建:若提供了 realName 且 realName 尚未填写,同时回填 realName + nickname(nickname 仅空时补)
+        if (realName != null && !realName.trim().isEmpty()) {
+            realNameBackfillService.backfillRealNameAndNickname(user.getId(), realName.trim());
+        }
+        user.setPassword(null);
+        return Result.success(user);
+    }
+
+    /**
+     * 更新供应商信息
+     */
+    @PostMapping("/update")
+    public Result<Boolean> update(@RequestBody Map<String, Object> params) {
+        Long id = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+
+        User user = userMapper.selectById(id);
+        if (user == null) {
+            return Result.error("供应商不存在");
+        }
+
+        if (params.containsKey("nickname")) {
+            user.setNickname((String) params.get("nickname"));
+        }
+        if (params.containsKey("realName")) {
+            String realName = (String) params.get("realName");
+            if (realName != null && !realName.trim().isEmpty()) {
+                // 供应商更新:若 realName 尚未填写,同时回填 realName + nickname(nickname 仅空时补)
+                realNameBackfillService.backfillRealNameAndNickname(id, realName.trim());
+                // 同步内存:helper 可能补写了 nickname,保证外层 updateById 不覆盖
+                if (user.getNickname() == null || user.getNickname().trim().isEmpty()) {
+                    user.setNickname(realName.trim());
+                }
+            }
+            user.setRealName(realName);
+        }
+        if (params.containsKey("vendorType")) {
+            user.setVendorType((String) params.get("vendorType"));
+            if ("activity_provider".equals(user.getVendorType())) {
+                user.setActivityProviderStatus("approved");
+            } else if ("planner".equals(user.getVendorType()) || "product_supplier".equals(user.getVendorType())) {
+                user.setActivityProviderStatus(null);
+            }
+        }
+        if (params.containsKey("vendorStatus")) {
+            user.setVendorStatus((String) params.get("vendorStatus"));
+        }
+        if (params.containsKey("activityProviderStatus")) {
+            user.setActivityProviderStatus((String) params.get("activityProviderStatus"));
+        }
+        if (params.containsKey("vendorInfo")) {
+            user.setVendorInfo((String) params.get("vendorInfo"));
+        }
+
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+        return Result.success(true);
+    }
+
+    /**
+     * 删除供应商
+     */
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> params) {
+        Long id = params.get("id") != null ? ((Number) params.get("id")).longValue() : null;
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+
+        User user = userMapper.selectById(id);
+        if (user == null) {
+            return Result.error("供应商不存在");
+        }
+
+        userMapper.deleteById(id);
+        return Result.success(true);
+    }
+
+    /**
+     * 添加供应商管理员角色到现有用户
+     */
+    @PostMapping("/add-role")
+    public Result<Boolean> addRole(@RequestBody Map<String, Object> params) {
+        Long userId = params.get("userId") != null ? ((Number) params.get("userId")).longValue() : null;
+        if (userId == null) {
+            return Result.error("userId不能为空");
+        }
+
+        boolean added = userService.addRole(userId, "supplier_admin");
+        return added ? Result.success(true) : Result.error("添加角色失败");
+    }
+
+    /**
+     * 移除供应商管理员角色
+     */
+    @PostMapping("/remove-role")
+    public Result<Boolean> removeRole(@RequestBody Map<String, Object> params) {
+        Long userId = params.get("userId") != null ? ((Number) params.get("userId")).longValue() : null;
+        if (userId == null) {
+            return Result.error("userId不能为空");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        // 移除 supplier_admin 角色
+        if (user.getRoles() != null && user.getRoles().contains("supplier_admin")) {
+            java.util.List<String> roles = user.getRoles();
+            roles.remove("supplier_admin");
+            user.setRoles(roles);
+            user.setUpdatedAt(new Date());
+            userMapper.updateById(user);
+        }
+
+        return Result.success(true);
+    }
+
+    /**
+     * 调整服务商层级
+     * vendorType: planner / activity_provider / product_supplier
+     */
+    @PostMapping("/adjust-tier")
+    public Result<Boolean> adjustTier(@RequestBody Map<String, Object> params) {
+        Long userId = params.get("userId") != null ? ((Number) params.get("userId")).longValue() : null;
+        String vendorType = (String) params.get("vendorType");
+
+        if (userId == null || vendorType == null || vendorType.isEmpty()) {
+            return Result.error("参数不完整");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        user.setVendorType(vendorType);
+        if ("activity_provider".equals(vendorType)) {
+            user.setActivityProviderStatus("approved");
+        } else if ("planner".equals(vendorType) || "product_supplier".equals(vendorType)) {
+            user.setActivityProviderStatus(null);
+        }
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        return Result.success(true);
+    }
+}

+ 95 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplySettlementController.java

@@ -0,0 +1,95 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.SupplySettlement;
+import com.etotem.cfc.entity.SupplySettlementDetail;
+import com.etotem.cfc.service.SupplySettlementService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/supply-settlement")
+public class SupplySettlementController {
+
+    @Resource
+    private SupplySettlementService supplySettlementService;
+
+    /**
+     * 结算记录列表(分页+过滤)
+     * B-5 行级隔离:纯供应商仅能看到自己体系的结算单
+     */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute(value = "userId", required = false) Long userId,
+                                            @RequestAttribute(value = "roles", required = false) List<String> roleList) {
+        Long supplierUserId = AdminRoles.isSupplierOnly(roleList) ? userId : null;
+        return supplySettlementService.list(params, supplierUserId);
+    }
+
+    /**
+     * 结算详情
+     */
+    @PostMapping("/detail")
+    public Result<SupplySettlement> detail(@RequestBody Map<String, Object> params,
+                                           @RequestAttribute(value = "userId", required = false) Long userId,
+                                           @RequestAttribute(value = "roles", required = false) List<String> roleList) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        Long supplierUserId = AdminRoles.isSupplierOnly(roleList) ? userId : null;
+        return supplySettlementService.detail(id, supplierUserId);
+    }
+
+    /**
+     * 结算明细列表
+     */
+    @PostMapping("/detail-items")
+    public Result<List<SupplySettlementDetail>> detailItems(@RequestBody Map<String, Object> params,
+                                                            @RequestAttribute(value = "userId", required = false) Long userId,
+                                                            @RequestAttribute(value = "roles", required = false) List<String> roleList) {
+        Long settlementId = ParamUtils.getLong(params.get("settlementId"));
+        if (settlementId == null) {
+            return Result.error("settlementId不能为空");
+        }
+        Long supplierUserId = AdminRoles.isSupplierOnly(roleList) ? userId : null;
+        return supplySettlementService.detailItems(settlementId, supplierUserId);
+    }
+
+    /**
+     * 手动生成结算单(平台操作,供应商只读)
+     */
+    @PostMapping("/create")
+    public Result<SupplySettlement> create(@RequestBody Map<String, Object> params,
+                                           @RequestAttribute(value = "roles", required = false) List<String> roleList) {
+        if (AdminRoles.isSupplierOnly(roleList)) {
+            return Result.error("供应商无权生成结算单");
+        }
+        return supplySettlementService.createSettlement(params);
+    }
+
+    /**
+     * 确认结算(平台操作,供应商只读)
+     */
+    @PostMapping("/confirm")
+    public Result<Void> confirm(@RequestBody Map<String, Object> params,
+                                @RequestAttribute(value = "roles", required = false) List<String> roleList) {
+        if (AdminRoles.isSupplierOnly(roleList)) {
+            return Result.error("供应商无权确认结算");
+        }
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        return supplySettlementService.confirm(id);
+    }
+}

+ 129 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplySystemController.java

@@ -0,0 +1,129 @@
+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.SupplySystem;
+import com.etotem.cfc.entity.SupplySystemMember;
+import com.etotem.cfc.service.SupplySystemService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/supply-system")
+public class SupplySystemController {
+
+    @Resource
+    private SupplySystemService supplySystemService;
+
+    @PostMapping("/list")
+    public Result<Page<SupplySystem>> list(@RequestBody(required = false) Map<String, Object> params) {
+        String keyword = (String) params.get("keyword");
+        String status = (String) params.get("status");
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 10;
+        return Result.success(supplySystemService.list(keyword, status, page, size));
+    }
+
+    @PostMapping("/create")
+    public Result<SupplySystem> create(@RequestBody SupplySystem system) {
+        return Result.success(supplySystemService.create(system));
+    }
+
+    @PostMapping("/update")
+    public Result<SupplySystem> update(@RequestBody SupplySystem system) {
+        boolean success = supplySystemService.update(system);
+        return success ? Result.success(system) : Result.error("更新失败");
+    }
+
+    @PostMapping("/detail")
+    public Result<SupplySystem> detail(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        return Result.success(supplySystemService.detail(id));
+    }
+
+    @PostMapping("/toggle-status")
+    public Result<Void> toggleStatus(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        boolean success = supplySystemService.toggleStatus(id);
+        return success ? Result.success(null) : Result.error("操作失败");
+    }
+
+    @PostMapping("/list-all")
+    public Result<List<SupplySystem>> listAll() {
+        return Result.success(supplySystemService.listAll());
+    }
+
+    @PostMapping("/my-system")
+    public Result<SupplySystem> getMySystem(@RequestAttribute("userId") Long userId,
+                                            @RequestBody(required = false) Map<String, Object> params) {
+        if (userId == null || userId < 0) {
+            return Result.error("未登录");
+        }
+        Long systemId = params != null ? ParamUtils.getLong(params.get("systemId")) : null;
+        SupplySystem system;
+        if (systemId != null) {
+            // 显式指定团队:校验当前用户是 admin/成员,防越权读取他人团队(T31)
+            system = supplySystemService.getBySystemIdForUser(systemId, userId);
+            if (system == null) {
+                return Result.error("无权访问该团队或团队不存在");
+            }
+        } else {
+            // 缺省取默认团队:优先管理员体系,否则回退到用户所属第一个团队
+            system = supplySystemService.getByAdminId(userId);
+            if (system == null) {
+                List<SupplySystem> teams = supplySystemService.getMyTeams(userId);
+                system = teams.isEmpty() ? null : teams.get(0);
+            }
+        }
+        if (system == null) {
+            return Result.error("您没有关联的供应商体系");
+        }
+        return Result.success(system);
+    }
+
+    /**
+     * 我的团队列表(小程序端「我的团队」顶部切换器数据源,T31)
+     * 按当前登录用户鉴权,返回其作为 admin/成员的全部供应体系,不泄露他人团队。
+     */
+    @PostMapping("/my-teams")
+    public Result<List<SupplySystem>> getMyTeams(@RequestAttribute("userId") Long userId) {
+        if (userId == null || userId < 0) {
+            return Result.error("未登录");
+        }
+        return Result.success(supplySystemService.getMyTeams(userId));
+    }
+
+    // ========== Member Management ==========
+
+    @PostMapping("/member/list")
+    public Result<List<SupplySystemMember>> memberList(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        return Result.success(supplySystemService.memberList(systemId));
+    }
+
+    @PostMapping("/member/add")
+    public Result<SupplySystemMember> addMember(@RequestBody Map<String, Object> params) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        return Result.success(supplySystemService.addMember(systemId, userId));
+    }
+
+    @PostMapping("/member/remove")
+    public Result<Void> removeMember(@RequestBody Map<String, Object> params) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"));
+        boolean success = supplySystemService.removeMember(memberId);
+        return success ? Result.success(null) : Result.error("移除失败");
+    }
+
+    @PostMapping("/member/change-role")
+    public Result<Void> changeRole(@RequestBody Map<String, Object> params) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"));
+        String role = (String) params.get("role");
+        boolean success = supplySystemService.changeRole(memberId, role);
+        return success ? Result.success(null) : Result.error("角色变更失败");
+    }
+}

+ 153 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SupplyTeamController.java

@@ -0,0 +1,153 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.service.SupplyCustomerRelationService;
+import com.etotem.cfc.service.SupplySystemService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/supply-team")
+public class SupplyTeamController {
+
+    @Resource
+    private SupplyCustomerRelationService supplyCustomerRelationService;
+
+    @Resource
+    private SupplySystemService supplySystemService;
+
+    /**
+     * 查询上级供应商下的客户列表
+     */
+    @PostMapping("/customers")
+    public Result<Map<String, Object>> listCustomers(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) {
+            return Result.error("systemId不能为空");
+        }
+        // 越权防护:当前用户必须为体系的 admin/成员(T31)
+        if (!supplySystemService.isMemberOrAdmin(systemId, userId)) {
+            return Result.error("无权访问该团队");
+        }
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+
+        Map<String, Object> data = supplyCustomerRelationService.listCustomers(systemId, parentId, page, size);
+        return Result.success(data);
+    }
+
+    /**
+     * 人工绑定客户归属
+     */
+    @PostMapping("/bind-customer")
+    public Result<Void> bindCustomer(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        Long familyId = ParamUtils.getLong(params.get("familyId"));
+        Long childUserId = ParamUtils.getLong(params.get("childUserId"));
+        String source = (String) params.get("source");
+
+        boolean success = supplyCustomerRelationService.bindCustomer(systemId, parentId, familyId, childUserId, source);
+        return success ? Result.success(null) : Result.error("绑定失败");
+    }
+
+    /**
+     * 查询团队成员列表(含客户数量统计)
+     */
+    @PostMapping("/members")
+    public Result<List<Map<String, Object>>> listTeamMembers(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) {
+            return Result.error("systemId不能为空");
+        }
+        // 越权防护:当前用户必须为体系的 admin/成员(T31)
+        if (!supplySystemService.isMemberOrAdmin(systemId, userId)) {
+            return Result.error("无权访问该团队");
+        }
+        List<Map<String, Object>> members = supplyCustomerRelationService.listTeamMembers(systemId);
+        return Result.success(members);
+    }
+
+    /**
+     * 查询某个家庭的归属关系
+     */
+    @PostMapping("/relation")
+    public Result<Object> getRelation(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        Long familyId = ParamUtils.getLong(params.get("familyId"));
+        Object relation = supplyCustomerRelationService.getRelationByFamily(systemId, familyId);
+        return Result.success(relation);
+    }
+
+    // ========== 邀请功能(T38:在我的团队邀请其他用户加入)==========
+
+    /**
+     * 生成/获取我的邀请码(幂等)。body: {systemId, refresh?};refresh=true 重置旧码。
+     * 返回 {inviteCode, systemId, teamName, shareText}。仅当前用户的团队成员可调用(越权防护)。
+     */
+    @PostMapping("/invite-code")
+    public Result<Map<String, Object>> getInviteCode(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long systemId = ParamUtils.getLong(params.get("systemId"));
+        if (systemId == null) {
+            return Result.error("systemId不能为空");
+        }
+        // 越权防护:仅体系的 admin/active 成员可生成自己的邀请码(T31)
+        if (!supplySystemService.isMemberOrAdmin(systemId, userId)) {
+            return Result.error("无权操作该团队");
+        }
+        boolean refresh = Boolean.TRUE.equals(ParamUtils.getBoolean(params.get("refresh")));
+        String code = supplySystemService.generateInviteCode(systemId, userId, refresh);
+        SupplySystem system = supplySystemService.getById(systemId);
+        Map<String, Object> data = new HashMap<>();
+        data.put("inviteCode", code);
+        data.put("systemId", systemId);
+        data.put("teamName", system != null ? system.getName() : "");
+        data.put("shareText", "邀请您加入「" + (system != null && system.getName() != null ? system.getName() : "我的团队")
+                + "」,我的专属邀请码:" + code);
+        return Result.success(data);
+    }
+
+    /**
+     * 邀请码信息(确认页展示:团队名/邀请人昵称头像/成员数,不泄露其他隐私)。body: {inviteCode}
+     */
+    @PostMapping("/invite/info")
+    public Result<Map<String, Object>> getInviteInfo(@RequestBody Map<String, Object> params) {
+        String inviteCode = (String) params.get("inviteCode");
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+        return Result.success(supplySystemService.getInviteInfo(inviteCode));
+    }
+
+    /**
+     * 凭邀请码加入团队(挂邀请人为上级)。body: {inviteCode}
+     * 边界:同一 (systemId,userId) 仅 active 一次;被移除后可重新加入;role=member 不可自助变更。
+     */
+    @PostMapping("/invite/join")
+    public Result<Map<String, Object>> joinByInviteCode(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        String inviteCode = (String) params.get("inviteCode");
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+        return Result.success(supplySystemService.joinByInviteCode(inviteCode, userId));
+    }
+}

+ 75 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/SysMenuController.java

@@ -0,0 +1,75 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.SysMenu;
+import com.etotem.cfc.service.SysMenuService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/menu")
+public class SysMenuController {
+
+    @Resource
+    private SysMenuService sysMenuService;
+
+    @PostMapping("/tree")
+    public Result<List<SysMenu>> tree() {
+        return Result.success(sysMenuService.tree());
+    }
+
+    @PostMapping("/role-menus")
+    public Result<List<Long>> roleMenus(@RequestBody Map<String, String> body) {
+        String role = body.get("role");
+        return Result.success(sysMenuService.roleMenuIds(role));
+    }
+
+    @PostMapping("/save-role-menus")
+    public Result<Void> saveRoleMenus(@RequestBody Map<String, Object> body) {
+        String role = (String) body.get("role");
+        @SuppressWarnings("unchecked")
+        List<Long> menuIds = (List<Long>) body.get("menuIds");
+        sysMenuService.saveRoleMenus(role, menuIds);
+        return Result.success(null);
+    }
+
+    @PostMapping("/user-menus")
+    public Result<List<SysMenu>> userMenus(HttpServletRequest request) {
+        @SuppressWarnings("unchecked")
+        List<String> roles = (List<String>) request.getAttribute("roles");
+        return Result.success(sysMenuService.userMenus(roles));
+    }
+
+    @PostMapping("/create")
+    public Result<SysMenu> create(@RequestBody SysMenu menu) {
+        return Result.success(sysMenuService.create(menu));
+    }
+
+    @PostMapping("/update")
+    public Result<SysMenu> update(@RequestBody SysMenu menu) {
+        boolean success = sysMenuService.update(menu);
+        return success ? Result.success(menu) : Result.error("更新失败");
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestBody Map<String, Long> body) {
+        Long id = body.get("id");
+        boolean success = sysMenuService.delete(id);
+        return success ? Result.success(null) : Result.error("请先删除子菜单");
+    }
+
+    @PostMapping("/move")
+    public Result<Void> move(@RequestBody Map<String, Object> body) {
+        Long id = ((Number) body.get("id")).longValue();
+        String direction = (String) body.get("direction");
+        boolean success = sysMenuService.move(id, direction);
+        return success ? Result.success(null) : Result.error("移动失败");
+    }
+}

+ 276 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/TeamProfitAdminController.java

@@ -0,0 +1,276 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.TeamAwardRecord;
+import com.etotem.cfc.entity.TeamShareRecord;
+import com.etotem.cfc.entity.WithdrawalRequest;
+import com.etotem.cfc.service.ServiceCostConfigService;
+import com.etotem.cfc.service.TeamProfitConfigService;
+import com.etotem.cfc.service.TeamProfitFlowService;
+import com.etotem.cfc.service.WithdrawalService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 管理端团队分润(能力键 {@code team.admin.manage},单元 admin,§12-T5)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * §12-T5:成本价/星级档位(后台配置 #12)/团队门槛/团队奖分档配置 + 分润流水查询与提现审核
+ * (复用现有管理端佣金模式)。</p>
+ *
+ * <p><b>接口约定(项目规范)</b>:{@code /api/admin} 前缀统一 {@code @PostMapping},
+ * JwtInterceptor 拦截 + 控制器内管理员角色门禁(admin/operator/finance 平台角色)。</p>
+ *
+ * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
+ * §7.5 + §7.8 + §11-#12 + §12-T5。</b></p>
+ */
+@Tag(name = "管理端-团队分润")
+@RestController
+@RequestMapping("/api/admin/team-profit")
+public class TeamProfitAdminController {
+
+    @Resource
+    private TeamProfitConfigService teamProfitConfigService;
+
+    @Resource
+    private TeamProfitFlowService teamProfitFlowService;
+
+    @Resource
+    private ServiceCostConfigService serviceCostConfigService;
+
+    @Resource
+    private WithdrawalService withdrawalService;
+
+    // ==================== 配置(§7.8 + §11-#12) ====================
+
+    @Operation(summary = "团队分润配置总览(星级档位/比率/份额/归属/权重)")
+    @PostMapping("/config")
+    public Result<Map<String, Object>> config(@RequestAttribute("role") String role,
+                                              @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return gate;
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("starTiers", teamProfitConfigService.getStarTiers());
+        data.put("eightShareRatio", teamProfitConfigService.getEightShareRatio());
+        data.put("teamAwardRatio", teamProfitConfigService.getTeamAwardRatio());
+        data.put("shareTotal", teamProfitConfigService.getShareTotal());
+        data.put("awardDistribute", teamProfitConfigService.getAwardDistribute());
+        data.put("starWeight", teamProfitConfigService.getStarWeight());
+        return Result.success(data);
+    }
+
+    @Operation(summary = "保存星级档位(后台配置 #12,非 6 档拒收)")
+    @PostMapping("/config/star-tiers")
+    public Result<String> saveStarTiers(@RequestBody(required = false) Map<String, Object> body,
+                                        @RequestAttribute("role") String role,
+                                        @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        if (body == null) {
+            return Result.badRequest("请求体不能为空");
+        }
+        int[] tiers = toIntArray(body.get("starTiers"));
+        if (tiers == null) {
+            return Result.badRequest("starTiers 不能为空");
+        }
+        try {
+            teamProfitConfigService.saveStarTiers(tiers);
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+        return Result.success("星级档位已保存");
+    }
+
+    @Operation(summary = "保存团队分润配置项(写入 service_config group_key='team_profit')")
+    @PostMapping("/config/save")
+    public Result<String> saveConfig(@RequestBody(required = false) Map<String, Object> body,
+                                     @RequestAttribute("role") String role,
+                                     @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        if (body == null) {
+            return Result.badRequest("请求体不能为空");
+        }
+        String key = (String) body.get("key");
+        String value = body.get("value") != null ? String.valueOf(body.get("value")) : null;
+        if (key == null || key.trim().isEmpty()) {
+            return Result.badRequest("配置键不能为空");
+        }
+        try {
+            teamProfitConfigService.saveConfig(key, value);
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+        return Result.success("配置已保存");
+    }
+
+    // ==================== 分润流水查询(§7.3/§7.4) ====================
+
+    @Operation(summary = "8 份分佣流水分页查询(§7.3 team_share_record)")
+    @PostMapping("/flow/share-records")
+    public Result<Page<TeamShareRecord>> shareRecords(@RequestBody(required = false) Map<String, Object> body,
+                                                      @RequestAttribute("role") String role,
+                                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        Long recipientUserId = ParamUtils.getLong(body != null ? body.get("recipientUserId") : null);
+        String status = body != null ? (String) body.get("status") : null;
+        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
+        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
+        return Result.success(teamProfitFlowService.queryTeamShareRecords(recipientUserId, status, page, size));
+    }
+
+    @Operation(summary = "团队奖流水分页查询(§7.4 team_award_record)")
+    @PostMapping("/flow/award-records")
+    public Result<Page<TeamAwardRecord>> awardRecords(@RequestBody(required = false) Map<String, Object> body,
+                                                      @RequestAttribute("role") String role,
+                                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        Long teamId = ParamUtils.getLong(body != null ? body.get("teamId") : null);
+        String status = body != null ? (String) body.get("status") : null;
+        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
+        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
+        return Result.success(teamProfitFlowService.queryTeamAwardRecords(teamId, status, page, size));
+    }
+
+    // ==================== 成本价配置(§7.5) ====================
+
+    @Operation(summary = "读取服务成本价 C(分)")
+    @PostMapping("/cost/get")
+    public Result<Integer> getCost(@RequestBody(required = false) Map<String, Object> body,
+                                   @RequestAttribute("role") String role,
+                                   @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        String serviceType = body != null ? (String) body.get("serviceType") : null;
+        return Result.success(serviceCostConfigService.getCostCent(serviceType));
+    }
+
+    @Operation(summary = "保存服务成本价 C(分,管理端维护)")
+    @PostMapping("/cost/save")
+    public Result<Integer> saveCost(@RequestBody(required = false) Map<String, Object> body,
+                                    @RequestAttribute("role") String role,
+                                    @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        if (body == null) {
+            return Result.badRequest("请求体不能为空");
+        }
+        String serviceType = (String) body.get("serviceType");
+        String serviceName = (String) body.get("serviceName");
+        int costCent = (int) ParamUtils.getLong(body.get("costCent"), -1L);
+        if (serviceType == null || serviceType.trim().isEmpty()) {
+            return Result.badRequest("serviceType 不能为空");
+        }
+        if (costCent < 0) {
+            return Result.badRequest("costCent 不能为负数");
+        }
+        try {
+            return Result.success(serviceCostConfigService.saveCostCent(serviceType, serviceName, costCent));
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+    }
+
+    // ==================== 提现审核(复用 withdrawal_requests,type=team_share/team_award,§11-#7) ====================
+
+    @Operation(summary = "提现审核列表(按来源 type=team_share/team_award 过滤,§11-#7)")
+    @PostMapping("/withdrawal/list")
+    public Result<Page<WithdrawalRequest>> withdrawalList(@RequestBody(required = false) Map<String, Object> body,
+                                                          @RequestAttribute("role") String role,
+                                                          @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
+        if (gate != null) {
+            return Result.error(gate.getCode(), gate.getMessage());
+        }
+        String status = body != null ? (String) body.get("status") : null;
+        String type = body != null ? (String) body.get("type") : null;
+        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
+        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
+        return Result.success(withdrawalService.getAdminList(status, type, page, size));
+    }
+
+    // ==================== 内部辅助 ====================
+
+    /** 管理员角色门禁:平台角色(admin/operator/finance)直通;否则 403。 */
+    private Result<Map<String, Object>> requirePlatformRole(String role, List<String> roles) {
+        if ("admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles)) {
+            return null;
+        }
+        return Result.forbidden("无权限:需要管理员角色");
+    }
+
+    /** 解析请求体中的 int[](接受 List<Number>/List<String>/int[]),失败返回 null。 */
+    private int[] toIntArray(Object value) {
+        if (value == null) {
+            return null;
+        }
+        if (value instanceof int[]) {
+            return ((int[]) value).clone();
+        }
+        if (value instanceof List) {
+            List<?> list = (List<?>) value;
+            int[] result = new int[list.size()];
+            for (int i = 0; i < list.size(); i++) {
+                Object item = list.get(i);
+                if (item instanceof Number) {
+                    result[i] = ((Number) item).intValue();
+                } else if (item instanceof String) {
+                    try {
+                        result[i] = Integer.parseInt(((String) item).trim());
+                    } catch (NumberFormatException e) {
+                        return null;
+                    }
+                } else {
+                    return null;
+                }
+            }
+            return result;
+        }
+        if (value instanceof String) {
+            String raw = ((String) value).replace('[', ' ').replace(']', ' ').trim();
+            if (raw.isEmpty()) {
+                return null;
+            }
+            String[] parts = raw.split("[,/]");
+            int[] result = new int[parts.length];
+            for (int i = 0; i < parts.length; i++) {
+                try {
+                    result[i] = Integer.parseInt(parts[i].trim());
+                } catch (NumberFormatException e) {
+                    return null;
+                }
+            }
+            return result;
+        }
+        return null;
+    }
+}

+ 55 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/VirtualGoodsConfigAdminController.java

@@ -0,0 +1,55 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.VirtualGoodsConfig;
+import com.etotem.cfc.service.VirtualGoodsConfigService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/admin/virtual-goods")
+public class VirtualGoodsConfigAdminController {
+
+    @Resource
+    private VirtualGoodsConfigService virtualGoodsConfigService;
+
+    @PostMapping("/list")
+    public Result<List<VirtualGoodsConfig>> list(@RequestBody(required = false) Map<String, Object> params,
+                                                 @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String goodsType = params == null ? null : (String) params.get("goodsType");
+        return Result.success(virtualGoodsConfigService.list(goodsType));
+    }
+
+    @PostMapping("/save")
+    public Result<Boolean> save(@RequestBody VirtualGoodsConfig config,
+                                @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(virtualGoodsConfigService.saveConfig(config));
+    }
+
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> params,
+                                  @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) {
+            return Result.error("参数错误");
+        }
+        return Result.success(virtualGoodsConfigService.delete(id));
+    }
+}

+ 39 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ZodiacConfigController.java

@@ -0,0 +1,39 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ZodiacConfig;
+import com.etotem.cfc.service.ZodiacConfigService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/admin/zodiac-config")
+public class ZodiacConfigController {
+
+    @Resource
+    private ZodiacConfigService zodiacConfigService;
+
+    @PostMapping("/list")
+    public Result<List<ZodiacConfig>> list() {
+        return Result.success(zodiacConfigService.getAll());
+    }
+
+    @PostMapping("/create")
+    public Result<ZodiacConfig> create(@RequestBody ZodiacConfig config) {
+        return Result.success(zodiacConfigService.create(config));
+    }
+
+    @PostMapping("/update")
+    public Result<ZodiacConfig> update(@RequestBody ZodiacConfig config) {
+        boolean success = zodiacConfigService.update(config);
+        return success ? Result.success(config) : Result.error("更新失败");
+    }
+
+    @PostMapping("/delete")
+    public Result<Void> delete(@RequestParam Long id) {
+        boolean success = zodiacConfigService.delete(id);
+        return success ? Result.success(null) : Result.error("删除失败");
+    }
+}

+ 26 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIBehaviorController.java

@@ -0,0 +1,26 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.FamilyContextService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/ai/behavior")
+public class AIBehaviorController {
+    @Resource
+    private FamilyContextService familyContextService;
+
+    @PostMapping("/summary")
+    public Result<Map<String, Object>> getBehaviorSummary(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Long memberId = params.get("member_id") != null
+                ? Long.valueOf(params.get("member_id").toString()) : null;
+        Map<String, Object> context = familyContextService.buildContext(userId);
+        if (memberId != null) context.put("memberId", memberId);
+        return Result.success(context);
+    }
+}

+ 1101 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIChatController.java

@@ -0,0 +1,1101 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AiGateResult;
+import com.etotem.cfc.dto.HealthAnalysisResult;
+import com.etotem.cfc.dto.RecommendationQuery;
+import com.etotem.cfc.dto.RecommendationResult;
+import com.etotem.cfc.dto.TaskParseResult;
+import com.etotem.cfc.enums.AiGateStatus;
+import com.etotem.cfc.service.AIService;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.CoachSafetyGuardService;
+import com.etotem.cfc.service.FamilyContextService;
+import com.etotem.cfc.service.HealthAnalysisService;
+import com.etotem.cfc.service.RecommendationService;
+import com.etotem.cfc.service.SelfCheckAnalysisService;
+import com.etotem.cfc.service.TaskParseService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.MembershipService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * AI 聊天接口
+ * 对接 LangGraph Chatbot API,自动注入家庭上下文
+ */
+@Slf4j
+@Tag(name = "AI聊天", description = "AI家庭助手聊天接口")
+@RestController
+@RequestMapping("/api/ai")
+public class AIChatController {
+
+    @Resource
+    private AIService aiService;
+
+    @Resource
+    private FamilyContextService familyContextService;
+
+    @Resource
+    private HealthAnalysisService healthAnalysisService;
+
+    @Resource
+    private SelfCheckAnalysisService selfCheckAnalysisService;
+
+    @Resource
+    private RecommendationService recommendationService;
+
+    @Resource
+    private com.etotem.cfc.service.GrowthTaskService growthTaskService;
+
+    @Resource
+    private TaskParseService taskParseService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private com.etotem.cfc.service.ChatMirrorService chatMirrorService;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    /** 内容安全过滤前置门禁(ai.coach.safetyGuard / SC-B-05)。 */
+    @Resource
+    private CoachSafetyGuardService coachSafetyGuardService;
+
+    /** 纯单测/离线环境未注入时的兜底实例(内置基础词库)。 */
+    private static final CoachSafetyGuardService DEFAULT_SAFETY_GUARD = new CoachSafetyGuardService();
+
+    @Resource
+    private com.etotem.cfc.service.PortraitService portraitService;
+
+    @Resource
+    private com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper selfCheckMapper;
+
+    @Resource
+    private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
+
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
+
+    /** 会员专享业务错误码:前端据此展示会员开通付费墙(UPGRADE_REQUIRED) */
+    private static final int ERR_AI_COACH_MEMBER_ONLY = 46003;
+
+    /** 会员已过期业务错误码:前端据此展示续费引导(MEMBER_EXPIRED) */
+    private static final int ERR_AI_MEMBER_EXPIRED = 46004;
+
+    /** AI 教练对应的会员权益功能码 */
+    private static final String AI_COACH_FEATURE = "mascot_ai";
+
+    /** 内容安全命中拒答业务错误码(区别于会员门禁 46003/46004,不返回 500) */
+    private static final int ERR_CONTENT_SAFETY_BLOCKED = 46005;
+
+    /**
+     * 门禁拦截统一响应:过期 → 46004;从未付费 → 46003。
+     */
+    private <T> Result<T> gateError(AiGateResult gate) {
+        if (gate != null && gate.getStatus() == AiGateStatus.MEMBER_EXPIRED) {
+            return Result.error(ERR_AI_MEMBER_EXPIRED, "会员已过期,请续费后继续使用");
+        }
+        return Result.error(ERR_AI_COACH_MEMBER_ONLY, "该功能为会员专享,请先开通会员");
+    }
+
+    /**
+     * 门禁校验:返回 null 表示放行,否则返回拦截响应。
+     * 原 canUseAiCoach()(仅 FAMILY/PREMIUM)已收敛到此处统一门禁(BASIC+ 且需在有效期内)。
+     */
+    private <T> Result<T> checkGate(Long userId) {
+        AiGateResult gate = membershipService.checkAiFeatureGate(userId);
+        if (gate == null || !gate.isCanUse()) {
+            return gateError(gate);
+        }
+        return null;
+    }
+
+    /**
+     * 组装 /api/ai/gate 的 features 明细:
+     * 纳入门禁的 4 项同源同 status;不纳入门禁的 4 项固定放行。
+     */
+    private Map<String, AiGateResult.FeatureGate> buildGateFeatures(AiGateResult gate) {
+        boolean canUse = gate != null && gate.isCanUse();
+        String reason = gate != null ? gate.getReason() : AiGateStatus.UPGRADE_REQUIRED.name();
+        AiGateResult.FeatureGate gated = new AiGateResult.FeatureGate(canUse, canUse ? null : reason);
+
+        Map<String, AiGateResult.FeatureGate> features = new LinkedHashMap<>();
+        features.put("chat", gated);
+        features.put("nutrition", gated);
+        features.put("healthCoach", gated);
+        features.put("butler", gated);
+        features.put("reportAnalyze", AiGateResult.FeatureGate.allow());
+        features.put("emotion", AiGateResult.FeatureGate.allow());
+        features.put("tongue", AiGateResult.FeatureGate.allow());
+        features.put("diet", AiGateResult.FeatureGate.allow());
+        return features;
+    }
+
+    @Operation(summary = "发送聊天消息(支持传入reportId以解读报告)")
+    @PostMapping("/chat/send")
+    public Result<Map<String, Object>> sendMessage(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> params) {
+        String query = params.get("query");
+        String conversationId = params.get("conversationId");
+
+        if (query == null || query.trim().isEmpty()) {
+            return Result.error("消息不能为空");
+        }
+
+        // 内容安全前置门禁(SC-B-05):命中敏感词/提示词注入即拒答 + 合规提示,
+        // 不透传 LangGraph、不泄露内部错误、不返回 500。
+        CoachSafetyGuardService guard = coachSafetyGuardService != null
+                ? coachSafetyGuardService : DEFAULT_SAFETY_GUARD;
+        String sensitiveCategory = guard.detectCategory(query);
+        if (sensitiveCategory != null) {
+            return Result.error(ERR_CONTENT_SAFETY_BLOCKED, guard.refuseNotice(sensitiveCategory));
+        }
+
+        // AI 使用会员门禁(前置;放行后仍走原配额链 AiGateway/consumeMemberQuota)
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+
+        // 复用上下文组装(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
+        Map<String, Object> inputs = buildChatInputs(userId, params);
+
+        Map<String, Object> difyResp = aiService.sendMessage(
+                query, String.valueOf(userId),
+                conversationId, inputs);
+
+        String answer = (String) difyResp.getOrDefault("answer", "");
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("answer", answer);
+        result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
+        // 降级态标记透传(SC-B-06 / e2e TC-B-06/2):供前端提示「AI 服务降级中」
+        if (Boolean.TRUE.equals(difyResp.get("degraded"))) {
+            result.put("degraded", Boolean.TRUE);
+            result.put("fallbackUsed", Boolean.TRUE);
+        }
+
+        // Parse [TASK] markers and create task records
+        List<Map<String, Object>> tasks = new ArrayList<>();
+        List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
+        String cleanAnswer = taskParseService.stripTaskMarkers(answer);
+        
+        for (TaskParseResult taskResult : parsedTasks) {
+            com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
+                userId,
+                taskResult.getTitle(),
+                taskResult.getDescription(),
+                taskResult.getDimension(),
+                taskResult.getRewardPoints(),
+                (String) difyResp.getOrDefault("conversationId", "")
+            );
+            Map<String, Object> taskInfo = new LinkedHashMap<>();
+            taskInfo.put("id", task.getId());
+            taskInfo.put("title", task.getTitle());
+            taskInfo.put("description", task.getDescription());
+            taskInfo.put("dimension", task.getDimension());
+            taskInfo.put("rewardPoints", task.getRewardPoints());
+            tasks.add(taskInfo);
+        }
+        
+        result.put("answer", cleanAnswer);
+        result.put("tasks", tasks);
+
+        try { growthTaskService.updateProgress(userId, "DAILY_AI", 1); } catch (Exception e) { log.warn("成长任务AI对话进度更新失败: userId={}, error={}", userId, e.getMessage()); }
+
+        return Result.success(result);
+    }
+
+    /**
+     * 组装 AI 对话上下文(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
+     * 供 /chat/send 和 /report/analyze 共用
+     */
+    private Map<String, Object> buildChatInputs(Long userId, Map<String, String> params) {
+        String conversationId = params.get("conversationId");
+        String reportIdStr = params.get("reportId");
+        String surveyIdStr = params.get("surveyId");
+        String selfCheckIdStr = params.get("selfCheckId");
+
+        // 获取用户mascot设置
+        com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
+        String mascotCode = user != null ? user.getMascot() : null;
+
+        // 组装家庭上下文(如果指定reportId/surveyId,注入报告+问卷数据)
+        Long reportId = null;
+        Long surveyId = null;
+        if (reportIdStr != null && !reportIdStr.trim().isEmpty()) {
+            reportId = Long.valueOf(reportIdStr);
+        }
+        if (surveyIdStr != null && !surveyIdStr.trim().isEmpty()) {
+            surveyId = Long.valueOf(surveyIdStr);
+        }
+        String draftIdStr = params.get("draftId");
+        Long draftId = null;
+        if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
+            draftId = Long.valueOf(draftIdStr);
+        }
+        Map<String, Object> inputs;
+        if (reportId != null && surveyId != null) {
+            inputs = familyContextService.buildContext(userId, reportId, surveyId);
+        } else if (reportId != null) {
+            inputs = familyContextService.buildContext(userId, reportId);
+        } else if (draftId != null) {
+            inputs = familyContextService.buildContextFromDraft(userId, draftId);
+        } else {
+            inputs = familyContextService.buildContext(userId);
+        }
+
+        // 注入mascot信息到LangGraph inputs
+        if (mascotCode != null && !mascotCode.isEmpty()) {
+            com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
+            if (mascot != null) {
+                inputs.put("mascot_name", mascot.name());
+                inputs.put("mascot_gender", mascot.gender());
+                inputs.put("mascot_persona", mascot.persona());
+            }
+        } else {
+            inputs.put("mascot_name", "小助手");
+            inputs.put("mascot_gender", "");
+            inputs.put("mascot_persona", "");
+        }
+
+        // 画像注入
+        String chatMemberIdStr = params.get("memberId");
+        Long chatMemberId = chatMemberIdStr != null && !chatMemberIdStr.trim().isEmpty()
+                ? Long.valueOf(chatMemberIdStr) : null;
+        String chatPortrait = portraitService.buildPortraitPrompt(userId, chatMemberId);
+        if (chatPortrait != null) {
+            inputs.put("portrait_prompt", chatPortrait);
+        }
+
+        // 注入自检上下文(P1-2):自动注入最近一次自检摘要(维度分 + 低分项),
+        // 使 /chat/send 无需前端额外传参即可针对自检结果连续对话;
+        // 指定 selfCheckId 时优先用该记录(服务内校验归属,无效静默跳过)
+        Long selfCheckId = null;
+        if (selfCheckIdStr != null && !selfCheckIdStr.trim().isEmpty()) {
+            try {
+                selfCheckId = Long.valueOf(selfCheckIdStr);
+            } catch (Exception e) {
+                log.warn("selfCheckId 解析失败: {}", e.getMessage());
+            }
+        }
+        java.util.Map<String, Object> selfCheckSummary = selfCheckAnalysisService.buildLatestSummary(userId, selfCheckId);
+        if (selfCheckSummary != null) {
+            try {
+                inputs.put("self_check_result", objectMapper.writeValueAsString(selfCheckSummary));
+            } catch (Exception e) {
+                log.warn("序列化自检上下文失败: {}", e.getMessage());
+            }
+        }
+
+        // AI记忆层注入(会话摘要+关键事实)
+        inputs = aiService.enrichInputsWithMemory(userId, conversationId, inputs);
+        return inputs;
+    }
+
+    @Operation(summary = "报告快速分析(免费版每日1次,付费版多轮)")
+    @PostMapping("/report/analyze")
+    public Result<Map<String, Object>> reportAnalyze(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> params) {
+        String query = params.get("query");
+        String reportIdStr = params.get("reportId");
+        String draftIdStr = params.get("draftId");
+        if (query == null || query.trim().isEmpty()) {
+            return Result.error("消息不能为空");
+        }
+        if ((reportIdStr == null || reportIdStr.trim().isEmpty())
+                && (draftIdStr == null || draftIdStr.trim().isEmpty())) {
+            return Result.error("报告ID或草稿ID不能为空");
+        }
+
+        // 1. 会员级别检查
+        com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
+        String memberLevel = user != null ? user.getMemberLevel() : "FREE";
+        boolean isFree = memberLevel == null || "FREE".equals(memberLevel);
+
+        // 2. 免费版 Redis 计数(每日 1 次;Redis 异常时 fail-open 放行)
+        if (isFree) {
+            try {
+                String key = "report:analyze:free:" + userId + ":" + LocalDate.now();
+                Long count = redisTemplate.opsForValue().increment(key);
+                if (count != null && count == 1L) {
+                    redisTemplate.expire(key, Duration.ofDays(1));
+                }
+                if (count != null && count > 1L) {
+                    return Result.error("免费版每日仅限 1 次快速分析,升级会员解锁更多");
+                }
+            } catch (Exception e) {
+                log.warn("Redis 计数失败,放行: {}", e.getMessage());
+            }
+        }
+
+        // 3. 组装上下文(免费版不带 conversationId → LangGraph 每次新建会话,锁死多轮)
+        if (isFree) {
+            params.remove("conversationId");
+        }
+        Map<String, Object> inputs = buildChatInputs(userId, params);
+
+        // 3.5 报告可用性门禁(S-cfc-350 / TC-B-04-E)
+        //   - draftId 路径:草稿上下文必须已带解析后 payload(reportDetail),否则视为「报告解析中」
+        //   - reportId 路径:上下文已带 reportDetail 时按归属校验;缺 reportDetail 视为无报告 → 提示上传
+        if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
+            Object draftDetail = inputs.get("reportDetail");
+            if (!(draftDetail instanceof Map) || ((Map<?, ?>) draftDetail).isEmpty()) {
+                return Result.error("报告解析中,请稍后重试");
+            }
+        } else {
+            Object detailObj = inputs.get("reportDetail");
+            if (detailObj instanceof Map) {
+                Object reportObj = ((Map<?, ?>) detailObj).get("report");
+                if (reportObj == null) {
+                    return Result.error("尚未上传报告,请先上传报告后再发起解读");
+                }
+                Result<Void> accessDenied = checkReportAccess(user, reportObj);
+                if (accessDenied != null) {
+                    @SuppressWarnings("unchecked")
+                    Result<Map<String, Object>> denied = (Result<Map<String, Object>>) (Result<?>) accessDenied;
+                    return denied;
+                }
+            }
+            // detailObj 缺失/非 Map(如上下文未注入 reportDetail):保持原有宽容行为,交由 AI 侧兜底回答
+        }
+
+        // 4. 调 LangGraph(经 aiService.sendMessage 含记忆层+镜像)
+        Map<String, Object> difyResp = aiService.sendMessage(
+                query, String.valueOf(userId),
+                params.get("conversationId"), inputs);
+
+        if (difyResp == null || difyResp.isEmpty()) {
+            return Result.error("AI 服务暂不可用,请稍后重试");
+        }
+        String answer = (String) difyResp.getOrDefault("answer", "");
+        String cleanAnswer = maskSensitiveInfo(taskParseService.stripTaskMarkers(answer));
+
+        // 5. 结构化三段输出(通俗解读 / 五维关联 / 行动建议)+ 类型一致性提示
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("answer", cleanAnswer);
+        result.put("plainSummary", cleanAnswer);
+        result.put("fiveDimAssociations", buildFiveDimAssociations(cleanAnswer));
+        result.put("actionSuggestions", buildActionSuggestions(cleanAnswer));
+        result.put("typeWarning", buildTypeWarning(inputs));
+        result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
+        return Result.success(result);
+    }
+
+    /**
+     * 报告归属校验(TC-B-04-P):报告已带 familyId 且与当前登录用户家庭不一致 → 拒绝。
+     * 报告缺 familyId(历史数据/未归属)时 fail-open 放行,由上游 family 上下文保证隔离。
+     */
+    private Result<Void> checkReportAccess(com.etotem.cfc.entity.User user, Object reportObj) {
+        if (!(reportObj instanceof com.etotem.cfc.entity.HealthReport)) {
+            return null;
+        }
+        com.etotem.cfc.entity.HealthReport report = (com.etotem.cfc.entity.HealthReport) reportObj;
+        Long reportFamilyId = report.getFamilyId();
+        if (reportFamilyId == null || user == null) {
+            return null;
+        }
+        Long userFamilyId = user.getFamilyId();
+        if (userFamilyId != null && !reportFamilyId.equals(userFamilyId)) {
+            return Result.forbidden("无权解读该报告,报告不属于当前家庭");
+        }
+        return null;
+    }
+
+    /** 五维关键词表(身/心/智/行/富) */
+    private static final String[][] FIVE_DIM_KEYWORDS = {
+            // body 身
+            {"肠道", "菌群", "免疫", "营养", "代谢", "消化", "身体", "体质", "健康", "炎症", "睡眠", "体重"},
+            // mind 心
+            {"情绪", "压力", "焦虑", "心理", "心情", "情感", "抑郁", "心态"},
+            // intellect 智
+            {"认知", "学习", "记忆", "专注", "注意力", "智力", "思维", "大脑"},
+            // action 行
+            {"运动", "锻炼", "作息", "习惯", "行为", "活动", "执行", "坚持"},
+            // wealth 富
+            {"医疗", "保险", "费用", "花费", "支出", "财富", "理财", "预算", "经济"}
+    };
+
+    private static final String[] FIVE_DIM_FALLBACKS = {
+            "身体维度:建议结合本次报告关注身体基础指标,维持均衡饮食与规律作息。",
+            "心理维度:报告未直接覆盖情绪,可结合日常情绪变化观察身体状况对心理的影响。",
+            "智力维度:报告未直接覆盖认知,可关注营养与睡眠对学习专注度的间接支持。",
+            "行动维度:建议把报告中的改善建议转化为可执行的小步骤并持续跟进。",
+            "财富维度:报告未涉及财务信息,可在医疗/营养支出上做合理规划。"
+    };
+
+    private static final String[] ACTION_SUGGESTION_KEYWORDS = {
+            "建议", "应该", "可以", "需要", "推荐", "尽量", "注意", "不妨", "宜"
+    };
+
+    private static final List<String> DEFAULT_ACTION_SUGGESTIONS;
+
+    static {
+        List<String> defaults = new ArrayList<>();
+        defaults.add("建议结合报告结论,把改善动作拆成每天可完成的小步骤并记录执行情况。");
+        defaults.add("建议持续跟踪关键指标变化,必要时复检或咨询专业人士。");
+        DEFAULT_ACTION_SUGGESTIONS = Collections.unmodifiableList(defaults);
+    }
+
+    /** 把解读文本按中文句读切分为句子 */
+    private List<String> splitSentences(String text) {
+        List<String> sentences = new ArrayList<>();
+        if (text == null || text.trim().isEmpty()) {
+            return sentences;
+        }
+        String[] parts = text.split("[。!?!?;;\n]+");
+        for (String part : parts) {
+            String trimmed = part == null ? "" : part.trim();
+            if (!trimmed.isEmpty()) {
+                sentences.add(trimmed);
+            }
+        }
+        return sentences;
+    }
+
+    /**
+     * 基于关键词把解读文本映射到身/心/智/行/富五维;命不中的维度用兜底文案,
+     * 保证输出恒定含 body/mind/intellect/action/wealth 五键。
+     */
+    private Map<String, Object> buildFiveDimAssociations(String text) {
+        List<String> sentences = splitSentences(text);
+        String[] dimKeys = {"body", "mind", "intellect", "action", "wealth"};
+        Map<String, Object> dims = new LinkedHashMap<>();
+        for (int i = 0; i < dimKeys.length; i++) {
+            String matched = null;
+            for (String sentence : sentences) {
+                for (String keyword : FIVE_DIM_KEYWORDS[i]) {
+                    if (sentence.contains(keyword)) {
+                        matched = sentence;
+                        break;
+                    }
+                }
+                if (matched != null) break;
+            }
+            dims.put(dimKeys[i], matched != null ? matched : FIVE_DIM_FALLBACKS[i]);
+        }
+        return dims;
+    }
+
+    /** 抽取含建议类关键词的句子作为行动建议;无命中时返回兜底建议 */
+    private List<String> buildActionSuggestions(String text) {
+        List<String> suggestions = new ArrayList<>();
+        for (String sentence : splitSentences(text)) {
+            for (String keyword : ACTION_SUGGESTION_KEYWORDS) {
+                if (sentence.contains(keyword)) {
+                    suggestions.add(sentence);
+                    break;
+                }
+            }
+        }
+        if (suggestions.isEmpty()) {
+            return new ArrayList<>(DEFAULT_ACTION_SUGGESTIONS);
+        }
+        return suggestions;
+    }
+
+    /**
+     * 报告类型一致性提示:类型集合为空 / 含未知类型 / 多于一种类型时视为不可横向比较。
+     */
+    private Map<String, Object> buildTypeWarning(Map<String, Object> inputs) {
+        Set<String> types = new LinkedHashSet<>();
+        Object detailObj = inputs.get("reportDetail");
+        if (detailObj instanceof Map) {
+            Object reportObj = ((Map<?, ?>) detailObj).get("report");
+            if (reportObj instanceof com.etotem.cfc.entity.HealthReport) {
+                String reportType = ((com.etotem.cfc.entity.HealthReport) reportObj).getReportType();
+                if (reportType != null && !reportType.trim().isEmpty()) {
+                    types.add(reportType.trim());
+                } else {
+                    types.add("");
+                }
+            }
+        }
+        boolean mismatch = types.isEmpty() || types.contains("") || types.size() > 1;
+        Map<String, Object> warning = new LinkedHashMap<>();
+        warning.put("mismatch", mismatch);
+        if (mismatch) {
+            warning.put("message", "检测到不同类型的报告,数据口径不一致,不建议直接横向比较");
+        }
+        return warning;
+    }
+
+    // ── PII 脱敏(S-cfc-350 / TC-B-04-E 异常流-4) ──
+
+    /** 中国大陆手机号:1[3-9] 开头的 11 位数字,前后不接数字 */
+    private static final Pattern PII_PHONE_PATTERN =
+            Pattern.compile("(?<!\\d)1[3-9]\\d{9}(?!\\d)");
+
+    /** 长数字串(身份证/银行卡等 15-18 位)整体遮蔽 */
+    private static final Pattern PII_LONG_DIGIT_PATTERN =
+            Pattern.compile("(?<!\\d)\\d{15,18}(?!\\d)");
+
+    /** 中文姓名:2-3 个汉字后紧跟「的」或称谓类后缀 */
+    private static final Pattern PII_NAME_PATTERN =
+            Pattern.compile("[\\u4e00-\\u9fa5]{2,3}(?=的|先生|女士|小姐|老师|医生|大夫|教授|主任|同学|患者|受检人|受检者|本人)");
+
+    /** 姓名脱敏白名单:常见泛指/亲属/职业/部位词,命中后缀时不应被当成姓名遮蔽 */
+    private static final Set<String> NAME_STOPWORDS;
+
+    static {
+        Set<String> words = new HashSet<>();
+        String[] raw = {
+                "孩子", "家长", "小孩", "宝宝", "儿童", "学生", "大人", "父母", "爸爸", "妈妈",
+                "爷爷", "奶奶", "外公", "外婆", "哥哥", "姐姐", "弟弟", "妹妹", "儿子", "女儿",
+                "老师", "医生", "大夫", "护士", "教授", "主任", "同学", "朋友", "本人", "患者",
+                "受检人", "受检者", "用户", "我们", "他们", "大家", "建议", "关注", "注意",
+                "肠道", "菌群", "免疫", "营养", "代谢", "消化", "睡眠", "体重", "体质",
+                "情绪", "心理", "压力", "焦虑", "认知", "学习", "记忆", "专注", "大脑",
+                "运动", "锻炼", "作息", "习惯", "行为", "医疗", "保险", "费用", "花费",
+                "主治", "主治医生", "可联系主治", "联系", "可以联系", "报告", "数据", "结果",
+                "以上", "以下", "如下", "因此", "所以", "但是", "然而", "如果", "当", "其中",
+                "其他", "其它", "有些", "有的", "所有", "任何", "每个", "某些", "这种", "那种"
+        };
+        for (String w : raw) {
+            words.add(w);
+        }
+        NAME_STOPWORDS = Collections.unmodifiableSet(words);
+    }
+
+    /**
+     * 对解读输出做最小必要脱敏:手机号 → 前 3 + **** + 后 4;长数字串遮蔽;中文姓名 → ***。
+     */
+    private String maskSensitiveInfo(String text) {
+        if (text == null || text.isEmpty()) {
+            return text;
+        }
+        Matcher phoneMatcher = PII_PHONE_PATTERN.matcher(text);
+        StringBuffer phoneBuf = new StringBuffer();
+        while (phoneMatcher.find()) {
+            String full = phoneMatcher.group();
+            phoneMatcher.appendReplacement(phoneBuf,
+                    Matcher.quoteReplacement(full.substring(0, 3) + "****" + full.substring(full.length() - 4)));
+        }
+        phoneMatcher.appendTail(phoneBuf);
+        String masked = PII_LONG_DIGIT_PATTERN.matcher(phoneBuf.toString()).replaceAll("********");
+        Matcher nameMatcher = PII_NAME_PATTERN.matcher(masked);
+        StringBuilder sb = new StringBuilder();
+        int lastEnd = 0;
+        while (nameMatcher.find()) {
+            String token = nameMatcher.group();
+            int start = nameMatcher.start();
+            sb.append(masked, lastEnd, start);
+            if (NAME_STOPWORDS.contains(token)) {
+                sb.append(token);
+            } else {
+                sb.append("***");
+            }
+            lastEnd = nameMatcher.end();
+        }
+        sb.append(masked.substring(lastEnd));
+        return sb.toString();
+    }
+
+    @Operation(summary = "获取会话列表")
+    @PostMapping("/chat/conversations")
+    public Result<List<Map<String, Object>>> getConversations(
+            @RequestAttribute("userId") Long userId) {
+        try {
+            List<Map<String, Object>> list = aiService.getConversations(String.valueOf(userId));
+            return Result.success(list);
+        } catch (Exception e) {
+            log.warn("LangGraph获取会话列表失败,回退到本地: {}", e.getMessage());
+            List<com.etotem.cfc.entity.ChatConversation> local = chatMirrorService.getConversations(userId);
+            List<Map<String, Object>> fallback = new ArrayList<>();
+            for (com.etotem.cfc.entity.ChatConversation c : local) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("id", c.getDifyConversationId());
+                m.put("name", c.getTitle());
+                m.put("last_message_at", c.getLastMessageAt());
+                fallback.add(m);
+            }
+            return Result.success(fallback);
+        }
+    }
+
+    @Operation(summary = "获取消息历史")
+    @PostMapping("/chat/messages")
+    public Result<List<Map<String, Object>>> getMessages(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> params) {
+        String conversationId = params.get("conversationId");
+        if (conversationId == null || conversationId.trim().isEmpty()) {
+            return Result.error("conversationId 不能为空");
+        }
+        try {
+            List<Map<String, Object>> list = aiService.getMessages(conversationId, String.valueOf(userId));
+            return Result.success(list);
+        } catch (Exception e) {
+            log.warn("LangGraph获取消息历史失败,回退到本地: {}", e.getMessage());
+            List<com.etotem.cfc.entity.ChatConversation> conversations = chatMirrorService.getConversations(userId);
+            Long localConvId = null;
+            for (com.etotem.cfc.entity.ChatConversation c : conversations) {
+                if (conversationId.equals(c.getDifyConversationId())) {
+                    localConvId = c.getId();
+                    break;
+                }
+            }
+            if (localConvId == null) {
+                return Result.success(Collections.emptyList());
+            }
+            List<com.etotem.cfc.entity.ChatMessage> messages = chatMirrorService.getMessages(localConvId);
+            List<Map<String, Object>> fallback = new ArrayList<>();
+            for (com.etotem.cfc.entity.ChatMessage msg : messages) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("role", msg.getRole());
+                m.put("content", msg.getContent());
+                m.put("created_at", msg.getCreatedAt());
+                fallback.add(m);
+            }
+            return Result.success(fallback);
+        }
+    }
+
+    @Operation(summary = "删除会话")
+    @PostMapping("/chat/conversations/{id}/delete")
+    public Result<Void> deleteConversation(
+            @RequestAttribute("userId") Long userId,
+            @PathVariable("id") String conversationId) {
+        aiService.deleteConversation(conversationId, String.valueOf(userId));
+        return Result.success(null);
+    }
+
+    // ── 精准营养助手 ──
+
+    private static final Pattern RECOMMEND_PATTERN =
+            Pattern.compile("\\[RECOMMEND:\\s*(\\{.*?\\})\\]", Pattern.DOTALL);
+
+    @Operation(summary = "发送营养分析消息(基于菌群报告)")
+    @PostMapping("/nutrition/send")
+    public Result<Map<String, Object>> sendNutritionMessage(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> params) {
+        String query = params.get("query");
+        String conversationId = params.get("conversationId");
+        String reportIdStr = params.get("reportId");
+
+        if (query == null || query.trim().isEmpty()) {
+            return Result.error("消息不能为空");
+        }
+        if (reportIdStr == null || reportIdStr.trim().isEmpty()) {
+            return Result.error("需要reportId进行营养分析");
+        }
+
+        // AI 使用会员门禁(参数校验后、分析前)
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+
+        // 获取用户mascot设置
+        com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
+        String mascotCode = user != null ? user.getMascot() : null;
+
+        Long reportId = Long.valueOf(reportIdStr);
+
+        // 1. 菌群分析
+        HealthAnalysisResult analysis = healthAnalysisService.analyze(reportId);
+        if (analysis == null) {
+            return Result.error("报告不存在或分析失败: reportId=" + reportId);
+        }
+
+        // 2. 构建 LangGraph inputs(菌群分析 + 家庭上下文)
+        Map<String, Object> inputs = familyContextService.buildContext(userId);
+        inputs.put("health_analysis", analysis);
+
+        // 注入mascot信息到LangGraph inputs
+        if (mascotCode != null && !mascotCode.isEmpty()) {
+            com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
+            if (mascot != null) {
+                inputs.put("mascot_name", mascot.name());
+                inputs.put("mascot_gender", mascot.gender());
+                inputs.put("mascot_persona", mascot.persona());
+            }
+        } else {
+            inputs.put("mascot_name", "小助手");
+            inputs.put("mascot_gender", "");
+            inputs.put("mascot_persona", "");
+        }
+
+        // 3. 注入用户画像
+        String memberIdStr = params.get("memberId");
+        Long memberId = memberIdStr != null && !memberIdStr.trim().isEmpty()
+                ? Long.valueOf(memberIdStr) : null;
+        String portraitPrompt = portraitService.buildPortraitPrompt(userId, memberId);
+        if (portraitPrompt != null) {
+            inputs.put("portrait_prompt", portraitPrompt);
+        }
+
+        // 4. 调用营养助手(走 LangGraph)
+        // 契约 langgraph.intent.errorPropagate:上游 429/401 由 AiGateway.chat 直接抛出,
+        // 不在此处吞 null 伪装成「普通失败」;编排层(Controller)负责统一降级
+        Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
+
+        String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
+
+        // 4. 解析 [RECOMMEND] 标记
+        List<RecommendationResult> recommendations = null;
+        String cleanAnswer = answer;
+        Matcher matcher = RECOMMEND_PATTERN.matcher(answer);
+        if (matcher.find()) {
+            try {
+                String json = matcher.group(1);
+                // 简单 JSON 解析(不用 Jackson 避免异常链)
+                Map<String, Object> rec = parseSimpleJson(json);
+                if (rec != null) {
+                    @SuppressWarnings("unchecked")
+                    List<String> tags = (List<String>) rec.get("tags");
+                    @SuppressWarnings("unchecked")
+                    List<String> types = (List<String>) rec.get("types");
+                    Object limitObj = rec.get("limit");
+                    int limit = limitObj instanceof Number ? ((Number) limitObj).intValue() : 3;
+
+                    if (tags != null && !tags.isEmpty()) {
+                        RecommendationQuery rq = new RecommendationQuery();
+                        rq.setNutritionTags(tags);
+                        rq.setTypes(types != null && !types.isEmpty() ? types : null);
+                        rq.setLimit(limit);
+                        rq.setUserId(userId);
+                        if (user != null) {
+                            rq.setFamilyId(user.getFamilyId());
+                        }
+                        recommendations = recommendationService.search(rq);
+                    }
+                }
+            } catch (Exception e) {
+                log.warn("解析 [RECOMMEND] 标记失败, 忽略: {}", e.getMessage());
+            }
+        // 从回答中移除标记
+        cleanAnswer = matcher.replaceAll("").trim();
+    }
+
+    // Parse [TASK] markers and create task records
+    List<Map<String, Object>> tasks = new ArrayList<>();
+    List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
+    cleanAnswer = taskParseService.stripTaskMarkers(cleanAnswer);
+    
+    for (TaskParseResult taskResult : parsedTasks) {
+        com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
+            userId,
+            taskResult.getTitle(),
+            taskResult.getDescription(),
+            taskResult.getDimension(),
+            taskResult.getRewardPoints(),
+            null
+        );
+        Map<String, Object> taskInfo = new LinkedHashMap<>();
+        taskInfo.put("id", task.getId());
+        taskInfo.put("title", task.getTitle());
+        taskInfo.put("description", task.getDescription());
+        taskInfo.put("dimension", task.getDimension());
+        taskInfo.put("rewardPoints", task.getRewardPoints());
+        tasks.add(taskInfo);
+    }
+
+    // 5. 组装结果
+    Map<String, Object> result = new LinkedHashMap<>();
+    result.put("answer", cleanAnswer);
+    result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
+    result.put("recommendations", recommendations != null ? recommendations : Collections.emptyList());
+    result.put("tasks", tasks);
+    return Result.success(result);
+    }
+
+    /**
+     * 极简 JSON 解析(仅用于 [RECOMMEND] 标记中的简单对象)
+     * 避免引入 Jackson 依赖或抛异常
+     */
+    private Map<String, Object> parseSimpleJson(String json) {
+        json = json.trim();
+        if (!json.startsWith("{") || !json.endsWith("}")) return null;
+        json = json.substring(1, json.length() - 1).trim();
+
+        Map<String, Object> map = new LinkedHashMap<>();
+        // 按逗号分割顶层键值对(忽略引号内的逗号)
+        List<String> pairs = splitOutsideQuotes(json);
+        for (String pair : pairs) {
+            int colonIdx = pair.indexOf(':');
+            if (colonIdx < 0) continue;
+            String key = pair.substring(0, colonIdx).trim();
+            String value = pair.substring(colonIdx + 1).trim();
+            key = stripQuotes(key);
+            if (key.isEmpty()) continue;
+
+            if (value.startsWith("[") && value.endsWith("]")) {
+                // 解析数组
+                String inner = value.substring(1, value.length() - 1).trim();
+                List<String> items = new ArrayList<>();
+                for (String item : splitOutsideQuotes(inner)) {
+                    items.add(stripQuotes(item.trim()));
+                }
+                map.put(key, items);
+            } else {
+                map.put(key, stripQuotes(value));
+            }
+        }
+        return map;
+    }
+
+    private List<String> splitOutsideQuotes(String s) {
+        List<String> parts = new ArrayList<>();
+        int depth = 0;
+        boolean inStr = false;
+        int start = 0;
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+            if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
+                inStr = !inStr;
+            } else if (!inStr) {
+                if (c == '{' || c == '[') depth++;
+                else if (c == '}' || c == ']') depth--;
+                else if (c == ',' && depth == 0) {
+                    parts.add(s.substring(start, i));
+                    start = i + 1;
+                }
+            }
+        }
+        if (start < s.length()) {
+            parts.add(s.substring(start));
+        }
+        return parts;
+    }
+
+    private String stripQuotes(String s) {
+        if (s == null) return "";
+        s = s.trim();
+        if (s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) {
+            return s.substring(1, s.length() - 1);
+        }
+        return s;
+    }
+
+    // ── 健康教练 ──
+
+    @Operation(summary = "发送健康教练消息")
+    @PostMapping("/health-coach/send")
+    public Result<Map<String, Object>> sendHealthCoachMessage(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        String query = (String) params.get("query");
+        String conversationId = (String) params.get("conversationId");
+        if (query == null || query.trim().isEmpty()) {
+            return Result.error("消息不能为空");
+        }
+        // 会员付费门禁:有效期内 BASIC 及以上会员可用(开关关闭时对所有登录用户放行)
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Map<String, Object> inputs = new LinkedHashMap<>();
+        if (memberId != null) {
+            inputs.put("child_id", memberId);
+        }
+        // 注入教练人格(对齐 /chat/send 的 mascot 范式;coach_id 用于 LangGraph prompt 路由)
+        com.etotem.cfc.entity.User hcUser = userService.getUserInfo(userId);
+        String hcMascotCode = hcUser != null ? hcUser.getMascot() : null;
+        if (hcMascotCode != null && !hcMascotCode.isEmpty()) {
+            com.etotem.cfc.enums.MascotEnum hcMascot = com.etotem.cfc.enums.MascotEnum.fromCode(hcMascotCode);
+            if (hcMascot != null) {
+                inputs.put("coach_id", hcMascot.getCode());
+                inputs.put("mascot_name", hcMascot.name());
+                inputs.put("mascot_gender", hcMascot.gender());
+                inputs.put("mascot_persona", hcMascot.persona());
+            }
+        } else {
+            inputs.put("coach_id", "");
+            inputs.put("mascot_name", "健康教练");
+            inputs.put("mascot_gender", "");
+            inputs.put("mascot_persona", "");
+        }
+        // 画像注入
+        String coachPortrait = portraitService.buildPortraitPrompt(userId, memberId);
+        if (coachPortrait != null) {
+            inputs.put("portrait_prompt", coachPortrait);
+        }
+        Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
+        String answer = resp != null && resp.get("answer") != null ? String.valueOf(resp.get("answer")) : "";
+        if (answer.trim().isEmpty()) {
+            // TC-P-40-E:LangGraph 超时/熔断返回 null 时给出非空兜底文案,不返回空白、不 500
+            answer = "AI 服务暂时不可用,已为您准备兜底建议:先保持规律作息与均衡饮食,"
+                    + "每天安排适量户外活动,稍后可再次询问获取完整方案。";
+        }
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("answer", answer);
+        result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
+        result.put("recommendations", Collections.emptyList());
+        result.put("tasks", Collections.emptyList());
+        return Result.success(result);
+    }
+
+    // ── AI 成长方案(SC-P-40/41,能力键 plan.ai.generate) ──
+
+    /**
+     * 生成 AI 成长方案:选成员 + 目标 → AiGateway(LangGraph) → overview + nutrition/diet/exercise 三板块。
+     * 未购会员由统一门禁拦截(46003);LangGraph 超时走 AiGateway Fallback,不 500。
+     */
+    @Operation(summary = "生成 AI 成长方案")
+    @PostMapping("/plan/generate")
+    public Result<Map<String, Object>> generatePlan(
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> params) {
+        // userId/familyId 承载付费墙与家庭归属校验(TC-P-40-P);归属校验由 JwtInterceptor + 业务侧统一处理
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Map<String, Object> result = aiGateway.generateGrowthPlan(params, true);
+        if (Boolean.TRUE.equals(result.get("needPurchase"))) {
+            return Result.error(ERR_AI_COACH_MEMBER_ONLY, String.valueOf(result.get("message")));
+        }
+        return Result.success(result);
+    }
+
+    /**
+     * 分板块重生成/确认(SC-P-41):仅重生成 sectionKey 对应板块,其余两板块原样保留。
+     */
+    @Operation(summary = "分板块重生成 AI 成长方案")
+    @PostMapping("/plan/regenerate-section")
+    public Result<Map<String, Object>> regeneratePlanSection(
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> params) {
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Map<String, Object> result = aiGateway.regenerateGrowthPlanSection(params, true);
+        if (Boolean.TRUE.equals(result.get("needPurchase"))) {
+            return Result.error(ERR_AI_COACH_MEMBER_ONLY, String.valueOf(result.get("message")));
+        }
+        return Result.success(result);
+    }
+
+    /**
+     * AI 使用会员门禁统一状态接口(新):返回 AiGateResult + features 明细。
+     * 前端一次请求即可渲染会员状态条与功能锁。
+     */
+    @Operation(summary = "获取AI使用会员门禁状态(全量功能)")
+    @PostMapping("/gate")
+    public Result<AiGateResult> aiGateStatus(@RequestAttribute("userId") Long userId) {
+        AiGateResult gate = membershipService.checkAiFeatureGate(userId);
+        if (gate == null) {
+            gate = new AiGateResult();
+            gate.setStatus(AiGateStatus.ALLOW);
+            gate.setEnabled(true);
+            gate.setCanUse(true);
+            gate.setCanViewHistory(true);
+            gate.setMemberLevel("FREE");
+            gate.setIsActive(false);
+            gate.setDaysRemaining(0L);
+        }
+        gate.setFeatures(buildGateFeatures(gate));
+        return Result.success(gate);
+    }
+
+    /**
+     * AI 教练会员付费开关状态(兼容保留,前端新代码统一改调 /api/ai/gate)。
+     * enabled=true 表示开关开启(会员门禁生效);canUse=false 表示当前用户被拦截。
+     */
+    @Operation(summary = "获取AI教练会员付费开关状态")
+    @PostMapping("/health-coach/gate")
+    public Result<Map<String, Object>> aiCoachGateStatus(@RequestAttribute("userId") Long userId) {
+        AiGateResult gate = membershipService.checkAiFeatureGate(userId);
+        boolean enabled = gate != null && gate.isEnabled();
+        boolean canUse = gate != null && gate.isCanUse();
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("enabled", enabled);
+        result.put("canUse", canUse);
+        result.put("memberOnly", enabled);
+        result.put("feature", AI_COACH_FEATURE);
+        result.put("status", gate != null ? gate.getStatus() : AiGateStatus.UPGRADE_REQUIRED);
+        result.put("canViewHistory", gate != null && gate.isCanViewHistory());
+        result.put("memberLevel", gate != null && gate.getMemberLevel() != null ? gate.getMemberLevel() : "FREE");
+        result.put("memberExpireTime", gate != null ? gate.getMemberExpireTime() : null);
+        return Result.success(result);
+    }
+
+    // ── 健康管家 ──
+
+    @Operation(summary = "发送健康管家消息")
+    @PostMapping("/butler/send")
+    public Result<Map<String, Object>> sendHealthButlerMessage(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        String query = (String) params.get("query");
+        String conversationId = (String) params.get("conversationId");
+        if (query == null || query.trim().isEmpty()) {
+            return Result.error("消息不能为空");
+        }
+        // AI 使用会员门禁
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Map<String, Object> inputs = new LinkedHashMap<>();
+        if (params.get("memberId") != null) {
+            inputs.put("child_id", Long.valueOf(params.get("memberId").toString()));
+        }
+        if (params.get("reportId") != null) {
+            inputs.put("report_id", Long.valueOf(params.get("reportId").toString()));
+        }
+        if (params.get("focus") != null) {
+            inputs.put("focus", params.get("focus").toString());
+        }
+        // 画像注入
+        Long butlerMemberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        String butlerPortrait = portraitService.buildPortraitPrompt(userId, butlerMemberId);
+        if (butlerPortrait != null) {
+            inputs.put("portrait_prompt", butlerPortrait);
+        }
+        Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
+        String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("answer", answer);
+        result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
+        result.put("recommendations", Collections.emptyList());
+        @SuppressWarnings("unchecked")
+        List<Object> tasks = resp != null && resp.get("tasks") instanceof List
+                ? (List<Object>) resp.get("tasks") : Collections.emptyList();
+        result.put("tasks", tasks);
+        return Result.success(result);
+    }
+
+    @Operation(summary = "语音转文字")
+    @PostMapping("/transcribe")
+    public Result<Map<String, Object>> transcribe(
+            @RequestAttribute("userId") Long userId,
+            @RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
+        if (file == null || file.isEmpty()) {
+            return Result.error(400, "音频文件为空");
+        }
+        try {
+            Map<String, Object> result = aiGateway.transcribe(file.getBytes(), file.getOriginalFilename());
+            if (result != null) {
+                return Result.success(result);
+            }
+            return Result.error(500, "语音转写失败");
+        } catch (java.io.IOException e) {
+            return Result.error(500, "读取音频文件失败");
+        }
+    }
+
+}

+ 125 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/ButlerController.java

@@ -0,0 +1,125 @@
+package com.etotem.cfc.controller.ai;
+
+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 com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "AI管家", description = "AI管家会话管理接口")
+@RestController("aiButlerController")
+@RequestMapping("/api/ai/butler")
+public class ButlerController {
+
+    @Resource
+    private ButlerSessionService butlerSessionService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    /** 会员专享业务错误码(UPGRADE_REQUIRED,与 AIChatController 同码) */
+    private static final int ERR_AI_COACH_MEMBER_ONLY = 46003;
+
+    /** 会员已过期业务错误码(MEMBER_EXPIRED,与 AIChatController 同码) */
+    private static final int ERR_AI_MEMBER_EXPIRED = 46004;
+
+    /**
+     * AI 管家新建会话门禁:仅有效期内 BASIC 及以上会员可新建。
+     * 历史会话的 list/detail/archive/delete/update-conversation 保持开放(决策 3)。
+     */
+    private <T> Result<T> gateError(AiGateResult gate) {
+        if (gate != null && gate.getStatus() == AiGateStatus.MEMBER_EXPIRED) {
+            return Result.error(ERR_AI_MEMBER_EXPIRED, "会员已过期,请续费后继续使用");
+        }
+        return Result.error(ERR_AI_COACH_MEMBER_ONLY, "该功能为会员专享,请先开通会员");
+    }
+
+    @Operation(summary = "创建新会话")
+    @PostMapping("/sessions/create")
+    public Result<Map<String, Object>> createSession(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> params) {
+        // 门禁:新建会话=新建对话入口,FREE/过期会员拦截(历史会话不受影响)
+        AiGateResult gate = membershipService.checkAiFeatureGate(userId);
+        if (gate == null || !gate.isCanUse()) {
+            return gateError(gate);
+        }
+        String title = params.getOrDefault("title", "新会话");
+        String context = params.get("context");
+        Long sessionId = butlerSessionService.createSession(userId, title, context);
+        return Result.success(Collections.singletonMap("sessionId", sessionId));
+    }
+
+    @Operation(summary = "更新会话LangGraph conversationId")
+    @PostMapping("/sessions/update-conversation")
+    public Result<Void> updateConversationId(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Long sessionId = ParamUtils.getLong(params.get("sessionId"));
+        String conversationId = (String) params.get("conversationId");
+        ButlerSession session = butlerSessionService.getSession(sessionId, userId);
+        if (session == null) {
+            return Result.error("会话不存在或无权访问");
+        }
+        butlerSessionService.updateConversationId(sessionId, conversationId);
+        return Result.success(null);
+    }
+
+    @Operation(summary = "归档会话")
+    @PostMapping("/sessions/archive")
+    public Result<Void> archiveSession(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Long sessionId = ParamUtils.getLong(params.get("sessionId"));
+        butlerSessionService.archiveSession(sessionId, userId);
+        return Result.success(null);
+    }
+
+    @Operation(summary = "获取会话列表")
+    @PostMapping("/sessions/list")
+    public Result<Page<ButlerSession>> listSessions(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 20;
+        String status = (String) params.get("status");
+        Page<ButlerSession> sessions = butlerSessionService.getSessionsByUser(userId, page, size, status);
+        return Result.success(sessions);
+    }
+
+    @Operation(summary = "获取会话详情")
+    @PostMapping("/sessions/detail")
+    public Result<ButlerSession> sessionDetail(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Long sessionId = ParamUtils.getLong(params.get("sessionId"));
+        ButlerSession session = butlerSessionService.getSession(sessionId, userId);
+        if (session == null) {
+            return Result.error("会话不存在或无权访问");
+        }
+        return Result.success(session);
+    }
+
+    @Operation(summary = "删除会话")
+    @PostMapping("/sessions/delete")
+    public Result<Void> deleteSession(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Long sessionId = ParamUtils.getLong(params.get("sessionId"));
+        boolean deleted = butlerSessionService.deleteSession(sessionId, userId);
+        if (!deleted) {
+            return Result.error("会话不存在或无权删除");
+        }
+        return Result.success(null);
+    }
+}

+ 80 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/CoachFamilyBoardController.java

@@ -0,0 +1,80 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.CoachFamilyBoardService;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 家庭成长看板(教练聚合视图)端点,能力键 {@code ai.coach.familyBoard} / SC-B-10。
+ *
+ * <p>类级 {@code /api/ai/coach/family-board};{@code /aggregate} 一屏聚合展示,
+ * {@code /drill-down} 卡片下钻。全程统一 {@code @PostMapping} + {@link Result}。</p>
+ */
+@Tag(name = "AI教练家庭成长看板", description = "全家五维/报告/任务/方案/预警一屏聚合与下钻(SC-B-10)")
+@RestController
+@RequestMapping("/api/ai/coach/family-board")
+public class CoachFamilyBoardController {
+
+    @Resource
+    private CoachFamilyBoardService coachFamilyBoardService;
+
+    /** 打开看板:一屏聚合(可指定 familyId 做跨家庭门禁)。 */
+    @PostMapping("/aggregate")
+    public Result<Map<String, Object>> aggregate(@RequestBody(required = false) Map<String, Object> body,
+                                                 @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error(401, "请先登录");
+        }
+        if (!Boolean.TRUE.equals(coachFamilyBoardService.canViewWholeFamilyBoard(userId))) {
+            return Result.forbidden("当前角色无权查看全家看板");
+        }
+        Map<String, Object> params = body == null ? new LinkedHashMap<String, Object>() : body;
+        Long familyId = getLong(params.get("familyId"));
+        if (familyId != null) {
+            return Result.success(coachFamilyBoardService.aggregateBoardForFamily(userId, familyId));
+        }
+        return Result.success(coachFamilyBoardService.aggregateBoard(userId, params));
+    }
+
+    /** 卡片下钻:按 card + memberId 返回同源详情路由与明细。 */
+    @PostMapping("/drill-down")
+    public Result<Map<String, Object>> drillDown(@RequestBody(required = false) Map<String, Object> body,
+                                                 @RequestAttribute("userId") Long userId,
+                                                 @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        if (userId == null) {
+            return Result.error(401, "请先登录");
+        }
+        if (!Boolean.TRUE.equals(coachFamilyBoardService.canViewWholeFamilyBoard(userId))) {
+            return Result.forbidden("当前角色无权查看全家看板");
+        }
+        Map<String, Object> params = body == null ? Collections.<String, Object>emptyMap() : body;
+        Object cardValue = params.get("card");
+        String card = cardValue == null ? null : String.valueOf(cardValue);
+        Long memberId = params.get("memberId") != null ? getLong(params.get("memberId")) : currentMemberId;
+        return Result.success(coachFamilyBoardService.drillDown(userId, card, memberId));
+    }
+
+    private Long getLong(Object value) {
+        if (value instanceof Number) {
+            return ((Number) value).longValue();
+        }
+        if (value instanceof String) {
+            try {
+                return Long.valueOf((String) value);
+            } catch (NumberFormatException ignored) {
+                return null;
+            }
+        }
+        return null;
+    }
+}

+ 89 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/CoachRecommendController.java

@@ -0,0 +1,89 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.CoachRecommendService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * AI 教练个性化任务/饮食推荐与采纳端点(能力键 {@code ai.coach.recommend},SC-B-07)。
+ *
+ * <p>类级 {@code /api/ai/coach/recommend};{@code /recommend} 生成推荐清单,
+ * {@code /adopt} 一键采纳为正式任务/心愿(task 经 TaskService.createTask,wish 经 WishService)。</p>
+ */
+@Slf4j
+@Tag(name = "AI教练推荐", description = "AI 教练个性化任务/饮食推荐与采纳(SC-B-07)")
+@RestController
+@RequestMapping("/api/ai/coach/recommend")
+public class CoachRecommendController {
+
+    @Resource
+    private CoachRecommendService coachRecommendService;
+
+    @Operation(summary = "生成个性化推荐(任务/心愿/饮食)")
+    @PostMapping("/recommend")
+    public Result<Map<String, Object>> recommend(@RequestBody Map<String, Object> body,
+                                                 @RequestAttribute("userId") Long userId,
+                                                 @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        if (userId == null) {
+            return Result.error(401, "请先登录");
+        }
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        Long reportId = ParamUtils.getLong(body.get("reportId"));
+        if (memberId == null) {
+            return Result.badRequest("缺少成员ID");
+        }
+        if (!coachRecommendService.hasFamilyAccess(userId, memberId)) {
+            return Result.error(403, "无权代管该家庭成员");
+        }
+        Map<String, Object> basis = coachRecommendService.analyzeBasis(memberId, reportId);
+        List<Map<String, Object>> items = coachRecommendService.recommend(memberId, reportId);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("basis", basis);
+        data.put("items", items);
+        return Result.success(data);
+    }
+
+    @Operation(summary = "一键采纳推荐为正式任务/心愿")
+    @PostMapping("/adopt")
+    public Result<Map<String, Object>> adopt(@RequestBody Map<String, Object> body,
+                                             @RequestAttribute("userId") Long userId,
+                                             @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        if (userId == null) {
+            return Result.error(401, "请先登录");
+        }
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        String type = stringValue(body.get("type"));
+        String recoId = stringValue(body.get("recoId"));
+        if (memberId == null) {
+            return Result.badRequest("缺少成员ID");
+        }
+        if (recoId == null || recoId.trim().isEmpty()) {
+            return Result.badRequest("缺少推荐ID");
+        }
+        try {
+            Map<String, Object> r = coachRecommendService.adopt(userId, memberId, type, recoId);
+            return Result.success(r);
+        } catch (SecurityException e) {
+            return Result.error(403, e.getMessage());
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+    }
+
+    private String stringValue(Object o) {
+        return o == null ? null : String.valueOf(o);
+    }
+}

+ 41 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/ContextApiController.java

@@ -0,0 +1,41 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.AiContextService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 上下文数据 API (供 LangGraph Python 服务调用)
+ * 替代 LangGraph Workflow HTTP 回调的 /api/ai/context
+ */
+@Tag(name = "AI上下文", description = "供 LangGraph 服务调用的上下文数据接口")
+@RestController("aiContextApiController")
+@RequestMapping("/api/ai/context")
+public class ContextApiController {
+
+    @Resource
+    private AiContextService aiContextService;
+
+    @Operation(summary = "获取 AI 上下文数据", hidden = true)
+    @PostMapping("")
+    public Result<Map<String, Object>> getContext(@RequestBody Map<String, Object> params) {
+        String userIdStr = (String) params.get("user_id");
+        String intentType = (String) params.get("intent_type");
+        Map<String, Object> contextParams = (Map<String, Object>) params.get("params");
+
+        if (userIdStr == null) {
+            return Result.error("缺少参数: user_id");
+        }
+        Long userId = Long.valueOf(userIdStr);
+        Map<String, Object> ctx = aiContextService.getContext(intentType, userId, contextParams);
+        return Result.success(ctx);
+    }
+}

+ 77 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/RecommendationController.java

@@ -0,0 +1,77 @@
+package com.etotem.cfc.controller.ai;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.RecommendationQuery;
+import com.etotem.cfc.dto.RecommendationResult;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.RecommendationService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "营养推荐", description = "精准营养推荐搜索")
+@RestController
+@RequestMapping("/api/recommend")
+public class RecommendationController {
+
+    private static final Logger log = LoggerFactory.getLogger(RecommendationController.class);
+
+    @Resource
+    private RecommendationService recommendationService;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Operation(summary = "按营养标签搜索推荐内容")
+    @PostMapping("/search")
+    public Result<List<RecommendationResult>> search(
+            @RequestBody RecommendationQuery query) {
+
+        // 灰度: 5% 流量走 Python LangGraph
+        Long userId = query.getUserId() != null ? query.getUserId() : 0L;
+        if (aiGateway.isEnabled() && Math.random() < 0.05) {
+            List<RecommendationResult> pythonResults = aiGateway.recommend(
+                userId, query.getNutritionTags(), query.getTypes(), query.getLimit());
+            if (pythonResults != null && !pythonResults.isEmpty()) {
+                log.info("[灰度] Recommend via LangGraph, userId={}", userId);
+                return Result.success(pythonResults);
+            }
+            log.info("[灰度] LangGraph 无结果/异常, fallback 本地搜索");
+        }
+
+        // 现有业务逻辑
+        List<RecommendationResult> results = recommendationService.search(query);
+        return Result.success(results);
+    }
+
+    @Operation(summary = "获取用户复购提醒列表")
+    @PostMapping("/repurchase-reminders")
+    public Result<List<RecommendationResult>> repurchaseReminders(
+            HttpServletRequest request) {
+        Long userId = (Long) request.getAttribute("userId");
+        List<RecommendationResult> results = recommendationService.getRepurchaseReminders(userId);
+        return Result.success(results);
+    }
+
+    @Operation(summary = "标记复购提醒已点击")
+    @PostMapping("/repurchase-reminder/{id}/click")
+    public Result<?> clickRepurchaseReminder(
+            @PathVariable Long id) {
+        recommendationService.markRepurchaseClicked(id);
+        return Result.success(null);
+    }
+
+    }

+ 207 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentAppointmentController.java

@@ -0,0 +1,207 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.AssessmentAppointment;
+import com.etotem.cfc.entity.AssessmentQuota;
+import com.etotem.cfc.entity.DanAssessmentExecution;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AssessmentAppointmentService;
+import com.etotem.cfc.service.AssessmentQuotaService;
+import com.etotem.cfc.service.DanAssessmentExecutionService;
+import com.etotem.cfc.service.GuideFamilyService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.ParamUtils;
+import com.etotem.cfc.common.RolesUtil;
+
+@Tag(name = "评估预约", description = "评估预约管理")
+@RestController
+@RequestMapping("/api/assessment/appointment")
+public class AssessmentAppointmentController {
+
+    @Resource
+    private AssessmentAppointmentService appointmentService;
+
+    @Resource
+    private AssessmentQuotaService quotaService;
+
+    @Resource
+    private DanAssessmentExecutionService danAssessmentExecutionService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private GuideFamilyService guideFamilyService;
+
+    @Operation(summary = "创建评估预约(含新执行记录)")
+    @PostMapping("/create")
+    public Result<Map<String, Object>> createAppointment(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        Long guideId = ParamUtils.getLong(body.get("guideId"));
+        Long assessorId = ParamUtils.getLong(body.get("assessorId"));
+        String appointmentDate = body.get("appointmentDate") != null ? body.get("appointmentDate").toString() : null;
+        String appointmentTime = body.get("appointmentTime") != null ? body.get("appointmentTime").toString() : null;
+        String notes = body.get("notes") != null ? body.get("notes").toString() : null;
+        Long quotaId = ParamUtils.getLong(body.get("quotaId"));
+
+        if (memberId == null || quotaId == null) {
+            return Result.error("memberId和quotaId不能为空");
+        }
+        // 契约 assessment.planner.select(SC-P-32 / API_REFERENCE §4.10『预约前需规划师绑定』):
+        // 家长侧选规划师 = 所选规划师(guideId)必须属于家庭已绑定 T 列表;未绑定 → 提示先绑定。
+        if (assessorId == null && guideId == null) {
+            return Result.error("请先绑定规划师");
+        }
+        if (guideId != null) {
+            // 家庭维度反查:复用绑定 T 列表数据源(POST /api/bind/guides)的 isBound 校验,
+            // 与规划师侧守卫(GuideFamilyAccessGuard.checkBinding)方向区分。
+            AssessmentQuota quotaForBind = quotaService.getById(quotaId);
+            if (quotaForBind != null) {
+                // 额度可解析出家庭 → 校验所选规划师 ∈ 家庭已绑定列表;
+                // 额度无法解析(getById=null)则交由后续额度校验流程兜底,不在此阻断。
+                Long familyIdForBind = quotaForBind.getFamilyId();
+                if (!appointmentService.requireBoundPlanner(guideId, familyIdForBind)) {
+                    return Result.error("请先绑定规划师");
+                }
+            }
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) return Result.error("用户不存在");
+
+        // 消耗一次额度
+        int consumed = quotaService.consumeQuota(quotaId, memberId);
+        if (consumed <= 0) {
+            return Result.error("额度不足或已过期");
+        }
+
+        // 获取额度信息(含 familyId, productOrderId)
+        AssessmentQuota quota = quotaService.getById(quotaId);
+        if (quota == null) return Result.error("额度记录不存在");
+
+        // 创建预约
+        AssessmentAppointment appointment = appointmentService.createAppointment(
+                userId, memberId, guideId, assessorId, null, appointmentDate, appointmentTime, notes);
+
+        // 创建新执行记录(dan_assessment_executions,含 assessor 角色)
+        Long finalAssessorId = assessorId != null ? assessorId : guideId;
+        DanAssessmentExecution exec = danAssessmentExecutionService.createExecution(
+                quota.getProductOrderId(), // assessmentOrderId 复用 shop productOrderId
+                memberId,
+                quota.getFamilyId(),
+                quotaId,
+                finalAssessorId,
+                null, // plannerId(可选)
+                appointment.getId()
+        );
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("appointmentId", appointment.getId());
+        result.put("executionId", exec.getId());
+        result.put("quotaId", quotaId);
+
+        return Result.success(result);
+    }
+
+    @Operation(summary = "确认预约(由指派的测评师确认)")
+    @PostMapping("/confirm/{id}")
+    public Result<Boolean> confirmAppointment(
+            @RequestAttribute("userId") Long userId,
+            @PathVariable Long id) {
+        boolean success = appointmentService.confirmAppointment(id, userId);
+        if (!success) {
+            return Result.error("确认失败,您不是被指派的测评师");
+        }
+        return Result.success(true);
+    }
+
+    @Operation(summary = "取消预约")
+    @PostMapping("/cancel/{id}")
+    public Result<Boolean> cancelAppointment(@PathVariable Long id) {
+        boolean success = appointmentService.cancelAppointment(id);
+        return Result.success(success);
+    }
+
+    @Operation(summary = "标记预约未到(由成长规划师操作,status=4)")
+    @PostMapping("/no-show/{id}")
+    public Result<Boolean> noShowAppointment(
+            @RequestAttribute("userId") Long userId,
+            @PathVariable Long id) {
+        boolean success = appointmentService.noShowAppointment(id, userId);
+        if (!success) {
+            return Result.error("标记未到失败:预约状态不允许流转或您不是该预约的成长规划师");
+        }
+        return Result.success(true);
+    }
+
+    @Operation(summary = "我的预约列表(本人视角)")
+    @PostMapping("/my-list")
+    public Result<List<Map<String, Object>>> getMyAppointments(@RequestAttribute("userId") Long userId) {
+        List<AssessmentAppointment> appointments = appointmentService.getByUserId(userId);
+        List<Map<String, Object>> result = appointments.stream().map(this::toMap).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    @Operation(summary = "成长规划师的预约列表")
+    @PostMapping("/guide-list")
+    public Result<List<Map<String, Object>>> getGuideAppointments(
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute("role") String role,
+            @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        if (!RolesUtil.hasTeacherRole(role, roles)) {
+            return Result.error("只有成长规划师可以查看此列表");
+        }
+        List<AssessmentAppointment> appointments = appointmentService.getByGuideId(userId);
+        List<Map<String, Object>> result = appointments.stream().map(this::toMap).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    @Operation(summary = "测评师的预约列表")
+    @PostMapping("/assessor-list")
+    public Result<List<Map<String, Object>>> getAssessorAppointments(
+            @RequestAttribute("userId") Long userId) {
+        List<AssessmentAppointment> appointments = appointmentService.getByAssessorId(userId);
+        List<Map<String, Object>> result = appointments.stream().map(this::toMap).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    private Map<String, Object> toMap(AssessmentAppointment appt) {
+        Map<String, Object> map = new HashMap<>();
+        map.put("id", appt.getId());
+        map.put("memberId", appt.getMemberId());
+        map.put("guideId", appt.getGuideId());
+        map.put("assessorId", appt.getAssessorId());
+        map.put("appointmentDate", appt.getAppointmentDate());
+        map.put("appointmentTime", appt.getAppointmentTime());
+        map.put("status", appt.getStatus());
+        map.put("statusText", getStatusText(appt.getStatus()));
+        map.put("notes", appt.getNotes());
+        map.put("createdAt", appt.getCreatedAt());
+        return map;
+    }
+
+    private String getStatusText(Integer status) {
+        if (status == null) return "未知";
+        switch (status) {
+            case 0: return "待确认";
+            case 1: return "已确认";
+            case 2: return "已完成";
+            case 3: return "已取消";
+            case 4: return "未到";
+            default: return "未知";
+        }
+    }
+}

+ 92 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentComparisonController.java

@@ -0,0 +1,92 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.etotem.cfc.common.Result;
+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 com.etotem.cfc.service.AssessmentComparisonService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "测评对比", description = "首次 vs 最新测评对比分析")
+@RestController
+@RequestMapping("/api/assessment/compare")
+public class AssessmentComparisonController {
+
+    @Resource
+    private AssessmentComparisonService comparisonService;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Operation(summary = "对比成员首次与最新测评")
+    @PostMapping("/by-child")
+    public Result<AssessmentComparisonService.CompareResult> compareByChild(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        AssessmentComparisonService.CompareResult result = comparisonService.compareByChild(memberId);
+        if (result == null) {
+            return Result.error("至少需要两次完成测评才能对比");
+        }
+        return Result.success(result);
+    }
+
+    @Operation(summary = "对比成员单维度变化")
+    @PostMapping("/by-child-dimension")
+    public Result<AssessmentComparisonService.DimensionDelta> compareByChildDimension(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+        String dimensionCode = (String) params.get("dimensionCode");
+        if (memberId == null || dimensionCode == null) {
+            return Result.error("memberId和dimensionCode不能为空");
+        }
+        AssessmentComparisonService.DimensionDelta result =
+                comparisonService.compareByChildAndDimension(memberId, dimensionCode);
+        if (result == null) {
+            return Result.error("暂无足够数据");
+        }
+        return Result.success(result);
+    }
+
+    @Operation(summary = "对比家庭所有成员首次与最新测评")
+    @PostMapping("/by-family")
+    public Result<List<AssessmentComparisonService.CompareResult>> compareByFamily(
+            @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        if (familyId == null) {
+            return Result.error("familyId不能为空");
+        }
+        List<AssessmentComparisonService.CompareResult> results =
+                comparisonService.compareByFamily(familyId);
+        return Result.success(results);
+    }
+
+    @Operation(summary = "获取进步叙事")
+    @PostMapping("/narrative")
+    public Result<String> getNarrative(@RequestBody Map<String, Object> params,
+                                       @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        String narrative = comparisonService.getProgressNarrative(memberId);
+        return Result.success(narrative);
+    }
+}

+ 79 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentQuotaController.java

@@ -0,0 +1,79 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AssessmentQuotaVO;
+import com.etotem.cfc.entity.AssessmentQuota;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AssessmentExecutionService;
+import com.etotem.cfc.service.AssessmentQuotaService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "测评额度", description = "测评额度查询与使用")
+@RestController
+@RequestMapping("/api/assessment/quota")
+public class AssessmentQuotaController {
+
+    @Resource
+    private AssessmentQuotaService quotaService;
+
+    @Resource
+    private AssessmentExecutionService executionService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Operation(summary = "我的可用额度列表")
+    @PostMapping("/my-list")
+    public Result<List<AssessmentQuotaVO>> getMyQuotas(@RequestAttribute("userId") Long userId) {
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.error("用户或家庭信息不存在");
+        }
+        List<AssessmentQuota> quotas = quotaService.getAvailableQuotas(user.getFamilyId(), null);
+        List<AssessmentQuotaVO> vos = quotas.stream().map(this::toVO).collect(Collectors.toList());
+        return Result.success(vos);
+    }
+
+    @Operation(summary = "额度详情")
+    @PostMapping("/detail")
+    public Result<AssessmentQuotaVO> detail(@RequestBody Map<String, Object> params) {
+        Long quotaId = ParamUtils.getLong(params.get("quotaId"));
+        if (quotaId == null) {
+            return Result.error("quotaId不能为空");
+        }
+        AssessmentQuota quota = quotaService.getById(quotaId);
+        if (quota == null) {
+            return Result.error("额度不存在");
+        }
+        return Result.success(toVO(quota));
+    }
+
+    private AssessmentQuotaVO toVO(AssessmentQuota q) {
+        AssessmentQuotaVO vo = new AssessmentQuotaVO();
+        vo.setId(q.getId());
+        vo.setQuotaNo(q.getQuotaNo());
+        vo.setFamilyId(q.getFamilyId());
+        vo.setMemberId(q.getMemberId());
+        vo.setProductOrderId(q.getProductOrderId());
+        vo.setProductId(q.getProductId());
+        vo.setProductName(q.getProductName());
+        vo.setTotalSessions(q.getTotalSessions());
+        vo.setRemainingSessions(q.getRemainingSessions());
+        vo.setValidityStart(q.getValidityStart());
+        vo.setValidityEnd(q.getValidityEnd());
+        vo.setStatus(q.getStatus());
+        vo.setUsedSessions(q.getTotalSessions() - q.getRemainingSessions());
+        vo.setExpired(q.getValidityEnd() != null && q.getValidityEnd().before(new Date()));
+        return vo;
+    }
+}

+ 218 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentReportController.java

@@ -0,0 +1,218 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.GrowthGuidance;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AssessmentPlanGenerator;
+import com.etotem.cfc.service.FileStorageService;
+import com.etotem.cfc.service.GrowthGuidanceService;
+import com.etotem.cfc.service.ReportParseService;
+import com.etotem.cfc.service.StorageService;
+import com.etotem.cfc.service.TaskPlanService;
+import com.etotem.cfc.entity.TaskPlanInstance;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Date;
+import java.util.concurrent.CompletableFuture;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "测评报告", description = "测评报告上传、指导意见管理")
+@RestController
+@RequestMapping("/api/dan-assessment/result")
+public class AssessmentReportController {
+
+    private static final Logger log = LoggerFactory.getLogger(AssessmentReportController.class);
+
+    @Resource
+    private DanAssessmentResultMapper resultMapper;
+
+    @Resource
+    private GrowthGuidanceService guidanceService;
+
+    @Resource
+    private FileStorageService fileStorageService;
+
+    @Resource
+    private ReportParseService reportParseService;
+
+    @Resource
+    private StorageService storageService;
+
+    @Resource
+    private AssessmentPlanGenerator planGenerator;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private TaskPlanService taskPlanService;
+
+    @Operation(summary = "获取用户已生成的测评方案列表")
+    @PostMapping("/plans/list")
+    public Result<List<TaskPlanInstance>> getMyPlans(
+            @RequestParam(value = "familyId", required = false) Long familyId,
+            @RequestParam(value = "childId", required = false) Long memberId,
+            @RequestBody(required = false) Map<String, Object> body,
+            HttpServletRequest request) {
+        try {
+            // 参数兼容:优先查询参数,其次 JSON body,最后回退 JWT 注入的 familyId
+            if (familyId == null && body != null && body.get("familyId") != null) {
+                familyId = ((Number) body.get("familyId")).longValue();
+            }
+            if (memberId == null && body != null && body.get("childId") != null) {
+                memberId = ((Number) body.get("childId")).longValue();
+            }
+            if (familyId == null) {
+                Object attr = request.getAttribute("familyId");
+                if (attr instanceof Number) {
+                    familyId = ((Number) attr).longValue();
+                }
+            }
+            if (familyId == null) {
+                return Result.error("缺少familyId参数且无法从登录态获取家庭信息");
+            }
+
+            // 如果传了 memberId,只查该家庭成员的方案;否则查整个家庭的方案
+            List<TaskPlanInstance> plans;
+            if (memberId != null) {
+                plans = taskPlanService.getChildPlans(memberId);
+            } else {
+                plans = taskPlanService.getFamilyPlans(familyId);
+            }
+            
+            // 按创建时间倒序排列
+            plans.sort((a, b) -> b.getCreatedAt().after(a.getCreatedAt()) ? 1 : -1);
+            return Result.success(plans);
+        } catch (Exception e) {
+            log.error("获取测评方案失败: familyId={}, memberId={}", familyId, memberId, e);
+            return Result.error("获取方案失败:" + e.getMessage());
+        }
+    }
+
+    @Operation(summary = "家庭主账号上传测评报告")
+    @PostMapping("/upload")
+    public Result<DanAssessmentResult> uploadReport(
+            @RequestParam("file") MultipartFile file,
+            @RequestParam("memberId") Long memberId,
+            @RequestParam(value = "notes", required = false) String notes,
+            HttpServletResponse response) {
+
+        if (file == null || file.isEmpty()) {
+            return Result.error("文件不能为空");
+        }
+
+        // SEC-20261031-01:上传类型校验——仅接受 PDF(Content-Type 或扩展名任一命中),
+        // 非 PDF/恶意内容直接 HTTP 415,防止进入存储/解析链路(对齐 HealthReportController 口径)
+        String contentType = file.getContentType();
+        String originalFilename = file.getOriginalFilename();
+        boolean isPdf = (contentType != null && "application/pdf".equalsIgnoreCase(contentType))
+                || (originalFilename != null && originalFilename.toLowerCase().endsWith(".pdf"));
+        if (!isPdf) {
+            response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
+            return Result.error(415, "仅支持PDF文件");
+        }
+
+        String filePath = fileStorageService.store(file, "assessment-reports");
+        if (filePath == null) {
+            return Result.error("文件上传失败");
+        }
+
+        DanAssessmentResult result = new DanAssessmentResult();
+        result.setMemberId(memberId);
+        result.setStatus("draft");
+        result.setSource(DanAssessmentResult.SOURCE_PARENT_UPLOAD);
+        result.setProcessDesc(notes);
+        result.setAssessmentDate(new Date());
+        result.setCreatedAt(new Date());
+        result.setUpdatedAt(new Date());
+        result.setPics(filePath);
+        resultMapper.insert(result);
+
+        // 异步解析上传的报告文件
+        final String parsePath = filePath;
+        final Long parseResultId = result.getId();
+        final MultipartFile uploadFile = file;
+        CompletableFuture.runAsync(() -> {
+            try {
+                // 下载到临时目录后解析(兼容本地/京东云两种存储模式)
+                String localPath = storageService.getFilePath(parsePath);
+                reportParseService.parseReport(localPath);
+                log.info("异步解析报告完成: resultId={}", parseResultId);
+            } catch (Exception e) {
+                log.error("异步解析报告失败: resultId={}", parseResultId, e);
+            }
+        });
+
+        return Result.success(result);
+    }
+
+    @Operation(summary = "保存结构化指导意见")
+    @PostMapping("/{resultId}/guidance/save")
+    public Result<List<GrowthGuidance>> saveGuidance(
+            @PathVariable Long resultId,
+            @RequestBody Map<String, Object> body) {
+
+        @SuppressWarnings("unchecked")
+        List<GrowthGuidance> items = (List<GrowthGuidance>) body.get("items");
+        if (items == null || items.isEmpty()) {
+            return Result.error("指导意见不能为空");
+        }
+
+        guidanceService.saveGuidances(resultId, items);
+        List<GrowthGuidance> saved = guidanceService.getByResultId(resultId);
+        return Result.success(saved);
+    }
+
+    @Operation(summary = "获取结构化指导意见")
+    @PostMapping("/{resultId}/guidance")
+    public Result<List<GrowthGuidance>> getGuidance(@PathVariable Long resultId) {
+        List<GrowthGuidance> list = guidanceService.getByResultId(resultId);
+        return Result.success(list);
+    }
+
+    @Operation(summary = "用户确认报告入库并自动生成方案")
+    @PostMapping("/{resultId}/confirm-inbox")
+    public Result<DanAssessmentResult> confirmUpload(
+            @PathVariable Long resultId,
+            @RequestBody Map<String, Object> body) {
+
+        DanAssessmentResult result = resultMapper.selectById(resultId);
+        if (result == null) {
+            return Result.error("报告不存在");
+        }
+        result.setStatus("completed");
+        result.setUpdatedAt(new Date());
+        Integer overallScore = body.get("overallScore") != null
+                ? Integer.valueOf(body.get("overallScore").toString()) : null;
+        if (overallScore != null) {
+            result.setOverallScore(overallScore);
+        }
+        resultMapper.updateById(result);
+
+        // 用户确认后立即自动生成测评方案(无需规划师审核)
+        try {
+            User child = userMapper.selectById(result.getMemberId());
+            Long familyId = child != null ? child.getFamilyId() : null;
+            if (familyId != null) {
+                TaskPlanInstance plan = planGenerator.generate(result, familyId, result.getMemberId());
+                log.info("已为测评结果{}自动生成方案 planId={}", resultId, plan.getId());
+            }
+        } catch (Exception e) {
+            log.error("自动生成方案失败:resultId={}", resultId, e);
+        }
+
+        return Result.success(result);
+    }
+}

+ 137 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentResultController.java

@@ -0,0 +1,137 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.common.constant.DimensionCodeConstants;
+import com.etotem.cfc.dto.AssessmentHistoryItemDTO;
+import com.etotem.cfc.dto.AssessmentResultDTO;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.service.CognitiveService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "测评结果", description = "DAN认知测评结果查询")
+@RestController
+@RequestMapping("/api/assessment")
+public class AssessmentResultController {
+
+    @Resource
+    private CognitiveService cognitiveService;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Operation(summary = "获取成员最新认知测评结果")
+    @PostMapping("/latest-result")
+    public Result<AssessmentResultDTO> getLatestResult(@RequestBody Map<String, Object> body,
+                                                       @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        DanAssessmentResult result = cognitiveService.getChildLatestResult(memberId);
+        if (result == null) {
+            return Result.success(null);
+        }
+
+        // SC-P-39 边界「量纲标注」:八类报告分数超出 0-100 量纲(dimension-scoring-convention §1)时拒显,
+        // 不透传脏数据(覆盖八类全部维度字段,任一越界即整体拒显)
+        if (hasAnyDimensionOutOfRange(result)) {
+            return Result.error(400, "测评结果分数超出0-100量纲范围,拒绝展示");
+        }
+
+        AssessmentResultDTO dto = new AssessmentResultDTO();
+        dto.setMemberId(result.getMemberId());
+        dto.setChildName(result.getChildName());
+        dto.setScaleMin(DimensionCodeConstants.SCORE_MIN);
+        dto.setScaleMax(DimensionCodeConstants.SCORE_MAX);
+        // 八类报告中文标签(供结果页直接渲染,与 indicator_definitions 认知维度命名一致)
+        dto.setOverallLabel("综合");
+        dto.setAttentionLabel("注意力");
+        dto.setFocusLabel("专注力");
+        dto.setMemoryLabel("记忆力");
+        dto.setLogicLabel("逻辑思维");
+        dto.setPerceptionLabel("感知能力");
+        dto.setSpatialLabel("空间思维");
+        dto.setProcessingSpeedLabel("加工速度");
+        dto.setOverallScore(result.getOverallScore());
+        dto.setAttentionScore(result.getAttentionScore());
+        dto.setFocusScore(result.getFocusScore());
+        dto.setMemoryScore(result.getMemoryScore());
+        dto.setLogicScore(result.getLogicScore());
+        dto.setPerceptionScore(result.getPerceptionScore());
+        dto.setSpatialScore(result.getSpatialScore());
+        dto.setProcessingSpeedScore(result.getProcessingSpeedScore());
+        dto.setAnalysisReport(result.getAnalysisReport());
+        dto.setGrowthSuggestions(result.getGrowthSuggestions());
+        dto.setAssessmentDate(result.getAssessmentDate());
+        return Result.success(dto);
+    }
+
+    @Operation(summary = "获取成员测评历史记录")
+    @PostMapping("/history")
+    public Result<List<AssessmentHistoryItemDTO>> getHistory(@RequestBody Map<String, Object> body,
+                                                             @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        int size = body.get("size") != null
+                ? Integer.parseInt(body.get("size").toString())
+                : 5;
+
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<DanAssessmentResult>()
+                .eq(DanAssessmentResult::getMemberId, memberId)
+                .eq(DanAssessmentResult::getStatus, "completed")
+                .orderByDesc(DanAssessmentResult::getAssessmentDate)
+                .last("LIMIT " + size);
+        SortUtil.applySort(wrapper);
+        List<DanAssessmentResult> results = danAssessmentResultMapper.selectList(wrapper);
+
+        List<AssessmentHistoryItemDTO> list = new ArrayList<>();
+        for (DanAssessmentResult r : results) {
+            // SC-P-39 量纲口径(0-100 闭区间):历史链路同样拒绝透传越界分数,越界条目拒显/过滤
+            if (isOutOfRange(r.getOverallScore())) {
+                continue;
+            }
+            AssessmentHistoryItemDTO item = new AssessmentHistoryItemDTO();
+            item.setAssessmentDate(r.getAssessmentDate());
+            item.setOverallScore(r.getOverallScore());
+            // 量纲标注(与最新结果页同口径):0-100 闭区间 + 综合得分中文标签
+            item.setScaleMin(DimensionCodeConstants.SCORE_MIN);
+            item.setScaleMax(DimensionCodeConstants.SCORE_MAX);
+            item.setOverallLabel("综合");
+            list.add(item);
+        }
+        return Result.success(list);
+    }
+
+    /** 八类报告维度是否任一越界(超出 0-100 量纲闭区间即拒显) */
+    private static boolean hasAnyDimensionOutOfRange(DanAssessmentResult r) {
+        return isOutOfRange(r.getOverallScore())
+                || isOutOfRange(r.getAttentionScore())
+                || isOutOfRange(r.getFocusScore())
+                || isOutOfRange(r.getMemoryScore())
+                || isOutOfRange(r.getLogicScore())
+                || isOutOfRange(r.getPerceptionScore())
+                || isOutOfRange(r.getSpatialScore())
+                || isOutOfRange(r.getProcessingSpeedScore());
+    }
+
+    /** 单维度越界判断:null 视为未录入(不算越界),非 null 须落在 [SCORE_MIN, SCORE_MAX] 闭区间 */
+    private static boolean isOutOfRange(Integer score) {
+        return score != null
+                && (score < DimensionCodeConstants.SCORE_MIN || score > DimensionCodeConstants.SCORE_MAX);
+    }
+}

+ 249 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/CognitiveController.java

@@ -0,0 +1,249 @@
+package com.etotem.cfc.controller.assessment;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CognitiveRecommendationDTO;
+import com.etotem.cfc.dto.CognitiveTrendItemDTO;
+import com.etotem.cfc.dto.CreateCognitiveTaskDTO;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.service.CognitiveNormService;
+import com.etotem.cfc.service.CognitiveService;
+import com.etotem.cfc.service.CognitiveTrainingConfigService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.*;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "认知维度", description = "六维认知体系(感知、专注、记忆、逻辑、空间、加工速度)")
+@RestController
+@RequestMapping("/api/cognitive")
+public class CognitiveController {
+
+    @Resource
+    private CognitiveService cognitiveService;
+
+    @Resource
+    private CognitiveTrainingConfigService cognitiveTrainingConfigService;
+
+    @Resource
+    private CognitiveNormService cognitiveNormService;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Operation(summary = "获取成员最新六维认知得分")
+    @PostMapping("/child")
+    public Result<Map<String, Object>> getChildCognitiveScores(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        DanAssessmentResult result = cognitiveService.getChildLatestResult(memberId);
+        if (result == null) {
+            return Result.success(null);
+        }
+
+        Map<String, Object> scores = new LinkedHashMap<>();
+        scores.put("memberId", result.getMemberId());
+        scores.put("childName", result.getChildName());
+        scores.put("attentionScore", result.getAttentionScore());
+        scores.put("focusScore", result.getFocusScore());
+        scores.put("memoryScore", result.getMemoryScore());
+        scores.put("logicScore", result.getLogicScore());
+        scores.put("perceptionScore", result.getPerceptionScore());
+        scores.put("spatialScore", result.getSpatialScore());
+        scores.put("processingSpeedScore", result.getProcessingSpeedScore());
+        scores.put("overallScore", result.getOverallScore());
+        scores.put("assessmentDate", result.getAssessmentDate());
+
+        return Result.success(scores);
+    }
+
+    @Operation(summary = "获取家庭所有成员的最新六维认知得分")
+    @PostMapping("/family")
+    public Result<List<Map<String, Object>>> getFamilyCognitiveScores(
+            @RequestAttribute("userId") Long userId) {
+        Map<Long, DanAssessmentResult> results = cognitiveService.getFamilyLatestResults(userId);
+
+        List<Map<String, Object>> list = new ArrayList<>();
+        for (Map.Entry<Long, DanAssessmentResult> entry : results.entrySet()) {
+            DanAssessmentResult r = entry.getValue();
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("memberId", r.getMemberId());
+            item.put("childName", r.getChildName());
+            item.put("attentionScore", r.getAttentionScore());
+            item.put("focusScore", r.getFocusScore());
+            item.put("memoryScore", r.getMemoryScore());
+            item.put("logicScore", r.getLogicScore());
+            item.put("perceptionScore", r.getPerceptionScore());
+            item.put("spatialScore", r.getSpatialScore());
+            item.put("processingSpeedScore", r.getProcessingSpeedScore());
+            item.put("overallScore", r.getOverallScore());
+            item.put("assessmentDate", r.getAssessmentDate());
+            list.add(item);
+        }
+
+        return Result.success(list);
+    }
+
+    @Operation(summary = "更新成员认知维度得分")
+    @PostMapping("/update")
+    public Result<String> updateCognitiveScore(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        String dimension = body.get("dimension") != null
+                ? body.get("dimension").toString()
+                : null;
+        Integer score = body.get("score") != null
+                ? Integer.valueOf(body.get("score").toString())
+                : null;
+
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        if (dimension == null || dimension.isEmpty()) {
+            return Result.error("dimension不能为空");
+        }
+        if (score == null) {
+            return Result.error("score不能为空");
+        }
+
+        boolean success = cognitiveService.updateChildDimensionScore(memberId, dimension, score);
+        if (!success) {
+            return Result.error("更新失败,未找到最新测评结果或维度不存在");
+        }
+        return Result.success("更新成功");
+    }
+
+    @Operation(summary = "获取认知训练建议(根据最新DAN评估生成家庭行动清单)")
+    @PostMapping("/recommendations")
+    public Result<CognitiveRecommendationDTO> getRecommendations(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        CognitiveRecommendationDTO rec = cognitiveTrainingConfigService.generateRecommendations(memberId);
+        if (rec == null) {
+            return Result.error("暂无评估数据,请先完成认知评估");
+        }
+        return Result.success(rec);
+    }
+
+    @Operation(summary = "从认知训练建议创建任务(一键添加到今日任务)")
+    @PostMapping("/recommendations/create-task")
+    public Result<Long> createTaskFromRecommendation(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody CreateCognitiveTaskDTO dto,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = dto.getMemberId() != null ? dto.getMemberId() : currentMemberId;
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        if (dto.getDimensionKey() == null) {
+            return Result.error("dimensionKey不能为空");
+        }
+
+        Long taskId = cognitiveTrainingConfigService.createTaskFromRecommendation(
+                userId, memberId, dto.getDimensionKey(), dto.getTaskIndex());
+        if (taskId == null) {
+            return Result.error("创建任务失败,请检查评估数据");
+        }
+        return Result.success(taskId);
+    }
+
+    @Operation(summary = "获取认知维度百分位常模(与同龄人对比)")
+    @PostMapping("/norms")
+    public Result<Map<String, Object>> getNorms(@RequestBody Map<String, Object> body,
+                                                @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        Map<String, Object> norms = cognitiveNormService.getNorms(memberId);
+        if (norms.isEmpty()) {
+            return Result.error("暂无常模数据");
+        }
+        return Result.success(norms);
+    }
+
+    @Operation(summary = "获取认知维度历史趋势(六维分数+综合分按时序排列)")
+    @PostMapping("/trend")
+    public Result<List<CognitiveTrendItemDTO>> getTrend(@RequestBody Map<String, Object> body,
+                                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        int limit = body.get("limit") != null
+                ? Integer.parseInt(body.get("limit").toString())
+                : 5;
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+
+        List<DanAssessmentResult> results = danAssessmentResultMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<DanAssessmentResult>()
+                        .eq(DanAssessmentResult::getMemberId, memberId)
+                        .eq(DanAssessmentResult::getStatus, "completed")
+                        .orderByDesc(DanAssessmentResult::getAssessmentDate)
+                        .last("LIMIT " + limit)
+        );
+
+        List<CognitiveTrendItemDTO> trend = new ArrayList<>();
+        for (DanAssessmentResult r : results) {
+            CognitiveTrendItemDTO item = new CognitiveTrendItemDTO();
+            item.setAssessmentDate(r.getAssessmentDate());
+            item.setOverallScore(r.getOverallScore());
+            item.setPerceptionScore(r.getPerceptionScore());
+            item.setFocusScore(r.getFocusScore());
+            item.setMemoryScore(r.getMemoryScore());
+            item.setLogicScore(r.getLogicScore());
+            item.setSpatialScore(r.getSpatialScore());
+            item.setProcessingSpeedScore(r.getProcessingSpeedScore());
+            trend.add(item);
+        }
+
+        return Result.success(trend);
+    }
+
+    @Operation(summary = "提交认知自测结果(写入六维认知档案,自动创建档案)")
+    @PostMapping("/self-test")
+    public Result<String> submitSelfTest(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        String dimension = body.get("dimension") != null
+                ? body.get("dimension").toString()
+                : null;
+        Integer score = body.get("score") != null
+                ? Integer.valueOf(body.get("score").toString())
+                : null;
+
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        if (dimension == null || dimension.isEmpty()) {
+            return Result.error("dimension不能为空");
+        }
+        if (score == null) {
+            return Result.error("score不能为空");
+        }
+        if (score < 0 || score > 100) {
+            return Result.error("score必须在0-100之间");
+        }
+
+        boolean ok = cognitiveService.submitSelfTestScore(memberId, dimension, score);
+        if (!ok) {
+            return Result.error("提交失败,请重试");
+        }
+        return Result.success("提交成功");
+    }
+}

+ 412 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/auth/AuthController.java

@@ -0,0 +1,412 @@
+package com.etotem.cfc.controller.auth;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.JwtConfig;
+import com.etotem.cfc.dto.*;
+import com.etotem.cfc.dto.RegisterWithIdCardDTO;
+import com.etotem.cfc.dto.RegisterWithInviteCodeDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AuthProfileService;
+import com.etotem.cfc.service.SsoService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.VerificationCodeService;
+import io.jsonwebtoken.Claims;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "用户认证", description = "用户登录、验证码、密码设置等认证接口")
+@RestController
+@Slf4j
+@RequestMapping("/api/auth")
+public class AuthController {
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private VerificationCodeService verificationCodeService;
+
+    @Resource
+    private JwtConfig jwtConfig;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private SsoService ssoService;
+
+    @Resource
+    private AuthProfileService authProfileService;
+
+    /**
+     * 发送验证码
+     */
+    @Operation(summary = "发送验证码")
+    @PostMapping("/send-code")
+    public Result<Boolean> sendCode(@RequestBody SendCodeDTO dto) {
+        if (dto.getPhone() == null || dto.getPhone().isEmpty()) {
+            return Result.error("手机号不能为空");
+        }
+        // 验证手机号格式
+        if (!dto.getPhone().matches("^1[3-9]\\d{9}$")) {
+            return Result.error("手机号格式不正确");
+        }
+        verificationCodeService.generateCode(dto.getPhone(), dto.getType());
+        return Result.success(true);
+    }
+
+    /**
+     * 手机号验证码登录
+     */
+    @Operation(summary = "手机号验证码登录")
+    @PostMapping("/phone-login")
+    public Result<LoginResultDTO> phoneLogin(@RequestBody PhoneLoginDTO dto) {
+        if (dto.getPhone() == null || dto.getCode() == null) {
+            return Result.error("手机号和验证码不能为空");
+        }
+        // 验证验证码
+        boolean valid = verificationCodeService.verifyCode(dto.getPhone(), dto.getCode(), "login");
+        if (!valid) {
+            return Result.error("验证码错误或已过期");
+        }
+        // 执行登录
+        try {
+            LoginResultDTO result = userService.phoneLogin(dto);
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 微信手机号登录(通过微信开放能力获取手机号)
+     */
+    @Operation(summary = "微信手机号登录")
+    @PostMapping("/wechat-phone-login")
+    public Result<LoginResultDTO> wechatPhoneLogin(@RequestBody WechatPhoneLoginDTO dto) {
+        if (dto.getCode() == null || dto.getPhoneCode() == null) {
+            return Result.error("登录code和手机号code不能为空");
+        }
+        try {
+            LoginResultDTO result = userService.wechatPhoneLogin(dto);
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 微信静默登录(用户再次打开小程序时自动登录)
+     */
+    @Operation(summary = "微信静默登录")
+    @PostMapping("/silent-login")
+    public Result<LoginResultDTO> silentLogin(@RequestBody WechatLoginDTO dto) {
+        if (dto.getCode() == null) {
+            return Result.error("登录code不能为空");
+        }
+        try {
+            LoginResultDTO result = userService.silentLogin(dto.getCode());
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 通过openid自动登录 —— 已废弃(410 Gone)
+     *
+     * <p>废弃原因(安全漏洞,2026-09 修复):本接口只凭请求参数里的明文 openid 就签发完整 JWT,
+     * 不做任何持有性证明。而 openid 并非密钥——它会随登录响应返回、明文存于小程序本地 storage、
+     * 并可能经日志/截图泄露。任何拿到他人 openid 的人都能直接换取该账号的合法 token,
+     * 等同于完全冒充。
+     *
+     * <p>替代方案:{@code /api/auth/silent-login}。前端调 {@code uni.login()} 拿微信签发的
+     * 一次性 code,服务端 code2Session 换 openid。code 单次使用、5 分钟过期,且能证明调用方
+     * 持有该微信设备,因此不可伪造,同样零交互静默完成。
+     *
+     * <p>按项目规范(AGENTS.md「废弃接口标记 410 Gone 并注释说明,不直接删除」):
+     * 保留路由与注释,待线上旧版本小程序全部升级后再移除路由。
+     */
+    @Operation(summary = "openid自动登录(已废弃,返回 410,请改用 /api/auth/silent-login)")
+    @PostMapping("/auto-login")
+    public Result<LoginResultDTO> autoLogin(@RequestBody WechatLoginDTO dto) {
+        log.warn("/api/auth/auto-login 已被调用(已废弃接口):该接口仅凭 openid 签发 token 存在越权风险,已拒绝。请前端改用 /api/auth/silent-login");
+        return Result.error(410, "该接口已废弃,请改用 /api/auth/silent-login");
+    }
+
+    /**
+     * 手机号+身份证注册登录
+     */
+    @Operation(summary = "手机号+身份证注册登录")
+    @PostMapping("/register-with-idcard")
+    public Result<LoginResultDTO> registerWithIdCard(@RequestBody RegisterWithIdCardDTO dto) {
+        if (dto.getPhone() == null || dto.getCode() == null) {
+            return Result.error("手机号和验证码不能为空");
+        }
+        if (dto.getIdCard() == null || dto.getIdCard().isEmpty()) {
+            return Result.error("身份证号不能为空");
+        }
+        if (dto.getRealName() == null || dto.getRealName().isEmpty()) {
+            return Result.error("真实姓名不能为空");
+        }
+        
+        // 验证身份证格式(简单验证,实际应更严格)
+        if (!dto.getIdCard().matches("^\\d{15}$|^\\d{17}[0-9Xx]$")) {
+            return Result.error("身份证号格式不正确");
+        }
+        
+        try {
+            LoginResultDTO result = userService.registerWithIdCard(dto);
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 微信code登录(原有功能)
+     */
+    @Operation(summary = "微信code登录")
+    @PostMapping("/wechat-login")
+    public Result<LoginResultDTO> wechatLogin(@RequestBody WechatLoginDTO dto) {
+        try {
+            LoginResultDTO result = userService.wechatLogin(dto);
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取当前用户信息")
+    @PostMapping("/info")
+    public Result<User> getInfo(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("未登录");
+        }
+        User user = userService.getUserInfo(userId);
+        if (user != null) {
+            user.setPassword(null);
+        }
+        // C-16 受限资料投影:孩子端隐藏敏感字段
+        userService.maskChildSensitiveFields(user);
+        return Result.success(user);
+    }
+
+    @Operation(summary = "设置密码")
+    @PostMapping("/set-password")
+    public Result<Boolean> setPassword(@RequestBody SetPasswordDTO dto,
+                                       @RequestAttribute("userId") Long userId) {
+        boolean success = userService.setPassword(userId, dto.getPassword());
+        return Result.success(success);
+    }
+
+    @Operation(summary = "设置切换保护密码")
+    @PostMapping("/set-switch-password")
+    public Result<Boolean> setSwitchPassword(@RequestBody SetPasswordDTO dto,
+                                             @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        boolean success = userService.setSwitchPassword(userId, dto.getPassword());
+        return Result.success(success);
+    }
+
+    /**
+     * JWT Token 验证
+     * 从 Authorization header 提取 Bearer token,验证并返回用户信息
+     */
+    @Operation(summary = "验证JWT Token有效性(含 user 存在性)")
+    @PostMapping("/verify")
+    public Result<Map<String, Object>> verifyToken(HttpServletRequest request) {
+        String authHeader = request.getHeader("Authorization");
+        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
+            return Result.error(401, "无效的Token");
+        }
+        try {
+            String token = authHeader.substring(7);
+            Claims claims = jwtConfig.parseToken(token);
+            Long userId = Long.parseLong(claims.getSubject());
+            String role = (String) claims.get("role");
+
+            // 校验 user 是否仍存在(账号被清理/禁用时 JWT 仍可能合法)
+            // 不存在则视为登录态失效,返回 401 触发前端 _clearAuthAndRedirect
+            if (userMapper.selectById(userId) == null) {
+                log.warn("/api/auth/verify: userId={} 在数据库不存在,返回 401", userId);
+                return Result.error(401, "用户不存在");
+            }
+
+            Map<String, Object> data = new HashMap<>();
+            data.put("userId", userId);
+            data.put("role", role);
+            return Result.success(data);
+        } catch (Exception e) {
+            return Result.error(401, "Token无效或已过期");
+        }
+    }
+
+    @Operation(summary = "验证密码")
+    @PostMapping("/verify-password")
+    public Result<Boolean> verifyPassword(@RequestBody VerifyPasswordDTO dto,
+                                          @RequestAttribute("userId") Long userId) {
+        boolean valid = userService.verifyPassword(userId, dto.getPassword());
+        return Result.success(valid);
+    }
+
+    /**
+     * 检查手机号是否已注册(测试环境用)
+     */
+    @Operation(summary = "检查手机号是否已注册")
+    @PostMapping("/check-phone")
+    public Result<Boolean> checkPhone(@RequestBody CheckPhoneDTO dto) {
+        if (dto.getPhone() == null || dto.getPhone().isEmpty()) {
+            return Result.error("手机号不能为空");
+        }
+        if (!dto.getPhone().matches("^1[3-9]\\d{9}$")) {
+            return Result.error("手机号格式不正确");
+        }
+        boolean registered = userService.isPhoneRegistered(dto.getPhone());
+        return Result.success(registered);
+    }
+
+    /**
+     * 直接注册(测试环境:新用户不通过验证码直接注册)
+     */
+    @Operation(summary = "直接注册用户")
+    @PostMapping("/direct-register")
+    public Result<LoginResultDTO> directRegister(@RequestBody DirectRegisterDTO dto) {
+        if (dto.getPhone() == null || dto.getPhone().isEmpty()) {
+            return Result.error("手机号不能为空");
+        }
+        if (!dto.getPhone().matches("^1[3-9]\\d{9}$")) {
+            return Result.error("手机号格式不正确");
+        }
+        // 检查手机号是否已注册
+        if (userService.isPhoneRegistered(dto.getPhone())) {
+            return Result.error("该手机号已注册,请使用验证码登录");
+        }
+        
+        LoginResultDTO result = userService.directRegister(dto);
+        return Result.success(result);
+    }
+
+    /**
+     * 使用邀请码注册并加入家庭
+     */
+    @Operation(summary = "使用邀请码注册")
+    @PostMapping("/register-with-invite")
+    public Result<LoginResultDTO> registerWithInvite(@RequestBody RegisterWithInviteCodeDTO dto) {
+        if (dto.getPhone() == null || dto.getPhone().isEmpty()) {
+            return Result.error("手机号不能为空");
+        }
+        if (dto.getInviteCode() == null || dto.getInviteCode().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+        if (dto.getCode() == null || dto.getCode().isEmpty()) {
+            return Result.error("验证码不能为空");
+        }
+
+        // 验证验证码
+        if (!verificationCodeService.verifyCode(dto.getPhone(), dto.getCode(), dto.getCodeId())) {
+            return Result.error("验证码错误或已过期");
+        }
+
+        // 检查手机号是否已注册
+        if (userService.isPhoneRegistered(dto.getPhone())) {
+            return Result.error("该手机号已注册,请使用验证码登录");
+        }
+
+        try {
+            LoginResultDTO result = userService.registerWithInviteCode(dto);
+            return Result.success(result);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    
+    @PostMapping("/switch-role")
+    public Result<LoginResultDTO> switchRole(@RequestBody SwitchRoleDTO dto, @RequestAttribute("userId") Long userId) {
+        // SEC-20261031-01:鉴权统一——匿名注入 userId=-1,统一拦截为 401(对齐 ssoTicket 口径)
+        if (userId == null || userId <= 0) {
+            return Result.error(401, "请先登录");
+        }
+        try {
+            LoginResultDTO result = userService.switchRoleForLogin(userId, dto.getRole());
+            return Result.success(result);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 跨小程序单点登录 - 签发一次性票据(需登录)。
+     * 请求体: { "target": "train" };返回 { ticket, target }。
+     * 前端拿到 ticket 后通过 uni.navigateToMiniProgram 跳转到目标小程序的落地页。
+     */
+    @Operation(summary = "SSO 签发一次性票据")
+    @PostMapping("/sso-ticket")
+    public Result<Map<String, Object>> ssoTicket(@RequestBody Map<String, String> body,
+                                                 @RequestAttribute("userId") Long userId) {
+        if (userId == null || userId <= 0) {
+            return Result.error(401, "请先登录");
+        }
+        String target = body != null ? body.get("target") : null;
+        if (!SsoService.SYS_TRAIN.equals(target)) {
+            return Result.error("不支持的目标系统");
+        }
+        try {
+            String ticket = ssoService.issueTicket(SsoService.SYS_CFC, target, userId, userId);
+            Map<String, Object> data = new HashMap<>();
+            data.put("ticket", ticket);
+            data.put("target", target);
+            return Result.success(data);
+        } catch (Exception e) {
+            log.error("签发 SSO 票据失败: userId={}", userId, e);
+            return Result.error("签发票据失败,请稍后重试");
+        }
+    }
+
+    /**
+     * 跨小程序单点登录 - 消费一次性票据换取 cfc 登录态(公开接口)。
+     * 请求体: { "ticket": "..." }。
+     */
+    @Operation(summary = "SSO 票据换取登录态")
+    @PostMapping("/sso-login")
+    public Result<LoginResultDTO> ssoLogin(@RequestBody Map<String, String> body) {
+        String ticket = body != null ? body.get("ticket") : null;
+        if (ticket == null || ticket.trim().isEmpty()) {
+            return Result.error("票据不能为空");
+        }
+        Long cfcUserId = ssoService.consumeTicket(ticket, SsoService.SYS_CFC);
+        if (cfcUserId == null) {
+            return Result.error("票据无效或已过期,请重新进入");
+        }
+        try {
+            LoginResultDTO result = userService.ssoLogin(cfcUserId);
+            return Result.success(result);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 个人资料编辑(SC-P-64 / auth.profile.edit):编辑昵称 / 头像 / 绑定手机。
+     * 手机号格式与昵称边界非法 → 400;绑定手机变更需 verifyCode 二次确认。
+     */
+    @Operation(summary = "个人资料编辑(昵称/头像/绑定手机)")
+    @PostMapping("/profile/edit")
+    public Result<Boolean> editProfile(@RequestAttribute("userId") Long userId,
+                                       @RequestBody AuthProfileEditDTO dto) {
+        return authProfileService.editProfile(userId, dto);
+    }
+
+}

+ 130 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/auth/WechatWebAuthController.java

@@ -0,0 +1,130 @@
+package com.etotem.cfc.controller.auth;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.LoginResultDTO;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.WechatWebLoginService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * 微信「小程序码」扫码登录(桌面端 SSO)。
+ *
+ * <p>流程:桌面端 POST /qr 拿 state+小程序码图片 → 用户用微信扫码打开小程序落地页
+ * (从 scene 取 state)→ 小程序(已登录,带小程序 JWT)POST /scan 确认 →
+ * 服务端写 state=U{userId} → 桌面端轮询 POST /poll 取 JWT。
+ *
+ * <p>全部为 POST:/qr、/poll 公开(桌面端尚未持有令牌),/scan 需小程序 JWT
+ * (扫码者即小程序已登录用户,据此完成与小程序账号的 SSO)。
+ */
+@Tag(name = "微信小程序扫码登录", description = "桌面端小程序码扫码登录,与小程序账号 SSO")
+@RestController
+@Slf4j
+@RequestMapping("/api/auth/wechat-web")
+public class WechatWebAuthController {
+
+    @Resource
+    private WechatWebLoginService wechatWebLoginService;
+
+    @Resource
+    private UserService userService;
+
+    @Operation(summary = "获取扫码登录小程序码")
+    @PostMapping("/qr")
+    public Result<Map<String, Object>> qr() {
+        String state = UUID.randomUUID().toString().replace("-", "");
+        wechatWebLoginService.putState(state, "P");
+        Map<String, Object> data = new HashMap<>();
+        data.put("state", state);
+        try {
+            String base64 = wechatWebLoginService.generateQrImage(state);
+            data.put("qrImage", base64 == null || base64.isEmpty() ? "" : "data:image/png;base64," + base64);
+        } catch (RuntimeException e) {
+            log.error("生成登录小程序码失败: state={}", state, e);
+            wechatWebLoginService.removeState(state);
+            return Result.error("生成二维码失败:" + e.getMessage());
+        }
+        return Result.success(data);
+    }
+
+    @Operation(summary = "小程序扫码确认登录(小程序端调用,携带小程序 JWT)")
+    @PostMapping("/scan")
+    public Result<Map<String, Object>> scan(@RequestBody Map<String, String> body,
+                                            @RequestAttribute("userId") Long userId) {
+        String state = body != null ? body.get("state") : null;
+        if (state == null || state.trim().isEmpty()) {
+            return Result.error("缺少 state");
+        }
+        Object stored = wechatWebLoginService.getState(state);
+        if (stored == null) {
+            return Result.error("二维码已过期,请重新获取");
+        }
+        if (!"P".equals(stored.toString())) {
+            return Result.error("二维码已被使用或已过期");
+        }
+        if (userId == null) {
+            return Result.error("请先登录小程序");
+        }
+        wechatWebLoginService.putState(state, "U" + userId);
+        log.info("小程序扫码确认登录: state={}, userId={}", state, userId);
+        Map<String, Object> data = new HashMap<>();
+        data.put("status", "ok");
+        return Result.success(data);
+    }
+
+    @Operation(summary = "轮询扫码登录结果")
+    @PostMapping("/poll")
+    public Result<Map<String, Object>> poll(@RequestBody Map<String, String> body) {
+        String state = body != null ? body.get("state") : null;
+        Map<String, Object> data = new HashMap<>();
+        if (state == null || state.trim().isEmpty()) {
+            return Result.error("缺少 state");
+        }
+        Object stored = wechatWebLoginService.getState(state);
+        if (stored == null) {
+            data.put("status", "expired");
+            return Result.success(data);
+        }
+        String value = stored.toString();
+        if ("P".equals(value)) {
+            data.put("status", "pending");
+            return Result.success(data);
+        }
+        if ("N".equals(value)) {
+            wechatWebLoginService.removeState(state);
+            data.put("status", "notfound");
+            return Result.success(data);
+        }
+        if (value.startsWith("U")) {
+            wechatWebLoginService.removeState(state);
+            Long userId = Long.valueOf(value.substring(1));
+            try {
+                LoginResultDTO login = userService.ssoLogin(userId);
+                data.put("status", "success");
+                data.put("token", login.getToken());
+                data.put("userId", login.getUserId());
+                data.put("role", login.getRole());
+                data.put("nickname", login.getNickname());
+            } catch (RuntimeException e) {
+                log.warn("小程序扫码换取 JWT 失败: state={}, error={}", state, e.getMessage());
+                data.put("status", "error");
+                data.put("message", e.getMessage() != null ? e.getMessage() : "登录失败");
+            }
+            return Result.success(data);
+        }
+        data.put("status", "error");
+        data.put("message", "未知状态");
+        return Result.success(data);
+    }
+}

+ 410 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/butler/ButlerController.java

@@ -0,0 +1,410 @@
+package com.etotem.cfc.controller.butler;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ButlerEscalationOrder;
+import com.etotem.cfc.entity.ButlerOneOnOneCoachRecord;
+import com.etotem.cfc.entity.ButlerResourceMatchResult;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerAiCollaborationService;
+import com.etotem.cfc.service.ButlerEscalationService;
+import com.etotem.cfc.service.ButlerOneOnOneCoachService;
+import com.etotem.cfc.service.ButlerResourceMatchService;
+import com.etotem.cfc.service.ButlerService;
+import com.etotem.cfc.service.RealNameBackfillService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+
+@RestController("butlerController")
+public class ButlerController {
+
+    @Resource
+    private ButlerEscalationService butlerEscalationService;
+
+    @Resource
+    private ButlerService butlerService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private RealNameBackfillService realNameBackfillService;
+
+    @Resource
+    private ButlerResourceMatchService butlerResourceMatchService;
+
+    @Resource
+    private ButlerResourceMatchResultMapper butlerResourceMatchResultMapper;
+
+    @Resource
+    private ButlerOneOnOneCoachService butlerOneOnOneCoachService;
+
+    @Resource
+    private ButlerAiCollaborationService butlerAiCollaborationService;
+
+    /**
+     * 申请成为管家
+     * POST /api/butler/apply
+     */
+    @PostMapping("/api/butler/apply")
+    public Result<String> apply(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("userId") Long userId) {
+        String tier = (String) params.get("tier");
+        String description = (String) params.get("description");
+        // 管家申请:接收 realName,若 realName 尚未填写则同时回填 realName + nickname(nickname 仅空时补)
+        String realName = (String) params.get("realName");
+        Result<String> result = butlerService.apply(userId, tier, description);
+        if (result.getCode() == 200 && realName != null && !realName.trim().isEmpty()) {
+            realNameBackfillService.backfillRealNameAndNickname(userId, realName.trim());
+        }
+        return result;
+    }
+
+    /**
+     * 获取管家档案
+     * POST /api/butler/profile
+     */
+    @PostMapping("/api/butler/profile")
+    public Result<Map<String, Object>> getProfile(@RequestAttribute("userId") Long userId) {
+        return butlerService.getProfile(userId);
+    }
+
+    /**
+     * 更新管家档案
+     * POST /api/butler/update-profile
+     */
+    @PostMapping("/api/butler/update-profile")
+    public Result<String> updateProfile(@RequestBody Map<String, Object> params,
+                                         @RequestAttribute("userId") Long userId) {
+        return butlerService.updateProfile(userId, params);
+    }
+
+    /**
+     * 获取分配的家庭成员列表
+     * POST /api/butler/members
+     */
+    @PostMapping("/api/butler/members")
+    public Result<Map<String, Object>> getMembers(@RequestBody Map<String, Object> params,
+                                                   @RequestAttribute("userId") Long userId) {
+        int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
+        int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 20;
+
+        Page<User> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
+                .eq(User::getReferrerId, userId)
+                .orderByDesc(User::getUpdatedAt);
+
+        SortUtil.applySort(wrapper);
+        Page<User> result = userMapper.selectPage(pageParam, wrapper);
+
+        // B-4/F1:管理端/家庭端分页列表统一 envelope 为 data.records(与 activity 等列表一致),不再返回 data.list
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", result.getRecords());
+        data.put("total", result.getTotal());
+        data.put("page", page);
+        data.put("size", size);
+        return Result.success(data);
+    }
+
+    /**
+     * 家庭端查看匹配结果(AC2:家长端可查看并选择匹配结果)
+     * POST /api/butler/resource-match/list
+     */
+    @PostMapping("/api/butler/resource-match/list")
+    public Result<List<ButlerResourceMatchResult>> listResourceMatch(@RequestBody Map<String, Object> params,
+                                                                     @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult> wrapper =
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult>()
+                        .eq(ButlerResourceMatchResult::getMemberId, memberId)
+                        .orderByDesc(ButlerResourceMatchResult::getCreatedAt);
+        if (familyId != null) {
+            wrapper.eq(ButlerResourceMatchResult::getFamilyId, familyId);
+        }
+        return Result.success(butlerResourceMatchResultMapper.selectList(wrapper));
+    }
+
+    /**
+     * 匹配入口(按家长需求与孩子画像匹配资源,SC-H-05 正常流步骤1)
+     * POST /api/butler/resource-match/generate
+     */
+    @PostMapping("/api/butler/resource-match/generate")
+    public Result<List<ButlerResourceMatchResult>> generateResourceMatch(@RequestBody Map<String, Object> params,
+                                                                         @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        @SuppressWarnings("unchecked")
+        Map<String, Object> requirements = (Map<String, Object>) params.get("requirements");
+        return butlerResourceMatchService.match(userId, familyId, memberId, requirements);
+    }
+
+    /**
+     * 协助预约/报名(AC3:名额实时校验联动,满员提示「名额已满」)
+     * POST /api/butler/resource-match/book
+     */
+    @PostMapping("/api/butler/resource-match/book")
+    public Result<Map<String, Object>> bookResourceMatch(@RequestBody Map<String, Object> params,
+                                                         @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long matchResultId = params.get("matchResultId") != null ? Long.valueOf(params.get("matchResultId").toString()) : null;
+        return butlerResourceMatchService.book(userId, memberId, matchResultId);
+    }
+
+    /**
+     * 回访沉淀偏好(AC4:参与后回访记录写入家长档案)
+     * POST /api/butler/resource-match/follow-up
+     */
+    @PostMapping("/api/butler/resource-match/follow-up")
+    public Result<String> followUpResourceMatch(@RequestBody Map<String, Object> params,
+                                                @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        return butlerResourceMatchService.recordFollowUp(userId, familyId, memberId, params);
+    }
+
+    /**
+     * 获取服务记录(已废弃)
+     * POST /api/butler/service-records
+     */
+    @Deprecated
+    @Operation(summary = "获取服务记录", deprecated = true)
+    @PostMapping("/api/butler/service-records")
+    public Result<Map<String, Object>> getServiceRecords(@RequestBody Map<String, Object> params,
+    @RequestAttribute("userId") Long userId) {
+    return Result.error(410, "该接口已废弃,无替代方案");
+    }
+
+    /**
+     * 获取佣金记录(已废弃)
+     * POST /api/butler/commissions
+     */
+    @Deprecated
+    @Operation(summary = "获取佣金记录", deprecated = true)
+    @PostMapping("/api/butler/commissions")
+    public Result<Map<String, Object>> getCommissions(@RequestBody Map<String, Object> params,
+    @RequestAttribute("userId") Long userId) {
+    return Result.error(410, "该接口已废弃,无替代方案");
+    }
+
+    // ==================== 升级工单治理(能力键 butler.escalation.handle · SC-H-01 / SC-H-04) ====================
+
+    /**
+     * 工作台:按风险等级优先返回待认领/处理中/已升级工单(SC-H-01 工作台)。
+     * POST /api/butler/escalation/list
+     */
+    @PostMapping("/api/butler/escalation/list")
+    public Result<List<ButlerEscalationOrder>> escalationList(@RequestAttribute("userId") Long userId) {
+        return butlerEscalationService.list(userId);
+    }
+
+    /**
+     * 工单详情,仅本家庭可见(越界 403)。
+     * POST /api/butler/escalation/detail
+     */
+    @PostMapping("/api/butler/escalation/detail")
+    public Result<ButlerEscalationOrder> escalationDetail(@RequestBody Map<String, Object> params,
+                                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.detail(workorderId, userId);
+    }
+
+    /**
+     * 乐观锁认领:同一工单只允许一人认领,他人提示「已被认领」。
+     * POST /api/butler/escalation/claim
+     */
+    @PostMapping("/api/butler/escalation/claim")
+    public Result<String> escalationClaim(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.claim(workorderId, userId);
+    }
+
+    /**
+     * 记录联系动作留痕(电话/消息/站内),TC-H-01 步骤 3。
+     * POST /api/butler/escalation/log-contact
+     */
+    @PostMapping("/api/butler/escalation/log-contact")
+    public Result<String> escalationLogContact(@RequestBody Map<String, Object> params,
+                                               @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        String contactType = (String) params.get("contactType");
+        String content = (String) params.get("content");
+        return butlerEscalationService.logContact(workorderId, contactType, content, userId);
+    }
+
+    /**
+     * 人工处置结论并闭环(PENDING→PROCESSING→CLOSED 留痕),TC-H-01 步骤 4/5。
+     * POST /api/butler/escalation/close
+     */
+    @PostMapping("/api/butler/escalation/close")
+    public Result<String> escalationClose(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        String resolution = (String) params.get("resolution");
+        return butlerEscalationService.resolve(workorderId, resolution, userId);
+    }
+
+    /**
+     * 转交规划师(SC-H-01 转规划师)。
+     * POST /api/butler/escalation/transfer
+     */
+    @PostMapping("/api/butler/escalation/transfer")
+    public Result<String> escalationTransfer(@RequestBody Map<String, Object> params,
+                                             @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Long teacherId = ParamUtils.getLong(params.get("teacherId"));
+        return butlerEscalationService.transferToTeacher(workorderId, teacherId, userId);
+    }
+
+    /**
+     * 撤回工单(SC-H-04 已撤回状态),仅本家庭工单可撤回。
+     * POST /api/butler/escalation/withdraw
+     */
+    @PostMapping("/api/butler/escalation/withdraw")
+    public Result<String> escalationWithdraw(@RequestBody Map<String, Object> params,
+                                             @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.withdraw(workorderId, userId);
+    }
+
+    // ==================== 一对一陪跑 / 多方协调(能力键 butler.oneOnOne.coach · SC-H-02/H-03) ====================
+
+    /**
+     * 建立家长档案与服务计划(服务周期 / 回访节奏 / 可配 SLA)。
+     * POST /api/butler/one-on-one/profile/create
+     */
+    @PostMapping("/api/butler/one-on-one/profile/create")
+    public Result<ButlerOneOnOneCoachRecord> oneOnOneProfileCreate(@RequestBody Map<String, Object> params,
+                                                                    @RequestAttribute("userId") Long userId) {
+        Long familyId = ParamUtils.getLong(params.get("familyId"));
+        Long butlerUserId = ParamUtils.getLong(params.get("butlerUserId"));
+        String serviceCycle = (String) params.get("serviceCycle");
+        String followUpCadence = (String) params.get("followUpCadence");
+        Integer slaMinutes = params.get("slaMinutes") != null
+                ? Integer.valueOf(params.get("slaMinutes").toString()) : null;
+        java.util.Date expireAt = null;
+        if (params.get("serviceExpireAt") != null) {
+            try {
+                expireAt = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
+                        .parse(params.get("serviceExpireAt").toString());
+            } catch (Exception ignore) {
+                // 到期时间非法时按不设限处理,由 SLA 配置端点后续补齐
+            }
+        }
+        return butlerOneOnOneCoachService.createProfile(
+                familyId, userId, butlerUserId, serviceCycle, followUpCadence, slaMinutes, expireAt);
+    }
+
+    /**
+     * 定期回访留痕(时间 / 内容 / 待办),暂停期不回访。
+     * POST /api/butler/one-on-one/follow-up
+     */
+    @PostMapping("/api/butler/one-on-one/follow-up")
+    public Result<ButlerOneOnOneCoachRecord> oneOnOneFollowUp(@RequestBody Map<String, Object> params,
+                                                               @RequestAttribute("userId") Long userId) {
+        Long recordId = ParamUtils.getLong(params.get("recordId"));
+        Result<Boolean> access = butlerOneOnOneCoachService.canAccessProfile(recordId, userId);
+        if (access.getCode() != 200) {
+            return Result.error(access.getCode(), access.getMessage());
+        }
+        return butlerOneOnOneCoachService.recordFollowUp(recordId,
+                (String) params.get("content"), (String) params.get("todo"), userId);
+    }
+
+    /**
+     * 家长发起 1v1 咨询(即时到管家侧 + SLA 计时,到期给续费入口)。
+     * POST /api/butler/one-on-one/consult/start
+     */
+    @PostMapping("/api/butler/one-on-one/consult/start")
+    public Result<ButlerOneOnOneCoachRecord> oneOnOneConsultStart(@RequestBody Map<String, Object> params,
+                                                                   @RequestAttribute("userId") Long userId) {
+        Long recordId = ParamUtils.getLong(params.get("recordId"));
+        Result<Boolean> access = butlerOneOnOneCoachService.canAccessProfile(recordId, userId);
+        if (access.getCode() != 200) {
+            return Result.error(access.getCode(), access.getMessage());
+        }
+        return butlerOneOnOneCoachService.startConsultation(
+                recordId, (String) params.get("content"), userId);
+    }
+
+    /**
+     * 管家响应并记录,家长端可见答复。
+     * POST /api/butler/one-on-one/consult/respond
+     */
+    @PostMapping("/api/butler/one-on-one/consult/respond")
+    public Result<ButlerOneOnOneCoachRecord> oneOnOneConsultRespond(@RequestBody Map<String, Object> params,
+                                                                     @RequestAttribute("userId") Long userId) {
+        Long recordId = ParamUtils.getLong(params.get("recordId"));
+        Result<Boolean> access = butlerOneOnOneCoachService.canAccessProfile(recordId, userId);
+        if (access.getCode() != 200) {
+            return Result.error(access.getCode(), access.getMessage());
+        }
+        return butlerOneOnOneCoachService.respondConsultation(
+                recordId, (String) params.get("response"), userId);
+    }
+
+    /**
+     * 同源消息列表(复用 teacher.message.push 通道)。
+     * POST /api/butler/one-on-one/messages
+     */
+    @PostMapping("/api/butler/one-on-one/messages")
+    public Result<Map<String, Object>> oneOnOneMessages(@RequestBody Map<String, Object> params,
+                                                         @RequestAttribute("userId") Long userId) {
+        Long familyId = ParamUtils.getLong(params.get("familyId"));
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 20;
+        return butlerOneOnOneCoachService.listMessages(familyId, page, size);
+    }
+
+    // ==================== AI 管家协同闭环(能力键 butler.ai.collaborate · SC-H-06 / TC-H-06) ====================
+
+    /**
+     * 闭环标记:结论/处置/时长完整保存并将工单置为已闭环。
+     * POST /api/butler/collaborate/close
+     */
+    @PostMapping("/api/butler/collaborate/close")
+    public Result<String> collaborateClose(@RequestBody Map<String, Object> params,
+                                           @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Integer durationMinutes = params.get("durationMinutes") != null
+                ? Integer.valueOf(params.get("durationMinutes").toString()) : null;
+        return butlerAiCollaborationService.closeOrder(workorderId,
+                ParamUtils.getString(params.get("conclusion")),
+                ParamUtils.getString(params.get("disposition")), durationMinutes, userId);
+    }
+
+    /**
+     * 提炼可复用结论并提交知识反哺(脱敏 + 幂等去重,入待审队列)。
+     * POST /api/butler/collaborate/feedback
+     */
+    @PostMapping("/api/butler/collaborate/feedback")
+    public Result<com.etotem.cfc.entity.ButlerAiFeedback> collaborateFeedback(
+            @RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId) {
+        return butlerAiCollaborationService.submitFeedback(
+                ParamUtils.getLong(params.get("workorderId")),
+                ParamUtils.getString(params.get("content")), userId);
+    }
+
+    /**
+     * 反馈原家长、关闭升级链路(仅审核通过的反哺可通知)。
+     * POST /api/butler/collaborate/notify
+     */
+    @PostMapping("/api/butler/collaborate/notify")
+    public Result<com.etotem.cfc.dto.ButlerCollaborateNotifyDTO> collaborateNotify(
+            @RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId) {
+        return butlerAiCollaborationService.notifyParent(
+                ParamUtils.getLong(params.get("workorderId")),
+                ParamUtils.getLong(params.get("feedbackId")));
+    }
+}

+ 46 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/butler/FamilyButlerSelectController.java

@@ -0,0 +1,46 @@
+package com.etotem.cfc.controller.butler;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.ButlerService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 家庭端管家自助选择(仅 L2 绑定受限,浏览开放)
+ */
+@RestController
+@RequestMapping("/api/butler")
+public class FamilyButlerSelectController {
+
+    @Resource
+    private ButlerService butlerService;
+
+    @PostMapping("/available-list")
+    public Result<List<Map<String, Object>>> availableList() {
+        return butlerService.getAvailableButlers();
+    }
+
+    @PostMapping("/my-butler")
+    public Result<Map<String, Object>> myButler(@RequestAttribute("userId") Long userId) {
+        return butlerService.getMyButler(userId);
+    }
+
+    @PostMapping("/select")
+    public Result<Map<String, Object>> select(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params) {
+        Object butlerUserIdObj = params.get("butlerUserId");
+        if (butlerUserIdObj == null || butlerUserIdObj.toString().trim().isEmpty()) {
+            return Result.error("缺少 butlerUserId 参数");
+        }
+        Long butlerUserId = Long.valueOf(butlerUserIdObj.toString());
+        return butlerService.selectButler(userId, butlerUserId);
+    }
+}

+ 99 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/cart/CartController.java

@@ -0,0 +1,99 @@
+package com.etotem.cfc.controller.cart;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CartItemDTO;
+import com.etotem.cfc.dto.CartListResultDTO;
+import com.etotem.cfc.pricing.ComboOfferResult;
+import com.etotem.cfc.service.CartService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/cart")
+public class CartController {
+
+    @Resource
+    private CartService cartService;
+
+    @PostMapping("/add")
+    public Result<CartItemDTO> add(@RequestBody Map<String, Object> params,
+                                   @RequestAttribute("userId") Long userId) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        Integer quantity = params.containsKey("quantity") ? Integer.valueOf(params.get("quantity").toString()) : 1;
+        Long skuId = params.containsKey("skuId") ? ParamUtils.getLong(params.get("skuId")) : null;
+
+        CartItemDTO dto = cartService.addToCart(userId, productId, quantity, skuId);
+        if (dto == null) {
+            return Result.error("商品不存在");
+        }
+        return Result.success(dto);
+    }
+
+    @PostMapping("/list")
+    public Result<CartListResultDTO> list(@RequestAttribute("userId") Long userId) {
+        CartListResultDTO list = cartService.getCartList(userId);
+        return Result.success(list);
+    }
+
+    @PostMapping("/update")
+    public Result<Void> update(@RequestBody Map<String, Object> params,
+                               @RequestAttribute("userId") Long userId) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+        Integer quantity = Integer.valueOf(params.get("quantity").toString());
+
+        cartService.updateQuantity(userId, productId, quantity);
+        return Result.success();
+    }
+
+    @PostMapping("/remove")
+    public Result<Void> remove(@RequestBody Map<String, Object> params,
+                               @RequestAttribute("userId") Long userId) {
+        Long productId = ParamUtils.getLong(params.get("productId"));
+
+        cartService.removeItem(userId, productId);
+        return Result.success();
+    }
+
+    @PostMapping("/count")
+    public Result<Integer> count(@RequestAttribute("userId") Long userId) {
+        int count = cartService.getCartCount(userId);
+        return Result.success(count);
+    }
+
+    @PostMapping("/combo-offer")
+    public Result<ComboOfferResult> comboOffer(@RequestBody Map<String, Object> params,
+                                               @RequestAttribute("userId") Long userId) {
+        List<Long> checkedCartItemIds = parseIdList(params.get("checkedCartItemIds"));
+        ComboOfferResult result = cartService.computeComboOffer(userId, checkedCartItemIds);
+        return Result.success(result);
+    }
+
+    @PostMapping("/replace-combo")
+    public Result<Void> replaceCombo(@RequestBody Map<String, Object> params,
+                                     @RequestAttribute("userId") Long userId) {
+        List<Long> checkedCartItemIds = parseIdList(params.get("checkedCartItemIds"));
+        Long comboSkuId = ParamUtils.getLong(params.get("comboSkuId"));
+        return cartService.replaceCartWithCombo(userId, checkedCartItemIds, comboSkuId);
+    }
+
+    private List<Long> parseIdList(Object obj) {
+        List<Long> ids = new ArrayList<>();
+        if (obj instanceof List) {
+            for (Object o : (List<?>) obj) {
+                if (o == null) continue;
+                if (o instanceof Number) ids.add(((Number) o).longValue());
+                else ids.add(Long.valueOf(o.toString()));
+            }
+        }
+        return ids;
+    }
+}

+ 57 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/config/GuideConfigController.java

@@ -0,0 +1,57 @@
+package com.etotem.cfc.controller.config;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.GuideConfigService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 首页引导浮层配置读取(小程序端)。
+ * 配置存于 sys_config 表 key = onboarding_guide_config;
+ * 已读状态按账号存于 user_onboarding_guide。
+ */
+@RestController
+@RequestMapping("/api/guide-config")
+public class GuideConfigController {
+
+    @Resource
+    private GuideConfigService guideConfigService;
+
+    /**
+     * 获取引导配置 + 当前用户是否应展示(需登录)。
+     * 请求体可选:{"position":"home","role":"parent"} / {"position":"child","role":"child"}。
+     */
+    @PostMapping("/current")
+    public Result<Map<String, Object>> current(@RequestAttribute("userId") Long userId,
+                                               @RequestBody(required = false) Map<String, Object> params) {
+        return guideConfigService.current(userId, str(params, "position"), str(params, "role"));
+    }
+
+    /**
+     * 记录引导已完成(需登录)。
+     * 请求体:{"position":"home","role":"parent","version":"1.0","contentHash":"..."}。
+     */
+    @PostMapping("/ack")
+    public Result<String> ack(@RequestAttribute("userId") Long userId,
+                              @RequestBody Map<String, Object> params) {
+        if (params == null) {
+            return Result.error("参数不能为空");
+        }
+        guideConfigService.ack(userId, str(params, "position"), str(params, "role"),
+                str(params, "version"), str(params, "contentHash"));
+        return Result.success("已记录");
+    }
+
+    private static String str(Map<String, Object> params, String key) {
+        if (params == null || params.get(key) == null) {
+            return null;
+        }
+        return String.valueOf(params.get(key));
+    }
+}

+ 29 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/config/PublicConfigController.java

@@ -0,0 +1,29 @@
+package com.etotem.cfc.controller.config;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.SysConfigService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/config/public")
+public class PublicConfigController {
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @PostMapping("/value")
+    public Result<String> getValue(@RequestBody Map<String, String> params) {
+        String key = params.get("key");
+        if (key == null || key.trim().isEmpty()) {
+            return Result.error("key is required");
+        }
+        String value = sysConfigService.getValue(key);
+        return Result.success(value);
+    }
+}

+ 97 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/config/SeedsController.java

@@ -0,0 +1,97 @@
+package com.etotem.cfc.controller.config;
+
+import com.etotem.cfc.common.Result;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+
+/**
+ * 测试数据初始化接口 —— 仅限开发/测试环境使用
+ * 调用方式: POST /api/admin/seeds/init-test-data
+ * 需 role=admin 权限
+ */
+@RestController
+@RequestMapping("/api/admin/seeds")
+public class SeedsController {
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @PostMapping("init-test-data")
+    public Result<String> initTestData(HttpServletRequest request) {
+        // 权限检查:仅 role=admin 可调用
+        String role = (String) request.getAttribute("role");
+        if (role == null || !"admin".equals(role)) {
+            return Result.error(403, "仅限管理员角色调用");
+        }
+
+        try {
+            int inserted = executeSeedData();
+            return Result.success(String.format("测试数据初始化完成:活动 %d 条,文章 %d 条,商品 %d 条",
+                inserted / 3, inserted / 3, inserted / 3));
+        } catch (Exception e) {
+            return Result.error("初始化失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 读取 classpath 下的 seed-test-data.sql 并执行所有 INSERT 语句
+     */
+    private int executeSeedData() {
+        String sqlContent = loadResource("/seed-test-data.sql");
+        // 按 ; 分割 SQL 语句,去除注释和空行
+        List<String> statements = splitStatements(sqlContent);
+
+        int count = 0;
+        for (String stmt : statements) {
+            stmt = stmt.trim();
+            if (stmt.isEmpty() || stmt.startsWith("--") || stmt.startsWith("/*")) {
+                continue;
+            }
+            // 只执行 INSERT 语句(避免执行最后的 SELECT UNION ALL)
+            if (stmt.trim().toUpperCase().startsWith("INSERT")) {
+                jdbcTemplate.update(stmt);
+                count++;
+            }
+        }
+        return count;
+    }
+
+    /**
+     * 从类路径加载资源文件
+     */
+    private String loadResource(String path) {
+        try (InputStream is = getClass().getResourceAsStream(path);
+             java.util.Scanner scanner = new java.util.Scanner(is, StandardCharsets.UTF_8.name())) {
+            scanner.useDelimiter("\\A");
+            return scanner.hasNext() ? scanner.next() : "";
+        } catch (IOException e) {
+            throw new RuntimeException("加载资源文件失败: " + path, e);
+        }
+    }
+
+    /**
+     * 按 ; 分割 SQL 语句(本脚本中字符串内无分号,简单分割即可)
+     */
+    private List<String> splitStatements(String sql) {
+        List<String> statements = new ArrayList<>();
+        String[] rawParts = sql.split(";");
+        for (String part : rawParts) {
+            part = part.trim();
+            if (!part.isEmpty()) {
+                statements.add(part);
+            }
+        }
+        return statements;
+    }
+}

+ 43 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/config/SysConfigController.java

@@ -0,0 +1,43 @@
+package com.etotem.cfc.controller.config;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.CfConfigCache;
+import com.etotem.cfc.dto.SysConfigDTO;
+import com.etotem.cfc.service.SysConfigService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/admin/config")
+public class SysConfigController {
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @PostMapping("/list")
+    public Result<List<SysConfigDTO>> list() {
+        return sysConfigService.listAll();
+    }
+
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody Map<String, Object> params) {
+        String key = (String) params.get("configKey");
+        String value = (String) params.get("configValue");
+        String description = (String) params.get("description");
+        Result<String> result = sysConfigService.update(key, value, description);
+        // 过渡期:sys_config 仍存有少量 CF 参数(已标记迁往 service_config),改动后同步失效 CF 配置缓存
+        CfConfigCache.invalidate();
+        return result;
+    }
+
+    @PostMapping("/all")
+    public Result<Map<String, String>> getAllAsMap() {
+        return sysConfigService.getAllAsMap();
+    }
+}

+ 21 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleCategoryController.java

@@ -0,0 +1,21 @@
+package com.etotem.cfc.controller.content;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ArticleCategory;
+import com.etotem.cfc.service.ArticleCategoryService;
+import org.springframework.web.bind.annotation.*;
+import javax.annotation.Resource;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/articles")
+public class ArticleCategoryController {
+
+    @Resource
+    private ArticleCategoryService articleCategoryService;
+
+    @PostMapping("/categories")
+    public Result<List<ArticleCategory>> getCategories() {
+        return Result.success(articleCategoryService.getActiveCategories());
+    }
+}

+ 329 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleCommentController.java

@@ -0,0 +1,329 @@
+package com.etotem.cfc.controller.content;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CfEarnResult;
+import com.etotem.cfc.entity.ArticleComment;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.ArticleQuizRecord;
+import com.etotem.cfc.entity.ProfileSnapshot;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.ArticleQuizRecordMapper;
+import com.etotem.cfc.mapper.ProfileSnapshotMapper;
+import com.etotem.cfc.service.ArticleCommentService;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.CfPathwayEarnService;
+import com.etotem.cfc.service.EnergyService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.util.ParamUtils;
+import com.etotem.cfc.common.RolesUtil;
+
+@Tag(name = "文章评论", description = "文章评论与AI答题")
+@RestController
+@RequestMapping("/api/articles")
+public class ArticleCommentController {
+
+    private static final Logger log = LoggerFactory.getLogger(ArticleCommentController.class);
+
+    @Resource
+    private ArticleCommentService articleCommentService;
+    @Resource
+    private ArticleMapper articleMapper;
+    @Resource
+    private EnergyService energyService;
+    @Resource
+    private AiGateway aiGateway;
+    @Resource
+    private CfPathwayEarnService cfPathwayEarnService;
+    @Resource
+    private ArticleQuizRecordMapper articleQuizRecordMapper;
+    @Resource
+    private ProfileSnapshotMapper profileSnapshotMapper;
+
+    @PostMapping("/comments/list")
+    public Result<List<Map<String, Object>>> listComments(@RequestBody Map<String, Object> params) {
+        Long articleId = ParamUtils.getLong(params.get("articleId"));
+        return Result.success(articleCommentService.getApprovedComments(articleId));
+    }
+
+    @PostMapping("/comments/create")
+    public Result<ArticleComment> createComment(@RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId) {
+        Long articleId = ParamUtils.getLong(params.get("articleId"));
+        String content = (String) params.get("content");
+        if (content == null || content.trim().isEmpty()) return Result.error("评论内容不能为空");
+        Long parentId = ParamUtils.getLong(params.get("parentId"));
+        Long replyToId = ParamUtils.getLong(params.get("replyToId"));
+        return Result.success(articleCommentService.createComment(userId, articleId, content, parentId, replyToId));
+    }
+
+    @PostMapping("/comments/audit")
+    public Result<String> auditComment(@RequestBody Map<String, Object> params,
+                                        @RequestAttribute("userId") Long userId,
+                                        @RequestAttribute("role") String role,
+                                        @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        if (!"admin".equals(role) && !RolesUtil.hasTeacherRole(role, roles)) {
+            return Result.error("无权限,仅管理员或成长规划师可审核评论");
+        }
+        Long commentId = ParamUtils.getLong(params.get("commentId"));
+        String status = (String) params.get("status");
+        if (!"approved".equals(status) && !"rejected".equals(status)) return Result.error("status必须为approved或rejected");
+        return articleCommentService.auditComment(commentId, userId, status) ? Result.success("审核完成") : Result.error("评论不存在");
+    }
+
+    @PostMapping("/comments/pending")
+    public Result<List<Map<String, Object>>> getPendingComments(@RequestBody Map<String, Object> params,
+                                                                  @RequestAttribute("userId") Long userId,
+                                                                  @RequestAttribute("role") String role) {
+        Long articleId = ParamUtils.getLong(params.get("articleId"));
+        return Result.success(articleCommentService.getPendingCommentsWithDetail(articleId, userId, role));
+    }
+
+    @PostMapping("/comments/my")
+    public Result<List<Map<String, Object>>> getMyComments(@RequestAttribute("userId") Long userId) {
+        return Result.success(articleCommentService.getMyComments(userId));
+    }
+
+    @PostMapping("/complete-read")
+    public Result<Map<String, Object>> completeRead(@RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(params.get("articleId"));
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+        int earned = 5;
+        if (memberId != null) try { energyService.awardEnergy(memberId, "article", articleId, earned, "完成阅读", null); } catch (Exception e) {}
+        Map<String, Object> r = new HashMap<>();
+        r.put("completed", true); r.put("energyEarned", earned); return Result.success(r);
+    }
+
+    @PostMapping("/quiz/generate")
+    public Result<Map<String, Object>> generateQuiz(@RequestBody Map<String, Object> params,
+                                                    @RequestAttribute("userId") Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(params.get("articleId"));
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+        Article article = articleMapper.selectById(articleId);
+        if (article == null || !"published".equals(article.getStatus())) return Result.error("文章不存在");
+
+        String content = article.getContent();
+        if (content != null && content.length() > 2000) content = content.substring(0, 2000);
+
+        // 组装用户画像摘要(从 profile_snapshot 读五维评分)
+        String profileSummary = "";
+        if (memberId != null) {
+            ProfileSnapshot snapshot = profileSnapshotMapper.selectOne(
+                    new LambdaQueryWrapper<ProfileSnapshot>().eq(ProfileSnapshot::getMemberId, memberId));
+            if (snapshot != null && snapshot.getDimensionScores() != null) {
+                profileSummary = snapshot.getDimensionScores();
+            }
+        }
+
+        // 优先走 AiGateway + LangGraph,失败降级硬编码
+        List<Map<String, Object>> questions = null;
+        try {
+            questions = aiGateway.generateArticleQuiz(article.getTitle(), content, profileSummary);
+        } catch (Exception e) {
+            log.warn("AI 出题异常: {}", e.getMessage());
+        }
+
+        if (questions == null || questions.isEmpty()) {
+            questions = new ArrayList<>();
+            questions.add(q("文章的主要内容是什么?", Arrays.asList("A. 提升认知", "B. 健康生活", "C. 亲子关系", "D. 财富管理"), "A", "wisdom"));
+            questions.add(q("文章提到了哪些维度?", Arrays.asList("A. 身", "B. 心", "C. 智", "D. 以上都有"), "D", "wisdom"));
+            questions.add(q("你对这篇文章的收获是什么?", Arrays.asList("A. 学到了新知识", "B. 获得了启发", "C. 需要再想想", "D. 很有共鸣"), "A", "wisdom"));
+        }
+
+        // 落库题目快照,返回 recordId(判分以库内答案为准,防篡改)
+        ArticleQuizRecord record = new ArticleQuizRecord();
+        record.setArticleId(articleId);
+        record.setUserId(userId);
+        record.setMemberId(memberId);
+        record.setQuestions(JSON.toJSONString(questions));
+        record.setAnswers(null);
+        record.setScore(0);
+        record.setTotalQuestions(questions.size());
+        record.setCfEarned(0);
+        record.setEnergyEarned(0);
+        record.setCreatedAt(new Date());
+        record.setUpdatedAt(new Date());
+        articleQuizRecordMapper.insert(record);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("recordId", record.getId());
+        result.put("questions", questions);
+        return Result.success(result);
+    }
+
+    private Map<String, Object> q(String q, List<String> opts, String a, String dimension) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("question", q);
+        m.put("options", opts);
+        m.put("answer", a);
+        m.put("dimension", dimension);
+        return m;
+    }
+
+    @PostMapping("/quiz/submit")
+    public Result<Map<String, Object>> submitQuiz(@RequestBody Map<String, Object> params,
+                                                  @RequestAttribute("userId") Long userId,
+                                                  @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long recordId = ParamUtils.getLong(params.get("recordId"));
+        Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
+
+        ArticleQuizRecord record = articleQuizRecordMapper.selectById(recordId);
+        if (record == null) return Result.error("答题记录不存在");
+        if (record.getAnswers() != null && !record.getAnswers().isEmpty()) {
+            return Result.error("已作答,不可重复提交");
+        }
+
+        int score = 0;
+        int totalQuestions = 0;
+        List<String> answerList = new ArrayList<>();
+        Map<String, int[]> dimStats = new HashMap<>(); // dimension -> [correct, total]
+        try {
+            JSONArray qArr = JSON.parseArray(record.getQuestions());
+            JSONArray aArr = parseAnswers(params.get("answers"));
+            totalQuestions = qArr != null ? qArr.size() : 0;
+            if (aArr != null) {
+                for (int i = 0; i < aArr.size(); i++) {
+                    answerList.add(aArr.getString(i));
+                }
+            }
+            for (int i = 0; i < totalQuestions; i++) {
+                JSONObject q = qArr.getJSONObject(i);
+                String correct = q.getString("answer");
+                String dim = q.getString("dimension");
+                if (dim == null || dim.isEmpty()) dim = "wisdom";
+                String selected = i < answerList.size() ? answerList.get(i) : "";
+                boolean isCorrect = correct != null && selected != null && correct.equalsIgnoreCase(selected.trim());
+                int[] stat = dimStats.computeIfAbsent(dim, k -> new int[2]);
+                stat[1]++;
+                if (isCorrect) { stat[0]++; score++; }
+            }
+        } catch (Exception e) {
+            log.warn("解析答题结果失败: {}", e.getMessage());
+        }
+
+        int energyEarned = score * 5;
+
+        // CF 值发放(F07 统一入口:数量 = 规则公式 score + (全对 ? 3 : 0),日限 5 次 N9;
+        // 幂等 ref_id = 答题记录ID,同一记录只发一次)
+        int cfEarned = 0;
+        if (memberId != null) {
+            try {
+                CfEarnResult earnResult = cfPathwayEarnService.earnArticleQuizCf(
+                        memberId, record.getId(), score, totalQuestions);
+                if (Boolean.TRUE.equals(earnResult.getEarned()) && earnResult.getAmount() != null) {
+                    cfEarned = earnResult.getAmount();
+                }
+            } catch (Exception e) {
+                log.warn("CF值发放失败: {}", e.getMessage());
+            }
+        }
+
+        record.setAnswers(JSON.toJSONString(answerList));
+        record.setScore(score);
+        record.setTotalQuestions(totalQuestions);
+        record.setCfEarned(cfEarned);
+        record.setEnergyEarned(energyEarned);
+        record.setUpdatedAt(new Date());
+        articleQuizRecordMapper.updateById(record);
+
+        if (memberId != null && energyEarned > 0) {
+            try { energyService.awardEnergy(memberId, "article_quiz", record.getArticleId(), energyEarned, "答题奖励", null); }
+            catch (Exception e) { log.warn("能量发放失败: {}", e.getMessage()); }
+        }
+
+        updateQuizSummary(memberId, score, totalQuestions, dimStats);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("correctCount", score);
+        result.put("totalQuestions", totalQuestions);
+        result.put("cfEarned", cfEarned);
+        result.put("energyEarned", energyEarned);
+        return Result.success(result);
+    }
+
+    /**
+     * 兼容前端两种传参:answers 为 JSON 数组字符串("[\"A\",\"B\"]")或直接为数组(["A","B"])。
+     * 后端 @RequestBody 反序列化时数组会变成 List,直接 String.valueOf(list) 得到 "[A, B]" 无法被 fastjson 解析,
+     * 故必须区分处理。
+     */
+    private JSONArray parseAnswers(Object answers) {
+        if (answers == null) return null;
+        if (answers instanceof String) {
+            String s = ((String) answers).trim();
+            return s.isEmpty() ? null : JSON.parseArray(s);
+        }
+        if (answers instanceof List) {
+            return JSON.parseArray(JSON.toJSONString(answers));
+        }
+        if (answers instanceof JSONArray) {
+            return (JSONArray) answers;
+        }
+        return null;
+    }
+
+    private void updateQuizSummary(Long memberId, int score, int totalQuestions, Map<String, int[]> dimStats) {
+        if (memberId == null) return;
+        try {
+            ProfileSnapshot snapshot = profileSnapshotMapper.selectOne(
+                    new LambdaQueryWrapper<ProfileSnapshot>().eq(ProfileSnapshot::getMemberId, memberId));
+
+            JSONObject summary = new JSONObject();
+            if (snapshot != null && snapshot.getQuizSummary() != null && !snapshot.getQuizSummary().isEmpty()) {
+                summary = JSON.parseObject(snapshot.getQuizSummary());
+            }
+
+            int prevCorrect = summary.getIntValue("correct_count");
+            int prevTotal = summary.getIntValue("total_count");
+            int newCorrect = prevCorrect + score;
+            int newTotal = prevTotal + totalQuestions;
+            summary.put("quiz_count", summary.getIntValue("quiz_count") + 1);
+            summary.put("correct_count", newCorrect);
+            summary.put("total_count", newTotal);
+            summary.put("correct_rate", newTotal > 0 ? (double) newCorrect / newTotal : 0.0);
+            summary.put("last_quiz_at", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+
+            JSONObject byDim = summary.getJSONObject("by_dimension");
+            if (byDim == null) byDim = new JSONObject();
+            for (Map.Entry<String, int[]> entry : dimStats.entrySet()) {
+                String dim = entry.getKey();
+                int correct = entry.getValue()[0];
+                int total = entry.getValue()[1];
+                JSONObject dimStat = byDim.getJSONObject(dim);
+                if (dimStat == null) dimStat = new JSONObject();
+                int dimCorrect = dimStat.getIntValue("correct_count") + correct;
+                int dimTotal = dimStat.getIntValue("total_count") + total;
+                dimStat.put("correct_count", dimCorrect);
+                dimStat.put("total_count", dimTotal);
+                dimStat.put("correct_rate", dimTotal > 0 ? (double) dimCorrect / dimTotal : 0.0);
+                byDim.put(dim, dimStat);
+            }
+            summary.put("by_dimension", byDim);
+
+            if (snapshot == null) {
+                snapshot = new ProfileSnapshot();
+                snapshot.setMemberId(memberId);
+                snapshot.setQuizSummary(summary.toJSONString());
+                snapshot.setUpdatedAt(new Date());
+                profileSnapshotMapper.insert(snapshot);
+            } else {
+                snapshot.setQuizSummary(summary.toJSONString());
+                snapshot.setUpdatedAt(new Date());
+                profileSnapshotMapper.updateById(snapshot);
+            }
+        } catch (Exception e) {
+            log.warn("更新认知雷达失败: {}", e.getMessage());
+        }
+    }
+}

+ 355 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/content/ArticleController.java

@@ -0,0 +1,355 @@
+package com.etotem.cfc.controller.content;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ReadingStatsDTO;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.ArticleCategory;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ArticleCategoryService;
+import com.etotem.cfc.service.ArticleAudioService;
+import com.etotem.cfc.service.ArticleService;
+import com.etotem.cfc.service.ProductRecommendationService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import org.springframework.web.bind.annotation.*;
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "文章内容", description = "文章列表/阅读统计/每日贴士")
+@RestController
+@RequestMapping({"/api/articles", "/api/article"})
+public class ArticleController {
+
+    @Resource
+    private ArticleService articleService;
+
+    @Resource
+    private ArticleCategoryService articleCategoryService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ArticleAudioService articleAudioService;
+
+    @Resource
+    private ProductRecommendationService productRecommendationService;
+
+    @PostMapping("/related-products")
+    public Result<List<Map<String, Object>>> relatedProducts(@RequestBody Map<String, Object> body,
+                                                             @RequestAttribute(value = "userId", required = false) Long userId,
+                                                             @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("articleId"));
+        if (articleId == null) {
+            return Result.error("articleId不能为空");
+        }
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 6;
+        int page = body.get("page") != null ? Math.max(1, Integer.parseInt(body.get("page").toString())) : 1;
+
+        Long familyId = null;
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+            }
+        }
+
+        // 全量候选 → 按页切片(与 /api/recommend/dimension-products 分页语义一致,保证翻页不重复、不遗漏)
+        int fetchLimit = page * size;
+        List<Map<String, Object>> all = productRecommendationService.getArticleRelatedProductsFull(articleId, userId, familyId, memberId, fetchLimit);
+        int from = (page - 1) * size;
+        int to = Math.min(from + size, all.size());
+        List<Map<String, Object>> result = from >= all.size() ? Collections.emptyList() : all.subList(from, to);
+        return Result.success(result);
+    }
+
+    /**
+     * 相关文章:按标签关联(共享标签数优先,发布先后次之),默认 3 篇/页;无匹配返回空数组。
+     * 支持分页:page 从 1 开始,每页 size 篇。
+     */
+    @PostMapping("/related")
+    public Result<List<Article>> related(@RequestBody Map<String, Object> body,
+                                         @RequestAttribute(value = "userId", required = false) Long userId,
+                                         @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("articleId"));
+        if (articleId == null) {
+            return Result.error("articleId不能为空");
+        }
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 3;
+        if (size < 1) size = 1;
+        int page = body.get("page") != null ? Math.max(1, Integer.parseInt(body.get("page").toString())) : 1;
+
+        Long familyId = null;
+        String vendorType = null;
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+                vendorType = user.getVendorType();
+            }
+        }
+
+        List<Article> list = articleService.getRelatedArticles(articleId, size, page, userId, familyId, vendorType);
+        return Result.success(list);
+    }
+
+    /**
+     * 商品详情页相关文章:按商品标签匹配文章(共享标签数优先),支持分页;无匹配返回空数组。
+     * 游客可访问(白名单),未登录无家庭可见性加成。
+     */
+    @PostMapping("/related-by-product")
+    public Result<List<Article>> relatedByProduct(@RequestBody Map<String, Object> body,
+                                                   @RequestAttribute(value = "userId", required = false) Long userId,
+                                                   @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long productId = ParamUtils.getLong(body.get("productId"));
+        if (productId == null) {
+            return Result.error("productId不能为空");
+        }
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 3;
+        if (size < 1) size = 1;
+        int page = body.get("page") != null ? Math.max(1, Integer.parseInt(body.get("page").toString())) : 1;
+
+        Long familyId = null;
+        String vendorType = null;
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+                vendorType = user.getVendorType();
+            }
+        }
+
+        List<Article> list = articleService.getRelatedArticlesByProduct(productId, size, page, userId, familyId, vendorType);
+        return Result.success(list);
+    }
+
+    @PostMapping("/list")
+    public Result<Page<Article>> list(@RequestBody Map<String, Object> body,
+                                       @RequestAttribute(value = "userId", required = false) Long userId,
+                                       @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long categoryId = ParamUtils.getLong(body.get("categoryId"));
+        String keyword = (String) body.get("keyword");
+        String dimensionCode = body.get("dimensionCode") != null ? body.get("dimensionCode").toString() : null;
+        String tag = body.get("tag") != null ? body.get("tag").toString() : null;
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        int page = body.get("page") != null ? Integer.parseInt(body.get("page").toString()) : 1;
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 10;
+
+        Long familyId = null;
+        String vendorType = null;
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+                vendorType = user.getVendorType();
+            }
+        }
+
+        Page<Article> result = articleService.getPublicList(categoryId, keyword, dimensionCode, tag, page, size,
+                userId, familyId, vendorType, memberId);
+        return Result.success(result);
+    }
+
+    /**
+     * 知识中心动态标签列表:聚合已发布文章的标签,按出现频次降序返回 Top 20。
+     */
+    @PostMapping("/tags")
+    public Result<List<String>> tags() {
+        return Result.success(articleService.listTopTags(20));
+    }
+
+    @PostMapping("/detail")
+    public Result<Article> detail(@RequestBody Map<String, Object> body,
+                                   @RequestAttribute(value = "userId", required = false) Long userId) {
+        Long id = ParamUtils.getLong(body.get("id"));
+
+        Long familyId = null;
+        String vendorType = null;
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+                vendorType = user.getVendorType();
+            }
+        }
+
+        Article article = articleService.getDetail(id, userId, familyId, vendorType);
+        if (article == null) {
+            return Result.error(403, "无权访问该文章");
+        }
+        articleService.incrementViewCount(id);
+        return Result.success(article);
+    }
+
+    @PostMapping("/featured")
+    public Result<List<Article>> featured(@RequestBody Map<String, Object> body,
+                                            @RequestAttribute(value = "userId", required = false) Long userId,
+                                            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 5;
+        String dimensionCode = body.get("dimensionCode") != null ? body.get("dimensionCode").toString() : null;
+
+        Long familyId = null;
+        String vendorType = null;
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                familyId = user.getFamilyId();
+                vendorType = user.getVendorType();
+            }
+        }
+
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        List<Article> list = articleService.getFeatured(size, dimensionCode, userId, familyId, vendorType, memberId);
+        return Result.success(list);
+    }
+
+@PostMapping("/record-read")
+    public Result<Map<String, Object>> recordRead(@RequestBody Map<String, Object> body,
+                                                @RequestAttribute(value = "userId", required = false) Long userId,
+                                                @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("id"));
+        int durationSeconds = body.get("durationSeconds") != null
+                ? Integer.parseInt(body.get("durationSeconds").toString())
+                : 0;
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        Map<String, Object> result = articleService.recordRead(articleId, userId, memberId, durationSeconds);
+        return Result.success(result);
+    }
+    
+    @PostMapping("/audio")
+    public Result<Map<String, Object>> getArticleAudio(@RequestBody Map<String, Object> body,
+                                                    @RequestAttribute(value = "userId", required = false) Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("articleId"));
+        if (articleId == null) {
+            return Result.error("文章ID不能为空");
+        }
+        try {
+            Map<String, Object> result = articleAudioService.getOrGenerateAudio(articleId);
+            return Result.success(result);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/report-reading-time")
+    public Result<Void> reportReadingTime(@RequestBody Map<String, Object> body,
+                                           @RequestAttribute(value = "userId", required = false) Long userId,
+                                           @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("articleId"));
+        int durationSeconds = body.get("durationSeconds") != null
+                ? Integer.parseInt(body.get("durationSeconds").toString()) : 0;
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+
+        articleService.reportReadingTime(articleId, userId, memberId, durationSeconds);
+        return Result.success(null);
+    }
+
+    @PostMapping("/reading-stats")
+    public Result<ReadingStatsDTO> readingStats(@RequestBody Map<String, Object> body,
+                                                @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        ReadingStatsDTO stats = articleService.getReadingStats(memberId);
+        return Result.success(stats);
+    }
+
+    @PostMapping("/daily-tip")
+    public Result<Map<String, Object>> dailyTip() {
+        Map<String, Object> tip = articleService.getDailyTip();
+        return Result.success(tip);
+    }
+
+    @PostMapping("/ai-questions")
+    public Result<Map<String, Object>> aiQuestions(@RequestBody Map<String, Object> body,
+                                                    @RequestAttribute("userId") Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long articleId = ParamUtils.getLong(body.get("articleId"));
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        try {
+            Map<String, Object> data = articleService.getAiQuestions(articleId, userId, memberId);
+            return Result.success(data);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/submit-answers")
+    public Result<Map<String, Object>> submitAnswers(@RequestBody Map<String, Object> body,
+                                                      @RequestAttribute("userId") Long userId,
+                                                      @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long recordId = ParamUtils.getLong(body.get("recordId"));
+        String answersJson = (String) body.get("answers");
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        try {
+            Map<String, Object> data = articleService.submitAnswers(recordId, answersJson, userId, memberId);
+            return Result.success(data);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @PostMapping("/publish")
+    public Result<Map<String, Object>> publish(@RequestBody Map<String, Object> body,
+                                                @RequestAttribute("userId") Long userId,
+                                                @RequestAttribute("role") String role) {
+        String title = (String) body.get("title");
+        String content = (String) body.get("content");
+        String coverImage = (String) body.get("coverImage");
+        String visibility = (String) body.get("visibility");
+        String relatedDimensions = (String) body.get("relatedDimensions");
+
+        if (title == null || title.trim().isEmpty()) {
+            return Result.error("标题不能为空");
+        }
+        if (content == null || content.trim().isEmpty()) {
+            return Result.error("正文不能为空");
+        }
+
+        Article article = articleService.publishByUser(title, content, coverImage, visibility, relatedDimensions, userId, role);
+        Map<String, Object> result = new HashMap<>();
+        result.put("id", article.getId());
+        result.put("status", article.getStatus());
+        result.put("auditStatus", article.getAuditStatus());
+        return Result.success(result);
+    }
+
+    @PostMapping("/my-posts")
+    public Result<Page<Article>> myPosts(@RequestBody Map<String, Object> body,
+                                           @RequestAttribute("userId") Long userId) {
+        int page = body.get("page") != null ? Integer.parseInt(body.get("page").toString()) : 1;
+        int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 20;
+        return Result.success(articleService.getMyPosts(userId, page, size));
+    }
+
+    @Operation(summary = "增量查询文章(RAG)")
+    @PostMapping("/updated-since")
+    public Result<List<Article>> updatedSince(@RequestBody Map<String, Object> body) {
+        String since = (String) body.get("since");
+        String status = (String) body.get("status");
+        if (since == null || since.trim().isEmpty()) {
+            return Result.error("since 参数不能为空");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+        Date sinceDate;
+        try {
+            sinceDate = sdf.parse(since);
+        } catch (Exception e) {
+            return Result.error("since 格式无效,请使用 ISO 8601 格式");
+        }
+        return Result.success(articleService.getUpdatedSince(sinceDate, status));
+    }
+}

+ 46 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/content/ContentRelatedController.java

@@ -0,0 +1,46 @@
+package com.etotem.cfc.controller.content;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.ContentRelatedService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 内容关联推荐:活动/文章/商品任意一类为源,按共享标签一次返回「相关文章 / 相关活动 / 相关商品」三组数据。
+ * 游客可访问(白名单),未登录无家庭可见性/个性化权重加成。
+ */
+@Tag(name = "内容关联", description = "按标签跨类型匹配相关文章/活动/商品")
+@RestController
+@RequestMapping("/api/content")
+public class ContentRelatedController {
+
+    @Resource
+    private ContentRelatedService contentRelatedService;
+
+    @Operation(summary = "内容关联推荐:按源内容标签匹配相关文章/活动/商品(三源一次返回,支持分页)")
+    @PostMapping("/related-items")
+    public Result<Map<String, Object>> relatedItems(@RequestBody Map<String, Object> params,
+                                                    @RequestAttribute(value = "userId", required = false) Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        String sourceType = (String) params.get("sourceType");
+        Long sourceId = ParamUtils.getLong(params.get("sourceId"));
+        if (sourceType == null || sourceType.trim().isEmpty() || sourceId == null) {
+            return Result.error("sourceType/sourceId不能为空");
+        }
+        int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 4;
+        if (size < 1) size = 4;
+        if (size > 20) size = 20;
+        int page = params.get("page") != null ? Math.max(1, Integer.parseInt(params.get("page").toString())) : 1;
+
+        return Result.success(contentRelatedService.getRelated(sourceType.trim().toLowerCase(), sourceId, size, page, userId, currentMemberId));
+    }
+}

+ 86 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/content/ContentSectionController.java

@@ -0,0 +1,86 @@
+package com.etotem.cfc.controller.content;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ContentSection;
+import com.etotem.cfc.service.ContentSectionService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/content-sections")
+public class ContentSectionController {
+
+    @Resource
+    private ContentSectionService contentSectionService;
+
+    /**
+     * 获取指定页面对指定角色可见的区块
+     * role 为可选参数,不传或为空时只返回 public 区块(allowedRoles 包含 "anonymous")
+     */
+    @PostMapping("/visible")
+    public Result<List<ContentSection>> getVisibleSections(@RequestBody Map<String, Object> body) {
+        String pageKey = (String) body.get("pageKey");
+        if (pageKey == null || pageKey.trim().isEmpty()) {
+            return Result.error("pageKey 不能为空");
+        }
+        String role = (String) body.get("role");
+        List<ContentSection> sections = contentSectionService.getVisibleSections(pageKey.trim(), role);
+        return Result.success(sections);
+    }
+
+    /**
+     * 获取所有内容区块配置(管理端)
+     */
+    @PostMapping("/list")
+    public Result<List<ContentSection>> listAll() {
+        return Result.success(contentSectionService.listAll());
+    }
+
+    /**
+     * 获取单个区块详情
+     */
+    @PostMapping("/detail")
+    public Result<ContentSection> getDetail(@RequestBody Map<String, Object> body) {
+        Long id = ParamUtils.getLong(body.get("id"));
+        ContentSection section = contentSectionService.getById(id);
+        if (section == null) {
+            return Result.error("区块不存在");
+        }
+        return Result.success(section);
+    }
+
+    /**
+     * 创建区块(管理端)
+     */
+    @PostMapping("/create")
+    public Result<String> create(@RequestBody ContentSection section) {
+        contentSectionService.create(section);
+        return Result.success("创建成功");
+    }
+
+    /**
+     * 更新区块(管理端)
+     */
+    @PostMapping("/update")
+    public Result<String> update(@RequestBody ContentSection section) {
+        contentSectionService.update(section);
+        return Result.success("更新成功");
+    }
+
+    /**
+     * 删除区块(管理端)
+     */
+    @PostMapping("/delete")
+    public Result<String> delete(@RequestBody Map<String, Object> body) {
+        Long id = ParamUtils.getLong(body.get("id"));
+        contentSectionService.delete(id);
+        return Result.success("删除成功");
+    }
+}

+ 179 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/dan/DanAssessmentExecutionController.java

@@ -0,0 +1,179 @@
+package com.etotem.cfc.controller.dan;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.*;
+import com.etotem.cfc.entity.DanAssessmentExecution;
+import com.etotem.cfc.entity.ServiceRating;
+import com.etotem.cfc.service.DanAssessmentExecutionService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+/**
+ * DAN 测评执行服务控制器
+ * 提供服务完成、用户确认、评价等核心流程 API
+ */
+@RestController
+@RequestMapping("/api/dan-execution")
+public class DanAssessmentExecutionController {
+
+    private static final Logger log = LoggerFactory.getLogger(DanAssessmentExecutionController.class);
+
+    @Resource
+    private DanAssessmentExecutionService executionService;
+
+    /**
+     * 规划师/评估师完成服务
+     */
+    @PostMapping("/complete")
+    public Result<Void> complete(@RequestBody CompleteRequest req, @RequestAttribute("userId") Long userId) {
+        executionService.completeExecution(req.getExecutionId(), "planner", req.getNotes());
+        return Result.success();
+    }
+
+    /**
+     * 用户确认服务完成
+     */
+    @PostMapping("/confirm")
+    public Result<Void> confirm(@RequestBody ConfirmRequest req, @RequestAttribute("userId") Long userId) {
+        executionService.confirmExecution(req.getExecutionId(), 1);
+        return Result.success();
+    }
+
+    /**
+     * 用户评价服务
+     */
+    @PostMapping("/rate")
+    public Result<ServiceRatingDTO> rate(@RequestBody ServiceRateRequest req, @RequestAttribute("userId") Long userId) {
+        req.setUserId(userId);
+        ServiceRating rating = executionService.rateService(req);
+        return Result.success(new ServiceRatingDTO(rating));
+    }
+
+    /**
+     * 获取执行详情(含结算信息)
+     */
+    @PostMapping("/detail")
+    public Result<ExecutionDetailResponse> detail(@RequestBody DetailRequest req) {
+        ExecutionDetailResponse resp = executionService.getExecutionDetail(req.getExecutionId());
+        return Result.success(resp);
+    }
+
+    /**
+     * 用户执行记录列表
+     */
+    @PostMapping("/my-list")
+    public Result<List<DanAssessmentExecution>> myList(@RequestBody MyExecutionFilter filter, @RequestAttribute("userId") Long userId) {
+        List<DanAssessmentExecution> executions = executionService.getByFamilyId(filter.getFamilyId());
+        return Result.success(executions);
+    }
+
+    /**
+     * 规划师待执行任务列表
+     */
+    @PostMapping("/guide/my-tasks")
+    public Result<List<DanAssessmentExecution>> guideMyTasks(@RequestBody GuideTasksRequest req) {
+        List<DanAssessmentExecution> tasks = executionService.getByPlannerId(req.getPlannerId());
+        return Result.success(tasks);
+    }
+
+    /**
+     * 按订单ID查询执行记录
+     */
+    @PostMapping("/by-order")
+    public Result<DanAssessmentExecution> getByOrder(@RequestBody OrderRequest req) {
+        DanAssessmentExecution exec = executionService.getByOrderId(req.getOrderId());
+        return Result.success(exec);
+    }
+}
+
+// ==================== DTO 定义 ====================
+
+class CompleteRequest {
+    private Long executionId;
+    private String notes;
+    public Long getExecutionId() { return executionId; }
+    public void setExecutionId(Long executionId) { this.executionId = executionId; }
+    public String getNotes() { return notes; }
+    public void setNotes(String notes) { this.notes = notes; }
+}
+
+class ConfirmRequest {
+    private Long executionId;
+    public Long getExecutionId() { return executionId; }
+    public void setExecutionId(Long executionId) { this.executionId = executionId; }
+}
+
+class MyExecutionFilter {
+    private Long familyId;
+    public Long getFamilyId() { return familyId; }
+    public void setFamilyId(Long familyId) { this.familyId = familyId; }
+}
+
+class DetailRequest {
+    private Long executionId;
+    public Long getExecutionId() { return executionId; }
+    public void setExecutionId(Long executionId) { this.executionId = executionId; }
+}
+
+class GuideTasksRequest {
+    private Long plannerId;
+    public Long getPlannerId() { return plannerId; }
+    public void setPlannerId(Long plannerId) { this.plannerId = plannerId; }
+}
+
+class OrderRequest {
+    private Long orderId;
+    public Long getOrderId() { return orderId; }
+    public void setOrderId(Long orderId) { this.orderId = orderId; }
+}
+
+class ServiceRatingDTO {
+    private Long id;
+    private Long executionId;
+    private Long userId;
+    private Long assessorId;
+    private Integer assessorRating;
+    private String assessorComment;
+    private Long plannerId;
+    private Integer plannerRating;
+    private String plannerComment;
+    private String createdAt;
+
+    public ServiceRatingDTO(com.etotem.cfc.entity.ServiceRating rating) {
+        this.id = rating.getId();
+        this.executionId = rating.getExecutionId();
+        this.userId = rating.getUserId();
+        this.assessorId = rating.getAssessorId();
+        this.assessorRating = rating.getAssessorRating();
+        this.assessorComment = rating.getAssessorComment();
+        this.plannerId = rating.getPlannerId();
+        this.plannerRating = rating.getPlannerRating();
+        this.plannerComment = rating.getPlannerComment();
+        this.createdAt = rating.getCreatedAt().toString();
+    }
+
+    public Long getId() { return id; }
+    public void setId(Long id) { this.id = id; }
+    public Long getExecutionId() { return executionId; }
+    public void setExecutionId(Long executionId) { this.executionId = executionId; }
+    public Long getUserId() { return userId; }
+    public void setUserId(Long userId) { this.userId = userId; }
+    public Long getAssessorId() { return assessorId; }
+    public void setAssessorId(Long assessorId) { this.assessorId = assessorId; }
+    public Integer getAssessorRating() { return assessorRating; }
+    public void setAssessorRating(Integer assessorRating) { this.assessorRating = assessorRating; }
+    public String getAssessorComment() { return assessorComment; }
+    public void setAssessorComment(String assessorComment) { this.assessorComment = assessorComment; }
+    public Long getPlannerId() { return plannerId; }
+    public void setPlannerId(Long plannerId) { this.plannerId = plannerId; }
+    public Integer getPlannerRating() { return plannerRating; }
+    public void setPlannerRating(Integer plannerRating) { this.plannerRating = plannerRating; }
+    public String getPlannerComment() { return plannerComment; }
+    public void setPlannerComment(String plannerComment) { this.plannerComment = plannerComment; }
+    public String getCreatedAt() { return createdAt; }
+    public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
+}

+ 58 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietIngredientController.java

@@ -0,0 +1,58 @@
+package com.etotem.cfc.controller.diet;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.DietIngredientService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/diet/ingredients")
+public class DietIngredientController {
+
+    @Resource
+    private DietIngredientService dietIngredientService;
+
+    @PostMapping("/suggest")
+    public Result<Map> suggestIngredients(@RequestAttribute("familyId") Long familyId) {
+        return Result.success(dietIngredientService.suggestIngredients(familyId));
+    }
+
+    @PostMapping("/recommend")
+    public Result<Map> recommendIngredients(@RequestAttribute("familyId") Long familyId) {
+        return Result.success(dietIngredientService.refreshIngredients(familyId));
+    }
+
+    @PostMapping("/add")
+    public Result<Map> addIngredient(
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> request) {
+        Long foodId = ParamUtils.getLong(request.get("food_id"));
+        String name = request.get("name").toString();
+        return Result.success(dietIngredientService.addIngredient(familyId, foodId, name));
+    }
+
+    @PostMapping("/remove")
+    public Result<Map> removeIngredient(
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> request) {
+        Long foodId = ParamUtils.getLong(request.get("food_id"));
+        return Result.success(dietIngredientService.removeIngredient(familyId, foodId));
+    }
+
+    @PostMapping("/confirm")
+    public Result<Map> confirmIngredients(
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> request) {
+        return Result.success(dietIngredientService.confirmIngredients(familyId, request));
+    }
+
+    @PostMapping("/search")
+    public Result<Map> searchFoods(@RequestBody(required = false) Map<String, Object> request) {
+        String keyword = request != null && request.get("keyword") != null
+                ? request.get("keyword").toString() : "";
+        return Result.success(dietIngredientService.searchFoods(keyword));
+    }
+}

+ 33 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietMealConfigController.java

@@ -0,0 +1,33 @@
+package com.etotem.cfc.controller.diet;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.DietMealConfigService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/diet/meals")
+public class DietMealConfigController {
+
+    @Resource
+    private DietMealConfigService dietMealConfigService;
+
+    @PostMapping("/config")
+    public Result<Map> getConfig(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody Map<String, Object> request) {
+        String dateType = request.get("date_type") != null ? request.get("date_type").toString() : null;
+        String mealType = request.get("meal_type") != null ? request.get("meal_type").toString() : null;
+        return Result.success(dietMealConfigService.getConfig(familyId, dateType, mealType));
+    }
+
+    @PostMapping("/config/save")
+    public Result<Void> saveConfig(
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> request) {
+        dietMealConfigService.saveConfig(familyId, request);
+        return Result.success(null);
+    }
+}

+ 79 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietPreferencesController.java

@@ -0,0 +1,79 @@
+package com.etotem.cfc.controller.diet;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.DietPreferencesDTO;
+import com.etotem.cfc.service.DietPreferencesService;
+import com.etotem.cfc.service.FamilyMemberService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/diet/preferences")
+public class DietPreferencesController {
+
+    @Resource
+    private DietPreferencesService dietPreferencesService;
+
+    @Resource
+    private FamilyMemberService familyMemberService;
+
+    @PostMapping("/current-member")
+    public Result<DietPreferencesDTO> getCurrentMemberPreferences(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestAttribute(value = "familyMemberId", required = false) Long currentMemberId,
+            @RequestBody(required = false) Map<String, Object> params) {
+        // 显式 memberId(须同家庭)优先,未传时回退登录账号本人
+        Long memberId = resolveMemberId(params != null ? params.get("memberId") : null, familyId, currentMemberId);
+        if (memberId == null) {
+            return Result.success(null);
+        }
+        DietPreferencesDTO dto = dietPreferencesService.getCurrentMemberPreferences(memberId);
+        // 成员级查不到 → 回退 familyMemberId 上下文成员偏好
+        if (dto == null && currentMemberId != null && !memberId.equals(currentMemberId)) {
+            dto = dietPreferencesService.getCurrentMemberPreferences(currentMemberId);
+        }
+        return Result.success(dto);
+    }
+
+    @PostMapping("/save")
+    public Result<Void> savePreferences(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestAttribute(value = "familyMemberId", required = false) Long currentMemberId,
+            @RequestBody DietPreferencesDTO dto) {
+        // 显式 familyMemberId(须同家庭)优先,未传时回退登录账号本人
+        Long memberId = resolveMemberId(dto.getFamilyMemberId(), familyId, currentMemberId);
+        if (memberId == null) {
+            return Result.error("未指定成员");
+        }
+        dto.setFamilyMemberId(memberId);
+        dietPreferencesService.savePreferences(memberId, dto);
+        return Result.success(null);
+    }
+
+    /**
+     * 解析目标成员:显式 memberId(须与登录用户同家庭)优先,否则回退登录成员。
+     */
+    private Long resolveMemberId(Object requestedRaw, Long familyId, Long currentMemberId) {
+        Long requested = toLong(requestedRaw);
+        if (requested != null && familyMemberService.isMemberInFamily(familyId, requested)) {
+            return requested;
+        }
+        return currentMemberId;
+    }
+
+    private Long toLong(Object raw) {
+        if (raw == null) {
+            return null;
+        }
+        if (raw instanceof Number) {
+            return ((Number) raw).longValue();
+        }
+        try {
+            return Long.valueOf(String.valueOf(raw).trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 108 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecommendationController.java

@@ -0,0 +1,108 @@
+package com.etotem.cfc.controller.diet;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.DietRecommendationService;
+import com.etotem.cfc.util.ParamUtils;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/diet/recommendation")
+public class DietRecommendationController {
+
+    @Resource
+    private DietRecommendationService dietRecommendationService;
+
+    /**
+     * 今日食谱(K1):可选 view_key 参与视角隔离;不传则完全走原查询(老客户端 / 存量 NULL 行兼容)。
+     * date 必填校验 Result.error("date不能为空") 原样保留。
+     */
+    @PostMapping("/today")
+    public Result<Map> getTodayRecommendation(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody(required = false) Map<String, Object> request) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        Object dateObj = (request != null) ? request.get("date") : null;
+        String date = (dateObj == null) ? null : String.valueOf(dateObj);
+        if (date == null || date.isEmpty()) {
+            return Result.error("date不能为空");
+        }
+        Object viewKeyObj = (request != null) ? request.get("view_key") : null;
+        String viewKey = (viewKeyObj == null) ? null : String.valueOf(viewKeyObj);
+        return Result.success(dietRecommendationService.getTodayRecommendation(familyId, date, viewKey));
+    }
+
+    /**
+     * 菜谱分享只读查询:按 id 获取菜谱详情(跨家庭可看,无需 familyId)。
+     * 仅需登录用户;数据只含菜谱/营养信息,无个人信息。
+     */
+    @PostMapping("/share")
+    public Result<Map> getShareDetail(
+            @RequestAttribute(value = "userId", required = false) Long userId,
+            @RequestBody(required = false) Map<String, Object> request) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long id = (request != null) ? ParamUtils.getLong(request.get("id")) : null;
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        return Result.success(dietRecommendationService.getShareDetail(id));
+    }
+
+    /**
+     * 生成食谱(K3):改 Map&lt;String,Object&gt; 接住 participant_member_ids 的 JSON 字符串与原生数组双形态,
+     * 以及可选 view_key;date / meal_type / selected_foods 由 Service 侧 asString 兜底。
+     */
+    @PostMapping("/generate")
+    public Result<Map> generateRecommendation(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody Map<String, Object> request) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        // [teacher.nutrition.plan / SC-T-26] 营养目标非法(负/超上限)→ 400 拒绝;
+        // 单测直调 Controller 不经 GlobalExceptionHandler,故在此捕获(与全局 400 语义一致)。
+        try {
+            return Result.success(dietRecommendationService.generateRecommendation(familyId, request));
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+    }
+
+    @PostMapping("/update")
+    public Result<Void> updateRecommendation(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody Map<String, Object> request) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        dietRecommendationService.updateRecommendation(familyId, request);
+        return Result.success(null);
+    }
+
+    @PostMapping("/regenerate")
+    public Result<Map> regenerateRecommendation(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody Map<String, Object> request) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        return Result.success(dietRecommendationService.regenerateRecommendation(familyId, request));
+    }
+
+    @PostMapping("/complete")
+    public Result<Void> completeRecommendation(
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
+            @RequestBody Map<String, Object> request) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        dietRecommendationService.completeRecommendation(familyId, request);
+        return Result.success(null);
+    }
+}

+ 62 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecordController.java

@@ -0,0 +1,62 @@
+package com.etotem.cfc.controller.diet;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.QuotaConsumeResult;
+import com.etotem.cfc.service.BasicQuotaService;
+import com.etotem.cfc.service.DietRecordService;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/diet/record")
+public class DietRecordController {
+
+    @Resource
+    private DietRecordService dietRecordService;
+
+    @Resource
+    private BasicQuotaService basicQuotaService;
+
+    @PostMapping("/recognize")
+    public Result<com.etotem.cfc.dto.RecognizeFoodResult> recognizeFood(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, String> request) {
+        QuotaConsumeResult quota = basicQuotaService.consumeFoodRecognizeQuota(userId);
+        if (!quota.isSuccess()) {
+            return Result.error(403, quota.getToastMsg());
+        }
+        return Result.success(dietRecordService.recognizeFood(request.get("image_url")));
+    }
+
+    @PostMapping("/save")
+    public Result<Map> saveRecord(
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> request) {
+        return Result.success(dietRecordService.saveRecord(familyId, request));
+    }
+
+    @PostMapping("/daily")
+    public Result<Map> getDailySummary(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute(value = "familyMemberId", required = false) Long familyMemberId,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = familyMemberId != null ? familyMemberId : currentMemberId;
+        String date = params.get("date") != null ? params.get("date").toString() : java.time.LocalDate.now().toString();
+        return Result.success(dietRecordService.getDailySummary(userId, memberId, date));
+    }
+
+    @PostMapping("/weekly")
+    public Result<Map> getWeeklyTrend(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute(value = "familyMemberId", required = false) Long familyMemberId,
+            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = familyMemberId != null ? familyMemberId : currentMemberId;
+        String startDate = params.get("startDate") != null ? params.get("startDate").toString() : null;
+        if (startDate == null) return Result.error("startDate不能为空");
+        return Result.success(dietRecordService.getWeeklyTrend(userId, memberId, startDate));
+    }
+}

+ 113 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/BindController.java

@@ -0,0 +1,113 @@
+package com.etotem.cfc.controller.family;
+import javax.annotation.Resource;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.BindGuideDTO;
+import com.etotem.cfc.entity.GuideFamily;
+import com.etotem.cfc.service.GuideFamilyService;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.PlannerCertificationGuard;
+import com.etotem.cfc.service.PlannerCertificationService;
+import com.etotem.cfc.service.TeacherMessageService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "家庭主账号绑定", description = "家庭主账号绑定指导师接口")
+@RestController
+@RequestMapping("/api/bind")
+public class BindController {
+
+    @Resource
+    private GuideFamilyService guideFamilyService;
+
+    @Resource
+    private TeacherMessageService teacherMessageService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private PlannerCertificationGuard plannerCertificationGuard;
+
+    /**
+     * 家庭主账号确认绑定指导师
+     */
+    @Operation(summary = "确认绑定指导师")
+    @PostMapping("/accept")
+    public Result<Boolean> acceptBind(@RequestAttribute("userId") Long userId,
+                                        @RequestBody BindGuideDTO dto) {
+        try {
+            Long familyId = membershipService.getUserFamilyId(userId);
+            if (familyId == null) {
+                return Result.noFamily("请先创建或加入家庭");
+            }
+            // 认证闸门:规划师(基础类别)认证通过才可开始服务(家庭绑定)
+            Result<Void> denied = plannerCertificationGuard.assertCertified(dto.getGuideId(),
+                    PlannerCertificationService.CATEGORY_PLANNER);
+            if (denied != null) {
+                return Result.error(denied.getCode(), denied.getMessage());
+            }
+            boolean success = guideFamilyService.confirmBind(dto.getGuideId(), familyId,
+                dto.getServiceType(), dto.getServicePrice());
+            return Result.success(success);
+        } catch (RuntimeException e) {
+            return Result.error(400, e.getMessage());
+        }
+    }
+
+    /**
+     * 获取绑定的指导师列表
+     */
+    @Operation(summary = "获取绑定的指导师列表")
+    @PostMapping("/guides")
+    public Result<List<Map<String, Object>>> getBoundGuides(@RequestAttribute("userId") Long userId) {
+        Long familyId = membershipService.getUserFamilyId(userId);
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        List<GuideFamily> bindings = guideFamilyService.getGuidesByFamily(familyId);
+        
+        List<Map<String, Object>> result = bindings.stream().map(binding -> {
+            Map<String, Object> item = new java.util.HashMap<>();
+            item.put("id", binding.getId());
+            item.put("guideId", binding.getGuideId());
+            item.put("serviceType", binding.getServiceType());
+            item.put("servicePrice", binding.getServicePrice());
+            item.put("status", binding.getStatus());
+            item.put("boundAt", binding.getBoundAt());
+            return item;
+        }).collect(Collectors.toList());
+        
+        return Result.success(result);
+    }
+
+    /**
+     * 家庭主账号解除绑定规划师(会通知规划师)
+     */
+    @Operation(summary = "解除绑定规划师")
+    @PostMapping("/unbind")
+    public Result<Boolean> unbind(@RequestAttribute("userId") Long userId,
+                                    @RequestBody Map<String, Object> params) {
+        Long familyId = membershipService.getUserFamilyId(userId);
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        Long id = ParamUtils.getLong(params.get("id"));
+        try {
+            GuideFamily gf = guideFamilyService.unbindAndGet(id, familyId);
+            // 发送解绑通知给规划师
+            teacherMessageService.sendMessage(familyId, userId, gf.getGuideId(),
+                "家庭主账号已解除与您的绑定关系");
+            return Result.success(true);
+        } catch (RuntimeException e) {
+            return Result.error(400, e.getMessage());
+        }
+    }
+}

+ 101 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/BindInviteController.java

@@ -0,0 +1,101 @@
+package com.etotem.cfc.controller.family;
+
+import javax.annotation.Resource;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.BindInviteService;
+import com.etotem.cfc.service.MembershipService;
+import com.etotem.cfc.service.PlannerCertificationGuard;
+import com.etotem.cfc.service.PlannerCertificationService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Map;
+
+@Tag(name = "指导师绑定邀请", description = "指导师生成邀请、家庭主账号确认绑定等接口")
+@RestController
+@RequestMapping("/api/guide/bind")
+public class BindInviteController {
+
+    @Resource
+    private BindInviteService bindInviteService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private PlannerCertificationGuard plannerCertificationGuard;
+
+    /**
+     * 生成绑定邀请
+     */
+    @Operation(summary = "生成绑定邀请")
+    @PostMapping("/invite")
+    public Result<Map<String, Object>> generateInvite(@RequestAttribute("userId") Long userId) {
+        Map<String, Object> result = bindInviteService.generateInvite(userId);
+        return Result.success(result);
+    }
+
+    /**
+     * 校验邀请令牌
+     */
+    @Operation(summary = "校验邀请令牌")
+    @PostMapping("/validate")
+    public Result<Map<String, Object>> validateToken(@RequestBody Map<String, Object> params) {
+        String token = params.get("token") != null ? params.get("token").toString() : null;
+        Map<String, Object> result = bindInviteService.validateToken(token);
+        return Result.success(result);
+    }
+
+    /**
+     * 家庭主账号通过邀请令牌确认绑定规划师。
+     * 语义对齐 BindController#acceptBind(/api/bind/accept):家庭校验 → 规划师认证闸门 → 落库绑定。
+     */
+    @Operation(summary = "家庭主账号确认绑定规划师(邀请令牌)")
+    @PostMapping("/confirm")
+    public Result<Boolean> confirmBind(@RequestAttribute("userId") Long userId,
+                                       @RequestBody(required = false) Map<String, Object> body) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        try {
+            Long familyId = membershipService.getUserFamilyId(userId);
+            if (familyId == null) {
+                return Result.noFamily("请先创建或加入家庭");
+            }
+            Long guideId = ParamUtils.getLong(body != null ? body.get("guideId") : null);
+            if (guideId == null) {
+                return Result.error("guideId不能为空");
+            }
+            // 认证闸门:规划师(基础类别)认证通过才可开始服务(家庭绑定)
+            Result<Void> denied = plannerCertificationGuard.assertCertified(guideId,
+                    PlannerCertificationService.CATEGORY_PLANNER);
+            if (denied != null) {
+                return Result.error(denied.getCode(), denied.getMessage());
+            }
+            String inviteToken = firstNonBlank(
+                    body.get("bindToken") != null ? body.get("bindToken").toString() : null,
+                    body.get("inviteToken") != null ? body.get("inviteToken").toString() : null);
+            String serviceType = body.get("serviceType") != null ? body.get("serviceType").toString() : "consulting";
+            Long servicePrice = ParamUtils.getLong(body.get("servicePrice"));
+            boolean success = bindInviteService.confirmBind(inviteToken, guideId, familyId, serviceType,
+                    servicePrice != null ? servicePrice.intValue() : 0);
+            return Result.success(success);
+        } catch (RuntimeException e) {
+            return Result.error(400, e.getMessage());
+        }
+    }
+
+    /** 取第一个非空白字符串(bindToken / inviteToken 兼容) */
+    private static String firstNonBlank(String... values) {
+        for (String value : values) {
+            if (value != null && !value.trim().isEmpty()) {
+                return value;
+            }
+        }
+        return null;
+    }
+}

+ 94 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyController.java

@@ -0,0 +1,94 @@
+package com.etotem.cfc.controller.family;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.TeacherFamilyBindingRequestService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * 家庭管理控制器
+ */
+@Tag(name = "家庭管理", description = "家庭相关接口")
+@RestController
+@RequestMapping("/api/family")
+public class FamilyController {
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private TeacherFamilyBindingRequestService bindingRequestService;
+
+    /**
+     * 获取当前家庭的邀请码(已废弃,请使用邀请令牌系统)
+     */
+    @Operation(summary = "获取邀请码(已废弃)")
+    @Deprecated
+    @PostMapping("/invite-code")
+    public Result<String> getInviteCode() {
+        return Result.error(410, "该接口已废弃,请使用 /api/family/invite/generate 生成邀请令牌");
+    }
+
+    /**
+     * 生成/重置邀请码(已废弃,请使用邀请令牌系统)
+     */
+    @Operation(summary = "生成邀请码(已废弃)")
+    @Deprecated
+    @PostMapping("/invite-code/generate")
+    public Result<String> generateInviteCode() {
+        return Result.error(410, "该接口已废弃,请使用 /api/family/invite/generate 生成邀请令牌");
+    }
+
+    /**
+     * 成长规划师申请绑定家庭(需要家庭主账号审批)
+     */
+    @Operation(summary = "成长规划师申请绑定家庭(需家庭主账号审批)")
+    @PostMapping("/guide-bind")
+    public Result<String> guideBindFamily(@RequestAttribute("userId") Long userId,
+                                          @RequestBody Map<String, String> params) {
+        String inviteCode = params.get("inviteCode");
+        if (inviteCode == null || inviteCode.isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+
+        User guide = userMapper.selectById(userId);
+        if (guide == null || !"teacher".equals(guide.getRole())) {
+            return Result.error("只有成长规划师才能使用此功能");
+        }
+
+        // 查找家庭
+        Family family = familyMapper.selectOne(new LambdaQueryWrapper<Family>()
+                .eq(Family::getInviteCode, inviteCode));
+
+        if (family == null) {
+            return Result.error("邀请码无效");
+        }
+
+        // 检查规划师是否已绑定该家庭
+        if (bindingRequestService.isTeacherBoundToFamily(userId, family.getId())) {
+            return Result.error("您已绑定该家庭,无需重复申请");
+        }
+
+        // 创建绑定申请(家庭主账号审批后生效)
+        try {
+            String message = params.get("message");
+            Long requestId = bindingRequestService.createRequest(userId, inviteCode, message);
+            return Result.success("申请已提交,请等待家庭主账号审批");
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+}

+ 498 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyInviteController.java

@@ -0,0 +1,498 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.FamilyStatusDTO;
+import com.etotem.cfc.dto.InviteAcceptDTO;
+import com.etotem.cfc.dto.InviteGenerateDTO;
+import com.etotem.cfc.dto.InviteRevokeDTO;
+import com.etotem.cfc.dto.InviteValidateDTO;
+import com.etotem.cfc.dto.JoinApproveDTO;
+import com.etotem.cfc.dto.TransferAdminDTO;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMapper;
+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.WechatService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "家庭邀请", description = "家庭成员邀请二维码相关接口")
+@RestController
+@RequestMapping("/api/family/invite")
+public class FamilyInviteController {
+
+    private static final Logger log = LoggerFactory.getLogger(FamilyInviteController.class);
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private QrCodeService qrCodeService;
+
+    @Resource
+    private FamilyInvitationService familyInvitationService;
+
+    @Resource
+    private FamilyJoinRequestService familyJoinRequestService;
+
+    @Resource
+    private WechatService wechatService;
+
+    @Resource
+    private UnlockGateService unlockGateService;
+
+    /**
+     * 生成家庭邀请二维码
+     * 返回: base64 QR 码图片 + 邀请码 + 家庭名称
+     */
+    @Operation(summary = "生成家庭邀请二维码")
+    @PostMapping("/qrcode")
+    public Result<Map<String, Object>> generateQrCode(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+
+        Family family = familyMapper.selectById(user.getFamilyId());
+        if (family == null) {
+            return Result.error("家庭不存在");
+        }
+
+        // 确保有邀请码
+        String inviteCode = family.getInviteCode();
+        if (inviteCode == null || inviteCode.isEmpty()) {
+            inviteCode = generateInviteCode();
+            family.setInviteCode(inviteCode);
+            family.setUpdatedAt(new Date());
+            familyMapper.updateById(family);
+        }
+
+        // 二维码内容:邀请码
+        String qrContent = inviteCode;
+        String qrBase64 = qrCodeService.generateQrCodeBase64(qrContent);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("inviteCode", inviteCode);
+        result.put("familyName", family.getName());
+        result.put("qrCodeBase64", "data:image/png;base64," + qrBase64);
+        result.put("familyId", family.getId());
+
+        return Result.success(result);
+    }
+
+    /**
+     * 通过邀请码/令牌提交加入家庭请求(令牌路径绑定邀请人,等待邀请人确认;旧邀请码路径由家庭管理员兜底审批)
+     */
+    @Operation(summary = "通过邀请码申请加入家庭")
+    @PostMapping("/request-join-by-code")
+    public Result<Map<String, Object>> requestJoinByCode(@RequestBody Map<String, String> body,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        String inviteCode = body.get("inviteCode");
+
+        // 获取申请人角色
+        String familyRole = body.get("familyRole");
+
+        // 兼容邀请令牌(token):直接透传原始 token,服务层解析并绑定邀请人(审批人)
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            String token = body.get("token");
+            if (token != null && !token.trim().isEmpty()) {
+                inviteCode = token;
+            }
+        }
+
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+
+        try {
+            com.etotem.cfc.entity.FamilyJoinRequest request = familyJoinRequestService.createJoinRequest(userId, inviteCode, familyRole);
+            Family family = familyMapper.selectById(request.getTargetFamilyId());
+            Map<String, Object> result = new HashMap<>();
+            result.put("requestId", request.getId());
+            result.put("familyName", family != null ? family.getName() : "");
+            return Result.success("申请已提交,等待邀请人确认", result);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 邀请人审批加入请求(谁分享的卡谁确认;旧数据无邀请人时由家庭管理员兜底)
+     * 身份由邀请人在审批时指定:generationLevel(辈分,必填)+ peerType(同辈类型,仅 peer 时必填)
+     */
+    @Operation(summary = "审批加入请求")
+    @PostMapping("/approve-request")
+    public Result<Void> approveJoinRequest(@RequestBody JoinApproveDTO dto,
+        @RequestAttribute("userId") Long approverUserId) {
+        if (approverUserId == null) {
+            return Result.error("请先登录");
+        }
+        if (dto == null || dto.getRequestId() == null) {
+            return Result.error("请求ID不能为空");
+        }
+        String generationLevel = dto.getGenerationLevel();
+        if (generationLevel == null || generationLevel.trim().isEmpty()) {
+            return Result.error("请选择辈分关系");
+        }
+        if ("peer".equals(generationLevel)
+                && (dto.getPeerType() == null || dto.getPeerType().trim().isEmpty())) {
+            return Result.error("请选择同辈关系类型");
+        }
+        try {
+            familyJoinRequestService.approveJoinRequest(dto.getRequestId(), approverUserId,
+                    dto.getComment() != null ? dto.getComment() : "", generationLevel, dto.getPeerType());
+            return Result.success();
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 邀请人拒绝加入请求(旧数据无邀请人时由家庭管理员兜底)
+     */
+    @Operation(summary = "拒绝加入请求")
+    @PostMapping("/reject-request")
+    public Result<Void> rejectJoinRequest(@RequestBody Map<String, Object> body,
+        @RequestAttribute("userId") Long approverUserId) {
+        if (approverUserId == null) {
+            return Result.error("请先登录");
+        }
+        Long requestId = ParamUtils.getLong(body.get("requestId"));
+        String comment = body.get("comment") != null ? body.get("comment").toString() : "";
+        if (requestId == null) {
+            return Result.error("请求ID不能为空");
+        }
+        try {
+            familyJoinRequestService.rejectJoinRequest(requestId, approverUserId, comment);
+            return Result.success();
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 查询待我处理的加入申请(我是邀请人的;旧数据未绑定邀请人的由目标家庭管理员兜底可见)
+     */
+    @Operation(summary = "查询待我处理的加入申请")
+    @PostMapping("/pending-requests")
+    public Result<java.util.List<com.etotem.cfc.dto.FamilyJoinRequestDTO>> getPendingRequests(
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        try {
+            return Result.success(familyJoinRequestService.getPendingRequests(userId));
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 查询用户自己的待审批请求
+     */
+    @Operation(summary = "查询我的加入请求")
+    @PostMapping("/my-request")
+    public Result<com.etotem.cfc.dto.FamilyJoinRequestDTO> getMyRequest(
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        com.etotem.cfc.dto.FamilyJoinRequestDTO dto = familyJoinRequestService.getMyPendingRequest(userId);
+        return Result.success(dto);
+    }
+
+    /**
+     * 取消用户自己的加入请求
+     */
+    @Operation(summary = "取消加入请求")
+    @PostMapping("/cancel-request")
+    public Result<Void> cancelJoinRequest(@RequestBody Map<String, Object> body,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long requestId = ParamUtils.getLong(body.get("requestId"));
+        if (requestId == null) {
+            return Result.error("请求ID不能为空");
+        }
+        try {
+            familyJoinRequestService.cancelJoinRequest(userId, requestId);
+            return Result.success();
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 生成家庭邀请(含小程序二维码)
+     */
+    @Operation(summary = "生成家庭邀请")
+    @PostMapping("/generate")
+    public Result<InviteGenerateDTO> generateInvite(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+
+        String token;
+        try {
+            token = familyInvitationService.generateInvitation(user.getFamilyId(), userId);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+
+        String qrBase64 = wechatService.generateWxacode(token, "pages/invite/join");
+
+        Family family = familyMapper.selectById(user.getFamilyId());
+
+        InviteGenerateDTO result = new InviteGenerateDTO();
+        result.setToken(token);
+        result.setQrCodeBase64(qrBase64);
+        result.setFamilyName(family != null ? family.getName() : null);
+        result.setFamilyId(user.getFamilyId());
+        return Result.success(result);
+    }
+
+    /**
+     * 重生成家庭邀请(SC-P-09:失效旧码 → 生成新码;旧码已加入成员不受影响)
+     */
+    @Operation(summary = "重生成家庭邀请")
+    @PostMapping("/regenerate")
+    public Result<InviteGenerateDTO> regenerateInvite(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+
+        String token;
+        try {
+            token = familyInvitationService.regenerateInvitation(user.getFamilyId(), userId);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+
+        String qrBase64 = wechatService.generateWxacode(token, "pages/invite/join");
+        Family family = familyMapper.selectById(user.getFamilyId());
+
+        InviteGenerateDTO result = new InviteGenerateDTO();
+        result.setToken(token);
+        result.setQrCodeBase64(qrBase64);
+        result.setFamilyName(family != null ? family.getName() : null);
+        result.setFamilyId(user.getFamilyId());
+        return Result.success(result);
+    }
+
+    /**
+     * 校验邀请令牌有效性
+     */
+    @Operation(summary = "校验邀请令牌")
+    @PostMapping("/validate")
+    public Result<InviteValidateDTO> validateInvite(@RequestBody Map<String, String> body) {
+        String token = body.get("token");
+        if (token == null || token.trim().isEmpty()) {
+            return Result.error("邀请令牌不能为空");
+        }
+
+        try {
+            InviteValidateDTO dto = familyInvitationService.validateInvitation(token);
+            return Result.success(dto);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 验证家庭短邀请码(如 fam_abc123)
+     * 供落地页展示家庭信息用,不创建加入请求记录
+     */
+    @Operation(summary = "验证家庭短邀请码")
+    @PostMapping("/validate-family-code")
+    public Result<InviteValidateDTO> validateFamilyCode(@RequestBody Map<String, String> body) {
+        String inviteCode = body.get("inviteCode");
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+
+        Family family = familyMapper.selectOne(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Family>()
+                        .eq(Family::getInviteCode, inviteCode.trim()));
+        if (family == null) {
+            return Result.error("邀请码无效或不存在");
+        }
+
+        User creator = userMapper.selectById(family.getCreatorId());
+        Long memberCount = userMapper.selectCount(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<User>()
+                        .eq(User::getFamilyId, family.getId()));
+
+        InviteValidateDTO dto = new InviteValidateDTO();
+        dto.setFamilyId(family.getId());
+        dto.setFamilyName(family.getName());
+        dto.setInviterName(creator != null ? creator.getNickname() : null);
+        dto.setInviterAvatar(creator != null ? creator.getAvatar() : null);
+        dto.setMemberCount(memberCount.intValue());
+        return Result.success(dto);
+    }
+
+    /**
+     * 首次注册绑定家庭邀请人(幂等,已有绑定则忽略)
+     */
+    @Operation(summary = "首次注册绑定家庭邀请人")
+    @PostMapping("/bind-inviter")
+    public Result<Void> bindFamilyInviter(@RequestBody Map<String, String> body,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        String inviteCode = body.get("familyInviteCode");
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+
+        Family family = familyMapper.selectOne(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Family>()
+                        .eq(Family::getInviteCode, inviteCode.trim()));
+        if (family == null) {
+            return Result.error("邀请码无效");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+        // 幂等:已绑定过则直接返回成功
+        if (user.getFamilyInviterId() != null && user.getFamilyInviterId().equals(family.getCreatorId())) {
+            return Result.success();
+        }
+        user.setFamilyInviterId(family.getCreatorId());
+        user.setUpdatedAt(new java.util.Date());
+        userMapper.updateById(user);
+        return Result.success();
+    }
+
+    /**
+     * 接受家庭邀请
+     */
+    @Operation(summary = "接受家庭邀请")
+    @PostMapping("/accept")
+    public Result<String> acceptInvite(@RequestBody InviteAcceptDTO dto,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        try {
+            familyInvitationService.acceptInvitation(userId, dto.getToken(), dto.getFamilyRole(), dto.getMergeFamily());
+            // 触发通关解锁刷新:邀请家人成功
+            User user = userMapper.selectById(userId);
+            if (user != null && user.getFamilyId() != null) {
+                unlockGateService.refreshFamilyGates(user.getFamilyId(), userId);
+            }
+            return Result.success("加入家庭成功");
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 查询当前用户的家庭状态
+     */
+    @Operation(summary = "查询家庭状态")
+    @PostMapping("/check-family")
+    public Result<FamilyStatusDTO> checkFamilyStatus(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        try {
+            FamilyStatusDTO dto = familyInvitationService.checkUserFamilyStatus(userId);
+            return Result.success(dto);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 吊销邀请链接
+     */
+    @Operation(summary = "吊销邀请链接")
+    @PostMapping("/revoke")
+    public Result<String> revokeInvite(@RequestBody InviteRevokeDTO dto,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        try {
+            familyInvitationService.revokeInvitation(dto.getInvitationId(), userId);
+            return Result.success("邀请已吊销");
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 转让家庭管理员
+     */
+    @Operation(summary = "转让家庭管理员")
+    @PostMapping("/transfer-admin")
+    public Result<String> transferAdmin(@RequestBody TransferAdminDTO dto,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+
+        try {
+            familyInvitationService.transferAdmin(user.getFamilyId(), userId, dto.getNewAdminId());
+            return Result.success("转让成功");
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    private String generateInviteCode() {
+        String uuid = java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase();
+        return uuid.substring(0, 8);
+    }
+}

+ 300 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyMembersController.java

@@ -0,0 +1,300 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.dto.AddFamilyMemberDTO;
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.dto.SwitchMemberVO;
+import com.etotem.cfc.entity.FamilyMemberLog;
+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 io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "家庭成员管理", description = "手动添加的家庭成员管理接口")
+@RestController
+@RequestMapping("/api/family/member")
+public class FamilyMembersController {
+
+    @Resource
+    private FamilyMemberService familyMemberService;
+
+    @Resource
+    private UnlockGateService unlockGateService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private UserMapper userMapper;
+
+@Operation(summary = "添加家庭成员")
+@PostMapping("/add")
+public Result<FamilyMemberVO> addMember(@RequestBody AddFamilyMemberDTO dto,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ try {
+   FamilyMemberVO vo = familyMemberService.addMember(userId, dto);
+   // 触发通关解锁刷新:创建家人成功
+    User user = userMapper.selectById(userId);
+    if (user != null && user.getFamilyId() != null) {
+        unlockGateService.refreshFamilyGates(user.getFamilyId(), userId);
+    }
+   return Result.success(vo);
+ } catch (IllegalArgumentException e) {
+   return Result.error(e.getMessage());
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "获取家庭成员列表(统一入口)")
+@PostMapping("/list")
+public Result<?> listMembers(@RequestBody(required = false) Map<String, Object> params,
+                             @RequestAttribute("userId") Long userId,
+                             @RequestAttribute("role") String role,
+                             @RequestAttribute("roles") List<String> roles) {
+    // SEC-20261031-01:拦截器对匿名请求注入 userId=-1,此处必须同时拦截 null 与 <=0,
+    // 防止匿名请求绕到家庭私有数据列表(口径统一为 401,与 JwtInterceptor LOGIN_REQUIRED_PATHS 一致)
+    if (userId == null || userId <= 0) {
+        return Result.error(401, "请先登录");
+    }
+
+    // B2-1:显式指定 familyId 时,按该家庭返回成员(teacher 可查绑定家庭;平台角色任意家庭)。
+    // 越权(familyId 不在调用者有效家庭集内)直接 403,与 FamilyAccessInterceptor 口径一致。
+    Long requestedFamilyId = params != null ? ParamUtils.getLong(params.get("familyId")) : null;
+    if (requestedFamilyId != null) {
+        if (!canAccessFamily(requestedFamilyId, userId, role, roles)) {
+            return Result.error(403, "无权访问该家庭数据");
+        }
+        return Result.success(familyMemberService.listMembersOfFamily(requestedFamilyId, userId));
+    }
+
+    boolean visibleOnly = params != null && Boolean.TRUE.equals(params.get("visibleOnly"));
+    boolean includeFamily = params != null && Boolean.TRUE.equals(params.get("includeFamily"));
+    if (includeFamily) {
+        // 不再 ensureUserFamily:无家庭时返回空列表,绝不静默建家庭
+        return Result.success(familyMemberService.listMembersWithFamily(userId));
+    }
+    if (visibleOnly) {
+        return Result.success(userService.getVisibleMembers(userId));
+    }
+    return listMembersWithPage(params, userId);
+}
+
+/**
+ * SC-P-04 family.familyMembers.list:成员列表分页/搜索(keyword/page/pageSize)。
+ * <p>兼容现状语义:不传分页/搜索参数时返回全量 {@code List<FamilyMemberVO>}(裸列表);
+ * 仅显式传入 page/pageSize/keyword 时返回分页结构 {@code {total, list}}(当前页数据)。</p>
+ * <p>边界:page/pageSize 显式为 0 或负数 → 400 校验失败(不再静默忽略)。</p>
+ */
+private Result<?> listMembersWithPage(Map<String, Object> params, Long userId) {
+    Long page = params != null ? ParamUtils.getLong(params.get("page")) : null;
+    Long pageSize = params != null ? ParamUtils.getLong(params.get("pageSize")) : null;
+    String keyword = params != null && params.get("keyword") != null
+            ? params.get("keyword").toString() : null;
+
+    boolean hasPageOrKeyword = page != null || pageSize != null
+            || (keyword != null && !keyword.trim().isEmpty());
+    if (!hasPageOrKeyword) {
+        List<FamilyMemberVO> members = familyMemberService.listMembers(userId);
+        return Result.success(members);
+    }
+    // SC-P-04 边界:非法分页参数(0/负数)→ 400 校验失败,而非静默忽略
+    if ((page != null && page <= 0) || (pageSize != null && pageSize <= 0)) {
+        return Result.error(400, "分页参数必须为正整数");
+    }
+    List<FamilyMemberVO> all = familyMemberService.listMembers(userId);
+    Map<String, Object> paged = FamilyMemberService.paginateMembers(all, keyword,
+            page != null ? page.intValue() : null,
+            pageSize != null ? pageSize.intValue() : null);
+    return Result.success(paged);
+}
+
+/**
+ * B2-1 行级隔离口径:平台角色(admin/operator/finance)任意家庭;
+ * 否则 familyId 必在用户有效家庭集内(own family / teacher_family_ids / family_members 反查 / guide_family 绑定)。
+ * 与 FamilyAccessInterceptor.getEffectiveFamilyIds 保持一致,避免两套口径导致越权放行或误伤。
+ */
+private boolean canAccessFamily(Long familyId, Long userId, String role, List<String> roles) {
+    if ("admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles)) {
+        return true;
+    }
+    Set<Long> effective = userService.getEffectiveFamilyIds(userId);
+    return effective != null && effective.contains(familyId);
+}
+
+@Operation(summary = "切换到家庭成员视图")
+@PostMapping("/switch")
+public Result<SwitchMemberVO> switchToMember(@RequestBody Map<String, Object> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error(401, "请先登录");
+ }
+ Long memberId = ParamUtils.getLong(body.get("memberId"));
+ if (memberId == null) {
+   return Result.badRequest("缺少成员ID");
+ }
+ // 异常(参数/业务规则→400,权限→403)由 GlobalExceptionHandler 统一映射
+ SwitchMemberVO vo = familyMemberService.switchToMember(userId, memberId);
+ return Result.success(vo);
+}
+
+@Operation(summary = "踢出家庭成员")
+@PostMapping("/kick")
+public Result<String> kickMember(@RequestBody Map<String, Long> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ Long memberId = body.get("memberId");
+ if (memberId == null) {
+   return Result.error("缺少成员ID");
+ }
+ try {
+   familyMemberService.kickMember(userId, memberId);
+   return Result.success("踢出成功");
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "主动退出家庭")
+@PostMapping("/leave")
+public Result<String> leaveFamily(@RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ try {
+   familyMemberService.leaveFamily(userId);
+   return Result.success("退出成功");
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "从回收箱回收成员")
+@PostMapping("/recycle")
+public Result<String> recycleMember(@RequestBody Map<String, Long> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ Long memberId = body.get("memberId");
+ Long targetFamilyId = body.get("targetFamilyId");
+ if (memberId == null) {
+   return Result.error("缺少成员ID");
+ }
+ if (targetFamilyId == null) {
+   return Result.error("缺少目标家庭ID");
+ }
+ try {
+   familyMemberService.recycleMember(userId, memberId, targetFamilyId);
+   return Result.success("回收成功");
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "更新成员信息")
+@PostMapping("/update")
+public Result<FamilyMemberVO> updateMember(@RequestBody Map<String, Object> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ Long memberId = ParamUtils.getLong(body.get("memberId"));
+ if (memberId == null) {
+   return Result.error("缺少成员ID");
+ }
+
+ AddFamilyMemberDTO dto = new AddFamilyMemberDTO();
+ if (body.get("nickname") != null) dto.setNickname(body.get("nickname").toString());
+ if (body.get("phone") != null) dto.setPhone(body.get("phone").toString());
+ if (body.get("avatar") != null) dto.setAvatar(body.get("avatar").toString());
+ if (body.get("gender") != null) dto.setGender(body.get("gender").toString());
+ if (body.get("birthday") != null) dto.setBirthday(body.get("birthday").toString());
+ if (body.get("generationLevel") != null) dto.setGenerationLevel(body.get("generationLevel").toString());
+ if (body.get("peerType") != null) dto.setPeerType(body.get("peerType").toString());
+ if (body.get("isAdmin") != null) {
+   dto.setIsAdmin(Integer.parseInt(body.get("isAdmin").toString()));
+ }
+ if (body.get("isChild") != null) {
+   Object raw = body.get("isChild");
+   if (raw instanceof Boolean) {
+     dto.setIsChild(Boolean.TRUE.equals(raw) ? 1 : 0);
+   } else if (raw instanceof Number) {
+     dto.setIsChild(((Number) raw).intValue() == 1 ? 1 : 0);
+   } else {
+     String s = raw.toString();
+     if ("true".equalsIgnoreCase(s) || "1".equals(s)) dto.setIsChild(1);
+     else if ("false".equalsIgnoreCase(s) || "0".equals(s)) dto.setIsChild(0);
+   }
+ }
+
+ try {
+   FamilyMemberVO vo = familyMemberService.updateMember(userId, memberId, dto);
+   return Result.success(vo);
+ } catch (org.springframework.security.access.AccessDeniedException e) {
+   return Result.error(403, e.getMessage() != null ? e.getMessage() : "无权限");
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "修改家庭名称(仅家庭管理员)")
+@PostMapping("/rename-family")
+public Result<String> renameFamily(@RequestBody Map<String, Object> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null || userId <= 0) {
+  return Result.error(401, "请先登录");
+ }
+ String name = body != null && body.get("name") != null ? body.get("name").toString() : null;
+ try {
+  String newName = familyMemberService.renameFamily(userId, name);
+  return Result.success(newName);
+ } catch (IllegalArgumentException e) {
+  return Result.error(e.getMessage());
+ } catch (RuntimeException e) {
+  return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "检查成员是否可编辑")
+@PostMapping("/editable")
+public Result<Boolean> checkEditable(@RequestBody Map<String, Long> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ Long memberId = body.get("memberId");
+ if (memberId == null) {
+   return Result.error("缺少成员ID");
+ }
+ boolean editable = familyMemberService.isEditable(memberId);
+ return Result.success(editable);
+}
+
+@Operation(summary = "查询成员变更日志")
+@PostMapping("/logs")
+public Result<List<FamilyMemberLog>> logs(@RequestBody Map<String, Long> body,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ Long memberId = body != null ? body.get("memberId") : null;
+ return familyMemberService.getMemberLogs(userId, memberId);
+}
+}

+ 290 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyUserController.java

@@ -0,0 +1,290 @@
+package com.etotem.cfc.controller.family;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.*;
+import com.etotem.cfc.entity.FamilyJoinRequest;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyJoinRequestService;
+import com.etotem.cfc.service.UserService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import javax.annotation.Resource;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "家庭用户管理", description = "家庭用户信息、家庭成员管理等接口")
+@RestController
+@RequestMapping("/api/family/user")
+public class FamilyUserController {
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private FamilyJoinRequestService familyJoinRequestService;
+
+    @Operation(summary = "获取用户信息")
+    @PostMapping("/info")
+    public Result<User> getUserInfo(@RequestAttribute("userId") Long userId) {
+        User user = userService.getUserInfo(userId);
+        if (user != null) {
+            user.setPassword(null);
+        }
+        // C-16 受限资料投影:孩子端隐藏敏感字段
+        userService.maskChildSensitiveFields(user);
+        return Result.success(user);
+    }
+
+    @Operation(summary = "更新用户信息")
+    @PostMapping("/update")
+    public Result<Boolean> updateUserInfo(@RequestAttribute("userId") Long userId,
+        @RequestBody UpdateUserDTO dto) {
+        boolean success = userService.updateUserInfo(userId, dto);
+        return Result.success(success);
+    }
+
+    @Operation(summary = "加入家庭(通过邀请码)")
+    @PostMapping("/join-family")
+    public Result<Map<String, Object>> joinFamily(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, String> body) {
+        String inviteCode = body.get("inviteCode");
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return Result.error("邀请码不能为空");
+        }
+
+        try {
+            FamilyJoinRequest request = familyJoinRequestService.createJoinRequest(userId, inviteCode, null);
+            Family family = familyMapper.selectById(request.getTargetFamilyId());
+            Map<String, Object> result = new HashMap<>();
+            result.put("requestId", request.getId());
+            result.put("familyName", family != null ? family.getName() : "");
+            return Result.success("申请已提交,等待家庭管理员审批", result);
+        } catch (Exception e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "创建新家庭")
+    @PostMapping("/create-family")
+    public Result<Long> createFamily(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, String> body) {
+        String familyName = body.getOrDefault("name", "我的家庭");
+        Long familyId = userService.createFamilyForUser(userId, familyName);
+        return Result.success(familyId);
+    }
+
+    @Operation(summary = "切换本人/成员模式(已废弃,使用 /api/family/member/switch)")
+    @Deprecated
+    @PostMapping("/switch-mode")
+    public Result<String> switchMode(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, String> body) {
+        return Result.error(410, "该接口已废弃,请使用 /api/family/member/switch");
+    }
+
+    @Operation(summary = "切换用户角色 (支持 parent/child/teacher)")
+    @PostMapping("/switch-role")
+    public Result<String> switchRole(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, String> body) {
+        // SEC-20261031-01:鉴权统一——匿名注入 userId=-1,统一拦截为 401
+        if (userId == null || userId <= 0) {
+            return Result.error(401, "请先登录");
+        }
+        String role = body.get("role");
+        String result = userService.switchRole(userId, role);
+        if (result == null) {
+            return Result.error("切换失败,请确认您拥有该角色");
+        }
+        return Result.success(result);
+    }
+
+    @Operation(summary = "获取用户所有角色列表")
+    @PostMapping("/roles")
+    public Result<List<String>> getUserRoles(@RequestAttribute("userId") Long userId) {
+        List<String> roles = userService.getUserRoles(userId);
+        return Result.success(roles);
+    }
+
+    @Operation(summary = "本人切换到指定成员身份(已废弃,使用 /api/family/member/switch)")
+    @Deprecated
+    @PostMapping("/switch-to-child")
+    public Result<Long> switchToFamilyMember(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, Long> body) {
+        return Result.error(410, "该接口已废弃,请使用 /api/family/member/switch");
+    }
+
+    @Operation(summary = "成员切换回本人身份(已废弃,使用 /api/family/member/switch)")
+    @Deprecated
+    @PostMapping("/switch-back-to-parent")
+    public Result<Boolean> switchBackToParent(@RequestAttribute("userId") Long userId) {
+        return Result.error(410, "该接口已废弃,请使用 /api/family/member/switch");
+    }
+
+    @Operation(summary = "带密码校验退出成员切换(返回原用户身份)")
+    @PostMapping("/switch-back-verify")
+    public Result<Boolean> switchBackVerify(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, String> body) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        String password = body != null ? body.get("password") : null;
+        if (password == null || password.isEmpty()) {
+            return Result.error("请输入密码");
+        }
+        boolean valid = userService.verifyPassword(userId, password);
+        if (!valid) {
+            return Result.error("密码错误");
+        }
+        return Result.success(true);
+    }
+
+    @Operation(summary = "创建家庭成员")
+    @PostMapping("/children")
+    public Result<FamilyMemberInfoDTO> createFamilyMember(@RequestAttribute("userId") Long userId,
+        @RequestBody CreateFamilyMemberDTO dto) {
+        FamilyMemberInfoDTO child = userService.createFamilyMember(userId, dto);
+        return Result.success(child);
+    }
+
+    @Operation(summary = "获取家庭成员列表")
+    @PostMapping("/children/list")
+    public Result<List<FamilyMemberInfoDTO>> getFamilyMemberren(@RequestAttribute("userId") Long userId) {
+        List<FamilyMemberInfoDTO> children = userService.getFamilyMemberren(userId);
+        return Result.success(children);
+    }
+
+    @Operation(summary = "更新家庭成员信息")
+    @PostMapping("/children/update")
+    public Result<Boolean> updateFamilyMember(@RequestAttribute("userId") Long userId,
+        @RequestBody UpdateFamilyMemberDTO dto) {
+        Long memberId = dto.getFamilyMemberId();
+        boolean success = userService.updateFamilyMember(userId, memberId, dto);
+        return Result.success(success);
+    }
+
+    @Operation(summary = "获取家庭成员列表")
+    @PostMapping("/family-members")
+    public Result<Map<String, Object>> getFamilyMembers(@RequestAttribute("userId") Long userId) {
+        User user = userMapper.selectById(userId);
+
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        Long familyId = user.getFamilyId();
+        if (familyId == null) {
+            // 兜底:无家庭时自动创建,避免"暂无家庭"空态
+            familyId = userService.ensureUserFamily(userId);
+            if (familyId == null) {
+                return Result.error("用户不存在");
+            }
+        }
+
+        // 获取家庭信息
+        Family family = familyMapper.selectById(familyId);
+        if (family == null) {
+            return Result.error("家庭不存在");
+        }
+
+        // 查询家庭主账号列表
+        List<User> parents = userMapper.selectList(
+            new LambdaQueryWrapper<User>()
+                .eq(User::getFamilyId, familyId)
+                .eq(User::getRole, "parent")
+        );
+
+        // 查询家庭成员列表
+        List<FamilyMember> children = familyMemberMapper.selectList(
+            new LambdaQueryWrapper<FamilyMember>()
+                .eq(FamilyMember::getFamilyId, familyId)
+        );
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("familyId", familyId);
+        result.put("familyName", family.getName());
+        result.put("inviteCode", family.getInviteCode());
+        result.put("creatorId", family.getCreatorId());
+        result.put("parents", parents);
+        result.put("children", children);
+
+        return Result.success(result);
+    }
+
+    @Operation(summary = "获取对家庭成员可见的成员列表")
+    @PostMapping("/members/visible")
+    public Result<List<FamilyMemberVO>> getVisibleMembers(@RequestAttribute("userId") Long userId) {
+        List<FamilyMemberVO> members = userService.getVisibleMembers(userId);
+        return Result.success(members);
+    }
+
+    @Operation(summary = "更新成员可见性")
+    @PostMapping("/members/update-visibility")
+    public Result<Boolean> updateVisibility(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, Object> body) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"));
+        String memberType = (String) body.get("memberType");
+        Integer showToFamily = Integer.valueOf(body.get("showToFamily").toString());
+        boolean success = userService.updateVisibility(userId, memberId, memberType, showToFamily);
+        return Result.success(success);
+    }
+
+    @Operation(summary = "踢出家庭成员(仅管理员可操作)")
+    @PostMapping("/kick")
+    public Result<Boolean> kickMember(@RequestAttribute("userId") Long userId,
+        @RequestBody Map<String, Long> body) {
+        Long targetUserId = body.get("targetUserId");
+        if (targetUserId == null) {
+            return Result.error("缺少目标用户ID");
+        }
+        if (targetUserId.equals(userId)) {
+            return Result.error("不能踢出自己");
+        }
+        User operator = userMapper.selectById(userId);
+        if (operator == null) {
+            return Result.error("用户不存在");
+        }
+        Long familyId = operator.getFamilyId();
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        Family family = familyMapper.selectById(familyId);
+        if (family == null) {
+            return Result.error("家庭不存在");
+        }
+        if (!Long.valueOf(userId).equals(family.getCreatorId())) {
+            return Result.error("只有家庭管理员才能踢出成员");
+        }
+        User target = userMapper.selectById(targetUserId);
+        if (target == null) {
+            return Result.error("目标用户不存在");
+        }
+        if (!familyId.equals(target.getFamilyId())) {
+            return Result.error("目标用户不属于同一家庭");
+        }
+        // 踢出:清空目标用户的家庭ID
+        target.setFamilyId(null);
+        target.setUpdatedAt(new Date());
+        userMapper.updateById(target);
+        return Result.success(true);
+    }
+}

+ 207 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FiveDimensionSelfCheckController.java

@@ -0,0 +1,207 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.SelfCheckQuestionVO;
+import com.etotem.cfc.dto.SelfCheckResultVO;
+import com.etotem.cfc.dto.SubmitSelfCheckDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.FiveDimensionSelfCheckService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 五维家庭自检问卷(P0-1)
+ * 对应书稿《终章-绘制你家的幸福全景图》15题自检问卷 + 五行相生寻源建议(P0-2)
+ */
+@Tag(name = "五维家庭自检", description = "15题五维自检问卷、五行相生寻源建议")
+@RestController
+@RequestMapping("/api/family/self-check")
+public class FiveDimensionSelfCheckController {
+
+    @Resource
+    private FiveDimensionSelfCheckService selfCheckService;
+
+    @Resource
+    private UnlockGateService unlockGateService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private com.etotem.cfc.service.HealthPlanService healthPlanService;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Operation(summary = "获取自检问卷题目(首次固定 15 题;再次合并题库随机抽)")
+    @PostMapping("/questions")
+    public Result<List<SelfCheckQuestionVO>> getQuestions(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Boolean retake = body != null && body.get("retake") != null && Boolean.TRUE.equals(body.get("retake"));
+        if (retake) {
+            return Result.success(selfCheckService.getQuestionsForRetake(userId));
+        }
+        return Result.success(selfCheckService.getQuestions());
+    }
+
+    @Operation(summary = "提交自检问卷并计算五维得分与寻源建议")
+    @PostMapping("/submit")
+    public Result<SelfCheckResultVO> submit(@RequestBody SubmitSelfCheckDTO dto,
+                                            @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        try {
+            SelfCheckResultVO vo = selfCheckService.submitSelfCheck(dto, userId);
+
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                unlockGateService.refreshPersonalGates(userId, user.getFamilyId());
+                if (user.getFamilyId() != null) {
+                    unlockGateService.refreshFamilyGates(user.getFamilyId(), userId);
+                }
+            }
+            return Result.success(vo);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取最新一次自检结果")
+    @PostMapping("/latest")
+    public Result<SelfCheckResultVO> getLatest(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        try {
+            SelfCheckResultVO vo = selfCheckService.getLatest(userId);
+            return Result.success(vo);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取自检历史记录")
+    @PostMapping("/history")
+    public Result<List<SelfCheckResultVO>> getHistory(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        try {
+            List<SelfCheckResultVO> history = selfCheckService.getHistory(userId, 20);
+            return Result.success(history);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取自检状态(是否有记录、是否可检、距下次提醒天数)")
+    @PostMapping("/status")
+    public Result<Map<String, Object>> getStatus(@RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        return Result.success(selfCheckService.getStatus(userId));
+    }
+
+    @Operation(summary = "忽略本次自检提醒(重置 15 天计时)")
+    @PostMapping("/ignore")
+    public Result<Map<String, Object>> ignoreSelfCheck(@RequestBody(required = false) Map<String, Object> body,
+                                                       @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long checkId = body != null ? ParamUtils.getLong(body.get("checkId")) : null;
+        Date ignoredAt = selfCheckService.ignoreSelfCheck(userId, checkId);
+        Map<String, Object> resp = new HashMap<>();
+        resp.put("nextRemindAt", new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(
+                new Date(ignoredAt.getTime() + 15L * 24 * 60 * 60 * 1000)));
+        return Result.success(resp);
+    }
+
+    @Operation(summary = "用户点击生成健康计划(基于自检低分维度)")
+    @PostMapping("/generate-plan")
+    public Result<Map<String, Object>> generatePlan(
+            @RequestBody(required = false) Map<String, Object> body,
+            @RequestAttribute("userId") Long userId) {
+        if (userId == null) return Result.error("请先登录");
+        Long checkId = body != null ? com.etotem.cfc.util.ParamUtils.getLong(body.get("checkId")) : null;
+        try {
+            Long planId = healthPlanService.generateFromSelfCheck(userId, checkId);
+            if (planId == null) return Result.error("计划生成失败,请稍后重试");
+            Map<String, Object> resp = new HashMap<>();
+            resp.put("planId", planId);
+            resp.put("status", "draft");
+            return Result.success(resp);
+        } catch (Exception e) {
+            return Result.error("计划生成失败");
+        }
+    }
+
+    @Operation(summary = "获取自检历史趋势分析")
+    @PostMapping("/trend-analysis")
+    public Result<Map<String, Object>> getTrendAnalysis(@RequestAttribute("userId") Long userId) {
+        if (userId == null) return Result.error("请先登录");
+        try {
+            return Result.success(selfCheckService.getTrendAnalysis(userId));
+        } catch (Exception e) {
+            return Result.error("趋势分析失败");
+        }
+    }
+
+    @Operation(summary = "AI生成五维自检题目(智能出题)")
+    @PostMapping("/ai-generate-questions")
+    public Result<List<SelfCheckQuestionVO>> aiGenerateQuestions(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        if (userId == null) return Result.error("请先登录");
+        try {
+            Map<String, Object> inputs = new HashMap<>();
+            inputs.put("user_id", userId);
+            if (body != null) {
+                if (body.get("count") != null) inputs.put("count", body.get("count"));
+                if (body.get("difficulty") != null) inputs.put("difficulty", body.get("difficulty"));
+                if (body.get("dimensions") != null) inputs.put("dimensions", body.get("dimensions"));
+                if (body.get("exclude_ids") != null) inputs.put("exclude_ids", body.get("exclude_ids"));
+            }
+            List<Map<String, Object>> rawQuestions = aiGateway.generateSelfCheckQuestions(inputs);
+            List<SelfCheckQuestionVO> questions = new ArrayList<>();
+            if (rawQuestions != null) {
+                for (Map<String, Object> q : rawQuestions) {
+                    SelfCheckQuestionVO vo = new SelfCheckQuestionVO();
+                    if (q.get("id") != null) vo.setId(Integer.parseInt(q.get("id").toString()));
+                    if (q.get("dimension") != null) vo.setDimension(q.get("dimension").toString());
+                    if (q.get("sub_dim") != null) vo.setSubDim(q.get("sub_dim").toString());
+                    if (q.get("text") != null) vo.setText(q.get("text").toString());
+                    // options 暂不映射,请根据实际返回格式补充
+                    questions.add(vo);
+                }
+            }
+            return Result.success(questions);
+        } catch (Exception e) {
+            return Result.error("AI生成题目失败: " + e.getMessage());
+        }
+    }
+}

+ 104 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/InteractionLogController.java

@@ -0,0 +1,104 @@
+package com.etotem.cfc.controller.family;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AddInteractionDTO;
+import com.etotem.cfc.dto.InteractionLogVO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.InteractionLogService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "互动记录管理", description = "家庭成员互动记录 CRUD")
+@RestController
+@RequestMapping("/api/family/interaction")
+public class InteractionLogController {
+
+    @Resource
+    private InteractionLogService interactionLogService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FamilyMemberService familyMemberService;
+
+ @Operation(summary = "添加互动记录")
+ @PostMapping("/add")
+ public Result<InteractionLogVO> addInteraction(@RequestBody AddInteractionDTO dto,
+  @RequestAttribute("userId") Long userId) {
+  if (userId == null) {
+    return Result.error("请先登录");
+  }
+  if (dto.getFamilyId() == null) {
+    User user = userMapper.selectById(userId);
+    if (user == null || user.getFamilyId() == null) {
+      return Result.noFamily("请先创建或加入家庭");
+    }
+    dto.setFamilyId(user.getFamilyId());
+  }
+  if (!familyMemberService.isCallerInFamily(dto.getFamilyId(), userId)) {
+    return Result.error("无权操作其他家庭");
+  }
+  if (dto.getFromMemberId() != null && !familyMemberService.isCallerInSameFamily(dto.getFromMemberId(), userId)) {
+    return Result.error("无权操作其他家庭成员");
+  }
+  if (dto.getToMemberId() != null && !familyMemberService.isCallerInSameFamily(dto.getToMemberId(), userId)) {
+    return Result.error("无权操作其他家庭成员");
+  }
+  try {
+   InteractionLogVO vo = interactionLogService.addInteraction(dto);
+   return Result.success(vo);
+  } catch (IllegalArgumentException e) {
+    return Result.error(e.getMessage());
+  } catch (RuntimeException e) {
+    return Result.error(e.getMessage());
+  }
+ }
+
+@Operation(summary = "查询互动记录列表")
+@PostMapping("/list")
+public Result<Page<InteractionLogVO>> listInteractions(@RequestBody Map<String, Object> body,
+ @RequestAttribute("userId") Long userId,
+ @RequestAttribute(value = "familyId", required = false) Long familyId) {
+ if (userId == null) {
+  return Result.error("请先登录");
+ }
+         if (familyId == null) {
+             return Result.noFamily("请先创建或加入家庭");
+         }
+         Long fromMemberId = ParamUtils.getLong(body.get("fromMemberId"));
+         Long toMemberId = ParamUtils.getLong(body.get("toMemberId"));
+         Integer page = body.get("page") != null
+                 ? Integer.valueOf(body.get("page").toString()) : 1;
+         Integer size = body.get("size") != null
+                 ? Integer.valueOf(body.get("size").toString()) : 10;
+
+         if (!familyMemberService.isCallerInFamily(familyId, userId)) {
+           return Result.error("无权查看其他家庭的互动记录");
+         }
+        if (fromMemberId != null && !familyMemberService.isCallerInSameFamily(fromMemberId, userId)) {
+          return Result.error("无权查看其他家庭成员的互动记录");
+        }
+        if (toMemberId != null && !familyMemberService.isCallerInSameFamily(toMemberId, userId)) {
+          return Result.error("无权查看其他家庭成员的互动记录");
+        }
+
+        Page<InteractionLogVO> result = interactionLogService.listInteractions(
+                familyId, fromMemberId, toMemberId, page, size);
+        return Result.success(result);
+    }
+
+    @Operation(summary = "获取互动类型列表")
+    @PostMapping("/types")
+    public Result<Map<String, String>> getInteractionTypes() {
+        return Result.success(interactionLogService.getInteractionTypes());
+    }
+}

+ 58 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/ManualDimensionScoreController.java

@@ -0,0 +1,58 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ManualScoreSubmitDTO;
+import com.etotem.cfc.dto.ManualScoreVO;
+import com.etotem.cfc.service.ManualDimensionScoreService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "五维手动填分", description = "直接填写 0-100 分,跳过问卷")
+@RestController
+@RequestMapping("/api/family/manual-score")
+public class ManualDimensionScoreController {
+
+    @Resource
+    private ManualDimensionScoreService manualScoreService;
+
+    @Operation(summary = "提交五维手动分数")
+    @PostMapping("/submit")
+    public Result<ManualScoreVO> submit(@RequestBody ManualScoreSubmitDTO dto,
+                                        @RequestAttribute("userId") Long userId) {
+        try {
+            return Result.success(manualScoreService.submit(dto, userId));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取最新手动填分记录")
+    @PostMapping("/latest")
+    public Result<ManualScoreVO> latest(@RequestBody(required = false) Map<String, Object> body,
+                                        @RequestAttribute("userId") Long userId,
+                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = body != null ? ParamUtils.getLong(body.get("memberId"), currentMemberId) : currentMemberId;
+        return Result.success(manualScoreService.getLatest(userId, memberId));
+    }
+
+    @Operation(summary = "获取手动填分历史")
+    @PostMapping("/history")
+    public Result<List<ManualScoreVO>> history(@RequestBody(required = false) Map<String, Object> body,
+                                               @RequestAttribute("userId") Long userId,
+                                               @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = body != null ? ParamUtils.getLong(body.get("memberId"), currentMemberId) : currentMemberId;
+        Integer limit = body != null && body.get("limit") != null
+                ? Integer.valueOf(body.get("limit").toString()) : 20;
+        return Result.success(manualScoreService.getHistory(userId, memberId, limit));
+    }
+}

+ 75 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/MbtiController.java

@@ -0,0 +1,75 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.*;
+import com.etotem.cfc.service.MbtiService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "MBTI 人格测评", description = "标准版 ~30题 + 16型画像 + 五维联动")
+@RestController
+@RequestMapping("/api/family/mbti")
+public class MbtiController {
+
+    @Resource
+    private MbtiService mbtiService;
+
+    @Operation(summary = "获取题库")
+    @PostMapping("/questions")
+    public Result<List<MbtiQuestionVO>> questions(@RequestAttribute("userId") Long userId) {
+        if (userId == null) return Result.error("请先登录");
+        return Result.success(mbtiService.getQuestions());
+    }
+
+    @Operation(summary = "提交答案计算类型")
+    @PostMapping("/submit")
+    public Result<MbtiResultVO> submit(@RequestBody SubmitMbtiDTO dto,
+                                       @RequestAttribute("userId") Long userId) {
+        if (userId == null) return Result.error("请先登录");
+        try {
+            return Result.success(mbtiService.submit(dto, userId));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取最新测评结果")
+    @PostMapping("/latest")
+    public Result<MbtiResultVO> latest(@RequestBody(required = false) Map<String, Object> body,
+                                       @RequestAttribute("userId") Long userId,
+                                       @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        if (userId == null) return Result.error("请先登录");
+        Long memberId = body != null ? ParamUtils.getLong(body.get("memberId"), currentMemberId) : currentMemberId;
+        return Result.success(mbtiService.getLatest(userId, memberId));
+    }
+
+    @Operation(summary = "获取指定类型画像")
+    @PostMapping("/profile")
+    public Result<MbtiProfileVO> profile(@RequestBody Map<String, Object> body,
+                                         @RequestAttribute("userId") Long userId) {
+        if (userId == null) return Result.error("请先登录");
+        String typeCode = body != null ? String.valueOf(body.get("typeCode")) : null;
+        if (typeCode == null) return Result.error("typeCode不能为空");
+        MbtiProfileVO vo = mbtiService.getProfile(typeCode.toUpperCase());
+        if (vo == null) return Result.error("类型不存在");
+        return Result.success(vo);
+    }
+
+    @Operation(summary = "获取测评历史")
+    @PostMapping("/history")
+    public Result<List<MbtiResultVO>> history(@RequestBody(required = false) Map<String, Object> body,
+                                              @RequestAttribute("userId") Long userId,
+                                              @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        if (userId == null) return Result.error("请先登录");
+        Long memberId = body != null ? ParamUtils.getLong(body.get("memberId"), currentMemberId) : currentMemberId;
+        Integer limit = body != null && body.get("limit") != null
+                ? Integer.valueOf(body.get("limit").toString()) : 20;
+        return Result.success(mbtiService.getHistory(userId, memberId, limit));
+    }
+}

+ 144 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/ParentController.java

@@ -0,0 +1,144 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CreateRewardDTO;
+import com.etotem.cfc.dto.RewardDTO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.entity.Wish;
+import com.etotem.cfc.mapper.WishMapper;
+import com.etotem.cfc.service.CfSpendDispatchService;
+import com.etotem.cfc.service.RewardService;
+import com.etotem.cfc.service.UserService;
+import javax.annotation.Resource;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/parent")
+public class ParentController {
+
+    @Resource
+    private RewardService rewardService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private WishMapper wishMapper;
+
+    /** F-5:家庭主账号心愿兑换扣减改投统一账本 cf_balance(本人自己的成员维度,幂等 refId = 心愿 ID) */
+    @Resource
+    private CfSpendDispatchService cfSpendDispatchService;
+
+    /**
+     * 家庭主账号心愿单 - 创建心愿(直接进入可用列表)
+     */
+    @PostMapping("/wishlist")
+    public Result<Long> createParentWishlist(@RequestAttribute("userId") Long userId,
+                                              @RequestBody CreateRewardDTO dto) {
+        // 家庭主账号直接创建奖励,状态为available
+        Long rewardId = rewardService.createReward(userId, dto);
+        return Result.success(rewardId);
+    }
+
+    /**
+     * 家庭主账号心愿单 - 获取列表(所有家庭成员的心愿)
+     */
+    @PostMapping("/wishlist/list")
+    public Result<List<RewardDTO>> getParentWishlist(@RequestAttribute("userId") Long userId) {
+        User user = userService.getUserInfo(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        
+        // 获取家庭所有可用的奖励(包括家庭成员创建的待审批心愿)
+        List<RewardDTO> rewards = rewardService.getFamilyRewardLibrary(user.getFamilyId());
+        return Result.success(rewards);
+    }
+
+    /**
+     * 家庭主账号心愿单 - 获取家庭心愿列表(路由兼容)
+     */
+    @PostMapping("/wishlist/family")
+    public Result<List<RewardDTO>> getFamilyWishlist(@RequestAttribute("userId") Long userId) {
+        User user = userService.getUserInfo(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        
+        List<RewardDTO> rewards = rewardService.getFamilyRewardLibrary(user.getFamilyId());
+        return Result.success(rewards);
+    }
+
+    /**
+     * 家庭主账号心愿单 - 审批家庭成员的心愿并填写积分
+     */
+    @PostMapping("/wishlist/{id}/approve")
+    public Result<Boolean> approveWishlist(@PathVariable Long id,
+                                            @RequestAttribute("userId") Long userId,
+                                            @RequestBody Map<String, Object> params) {
+        Integer pointsRequired = params.get("pointsRequired") != null ? (Integer) params.get("pointsRequired") : null;
+        
+        if (pointsRequired == null || pointsRequired <= 0) {
+            return Result.error("请填写有效的积分");
+        }
+        
+        boolean success = rewardService.approveWishlist(id, userId, pointsRequired);
+        return Result.success(success);
+    }
+
+    /**
+     * 家庭主账号心愿单 - 兑换家庭主账号的心愿
+     */
+    @PostMapping("/wishlist/{id}/exchange")
+    public Result<Map<String, Object>> exchangeParentWishlist(@PathVariable Long id,
+                                                               @RequestAttribute("userId") Long userId) {
+        User user = userService.getUserInfo(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        Wish wish = wishMapper.selectById(id);
+        if (wish == null) {
+            return Result.error("心愿不存在");
+        }
+
+        String status = wish.getStatus();
+        if (!"active".equals(status) && !"approved".equals(status)) {
+            return Result.error("心愿当前状态不可兑换(" + status + ")");
+        }
+
+        if (wish.getPointsRequired() == null || wish.getPointsRequired() <= 0) {
+            return Result.error("心愿未设置积分");
+        }
+
+        // F-5:余额与扣减都改投统一账本 cf_balance(不再读/写 users.total_points)
+        int currentBalance = cfSpendDispatchService.getAvailableForUser(userId);
+        if (currentBalance < wish.getPointsRequired()) {
+            return Result.error("积分不足,需要" + wish.getPointsRequired() + "积分,当前" + currentBalance + "积分");
+        }
+
+        try {
+            cfSpendDispatchService.spendForUser(userId, wish.getPointsRequired(),
+                    "wish_exchange", wish.getId(), "心愿兑换:" + wish.getTitle());
+        } catch (RuntimeException e) {
+            return Result.error("积分扣除失败:" + e.getMessage());
+        }
+
+        wish.setStatus("exchanging");
+        wish.setPointsDeductedAt(new Date());
+        wish.setExchangeRequestedAt(new Date());
+        wish.setUpdatedAt(new Date());
+        wishMapper.updateById(wish);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("success", true);
+        result.put("newBalance", currentBalance - wish.getPointsRequired());
+        result.put("wishId", wish.getId());
+        return Result.success(result);
+    }
+}

+ 78 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/PointsController.java

@@ -0,0 +1,78 @@
+package com.etotem.cfc.controller.family;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.PointsLog;
+import com.etotem.cfc.service.PointsService;
+import javax.annotation.Resource;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.HashMap;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@RestController
+@RequestMapping("/api/points")
+public class PointsController {
+
+    @Resource
+    private PointsService pointsService;
+
+    @PostMapping("/balance")
+    public Result<Map<String, Object>> getBalance(@RequestBody Map<String, Object> params,
+                                                  @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = params.get("memberId") != null ? ParamUtils.getLong(params.get("memberId")) : currentMemberId;
+        Map<String, Object> balance = pointsService.getBalance(memberId);
+        return Result.success(balance);
+    }
+
+    @PostMapping("/logs")
+    public Result<Page<PointsLog>> getPointsLogs(@RequestBody Map<String, Object> params,
+                                                 @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = params.get("memberId") != null ? ParamUtils.getLong(params.get("memberId")) : currentMemberId;
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 10;
+        String startTime = params.get("startTime") != null ? params.get("startTime").toString() : null;
+        String endTime = params.get("endTime") != null ? params.get("endTime").toString() : null;
+        Page<PointsLog> logs = pointsService.getPointsLogs(memberId, page, size, startTime, endTime);
+        return Result.success(logs);
+    }
+
+    @PostMapping("/adjust")
+    public Result<Map<String, Object>> adjustPoints(@RequestBody Map<String, Object> params,
+                                                    @RequestAttribute("userId") Long userId,
+                                                    @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = params.get("memberId") != null ? ParamUtils.getLong(params.get("memberId")) : currentMemberId;
+        Integer amount = Integer.valueOf(params.get("amount").toString());
+        String reason = params.get("reason") != null ? params.get("reason").toString() : null;
+        String password = params.get("password") != null ? params.get("password").toString() : null;
+        // 可选幂等键:同一键重复提交只生效一次(F19 管理员调整)
+        String idempotencyKey = params.get("idempotencyKey") != null ? params.get("idempotencyKey").toString() : null;
+        Map<String, Object> result = pointsService.adjustPoints(memberId, amount, reason, password, userId, idempotencyKey);
+        return Result.success(result);
+    }
+
+    @PostMapping("/system-balance")
+    public Result<Map<String, Object>> getSystemBalance(@RequestBody Map<String, Object> params,
+                                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = params.get("memberId") != null ? ParamUtils.getLong(params.get("memberId")) : currentMemberId;
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        int balance = pointsService.getCfPointsBalance(memberId);
+        Map<String, Object> result = new HashMap<>();
+        result.put("systemPoints", balance);
+        return Result.success(result);
+    }
+
+    @PostMapping("/logs-by-category")
+    public Result<Page<PointsLog>> getPointsLogsByCategory(@RequestBody Map<String, Object> params,
+                                                          @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = params.get("memberId") != null ? ParamUtils.getLong(params.get("memberId")) : currentMemberId;
+        String category = params.get("category") != null ? params.get("category").toString() : null;
+        Integer page = params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
+        Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 10;
+        Page<PointsLog> logs = pointsService.getPointsLogsByCategory(memberId, category, page, size);
+        return Result.success(logs);
+    }
+}

+ 128 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/RelationshipQualityController.java

@@ -0,0 +1,128 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.dto.HealthAlertVO;
+import com.etotem.cfc.dto.MilestoneVO;
+import com.etotem.cfc.dto.RelationshipScoreVO;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.RelationshipQualityService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+@Tag(name = "关系质量管理", description = "家庭成员关系质量评分、健康预警、里程碑")
+@RestController
+@RequestMapping("/api/family/relationship")
+public class RelationshipQualityController {
+
+    @Resource
+    private RelationshipQualityService relationshipQualityService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Operation(summary = "获取家庭成员关系质量评分")
+    @PostMapping("/scores")
+    public Result<List<RelationshipScoreVO>> getScores(@RequestAttribute(value = "familyId", required = false) Long familyId) {
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+        List<RelationshipScoreVO> scores = relationshipQualityService.getScores(familyId);
+        return Result.success(scores);
+    }
+
+    @Operation(summary = "计算并保存成员关系质量评分")
+    @PostMapping("/calculate")
+    public Result<RelationshipScoreVO> calculateScore(@RequestBody Map<String, Object> body,
+                                                      @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        if (memberId == null) {
+            return Result.error("memberId不能为空");
+        }
+        try {
+            RelationshipScoreVO vo = relationshipQualityService.calculateScore(memberId);
+            return Result.success(vo);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "获取健康预警列表")
+    @PostMapping("/health-alerts")
+    public Result<List<HealthAlertVO>> getHealthAlerts(@RequestBody Map<String, Object> body,
+                                                      @RequestAttribute("userId") Long userId,
+                                                      @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long familyIdFromAttr = getFamilyIdFromRequest(userId, body, familyId);
+        if (familyIdFromAttr == null) {
+            return Result.success(Collections.emptyList());
+        }
+        List<HealthAlertVO> alerts = relationshipQualityService.getHealthAlerts(familyIdFromAttr);
+        return Result.success(alerts);
+    }
+
+    @Operation(summary = "获取即将到来的里程碑")
+    @PostMapping("/milestones")
+    public Result<List<MilestoneVO>> getMilestones(@RequestBody Map<String, Object> body,
+                                                    @RequestAttribute("userId") Long userId,
+                                                    @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long familyIdFromAttr = getFamilyIdFromRequest(userId, body, familyId);
+        if (familyIdFromAttr == null) {
+            return Result.success(Collections.emptyList());
+        }
+        Integer daysAhead = body != null && body.get("daysAhead") != null
+                ? Integer.valueOf(body.get("daysAhead").toString()) : 7;
+        List<MilestoneVO> milestones = relationshipQualityService.getMilestones(familyIdFromAttr, daysAhead);
+        return Result.success(milestones);
+    }
+
+/**
+     * 解析请求中的家庭ID:优先request attribute,最后回退用户所属家庭
+     * 不再接受 body 中的 familyId,改为从登录用户派生
+     */
+    private Long getFamilyIdFromRequest(Long userId, Map<String, Object> body, Long familyId) {
+        if (familyId != null) {
+            return familyId;
+        }
+        if (userId != null) {
+            User user = userMapper.selectById(userId);
+            if (user != null) {
+                return user.getFamilyId();
+            }
+        }
+        return null;
+    }
+
+    @Operation(summary = "获取以指定成员为中心的所有成员关系(pairwise)")
+    @PostMapping("/pairwise")
+    public Result<List<FamilyMemberVO>> getPairwise(@RequestBody Map<String, Object> body,
+                                                    @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("请先登录");
+        }
+        Long centerMemberId = ParamUtils.getLong(body.get("centerMemberId"));
+        if (centerMemberId == null) {
+            return Result.error("centerMemberId不能为空");
+        }
+        Long familyId = getFamilyIdFromRequest(userId, body, null);
+        try {
+            List<FamilyMemberVO> members = relationshipQualityService.getPairwiseRelationships(centerMemberId, familyId);
+            return Result.success(members);
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+}

+ 110 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/RelationshipQuestionnaireController.java

@@ -0,0 +1,110 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.GenerateQuestionnaireDTO;
+import com.etotem.cfc.dto.QuestionnaireSnapshotVO;
+import com.etotem.cfc.dto.SubmitQuestionnaireDTO;
+import com.etotem.cfc.entity.RelationshipQuestionnaireResponse;
+import com.etotem.cfc.entity.RelationshipQuestionnaireSnapshot;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.RelationshipQuestionnaireService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "关系问卷管理", description = "AI 生成问卷、提交答案、查询历史")
+@RestController
+@RequestMapping("/api/family/questionnaire")
+public class RelationshipQuestionnaireController {
+
+    @Resource
+    private RelationshipQuestionnaireService questionnaireService;
+
+    @Resource
+    private FamilyMemberService familyMemberService;
+
+@Operation(summary = "AI 生成关系问卷")
+@PostMapping("/generate")
+public Result<QuestionnaireSnapshotVO> generateQuestionnaire(@RequestBody GenerateQuestionnaireDTO dto,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ dto.setRespondentId(userId);
+ if (dto.getMemberId() != null && !familyMemberService.isCallerInSameFamily(dto.getMemberId(), userId)) {
+   return Result.error("无权操作其他家庭成员");
+ }
+ try {
+   QuestionnaireSnapshotVO vo = questionnaireService.generateQuestionnaire(dto);
+   return Result.success(vo);
+ } catch (IllegalArgumentException e) {
+   return Result.error(e.getMessage());
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "提交问卷答案")
+@PostMapping("/submit")
+public Result<RelationshipQuestionnaireResponse> submitQuestionnaire(@RequestBody SubmitQuestionnaireDTO dto,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ dto.setRespondentId(userId);
+ if (dto.getSnapshotId() != null) {
+    RelationshipQuestionnaireSnapshot snapshot = questionnaireService.getSnapshotById(dto.getSnapshotId());
+   if (snapshot != null && !familyMemberService.isCallerInSameFamily(snapshot.getFamilyMemberId(), userId)) {
+     return Result.error("无权操作其他家庭的问卷");
+   }
+ }
+ try {
+   RelationshipQuestionnaireResponse resp = questionnaireService.submitQuestionnaire(dto);
+   return Result.success(resp);
+ } catch (IllegalArgumentException e) {
+   return Result.error(e.getMessage());
+ } catch (RuntimeException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "获取最新问卷快照")
+@PostMapping("/snapshot/{memberId}")
+public Result<QuestionnaireSnapshotVO> getSnapshot(@PathVariable Long memberId,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ if (!familyMemberService.isCallerInSameFamily(memberId, userId)) {
+   return Result.error("无权查看其他家庭的问卷");
+ }
+ try {
+   QuestionnaireSnapshotVO vo = questionnaireService.getSnapshot(memberId);
+   return Result.success(vo);
+ } catch (IllegalArgumentException e) {
+   return Result.error(e.getMessage());
+ }
+}
+
+@Operation(summary = "获取问卷历史记录")
+@PostMapping("/history/{memberId}")
+public Result<List<RelationshipQuestionnaireResponse>> getHistory(@PathVariable Long memberId,
+ @RequestAttribute("userId") Long userId) {
+ if (userId == null) {
+   return Result.error("请先登录");
+ }
+ if (!familyMemberService.isCallerInSameFamily(memberId, userId)) {
+   return Result.error("无权查看其他家庭的问卷历史");
+ }
+ try {
+   List<RelationshipQuestionnaireResponse> history = questionnaireService.getHistory(memberId);
+   return Result.success(history);
+ } catch (IllegalArgumentException e) {
+   return Result.error(e.getMessage());
+ }
+}
+}

+ 114 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/family/TeacherFamilyBindingController.java

@@ -0,0 +1,114 @@
+package com.etotem.cfc.controller.family;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.TeacherFamilyBindingRequest;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.TeacherFamilyBindingRequestService;
+import com.etotem.cfc.service.WechatService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * 规划师绑定家庭审批接口
+ * 家庭主账号查看/审批规划师的绑定申请
+ */
+@Tag(name = "规划师绑定审批", description = "家庭主账号审批规划师绑定家庭申请")
+@RestController
+@RequestMapping("/api/family/teacher-bindings")
+public class TeacherFamilyBindingController {
+
+    @Resource
+    private TeacherFamilyBindingRequestService bindingRequestService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private WechatService wechatService;
+
+    /**
+     * 获取自家待审批的规划师绑定申请列表
+     */
+    @Operation(summary = "获取待审批列表")
+    @PostMapping("/pending")
+    public Result<List<TeacherFamilyBindingRequest>> getPending(@RequestAttribute("userId") Long userId) {
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return Result.noFamily("请先创建或加入家庭");
+        }
+
+        List<TeacherFamilyBindingRequest> list = bindingRequestService.getPendingByFamily(user.getFamilyId());
+        return Result.success(list);
+    }
+
+    /**
+     * 审批通过
+     */
+    @Operation(summary = "审批通过")
+    @PostMapping("/approve")
+    public Result<String> approve(@RequestAttribute("userId") Long userId,
+                                  @RequestBody Map<String, Object> body) {
+        Long requestId = ParamUtils.getLong(body.get("requestId"));
+        try {
+            bindingRequestService.approve(requestId, userId);
+            return Result.success("审批通过");
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 审批拒绝
+     */
+    @Operation(summary = "审批拒绝")
+    @PostMapping("/reject")
+    public Result<String> reject(@RequestAttribute("userId") Long userId,
+                                 @RequestBody Map<String, Object> body) {
+        Long requestId = ParamUtils.getLong(body.get("requestId"));
+        String reason = body.get("reason") != null ? body.get("reason").toString() : null;
+        try {
+            bindingRequestService.reject(requestId, userId, reason);
+            return Result.success("已拒绝");
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 规划师查看自己的绑定请求列表
+     */
+    @Operation(summary = "我的绑定请求")
+    @PostMapping("/my-requests")
+    public Result<List<TeacherFamilyBindingRequest>> myRequests(@RequestAttribute("userId") Long userId) {
+        List<TeacherFamilyBindingRequest> list = bindingRequestService.getByTeacher(userId);
+        return Result.success(list);
+    }
+
+    /**
+     * 规划师撤销自己的申请
+     */
+    @Operation(summary = "撤销申请")
+    @PostMapping("/cancel")
+    public Result<String> cancel(@RequestAttribute("userId") Long userId,
+                                  @RequestBody Map<String, Object> body) {
+        Long requestId = ParamUtils.getLong(body.get("requestId"));
+        try {
+            bindingRequestService.cancel(requestId, userId);
+            return Result.success("已撤销");
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+}

+ 98 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/fatloss/FatDietController.java

@@ -0,0 +1,98 @@
+package com.etotem.cfc.controller.fatloss;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FatDietRecord;
+import com.etotem.cfc.service.FatDietService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "减脂-饮食记录")
+@RestController
+@RequestMapping("/api/fatloss/diet")
+public class FatDietController {
+
+    @Resource
+    private FatDietService fatDietService;
+
+    @Operation(summary = "获取饮食记录列表")
+    @PostMapping("/list")
+    public Result<List<FatDietRecord>> list(@RequestBody(required = false) Map<String, Object> params,
+                                            @RequestAttribute("userId") Long userId,
+                                            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params == null ? null : params.get("memberId"), currentMemberId);
+        if (memberId == null) return Result.error("memberId不能为空");
+        Date startDate = parseDateParam(params == null ? null : params.get("startDate"));
+        Date endDate = parseDateParam(params == null ? null : params.get("endDate"));
+        return Result.success(fatDietService.list(memberId, startDate, endDate));
+    }
+
+    @Operation(summary = "创建饮食记录")
+    @PostMapping("/create")
+    public Result<FatDietRecord> create(@RequestBody Map<String, Object> params,
+                                        @RequestAttribute("userId") Long userId,
+                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        FatDietRecord record = new FatDietRecord();
+        record.setMemberId(ParamUtils.getLong(params.get("memberId"), currentMemberId));
+        record.setMealType((String) params.get("mealType"));
+        record.setFoodName((String) params.get("foodName"));
+        record.setFoodWeight(toBigDecimal(params.get("foodWeight")));
+        record.setCalories(toInteger(params.get("calories")));
+        record.setProtein(toBigDecimal(params.get("protein")));
+        record.setFat(toBigDecimal(params.get("fat")));
+        record.setCarbs(toBigDecimal(params.get("carbs")));
+        record.setEatDate(parseDateParam(params.get("eatDate")));
+        record.setRemark((String) params.get("remark"));
+        if (record.getMemberId() == null) return Result.error("memberId不能为空");
+        if (record.getEatDate() == null) return Result.error("进餐日期不能为空");
+        if (record.getFoodName() == null || record.getFoodName().isEmpty()) return Result.error("食物名称不能为空");
+        return Result.success(fatDietService.create(record));
+    }
+
+    @Operation(summary = "删除饮食记录")
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) return Result.error("id不能为空");
+        return Result.success(fatDietService.delete(id));
+    }
+
+    @Operation(summary = "获取当日总热量")
+    @PostMapping("/calories-summary")
+    public Result<Integer> caloriesSummary(@RequestBody(required = false) Map<String, Object> params,
+                                           @RequestAttribute("userId") Long userId,
+                                           @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params == null ? null : params.get("memberId"), currentMemberId);
+        if (memberId == null) return Result.error("memberId不能为空");
+        Date date = parseDateParam(params == null ? null : params.get("date"));
+        if (date == null) date = new Date();
+        return Result.success(fatDietService.sumCalories(memberId, date));
+    }
+
+    private BigDecimal toBigDecimal(Object obj) {
+        if (obj == null) return null;
+        String s = obj.toString().trim();
+        if (s.isEmpty()) return null;
+        try { return new BigDecimal(s); } catch (NumberFormatException e) { return null; }
+    }
+
+    private Integer toInteger(Object obj) {
+        if (obj == null) return 0;
+        String s = obj.toString().trim();
+        if (s.isEmpty()) return 0;
+        try { return Integer.parseInt(s); } catch (NumberFormatException e) { return 0; }
+    }
+
+    private Date parseDateParam(Object obj) {
+        if (obj == null) return null;
+        try { return new SimpleDateFormat("yyyy-MM-dd").parse(obj.toString()); } catch (Exception e) { return null; }
+    }
+}

+ 83 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/fatloss/FatExerciseController.java

@@ -0,0 +1,83 @@
+package com.etotem.cfc.controller.fatloss;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FatExerciseRecord;
+import com.etotem.cfc.service.FatExerciseService;
+import com.etotem.cfc.util.ParamUtils;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Tag(name = "减脂-运动记录")
+@RestController
+@RequestMapping("/api/fatloss/exercise")
+public class FatExerciseController {
+
+    @Resource
+    private FatExerciseService fatExerciseService;
+
+    @Operation(summary = "获取运动记录列表")
+    @PostMapping("/list")
+    public Result<List<FatExerciseRecord>> list(@RequestBody(required = false) Map<String, Object> params,
+                                                @RequestAttribute("userId") Long userId,
+                                                @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(params == null ? null : params.get("memberId"), currentMemberId);
+        if (memberId == null) return Result.error("memberId不能为空");
+        Date startDate = parseDateParam(params == null ? null : params.get("startDate"));
+        Date endDate = parseDateParam(params == null ? null : params.get("endDate"));
+        return Result.success(fatExerciseService.list(memberId, startDate, endDate));
+    }
+
+    @Operation(summary = "创建运动记录")
+    @PostMapping("/create")
+    public Result<FatExerciseRecord> create(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("userId") Long userId,
+                                            @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        FatExerciseRecord record = new FatExerciseRecord();
+        record.setMemberId(ParamUtils.getLong(params.get("memberId"), currentMemberId));
+        record.setExerciseType((String) params.get("exerciseType"));
+        record.setDurationMin(toInteger(params.get("durationMin")));
+        record.setDistanceKm(toBigDecimal(params.get("distanceKm")));
+        record.setCaloriesBurned(toInteger(params.get("caloriesBurned")));
+        record.setExerciseDate(parseDateParam(params.get("exerciseDate")));
+        record.setRemark((String) params.get("remark"));
+        if (record.getMemberId() == null) return Result.error("memberId不能为空");
+        if (record.getExerciseDate() == null) return Result.error("运动日期不能为空");
+        if (record.getExerciseType() == null || record.getExerciseType().isEmpty()) return Result.error("运动类型不能为空");
+        return Result.success(fatExerciseService.create(record));
+    }
+
+    @Operation(summary = "删除运动记录")
+    @PostMapping("/delete")
+    public Result<Boolean> delete(@RequestBody Map<String, Object> params) {
+        Long id = ParamUtils.getLong(params.get("id"));
+        if (id == null) return Result.error("id不能为空");
+        return Result.success(fatExerciseService.delete(id));
+    }
+
+    private BigDecimal toBigDecimal(Object obj) {
+        if (obj == null) return null;
+        String s = obj.toString().trim();
+        if (s.isEmpty()) return null;
+        try { return new BigDecimal(s); } catch (NumberFormatException e) { return null; }
+    }
+
+    private Integer toInteger(Object obj) {
+        if (obj == null) return 0;
+        String s = obj.toString().trim();
+        if (s.isEmpty()) return 0;
+        try { return Integer.parseInt(s); } catch (NumberFormatException e) { return 0; }
+    }
+
+    private Date parseDateParam(Object obj) {
+        if (obj == null) return null;
+        try { return new SimpleDateFormat("yyyy-MM-dd").parse(obj.toString()); } catch (Exception e) { return null; }
+    }
+}

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff