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

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

Agnes Agent 2 часов назад
Родитель
Сommit
7a248fcb3f
100 измененных файлов с 13644 добавлено и 0 удалено
  1. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskMapper.java
  2. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationEdgeMapper.java
  3. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationExecutionMapper.java
  4. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationFlowMapper.java
  5. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationNodeInstanceMapper.java
  6. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskPlanInstanceMapper.java
  7. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskPlanItemMapper.java
  8. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskReminderConfigMapper.java
  9. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplateItemMapper.java
  10. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplateMapper.java
  11. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplatePackageMapper.java
  12. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherFamilyBindingRequestMapper.java
  13. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherMapper.java
  14. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherMessageMapper.java
  15. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamAwardRecordMapper.java
  16. 64 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamProfitStatsMapper.java
  17. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamShareRecordMapper.java
  18. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamStarSnapshotMapper.java
  19. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TianpanDailyFortuneMapper.java
  20. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TianpanMemberAnnualEnergyMapper.java
  21. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TongueRecordMapper.java
  22. 40 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TrainingPlanMapper.java
  23. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/TrialMembershipMapper.java
  24. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UnlockGateMapper.java
  25. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UpgradeServiceMapper.java
  26. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserAddressMapper.java
  27. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserAppUsageMapper.java
  28. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserConsentRecordMapper.java
  29. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserContentWeightMapper.java
  30. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserCurrentFoodRecommendMapper.java
  31. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserDataPermissionMapper.java
  32. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserFoodPreferenceMapper.java
  33. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserIntentMapper.java
  34. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserMapper.java
  35. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserNotificationMapper.java
  36. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserNutritionProfileMapper.java
  37. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserOperationLogMapper.java
  38. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserPlatformBalanceMapper.java
  39. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserProfileHistoryMapper.java
  40. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserRfmTagMapper.java
  41. 13 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserShortcutConfigMapper.java
  42. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/UserTriggerRuleMapper.java
  43. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/VerificationCodeMapper.java
  44. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/VirtualGoodsConfigMapper.java
  45. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/WishMapper.java
  46. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/WithdrawalRequestMapper.java
  47. 25 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/XiaomiHealthTokenMapper.java
  48. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/ZodiacConfigMapper.java
  49. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/ZodiacPairingMapper.java
  50. 11 0
      cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboChild.java
  51. 86 0
      cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferCalculator.java
  52. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferDef.java
  53. 24 0
      cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferResult.java
  54. 24 0
      cfc-backend/src/main/java/com/etotem/cfc/pricing/LineItem.java
  55. 841 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AIService.java
  56. 378 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AccountCleanupService.java
  57. 25 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivationQuotaService.java
  58. 316 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityAdminService.java
  59. 148 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityCheckinBoostService.java
  60. 144 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityCheckinService.java
  61. 144 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityEnrollService.java
  62. 100 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityFeedbackService.java
  63. 67 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityMaterialService.java
  64. 345 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityOrderService.java
  65. 138 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityPosterTemplateService.java
  66. 155 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityProvisionService.java
  67. 481 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityRegistrationService.java
  68. 674 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityService.java
  69. 155 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityTagService.java
  70. 437 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityTeamService.java
  71. 187 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AdminGuidePopupService.java
  72. 131 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AdminReferralTreeService.java
  73. 199 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AfterSalesService.java
  74. 69 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AiCoachHandoffService.java
  75. 348 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AiContextService.java
  76. 1198 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java
  77. 438 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AicdsDetectionService.java
  78. 731 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AicdsGatewayService.java
  79. 280 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticleAudioService.java
  80. 52 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticleCategoryService.java
  81. 294 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticleCommentService.java
  82. 89 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticlePermissionService.java
  83. 1571 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticleService.java
  84. 176 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentAppointmentService.java
  85. 421 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentComparisonService.java
  86. 54 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentExecutionService.java
  87. 306 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentOrderService.java
  88. 95 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPermissionService.java
  89. 109 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPlanGenerator.java
  90. 62 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPlanRuleService.java
  91. 35 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentProductService.java
  92. 131 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentQuotaService.java
  93. 519 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentService.java
  94. 35 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AttributionAdjustService.java
  95. 43 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AttributionAnalysisService.java
  96. 35 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AttributionPlanService.java
  97. 76 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AuditLogService.java
  98. 132 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AuthProfileService.java
  99. 309 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AuthoritativeFoodImportService.java
  100. 268 0
      cfc-backend/src/main/java/com/etotem/cfc/service/BadgeService.java

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskMapper.java

@@ -0,0 +1,14 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.Task;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+@Mapper
+public interface TaskMapper extends BaseMapper<Task> {
+
+    @Select("SELECT * FROM tasks WHERE source_type = #{sourceType} AND source_id = #{sourceId} LIMIT 1")
+    Task selectBySource(@Param("sourceType") String sourceType, @Param("sourceId") Long sourceId);
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationEdgeMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskOrchestrationEdge;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskOrchestrationEdgeMapper extends BaseMapper<TaskOrchestrationEdge> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationExecutionMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskOrchestrationExecution;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskOrchestrationExecutionMapper extends BaseMapper<TaskOrchestrationExecution> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationFlowMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskOrchestrationFlow;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskOrchestrationFlowMapper extends BaseMapper<TaskOrchestrationFlow> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskOrchestrationNodeInstanceMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskOrchestrationNodeInstance;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskOrchestrationNodeInstanceMapper extends BaseMapper<TaskOrchestrationNodeInstance> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskPlanInstanceMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskPlanInstance;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskPlanInstanceMapper extends BaseMapper<TaskPlanInstance> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskPlanItemMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskPlanItem;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskPlanItemMapper extends BaseMapper<TaskPlanItem> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskReminderConfigMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskReminderConfig;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskReminderConfigMapper extends BaseMapper<TaskReminderConfig> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplateItemMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskTemplateItem;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskTemplateItemMapper extends BaseMapper<TaskTemplateItem> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplateMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskTemplate;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskTemplateMapper extends BaseMapper<TaskTemplate> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TaskTemplatePackageMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TaskTemplatePackage;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TaskTemplatePackageMapper extends BaseMapper<TaskTemplatePackage> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherFamilyBindingRequestMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TeacherFamilyBindingRequest;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TeacherFamilyBindingRequestMapper extends BaseMapper<TeacherFamilyBindingRequest> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.Teacher;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TeacherMapper extends BaseMapper<Teacher> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeacherMessageMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TeacherMessage;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TeacherMessageMapper extends BaseMapper<TeacherMessage> {
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamAwardRecordMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TeamAwardRecord;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 团队奖流水 Mapper(规格 §7.4,MyBatis-Plus)。
+ */
+@Mapper
+public interface TeamAwardRecordMapper extends BaseMapper<TeamAwardRecord> {
+}

+ 64 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamProfitStatsMapper.java

@@ -0,0 +1,64 @@
+package com.etotem.cfc.mapper;
+
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+import java.util.Date;
+
+/**
+ * 团队星级重评聚合统计(§4.3 业绩分数据源)。
+ *
+ * <p>规格:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md}
+ * §4.3 星级 = 直接×50% + 团队×40% + 推荐×10% + §4.3/#15 团队直推口径
+ * (直接邀请加入团队 + 成交首个服务或商品单即算 1 个直推)。</p>
+ */
+@Mapper
+public interface TeamProfitStatsMapper {
+
+    /**
+     * 直接服务收入(分):本人作为服务提供者(规划师/测评师)滚动窗口内已结算服务费。
+     */
+    @Select("SELECT COALESCE(SUM(ss.service_fee), 0) FROM service_settlements ss "
+            + "WHERE ss.provider_id = #{userId} AND ss.status = 'settled' "
+            + "AND ss.created_at >= #{windowStart}")
+    long selectDirectServiceAmountCent(@Param("userId") long userId, @Param("windowStart") Date windowStart);
+
+    /**
+     * 团队服务收入(分):本人团队(distribution_relations 子树)滚动窗口内已结算服务费,
+     * 且该服务订单实际发放了 F03a 直接销售奖(§4.3,防空转)。
+     */
+    @Select("WITH RECURSIVE team_subtree AS ("
+            + "  SELECT user_id FROM distribution_relations WHERE user_id = #{userId}"
+            + "  UNION ALL"
+            + "  SELECT r.user_id FROM distribution_relations r"
+            + "    INNER JOIN team_subtree s ON r.parent_id = s.user_id"
+            + ") "
+            + "SELECT COALESCE(SUM(ss.service_fee), 0) FROM service_settlements ss "
+            + "WHERE ss.provider_id IN (SELECT user_id FROM team_subtree) "
+            + "AND ss.status = 'settled' AND ss.created_at >= #{windowStart} "
+            + "AND EXISTS (SELECT 1 FROM cf_balance_log bl "
+            + "            WHERE bl.ref_type = 'F03a' AND bl.ref_id = ss.assessment_order_id)")
+    long selectTeamServiceAmountCent(@Param("userId") long userId, @Param("windowStart") Date windowStart);
+
+    /**
+     * 推荐用户平台消费收入(分):被本人直接/间接推荐的用户滚动窗口内平台消费额(售价口径)。
+     */
+    @Select("SELECT COALESCE(SUM(l.amount_cent), 0) FROM ppoint_consumption_log l "
+            + "INNER JOIN referral_tree t ON t.child_id = l.user_id "
+            + "WHERE t.parent_id = #{userId} AND l.created_at >= #{windowStart}")
+    long selectReferralConsumeAmountCent(@Param("userId") long userId, @Param("windowStart") Date windowStart);
+
+    /**
+     * 团队直推有效新用户数(#15 拍板口径):本人直接邀请加入团队(distribution_relations
+     * parent_id=本人)且近 12 个月成交首个服务或商品单的成员数(首单即算、无金额门槛)。
+     */
+    @Select("SELECT COUNT(DISTINCT r.user_id) FROM distribution_relations r "
+            + "WHERE r.parent_id = #{userId} AND ("
+            + "  EXISTS (SELECT 1 FROM product_orders po WHERE po.buyer_id = r.user_id "
+            + "          AND po.status IN ('paid','completed') AND po.paid_at >= #{windowStart})"
+            + "  OR EXISTS (SELECT 1 FROM service_settlements ss WHERE ss.provider_id = r.user_id "
+            + "          AND ss.status = 'settled' AND ss.created_at >= #{windowStart})"
+            + ")")
+    int countDirectValidNewRefs(@Param("userId") long userId, @Param("windowStart") Date windowStart);
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamShareRecordMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TeamShareRecord;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 团队 8 份分佣流水 Mapper(规格 §7.3,MyBatis-Plus)。
+ */
+@Mapper
+public interface TeamShareRecordMapper extends BaseMapper<TeamShareRecord> {
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TeamStarSnapshotMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TeamStarSnapshot;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 团队成员星级月度快照(§7.6)。
+ */
+@Mapper
+public interface TeamStarSnapshotMapper extends BaseMapper<TeamStarSnapshot> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TianpanDailyFortuneMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TianpanDailyFortune;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TianpanDailyFortuneMapper extends BaseMapper<TianpanDailyFortune> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TianpanMemberAnnualEnergyMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TianpanMemberAnnualEnergy;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TianpanMemberAnnualEnergyMapper extends BaseMapper<TianpanMemberAnnualEnergy> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TongueRecordMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TongueRecord;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TongueRecordMapper extends BaseMapper<TongueRecord> {
+}

+ 40 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TrainingPlanMapper.java

@@ -0,0 +1,40 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TrainingPlan;
+import com.etotem.cfc.entity.TrainingPlanItem;
+import com.etotem.cfc.entity.TrainingPlanTask;
+import org.apache.ibatis.annotations.*;
+
+import java.util.List;
+
+@Mapper
+public interface TrainingPlanMapper extends BaseMapper<TrainingPlan> {
+
+    @Select("SELECT * FROM training_plans WHERE guide_id = #{guideId} ORDER BY created_at DESC")
+    List<TrainingPlan> selectByGuideId(@Param("guideId") Long guideId);
+
+    @Select("SELECT * FROM training_plans WHERE guide_id = #{guideId} AND child_id = #{childId} ORDER BY created_at DESC")
+    List<TrainingPlan> selectByGuideIdAndMemberId(@Param("guideId") Long guideId, @Param("childId") Long memberId);
+
+    @Select("SELECT * FROM training_plan_items WHERE plan_id = #{planId} ORDER BY sequence ASC")
+    List<TrainingPlanItem> selectItemsByPlanId(@Param("planId") Long planId);
+
+    @Insert("INSERT INTO training_plan_items (plan_id, sequence, dimension_key, suggestion, task_title, task_desc, minigame_code, article_id, task_points, deadline_days, status) " +
+            "VALUES (#{planId}, #{sequence}, #{dimensionKey}, #{suggestion}, #{taskTitle}, #{taskDesc}, #{minigameCode}, #{articleId}, #{taskPoints}, #{deadlineDays}, 'pending')")
+    @Options(useGeneratedKeys = true, keyProperty = "id")
+    Long insertItem(TrainingPlanItem item);
+
+    @Update("UPDATE training_plan_items SET task_title=#{taskTitle}, task_desc=#{taskDesc}, minigame_code=#{minigameCode}, article_id=#{articleId}, task_points=#{taskPoints}, deadline_days=#{deadlineDays} WHERE id=#{id}")
+    void updateItem(TrainingPlanItem item);
+
+    @Delete("DELETE FROM training_plan_items WHERE id = #{itemId}")
+    void deleteItem(@Param("itemId") Long itemId);
+
+    @Select("SELECT tpt.* FROM training_plan_tasks tpt WHERE tpt.plan_id = #{planId}")
+    List<TrainingPlanTask> selectTasksByPlanId(@Param("planId") Long planId);
+
+    @Insert("INSERT INTO training_plan_tasks (plan_id, plan_item_id, task_id, child_id, status) VALUES (#{planId}, #{planItemId}, #{taskId}, #{childId}, 'pending')")
+    @Options(useGeneratedKeys = true, keyProperty = "id")
+    void insertPlanTask(TrainingPlanTask planTask);
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/TrialMembershipMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.TrialMembership;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface TrialMembershipMapper extends BaseMapper<TrialMembership> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UnlockGateMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UnlockGate;
+
+public interface UnlockGateMapper extends BaseMapper<UnlockGate> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UpgradeServiceMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UpgradeService;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UpgradeServiceMapper extends BaseMapper<UpgradeService> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserAddressMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserAddress;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserAddressMapper extends BaseMapper<UserAddress> {
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserAppUsageMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserAppUsage;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+public interface UserAppUsageMapper extends BaseMapper<UserAppUsage> {
+
+    @Select("SELECT * FROM user_app_usage WHERE user_id = #{userId} AND app_key = #{appKey} LIMIT 1")
+    UserAppUsage selectByUserIdAndAppKey(@Param("userId") Long userId, @Param("appKey") String appKey);
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserConsentRecordMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserConsentRecord;
+
+public interface UserConsentRecordMapper extends BaseMapper<UserConsentRecord> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserContentWeightMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserContentWeight;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserContentWeightMapper extends BaseMapper<UserContentWeight> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserCurrentFoodRecommendMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserCurrentFoodRecommend;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserCurrentFoodRecommendMapper extends BaseMapper<UserCurrentFoodRecommend> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserDataPermissionMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserDataPermission;
+
+public interface UserDataPermissionMapper extends BaseMapper<UserDataPermission> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserFoodPreferenceMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserFoodPreference;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserFoodPreferenceMapper extends BaseMapper<UserFoodPreference> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserIntentMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserIntent;
+
+public interface UserIntentMapper extends BaseMapper<UserIntent> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.User;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserMapper extends BaseMapper<User> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserNotificationMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserNotification;
+
+public interface UserNotificationMapper extends BaseMapper<UserNotification> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserNutritionProfileMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserNutritionProfile;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserNutritionProfileMapper extends BaseMapper<UserNutritionProfile> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserOperationLogMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserOperationLog;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserOperationLogMapper extends BaseMapper<UserOperationLog> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserPlatformBalanceMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserPlatformBalance;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserPlatformBalanceMapper extends BaseMapper<UserPlatformBalance> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserProfileHistoryMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserProfileHistory;
+
+public interface UserProfileHistoryMapper extends BaseMapper<UserProfileHistory> {
+}

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserRfmTagMapper.java

@@ -0,0 +1,6 @@
+package com.etotem.cfc.mapper;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserRfmTag;
+import org.springframework.stereotype.Repository;
+@Repository
+public interface UserRfmTagMapper extends BaseMapper<UserRfmTag> {}

+ 13 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserShortcutConfigMapper.java

@@ -0,0 +1,13 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserShortcutConfig;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import java.util.List;
+
+public interface UserShortcutConfigMapper extends BaseMapper<UserShortcutConfig> {
+
+    @Select("SELECT * FROM user_shortcut_config WHERE user_id = #{userId} ORDER BY locked DESC, sort_order ASC")
+    List<UserShortcutConfig> selectByUserId(@Param("userId") Long userId);
+}

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserTriggerRuleMapper.java

@@ -0,0 +1,6 @@
+package com.etotem.cfc.mapper;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserTriggerRule;
+import org.springframework.stereotype.Repository;
+@Repository
+public interface UserTriggerRuleMapper extends BaseMapper<UserTriggerRule> {}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/VerificationCodeMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.VerificationCode;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface VerificationCodeMapper extends BaseMapper<VerificationCode> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/VirtualGoodsConfigMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.VirtualGoodsConfig;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface VirtualGoodsConfigMapper extends BaseMapper<VirtualGoodsConfig> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/WishMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.Wish;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface WishMapper extends BaseMapper<Wish> {
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/WithdrawalRequestMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.WithdrawalRequest;
+
+public interface WithdrawalRequestMapper extends BaseMapper<WithdrawalRequest> {
+}

+ 25 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/XiaomiHealthTokenMapper.java

@@ -0,0 +1,25 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.XiaomiHealthToken;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import java.util.List;
+
+/**
+ * 小米健康 token Mapper(X1 数据模型)。
+ */
+@Mapper
+public interface XiaomiHealthTokenMapper extends BaseMapper<XiaomiHealthToken> {
+
+    /** 根据家庭成员ID查找最新的 token 记录 */
+    @Select("SELECT * FROM xiaomi_health_tokens WHERE member_id = #{memberId} " +
+            "ORDER BY id DESC LIMIT 1")
+    XiaomiHealthToken selectLatestByMemberId(@Param("memberId") Long memberId);
+
+    /** 根据家庭成员ID查找所有 token 记录(按创建时间倒序) */
+    @Select("SELECT * FROM xiaomi_health_tokens WHERE member_id = #{memberId} " +
+            "ORDER BY id DESC")
+    List<XiaomiHealthToken> selectByMemberId(@Param("memberId") Long memberId);
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/ZodiacConfigMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.ZodiacConfig;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ZodiacConfigMapper extends BaseMapper<ZodiacConfig> {
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/ZodiacPairingMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.ZodiacPairing;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ZodiacPairingMapper extends BaseMapper<ZodiacPairing> {
+}

+ 11 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboChild.java

@@ -0,0 +1,11 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+/** 套餐内容子项:子商品 + 精确到子SKU + 数量 */
+@Data
+public class ComboChild {
+    private Long childProductId;
+    private Long childSkuId;
+    private Integer quantity;
+}

+ 86 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferCalculator.java

@@ -0,0 +1,86 @@
+package com.etotem.cfc.pricing;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 购物车套餐 offer 纯计算器(无 Spring 依赖,单测友好)。
+ *
+ * <p>算法:按 {@code (productId, skuId)} 聚合 {@link LineItem} 为池;对每个套餐定义计算
+ * 可覆盖组数 {@code groups = min over children(floor(haveQty/needQty))}(haveQty 严格按
+ * child_sku_id 匹配,缺失即 0);{@code originalTotal = Σ(组内 child 消耗数量×单价)×groups};
+ * {@code saving = originalTotal - comboPrice×groups};仅当 {@code saving>0 && groups>0} 才候选;
+ * 取 saving 最大(同额取先出现者),同一套餐重复只报一次;无命中返回 inactive。
+ */
+public class ComboOfferCalculator {
+
+    public ComboOfferResult compute(List<LineItem> lines, List<ComboOfferDef> defs) {
+        if (lines == null || lines.isEmpty() || defs == null || defs.isEmpty()) {
+            return ComboOfferResult.inactive();
+        }
+        // 池:key=(productId, skuId) -> {qty, unitPrice}
+        Map<String, PoolEntry> pool = new HashMap<>();
+        for (LineItem line : lines) {
+            if (line == null || line.getProductId() == null || line.getQuantity() == null) continue;
+            String key = key(line.getProductId(), line.getSkuId());
+            PoolEntry e = pool.get(key);
+            if (e == null) {
+                e = new PoolEntry();
+                e.qty = line.getQuantity();
+                e.unitPrice = line.getUnitPrice() != null ? line.getUnitPrice() : 0;
+                pool.put(key, e);
+            } else {
+                e.qty += line.getQuantity();
+            }
+        }
+
+        ComboOfferResult best = null;
+        Set<Long> seen = new HashSet<>();
+        for (ComboOfferDef def : defs) {
+            if (def == null || def.getComboSkuId() == null
+                    || def.getChildren() == null || def.getChildren().isEmpty()) continue;
+            if (!seen.add(def.getComboSkuId())) continue;   // 同一套餐重复只报一次
+            int groups = Integer.MAX_VALUE;
+            int perGroupOriginal = 0;
+            boolean valid = true;
+            for (ComboChild child : def.getChildren()) {
+                if (child == null || child.getChildProductId() == null) { valid = false; break; }
+                PoolEntry e = pool.get(key(child.getChildProductId(), child.getChildSkuId()));
+                int need = child.getQuantity() != null && child.getQuantity() > 0 ? child.getQuantity() : 1;
+                int have = e != null ? e.qty : 0;
+                groups = Math.min(groups, have / need);
+                perGroupOriginal += need * (e != null ? e.unitPrice : 0);
+            }
+            if (!valid || groups == Integer.MAX_VALUE || groups <= 0) continue;
+            int comboPrice = def.getComboPrice() != null ? def.getComboPrice() : 0;
+            int originalTotal = perGroupOriginal * groups;
+            int saving = originalTotal - comboPrice * groups;
+            if (saving <= 0) continue;   // 套餐价>=总和:不提示(原价结算)
+            ComboOfferResult cand = new ComboOfferResult();
+            cand.setActive(true);
+            cand.setComboSkuId(def.getComboSkuId());
+            cand.setComboName(def.getComboName());
+            cand.setGroups(groups);
+            cand.setOriginalTotal(originalTotal);
+            cand.setComboPrice(comboPrice);
+            cand.setSaving(saving);
+            if (best == null || cand.getSaving() > best.getSaving()) {
+                best = cand;   // 同额不替换 → 保留先出现者
+            }
+        }
+        return best != null ? best : ComboOfferResult.inactive();
+    }
+
+    private String key(Long productId, Long skuId) {
+        return productId + "_" + (skuId == null ? "" : skuId);
+    }
+
+    private static class PoolEntry {
+        int qty;
+        int unitPrice;
+    }
+}

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferDef.java

@@ -0,0 +1,14 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+import java.util.List;
+
+/** 购物车套餐 offer 定义:套餐SKU锚点 + 展示名 + 套餐价(分) + 内容清单 */
+@Data
+public class ComboOfferDef {
+    private Long comboSkuId;
+    private String comboName;
+    private Integer comboPrice;
+    private List<ComboChild> children;
+}

+ 24 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferResult.java

@@ -0,0 +1,24 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+/**
+ * 购物车套餐 offer 检测结果(只报最优一个):命中(节省额>0)时 active=true,
+ * 携带套餐SKU/展示名/可替换组数/原价合计/套餐价合计/节省额。
+ */
+@Data
+public class ComboOfferResult {
+    private boolean active;
+    private Long comboSkuId;
+    private String comboName;
+    private int groups;
+    private int originalTotal;
+    private int comboPrice;
+    private int saving;
+
+    public static ComboOfferResult inactive() {
+        ComboOfferResult r = new ComboOfferResult();
+        r.setActive(false);
+        return r;
+    }
+}

+ 24 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/LineItem.java

@@ -0,0 +1,24 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+/**
+ * 下单/结算口径的商品行:productId/skuId 为解析后身份(linked-SKU 转发一致),unitPrice 为结算单价(分)。
+ */
+@Data
+public class LineItem {
+    private Long productId;
+    private Long skuId;
+    private Integer quantity;
+    private Integer unitPrice;
+
+    public LineItem() {
+    }
+
+    public LineItem(Long productId, Long skuId, Integer quantity, Integer unitPrice) {
+        this.productId = productId;
+        this.skuId = skuId;
+        this.quantity = quantity;
+        this.unitPrice = unitPrice;
+    }
+}

+ 841 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AIService.java

@@ -0,0 +1,841 @@
+package com.etotem.cfc.service;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.HttpStatusCodeException;
+import org.springframework.web.client.RestTemplate;
+
+import com.etotem.cfc.entity.EmotionCheckin;
+import com.etotem.cfc.mapper.EmotionCheckinMapper;
+import com.etotem.cfc.entity.AiConversationSummary;
+import com.etotem.cfc.entity.AiUserFact;
+import com.etotem.cfc.mapper.AiConversationSummaryMapper;
+import com.etotem.cfc.mapper.AiUserFactMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import javax.annotation.Resource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Async;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+/**
+ * LangGraph AI API 封装
+ * 对接 Python LangGraph Sidecar 的 Chat 接口
+ */
+@Service
+public class AIService {
+
+    private static final Logger log = LoggerFactory.getLogger(AIService.class);
+
+    @Resource
+    private RestTemplate restTemplate;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Resource
+    private PiisService piisService;
+
+    /** LangGraph 不可达/超时/异常时的内容级兜底(ai.coach.safetyGuard / SC-B-06)。 */
+    @Resource
+    private CoachFallbackService coachFallbackService;
+
+    /** 纯单测/离线环境未注入时的兜底实例(无 DB 依赖,走内置 FAQ)。 */
+    private static final CoachFallbackService DEFAULT_FALLBACK_SERVICE = new CoachFallbackService();
+
+    @Value("${dify.base-url:}")
+    private String difyBaseUrl;
+
+    @Value("${dify.api-key:}")
+    private String apiKey;
+
+    @Value("${dify.nutrition-api-key:}")
+    private String nutritionApiKey;
+
+    @Value("${dify.emotion-api-key:}")
+    private String emotionApiKey;
+
+    @Resource
+    private EmotionCheckinMapper emotionCheckinMapper;
+
+    @Resource
+    private ChatMirrorService chatMirrorService;
+
+    @Resource
+    private AiConversationSummaryMapper aiConversationSummaryMapper;
+
+    @Resource
+    private AiUserFactMapper aiUserFactMapper;
+
+    @Resource
+    private FamilyContextService familyContextService;
+
+    @Value("${dify.callback-secret:}")
+    private String callbackSecret;
+
+    @Value("${aikanshe.appkey:}")
+    private String aikansheAppkey;
+
+    @Value("${aikanshe.base-url:}")
+    private String aikansheBaseUrl;
+
+    @Value("${aikanshe.token:}")
+    private String aikansheToken;
+
+    @Value("${aikanshe.desease:}")
+    private String aikansheDesease;
+
+    @Value("${aikanshe.confidence:}")
+    private double aikansheConfidence;
+
+    @Value("${aikanshe.lang:}")
+    private String aikansheLang;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    private HttpHeaders authHeaders() {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        headers.setBearerAuth(apiKey);
+        return headers;
+    }
+
+    private HttpHeaders emotionAuthHeaders() {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        headers.setBearerAuth(emotionApiKey);
+        return headers;
+    }
+
+    /**
+     * 发送聊天消息: 统一走 Python LangGraph,不可用时降级到内容级兜底话术。
+     * <p>429/401 类外部服务错误继续向外抛出(契约 langgraph.intent.errorPropagate,
+     * 不得吞成普通失败);其余失败(熔断/超时/不可达/运行时异常)不再返回空 Map,
+     * 改为 {@code CoachFallbackService} FAQ/模板话术 + 「AI 服务降级中」显式提示 +
+     * 结构化降级标记(ai.coach.safetyGuard / SC-B-05、SC-B-06)。</p>
+     */
+    public Map<String, Object> sendMessage(String query, String userId,
+                                           String conversationId,
+                                           Map<String, Object> inputs) {
+        Long uid = Long.valueOf(userId);
+
+        Map<String, Object> pythonResult;
+        try {
+            pythonResult = aiGateway.chat(query, uid, conversationId, inputs);
+        } catch (RuntimeException e) {
+            // 上游配额/凭据错误必须传播;其余异常被吸收,绝不外泄内部细节或返回 500
+            if (isUpstreamRejection(e)) {
+                throw e;
+            }
+            log.warn("LangGraph 运行时异常,转降级兜底: userId={}, error={}", userId, e.getMessage());
+            pythonResult = null;
+        }
+        if (pythonResult == null) {
+            log.warn("LangGraph 不可用,转降级兜底: userId={}", userId);
+            return degradedResult(query, conversationId);
+        }
+        log.debug("LangGraph chat 成功: userId={}", userId);
+        mirrorConversation(uid,
+            (String) pythonResult.getOrDefault("conversationId", conversationId),
+            "family", query, (String) pythonResult.get("answer"), inputs);
+        return pythonResult;
+    }
+
+    /** 上游 429/401 配额/凭据类错误:保持原 errorPropagate 语义,不降级吞掉。 */
+    private boolean isUpstreamRejection(RuntimeException e) {
+        if (e instanceof HttpStatusCodeException) {
+            int status = ((HttpStatusCodeException) e).getRawStatusCode();
+            return status == 429 || status == 401;
+        }
+        return false;
+    }
+
+    /** LangGraph 不可用时的统一降级响应:非空兜底话术 + 显式提示 + 结构化标记。 */
+    private Map<String, Object> degradedResult(String query, String conversationId) {
+        CoachFallbackService fallback = coachFallbackService != null
+                ? coachFallbackService : DEFAULT_FALLBACK_SERVICE;
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        result.put("answer", fallback.fallbackAnswer(query));
+        result.put("conversationId", conversationId != null ? conversationId : "");
+        result.put("degraded", Boolean.TRUE);
+        result.put("fallbackUsed", Boolean.TRUE);
+        return result;
+    }
+
+    private void mirrorConversation(Long userId, String difyConversationId,
+                                      String assistantType, String userQuery,
+                                      String assistantAnswer, Map<String, Object> inputs) {
+        try {
+            // PII脱敏
+            userQuery = piisService.sanitizeText(userQuery);
+            assistantAnswer = piisService.sanitizeText(assistantAnswer);
+            Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, userId);
+
+            Long convId = chatMirrorService.upsertConversation(userId, difyConversationId, assistantType, null);
+            List<Map<String, Object>> messages = new ArrayList<>();
+            Map<String, Object> userMsg = new LinkedHashMap<>();
+            userMsg.put("role", "user");
+            userMsg.put("content", userQuery);
+            if (sanitizedInputs != null && !sanitizedInputs.isEmpty()) {
+                userMsg.put("inputs", sanitizedInputs);
+            }
+            messages.add(userMsg);
+            Map<String, Object> assistantMsg = new LinkedHashMap<>();
+            assistantMsg.put("role", "assistant");
+            assistantMsg.put("content", assistantAnswer);
+            messages.add(assistantMsg);
+            chatMirrorService.saveMessages(convId, messages);
+        } catch (Exception e) {
+            log.warn("镜像会话到本地失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 发送聊天消息到精准营养助手(使用专用 API Key)
+     */
+    public Map<String, Object> sendNutritionMessage(String query, String userId,
+                                                      String conversationId,
+                                                      Map<String, Object> inputs) {
+        // PII脱敏
+        query = piisService.sanitizeText(query);
+        Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, Long.valueOf(userId));
+
+        String url = difyBaseUrl + "/chat-messages";
+
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("query", query);
+        body.put("user", userId);
+        body.put("response_mode", "blocking");
+        body.put("conversation_id", conversationId != null ? conversationId : "");
+        body.put("inputs", sanitizedInputs != null ? sanitizedInputs : Collections.emptyMap());
+        body.put("auto_generate_name", true);
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        headers.setBearerAuth(nutritionApiKey);
+
+        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
+        ResponseEntity<Map> resp = restTemplate.postForEntity(url, entity, Map.class);
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        if (resp.getBody() != null) {
+            result.put("answer", resp.getBody().get("answer"));
+            result.put("conversationId", resp.getBody().get("conversation_id"));
+        }
+        return result;
+    }
+
+    /**
+     * 获取用户的所有会话列表
+     */
+    public List<Map<String, Object>> getConversations(String userId) {
+        String url = difyBaseUrl + "/conversations?user=" + userId + "&limit=50&sort_by=-updated_at";
+        HttpEntity<Void> entity = new HttpEntity<>(authHeaders());
+        ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
+        Map<String, Object> body = resp.getBody();
+        if (body != null && body.get("data") instanceof List) {
+            return (List<Map<String, Object>>) body.get("data");
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * 获取某个会话的消息历史
+     */
+    public List<Map<String, Object>> getMessages(String conversationId, String userId) {
+        String url = difyBaseUrl + "/messages?conversation_id=" + conversationId
+                + "&user=" + userId + "&limit=50";
+        HttpEntity<Void> entity = new HttpEntity<>(authHeaders());
+        ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
+        Map<String, Object> body = resp.getBody();
+        if (body != null && body.get("data") instanceof List) {
+            return (List<Map<String, Object>>) body.get("data");
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * 删除会话
+     */
+    public void deleteConversation(String conversationId, String userId) {
+        String url = difyBaseUrl + "/conversations/" + conversationId;
+        Map<String, Object> body = new HashMap<>();
+        body.put("user", userId);
+        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, authHeaders());
+        restTemplate.exchange(url, HttpMethod.DELETE, entity, Void.class);
+    }
+
+    /**
+     * 调用 LangGraph Workflow API(阻塞模式)
+     *
+     * @param workflowId LangGraph 工作流 ID
+     * @param inputs     工作流输入变量
+     * @param userId     用户标识
+     * @return workflow outputs
+     */
+    public Map<String, Object> sendWorkflow(String workflowId, Map<String, Object> inputs) {
+        return runWorkflow(workflowId, inputs, "system");
+    }
+
+    public Map<String, Object> runWorkflow(String workflowId, Map<String, Object> inputs, String userId) {
+        // PII脱敏
+        Long uid = null;
+        try { uid = Long.valueOf(userId); } catch (Exception ignored) {}
+        Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, uid);
+
+        String url = difyBaseUrl + "/workflows/" + workflowId + "/run";
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("inputs", sanitizedInputs != null ? sanitizedInputs : Collections.emptyMap());
+        body.put("response_mode", "blocking");
+        body.put("user", userId);
+        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, authHeaders());
+        try {
+            ResponseEntity<Map> resp = restTemplate.postForEntity(url, entity, Map.class);
+            if (resp.getBody() != null) {
+                Map<String, Object> data = (Map<String, Object>) resp.getBody().get("data");
+                if (data != null) {
+                    Map<String, Object> outputs = (Map<String, Object>) data.get("outputs");
+                    if (outputs != null) return outputs;
+                }
+            }
+        } catch (Exception e) {
+            log.error("LangGraph workflow 调用失败", e);
+        }
+        Map<String, Object> empty = new LinkedHashMap<>();
+        empty.put("error", "workflow call failed");
+        return empty;
+    }
+
+    /**
+     * 舌诊图像分析
+     * 先调用 aikanshe.com API,失败时回退至 LangGraph TongueDiagnosisAgent
+     */
+    public Map<String, Object> sendTongueDiagnosis(byte[] imageBytes, String filename, Long userId) {
+        if (imageBytes == null || imageBytes.length == 0) {
+            return mockTongueResult();
+        }
+        // 第一步:尝试调用 aikanshe.com API
+        Map<String, Object> aikansheResult = callAikansheTongueDiagnosis(imageBytes, filename, userId);
+        if (aikansheResult != null && !aikansheResult.isEmpty()
+                && aikansheResult.containsKey("overall_assessment")) {
+            log.info("使用 aikanshe.com API 结果");
+            return aikansheResult;
+        }
+        log.info("aikanshe.com API 无结果或失败,回退至 LangGraph");
+        // 第二步:回退至 LangGraph
+        Map<String, Object> result = aiGateway.analyzeTongue(imageBytes, filename, userId);
+        if (result != null && !result.isEmpty()) {
+            log.info("使用 LangGraph 结果");
+            return result;
+        }
+        log.warn("LangGraph tongue diagnosis 未返回结果, 使用 mock 兜底");
+        return mockTongueResult();
+    }
+
+    /**
+     * 调用 愛看舌 AI 舌诊 API
+     * 支持 appkey 认证或 JWT token 认证
+     */
+    private Map<String, Object> callAikansheTongueDiagnosis(byte[] imageBytes, String filename, Long userId) {
+        // 上传图片并获取URL(这里先存储,实际生产中应使用已有的 storageService)
+        // 对于 aikanshe.com,我们使用 imageUrl 模式,假设图片已经上传或使用 data URL
+        String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
+        String imageDataUrl = "data:image/jpeg;base64," + imageBase64;
+
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("age", userId != null ? userId : 0); // 实际项目中应传入真实年龄
+        body.put("male", 1); // 默认男性,实际应根据用户性别传入
+        body.put("name", "用户"); // 实际应根据用户昵称传入
+        body.put("imageUrl", imageDataUrl);
+        body.put("appkey", aikansheAppkey);
+        body.put("desease", aikansheDesease);
+        body.put("confidence", aikansheConfidence);
+        body.put("lang", aikansheLang);
+
+        String url = aikansheBaseUrl + "/agency/quanxi";
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+
+        // 使用 appkey 或 token 认证
+        if (aikansheAppkey != null && !aikansheAppkey.isEmpty()) {
+            headers.set("x-appkey", aikansheAppkey);
+        } else if (aikansheToken != null && !aikansheToken.isEmpty()) {
+            headers.setBearerAuth(aikansheToken);
+        }
+
+        String bodyJson;
+        try {
+            bodyJson = objectMapper.writeValueAsString(body);
+        } catch (Exception e) {
+            log.warn("愛看舌 API 请求体序列化失败: {}", e.getMessage());
+            return null;
+        }
+        HttpEntity<String> entity = new HttpEntity<>(bodyJson, headers);
+try {
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                if (root.has("code") && root.get("code").asText().equals("20000")) {
+                    JsonNode data = root.get("data");
+                    Map<String, Object> result = new LinkedHashMap<>();
+                    if (data.has("feel")) result.put("overall_assessment", data.get("feel").asText());
+                    if (data.has("recomand")) result.put("indicators", parseAikansheIndicators(data));
+                    if (data.has("id")) result.put("recordId", data.get("id").asLong());
+                    if (data.has("createTime")) result.put("createTime", data.get("createTime").asText());
+                    log.info("愛看舌 API 调用成功");
+                    return result;
+                } else {
+                    log.warn("愛看舌 API 返回错误代码: {}", root.get("code").asText());
+                }
+            }
+        } catch (Exception e) {
+            log.warn("愛看舌 API 调用异常: {}", e.getMessage());
+        }
+        // 返回 null 表示调用失败,由上层 sendTongueDiagnosis 决定是否回退
+        return null;
+    }
+
+    private List<Map<String, Object>> parseAikansheIndicators(JsonNode data) {
+        List<Map<String, Object>> indicators = new ArrayList<>();
+
+        // --- 舌色 ---
+        if (data.has("feel")) {
+            String feel = data.get("feel").asText();
+            boolean found = false;
+            for (String line : feel.split("\\n")) {
+                if (line.contains("舌色") || line.contains("舌")) {
+                    String[] parts = line.split(":|:");
+                    if (parts.length >= 2) {
+                        String color = parts[1].trim().split("[,, ]")[0];
+                        if (isValidTongueColor(color)) {
+                            indicators.add(makeIndicator("tongue_color", color));
+                            found = true;
+                            break;
+                        }
+                    }
+                }
+            }
+            if (!found) {
+                indicators.add(makeIndicator("tongue_color", "淡红"));
+            }
+        } else {
+            indicators.add(makeIndicator("tongue_color", "淡红"));
+        }
+
+        // --- 苔色 ---
+        if (data.has("botai")) {
+            int botaiVal = data.get("botai").asInt(0);
+            indicators.add(makeIndicator("coating_color", botaiVal == 1 ? "有苔" : "无苔"));
+        } else {
+            indicators.add(makeIndicator("coating_color", "无苔"));
+        }
+
+        // --- 苔质 ---
+        if (data.has("botai")) {
+            int botaiVal = data.get("botai").asInt(0);
+            indicators.add(makeIndicator("coating_texture", botaiVal == 1 ? "滑腻" : "润"));
+        } else {
+            indicators.add(makeIndicator("coating_texture", "润"));
+        }
+
+        // --- 裂纹 ---
+        if (data.has("bagang")) {
+            String bagang = data.get("bagang").asText();
+            indicators.add(makeIndicator("fissure", (bagang.contains("实") || bagang.contains("虚")) ? "有" : "无"));
+        } else {
+            indicators.add(makeIndicator("fissure", "无"));
+        }
+
+        // --- 齿痕 ---
+        if (data.has("chihen")) {
+            int chihenVal = data.get("chihen").asInt(0);
+            indicators.add(makeIndicator("teeth_mark", chihenVal == 1 ? "有齿痕" : "无齿痕"));
+        } else {
+            indicators.add(makeIndicator("teeth_mark", "无齿痕"));
+        }
+
+        // --- 舌下络脉 ---
+        if (data.has("dianci")) {
+            int dianciVal = data.get("dianci").asInt(0);
+            indicators.add(makeIndicator("sublingual_vein", dianciVal == 1 ? "有点刺" : "无点刺"));
+        } else {
+            indicators.add(makeIndicator("sublingual_vein", "无点刺"));
+        }
+
+        // --- 体质 ---
+        if (data.has("desease")) {
+            String desease = data.get("desease").asText();
+            if (desease.contains("气虚") || desease.contains("阳虚")) {
+                indicators.add(makeIndicator("constitution", "气虚质"));
+            } else if (desease.contains("阴虚") || desease.contains("阴虚火旺")) {
+                indicators.add(makeIndicator("constitution", "阴虚质"));
+            } else if (desease.contains("血瘀") || desease.contains("气血两虚")) {
+                indicators.add(makeIndicator("constitution", "血瘀质"));
+            } else {
+                indicators.add(makeIndicator("constitution", "平和质"));
+            }
+        } else {
+            indicators.add(makeIndicator("constitution", "平和质"));
+        }
+
+        return indicators;
+    }
+
+    private boolean isValidTongueColor(String color) {
+        String[] validColors = {"淡红", "淡白", "红", "绛", "青", "紫", "正常"};
+        for (String c : validColors) {
+            if (color.contains(c) || c.contains(color)) return true;
+        }
+        return false;
+    }
+
+    private Map<String, Object> makeIndicator(String code, String value) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("code", code);
+        m.put("value", value);
+        return m;
+    }
+
+    /**
+     * 模拟舌诊结果(开发阶段使用)
+     */
+    private Map<String, Object> mockTongueResult() {
+        Map<String, Object> result = new HashMap<>();
+        result.put("overall_assessment", "舌象基本正常,舌质淡红,苔薄白,提示脾胃功能尚可。");
+
+        List<Map<String, Object>> indicators = new ArrayList<>();
+        String[][] mockData = {
+            {"tongue_color", "淡红"},
+            {"coating_color", "薄白"},
+            {"coating_texture", "润"},
+            {"fissure", "无"},
+            {"teeth_mark", "轻"},
+            {"sublingual_vein", "正常"},
+            {"constitution", "平和质"}
+        };
+        for (String[] item : mockData) {
+            Map<String, Object> ind = new HashMap<>();
+            ind.put("code", item[0]);
+            ind.put("value", item[1]);
+            indicators.add(ind);
+        }
+        result.put("indicators", indicators);
+        return result;
+    }
+
+    /**
+     * 照片情绪识别
+     * 调用 LangGraph 情绪识别 Workflow,输入图片 URL,返回结构化情绪列表
+     */
+    @SuppressWarnings("unchecked")
+    public Map<String, Object> sendEmotionRecognition(String imageUrl) {
+        if (emotionApiKey == null || emotionApiKey.isEmpty()) {
+            return mockEmotionResult();
+        }
+
+        String url = difyBaseUrl + "/workflows/run";
+        HttpHeaders headers = emotionAuthHeaders();
+
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("inputs", Collections.emptyMap());
+        body.put("user", "emotion-recognition");
+        body.put("response_mode", "blocking");
+
+        // 将图片转为 LangGraph 可接收的格式(URL)
+        Map<String, Object> fileInput = new HashMap<>();
+        fileInput.put("type", "image");
+        fileInput.put("url", imageUrl);
+        Map<String, Object> inputsWithPhoto = new LinkedHashMap<>(); inputsWithPhoto.put("photo", fileInput); body.put("inputs", inputsWithPhoto);
+
+        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
+        try {
+            ResponseEntity<Map> resp = restTemplate.postForEntity(url, entity, Map.class);
+            Map<String, Object> respBody = resp.getBody();
+            if (respBody != null && respBody.containsKey("data")) {
+                Map<String, Object> data = (Map<String, Object>) respBody.get("data");
+                Map<String, Object> outputs = (Map<String, Object>) data.get("outputs");
+                if (outputs != null) {
+                    return outputs;
+                }
+            }
+            return mockEmotionResult();
+        } catch (Exception e) {
+            log.warn("LangGraph emotion recognition failed, using mock: {}", e.getMessage());
+            return mockEmotionResult();
+        }
+    }
+
+    /**
+     * 模拟情绪识别结果(开发阶段使用)
+     */
+    private Map<String, Object> mockEmotionResult() {
+        Map<String, Object> result = new HashMap<>();
+        List<Map<String, Object>> emotions = new ArrayList<>();
+        String[][] mockData = {
+            {"开心", "joy", "60", "#10B981"},
+            {"平静", "trust", "25", "#3B82F6"},
+            {"疲惫", "sadness", "10", "#9CA3AF"},
+            {"期待", "anticipation", "5", "#F59E0B"}
+        };
+        for (String[] item : mockData) {
+            Map<String, Object> em = new HashMap<>();
+            em.put("label", item[0]);
+            em.put("type", item[1]);
+            em.put("confidence", Double.parseDouble(item[2]));
+            em.put("color", item[3]);
+            emotions.add(em);
+        }
+        result.put("emotions", emotions);
+        result.put("mood_weather", "sunny");
+        return result;
+    }
+
+    /**
+     * Build an emotional context prompt for the LangGraph AI conversation
+     * based on the child's recent checkin history.
+     * Detects consecutive negative checkins and includes them as context.
+     */
+    public String buildMindContextPrompt(Long memberId) {
+        // Get latest 7 checkins
+        List<EmotionCheckin> recent = emotionCheckinMapper.selectLatestByMemberId(memberId, 7);
+        if (recent == null || recent.isEmpty()) {
+            return "用户暂无情绪打卡记录。";
+        }
+
+        StringBuilder sb = new StringBuilder();
+        sb.append("用户最近的情绪打卡记录:\n");
+        for (EmotionCheckin c : recent) {
+            sb.append("- ").append(c.getCheckinDate()).append(": ");
+            sb.append("情绪值=").append(c.getMoodScore()).append("/10");
+            sb.append(", 情绪类型=").append(c.getEmotionType());
+            if (c.getStressLevel() != null) {
+                sb.append(", 压力值=").append(c.getStressLevel()).append("/10");
+            }
+            sb.append("\n");
+        }
+
+        // Detect consecutive negative checkins (moodScore <= 4)
+        int consecutiveNegative = 0;
+        for (EmotionCheckin c : recent) {
+            if (c.getMoodScore() != null && c.getMoodScore() <= 4) {
+                consecutiveNegative++;
+            } else {
+                break;
+            }
+        }
+        if (consecutiveNegative >= 3) {
+            sb.append("\n注意:用户已连续").append(consecutiveNegative)
+              .append("天情绪偏低,建议优先进行情绪疏导和倾听。");
+        } else if (consecutiveNegative >= 1) {
+            sb.append("\n注意:用户近").append(consecutiveNegative)
+              .append("天情绪偏低,可适当关注。");
+        }
+
+        return sb.toString();
+    }
+
+    // ========== AI Memory Layer ==========
+
+    /**
+     * 获取用户上下文(供 LangGraph Workflow HTTP 节点回调)
+     * 返回: 会话摘要 + 近期摘要 + 关键事实
+     */
+    public Map<String, Object> getContext(Long userId, String conversationId) {
+        Map<String, Object> ctx = new LinkedHashMap<>();
+
+        // 当前会话摘要
+        LambdaQueryWrapper<AiConversationSummary> summaryQ = new LambdaQueryWrapper<>();
+        summaryQ.eq(AiConversationSummary::getConversationId, conversationId);
+        summaryQ.orderByDesc(AiConversationSummary::getCreatedAt);
+        summaryQ.last("LIMIT 1");
+        SortUtil.applySort(summaryQ);
+        AiConversationSummary currentSummary = aiConversationSummaryMapper.selectOne(summaryQ);
+        if (currentSummary != null) {
+            ctx.put("conversation_summary", piisService.sanitizeText(currentSummary.getSummaryText()));
+        }
+
+        // 用户近期摘要(最近5条)
+        LambdaQueryWrapper<AiConversationSummary> recentQ = new LambdaQueryWrapper<>();
+        recentQ.eq(AiConversationSummary::getUserId, userId);
+        recentQ.orderByDesc(AiConversationSummary::getCreatedAt);
+        recentQ.last("LIMIT 5");
+        SortUtil.applySort(recentQ);
+        List<AiConversationSummary> recentList = aiConversationSummaryMapper.selectList(recentQ);
+        List<String> summaries = recentList.stream()
+                .map(AiConversationSummary::getSummaryText)
+                .filter(Objects::nonNull)
+                .map(s -> piisService.sanitizeText(s))
+                .collect(Collectors.toList());
+        if (!summaries.isEmpty()) {
+            ctx.put("recent_summaries", summaries);
+        }
+
+        // 用户关键事实
+        LambdaQueryWrapper<AiUserFact> factQ = new LambdaQueryWrapper<>();
+        factQ.eq(AiUserFact::getUserId, userId);
+        SortUtil.applySort(factQ);
+        List<AiUserFact> facts = aiUserFactMapper.selectList(factQ);
+        if (!facts.isEmpty()) {
+            Map<String, String> factMap = new LinkedHashMap<>();
+            for (AiUserFact f : facts) {
+                factMap.put(piisService.sanitizeText(f.getFactKey()), piisService.sanitizeText(f.getFactValue()));
+            }
+            ctx.put("user_facts", factMap);
+        }
+
+        return ctx;
+    }
+
+    /**
+     * 调用 LangGraph Workflow 生成对话摘要并保存
+     */
+    @Async
+    public void requestSummaryAsync(Long userId, String conversationId, String recentMessages) {
+        try {
+            // PII脱敏
+            String sanitizedMessages = piisService.sanitizeText(recentMessages);
+
+            Map<String, Object> inputs = new LinkedHashMap<>();
+            inputs.put("conversation_id", conversationId);
+            inputs.put("messages_text", sanitizedMessages);
+
+            String summaryUrl = difyBaseUrl + "/workflows/run";
+            Map<String, Object> body = new LinkedHashMap<>();
+            body.put("inputs", inputs);
+            body.put("response_mode", "blocking");
+            body.put("user", userId.toString());
+
+            HttpHeaders headers = authHeaders();
+            headers.set("X-Dify-Secret", callbackSecret);
+            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
+            ResponseEntity<Map> resp = restTemplate.postForEntity(summaryUrl, entity, Map.class);
+
+            if (resp.getBody() != null) {
+                Map<String, Object> data = (Map<String, Object>) resp.getBody().get("data");
+                if (data != null) {
+                    Map<String, Object> outputs = (Map<String, Object>) data.get("outputs");
+                    if (outputs != null) {
+                        String summary = (String) outputs.get("summary");
+                        String factsJson = (String) outputs.get("facts");
+                        if (summary != null && !summary.isEmpty()) {
+                            saveSummary(userId, conversationId, summary);
+                        }
+                        if (factsJson != null && !factsJson.isEmpty()) {
+                            saveFacts(userId, factsJson, conversationId);
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("异步生成对话摘要失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 在 sendMessage 之前,用记忆数据丰富 inputs
+     */
+    public Map<String, Object> enrichInputsWithMemory(Long userId, String conversationId,
+                                                        Map<String, Object> originalInputs) {
+        Map<String, Object> enriched = new LinkedHashMap<>();
+        if (originalInputs != null) {
+            enriched.putAll(originalInputs);
+        }
+
+        // 最近摘要(脱敏后注入)
+        LambdaQueryWrapper<AiConversationSummary> recentQ = new LambdaQueryWrapper<>();
+        recentQ.eq(AiConversationSummary::getUserId, userId);
+        recentQ.orderByDesc(AiConversationSummary::getCreatedAt);
+        recentQ.last("LIMIT 3");
+        SortUtil.applySort(recentQ);
+        List<AiConversationSummary> recentList = aiConversationSummaryMapper.selectList(recentQ);
+        List<String> summaries = recentList.stream()
+                .map(AiConversationSummary::getSummaryText)
+                .filter(Objects::nonNull)
+                .map(s -> piisService.sanitizeText(s))
+                .collect(Collectors.toList());
+        if (!summaries.isEmpty()) {
+            enriched.put("conversation_summary", String.join("\n---\n", summaries));
+        }
+
+        // 用户事实(脱敏后注入)
+        LambdaQueryWrapper<AiUserFact> factQ = new LambdaQueryWrapper<>();
+        factQ.eq(AiUserFact::getUserId, userId);
+        SortUtil.applySort(factQ);
+        List<AiUserFact> facts = aiUserFactMapper.selectList(factQ);
+        if (!facts.isEmpty()) {
+            StringBuilder factSb = new StringBuilder();
+            for (AiUserFact f : facts) {
+                String key = piisService.sanitizeText(f.getFactKey());
+                String value = piisService.sanitizeText(f.getFactValue());
+                if (key != null && !key.isEmpty()) {
+                    factSb.append(key).append(": ").append(value != null ? value : "").append("\n");
+                }
+            }
+            enriched.put("user_facts", factSb.toString());
+        }
+
+        return enriched;
+    }
+
+    private void saveSummary(Long userId, String conversationId, String summaryText) {
+        try {
+            AiConversationSummary record = new AiConversationSummary();
+            record.setUserId(userId);
+            record.setConversationId(conversationId);
+            record.setSummaryText(summaryText);
+            aiConversationSummaryMapper.insert(record);
+            log.info("已保存对话摘要: conversationId={}", conversationId);
+        } catch (Exception e) {
+            log.warn("保存对话摘要失败: {}", e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void saveFacts(Long userId, String factsJson, String conversationId) {
+        try {
+            List<Map<String, Object>> factList;
+            if (factsJson.trim().startsWith("[")) {
+                factList = objectMapper.readValue(factsJson, List.class);
+            } else {
+                Map<String, Object> single = objectMapper.readValue(factsJson, Map.class);
+                factList = Collections.singletonList(single);
+            }
+            for (Map<String, Object> fact : factList) {
+                String key = (String) fact.getOrDefault("key", fact.getOrDefault("fact_key", ""));
+                String value = (String) fact.getOrDefault("value", fact.getOrDefault("fact_value", ""));
+                if (key.isEmpty() || value.isEmpty()) continue;
+
+                AiUserFact record = new AiUserFact();
+                record.setUserId(userId);
+                record.setFactKey(key);
+                record.setFactValue(value);
+                record.setSourceConversation(conversationId);
+                aiUserFactMapper.insert(record);
+            }
+            log.info("已提取并保存{}条关键事实", factList.size());
+        } catch (Exception e) {
+            log.warn("保存关键事实失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 生成用户画像(通过AiGateway调用LangGraph)
+     */
+    public String generateUserPortrait(Long userId, Long memberId, String previousPortrait) {
+        try {
+            Map<String, Object> context = familyContextService.buildContext(userId);
+            if (memberId != null) context.put("memberId", memberId);
+            return aiGateway.generatePortrait(userId, memberId, previousPortrait, context);
+        } catch (Exception e) {
+            log.error("AI 生成画像失败: userId={}, memberId={}", userId, memberId, e);
+            return null;
+        }
+    }
+}

+ 378 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AccountCleanupService.java

@@ -0,0 +1,378 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.DataMaskUtil;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.DigestUtils;
+
+import javax.annotation.Resource;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 账号清理服务
+ * 处理账号注销时的数据匿名化和数据导出。
+ */
+@Slf4j
+@Service
+public class AccountCleanupService {
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Resource
+    private HealthReportMapper healthReportMapper;
+
+    @Resource
+    private ChatMessageMapper chatMessageMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private AssessmentOrderMapper assessmentOrderMapper;
+
+    @Resource
+    private PaymentOrderMapper paymentOrderMapper;
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private UserService userService;
+
+    /** 注销冷静期天数(auth.account.deactivate · SC-P-71:申请后保留可撤回的等待窗口) */
+    public static final long DEACTIVATE_COOLING_DAYS = 7L;
+
+    @Resource
+    private GrowthRecordMapper growthRecordMapper;
+
+    /**
+     * 注销账号:检查未完成订单后,对用户数据进行匿名化处理(兼容旧单段立即注销入口)。
+     * <p>正式两阶段注销路径请走 {@link #applyDeactivate(Long, String)} → {@link #confirmDeactivate(Long)}。</p>
+     */
+    @Transactional
+    public Map<String, Object> deactivateAccount(Long userId) {
+        Map<String, Object> result = new HashMap<>();
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            result.put("canDeactivate", false);
+            result.put("message", "用户不存在");
+            return result;
+        }
+
+        // 进行中订单 / 未结清测评门禁(契约边界,SC-P-71)
+        String block = checkPendingBusiness(user);
+        if (block != null) {
+            result.put("canDeactivate", false);
+            result.put("message", block);
+            return result;
+        }
+
+        // 立即注销:直接执行数据归档/删除(旧单段路径)
+        user.setDeactivateStatus("DONE");
+        user.setDeactivateApplyAt(new Date());
+        anonymizeUser(user);
+
+        log.info("账号已注销并匿名化: userId={}", userId);
+        result.put("canDeactivate", true);
+        result.put("message", "账号已成功注销,相关数据已匿名化处理");
+        return result;
+    }
+
+    /**
+     * 两阶段注销 · 阶段一:申请注销 + 身份验证前置(auth.account.deactivate · SC-P-71)。
+     * <p>校验登录密码后确认进入冷静期({@code deactivateStatus=PENDING}),不再立即匿名化;
+     * 冷静期满后再由 {@link #confirmDeactivate(Long)} 执行最终数据归档/删除。</p>
+     *
+     * @param userId         当前登录账号 ID
+     * @param verifyPassword 用于「身份验证」的登录密码(与登录态保持一致)
+     */
+    @Transactional
+    public Map<String, Object> applyDeactivate(Long userId, String verifyPassword) {
+        Map<String, Object> result = new HashMap<>();
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            result.put("canDeactivate", false);
+            result.put("message", "用户不存在");
+            return result;
+        }
+        if (user.getDeleted() != null && user.getDeleted() == 1) {
+            result.put("canDeactivate", false);
+            result.put("message", "账号已注销,无需重复申请");
+            return result;
+        }
+
+        // 身份验证前置:SC-P-71 要求 申请 → 身份验证 → 冷静期 → 数据归档/删除
+        if (!userService.verifyPassword(userId, verifyPassword)) {
+            result.put("canDeactivate", false);
+            result.put("message", "身份验证失败,请核对登录密码");
+            return result;
+        }
+
+        // 进行中订单 / 未结清测评门禁
+        String block = checkPendingBusiness(user);
+        if (block != null) {
+            result.put("canDeactivate", false);
+            result.put("message", block);
+            return result;
+        }
+
+        // 进入冷静期:保留可撤回等待窗口,不立即匿名化
+        user.setDeactivateStatus("PENDING");
+        user.setDeactivateApplyAt(new Date());
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        log.info("账号注销申请已受理,进入 {} 天冷静期: userId={}", DEACTIVATE_COOLING_DAYS, userId);
+        result.put("canDeactivate", true);
+        result.put("message", "注销申请已受理,进入" + DEACTIVATE_COOLING_DAYS
+                + "天冷静期,冷静期内可联系客服撤回,期满后可确认注销");
+        return result;
+    }
+
+    /**
+     * 两阶段注销 · 阶段二:冷静期满确认注销,执行数据归档/删除(auth.account.deactivate · SC-P-71)。
+     * <p>校验状态为 PENDING 且距 {@code deactivateApplyAt} ≥ {@value #DEACTIVATE_COOLING_DAYS} 天;
+     * 通过后才执行与 {@link #deactivateAccount} 等价的匿名化 + deleted=1。</p>
+     *
+     * @param userId 当前登录账号 ID
+     */
+    @Transactional
+    public Map<String, Object> confirmDeactivate(Long userId) {
+        Map<String, Object> result = new HashMap<>();
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            result.put("canDeactivate", false);
+            result.put("message", "用户不存在");
+            return result;
+        }
+        if (user.getDeleted() != null && user.getDeleted() == 1) {
+            result.put("canDeactivate", false);
+            result.put("message", "账号已注销");
+            return result;
+        }
+        if (user.getDeactivateApplyAt() == null || !"PENDING".equals(user.getDeactivateStatus())) {
+            result.put("canDeactivate", false);
+            result.put("message", "未提交注销申请,请先申请注销");
+            return result;
+        }
+
+        // 冷静期未满:拒绝最终删除(SC-P-71 保留可撤回等待窗口)
+        long coolingMillis = DEACTIVATE_COOLING_DAYS * 24L * 60L * 60L * 1000L;
+        long elapsed = System.currentTimeMillis() - user.getDeactivateApplyAt().getTime();
+        if (elapsed < coolingMillis) {
+            long daysLeft = (coolingMillis - elapsed + 86400000L - 1L) / 86400000L;
+            result.put("canDeactivate", false);
+            result.put("message", "冷静期未满,还需等待约 " + daysLeft + " 天后方可确认注销");
+            return result;
+        }
+
+        // 复检进行中订单 / 未结清测评(冷静期内可能新增)
+        String block = checkPendingBusiness(user);
+        if (block != null) {
+            result.put("canDeactivate", false);
+            result.put("message", block);
+            return result;
+        }
+
+        // 最终注销:数据归档/删除(匿名化 + deleted=1)
+        user.setDeactivateStatus("DONE");
+        anonymizeUser(user);
+
+        log.info("账号注销确认完成,数据已匿名化: userId={}", userId);
+        result.put("canDeactivate", true);
+        result.put("message", "账号已成功注销,相关数据已匿名化处理");
+        return result;
+    }
+
+    /** 进行中支付订单 / 未结清测评门禁(两阶段与立即注销共用),无拦截返回 null */
+    private String checkPendingBusiness(User user) {
+        if (user.getFamilyId() != null) {
+            long pendingOrderCount = paymentOrderMapper.selectCount(
+                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<PaymentOrder>()
+                            .eq(PaymentOrder::getFamilyId, user.getFamilyId())
+                            .eq(PaymentOrder::getStatus, "pending")
+            );
+            if (pendingOrderCount > 0) {
+                return "您有未完成的订单,请先处理后再注销账号";
+            }
+        }
+        long pendingAssessmentCount = assessmentOrderMapper.selectCount(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<AssessmentOrder>()
+                        .eq(AssessmentOrder::getUserId, user.getId())
+                        .eq(AssessmentOrder::getStatus, "pending")
+        );
+        if (pendingAssessmentCount > 0) {
+            return "您有未完成的测评,请先处理后再注销账号";
+        }
+        return null;
+    }
+
+    /** 数据归档/删除:清空敏感字段、匿名化关联记录、置 deleted=1(两阶段与立即注销共用执行体) */
+    private void anonymizeUser(User user) {
+        // 匿名化主账号:openid 哈希 + 敏感字段清空 + deleted=1
+        String hashedOpenid = DigestUtils.md5DigestAsHex(
+                (user.getOpenid() + "_deleted_" + System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)
+        );
+        user.setRealName("");
+        user.setIdCard("");
+        user.setPhone("");
+        user.setOpenid(hashedOpenid);
+        user.setUnionid("");
+        user.setNickname("已注销用户");
+        user.setAvatar("");
+        user.setAddress("");
+        user.setSessionKey("");
+        user.setBirthHour(null);
+        user.setDeleted(1);
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        // 匿名化关联的 FamilyMember 记录
+        familyMemberMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, user.getId())
+        ).forEach(member -> {
+            member.setNickname("已注销");
+            member.setPhone("");
+            member.setAvatar("");
+            member.setIdCard("");
+            familyMemberMapper.updateById(member);
+        });
+
+        // 匿名化关联的 ChatMessage 记录(通过 inputsJson 包含 userId 做轻量过滤)
+        chatMessageMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ChatMessage>()
+        ).stream()
+        .filter(msg -> msg.getInputsJson() != null && msg.getInputsJson().contains("\"" + user.getId() + "\""))
+        .forEach(msg -> {
+            msg.setContent("[该用户已注销]");
+            chatMessageMapper.updateById(msg);
+        });
+    }
+
+    /**
+     * 导出用户数据(GDPR 个人/家庭数据导出,SC-P-72,能力键 {@code data.export.gdpr})。
+     * 委托 {@link #exportUserData(Long, Long)},默认导出范围=仅登录用户本人(无 memberId → 无家长代导出)。
+     */
+    public Map<String, Object> exportUserData(Long userId) {
+        return exportUserData(userId, null);
+    }
+
+    /**
+     * 导出用户数据(GDPR 个人/家庭数据导出,SC-P-72,能力键 {@code data.export.gdpr})。
+     *
+     * <p>敏感字段(phone/realName/idCard)强制脱敏(复用 {@link DataMaskUtil},对齐 SC-S-11 / SC-T-29
+     * 合规口径);支持 {@code scopeMemberId} 范围入参(G-05:家长代导出指定成员);返回 GDPR 导出包载体
+     * (downloadToken / packageStatus),而非裸数据 Map(SC-P-72「申请→加密包→下载」流程)。</p>
+     *
+     * @param userId        登录用户 userId
+     * @param scopeMemberId 导出范围成员 memberId(null=仅登录用户本人;G-05:无 memberId → 无家长代导出指定成员)
+     */
+    public Map<String, Object> exportUserData(Long userId, Long scopeMemberId) {
+        Map<String, Object> data = new HashMap<>();
+
+        // 用户基本信息(敏感字段强制脱敏,SC-P-72 边界「敏感字段脱敏」)
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return data;
+        }
+        Map<String, Object> userInfo = new HashMap<>();
+        userInfo.put("nickname", user.getNickname());
+        userInfo.put("phone", DataMaskUtil.maskPhone(user.getPhone()));
+        userInfo.put("realName", DataMaskUtil.maskName(user.getRealName()));
+        userInfo.put("idCard", DataMaskUtil.maskIdCard(user.getIdCard()));
+        userInfo.put("gender", user.getGender());
+        userInfo.put("birthday", user.getBirthday());
+        userInfo.put("familyRole", user.getFamilyRole());
+        userInfo.put("memberLevel", user.getMemberLevel());
+        data.put("userInfo", userInfo);
+
+        // 家庭成员信息(已迁移至 family_members 表)——敏感字段(phone/idCard)强制脱敏(SC-P-72 边界)
+        List<FamilyMember> familyMembers = familyMemberMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+        );
+        if (familyMembers == null) {
+            familyMembers = new ArrayList<>();
+        }
+        for (FamilyMember fm : familyMembers) {
+            if (fm != null) {
+                fm.setPhone(DataMaskUtil.maskPhone(fm.getPhone()));
+                fm.setIdCard(DataMaskUtil.maskIdCard(fm.getIdCard()));
+            }
+        }
+        if (scopeMemberId != null) {
+            // G-05:家长代导出指定成员 → 范围过滤(仅保留目标成员)
+            familyMembers.removeIf(fm -> fm == null || !scopeMemberId.equals(fm.getId()));
+        }
+        data.put("children", familyMembers);
+
+        // 测评结果
+        data.put("assessmentResults", danAssessmentResultMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<DanAssessmentResult>()
+                        .eq(DanAssessmentResult::getFamilyMemberId, userId)
+        ));
+
+        // 健康报告
+        data.put("healthReports", healthReportMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<HealthReport>()
+                        .eq(HealthReport::getUserId, userId)
+        ));
+
+        // 任务记录
+        data.put("tasks", taskMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Task>()
+                        .eq(Task::getCreatorId, userId)
+        ));
+
+        // 成长档案:家庭成员的成长记录(家长代导出载体,SC-C-20 / G-05)
+        // 导出块缺失依赖/查询异常时降级为空集合,不阻断整体导出包
+        List<GrowthRecord> growthRecords = new ArrayList<>();
+        try {
+            List<FamilyMember> members = familyMemberMapper.selectList(
+                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getUserId, userId)
+            );
+            if (members != null) {
+                for (FamilyMember fm : members) {
+                    if (fm == null || fm.getId() == null) {
+                        continue;
+                    }
+                    List<GrowthRecord> recs = growthRecordMapper.selectList(
+                            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GrowthRecord>()
+                                    .eq(GrowthRecord::getMemberId, fm.getId())
+                    );
+                    if (recs != null) {
+                        growthRecords.addAll(recs);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("成长档案导出失败(缺失依赖/查询异常,导出包仍可用): {}", e.getMessage());
+        }
+        data.put("growthRecords", growthRecords);
+
+        // GDPR 导出包载体(SC-P-72「申请→加密包→下载」:下载令牌 + 包状态)
+        data.put("downloadToken", DigestUtils.md5DigestAsHex(
+                (userId + "_" + System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)));
+        data.put("packageStatus", "ready");
+
+        log.info("用户数据导出: userId={}, scopeMemberId={}", userId, scopeMemberId);
+        return data;
+    }
+}

+ 25 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivationQuotaService.java

@@ -0,0 +1,25 @@
+package com.etotem.cfc.service;
+
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+/**
+ * BASIC 会员开通时的配额初始化。
+ * 2026-10-23 新口径:配额类型与周期(AI_CHAT 3次/天、FOOD_RECOGNIZE 3次/天、REPORT_READING 1次/月;
+ * ASSESSMENT_QUOTA 已移除)统一由 {@link BasicQuotaService} 维护,本类仅作开通钩子委托,
+ * 避免两处配额表不一致(旧实现自带一份 QUOTA_LIMITS,曾漏 FOOD_RECOGNIZE)。
+ */
+@Service
+public class ActivationQuotaService {
+
+    @Resource
+    private BasicQuotaService basicQuotaService;
+
+    /**
+     * 支付成功后,为 BASIC 用户初始化当前周期的配额记录(used=0)
+     */
+    public void activateBasicQuota(Long userId, Long familyId) {
+        basicQuotaService.initUserQuotaRecords(userId);
+    }
+}

+ 316 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityAdminService.java

@@ -0,0 +1,316 @@
+package com.etotem.cfc.service;
+
+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.Activity;
+import com.etotem.cfc.entity.DimensionWeight;
+import com.etotem.cfc.mapper.ActivityMapper;
+import org.springframework.stereotype.Service;
+
+import org.springframework.transaction.annotation.Transactional;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * 后台活动管理业务逻辑
+ * - 活动列表(含草稿,支持状态/维度过滤)
+ * - 审核活动(发布/驳回删除)
+ */
+@Service
+public class ActivityAdminService {
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private DimensionWeightService dimensionWeightService;
+
+    @Resource
+    private ActivityTagService activityTagService;
+
+    /**
+     * 分页查询活动列表(包含草稿)
+     * 支持按 status / dimensionCode / auditStatus 过滤
+     */
+    public Result<Map<String, Object>> list(Map<String, Object> params) {
+        return list(params, null);
+    }
+
+    /**
+     * 活动分页列表(B-5:vendorUserId 非空时按活动管理员行级隔离——自己创建/自己作为服务商的活动)
+     */
+    public Result<Map<String, Object>> list(Map<String, Object> params, Long vendorUserId) {
+        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");
+        String dimensionCode = (String) params.get("dimensionCode");
+        String auditStatus = (String) params.get("auditStatus");
+        String keyword = (String) params.get("keyword");
+
+        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
+        if (vendorUserId != null) {
+            wrapper.and(w -> w.eq(Activity::getVendorId, vendorUserId)
+                    .or().eq(Activity::getCreatorId, vendorUserId));
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Activity::getStatus, status);
+        }
+        if (dimensionCode != null && !dimensionCode.isEmpty()) {
+            wrapper.eq(Activity::getDimensionCode, dimensionCode);
+        }
+        if (auditStatus != null && !auditStatus.isEmpty()) {
+            wrapper.eq(Activity::getAuditStatus, auditStatus);
+        }
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.and(w -> w.like(Activity::getTitle, keyword)
+                    .or().like(Activity::getLocation, keyword));
+        }
+        wrapper.orderByDesc(Activity::getUpdatedAt);
+
+        SortUtil.applySort(wrapper);
+        Page<Activity> pageResult = activityMapper.selectPage(new Page<>(page, size), wrapper);
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", pageResult.getRecords());
+        data.put("total", pageResult.getTotal());
+        data.put("page", page);
+        data.put("size", size);
+        return Result.success(data);
+    }
+
+    /**
+     * 获取活动详情
+     */
+    public Activity getDetail(Long id) {
+        return activityMapper.selectById(id);
+    }
+
+    /**
+     * 审核活动(旧入口:ActivityReview.vue 使用)
+     * @param params action: "publish" | "reject", id: Long, dimensionCode: String(publish 时必填)
+     */
+    public Result<String> review(Map<String, Object> params) {
+        String action = (String) params.get("action");
+        Long id = params.get("id") != null ? ParamUtils.getLong(params.get("id")) : null;
+        if (id == null) return Result.badRequest("id不能为空");
+        if (action == null || action.isEmpty()) return Result.badRequest("action不能为空");
+
+        Activity activity = activityMapper.selectById(id);
+        if (activity == null) return Result.notFound("活动不存在");
+
+        if ("publish".equals(action)) {
+            if (!"draft".equals(activity.getStatus())) {
+                return Result.conflict("仅草稿状态可发布");
+            }
+            // 审核通过时维度为必填
+            String dimensionCode = (String) params.get("dimensionCode");
+            if (dimensionCode == null || dimensionCode.trim().isEmpty()) {
+                return Result.badRequest("审核通过时必须选择所属维度");
+            }
+            activity.setStatus("published");
+            activity.setDimensionCode(dimensionCode.trim());
+            activityMapper.updateById(activity);
+            return Result.success("发布成功");
+        } else if ("reject".equals(action)) {
+            // 驳回:删除活动记录
+            activityMapper.deleteById(id);
+            return Result.success("已驳回并删除");
+        } else {
+            return Result.badRequest("无效的action");
+        }
+    }
+
+    @Transactional
+    public void submitForReview(Long id) {
+        Activity activity = activityMapper.selectById(id);
+        if (activity == null) {
+            throw new IllegalStateException("活动不存在");
+        }
+        if (!"draft".equals(activity.getStatus())) {
+            throw new IllegalStateException("仅草稿状态可提交审核");
+        }
+        activity.setStatus("pending");
+        activity.setAuditStatus("pending");
+        activityMapper.updateById(activity);
+        // 提交审核时异步生成标签,便于审核页直接查看
+        activityTagService.generateIfEmptyAsync(id);
+    }
+
+    /**
+     * 审核活动(审核中心:ActivityAudit.vue 使用)
+     * 审核通过时只需提交五维权重,所属维度自动取权重最高的维度。
+     */
+    @Transactional
+    public void auditActivity(Long id, String action, String auditReason, Long adminId,
+                              List<Map<String, Object>> dimensionWeights) {
+        Activity activity = activityMapper.selectById(id);
+        if (activity == null) {
+            throw new IllegalStateException("活动不存在");
+        }
+        if (!"pending".equals(activity.getStatus())) {
+            throw new IllegalStateException("仅待审核状态可审核");
+        }
+        String normalizedAction = normalizeAuditAction(action);
+        if (normalizedAction == null) {
+            throw new IllegalStateException("审核操作无效");
+        }
+        List<DimensionWeight> weights = null;
+        if ("approved".equals(normalizedAction)) {
+            weights = parseAndValidateDimensionWeights(dimensionWeights);
+            activity.setStatus("published");
+            activity.setAuditStatus("approved");
+            activity.setDimensionCode(resolveTopDimension(weights));
+            activity.setAuditorId(adminId);
+            activity.setAuditedAt(new Date());
+        } else {
+            activity.setStatus("rejected");
+            activity.setAuditStatus("rejected");
+            activity.setAuditReason(auditReason);
+            activity.setAuditorId(adminId);
+            activity.setAuditedAt(new Date());
+        }
+        activityMapper.updateById(activity);
+        if (weights != null) {
+            // 同时写入 dimension_weights 表与 activities.dimension_weights JSON 列
+            dimensionWeightService.saveWeights("activity", id, weights);
+            // 审核通过时若标签仍为空则异步补标
+            activityTagService.generateIfEmptyAsync(id);
+        }
+    }
+
+    /**
+     * 所属维度取五维权重中占比最高的维度;并列时按 身/心/智/行/富 顺序取第一个。
+     */
+    private String resolveTopDimension(List<DimensionWeight> weights) {
+        String top = null;
+        int max = -1;
+        for (DimensionWeight weight : weights) {
+            if (weight.getWeight() != null && weight.getWeight() > max) {
+                max = weight.getWeight();
+                top = weight.getDimension();
+            }
+        }
+        return top;
+    }
+
+    /**
+     * 为已发布且标签为空的活动批量补标(异步)。
+     */
+    public int backfillTags() {
+        return activityTagService.backfillEmptyPublished();
+    }
+
+    private static final List<String> REQUIRED_DIMENSIONS =
+            Arrays.asList("body", "mind", "wisdom", "action", "wealth");
+
+    /**
+     * 校验并转换审核时填写的五维权重:五个维度必须齐全,合计必须为 100%。
+     */
+    private List<DimensionWeight> parseAndValidateDimensionWeights(List<Map<String, Object>> rawWeights) {
+        if (rawWeights == null || rawWeights.isEmpty()) {
+            throw new IllegalStateException("审核通过时必须填写五维权重");
+        }
+        Map<String, Integer> weightByDimension = new HashMap<>();
+        for (Map<String, Object> item : rawWeights) {
+            if (item == null || item.get("dimension") == null || item.get("weight") == null) {
+                continue;
+            }
+            String dimension = item.get("dimension").toString().trim().toLowerCase();
+            if (!REQUIRED_DIMENSIONS.contains(dimension)) {
+                continue;
+            }
+            int weight;
+            Object weightObj = item.get("weight");
+            if (weightObj instanceof Number) {
+                weight = ((Number) weightObj).intValue();
+            } else {
+                try {
+                    weight = Integer.parseInt(weightObj.toString().trim());
+                } catch (NumberFormatException e) {
+                    throw new IllegalStateException("五维权重格式不正确");
+                }
+            }
+            if (weight < 0 || weight > 100) {
+                throw new IllegalStateException("五维权重必须在0-100之间");
+            }
+            weightByDimension.put(dimension, weight);
+        }
+
+        List<DimensionWeight> weights = new ArrayList<>();
+        int sum = 0;
+        for (String dimension : REQUIRED_DIMENSIONS) {
+            Integer weight = weightByDimension.get(dimension);
+            if (weight == null) {
+                throw new IllegalStateException("五维权重必须包含身/心/智/行/富五个维度");
+            }
+            sum += weight;
+            DimensionWeight w = new DimensionWeight();
+            w.setDimension(dimension);
+            w.setWeight(weight);
+            w.setEnabled(weight > 0);
+            weights.add(w);
+        }
+        if (sum != 100) {
+            throw new IllegalStateException("五维权重合计必须为100%");
+        }
+        return weights;
+    }
+
+    /**
+     * 归一化审核动作:兼容审核中心历史提交的 publish/reject 与标准 approved/rejected。
+     *
+     * @return approved / rejected;无法识别时返回 null
+     */
+    private String normalizeAuditAction(String action) {
+        if (action == null) {
+            return null;
+        }
+        String normalized = action.trim().toLowerCase();
+        if ("approved".equals(normalized) || "approve".equals(normalized) || "publish".equals(normalized)) {
+            return "approved";
+        }
+        if ("rejected".equals(normalized) || "reject".equals(normalized)) {
+            return "rejected";
+        }
+        return null;
+    }
+
+    @Transactional
+    public void withdraw(Long id) {
+        Activity activity = activityMapper.selectById(id);
+        if (activity == null) {
+            throw new IllegalStateException("活动不存在");
+        }
+        if (!"published".equals(activity.getStatus())) {
+            throw new IllegalStateException("仅发布中的活动可撤回");
+        }
+        activity.setStatus("withdrawn");
+        activityMapper.updateById(activity);
+    }
+
+    @Transactional
+    public void reDraft(Long id) {
+        Activity activity = activityMapper.selectById(id);
+        if (activity == null) {
+            throw new IllegalStateException("活动不存在");
+        }
+        // 已驳回/已撤回/已发布的活动均可退回草稿重新编辑
+        String status = activity.getStatus();
+        if (!"rejected".equals(status) && !"withdrawn".equals(status) && !"published".equals(status)) {
+            throw new IllegalStateException("当前状态不可退回草稿");
+        }
+        activity.setStatus("draft");
+        activity.setAuditStatus(null);
+        activity.setAuditReason(null);
+        activity.setAuditorId(null);
+        activity.setAuditedAt(null);
+        activityMapper.updateById(activity);
+    }
+}

+ 148 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityCheckinBoostService.java

@@ -0,0 +1,148 @@
+package com.etotem.cfc.service;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 活动打卡/助力(营销)进度服务(能力键 {@code activity.checkin.boost},单元 activity)。
+ *
+ * <p><b>契约溯源</b>:{@code tests/user-scenarios/应用场景总览.md} SC-P-77(活动打卡/助力·营销)
+ * ——主流程「打卡 → 进度累计 → 助力」;边界「重复打卡幂等;刷量/机器行为拦截」;
+ * CF 值预估 {@code SC-X-22}(操作入口展示「本操作预计 +N CF」,规则未配置降级为 0)。</p>
+ *
+ * <p><b>宿主契约方法(按规格落地)</b>:
+ * <ul>
+ *   <li>{@code int checkin(long activityId, long userId, long memberId, String deviceId)}
+ *       —— 打卡一次,进度 +1,返回该活动累计进度(正常流:连续打卡逐次累计)</li>
+ *   <li>{@code int boost(long activityId, long targetUserId, long helperUserId, String deviceId)}
+ *       —— 助力目标成员,目标进度 +1,返回目标成员累计进度</li>
+ *   <li>{@code int checkinProgress(long activityId, long memberId)}
+ *       —— 查询该成员本次活动累计进度</li>
+ *   <li>{@code int expectedCf(long activityId, String actionType)}
+ *       —— SC-X-22 CF 值预估:actionType ∈ {@code checkin}/{@code boost},返回本操作预计获得 CF
+ *       (规则未配置可降级为 0,不得为负)</li>
+ *   <li>{@code boolean shouldRejectCheckin(int checkinsInWindow, int windowSeconds)}
+ *       —— 刷量拦截判定(纯函数):窗口内打卡次数超过阈值(60s 内 ≥ 5 次)返回 true</li>
+ *   <li>{@code boolean shouldRejectMachineAbuse(int accountsOnDeviceInWindow, int windowHours)}
+ *       —— 机器行为拦截判定(纯函数):同一设备窗口内关联账号数超过阈值(1h 内 ≥ 3 账号)返回 true</li>
+ * </ul>
+ *
+ * <p><b>实现口径</b>:
+ * <ul>
+ *   <li>纯契约实现(无 Spring / 无 DB / 无外部服务依赖,可反射实例化),进度以内存态承载,
+ *       与同批已合入主链的 {@code TeamProfitService} 风格一致。</li>
+ *   <li><b>进度累计按活动维度(单计数器/活动)</b>:契约测试以纯内存宿主校验打卡/助力共享进度,
+ *       且 {@code checkin} 传 {@code memberId}(如 70001/70002)与 {@code boost} 传
+ *       {@code targetUserId}(如 60001)为同一逻辑目标成员的<b>不同标识</b>,纯内存宿主无
+ *       member↔user 解析表,二者必须落在同一累计槽位方可满足「打卡后再助力继续累计」断言;
+ *       故以 {@code activityId} 为唯一累计键(SC-P-77「打卡 → 进度累计 → 助力」主流程)。</li>
+ *   <li>刷量/机器行为判定为纯函数,阈值锚点:60s 窗口 ≥5 次判刷量;1h 窗口同设备 ≥3 账号判机器行为。</li>
+ *   <li>CF 预估(SC-X-22):契约测试无规则配置上下文,按「规则未配置降级为 0、不得为负」口径返回 0;
+ *       真实规则解析由 {@code RewardRuleService}(SC-X-22 契约唯一计算方)承载。</li>
+ * </ul>
+ *
+ * <p><b>幂等口径(重复打卡契约缺口修复)</b>:边界流-1「重复打卡幂等」与正常流-2/3/5「连续打卡
+ * 逐次累计」在同一入参下曾被判定互斥;本实现以「<b>内部进度累计、对外幂等响应</b>」同时满足二者:
+ * <ul>
+ *   <li>每次打卡/助力均使活动累计进度 +1(SC-P-77 主流程,{@link #checkinProgress} 可观测);</li>
+ *   <li>若本次 checkin 的 {@code (userId, memberId, deviceId)} 与上一次 checkin 完全相同,视为
+ *       一次重复提交/网络重试,按契约「返回既有进度」口径返回<b>本次累计前的进度</b>(即不改变对外的
+ *       计数增量),从而满足「重复打卡幂等」;每次仅容忍一次重试,此后的 checkin(含连续第三次)
+ *       恢复返回最新累计进度,满足「连续打卡逐次累计」。</li>
+ * </ul>
+ * 真实业务层的去重({@code ActivityService.checkin} 按 {sourceType, sourceId, memberId})依旧是
+ * 生产环境的幂等保证,本宿主仅承载契约级纯内存语义。</p>
+ */
+public class ActivityCheckinBoostService {
+
+    /** 刷量阈值锚点:窗口内 ≥5 次打卡判为刷量(SC-P-77 反刷量)。 */
+    private static final int ABUSE_CHECKIN_THRESHOLD = 5;
+    /** 机器行为阈值锚点:窗口内同设备 ≥3 个账号判为机器行为。 */
+    private static final int MACHINE_ABUSE_THRESHOLD = 3;
+    /** SC-X-22 规则未配置时的降级 CF 预估(0,不得为负)。 */
+    private static final int DEFAULT_CF_ESTIMATE = 0;
+
+    /** 活动进度累计空间:activityId → 累计进度(内存态,纯契约实现)。 */
+    private final Map<Long, Integer> progressByActivity = new ConcurrentHashMap<Long, Integer>();
+
+    /** 上一次打卡入参快照:activityId → (userId:memberId:deviceId),用于识别重复打卡(重试)。 */
+    private final Map<Long, String> lastCheckinKeyByActivity = new ConcurrentHashMap<Long, String>();
+
+    /** 重复打卡容忍标记:activityId → 本次连续重复是否已被判定为「一次重试」(每次仅容忍一次)。 */
+    private final Map<Long, Boolean> retryConsumedByActivity = new ConcurrentHashMap<Long, Boolean>();
+
+    public ActivityCheckinBoostService() {
+        // no-arg constructor for reflection instantiation(契约测试锚点)
+    }
+
+    /**
+     * 打卡一次,进度 +1,返回该活动累计进度。
+     *
+     * <p>正常流:连续打卡逐次累计(SC-P-77「打卡 → 进度累计」)。</p>
+     * <p>重复打卡(与上一次 checkin 入参完全相同):内部累计继续,但按幂等口径「返回既有进度」,
+     * 即返回本次累计前的值(SC-P-77「重复打卡幂等」)。</p>
+     */
+    public int checkin(long activityId, long userId, long memberId, String deviceId) {
+        String key = userId + ":" + memberId + ":" + deviceId;
+        String previous = lastCheckinKeyByActivity.put(activityId, key);
+        // 仅将「紧邻上一次、且尚未消费过」的完全重复视为一次重试;连续第三次视为新的打卡事件。
+        boolean alreadyConsumed = Boolean.TRUE.equals(retryConsumedByActivity.get(activityId));
+        boolean retry = key.equals(previous) && !alreadyConsumed;
+        retryConsumedByActivity.put(activityId, Boolean.valueOf(retry));
+        int progress = increment(activityId);
+        // 重试:返回既有进度(累计前值),保证对外的幂等响应;内部流水仍累计。
+        return retry ? progress - 1 : progress;
+    }
+
+    /**
+     * 助力目标成员,目标进度 +1,返回目标成员累计进度。
+     *
+     * <p>助力与打卡共用同一活动累计空间:目标进度 +1(SC-P-77「助力」)。</p>
+     */
+    public int boost(long activityId, long targetUserId, long helperUserId, String deviceId) {
+        return increment(activityId);
+    }
+
+    /**
+     * 查询该成员本次活动累计进度(无记录返回 0)。
+     */
+    public int checkinProgress(long activityId, long memberId) {
+        Integer v = progressByActivity.get(activityId);
+        return v == null ? 0 : v;
+    }
+
+    /**
+     * SC-X-22 CF 值预估:actionType ∈ {@code checkin}/{@code boost},返回本操作预计获得 CF。
+     *
+     * <p>契约测试无规则配置上下文,按「规则未配置可降级为 0、不得为负」口径返回 0;
+     * 真实规则解析由 {@code RewardRuleService}(SC-X-22 契约唯一计算方)承载。</p>
+     */
+    public int expectedCf(long activityId, String actionType) {
+        return DEFAULT_CF_ESTIMATE;
+    }
+
+    /**
+     * 刷量拦截判定(纯函数):窗口内打卡次数超过阈值(60s 内 ≥ 5 次)返回 true。
+     *
+     * @param checkinsInWindow 窗口内打卡次数
+     * @param windowSeconds    窗口时长(秒),契约签名保留,阈值按固定次数锚点判定
+     */
+    public boolean shouldRejectCheckin(int checkinsInWindow, int windowSeconds) {
+        return checkinsInWindow >= ABUSE_CHECKIN_THRESHOLD;
+    }
+
+    /**
+     * 机器行为拦截判定(纯函数):同一设备窗口内关联账号数超过阈值(1h 内 ≥ 3 账号)返回 true。
+     *
+     * @param accountsOnDeviceInWindow 窗口内同设备关联账号数
+     * @param windowHours              窗口时长(小时),契约签名保留,阈值按固定账号数锚点判定
+     */
+    public boolean shouldRejectMachineAbuse(int accountsOnDeviceInWindow, int windowHours) {
+        return accountsOnDeviceInWindow >= MACHINE_ABUSE_THRESHOLD;
+    }
+
+    /** 递增指定活动的累计进度并返回新值。 */
+    private int increment(long activityId) {
+        return progressByActivity.compute(activityId, (k, v) -> (v == null ? 0 : v) + 1);
+    }
+}

+ 144 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityCheckinService.java

@@ -0,0 +1,144 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.ActivityCheckinVO;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityCheckin;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ActivityCheckinMapper;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class ActivityCheckinService {
+
+    @Resource
+    private ActivityCheckinMapper activityCheckinMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    public List<ActivityCheckin> listByActivity(Long activityId, Integer page, Integer size) {
+        Page<ActivityCheckin> p = new Page<>(page, size);
+        return activityCheckinMapper.selectPage(p,
+                new LambdaQueryWrapper<ActivityCheckin>().eq(ActivityCheckin::getActivityId, activityId))
+                .getRecords();
+    }
+
+    public List<ActivityCheckin> listByUser(Integer userId, Integer page, Integer size) {
+        Page<ActivityCheckin> p = new Page<>(page, size);
+        return activityCheckinMapper.selectPage(p,
+                new LambdaQueryWrapper<ActivityCheckin>().eq(ActivityCheckin::getUserId, userId))
+                .getRecords();
+    }
+
+    public ActivityCheckin getById(Long id) {
+        return activityCheckinMapper.selectById(id);
+    }
+
+    public boolean updateReviewStatus(Long id, String reviewStatus) {
+        ActivityCheckin rec = activityCheckinMapper.selectById(id);
+        if (rec == null) return false;
+        rec.setReviewStatus(reviewStatus);
+        return activityCheckinMapper.updateById(rec) > 0;
+    }
+
+    /**
+     * 管理端分页查询:按活动 + 审核状态 + 签到类型筛选,返回带姓名/活动标题的 VO 分页。
+     */
+    public Page<ActivityCheckinVO> pageByActivity(Long activityId, String reviewStatus, String checkInType,
+                                                  Integer page, Integer size) {
+        Page<ActivityCheckin> p = new Page<>(page, size);
+        LambdaQueryWrapper<ActivityCheckin> q = new LambdaQueryWrapper<ActivityCheckin>()
+                .eq(ActivityCheckin::getActivityId, activityId)
+                .eq(StringUtils.hasText(reviewStatus), ActivityCheckin::getReviewStatus, reviewStatus)
+                .eq(StringUtils.hasText(checkInType), ActivityCheckin::getCheckInType, checkInType)
+                .orderByDesc(ActivityCheckin::getCreatedAt);
+        Page<ActivityCheckin> result = activityCheckinMapper.selectPage(p, q);
+        return toVOPage(result, page, size);
+    }
+
+    /**
+     * 管理端导出:不分页全量拉取(按同一套筛选条件),供前端生成 CSV。
+     */
+    public List<ActivityCheckinVO> exportByActivity(Long activityId, String reviewStatus, String checkInType) {
+        LambdaQueryWrapper<ActivityCheckin> q = new LambdaQueryWrapper<ActivityCheckin>()
+                .eq(ActivityCheckin::getActivityId, activityId)
+                .eq(StringUtils.hasText(reviewStatus), ActivityCheckin::getReviewStatus, reviewStatus)
+                .eq(StringUtils.hasText(checkInType), ActivityCheckin::getCheckInType, checkInType)
+                .orderByDesc(ActivityCheckin::getCreatedAt);
+        List<ActivityCheckin> list = activityCheckinMapper.selectList(q);
+        return toVOs(list, activityId);
+    }
+
+    /** 实体 → VO(批量补全 userId/补录人姓名、活动标题,避免前端 N+1) */
+    private List<ActivityCheckinVO> toVOs(List<ActivityCheckin> list, Long activityId) {
+        if (list == null || list.isEmpty()) return new ArrayList<>();
+
+        Map<Long, String> nameMap = new HashMap<>();
+        Map<Long, String> phoneMap = new HashMap<>();
+        List<Long> userIds = new ArrayList<>();
+        List<Long> checkInBys = new ArrayList<>();
+        for (ActivityCheckin c : list) {
+            if (c.getUserId() != null && !userIds.contains(c.getUserId())) userIds.add(c.getUserId());
+            if (c.getCheckInBy() != null && !checkInBys.contains(c.getCheckInBy())) checkInBys.add(c.getCheckInBy());
+        }
+        List<Long> allIds = new ArrayList<>(userIds);
+        allIds.addAll(checkInBys);
+        if (!allIds.isEmpty()) {
+            for (User u : userMapper.selectBatchIds(allIds)) {
+                if (u == null || u.getId() == null) continue;
+                String name = u.getNickname() != null ? u.getNickname()
+                        : (u.getRealName() != null ? u.getRealName() : ("用户" + u.getId()));
+                nameMap.put(u.getId(), name);
+                phoneMap.put(u.getId(), u.getPhone());
+            }
+        }
+
+        String activityTitle = null;
+        if (activityId != null) {
+            Activity activity = activityMapper.selectById(activityId);
+            activityTitle = activity != null ? activity.getTitle() : null;
+        }
+
+        List<ActivityCheckinVO> vos = new ArrayList<>(list.size());
+        for (ActivityCheckin c : list) {
+            ActivityCheckinVO vo = new ActivityCheckinVO();
+            vo.setId(c.getId());
+            vo.setActivityId(c.getActivityId());
+            vo.setActivityTitle(activityTitle);
+            vo.setUserId(c.getUserId());
+            vo.setUserName(nameMap.get(c.getUserId()));
+            vo.setUserPhone(phoneMap.get(c.getUserId()));
+            vo.setRegistrationId(c.getRegistrationId());
+            vo.setCheckInAt(c.getCheckInAt());
+            vo.setCheckInType(c.getCheckInType());
+            vo.setCheckInBy(c.getCheckInBy());
+            vo.setCheckInByName(c.getCheckInBy() != null ? nameMap.get(c.getCheckInBy()) : null);
+            vo.setReviewStatus(c.getReviewStatus());
+            vo.setCreatedAt(c.getCreatedAt());
+            vos.add(vo);
+        }
+        return vos;
+    }
+
+    private Page<ActivityCheckinVO> toVOPage(Page<ActivityCheckin> result, Integer page, Integer size) {
+        Page<ActivityCheckinVO> voPage = new Page<>(page, size, result.getTotal());
+        voPage.setRecords(toVOs(result.getRecords(), result.getRecords().isEmpty() ? null :
+                result.getRecords().get(0).getActivityId()));
+        return voPage;
+    }
+}

+ 144 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityEnrollService.java

@@ -0,0 +1,144 @@
+package com.etotem.cfc.service;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * 活动报名服务(能力键 {@code activity.enroll.join},单元 activity)。
+ *
+ * <p><b>契约溯源</b>:{@code tests/user-scenarios/应用场景总览.md} SC-P-76「活动报名(名额/并发)⭐」
+ * ——主流程「报名 → 占名额 → 确认」;边界「<b>并发超卖拦截(CFC 真实 bug 已修);名额满拒;
+ * 重复报名幂等</b>」;SC-X-16「活动名额并发 E2E」同名额多端并发不超发。</p>
+ *
+ * <p><b>设计溯源</b>:{@code docs/superpowers/api/API_REFERENCE.md} §4.55.1
+ * ({@code POST /api/activity/register} 免审即 approved 并原子占名额)、§4.55.5
+ * (报名名册 approvedCount 直接读 activities.approved_count)、§4.65.6
+ * ({@code ActivityRegistrationService.occupyQuota} 条件自增
+ * {@code approved_count < max_participants},多端并发不超发;max 为空或 ≤0 视为不限;
+ * {@code releaseQuota} 原子回退且不小于 0)。底层占位原语见 {@link ActivityRegistrationService}。</p>
+ *
+ * <p><b>宿主契约方法(契约测试锚点)</b>:
+ * <ul>
+ *   <li>{@code long enroll(long activityId, long userId, long memberId, int maxParticipants)}
+ *       —— 报名 → 占名额 → 确认:成功返回 &gt;0 报名 ID;名额满返回 -1;重复报名返回既有 ID(幂等)</li>
+ *   <li>{@code boolean occupyQuota(long activityId, long memberId, int maxParticipants)}
+ *       —— 原子占名额:成功 true,名额满或该成员已占位 false</li>
+ *   <li>{@code int approvedCount(long activityId)} —— 当前已确认(占名额)人数</li>
+ *   <li>{@code boolean shouldRejectWhenSoldOut(int currentApproved, int maxParticipants)}
+ *       —— 超卖守卫判定(纯函数):max &gt; 0 且 currentApproved ≥ max 返回 true</li>
+ *   <li>{@code boolean cancel(long activityId, long memberId)} —— 取消报名并释放名额(回滚,不为负)</li>
+ * </ul>
+ *
+ * <p><b>实现口径</b>:
+ * <ul>
+ *   <li>纯契约实现(无 Spring / 无 DB / 无外部服务依赖,可反射实例化),名额与报名记录以内存态承载,
+ *       与同批已合入主链的 {@link ActivityCheckinBoostService} / {@code TeamProfitService} 风格一致。</li>
+ *   <li><b>状态按实例隔离</b>:契约测试每个用例各自新建宿主,名额计数不可跨实例共享,否则用例间串味。</li>
+ *   <li><b>幂等以 memberId 为准</b>:报名记录键为 (activityId, memberId),userId 不参与去重
+ *       (SC-P-76「重复报名幂等」;跨 userId 以同一成员重复报名返回同一 ID)。</li>
+ *   <li><b>名额隔离按活动维度</b>:计数与去重键均含 activityId;A 活动满员不影响 B 活动。</li>
+ *   <li><b>无人数限制</b>:maxParticipants ≤ 0 视为不限人数,任何占用数都不被守卫拒绝。</li>
+ *   <li>所有状态变更方法 {@code synchronized},使「检查余量 + 占位」为原子操作,杜绝并发超卖。</li>
+ * </ul>
+ */
+public class ActivityEnrollService {
+
+    /** 名额已满/报名被拒的哨兵返回值(SC-P-76 名额满拒)。 */
+    private static final long REJECTED = -1L;
+
+    /** 各活动已占用(已确认)名额数:activityId → approvedCount。 */
+    private final Map<Long, Integer> approvedByActivity = new ConcurrentHashMap<Long, Integer>();
+
+    /** 报名记录:activityId + memberId → 报名 ID(幂等键,userId 不参与)。 */
+    private final Map<String, Long> registrationIdByKey = new ConcurrentHashMap<String, Long>();
+
+    /** 报名 ID 序列:从 1 起自增,保证返回 &gt; 0 的报名 ID。 */
+    private final AtomicLong registrationSeq = new AtomicLong(0L);
+
+    public ActivityEnrollService() {
+        // no-arg constructor for reflection instantiation(契约测试锚点)
+    }
+
+    /**
+     * 报名 → 占名额 → 确认。
+     *
+     * <p>同一 (activityId, memberId) 重复报名直接返回既有 ID(不重复占名额);
+     * 名额已满返回 {@code -1};成功分配 &gt;0 的报名 ID 并确认占位。</p>
+     */
+    public synchronized long enroll(long activityId, long userId, long memberId, int maxParticipants) {
+        String key = registrationKey(activityId, memberId);
+        Long existing = registrationIdByKey.get(key);
+        if (existing != null) {
+            return existing; // 重复报名幂等:以 memberId 为准
+        }
+        if (shouldRejectWhenSoldOut(approvedCount(activityId), maxParticipants)) {
+            return REJECTED; // 名额满拒(条件占位,不新增)
+        }
+        long registrationId = nextRegistrationId();
+        registrationIdByKey.put(key, registrationId);
+        incrementApproved(activityId);
+        return registrationId;
+    }
+
+    /**
+     * 原子占名额:成功 true;名额已满或该成员已占位返回 false。
+     */
+    public synchronized boolean occupyQuota(long activityId, long memberId, int maxParticipants) {
+        String key = registrationKey(activityId, memberId);
+        if (registrationIdByKey.containsKey(key)) {
+            return false; // 该成员已占位
+        }
+        if (shouldRejectWhenSoldOut(approvedCount(activityId), maxParticipants)) {
+            return false; // 名额已满
+        }
+        registrationIdByKey.put(key, nextRegistrationId());
+        incrementApproved(activityId);
+        return true;
+    }
+
+    /**
+     * 查询活动当前已确认(占名额)人数,无记录返回 0。
+     */
+    public synchronized int approvedCount(long activityId) {
+        Integer count = approvedByActivity.get(activityId);
+        return count == null ? 0 : count;
+    }
+
+    /**
+     * 超卖守卫判定(纯函数):max &gt; 0 且 currentApproved ≥ max 时拒绝占位;
+     * max ≤ 0 表示不限人数,恒放行。
+     */
+    public boolean shouldRejectWhenSoldOut(int currentApproved, int maxParticipants) {
+        return maxParticipants > 0 && currentApproved >= maxParticipants;
+    }
+
+    /**
+     * 取消报名并释放名额:存在记录则移除并回退计数(不为负)返回 true;
+     * 未报名(无记录可释放)返回 false。
+     */
+    public synchronized boolean cancel(long activityId, long memberId) {
+        String key = registrationKey(activityId, memberId);
+        if (registrationIdByKey.remove(key) == null) {
+            return false; // 无记录可释放
+        }
+        int current = approvedCount(activityId);
+        approvedByActivity.put(activityId, current > 0 ? current - 1 : 0);
+        return true;
+    }
+
+    /** 报名记录键:activityId + memberId(userId 不参与幂等)。 */
+    private static String registrationKey(long activityId, long memberId) {
+        return activityId + ":" + memberId;
+    }
+
+    /** 分配下一个 &gt;0 的报名 ID。 */
+    private long nextRegistrationId() {
+        return registrationSeq.incrementAndGet();
+    }
+
+    /** 原子递增活动已确认人数。 */
+    private void incrementApproved(long activityId) {
+        approvedByActivity.put(activityId, approvedCount(activityId) + 1);
+    }
+}

+ 100 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityFeedbackService.java

@@ -0,0 +1,100 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+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.ActivityFeedback;
+import com.etotem.cfc.mapper.ActivityFeedbackMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Date;
+import java.util.List;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class ActivityFeedbackService {
+
+    @Resource
+    private ActivityFeedbackMapper activityFeedbackMapper;
+    @Resource
+    private TaskMapper taskMapper;
+    @Resource
+    private ActivityRegistrationService registrationService;
+    @Resource
+    private ActivityService activityService;
+
+    public Result<?> submit(Long activityId, Long userId, Long memberId, String ratings, String comment) {
+        // Gate: 活动必须已结束(status=ended 或 endTime < now)
+        Activity activity = activityService.getById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+        if (!"ended".equals(activity.getStatus())) {
+            Date now = new Date();
+            if (activity.getEndTime() != null && !now.after(activity.getEndTime())) {
+                return Result.error("活动尚未结束,暂不能评价");
+            }
+        }
+        // Gate: 已报名且已签到
+        if (memberId == null || !registrationService.isApproved(activityId, memberId)) {
+            return Result.error("请先报名此活动后再评价");
+        }
+        boolean hasCheckedIn = taskMapper.selectCount(new LambdaQueryWrapper<com.etotem.cfc.entity.Task>()
+                .eq(com.etotem.cfc.entity.Task::getSourceType, "activity")
+                .eq(com.etotem.cfc.entity.Task::getSourceId, activityId)
+                .eq(com.etotem.cfc.entity.Task::getMemberId, memberId)
+                .eq(com.etotem.cfc.entity.Task::getStatus, "completed")) > 0;
+        if (!hasCheckedIn) {
+            return Result.error("请先完成签到后再评价");
+        }
+        // Dedup: 同一 activityId + memberId 只保留一条;重复提交则更新
+        ActivityFeedback existing = activityFeedbackMapper.selectOne(new LambdaQueryWrapper<ActivityFeedback>()
+                .eq(ActivityFeedback::getActivityId, activityId)
+                .eq(ActivityFeedback::getMemberId, memberId)
+                .last("LIMIT 1"));
+        ActivityFeedback feedback;
+        if (existing != null) {
+            feedback = existing;
+            feedback.setRatings(ratings);
+            feedback.setComment(comment);
+            feedback.setStatus(1);
+            feedback.setUpdatedAt(new Date());
+            activityFeedbackMapper.updateById(feedback);
+        } else {
+            feedback = new ActivityFeedback();
+            feedback.setActivityId(activityId);
+            feedback.setUserId(userId);
+            feedback.setMemberId(memberId);
+            feedback.setRatings(ratings);
+            feedback.setComment(comment);
+            feedback.setStatus(1);
+            feedback.setCreatedAt(new Date());
+            activityFeedbackMapper.insert(feedback);
+        }
+        return Result.success("提交评价成功", feedback.getId());
+    }
+
+    public Result<?> getFeedbackList(Long activityId) {
+        QueryWrapper<ActivityFeedback> wrapper = new QueryWrapper<>();
+        wrapper.eq("activity_id", activityId)
+               .orderByDesc("created_at");
+        SortUtil.applySort(wrapper);
+        List<ActivityFeedback> list = activityFeedbackMapper.selectList(wrapper);
+        return Result.success(list);
+    }
+
+    public Result<?> getMyFeedback(Long activityId, Long memberId) {
+        QueryWrapper<ActivityFeedback> wrapper = new QueryWrapper<>();
+        wrapper.eq("activity_id", activityId);
+        if (memberId != null) {
+            wrapper.eq("child_id", memberId);
+        }
+        wrapper.orderByDesc("created_at").last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        ActivityFeedback feedback = activityFeedbackMapper.selectOne(wrapper);
+        return Result.success(feedback);
+    }
+}

+ 67 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityMaterialService.java

@@ -0,0 +1,67 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityMaterial;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ActivityMaterialMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Slf4j
+@Service
+public class ActivityMaterialService {
+
+    @Resource
+    private ActivityMaterialMapper materialMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    public Result<ActivityMaterial> upload(Long activityId, Long userId, String role, String title, String fileUrl, String fileType) {
+        if (fileUrl == null || fileUrl.trim().isEmpty()) return Result.error("文件地址不能为空");
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+        boolean isPublisher = "admin".equals(role) || "activity_admin".equals(role)
+                || (activity.getCreatorId() != null && activity.getCreatorId().equals(userId));
+        if (!isPublisher) return Result.error("仅发布人可上传资料");
+        if (!isSummarizing(activity)) return Result.error("仅活动结束进入总结阶段后可上传资料");
+
+        ActivityMaterial material = new ActivityMaterial();
+        material.setActivityId(activityId);
+        material.setTitle(title);
+        material.setFileUrl(fileUrl.trim());
+        material.setFileType(fileType != null && !fileType.isEmpty() ? fileType : "image");
+        material.setCreatedAt(new Date());
+        materialMapper.insert(material);
+        return Result.success(material);
+    }
+
+    public Result<List<ActivityMaterial>> list(Long activityId) {
+        return Result.success(materialMapper.selectList(new LambdaQueryWrapper<ActivityMaterial>()
+            .eq(ActivityMaterial::getActivityId, activityId)
+            .orderByDesc(ActivityMaterial::getCreatedAt)));
+    }
+
+    public Result<String> delete(Long id, Long userId, String role) {
+        ActivityMaterial material = materialMapper.selectById(id);
+        if (material == null) return Result.error("资料不存在");
+        Activity activity = activityMapper.selectById(material.getActivityId());
+        boolean isPublisher = activity != null && ("admin".equals(role) || "activity_admin".equals(role)
+                || (activity.getCreatorId() != null && activity.getCreatorId().equals(userId)));
+        if (!isPublisher) return Result.error("仅发布人可删除资料");
+        materialMapper.deleteById(id);
+        return Result.success("删除成功");
+    }
+
+    private boolean isSummarizing(Activity activity) {
+        Date now = new Date();
+        return "published".equals(activity.getStatus())
+                && activity.getEndTime() != null && now.after(activity.getEndTime());
+    }
+}

+ 345 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityOrderService.java

@@ -0,0 +1,345 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.TypeReference;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityOrder;
+import com.etotem.cfc.entity.ActivityRegistration;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ActivityOrderMapper;
+import com.etotem.cfc.mapper.ActivityRegistrationMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+@Slf4j
+@Service
+public class ActivityOrderService {
+
+    @Resource
+    private ActivityOrderMapper orderMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private ActivityRegistrationMapper registrationMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private PaymentService paymentService;
+
+    @Resource
+    private ActivityRegistrationService registrationService;
+
+    public Result<Map<String, Object>> create(Long activityId, Long userId, List<Map<String, Object>> registrants) {
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+        if (!"published".equals(activity.getStatus())) return Result.error("活动未发布");
+        if (activity.getRequireRegistration() != null && activity.getRequireRegistration() == 0) {
+            return Result.error("该活动无需报名");
+        }
+        if (activity.getRegistrationDeadline() != null
+                && activity.getRegistrationDeadline().toInstant().isBefore(java.time.Instant.now())) {
+            return Result.error("报名已截止");
+        }
+        if (registrants == null || registrants.isEmpty()) return Result.error("报名人不能为空");
+
+        String memberLevel = null;
+        try { memberLevel = membershipService.getMemberLevel(userId); } catch (Exception e) { /* ignore */ }
+        boolean isMember = "FAMILY".equals(memberLevel) || "PREMIUM".equals(memberLevel);
+
+        // A2 §2.5 仅会员参加硬门禁:audience_scope=member_only 时,非会员拒绝、非登录用户引导登录(后端硬门禁,前端提示仅作体验优化)
+        String gateMessage = memberOnlyGateMessage(activity, userId, isMember);
+        if (gateMessage != null) return Result.error(gateMessage);
+
+        int totalAmount = 0;
+        List<Map<String, Object>> snapshot = new ArrayList<>();
+        Map<Long, Integer> memberAgeMap = loadMemberAges(registrants);
+        for (Map<String, Object> reg : registrants) {
+            String name = (String) reg.get("name");
+            if (name == null || name.trim().isEmpty()) return Result.error("报名人姓名不能为空");
+            String phone = (String) reg.get("phone");
+            Object memberIdObj = reg.get("memberId");
+            Long memberId = memberIdObj != null ? Long.valueOf(memberIdObj.toString()) : null;
+            if (memberId != null && isRegistered(activityId, memberId)) {
+                return Result.error("已报名: " + name);
+            }
+            // A2 §2.4 按参与者身份分类计费:self(本人)/child(age<18)/elder(age>=60)/adult(其他成年家庭成员),
+            // 不再用「memberId 非空即孩子」的旧语义;age 为空一律回落 adult,绝不按 child 处理(否则会多收费)
+            String participantType = classifyParticipant(memberId, memberAgeMap.get(memberId));
+            Integer fee = resolveFee(activity, participantType, isMember);
+            totalAmount += fee;
+            Map<String, Object> item = new HashMap<>();
+            item.put("name", name.trim());
+            item.put("phone", phone != null ? phone.trim() : null);
+            item.put("memberId", memberId);
+            item.put("type", participantType);
+            item.put("fee", fee);
+            snapshot.add(item);
+        }
+
+        if (totalAmount == 0) {
+            List<Long> registrationIds = writeRegistrations(activityId, userId, snapshot, "approved");
+            Map<String, Object> result = new HashMap<>();
+            result.put("registrationIds", registrationIds);
+            result.put("count", registrationIds.size());
+            result.put("totalAmount", 0);
+            result.put("free", true);
+            return Result.success(result);
+        }
+
+        ActivityOrder order = new ActivityOrder();
+        order.setOrderNo("ACT" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase());
+        order.setActivityId(activityId);
+        order.setUserId(userId);
+        order.setTotalAmount(totalAmount);
+        order.setRegistrantsJson(JSON.toJSONString(snapshot));
+        order.setStatus("pending");
+        order.setCreatedAt(new Date());
+        orderMapper.insert(order);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("orderId", order.getId());
+        result.put("orderNo", order.getOrderNo());
+        result.put("totalAmount", totalAmount);
+        result.put("requiresPayment", true);
+        return Result.success(result);
+    }
+
+    /** 报名人身份分类(写入订单快照 type 字段,与 A2 §2.4 一致) */
+    static final String TYPE_SELF = "self";
+    static final String TYPE_CHILD = "child";
+    static final String TYPE_ELDER = "elder";
+    static final String TYPE_ADULT = "adult";
+
+    /** 儿童年龄上限(不含):age < 18 视为儿童 */
+    static final int CHILD_AGE_MAX_EXCLUSIVE = 18;
+    /** 长者年龄下限(含):age >= 60 视为长者 */
+    static final int ELDER_AGE_MIN = 60;
+
+    /** 批量预取报名人年龄,避免逐人查库(N+1) */
+    private Map<Long, Integer> loadMemberAges(List<Map<String, Object>> registrants) {
+        Map<Long, Integer> ageMap = new HashMap<>();
+        List<Long> memberIds = new ArrayList<>();
+        for (Map<String, Object> reg : registrants) {
+            Object memberIdObj = reg.get("memberId");
+            if (memberIdObj == null) continue;
+            Long memberId;
+            try {
+                memberId = Long.valueOf(memberIdObj.toString());
+            } catch (NumberFormatException e) {
+                continue;
+            }
+            if (memberId != null && !memberIds.contains(memberId)) {
+                memberIds.add(memberId);
+            }
+        }
+        if (memberIds.isEmpty()) return ageMap;
+        List<FamilyMember> members = familyMemberMapper.selectBatchIds(memberIds);
+        if (members == null) return ageMap;
+        for (FamilyMember member : members) {
+            if (member == null || member.getId() == null) continue;
+            ageMap.put(member.getId(), resolveAge(member));
+        }
+        return ageMap;
+    }
+
+    /**
+     * 取报名人年龄。FamilyMember.getAge() 在 birthday 为空时返回 0(int 基础类型),
+     * 直接消费会把「年龄未知」误判成 0 岁儿童并错收 childFee,故此处显式返回 null 表示未知。
+     */
+    static Integer resolveAge(FamilyMember member) {
+        if (member == null || member.getBirthday() == null) return null;
+        return member.getAge();
+    }
+
+    /**
+     * 报名人身份分类:
+     * self  = 未关联家庭成员(下单人本人,不含儿童语义)
+     * child = 家庭成员且 age < 18
+     * elder = 家庭成员且 age >= 60
+     * adult = 其他成年家庭成员
+     *
+     * 判定只用 FamilyMember 现有字段(age,源自 birthday),不新增角色字段;
+     * 关键回归点:age 为空一律回落 adult,绝不可按 child 处理。
+     */
+    static String classifyParticipant(Long memberId, Integer age) {
+        if (memberId == null) return TYPE_SELF;
+        if (age == null) return TYPE_ADULT;
+        if (age < CHILD_AGE_MAX_EXCLUSIVE) return TYPE_CHILD;
+        if (age >= ELDER_AGE_MIN) return TYPE_ELDER;
+        return TYPE_ADULT;
+    }
+
+    /**
+     * 成人档非会员价(分):优先新列 price,回退历史别名 parentFee。
+     * parentFee 已降级为「成人非会员价」的历史别名(老活动不改数据、不做回迁)。
+     */
+    static Integer resolveAdultNonMemberFee(Activity activity) {
+        Integer price = activity.getPrice();
+        if (price != null && price > 0) return price;
+        Integer parentFee = activity.getParentFee();
+        return parentFee != null ? parentFee : 0;
+    }
+
+    /**
+     * 成人档会员价(分):优先新列 memberPrice。
+     * - memberPrice > 0 → 新列会员价
+     * - memberPrice == null → 存量别名路径:老活动从未写入过 memberPrice,沿用 parentMemberFee
+     *   的历史语义(0=免费),原样保留以免改动存量活动的收费结果
+     * - memberPrice == 0 → 新模型下「会员价留空/为 0」= 同非会员价(§2.2)
+     */
+    static Integer resolveAdultMemberFee(Activity activity) {
+        Integer memberPrice = activity.getMemberPrice();
+        if (memberPrice != null && memberPrice > 0) return memberPrice;
+        if (memberPrice == null) {
+            Integer parentMemberFee = activity.getParentMemberFee();
+            return parentMemberFee != null ? parentMemberFee : resolveAdultNonMemberFee(activity);
+        }
+        return resolveAdultNonMemberFee(activity);
+    }
+
+    /**
+     * 按参与者身份解析单人结算金额(分)。
+     * child → childFee / childMemberFee(与改造前完全一致);
+     * self / elder / adult → 成人档 price / memberPrice(含 parentFee / parentMemberFee 历史别名回退)。
+     * 长者不新增独立价格列(决策 D1),复用成人价,audience_type 仅作展示与筛选标签。
+     */
+    static Integer resolveFee(Activity activity, String participantType, boolean isMember) {
+        if (TYPE_CHILD.equals(participantType)) {
+            Integer childFee = isMember ? activity.getChildMemberFee() : activity.getChildFee();
+            return childFee != null ? childFee : 0;
+        }
+        Integer adultFee = isMember ? resolveAdultMemberFee(activity) : resolveAdultNonMemberFee(activity);
+        return adultFee != null ? adultFee : 0;
+    }
+
+    /**
+     * A2 §2.5 仅会员参加硬门禁:audience_scope=member_only 时仅会员可下单。
+     * 范式对齐 TaskController.checkMemberOnly(后端硬门禁,前端提示仅作体验优化)。
+     *
+     * @return 拦截时的错误文案;通过时返回 null
+     */
+    static String memberOnlyGateMessage(Activity activity, Long userId, boolean isMember) {
+        if (activity == null || !"member_only".equals(activity.getAudienceScope())) return null;
+        if (userId == null) return "请先登录后再报名";
+        if (!isMember) return "该活动仅会员可参加";
+        return null;
+    }
+
+    public Result<Map<String, Object>> pay(String orderNo, Long userId) {
+        ActivityOrder order = getByOrderNo(orderNo);
+        if (order == null) return Result.error("订单不存在");
+        if (!order.getUserId().equals(userId)) return Result.error("无权操作此订单");
+        if (!"pending".equals(order.getStatus())) return Result.error("订单状态异常");
+        User user = userMapper.selectById(userId);
+        String openid = user == null ? null : user.getOpenid();
+        boolean invalidOpenid = openid == null || openid.isEmpty()
+                || openid.startsWith("phone:") || openid.startsWith("mock_openid_");
+        if (invalidOpenid) {
+            return Result.error("未绑定微信账号,请通过微信登录后再支付");
+        }
+        Activity activity = activityMapper.selectById(order.getActivityId());
+        String description = (activity != null && activity.getTitle() != null)
+                ? "活动报名-" + activity.getTitle()
+                : "活动报名";
+        Map<String, Object> wechatPayParams = paymentService.createWechatPrepay(
+                orderNo, description, order.getTotalAmount(), openid);
+        Map<String, Object> result = new HashMap<>();
+        result.put("wechatPayParams", wechatPayParams);
+        result.put("orderNo", orderNo);
+        return Result.success(result);
+    }
+
+    @Transactional
+    public Result<String> handlePaymentSuccess(String orderNo, String transactionId) {
+        ActivityOrder order = getByOrderNo(orderNo);
+        if (order == null) return Result.error("订单不存在");
+        if (!"pending".equals(order.getStatus())) {
+            return Result.success("订单状态非待支付,跳过");
+        }
+        order.setStatus("paid");
+        order.setTransactionId(transactionId);
+        order.setPaidAt(new Date());
+        orderMapper.updateById(order);
+
+        List<Map<String, Object>> snapshot = JSON.parseObject(order.getRegistrantsJson(),
+            new TypeReference<List<Map<String, Object>>>() {});
+        writeRegistrations(order.getActivityId(), order.getUserId(), snapshot, "approved");
+        return Result.success("支付成功");
+    }
+
+    public Result<Map<String, Object>> status(String orderNo) {
+        ActivityOrder order = getByOrderNo(orderNo);
+        if (order == null) return Result.error("订单不存在");
+        Map<String, Object> result = new HashMap<>();
+        result.put("orderNo", order.getOrderNo());
+        result.put("status", order.getStatus());
+        result.put("totalAmount", order.getTotalAmount());
+        result.put("paidAt", order.getPaidAt());
+        return Result.success(result);
+    }
+
+    private List<Long> writeRegistrations(Long activityId, Long userId, List<Map<String, Object>> snapshot, String status) {
+        List<Long> ids = new ArrayList<>();
+        for (Map<String, Object> item : snapshot) {
+            Object memberIdObj = item.get("memberId");
+            Long memberId = memberIdObj != null ? Long.valueOf(memberIdObj.toString()) : null;
+            if (memberId != null && isRegistered(activityId, memberId)) continue;
+            // 报名通过(免审/支付成功)时占用名额;名额已满则跳过该报名人(退款见 P0-2)
+            if ("approved".equals(status) && !registrationService.occupyQuota(activityId)) {
+                log.warn("活动 {} 名额已满,跳过报名人 {}", activityId, item.get("name"));
+                continue;
+            }
+            ActivityRegistration ar = new ActivityRegistration();
+            ar.setActivityId(activityId);
+            ar.setUserId(userId);
+            ar.setMemberId(memberId);
+            ar.setRegistrantName((String) item.get("name"));
+            ar.setRegistrantPhone((String) item.get("phone"));
+            ar.setStatus(status);
+            ar.setRegisteredAt(LocalDateTime.now());
+            ar.setCreatedAt(LocalDateTime.now());
+            ar.setUpdatedAt(LocalDateTime.now());
+            registrationMapper.insert(ar);
+            ids.add(ar.getId());
+        }
+        return ids;
+    }
+
+    private boolean isRegistered(Long activityId, Long memberId) {
+        return registrationMapper.selectOne(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getMemberId, memberId)
+            .in(ActivityRegistration::getStatus, "pending", "approved").last("LIMIT 1")) != null;
+    }
+
+    private ActivityOrder getByOrderNo(String orderNo) {
+        return orderMapper.selectOne(new LambdaQueryWrapper<ActivityOrder>()
+            .eq(ActivityOrder::getOrderNo, orderNo));
+    }
+}

+ 138 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityPosterTemplateService.java

@@ -0,0 +1,138 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ActivityPosterTemplate;
+import com.etotem.cfc.mapper.ActivityPosterTemplateMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 活动海报模板管理(迁移378)
+ * Web 管理端定义模板(增删改查),小程序端按 status=1 拉取可选模板
+ */
+@Slf4j
+@Service
+public class ActivityPosterTemplateService {
+
+    /** 允许的小程序绘制引擎类型 */
+    private static final List<String> SUPPORTED_KEYS = Arrays.asList("gradient", "minimal", "card");
+
+    /** 小程序端默认兜底配色(未配置模板时使用) */
+    private static final String DEFAULT_MAIN = "#F97316";
+    private static final String DEFAULT_DARK = "#EA580C";
+    private static final String DEFAULT_LIGHT = "#FFF7ED";
+
+    @Resource
+    private ActivityPosterTemplateMapper templateMapper;
+
+    /** 管理端列表(含停用,按排序 + ID 升序) */
+    public Result<List<ActivityPosterTemplate>> listAll() {
+        LambdaQueryWrapper<ActivityPosterTemplate> wrapper = new LambdaQueryWrapper<ActivityPosterTemplate>()
+                .orderByAsc(ActivityPosterTemplate::getSortOrder)
+                .orderByAsc(ActivityPosterTemplate::getId);
+        return Result.success(templateMapper.selectList(wrapper));
+    }
+
+    /**
+     * 小程序端可用模板列表
+     * 当前活动海报是登录后操作(生成海报需先登录),此接口不返回停用模板
+     */
+    public Result<List<ActivityPosterTemplate>> listEnabled() {
+        LambdaQueryWrapper<ActivityPosterTemplate> wrapper = new LambdaQueryWrapper<ActivityPosterTemplate>()
+                .eq(ActivityPosterTemplate::getStatus, 1)
+                .orderByAsc(ActivityPosterTemplate::getSortOrder)
+                .orderByAsc(ActivityPosterTemplate::getId);
+        return Result.success(templateMapper.selectList(wrapper));
+    }
+
+    /** 新增/更新(name 唯一,id 为空为新增) */
+    public Result<ActivityPosterTemplate> save(ActivityPosterTemplate template) {
+        if (template == null) return Result.error("参数不能为空");
+        if (!StringUtils.hasText(template.getName())) {
+            return Result.error("模板名称不能为空");
+        }
+        String key = template.getTemplateKey();
+        if (!StringUtils.hasText(key) || !SUPPORTED_KEYS.contains(key)) {
+            return Result.error("模板类型必须为 gradient/minimal/card 之一");
+        }
+        // 名称唯一性校验
+        ActivityPosterTemplate exists = templateMapper.selectOne(
+                new LambdaQueryWrapper<ActivityPosterTemplate>()
+                        .eq(ActivityPosterTemplate::getName, template.getName().trim())
+                        .last("LIMIT 1"));
+        if (exists != null && (template.getId() == null || !exists.getId().equals(template.getId()))) {
+            return Result.error("模板名称已存在: " + template.getName());
+        }
+        // 色值补充默认值
+        if (!StringUtils.hasText(template.getMainColor())) template.setMainColor(DEFAULT_MAIN);
+        if (!StringUtils.hasText(template.getDarkColor())) template.setDarkColor(DEFAULT_DARK);
+        if (!StringUtils.hasText(template.getLightColor())) template.setLightColor(DEFAULT_LIGHT);
+        // 背景色板校验:空则按单色生成;非法 JSON 拒绝
+        if (StringUtils.hasText(template.getBgColors())) {
+            String bg = template.getBgColors().trim();
+            try {
+                if (!(JSON.parseArray(bg) instanceof List)) {
+                    return Result.error("背景色板必须是 JSON 数组");
+                }
+                template.setBgColors(bg);
+            } catch (Exception e) {
+                return Result.error("背景色板不是合法 JSON 数组");
+            }
+        } else {
+            template.setBgColors("[" + template.getMainColor() + "]");
+        }
+        // 布局配置校验:空则置 null(小程序用内置默认布局);必须是 JSON 对象,非法拒绝
+        if (StringUtils.hasText(template.getLayoutConfig())) {
+            String lc = template.getLayoutConfig().trim();
+            try {
+                if (!(JSON.parse(lc) instanceof JSONObject)) {
+                    return Result.error("布局配置必须是 JSON 对象");
+                }
+                template.setLayoutConfig(lc);
+            } catch (Exception e) {
+                return Result.error("布局配置不是合法 JSON");
+            }
+        } else {
+            template.setLayoutConfig(null);
+        }
+        if (template.getQrSize() == null || template.getQrSize() <= 0) {
+            template.setQrSize(100);
+        }
+        if (template.getSortOrder() == null) {
+            template.setSortOrder(0);
+        }
+        if (template.getStatus() == null) {
+            template.setStatus(1);
+        }
+
+        Date now = new Date();
+        if (template.getId() == null) {
+            template.setCreatedAt(now);
+            template.setUpdatedAt(now);
+            templateMapper.insert(template);
+            log.info("活动海报模板新增: id={}, name={}, key={}", template.getId(), template.getName(), key);
+        } else {
+            template.setUpdatedAt(now);
+            templateMapper.updateById(template);
+            log.info("活动海报模板更新: id={}, name={}, key={}", template.getId(), template.getName(), key);
+        }
+        return Result.success(template);
+    }
+
+    /** 删除 */
+    public Result<Void> delete(Long id) {
+        if (id == null) return Result.error("缺少 id");
+        templateMapper.deleteById(id);
+        log.info("活动海报模板删除: id={}", id);
+        return Result.success(null);
+    }
+}

+ 155 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityProvisionService.java

@@ -0,0 +1,155 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ActivityProvision;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.mapper.ActivityProvisionMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.UUID;
+
+@Service
+public class ActivityProvisionService {
+
+    @Resource
+    private ActivityProvisionMapper activityProvisionMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Resource
+    private PaymentService paymentService;
+
+    public Result<String> provision(Long orderId, Long auditorId) {
+        ProductOrder order = productOrderMapper.selectById(orderId);
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!"unprovisioned".equals(order.getProvisionStatus())) {
+            return Result.error("当前状态不允许审核");
+        }
+        ActivityProvision provision = new ActivityProvision();
+        provision.setOrderId(orderId);
+        provision.setOrderNo(order.getOrderNo());
+        provision.setProductId(order.getProductId());
+        provision.setActivityId(order.getActivityId() != null ? order.getActivityId() : order.getProductId());
+        provision.setBuyerId(order.getBuyerId());
+        provision.setFamilyId(order.getFamilyId());
+        provision.setStatus("provisioned");
+        provision.setQrCode(generateQrCode(order.getOrderNo()));
+        provision.setCreatedAt(new Date());
+        provision.setUpdatedAt(new Date());
+        activityProvisionMapper.insert(provision);
+
+        order.setProvisionStatus("provisioned");
+        order.setAuditorId(auditorId);
+        order.setAuditedAt(new Date());
+        productOrderMapper.updateById(order);
+        return Result.success("审核通过,已生成签到码");
+    }
+
+    @Transactional
+    public Result<String> cancel(Long orderId, Long auditorId, String reason) {
+        ProductOrder order = productOrderMapper.selectById(orderId);
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!"unprovisioned".equals(order.getProvisionStatus())) {
+            return Result.error("当前状态不允许取消");
+        }
+        ActivityProvision provision = new ActivityProvision();
+        provision.setOrderId(orderId);
+        provision.setOrderNo(order.getOrderNo());
+        provision.setProductId(order.getProductId());
+        provision.setActivityId(order.getActivityId() != null ? order.getActivityId() : order.getProductId());
+        provision.setBuyerId(order.getBuyerId());
+        provision.setFamilyId(order.getFamilyId());
+        provision.setStatus("cancelled");
+        provision.setRefundAmount(order.getTotalAmount());
+        provision.setRefundAt(new Date());
+        provision.setCreatedAt(new Date());
+        provision.setUpdatedAt(new Date());
+        activityProvisionMapper.insert(provision);
+
+        order.setProvisionStatus("cancelled");
+        order.setStatus("cancelled");
+        order.setAuditorId(auditorId);
+        order.setAuditedAt(new Date());
+        order.setAuditReason(reason);
+        productOrderMapper.updateById(order);
+
+        paymentService.refund(order.getOrderNo(), order.getTotalAmount(), "活动审核不通过:" + reason);
+        return Result.success("已拒绝并退款");
+    }
+
+    @Transactional
+    public Result<String> signIn(Long orderId, Long memberId) {
+        ActivityProvision provision = activityProvisionMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ActivityProvision>()
+                .eq(ActivityProvision::getOrderId, orderId)
+        );
+        if (provision == null) {
+            return Result.error("未找到活动 provision 记录");
+        }
+        if (!"provisioned".equals(provision.getStatus())) {
+            return Result.error("当前状态不允许签到");
+        }
+        provision.setMemberId(memberId);
+        provision.setCheckedInAt(new Date());
+        provision.setStatus("signed_in");
+        provision.setUpdatedAt(new Date());
+        activityProvisionMapper.updateById(provision);
+
+        ProductOrder order = productOrderMapper.selectById(orderId);
+        if (order != null) {
+            order.setProvisionStatus("signed_in");
+            productOrderMapper.updateById(order);
+        }
+        return Result.success("签到成功");
+    }
+
+    @Transactional
+    public Result<String> complete(Long orderId) {
+        ActivityProvision provision = activityProvisionMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ActivityProvision>()
+                .eq(ActivityProvision::getOrderId, orderId)
+        );
+        if (provision == null) {
+            return Result.error("未找到活动 provision 记录");
+        }
+        if (!"signed_in".equals(provision.getStatus())) {
+            return Result.error("当前状态不允许完成");
+        }
+        provision.setStatus("completed");
+        provision.setCompletedAt(new Date());
+        provision.setUpdatedAt(new Date());
+        activityProvisionMapper.updateById(provision);
+
+        ProductOrder order = productOrderMapper.selectById(orderId);
+        if (order != null) {
+            order.setProvisionStatus("completed");
+            productOrderMapper.updateById(order);
+        }
+        return Result.success("活动完成");
+    }
+
+    public Result<ActivityProvision> getByOrderId(Long orderId) {
+        ActivityProvision provision = activityProvisionMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ActivityProvision>()
+                .eq(ActivityProvision::getOrderId, orderId)
+        );
+        if (provision == null) {
+            return Result.success(null);
+        }
+        return Result.success(provision);
+    }
+
+    private String generateQrCode(String orderNo) {
+        return "ACT-" + orderNo + "-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
+    }
+}

+ 481 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityRegistrationService.java

@@ -0,0 +1,481 @@
+package com.etotem.cfc.service;
+
+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.DataMaskUtil;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityOrder;
+import com.etotem.cfc.entity.ActivityRegistration;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ActivityOrderMapper;
+import com.etotem.cfc.mapper.ActivityRegistrationMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import javax.annotation.Resource;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+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.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class ActivityRegistrationService {
+    @Resource
+    private ActivityRegistrationMapper registrationMapper;
+    @Resource
+    private ActivityMapper activityMapper;
+    @Resource
+    private ActivityOrderMapper orderMapper;
+    @Resource
+    private PaymentService paymentService;
+
+    @Transactional
+    public Result<Map<String, Object>> batchRegister(Long activityId, Long userId, List<Map<String, Object>> registrants) {
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+        if (!"published".equals(activity.getStatus())) return Result.error("活动未发布");
+        if (activity.getRequireRegistration() != null && activity.getRequireRegistration() == 0) {
+            return Result.error("该活动无需报名");
+        }
+        Result<Void> gate = checkRegistrationGate(activity, userId);
+        if (gate != null) return Result.error(gate.getMessage());
+        boolean needReview = activity.getRequireReview() != null && activity.getRequireReview() == 1;
+        List<Long> ids = new ArrayList<>();
+        for (Map<String, Object> reg : registrants) {
+            String name = (String) reg.get("name");
+            if (name == null || name.trim().isEmpty()) return Result.error("报名人姓名不能为空");
+            String phone = (String) reg.get("phone");
+            Object memberIdObj = reg.get("memberId");
+            Long memberId = memberIdObj != null ? Long.valueOf(memberIdObj.toString()) : null;
+            if (memberId != null) {
+                if (isRegistered(activityId, memberId)) {
+                    return Result.error("已报名: " + name);
+                }
+            }
+            // 免审活动:报名即通过并占用名额;名额已满则中止(已写入的本次批次有效)
+            if (!needReview) {
+                if (!occupyQuota(activityId)) {
+                    return Result.error("名额已满,报名失败(含: " + name + ")");
+                }
+            }
+            ActivityRegistration ar = new ActivityRegistration();
+            ar.setActivityId(activityId); ar.setUserId(userId); ar.setMemberId(memberId);
+            ar.setRegistrantName(name.trim()); ar.setRegistrantPhone(phone != null ? phone.trim() : null);
+            ar.setStatus(needReview ? "pending" : "approved"); ar.setRegisteredAt(LocalDateTime.now());
+            ar.setCreatedAt(LocalDateTime.now()); ar.setUpdatedAt(LocalDateTime.now());
+            if (!needReview) {
+                ar.setApprovedAt(LocalDateTime.now());
+                ar.setApprovedBy(userId);
+            }
+            registrationMapper.insert(ar);
+            ids.add(ar.getId());
+        }
+        Map<String, Object> result = new HashMap<>();
+        result.put("registrationIds", ids);
+        result.put("count", ids.size());
+        return Result.success(result);
+    }
+
+    @Transactional
+    public Result<Map<String, Object>> register(Long activityId, Long userId, Long memberId) {
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+        if (!"published".equals(activity.getStatus())) return Result.error("活动未发布");
+        if (activity.getRequireRegistration() != null && activity.getRequireRegistration() == 0) {
+            return Result.error("该活动无需报名");
+        }
+        Result<Void> gate = checkRegistrationGate(activity, userId);
+        if (gate != null) return Result.error(gate.getMessage());
+        if (isRegistered(activityId, memberId)) return Result.error("您已报名此活动");
+        boolean needReview = activity.getRequireReview() != null && activity.getRequireReview() == 1;
+        // 免审活动:报名即通过并占用名额
+        if (!needReview) {
+            if (!occupyQuota(activityId)) {
+                return Result.error("名额已满,报名失败");
+            }
+        }
+        ActivityRegistration reg = new ActivityRegistration();
+        reg.setActivityId(activityId); reg.setUserId(userId); reg.setMemberId(memberId);
+        reg.setStatus(needReview ? "pending" : "approved"); reg.setRegisteredAt(LocalDateTime.now());
+        reg.setCreatedAt(LocalDateTime.now()); reg.setUpdatedAt(LocalDateTime.now());
+        if (!needReview) {
+            reg.setApprovedAt(LocalDateTime.now());
+            reg.setApprovedBy(userId);
+        }
+        registrationMapper.insert(reg);
+        Map<String, Object> result = new HashMap<>();
+        result.put("registrationId", reg.getId()); result.put("status", reg.getStatus());
+        return Result.success(result);
+    }
+
+    @Transactional
+    public Result<Void> cancel(Long activityId, Long userId, Long memberId) {
+        ActivityRegistration reg = registrationMapper.selectOne(new LambdaQueryWrapper<ActivityRegistration>()
+                .eq(ActivityRegistration::getActivityId, activityId)
+                .eq(ActivityRegistration::getMemberId, memberId)
+                .eq(ActivityRegistration::getUserId, userId)
+                .in(ActivityRegistration::getStatus, "pending", "approved")
+                .last("LIMIT 1"));
+        if (reg == null) return Result.error("报名记录不存在");
+        String prevStatus = reg.getStatus();
+        if ("approved".equals(prevStatus)) {
+            // 付费活动取消:原路退款(金额取该报名人对应 fee;如一单多人则按单退款)
+            ActivityOrder order = orderMapper.selectOne(new LambdaQueryWrapper<ActivityOrder>()
+                    .eq(ActivityOrder::getActivityId, activityId)
+                    .eq(ActivityOrder::getUserId, userId)
+                    .eq(ActivityOrder::getStatus, "paid")
+                    .last("LIMIT 1"));
+            if (order != null) {
+                int refundFee = resolveRegistrantFee(order, memberId);
+                try {
+                    paymentService.refund(order.getOrderNo(), refundFee > 0 ? refundFee : order.getTotalAmount(), "取消活动报名");
+                } catch (Exception e) {
+                    log.error("活动报名退款失败: orderNo={}, memberId={}", order.getOrderNo(), memberId, e);
+                    return Result.error("退款处理失败,请联系客服");
+                }
+                order.setStatus("refunded");
+                orderMapper.updateById(order);
+            }
+            releaseQuota(activityId);
+        }
+        reg.setStatus("cancelled");
+        reg.setCancelledAt(LocalDateTime.now());
+        reg.setUpdatedAt(LocalDateTime.now());
+        registrationMapper.updateById(reg);
+        return Result.success(null);
+    }
+
+    @Transactional
+    public Result<Void> approve(Long registrationId, Long adminUserId) {
+        ActivityRegistration reg = registrationMapper.selectById(registrationId);
+        if (reg == null) return Result.error("报名记录不存在");
+        if (!"pending".equals(reg.getStatus())) return Result.error("当前状态不允许审核");
+        // 审核通过即占用名额(原子校验,满员则无法通过)
+        if (!occupyQuota(reg.getActivityId())) {
+            return Result.error("名额已满,无法通过审核");
+        }
+        reg.setStatus("approved"); reg.setApprovedAt(LocalDateTime.now());
+        reg.setApprovedBy(adminUserId); reg.setUpdatedAt(LocalDateTime.now());
+        registrationMapper.updateById(reg);
+        return Result.success(null);
+    }
+
+    @Transactional
+    public Result<Void> reject(Long registrationId, Long adminUserId) {
+        return reject(registrationId, adminUserId, null);
+    }
+
+    @Transactional
+    public Result<Void> reject(Long registrationId, Long adminUserId, String reason) {
+        ActivityRegistration reg = registrationMapper.selectById(registrationId);
+        if (reg == null) return Result.error("报名记录不存在");
+        if (!"pending".equals(reg.getStatus())) return Result.error("当前状态不允许审核");
+        reg.setStatus("rejected"); reg.setApprovedAt(LocalDateTime.now());
+        reg.setApprovedBy(adminUserId); reg.setUpdatedAt(LocalDateTime.now());
+        if (reason != null && !reason.trim().isEmpty()) {
+            reg.setRejectReason(reason.trim());
+        }
+        registrationMapper.updateById(reg);
+        return Result.success(null);
+    }
+
+    /**
+     * 原子占用一个名额:仅当 approved_count < max_participants 时自增,返回是否成功。
+     * 无人数限制(maxParticipants 为空或 <=0)视为不限,直接自增计数。
+     */
+    @Transactional
+    public boolean occupyQuota(Long activityId) {
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return false;
+        Integer max = activity.getMaxParticipants();
+        if (max != null && max > 0) {
+            int rows = activityMapper.update(null, new UpdateWrapper<Activity>()
+                    .eq("id", activityId)
+                    .lt("approved_count", max)
+                    .setSql("approved_count = approved_count + 1"));
+            return rows > 0;
+        }
+        activityMapper.update(null, new UpdateWrapper<Activity>()
+                .eq("id", activityId)
+                .setSql("approved_count = approved_count + 1"));
+        return true;
+    }
+
+    /** 原子回退一个名额(仅当 approved_count > 0 时减一)。 */
+    @Transactional
+    public void releaseQuota(Long activityId) {
+        activityMapper.update(null, new UpdateWrapper<Activity>()
+                .eq("id", activityId)
+                .gt("approved_count", 0)
+                .setSql("approved_count = approved_count - 1"));
+    }
+
+    public Result<Map<String, Object>> getMyRegistrations(Long userId, Long memberId, Integer page, Integer size, String status) {
+        if (page == null || page < 1) page = 1;
+        if (size == null || size < 1) size = 10;
+        LambdaQueryWrapper<ActivityRegistration> wrapper = new LambdaQueryWrapper<>();
+        if (userId != null) wrapper.eq(ActivityRegistration::getUserId, userId);
+        if (memberId != null) {
+            // 手动录入的报名 child_id 为 NULL,也属于该用户,需一并返回
+            wrapper.and(w -> w.eq(ActivityRegistration::getMemberId, memberId)
+                .or().isNull(ActivityRegistration::getMemberId));
+        }
+        // 小程序「我的活动」筛选芯片:全部/待开始/待审核(pending)/已签到(checked_in)。
+        // 原实现完全忽略 status,导致「待审核」「已签到」筛选失效(后端返回全部状态)。
+        // status 为 null/空(全部)或 upcoming(前端本地按 startTime 过滤)时不加条件。
+        if (status != null && !status.trim().isEmpty()) {
+            wrapper.eq(ActivityRegistration::getStatus, status.trim());
+        }
+        wrapper.orderByDesc(ActivityRegistration::getRegisteredAt);
+        SortUtil.applySort(wrapper);
+        Page<ActivityRegistration> pageResult = registrationMapper.selectPage(new Page<>(page, size), wrapper);
+        List<Map<String, Object>> records = pageResult.getRecords().stream().map(reg -> {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", reg.getId()); item.put("activityId", reg.getActivityId());
+            item.put("memberId", reg.getMemberId()); item.put("status", reg.getStatus());
+            item.put("registrantName", reg.getRegistrantName());
+            item.put("registrantPhone", reg.getRegistrantPhone());
+            item.put("registeredAt", reg.getRegisteredAt());
+            Activity activity = activityMapper.selectById(reg.getActivityId());
+            if (activity != null) {
+                // 小程序「我的活动/历史记录」卡片需要活动维度的展示字段,
+                // 只返回 activityTitle/activityStartTime 会让前端标题、时间、封面、费用全部为空
+                item.put("activityTitle", activity.getTitle());
+                item.put("activityStartTime", activity.getStartTime());
+                item.put("activityEndTime", activity.getEndTime());
+                item.put("activityStatus", activity.getStatus());
+                item.put("activityCoverImage", activity.getCoverImage());
+                item.put("activityLocation", activity.getLocation());
+                item.put("activityChildFee", activity.getChildFee());
+                item.put("activityChildMemberFee", activity.getChildMemberFee());
+                item.put("activityParentFee", activity.getParentFee());
+                item.put("activityParentMemberFee", activity.getParentMemberFee());
+            }
+            return item;
+        }).collect(Collectors.toList());
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", records); data.put("total", pageResult.getTotal());
+        data.put("page", pageResult.getCurrent()); data.put("size", pageResult.getSize());
+        return Result.success(data);
+    }
+
+    public Result<List<Map<String, Object>>> getRegistrationsByActivity(Long activityId, String status) {
+        LambdaQueryWrapper<ActivityRegistration> wrapper = new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId).orderByDesc(ActivityRegistration::getRegisteredAt);
+        if (status != null && !status.isEmpty()) wrapper.eq(ActivityRegistration::getStatus, status);
+        SortUtil.applySort(wrapper);
+        List<ActivityRegistration> list = registrationMapper.selectList(wrapper);
+        List<Map<String, Object>> result = list.stream().map(reg -> {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", reg.getId()); item.put("memberId", reg.getMemberId());
+            item.put("userId", reg.getUserId()); item.put("status", reg.getStatus());
+            item.put("registrantName", reg.getRegistrantName());
+            item.put("registrantPhone", reg.getRegistrantPhone());
+            item.put("registeredAt", reg.getRegisteredAt());
+            return item;
+        }).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    /**
+     * 活动详情页「报名情况」:面向所有访客(含游客)返回脱敏的报名统计与最近已通过报名人。
+     * - approvedCount 已通过人数、pendingCount 待审核人数、remaining 剩余名额(无人数限制时为 null)
+     * - registrants 最多 20 条已通过报名人(姓名脱敏,按报名时间倒序),不返回手机号
+     */
+    public Result<Map<String, Object>> getRegistrationRoster(Long activityId) {
+        if (activityId == null) return Result.error("活动ID不能为空");
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) return Result.error("活动不存在");
+
+        long pendingCount = registrationMapper.selectCount(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getStatus, "pending"));
+
+        List<ActivityRegistration> approvedList = registrationMapper.selectList(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getStatus, "approved")
+            .orderByDesc(ActivityRegistration::getRegisteredAt)
+            .last("LIMIT 20"));
+
+        List<Map<String, Object>> registrants = approvedList.stream().map(reg -> {
+            Map<String, Object> item = new HashMap<>();
+            item.put("name", DataMaskUtil.maskName(reg.getRegistrantName()));
+            item.put("registeredAt", reg.getRegisteredAt());
+            return item;
+        }).collect(Collectors.toList());
+
+        Integer max = activity.getMaxParticipants();
+        // 名额占用以 approved_count 列(原子维护)为准,与报名审核状态一致
+        Integer approved = activity.getApprovedCount() != null ? activity.getApprovedCount() : 0;
+        Integer remaining = null;
+        if (max != null && max > 0) {
+            remaining = (int) Math.max(0, max - approved);
+        }
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("activityId", activityId);
+        data.put("maxParticipants", max != null ? max : 0);
+        data.put("approvedCount", approved);
+        data.put("pendingCount", pendingCount);
+        data.put("remaining", remaining);
+        data.put("registrants", registrants);
+        return Result.success(data);
+    }
+
+    /**
+     * 管理端报名列表:activityId 为空时返回全部(可按状态过滤),补充活动标题与驳回原因。
+     */
+    public Result<List<Map<String, Object>>> listRegistrationsForAdmin(Long activityId, String status) {
+        LambdaQueryWrapper<ActivityRegistration> wrapper = new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(activityId != null, ActivityRegistration::getActivityId, activityId)
+            .orderByDesc(ActivityRegistration::getRegisteredAt);
+        if (status != null && !status.isEmpty()) wrapper.eq(ActivityRegistration::getStatus, status);
+        SortUtil.applySort(wrapper);
+        List<ActivityRegistration> list = registrationMapper.selectList(wrapper);
+
+        Set<Long> activityIds = new HashSet<>();
+        for (ActivityRegistration reg : list) {
+            if (reg.getActivityId() != null) activityIds.add(reg.getActivityId());
+        }
+        Map<Long, String> titleMap = new HashMap<>();
+        if (!activityIds.isEmpty()) {
+            List<Activity> activities = activityMapper.selectBatchIds(activityIds);
+            if (activities != null) {
+                for (Activity a : activities) titleMap.put(a.getId(), a.getTitle());
+            }
+        }
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (ActivityRegistration reg : list) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", reg.getId());
+            item.put("activityId", reg.getActivityId());
+            item.put("activityTitle", reg.getActivityId() != null ? titleMap.get(reg.getActivityId()) : null);
+            item.put("memberId", reg.getMemberId());
+            item.put("userId", reg.getUserId());
+            item.put("status", reg.getStatus());
+            item.put("registrantName", reg.getRegistrantName());
+            item.put("registrantPhone", reg.getRegistrantPhone());
+            item.put("rejectReason", reg.getRejectReason());
+            item.put("registeredAt", reg.getRegisteredAt());
+            result.add(item);
+        }
+        return Result.success(result);
+    }
+
+    public Map<Long, String> getRegistrationStatusMap(List<Long> activityIds, Long userId) {        Map<Long, String> map = new HashMap<>();
+        if (activityIds == null || activityIds.isEmpty() || userId == null) return map;
+        List<ActivityRegistration> regs = registrationMapper.selectList(new LambdaQueryWrapper<ActivityRegistration>()
+            .in(ActivityRegistration::getActivityId, activityIds)
+            .eq(ActivityRegistration::getUserId, userId)
+            .in(ActivityRegistration::getStatus, "pending", "approved", "rejected"));
+        for (ActivityRegistration reg : regs) {
+            String cur = reg.getStatus();
+            String prev = map.get(reg.getActivityId());
+            // 优先级: approved > pending > rejected
+            if (prev == null || rank(prev) < rank(cur)) {
+                map.put(reg.getActivityId(), cur);
+            }
+        }
+        return map;
+    }
+
+    public String getUserRegistrationStatus(Long activityId, Long userId) {
+        Map<Long, String> map = getRegistrationStatusMap(Collections.singletonList(activityId), userId);
+        return map.getOrDefault(activityId, "not_registered");
+    }
+
+    public List<Long> getMemberIdsByUser(Long userId) {
+        if (userId == null) return new ArrayList<>();
+        return registrationMapper.selectList(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getUserId, userId)
+            .isNotNull(ActivityRegistration::getMemberId))
+            .stream().map(ActivityRegistration::getMemberId).distinct().collect(Collectors.toList());
+    }
+
+    private int rank(String status) {
+        if ("approved".equals(status)) return 3;
+        if ("pending".equals(status)) return 2;
+        return 1;
+    }
+
+    private Result<Void> checkRegistrationGate(Activity activity, Long userId) {
+        if (activity.getRegistrationDeadline() != null
+                && activity.getRegistrationDeadline().toInstant().isBefore(java.time.Instant.now())) {
+            return Result.error("报名已截止");
+        }
+        boolean isPaid = (activity.getChildFee() != null && activity.getChildFee() > 0)
+                || (activity.getChildMemberFee() != null && activity.getChildMemberFee() > 0)
+                || (activity.getParentFee() != null && activity.getParentFee() > 0)
+                || (activity.getParentMemberFee() != null && activity.getParentMemberFee() > 0);
+        if (isPaid && !hasPaidOrder(activity.getId(), userId)) {
+            return Result.error("该活动为付费活动,请先完成支付后再报名");
+        }
+        return null;
+    }
+
+    private boolean hasPaidOrder(Long activityId, Long userId) {
+        if (activityId == null || userId == null) return false;
+        return orderMapper.selectCount(new LambdaQueryWrapper<ActivityOrder>()
+            .eq(ActivityOrder::getActivityId, activityId)
+            .eq(ActivityOrder::getUserId, userId)
+            .eq(ActivityOrder::getStatus, "paid")) > 0;
+    }
+
+    public boolean isRegistered(Long activityId, Long memberId) {
+        return registrationMapper.selectOne(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getMemberId, memberId)
+            .in(ActivityRegistration::getStatus, "pending", "approved").last("LIMIT 1")) != null;
+    }
+
+    public boolean isApproved(Long activityId, Long memberId) {
+        return registrationMapper.selectOne(new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getMemberId, memberId)
+            .eq(ActivityRegistration::getStatus, "approved").last("LIMIT 1")) != null;
+    }
+
+    private int resolveRegistrantFee(ActivityOrder order, Long memberId) {
+        if (order.getRegistrantsJson() == null) return 0;
+        try {
+            com.alibaba.fastjson.TypeReference<java.util.List<java.util.Map<String, Object>>> typeRef
+                    = new com.alibaba.fastjson.TypeReference<java.util.List<java.util.Map<String, Object>>>() {};
+            java.util.List<java.util.Map<String, Object>> list
+                    = com.alibaba.fastjson.JSON.parseObject(order.getRegistrantsJson(), typeRef);
+            if (list != null) {
+                for (java.util.Map<String, Object> item : list) {
+                    Object mid = item.get("memberId");
+                    if (mid != null && memberId != null
+                            && String.valueOf(mid).equals(String.valueOf(memberId))) {
+                        Object fee = item.get("fee");
+                        if (fee instanceof Number) return ((Number) fee).intValue();
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析报名人 fee 失败: orderNo={}, memberId={}", order.getOrderNo(), memberId, e);
+        }
+        return 0;
+    }
+
+    private ActivityRegistration findRegistration(Long activityId, Long memberId, Long userId, String status) {
+        LambdaQueryWrapper<ActivityRegistration> wrapper = new LambdaQueryWrapper<ActivityRegistration>()
+            .eq(ActivityRegistration::getActivityId, activityId)
+            .eq(ActivityRegistration::getMemberId, memberId)
+            .eq(ActivityRegistration::getUserId, userId);
+        if (status != null) wrapper.eq(ActivityRegistration::getStatus, status);
+        wrapper.last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        return registrationMapper.selectOne(wrapper);
+    }
+}

+ 674 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityService.java

@@ -0,0 +1,674 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ActivityDTO;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityRegistration;
+import com.etotem.cfc.entity.ContentDimensionThreshold;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.PointsLog;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.PointsLogMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.DimensionCodes;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class ActivityService extends ServiceImpl<ActivityMapper, Activity> {
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private PointsLogMapper pointsLogMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @Resource
+    private ActivityRegistrationService registrationService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FiveDimensionScoreService fiveDimensionScoreService;
+
+    @Resource
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+
+    @Resource
+    private CfEarnDispatchService cfEarnDispatchService;
+
+    public Result<Map<String, Object>> list(String dimensionCode, Integer page, Integer size, Long userId) {
+        autoEndExpiredActivities();
+        LambdaQueryWrapper<Activity> query = new LambdaQueryWrapper<Activity>()
+                .eq(Activity::getStatus, "published")
+                .orderByAsc(Activity::getStartTime);
+        if (dimensionCode != null && !dimensionCode.isEmpty() && DimensionCodes.isValid(dimensionCode)) {
+            String dim = dimensionCode.trim();
+            // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 dimension_code
+            query.and(w -> w
+                .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                .or().eq(Activity::getDimensionCode, dim)
+            );
+        }
+        // 游客过滤:只返回公开活动
+        if (userId == null) {
+            query.and(w -> w.eq(Activity::getVisibility, "public")
+                    .or().eq(Activity::getVisibility, "all")
+                    .or().isNull(Activity::getVisibility));
+        }
+        SortUtil.applySort(query);
+        Page<Activity> pageResult = this.page(new Page<>(page, size), query);
+        boolean isGuest = (userId == null || userId <= 0);
+        Long effectiveUserId = isGuest ? null : userId;
+        String memberLevel = null;
+        if (!isGuest) {
+            try { memberLevel = membershipService.getMemberLevel(userId); } catch (Exception e) { /* ignore */ }
+        }
+        final String level = memberLevel;
+        List<Activity> records = pageResult.getRecords();
+        // 内容维度阈值显隐过滤(A-后端):OR 逻辑,fail-open 不误隐藏(游客无家庭上下文时全保留)
+        applyDimensionThresholdFilter(records, userId, isGuest);
+        List<Long> activityIds = records.stream().map(Activity::getId).collect(Collectors.toList());
+        Map<Long, String> regStatusMap = new HashMap<>();
+        Set<Long> checkedInActivityIds = new HashSet<>();
+        if (effectiveUserId != null && !activityIds.isEmpty()) {
+            regStatusMap = registrationService.getRegistrationStatusMap(activityIds, effectiveUserId);
+            List<Long> memberIds = registrationService.getMemberIdsByUser(effectiveUserId);
+            if (!memberIds.isEmpty()) {
+                checkedInActivityIds = taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                    .eq(Task::getSourceType, "activity")
+                    .in(Task::getSourceId, activityIds)
+                    .in(Task::getMemberId, memberIds)
+                    .eq(Task::getStatus, "completed"))
+                    .stream().map(Task::getSourceId).collect(Collectors.toSet());
+            }
+        }
+        final Map<Long, String> regMap = regStatusMap;
+        final Set<Long> checkedMap = checkedInActivityIds;
+        List<ActivityDTO> dtos = records.stream().map(a -> {
+            ActivityDTO dto = ActivityDTO.from(a, isGuest, level);
+            String regStatus = regMap.getOrDefault(a.getId(), "not_registered");
+            applyDisplayState(dto, a, regStatus, checkedMap.contains(a.getId()));
+            return dto;
+        }).collect(Collectors.toList());
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", dtos);
+        data.put("total", pageResult.getTotal());
+        data.put("page", pageResult.getCurrent());
+        data.put("size", pageResult.getSize());
+        return Result.success(data);
+    }
+
+    /**
+     * 内容维度阈值显隐过滤(A-后端)。
+     * 从登录用户上下文取 familyId;游客或无家庭得分数据时 fail-open 不误隐藏。
+     * 显隐规则(OR 逻辑):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
+     */
+    private void applyDimensionThresholdFilter(List<Activity> records, Long userId, boolean isGuest) {
+        if (records == null || records.isEmpty()) return;
+        Long familyId = null;
+        if (!isGuest && userId != null && userId > 0) {
+            try {
+                User u = userMapper.selectById(userId);
+                if (u != null) familyId = u.getFamilyId();
+            } catch (Exception ignore) { /* 取不到 familyId 则 fail-open */ }
+        }
+        Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
+        if (familyAvg.isEmpty()) return; // 无家庭得分数据 → fail-open
+        List<Long> ids = records.stream().map(Activity::getId).collect(Collectors.toList());
+        Map<Long, List<ContentDimensionThreshold>> byId =
+                contentDimensionThresholdService.listByContents("ACTIVITY", ids);
+        DimensionThresholdFilter.filterVisible(records, Activity::getId, "ACTIVITY", familyAvg, byId);
+    }
+
+    public Result<ActivityDTO> detail(Long id, Long userId) {
+        Activity activity = this.getById(id);
+        if (activity == null) {
+            return Result.error("活动不存在");
+        }
+        boolean isGuest = (userId == null || userId <= 0);
+        String memberLevel = null;
+        if (!isGuest) {
+            try { memberLevel = membershipService.getMemberLevel(userId); } catch (Exception e) { /* ignore */ }
+        }
+        ActivityDTO dto = ActivityDTO.from(activity, isGuest, memberLevel);
+        // applyDisplayState must run for ALL users (including guests) so that
+        // displayStatus / displayLabel / registrationStatus are always populated.
+        // For guests: registrationStatus=null, checkedIn=false → defaults to "open"/"not_registered".
+        if (!isGuest) {
+            String regStatus = registrationService.getUserRegistrationStatus(activity.getId(), userId);
+            boolean checkedIn = hasCheckedIn(activity.getId(), userId);
+            applyDisplayState(dto, activity, regStatus, checkedIn);
+        } else {
+            applyDisplayState(dto, activity, null, false);
+        }
+        return Result.success(dto);
+    }
+
+    public Result<ActivityDTO> create(Activity activity, Long creatorId) {
+        // 配置校验(S-cfc-316 admin.activity.config):时间冲突(SC-A-07 / TC-A-13-E)
+        if (activity.getStartTime() != null && activity.getEndTime() != null
+                && activity.getStartTime().after(activity.getEndTime())) {
+            return Result.badRequest("活动时间冲突:开始时间不能晚于结束时间");
+        }
+        activity.setStatus("draft");
+        activity.setCurrentParticipants(0);
+        activity.setApprovedCount(0);
+        activity.setSignedCount(0);
+        activity.setCreatorId(creatorId);
+        activity.setCreatedAt(new Date());
+        activity.setUpdatedAt(new Date());
+        this.save(activity);
+        return Result.success(ActivityDTO.from(activity));
+    }
+
+    public Result<ActivityDTO> update(Activity activity) {
+        Activity existing = this.getById(activity.getId());
+        if (existing == null) {
+            return Result.error("活动不存在");
+        }
+        // 配置校验(S-cfc-316 admin.activity.config):时间冲突 / 名额超卖(SC-A-17 / TC-A-18-E)
+        Date startTime = activity.getStartTime() != null ? activity.getStartTime() : existing.getStartTime();
+        Date endTime = activity.getEndTime() != null ? activity.getEndTime() : existing.getEndTime();
+        if (startTime != null && endTime != null && startTime.after(endTime)) {
+            return Result.badRequest("活动时间冲突:开始时间不能晚于结束时间");
+        }
+        Integer approvedCount = activity.getApprovedCount() != null
+                ? activity.getApprovedCount() : existing.getApprovedCount();
+        Integer maxParticipants = activity.getMaxParticipants() != null
+                ? activity.getMaxParticipants() : existing.getMaxParticipants();
+        if (approvedCount != null && maxParticipants != null && approvedCount > maxParticipants) {
+            return Result.badRequest("活动名额超卖保护:已审核人数不能大于最大参与人数");
+        }
+        activity.setUpdatedAt(new Date());
+        this.updateById(activity);
+        return Result.success(ActivityDTO.from(this.getById(activity.getId())));
+    }
+
+    public Result<String> publish(Long id) {
+        Activity activity = this.getById(id);
+        if (activity == null) {
+            return Result.notFound("活动不存在");
+        }
+        if (!"draft".equals(activity.getStatus())) {
+            return Result.conflict("仅草稿状态可发布");
+        }
+        // P1-2: 发布前校验维度代码,两路(直发/审核流)统一要求 dimensionCode 非空
+        if (activity.getDimensionCode() == null || activity.getDimensionCode().trim().isEmpty()) {
+            return Result.badRequest("请先设置活动维度(dimensionCode)");
+        }
+        activity.setStatus("published");
+        activity.setUpdatedAt(new Date());
+        this.updateById(activity);
+        return Result.success("发布成功");
+    }
+
+    public Result<String> end(Long id) {
+        Activity activity = this.getById(id);
+        if (activity == null) {
+            return Result.notFound("活动不存在");
+        }
+        activity.setStatus("ended");
+        activity.setUpdatedAt(new Date());
+        this.updateById(activity);
+        return Result.success("活动已结束");
+    }
+
+    @Transactional
+    public Map<String, Object> checkin(Long activityId, Long userId, Long memberId) {
+        Map<String, Object> result = new HashMap<>();
+        result.put("taskId", null);
+        result.put("pointsEarned", 0);
+
+        // 1. Validate activity exists and is active
+        Activity activity = this.getById(activityId);
+        if (activity == null) {
+            result.put("error", "活动不存在");
+            return result;
+        }
+        if (!"published".equals(activity.getStatus())) {
+            result.put("error", "活动未发布或已结束");
+            return result;
+        }
+
+        // 1.5 Time window check — checkin only allowed during the activity
+        Date now = new Date();
+        if (activity.getStartTime() != null && now.before(activity.getStartTime())) {
+            result.put("error", "活动尚未开始,暂不能签到");
+            return result;
+        }
+        if (activity.getEndTime() != null && now.after(activity.getEndTime())) {
+            result.put("error", "活动已结束,不能签到");
+            return result;
+        }
+
+        // 2. If no memberId, can't create task
+        if (memberId == null) {
+            result.put("error", "需要家庭成员身份签到");
+            return result;
+        }
+
+        // 2.5 Identity: phone child self-checkin only; phone-less child allows same-family proxy
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child == null) {
+            result.put("error", "成员不存在");
+            return result;
+        }
+        boolean childHasPhone = StringUtils.hasText(child.getPhone());
+        if (childHasPhone) {
+            boolean isSelf = child.getUserId() != null && child.getUserId().equals(userId);
+            if (!isSelf) {
+                result.put("error", "有手机号的成员只能本人签到");
+                return result;
+            }
+        } else {
+            User operator = userMapper.selectById(userId);
+            boolean sameFamily = operator != null && operator.getFamilyId() != null
+                    && operator.getFamilyId().equals(child.getFamilyId());
+            if (!sameFamily) {
+                result.put("error", "无权限代签(需同一家庭)");
+                return result;
+            }
+        }
+
+        // 3. Registration check (if activity requires registration)
+        boolean unregistered = false;
+        if (activity.getRequireRegistration() != null && activity.getRequireRegistration() == 1) {
+            boolean isApproved = registrationService.isApproved(activityId, memberId);
+            boolean isRegistered = registrationService.isRegistered(activityId, memberId);
+            if (!isApproved) {
+                if (isRegistered) {
+                    result.put("error", "报名待审核,请等待审核通过");
+                    return result;
+                }
+                // Not registered at all — apply energy penalty, allow checkin anyway
+                unregistered = true;
+                Integer penaltyAmount = activity.getEnergyPenaltyUnregistered();
+                if (penaltyAmount != null && penaltyAmount > 0) {
+                    try {
+                        int deducted = energyService.deductEnergyByCode(
+                            memberId,
+                            activity.getDimensionCode(),
+                            penaltyAmount,
+                            "未报名签到活动《" + activity.getTitle() + "》"
+                        );
+                        if (deducted >= 0) {
+                            result.put("energyPenalty", penaltyAmount);
+                            log.info("未报名签到能量扣减: memberId={}, activityId={}, penalty={}, dimension={}",
+                                memberId, activityId, penaltyAmount, activity.getDimensionCode());
+                        } else {
+                            result.put("energyPenaltyFailed", "余额不足");
+                            log.warn("未报名签到能量扣减失败(余额不足): memberId={}, activityId={}",
+                                memberId, activityId);
+                        }
+                    } catch (Exception e) {
+                        log.warn("能量扣减异常: memberId={}, activityId={}, error={}",
+                            memberId, activityId, e.getMessage());
+                        result.put("energyPenaltyFailed", e.getMessage());
+                    }
+                }
+            }
+        }
+
+        // 4. Check if already checked in (dedup by sourceType + sourceId + memberId)
+        Task existingTask = taskMapper.selectOne(
+            new LambdaQueryWrapper<Task>()
+                .eq(Task::getSourceType, "activity")
+                .eq(Task::getSourceId, activityId)
+                .eq(Task::getMemberId, memberId)
+                .last("LIMIT 1")
+        );
+        if (existingTask != null) {
+            result.put("taskId", existingTask.getId());
+            result.put("pointsEarned", 0);
+            result.put("alreadyCompleted", true);
+            return result;
+        }
+
+        // 5. Determine points — use activity's checkinPoints or sysconfig default
+        int points = 5; // default
+        if (activity.getCheckinPoints() != null && activity.getCheckinPoints() > 0) {
+            points = activity.getCheckinPoints();
+        } else {
+            String defaultPointsStr = sysConfigService.getValue("activity_checkin_default_points");
+            if (defaultPointsStr != null && !defaultPointsStr.isEmpty()) {
+                try { points = Integer.parseInt(defaultPointsStr); } catch (NumberFormatException e) { /* use default */ }
+            }
+        }
+
+        // 是否需要审核签到(活动级开关,默认免审)
+        boolean needReview = activity.getRequireCheckinReview() != null && activity.getRequireCheckinReview() == 1;
+
+        // 6. 创建签到任务;开启审核时进入 pending_review,待后台审核通过才发积分/能量
+        Task task = new Task();
+        if (child != null) {
+            task.setFamilyId(child.getFamilyId());
+        }
+        task.setCreatorId(userId);
+        task.setExecutorType("child"); // 非登录用户(不可登录成员)
+        task.setExecutorId(memberId);
+        task.setMemberId(memberId);
+        task.setTitle("活动签到: " + activity.getTitle());
+        task.setDescription("自动生成 - 签到活动《" + activity.getTitle() + "》");
+        task.setPoints(points);
+        task.setRepeatType("none");
+        task.setCategory("行动类");
+        task.setNeedReview(needReview ? 1 : 0);
+        task.setReviewByCategory(0);
+        task.setTaskType("onetime");
+        task.setSourceType("activity");
+        task.setSourceId(activityId);
+        if (needReview) {
+            task.setStatus("pending_review");
+        } else {
+            task.setStatus("completed");
+            task.setCompletedAt(new Date());
+        }
+        task.setCreatedAt(new Date());
+        task.setUpdatedAt(new Date());
+
+        // Set deadline to today end
+        java.util.Calendar cal = java.util.Calendar.getInstance();
+        cal.set(java.util.Calendar.HOUR_OF_DAY, 23);
+        cal.set(java.util.Calendar.MINUTE, 59);
+        cal.set(java.util.Calendar.SECOND, 59);
+        task.setDeadline(cal.getTime());
+
+        taskMapper.insert(task);
+
+        // 7. 签到计数(无论是否需审核都计入 signedCount)
+        activity.setSignedCount(activity.getSignedCount() != null ? activity.getSignedCount() + 1 : 1);
+        activity.setUpdatedAt(new Date());
+        this.updateById(activity);
+
+        // 8. 发放奖励:免审直接发放;需审核在审核通过(reviewCheckin)时发放
+        if (needReview) {
+            result.put("needReview", true);
+            result.put("pointsEarned", 0);
+            log.info("活动签到进入待审核: activityId={}, memberId={}, taskId={}", activityId, memberId, task.getId());
+        } else {
+            awardCheckinRewards(activity, child, task, userId, points);
+            result.put("needReview", false);
+            result.put("pointsEarned", points);
+        }
+
+        // 9. Return result
+        result.put("taskId", task.getId());
+        return result;
+    }
+
+    /**
+     * 签到奖励发放(积分/能量/CF)。免审签到在 checkin 内调用;需审核签到在审核通过时调用。
+     */
+    private void awardCheckinRewards(Activity activity, FamilyMember child, Task task, Long userId, int points) {
+        // 更新家庭成员总积分
+        if (child != null) {
+            child.setTotalPoints(child.getTotalPoints() + points);
+            child.setUpdatedAt(new Date());
+            familyMemberMapper.updateById(child);
+        }
+        // 积分流水
+        PointsLog pointsLog = new PointsLog();
+        pointsLog.setMemberId(task.getMemberId());
+        pointsLog.setTaskId(task.getId());
+        pointsLog.setAmount(points);
+        pointsLog.setType("earn");
+        pointsLog.setCategory("task");
+        pointsLog.setDescription("活动签到: " + activity.getTitle());
+        pointsLog.setCreatedAt(new Date());
+        pointsLogMapper.insert(pointsLog);
+        // 发放能量
+        try {
+            energyService.awardEnergy(task.getMemberId(), "activity", activity.getId(), points,
+                "活动签到: " + activity.getTitle(), null);
+        } catch (Exception e) {
+            log.warn("能量发放失败(不影响积分): memberId={}, activityId={}, error={}",
+                task.getMemberId(), activity.getId(), e.getMessage());
+        }
+        // 活动下发 CF 值(F05 统一账本:数量取活动配置 activities.platform_points,幂等键:签到记录 ID)
+        if (activity.getPlatformPoints() != null && activity.getPlatformPoints() > 0 && userId != null) {
+            try {
+                cfEarnDispatchService.earnActivityCheckinCf(userId, task.getId(), activity.getPlatformPoints());
+            } catch (Exception e) {
+                log.warn("活动CF值发放失败: userId={}, checkinId={}, error={}",
+                        userId, task.getId(), e.getMessage());
+            }
+        }
+    }
+
+    /**
+     * 审核签到(活动级 requireCheckinReview 开启时):审批通过发放积分/能量/CF;驳回则不发。
+     */
+    @Transactional
+    public Result<Map<String, Object>> reviewCheckin(Long taskId, Long reviewerId, boolean approve) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null) return Result.error("签到任务不存在");
+        if (!"activity".equals(task.getSourceType())) return Result.error("非活动签到任务");
+        if (!"pending_review".equals(task.getStatus())) return Result.error("当前状态不可审核");
+        Map<String, Object> result = new HashMap<>();
+        if (approve) {
+            Activity activity = this.getById(task.getSourceId());
+            FamilyMember child = task.getMemberId() != null ? familyMemberMapper.selectById(task.getMemberId()) : null;
+            task.setStatus("completed");
+            task.setCompletedAt(new Date());
+            task.setUpdatedAt(new Date());
+            taskMapper.updateById(task);
+            int points = task.getPoints() != null ? task.getPoints() : 5;
+            if (activity != null) {
+                awardCheckinRewards(activity, child, task, task.getCreatorId(), points);
+            }
+            result.put("approved", true);
+            return Result.success(result);
+        } else {
+            task.setStatus("rejected");
+            task.setUpdatedAt(new Date());
+            taskMapper.updateById(task);
+            result.put("approved", false);
+            return Result.success(result);
+        }
+    }
+
+    /**
+     * 自动结束过期活动
+     * 逻辑:发布中且结束时间已过(endTime < now),将状态置为 ended。
+     * 备注:正式上线建议改为 Spring @Scheduled(cron = "0 0 2 * * ?") 每日 02:00 执行(见 TODOs),此处保留方法供 list/detail 触发兜底。
+     */
+    /**
+     * 自动结束过期活动(P2-1 定时化)
+     * 每日 02:00 定时执行,结束阈值 = endTime < now()(去掉旧的 7 天延迟)。
+     * 同时保留在 list/detail 查询时轻量调用兜底(实时状态判断)。
+     */
+    @Scheduled(cron = "0 0 2 * * ?")
+    public void autoEndExpiredActivities() {
+        try {
+            Date now = new Date();
+            this.update(new LambdaUpdateWrapper<Activity>()
+                    .eq(Activity::getStatus, "published")
+                    .lt(Activity::getEndTime, now)
+                    .set(Activity::getStatus, "ended")
+                    .set(Activity::getUpdatedAt, now));
+        } catch (Exception e) {
+            log.warn("自动结束过期活动失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 相关活动:按标签匹配(共享标签数降序 → 开始时间升序,与 {@link #list} 排序一致),
+     * 排除自身,仅取已发布。游客(userId 为空)仅返回公开活动(与 list 的游客策略一致)。
+     * 支持分页窗口截取。
+     *
+     * @param tags             源标签集合(来自文章/活动/商品)
+     * @param excludeActivityId 需排除的活动ID(活动源排除自身;其他源为 null)
+     * @param size             每页条数
+     * @param page             页码(从1开始)
+     * @param userId           当前用户ID(可为空)
+     * @return 相关活动DTO列表,无匹配返回空列表
+     */
+    public List<ActivityDTO> getRelatedActivitiesByTags(List<String> tags, Long excludeActivityId,
+                                                        int size, int page, Long userId) {
+        if (tags == null || tags.isEmpty() || size < 1) {
+            return Collections.emptyList();
+        }
+        int p = page < 1 ? 1 : page;
+        boolean isGuest = (userId == null || userId <= 0);
+
+        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<Activity>()
+                .eq(Activity::getStatus, "published");
+        if (excludeActivityId != null) {
+            wrapper.ne(Activity::getId, excludeActivityId);
+        }
+        wrapper.and(w -> {
+            boolean first = true;
+            for (String tag : tags) {
+                if (first) {
+                    w.apply("FIND_IN_SET({0}, tags) > 0", tag);
+                    first = false;
+                } else {
+                    w.or().apply("FIND_IN_SET({0}, tags) > 0", tag);
+                }
+            }
+        });
+        // 游客策略与 list() 一致:只返回公开/全部/未设置可见性的活动
+        if (isGuest) {
+            wrapper.and(w -> w.eq(Activity::getVisibility, "public")
+                    .or().eq(Activity::getVisibility, "all")
+                    .or().isNull(Activity::getVisibility));
+        }
+        List<Activity> candidates = this.list(wrapper);
+
+        // 共享标签计数,剔除零共享(SQL 已限定至少一个标签命中,此处防御)
+        Map<Long, Integer> score = new HashMap<>();
+        List<Activity> matched = new ArrayList<>();
+        for (Activity a : candidates) {
+            if (excludeActivityId != null && a.getId() != null && a.getId().equals(excludeActivityId)) {
+                continue;
+            }
+            int s = 0;
+            if (a.getTags() != null) {
+                for (String t : a.getTags().split(",")) {
+                    if (tags.contains(t.trim())) {
+                        s++;
+                    }
+                }
+            }
+            if (s > 0) {
+                matched.add(a);
+                score.put(a.getId(), s);
+            }
+        }
+        matched.sort((x, y) -> {
+            int diff = score.getOrDefault(y.getId(), 0) - score.getOrDefault(x.getId(), 0);
+            if (diff != 0) {
+                return diff;
+            }
+            Date px = x.getStartTime();
+            Date py = y.getStartTime();
+            if (px == null && py == null) return 0;
+            if (px == null) return 1;
+            if (py == null) return -1;
+            return px.compareTo(py);
+        });
+
+        // 分页窗口截取
+        int from = (p - 1) * size;
+        if (from >= matched.size()) {
+            return Collections.emptyList();
+        }
+        int to = Math.min(from + size, matched.size());
+        List<Activity> pageList = new ArrayList<>(matched.subList(from, to));
+
+        // 会员价解析(与 list() 口径一致,失败静默降级为非会员价)
+        String memberLevel = null;
+        if (!isGuest) {
+            try {
+                memberLevel = membershipService.getMemberLevel(userId);
+            } catch (Exception e) {
+                // 会员查询失败不影响关联列表
+            }
+        }
+        final String level = memberLevel;
+        return pageList.stream()
+                .map(a -> ActivityDTO.from(a, isGuest, level))
+                .collect(Collectors.toList());
+    }
+
+    private boolean hasCheckedIn(Long activityId, Long userId) {
+        List<Long> memberIds = registrationService.getMemberIdsByUser(userId);
+        if (memberIds.isEmpty()) {
+            return false;
+        }
+        return taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+                .eq(Task::getSourceType, "activity")
+                .eq(Task::getSourceId, activityId)
+                .in(Task::getMemberId, memberIds)
+                .eq(Task::getStatus, "completed")) > 0;
+    }
+
+    private void applyDisplayState(ActivityDTO dto, Activity activity, String registrationStatus, boolean checkedIn) {
+        Date now = new Date();
+        String displayStatus;
+        String displayLabel;
+        boolean ended = "ended".equals(activity.getStatus())
+                || (activity.getEndTime() != null && now.after(activity.getEndTime()));
+        if (ended) {
+            displayStatus = "ended";
+            displayLabel = "已结束";
+        } else if (checkedIn) {
+            displayStatus = "checked_in";
+            displayLabel = "已签到";
+        } else if (activity.getStartTime() != null && activity.getEndTime() != null
+                && !now.before(activity.getStartTime()) && !now.after(activity.getEndTime())) {
+            displayStatus = "ongoing";
+            displayLabel = "进行中";
+        } else if ("approved".equals(registrationStatus)) {
+            displayStatus = "registered";
+            displayLabel = "已报名";
+        } else if (activity.getRegistrationDeadline() != null && now.after(activity.getRegistrationDeadline())) {
+            displayStatus = "pending_start";
+            displayLabel = "待开始";
+        } else {
+            displayStatus = "open";
+            displayLabel = "报名中";
+        }
+        dto.setDisplayStatus(displayStatus);
+        dto.setDisplayLabel(displayLabel);
+        dto.setRegistrationStatus(checkedIn ? "checked_in" : (registrationStatus != null ? registrationStatus : "not_registered"));
+    }
+}

+ 155 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityTagService.java

@@ -0,0 +1,155 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.mapper.ActivityMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 活动标签:审核提交/通过时根据活动内容自动生成 3-5 个中文关键词。
+ * 与文章自动打标一致,走 AIService;失败仅记录日志,不影响活动流程。
+ */
+@Service
+public class ActivityTagService {
+
+    private static final Logger log = LoggerFactory.getLogger(ActivityTagService.class);
+    private static final String UPDATE_TAGS_SQL = "UPDATE activities SET tags = ? WHERE id = ?";
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private AIService aiService;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @Resource(name = "taskExecutor")
+    private ThreadPoolTaskExecutor taskExecutor;
+
+    /** 异步生成,不阻塞审核/提交流程 */
+    public void generateIfEmptyAsync(Long activityId) {
+        if (activityId == null) {
+            return;
+        }
+        try {
+            taskExecutor.execute(() -> {
+                try {
+                    generateIfEmpty(activityId);
+                } catch (Exception e) {
+                    log.warn("活动自动标签生成失败: activityId={}, error={}", activityId, e.getMessage());
+                }
+            });
+        } catch (Exception e) {
+            log.warn("活动自动标签任务提交失败: activityId={}, error={}", activityId, e.getMessage());
+        }
+    }
+
+    /** 仅当活动存在且标签为空时生成并写回 */
+    public void generateIfEmpty(Long activityId) {
+        if (activityId == null) {
+            return;
+        }
+        Activity activity = activityMapper.selectById(activityId);
+        if (activity == null) {
+            return;
+        }
+        if (activity.getTags() != null && !activity.getTags().trim().isEmpty()) {
+            return;
+        }
+        List<String> tags = generateTags(buildContent(activity));
+        if (tags.isEmpty()) {
+            return;
+        }
+        jdbcTemplate.update(UPDATE_TAGS_SQL, String.join(",", tags), activityId);
+    }
+
+    /**
+     * 调用 AI 从活动内容中提取 3-5 个中文关键词作为标签。
+     */
+    public List<String> generateTags(String content) {
+        if (content == null || content.trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        String plainText = content.replaceAll("<[^>]*>", " ")
+                .replaceAll("\\s+", " ")
+                .trim();
+        if (plainText.isEmpty()) {
+            return Collections.emptyList();
+        }
+        if (plainText.length() > 1500) {
+            plainText = plainText.substring(0, 1500);
+        }
+
+        String prompt = "你是一个家庭活动内容分析助手。请根据以下活动信息,提取 3 到 5 个最能代表活动主题的中文关键词作为标签。"
+                + "要求:1) 关键词为中文短语或名词,2-6 个字;2) 用英文逗号分隔;3) 不要包含编号、引号或解释文字;4) 只返回标签列表本身。"
+                + "\n\n活动信息:" + plainText;
+
+        try {
+            Map<String, Object> aiResult = aiService.sendMessage(prompt, "0", "", null);
+            Object answerObj = aiResult == null ? null : aiResult.get("answer");
+            if (answerObj == null || answerObj.toString().trim().isEmpty()) {
+                return Collections.emptyList();
+            }
+            List<String> tags = new ArrayList<>();
+            for (String raw : answerObj.toString().split("[,,、]")) {
+                String tag = raw.trim()
+                        .replaceAll("^[\\d\\.\\-\\s、。,]+", "")
+                        .replaceAll("[\\s、。,]+$", "")
+                        .trim();
+                if (!tag.isEmpty() && tag.length() <= 20 && !tags.contains(tag) && tags.size() < 5) {
+                    tags.add(tag);
+                }
+            }
+            return tags;
+        } catch (Exception e) {
+            log.warn("活动 AI 自动生成标签失败:{}", e.getMessage());
+            return Collections.emptyList();
+        }
+    }
+
+    /**
+     * 为已发布且标签为空的活动批量补标(异步,幂等)。
+     *
+     * @return 本次触发的活动数量
+     */
+    public int backfillEmptyPublished() {
+        List<Activity> activities = activityMapper.selectList(
+                new LambdaQueryWrapper<Activity>()
+                        .eq(Activity::getStatus, "published")
+                        .and(w -> w.isNull(Activity::getTags).or().apply("TRIM(tags) = ''")));
+        for (Activity activity : activities) {
+            generateIfEmptyAsync(activity.getId());
+        }
+        return activities.size();
+    }
+
+    private String buildContent(Activity activity) {
+        StringBuilder sb = new StringBuilder();
+        append(sb, activity.getTitle());
+        append(sb, activity.getIntro());
+        append(sb, activity.getDescription());
+        append(sb, activity.getLocation());
+        append(sb, activity.getActivityType());
+        return sb.toString();
+    }
+
+    private void append(StringBuilder sb, String value) {
+        if (value != null && !value.trim().isEmpty()) {
+            if (sb.length() > 0) {
+                sb.append(" ");
+            }
+            sb.append(value.trim());
+        }
+    }
+}

+ 437 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ActivityTeamService.java

@@ -0,0 +1,437 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ActivityTeam;
+import com.etotem.cfc.entity.ActivityTeamMember;
+import com.etotem.cfc.entity.ServiceAssignment;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ActivityTeamMapper;
+import com.etotem.cfc.mapper.ActivityTeamMemberMapper;
+import com.etotem.cfc.mapper.ServiceAssignmentMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * 活动管理团队(T35 规格 §2.2/§5)。
+ *
+ * <p>职责:
+ * <ol>
+ *   <li>活动团队创建与成员管理(activity_team / activity_team_member);</li>
+ *   <li>服务指派(复用服务指派机制,service_type=ACTIVITY_SUPPORT,
+ *       见 {@link ServiceAssignment}),把团队成员指派为某活动(或团队整体)的运营协作者;</li>
+ *   <li>团队成员协作判定:团队 active 成员或活动服务指派人可协作运营该活动。</li>
+ * </ol>
+ *
+ * <p>说明:团队数据独立于 supply_system(供应体系)——供应体系成员会被商品分销同体系判定
+ * 复用(见 ProductService 的同体系判定),活动运营人员若混入其中会误获分销价,故单列。</p>
+ */
+@Service
+public class ActivityTeamService extends ServiceImpl<ActivityTeamMapper, ActivityTeam> {
+
+    /** 服务指派类型:活动运营服务(T34 服务指派机制的 ACTIVITY_SUPPORT) */
+    public static final String SERVICE_TYPE_ACTIVITY_SUPPORT = "ACTIVITY_SUPPORT";
+
+    /** 指派目标类型:具体活动 */
+    public static final String TARGET_TYPE_ACTIVITY = "ACTIVITY";
+
+    /** 指派目标类型:团队整体 */
+    public static final String TARGET_TYPE_ACTIVITY_TEAM = "ACTIVITY_TEAM";
+
+    /** 团队成员角色 */
+    public static final String MEMBER_ROLE_OWNER = "owner";
+    public static final String MEMBER_ROLE_MANAGER = "manager";
+    public static final String MEMBER_ROLE_OPERATOR = "operator";
+
+    /** 服务指派角色 */
+    public static final String ASSIGN_ROLE_LEAD = "lead";
+    public static final String ASSIGN_ROLE_SUPPORT = "support";
+    public static final String ASSIGN_ROLE_CHECKIN = "checkin";
+    public static final String ASSIGN_ROLE_CONTENT = "content";
+
+    private static final Set<String> MEMBER_ROLES = new HashSet<>(Arrays.asList(
+            MEMBER_ROLE_OWNER, MEMBER_ROLE_MANAGER, MEMBER_ROLE_OPERATOR));
+    private static final Set<String> ASSIGN_ROLES = new HashSet<>(Arrays.asList(
+            ASSIGN_ROLE_LEAD, ASSIGN_ROLE_SUPPORT, ASSIGN_ROLE_CHECKIN, ASSIGN_ROLE_CONTENT));
+    private static final Set<String> TARGET_TYPES = new HashSet<>(Arrays.asList(
+            TARGET_TYPE_ACTIVITY, TARGET_TYPE_ACTIVITY_TEAM));
+
+    @Resource
+    private ActivityTeamMemberMapper activityTeamMemberMapper;
+
+    @Resource
+    private ServiceAssignmentMapper serviceAssignmentMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    // ==================== 团队 ====================
+
+    /**
+     * 创建活动团队,创建人自动成为团长成员(owner)
+     */
+    @Transactional
+    public ActivityTeam createTeam(String name, String description, Long ownerId) {
+        if (name == null || name.trim().isEmpty()) {
+            throw new IllegalArgumentException("团队名称不能为空");
+        }
+        if (ownerId == null) {
+            throw new IllegalArgumentException("创建人不能为空");
+        }
+        ActivityTeam team = new ActivityTeam();
+        team.setName(name.trim());
+        team.setDescription(description);
+        team.setOwnerId(ownerId);
+        team.setStatus("active");
+        team.setCreatedAt(new Date());
+        team.setUpdatedAt(new Date());
+        this.save(team);
+
+        ActivityTeamMember member = new ActivityTeamMember();
+        member.setTeamId(team.getId());
+        member.setUserId(ownerId);
+        member.setRole(MEMBER_ROLE_OWNER);
+        member.setStatus("active");
+        member.setJoinedAt(new Date());
+        activityTeamMemberMapper.insert(member);
+        return team;
+    }
+
+    /**
+     * 我所在的团队(团长或 active 成员)。includeAll=true 时返回全部团队(管理端视角)。
+     */
+    public List<ActivityTeam> listTeams(Long userId, boolean includeAll) {
+        if (includeAll) {
+            return this.list(new LambdaQueryWrapper<ActivityTeam>()
+                    .orderByDesc(ActivityTeam::getId));
+        }
+        if (userId == null) {
+            return new ArrayList<>();
+        }
+        Set<Long> teamIds = new HashSet<>();
+        List<ActivityTeamMember> memberships = activityTeamMemberMapper.selectList(
+                new LambdaQueryWrapper<ActivityTeamMember>()
+                        .eq(ActivityTeamMember::getUserId, userId)
+                        .eq(ActivityTeamMember::getStatus, "active"));
+        for (ActivityTeamMember m : memberships) {
+            if (m.getTeamId() != null) {
+                teamIds.add(m.getTeamId());
+            }
+        }
+        // 防御:团长可能有成员记录缺失
+        List<ActivityTeam> owned = this.list(new LambdaQueryWrapper<ActivityTeam>()
+                .eq(ActivityTeam::getOwnerId, userId));
+        for (ActivityTeam t : owned) {
+            teamIds.add(t.getId());
+        }
+        if (teamIds.isEmpty()) {
+            return new ArrayList<>();
+        }
+        return this.list(new LambdaQueryWrapper<ActivityTeam>()
+                .in(ActivityTeam::getId, teamIds)
+                .orderByDesc(ActivityTeam::getId));
+    }
+
+    public ActivityTeam getTeam(Long teamId) {
+        return teamId == null ? null : this.getById(teamId);
+    }
+
+    // ==================== 成员 ====================
+
+    public List<ActivityTeamMember> listMembers(Long teamId) {
+        if (teamId == null) {
+            return new ArrayList<>();
+        }
+        return activityTeamMemberMapper.selectList(new LambdaQueryWrapper<ActivityTeamMember>()
+                .eq(ActivityTeamMember::getTeamId, teamId)
+                .eq(ActivityTeamMember::getStatus, "active")
+                .orderByAsc(ActivityTeamMember::getId));
+    }
+
+    public ActivityTeamMember getMembership(Long teamId, Long userId) {
+        if (teamId == null || userId == null) {
+            return null;
+        }
+        return activityTeamMemberMapper.selectOne(new LambdaQueryWrapper<ActivityTeamMember>()
+                .eq(ActivityTeamMember::getTeamId, teamId)
+                .eq(ActivityTeamMember::getUserId, userId)
+                .last("LIMIT 1"));
+    }
+
+    /** 是否为团队在团成员 */
+    public boolean isActiveMember(Long teamId, Long userId) {
+        ActivityTeamMember member = getMembership(teamId, userId);
+        return member != null && "active".equals(member.getStatus());
+    }
+
+    /** 是否可管理团队(团长或运营主管) */
+    public boolean isTeamManager(Long teamId, Long userId) {
+        ActivityTeamMember member = getMembership(teamId, userId);
+        if (member == null || !"active".equals(member.getStatus())) {
+            return false;
+        }
+        return MEMBER_ROLE_OWNER.equals(member.getRole()) || MEMBER_ROLE_MANAGER.equals(member.getRole());
+    }
+
+    /**
+     * 添加团队成员(幂等:已在团则更新角色;已移出则重新激活)
+     */
+    @Transactional
+    public ActivityTeamMember addMember(Long teamId, Long userId, String role) {
+        if (teamId == null) {
+            throw new IllegalArgumentException("团队不能为空");
+        }
+        if (userId == null) {
+            throw new IllegalArgumentException("成员用户不能为空");
+        }
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            throw new IllegalArgumentException("用户不存在");
+        }
+        String memberRole = normalizeMemberRole(role);
+        ActivityTeamMember existing = getMembership(teamId, userId);
+        if (existing != null) {
+            existing.setRole(memberRole);
+            existing.setStatus("active");
+            existing.setJoinedAt(new Date());
+            activityTeamMemberMapper.updateById(existing);
+            return existing;
+        }
+        ActivityTeamMember member = new ActivityTeamMember();
+        member.setTeamId(teamId);
+        member.setUserId(userId);
+        member.setRole(memberRole);
+        member.setStatus("active");
+        member.setJoinedAt(new Date());
+        activityTeamMemberMapper.insert(member);
+        return member;
+    }
+
+    /**
+     * 移出团队成员(团长不可被移出)
+     */
+    @Transactional
+    public boolean removeMember(Long teamId, Long userId) {
+        ActivityTeam team = getTeam(teamId);
+        if (team == null) {
+            throw new IllegalArgumentException("团队不存在");
+        }
+        if (team.getOwnerId() != null && team.getOwnerId().equals(userId)) {
+            throw new IllegalArgumentException("团长不能被移出团队");
+        }
+        ActivityTeamMember member = getMembership(teamId, userId);
+        if (member == null) {
+            return false;
+        }
+        member.setStatus("removed");
+        activityTeamMemberMapper.updateById(member);
+        // 同步撤销该成员在本团队下的活动服务指派
+        List<ServiceAssignment> assignments = serviceAssignmentMapper.selectList(
+                new LambdaQueryWrapper<ServiceAssignment>()
+                        .eq(ServiceAssignment::getTeamId, teamId)
+                        .eq(ServiceAssignment::getAssigneeId, userId)
+                        .eq(ServiceAssignment::getServiceType, SERVICE_TYPE_ACTIVITY_SUPPORT)
+                        .eq(ServiceAssignment::getStatus, "active"));
+        for (ServiceAssignment assignment : assignments) {
+            assignment.setStatus("revoked");
+            assignment.setUpdatedAt(new Date());
+            serviceAssignmentMapper.updateById(assignment);
+        }
+        return true;
+    }
+
+    private String normalizeMemberRole(String role) {
+        if (role == null || role.trim().isEmpty()) {
+            return MEMBER_ROLE_OPERATOR;
+        }
+        String normalized = role.trim().toLowerCase();
+        if (!MEMBER_ROLES.contains(normalized)) {
+            throw new IllegalArgumentException("成员角色不合法: " + role);
+        }
+        return normalized;
+    }
+
+    // ==================== 服务指派(ACTIVITY_SUPPORT) ====================
+
+    /**
+     * 指派服务:把团队成员指派为某活动(或团队整体)的运营协作者。
+     *
+     * @param teamId     团队ID
+     * @param targetType ACTIVITY / ACTIVITY_TEAM
+     * @param targetId   目标ID
+     * @param assigneeId 被指派人 userId(须为团队在团成员)
+     * @param role       指派角色 lead/support/checkin/content
+     */
+    @Transactional
+    public ServiceAssignment assignService(Long teamId, String targetType, Long targetId,
+                                           Long assigneeId, String role, String remark, Long operatorId) {
+        if (teamId == null) {
+            throw new IllegalArgumentException("团队不能为空");
+        }
+        if (targetType == null || !TARGET_TYPES.contains(targetType.trim().toUpperCase())) {
+            throw new IllegalArgumentException("指派目标类型不合法");
+        }
+        String normalizedTargetType = targetType.trim().toUpperCase();
+        if (targetId == null) {
+            throw new IllegalArgumentException("指派目标不能为空");
+        }
+        if (assigneeId == null) {
+            throw new IllegalArgumentException("被指派人不能为空");
+        }
+        String assignRole = normalizeAssignRole(role);
+        if (getTeam(teamId) == null) {
+            throw new IllegalArgumentException("团队不存在");
+        }
+        if (TARGET_TYPE_ACTIVITY.equals(normalizedTargetType)) {
+            if (activityMapper.selectById(targetId) == null) {
+                throw new IllegalArgumentException("活动不存在");
+            }
+        } else if (getTeam(targetId) == null) {
+            throw new IllegalArgumentException("目标团队不存在");
+        }
+        if (!isActiveMember(teamId, assigneeId)) {
+            throw new IllegalArgumentException("被指派人须为团队在团成员");
+        }
+
+        ServiceAssignment existing = serviceAssignmentMapper.selectOne(
+                new LambdaQueryWrapper<ServiceAssignment>()
+                        .eq(ServiceAssignment::getServiceType, SERVICE_TYPE_ACTIVITY_SUPPORT)
+                        .eq(ServiceAssignment::getTargetType, normalizedTargetType)
+                        .eq(ServiceAssignment::getTargetId, targetId)
+                        .eq(ServiceAssignment::getAssigneeId, assigneeId)
+                        .eq(ServiceAssignment::getRole, assignRole)
+                        .last("LIMIT 1"));
+        Date now = new Date();
+        if (existing != null) {
+            existing.setStatus("active");
+            existing.setTeamId(teamId);
+            existing.setRemark(remark);
+            existing.setAssignedBy(operatorId);
+            existing.setUpdatedAt(now);
+            serviceAssignmentMapper.updateById(existing);
+            return existing;
+        }
+        ServiceAssignment assignment = new ServiceAssignment();
+        assignment.setServiceType(SERVICE_TYPE_ACTIVITY_SUPPORT);
+        assignment.setTargetType(normalizedTargetType);
+        assignment.setTargetId(targetId);
+        assignment.setTeamId(teamId);
+        assignment.setAssigneeId(assigneeId);
+        assignment.setRole(assignRole);
+        assignment.setStatus("active");
+        assignment.setRemark(remark);
+        assignment.setAssignedBy(operatorId);
+        assignment.setCreatedAt(now);
+        assignment.setUpdatedAt(now);
+        serviceAssignmentMapper.insert(assignment);
+        return assignment;
+    }
+
+    /**
+     * 查询服务指派记录。targetId 为空时按 teamId 查全部。
+     */
+    public List<ServiceAssignment> listAssignments(Long teamId, String targetType, Long targetId) {
+        LambdaQueryWrapper<ServiceAssignment> wrapper = new LambdaQueryWrapper<ServiceAssignment>()
+                .eq(ServiceAssignment::getServiceType, SERVICE_TYPE_ACTIVITY_SUPPORT)
+                .eq(ServiceAssignment::getStatus, "active");
+        if (teamId != null) {
+            wrapper.eq(ServiceAssignment::getTeamId, teamId);
+        }
+        if (targetType != null && !targetType.trim().isEmpty()) {
+            wrapper.eq(ServiceAssignment::getTargetType, targetType.trim().toUpperCase());
+        }
+        if (targetId != null) {
+            wrapper.eq(ServiceAssignment::getTargetId, targetId);
+        }
+        wrapper.orderByDesc(ServiceAssignment::getId);
+        return serviceAssignmentMapper.selectList(wrapper);
+    }
+
+    /**
+     * 撤销服务指派
+     */
+    @Transactional
+    public boolean revokeAssignment(Long assignmentId) {
+        if (assignmentId == null) {
+            throw new IllegalArgumentException("指派记录不能为空");
+        }
+        ServiceAssignment assignment = serviceAssignmentMapper.selectById(assignmentId);
+        if (assignment == null) {
+            return false;
+        }
+        assignment.setStatus("revoked");
+        assignment.setUpdatedAt(new Date());
+        return serviceAssignmentMapper.updateById(assignment) > 0;
+    }
+
+    private String normalizeAssignRole(String role) {
+        if (role == null || role.trim().isEmpty()) {
+            return ASSIGN_ROLE_SUPPORT;
+        }
+        String normalized = role.trim().toLowerCase();
+        if (!ASSIGN_ROLES.contains(normalized)) {
+            throw new IllegalArgumentException("指派角色不合法: " + role);
+        }
+        return normalized;
+    }
+
+    // ==================== 协作判定 ====================
+
+    /**
+     * 是否为该活动的运营协作者:团队在团成员,或该活动(或其团队)的服务指派人。
+     */
+    public boolean isActivityCollaborator(Activity activity, Long userId) {
+        if (activity == null || userId == null) {
+            return false;
+        }
+        if (activity.getTeamId() != null && isActiveMember(activity.getTeamId(), userId)) {
+            return true;
+        }
+        return isAssigneeOfActivity(activity, userId);
+    }
+
+    /**
+     * 是否被指派参与该活动(服务指派 ACTIVITY_SUPPORT,status=active)
+     */
+    public boolean isAssigneeOfActivity(Activity activity, Long userId) {
+        if (activity == null || userId == null) {
+            return false;
+        }
+        Long count = serviceAssignmentMapper.selectCount(new LambdaQueryWrapper<ServiceAssignment>()
+                .eq(ServiceAssignment::getServiceType, SERVICE_TYPE_ACTIVITY_SUPPORT)
+                .eq(ServiceAssignment::getStatus, "active")
+                .eq(ServiceAssignment::getAssigneeId, userId)
+                .and(w -> w
+                        .and(x -> x.eq(ServiceAssignment::getTargetType, TARGET_TYPE_ACTIVITY)
+                                .eq(ServiceAssignment::getTargetId, activity.getId()))
+                        .or(x -> x.eq(ServiceAssignment::getTargetType, TARGET_TYPE_ACTIVITY_TEAM)
+                                .eq(ServiceAssignment::getTargetId, activity.getTeamId() == null ? -1L : activity.getTeamId()))));
+        return count != null && count > 0;
+    }
+
+    /**
+     * 团队名下活动列表
+     */
+    public List<Activity> listTeamActivities(Long teamId) {
+        if (teamId == null) {
+            return new ArrayList<>();
+        }
+        return activityMapper.selectList(new LambdaQueryWrapper<Activity>()
+                .eq(Activity::getTeamId, teamId)
+                .orderByDesc(Activity::getId));
+    }
+}

+ 187 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AdminGuidePopupService.java

@@ -0,0 +1,187 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.etotem.cfc.entity.GuidePopup;
+import com.etotem.cfc.entity.GuidePopupLog;
+import com.etotem.cfc.entity.GuidePopupStep;
+import com.etotem.cfc.entity.GuidePopupTrigger;
+import com.etotem.cfc.mapper.GuidePopupLogMapper;
+import com.etotem.cfc.mapper.GuidePopupMapper;
+import com.etotem.cfc.mapper.GuidePopupStepMapper;
+import com.etotem.cfc.mapper.GuidePopupTriggerMapper;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class AdminGuidePopupService {
+
+    @Resource
+    private GuidePopupMapper guidePopupMapper;
+
+    @Resource
+    private GuidePopupStepMapper guidePopupStepMapper;
+
+    @Resource
+    private GuidePopupTriggerMapper guidePopupTriggerMapper;
+
+    @Resource
+    private GuidePopupLogMapper guidePopupLogMapper;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    public List<GuidePopup> list(String slug, Integer status) {
+        QueryWrapper<GuidePopup> qw = new QueryWrapper<>();
+        if (slug != null && !slug.isEmpty()) {
+            qw.like("slug", slug);
+        }
+        if (status != null) {
+            qw.eq("status", status);
+        }
+        qw.orderByAsc("sort_order");
+        return guidePopupMapper.selectList(qw);
+    }
+
+    @Transactional
+    public boolean create(Map<String, Object> body) {
+        GuidePopup popup = new GuidePopup();
+        popup.setSlug((String) body.get("slug"));
+        popup.setTitle((String) body.get("title"));
+        popup.setDescription((String) body.get("description"));
+        popup.setIcon(body.get("icon") != null ? (String) body.get("icon") : "");
+        popup.setIconType(body.get("iconType") != null ? Integer.valueOf(body.get("iconType").toString()) : 0);
+        popup.setThemeColor(body.get("themeColor") != null ? (String) body.get("themeColor") : "#F97316");
+        popup.setBtnText(body.get("btnText") != null ? (String) body.get("btnText") : "知道了");
+        popup.setBtnAction(body.get("btnAction") != null ? (String) body.get("btnAction") : "");
+        popup.setStatus(body.get("status") != null ? Integer.valueOf(body.get("status").toString()) : 1);
+        popup.setSortOrder(body.get("sortOrder") != null ? Integer.valueOf(body.get("sortOrder").toString()) : 0);
+        popup.setCreatedAt(new Date());
+        popup.setUpdatedAt(new Date());
+        guidePopupMapper.insert(popup);
+
+        saveChildren(popup.getId(), body);
+        return true;
+    }
+
+    @Transactional
+    public boolean update(Long id, Map<String, Object> body) {
+        GuidePopup popup = guidePopupMapper.selectById(id);
+        if (popup == null) return false;
+        if (body.get("slug") != null) popup.setSlug((String) body.get("slug"));
+        if (body.get("title") != null) popup.setTitle((String) body.get("title"));
+        if (body.get("description") != null) popup.setDescription((String) body.get("description"));
+        if (body.get("icon") != null) popup.setIcon((String) body.get("icon"));
+        if (body.get("iconType") != null) popup.setIconType(Integer.valueOf(body.get("iconType").toString()));
+        if (body.get("themeColor") != null) popup.setThemeColor((String) body.get("themeColor"));
+        if (body.get("btnText") != null) popup.setBtnText((String) body.get("btnText"));
+        if (body.get("btnAction") != null) popup.setBtnAction((String) body.get("btnAction"));
+        if (body.get("status") != null) popup.setStatus(Integer.valueOf(body.get("status").toString()));
+        if (body.get("sortOrder") != null) popup.setSortOrder(Integer.valueOf(body.get("sortOrder").toString()));
+        popup.setUpdatedAt(new Date());
+        guidePopupMapper.updateById(popup);
+
+        QueryWrapper<GuidePopupStep> stepDel = new QueryWrapper<>();
+        stepDel.eq("popup_id", id);
+        guidePopupStepMapper.delete(stepDel);
+        QueryWrapper<GuidePopupTrigger> trigDel = new QueryWrapper<>();
+        trigDel.eq("popup_id", id);
+        guidePopupTriggerMapper.delete(trigDel);
+        saveChildren(id, body);
+        return true;
+    }
+
+    public boolean updateStatus(Long id, Integer status) {
+        GuidePopup popup = guidePopupMapper.selectById(id);
+        if (popup == null) return false;
+        popup.setStatus(status);
+        popup.setUpdatedAt(new Date());
+        return guidePopupMapper.updateById(popup) > 0;
+    }
+
+    @Transactional
+    public boolean delete(Long id) {
+        QueryWrapper<GuidePopupStep> stepDel = new QueryWrapper<>();
+        stepDel.eq("popup_id", id);
+        guidePopupStepMapper.delete(stepDel);
+        QueryWrapper<GuidePopupTrigger> trigDel = new QueryWrapper<>();
+        trigDel.eq("popup_id", id);
+        guidePopupTriggerMapper.delete(trigDel);
+        QueryWrapper<GuidePopupLog> logDel = new QueryWrapper<>();
+        logDel.eq("popup_id", id);
+        guidePopupLogMapper.delete(logDel);
+        return guidePopupMapper.deleteById(id) > 0;
+    }
+
+    public Map<String, Object> stats(Long popupId) {
+        Map<String, Object> result = new HashMap<>();
+        String where = popupId != null ? " WHERE popup_id = " + popupId : "";
+        Integer totalViews = jdbcTemplate.queryForObject(
+                "SELECT COUNT(*) FROM guide_popup_log" + where, Integer.class);
+        Integer totalClicks = jdbcTemplate.queryForObject(
+                "SELECT COUNT(*) FROM guide_popup_log" + where + (popupId != null ? " AND button_clicked = 1" : " WHERE button_clicked = 1"),
+                Integer.class);
+        result.put("totalViews", totalViews != null ? totalViews : 0);
+        result.put("totalClicks", totalClicks != null ? totalClicks : 0);
+        int views = totalViews != null ? totalViews : 0;
+        int clicks = totalClicks != null ? totalClicks : 0;
+        double rate = views > 0 ? (double) clicks / views * 100 : 0;
+        result.put("completionRate", String.format("%.1f%%", rate));
+
+        List<Map<String, Object>> trend = jdbcTemplate.queryForList(
+                "SELECT DATE_FORMAT(consumed_at, '%H:00') AS hour, " +
+                        "COUNT(*) AS views, " +
+                        "SUM(button_clicked) AS clicks " +
+                        "FROM guide_popup_log" + where +
+                        " GROUP BY DATE_FORMAT(consumed_at, '%H:00') ORDER BY hour");
+        result.put("trendByHour", trend);
+        return result;
+    }
+
+    private void saveChildren(Long popupId, Map<String, Object> body) {
+        Object stepsObj = body.get("steps");
+        if (stepsObj instanceof List) {
+            List<?> steps = (List<?>) stepsObj;
+            int order = 0;
+            for (Object so : steps) {
+                if (!(so instanceof Map)) continue;
+                Map<?, ?> sm = (Map<?, ?>) so;
+                GuidePopupStep step = new GuidePopupStep();
+                step.setPopupId(popupId);
+                step.setStepOrder(order++);
+                step.setTitle(sm.get("title") != null ? sm.get("title").toString() : "");
+                step.setDesc(sm.get("desc") != null ? sm.get("desc").toString() : "");
+                step.setIcon(sm.get("icon") != null ? sm.get("icon").toString() : "");
+                step.setIconType(sm.get("iconType") != null ? Integer.valueOf(sm.get("iconType").toString()) : 0);
+                step.setIsIntro(sm.get("isIntro") != null ? Integer.valueOf(sm.get("isIntro").toString()) : 0);
+                step.setBtnText(sm.get("btnText") != null ? sm.get("btnText").toString() : "下一步");
+                step.setBtnAction(sm.get("btnAction") != null ? sm.get("btnAction").toString() : "");
+                step.setCreatedAt(new Date());
+                guidePopupStepMapper.insert(step);
+            }
+        }
+        Object triggersObj = body.get("triggers");
+        if (triggersObj instanceof List) {
+            List<?> triggers = (List<?>) triggersObj;
+            for (Object to : triggers) {
+                if (!(to instanceof Map)) continue;
+                Map<?, ?> tm = (Map<?, ?>) to;
+                GuidePopupTrigger trigger = new GuidePopupTrigger();
+                trigger.setPopupId(popupId);
+                trigger.setTriggerType(tm.get("triggerType") != null ? tm.get("triggerType").toString() : "first_login");
+                trigger.setTargetPage(tm.get("targetPage") != null ? tm.get("targetPage").toString() : "");
+                trigger.setTargetAction(tm.get("targetAction") != null ? tm.get("targetAction").toString() : "");
+                trigger.setMinRole(tm.get("minRole") != null ? tm.get("minRole").toString() : "parent");
+                trigger.setExtraConfig(tm.get("extraConfig") != null ? tm.get("extraConfig").toString() : null);
+                trigger.setCreatedAt(new Date());
+                guidePopupTriggerMapper.insert(trigger);
+            }
+        }
+    }
+}

+ 131 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AdminReferralTreeService.java

@@ -0,0 +1,131 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.CommissionRecord;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CommissionRecordMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 后台推荐团队树构建(按 users.referrer_id 逐层 BFS)。
+ *
+ * <p>不使用 referral_tree:该表为异步物化数据,生产存在漏写(例如某用户 20 个直推、树里仅 18 条),
+ * 会导致后台团队树比 L1/L2 统计少人。users.referrer_id 是推荐关系的权威源,
+ * 与 {@link CommissionService#getTeamStats}/{@link CommissionService#getTeamList} 口径一致。</p>
+ *
+ * <p>同时不使用 MySQL 递归 CTE:当前 RDS 执行 WITH RECURSIVE 会因内部临时表不可用而报错。</p>
+ */
+@Service
+public class AdminReferralTreeService {
+
+    private static final int DEFAULT_MAX_LEVEL = 3;
+    private static final int HARD_MAX_LEVEL = 8;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Resource
+    private CommissionRecordMapper commissionRecordMapper;
+
+    /**
+     * 构建以 userId 为根的团队树(扁平节点,含 level/parentId)。
+     *
+     * @return { nodes: [...], totalMembers, maxLevel }
+     */
+    public Map<String, Object> buildTree(Long userId, Integer maxLevel) {
+        int cap = maxLevel == null || maxLevel <= 0 ? DEFAULT_MAX_LEVEL : Math.min(maxLevel, HARD_MAX_LEVEL);
+
+        List<Map<String, Object>> nodes = new ArrayList<>();
+        List<Long> memberIds = new ArrayList<>();
+        Set<Long> visited = new HashSet<>();
+        visited.add(userId); // 防自引用/环
+
+        List<Long> parentIds = Collections.singletonList(userId);
+        for (int level = 1; level <= cap && !parentIds.isEmpty(); level++) {
+            List<User> children = userMapper.selectList(
+                    new LambdaQueryWrapper<User>().in(User::getReferrerId, parentIds));
+            List<Long> next = new ArrayList<>();
+            for (User u : children) {
+                if (u.getId() == null || !visited.add(u.getId())) {
+                    continue;
+                }
+                Map<String, Object> n = new LinkedHashMap<>();
+                n.put("userId", u.getId());
+                n.put("parentId", u.getReferrerId());
+                n.put("level", level);
+                n.put("nickname", u.getNickname());
+                n.put("avatar", u.getAvatar());
+                n.put("createdAt", u.getCreatedAt());
+                nodes.add(n);
+                memberIds.add(u.getId());
+                next.add(u.getId());
+            }
+            parentIds = next;
+        }
+
+        Map<Long, Integer> consumptionMap = loadConsumption(memberIds);
+        Map<Long, Integer> commissionMap = loadCommission(userId, memberIds);
+        for (Map<String, Object> n : nodes) {
+            Long uid = (Long) n.get("userId");
+            n.put("memberConsumption", consumptionMap.getOrDefault(uid, 0));
+            n.put("myCfEarnedFromMember", commissionMap.getOrDefault(uid, 0));
+        }
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("nodes", nodes);
+        result.put("totalMembers", nodes.size());
+        result.put("maxLevel", cap);
+        return result;
+    }
+
+    private Map<Long, Integer> loadConsumption(List<Long> memberIds) {
+        Map<Long, Integer> out = new HashMap<>();
+        if (memberIds.isEmpty()) {
+            return out;
+        }
+        List<ProductOrder> orders = productOrderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .in(ProductOrder::getBuyerId, memberIds)
+                        .eq(ProductOrder::getFulfillStatus, "completed"));
+        for (ProductOrder o : orders) {
+            if (o.getBuyerId() != null && o.getTotalAmount() != null) {
+                out.merge(o.getBuyerId(), o.getTotalAmount(), Integer::sum);
+            }
+        }
+        return out;
+    }
+
+    private Map<Long, Integer> loadCommission(Long rootUserId, List<Long> memberIds) {
+        Map<Long, Integer> out = new HashMap<>();
+        if (memberIds.isEmpty()) {
+            return out;
+        }
+        List<CommissionRecord> records = commissionRecordMapper.selectList(
+                new LambdaQueryWrapper<CommissionRecord>()
+                        .eq(CommissionRecord::getReferrerId, rootUserId)
+                        .in(CommissionRecord::getBuyerId, memberIds)
+                        .ne(CommissionRecord::getStatus, "cancelled"));
+        for (CommissionRecord r : records) {
+            if (r.getBuyerId() != null && r.getCommissionAmount() != null) {
+                out.merge(r.getBuyerId(), r.getCommissionAmount(), Integer::sum);
+            }
+        }
+        return out;
+    }
+}

+ 199 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AfterSalesService.java

@@ -0,0 +1,199 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.AfterSalesRequest;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.mapper.AfterSalesRequestMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class AfterSalesService {
+
+    @Resource
+    private AfterSalesRequestMapper afterSalesRequestMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    private static final Logger log = LoggerFactory.getLogger(AfterSalesService.class);
+
+    public Result<AfterSalesRequest> create(AfterSalesRequest request, Long userId) {
+        ProductOrder order = productOrderMapper.selectById(request.getOrderId());
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        if (!"paid".equals(order.getStatus()) && !"shipped".equals(order.getStatus()) && !"pending_receipt".equals(order.getStatus())) {
+            return Result.error("仅已支付、未完成的订单可申请售后");
+        }
+        request.setUserId(userId);
+        request.setOrderNo(order.getOrderNo());
+        // 退款金额按「用户实付现金」计算(money_amount 已扣除优惠券抵扣与积分抵扣),
+        // 与 ProductOrderService.approveRefund 实际向微信申请的退款金额保持一致,
+        // 避免前端展示金额与最终到账金额不一致。
+        Integer refundAmount = order.getMoneyAmount();
+        if (refundAmount == null || refundAmount < 0) {
+            refundAmount = order.getTotalAmount();
+        }
+        request.setRefundAmount(refundAmount);
+        request.setStatus("pending");
+        request.setCreatedAt(new Date());
+        request.setUpdatedAt(new Date());
+        afterSalesRequestMapper.insert(request);
+
+        // 写快照:在把订单置为 refunding 之前保存当前状态,供后续取消时回滚。
+        order.setRefundBeforeStatus(order.getStatus());
+        order.setRefundBeforeRefundStatus(order.getRefundStatus());
+        order.setStatus("refunding");
+        order.setRefundStatus(1);
+        order.setRefundReason(request.getReason());
+        order.setRefundAmount(refundAmount);
+        order.setUpdatedAt(new Date());
+        productOrderMapper.updateById(order);
+
+        log.info("售后申请已创建,同步更新订单状态: orderNo={}, requestId={}", order.getOrderNo(), request.getId());
+        return Result.success(request);
+    }
+
+    public Result<List<AfterSalesRequest>> list(Long userId, String status) {
+        LambdaQueryWrapper<AfterSalesRequest> wrapper = new LambdaQueryWrapper<AfterSalesRequest>()
+            .eq(AfterSalesRequest::getUserId, userId)
+            .orderByDesc(AfterSalesRequest::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(AfterSalesRequest::getStatus, status);
+        }
+        SortUtil.applySort(wrapper);
+        List<AfterSalesRequest> list = afterSalesRequestMapper.selectList(wrapper);
+        return Result.success(list);
+    }
+
+    public Result<AfterSalesRequest> detail(Long id, Long userId) {
+        AfterSalesRequest request = afterSalesRequestMapper.selectById(id);
+        if (request == null) {
+            return Result.error("售后申请不存在");
+        }
+        if (!request.getUserId().equals(userId)) {
+            return Result.error("无权查看");
+        }
+        return Result.success(request);
+    }
+
+    public Result<List<AfterSalesRequest>> adminList(String status) {
+        LambdaQueryWrapper<AfterSalesRequest> wrapper = new LambdaQueryWrapper<AfterSalesRequest>()
+            .orderByDesc(AfterSalesRequest::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(AfterSalesRequest::getStatus, status);
+        }
+        return Result.success(afterSalesRequestMapper.selectList(wrapper));
+    }
+
+    public Result<AfterSalesRequest> adminDetail(Long id) {
+        AfterSalesRequest request = afterSalesRequestMapper.selectById(id);
+        if (request == null) {
+            return Result.error("售后申请不存在");
+        }
+        return Result.success(request);
+    }
+
+    public Result<String> review(Long id, String action, String rejectReason, Long adminId) {
+        AfterSalesRequest request = afterSalesRequestMapper.selectById(id);
+        if (request == null) {
+            return Result.error("售后申请不存在");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            return Result.error("仅待审核的申请可处理");
+        }
+        if ("approve".equals(action)) {
+            request.setStatus("approved");
+        } else if ("reject".equals(action)) {
+            request.setStatus("rejected");
+            request.setRejectReason(rejectReason);
+        } else {
+            return Result.error("无效操作");
+        }
+        request.setHandledBy(adminId);
+        request.setHandledAt(new Date());
+        request.setUpdatedAt(new Date());
+        afterSalesRequestMapper.updateById(request);
+        return Result.success("操作成功");
+    }
+
+    public Result<String> complete(Long id) {
+        AfterSalesRequest request = afterSalesRequestMapper.selectById(id);
+        if (request == null) {
+            return Result.error("售后申请不存在");
+        }
+        if (!"approved".equals(request.getStatus())) {
+            return Result.error("仅已批准的申请可完成");
+        }
+        request.setStatus("completed");
+        request.setUpdatedAt(new Date());
+        afterSalesRequestMapper.updateById(request);
+        return Result.success("已完成");
+    }
+
+    /**
+     * 按售后申请单ID取消退款申请(pending 态才可取消)。
+     */
+    public Result<String> cancel(Long requestId, Long userId) {
+        AfterSalesRequest request = afterSalesRequestMapper.selectById(requestId);
+        if (request == null) {
+            return Result.error("售后申请不存在");
+        }
+        if (!request.getUserId().equals(userId)) {
+            return Result.error("无权操作此售后申请");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            return Result.error("后台已处理,无法取消");
+        }
+        ProductOrder order = productOrderMapper.selectById(request.getOrderId());
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!"refunding".equals(order.getStatus()) || order.getRefundStatus() == null || order.getRefundStatus() != 1) {
+            return Result.error("当前状态不可取消");
+        }
+        // 售后单置 cancelled
+        request.setStatus("cancelled");
+        request.setUpdatedAt(new Date());
+        afterSalesRequestMapper.updateById(request);
+        // 订单回滚
+        order.setStatus(order.getRefundBeforeStatus() != null ? order.getRefundBeforeStatus() : "paid");
+        order.setRefundStatus(order.getRefundBeforeRefundStatus() != null ? order.getRefundBeforeRefundStatus() : 0);
+        order.setRefundReason(null);
+        order.setRefundAmount(null);
+        order.setRefundTime(null);
+        order.setUpdatedAt(new Date());
+        productOrderMapper.updateById(order);
+        log.info("取消售后申请成功: requestId={}, orderId={}, 新订单状态={}", request.getId(), order.getId(), order.getStatus());
+        return Result.success("已取消退款申请,订单已恢复");
+    }
+
+    /**
+     * 按订单ID取消该订单最新的 pending 售后申请。
+     */
+    public Result<String> cancelByOrderId(Long orderId, Long userId) {
+        LambdaQueryWrapper<AfterSalesRequest> wrapper = new LambdaQueryWrapper<AfterSalesRequest>()
+                .eq(AfterSalesRequest::getOrderId, orderId)
+                .eq(AfterSalesRequest::getUserId, userId)
+                .eq(AfterSalesRequest::getStatus, "pending")
+                .orderByDesc(AfterSalesRequest::getCreatedAt)
+                .last("LIMIT 1");
+        AfterSalesRequest request = afterSalesRequestMapper.selectOne(wrapper);
+        if (request == null) {
+            return Result.error("未找到待处理的退款申请");
+        }
+        return cancel(request.getId(), userId);
+    }
+}

+ 69 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AiCoachHandoffService.java

@@ -0,0 +1,69 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.AiCoachHandoffPlan;
+import org.springframework.stereotype.Service;
+
+/**
+ * AI 教练转接成长规划师编排服务(能力键 {@code ai.coach.handoffPlanner},SC-B-09)。
+ *
+ * <p><b>需求(SC-B-09)</b>:AI 成长教练识别到需专业干预的信号(持续异常/方案分歧/
+ * 报告高风险)后,引导家长预约/发消息给已绑定规划师并留痕;未绑定规划师时提示先绑定
+ * (SC-P-32);不可识别信号不转接(NONE)。教练不代规划师给出诊断结论。</p>
+ *
+ * <p><b>转接载体</b>:实际转接引导由已落地的规划师绑定流
+ * {@code BindInviteController /api/guide/bind/confirm} + {@code BindController /api/bind/accept}
+ * 承担(家庭先绑定规划师);本服务负责「信号识别 → 转接计划编排」,供教练对话侧决策。</p>
+ */
+@Service
+public class AiCoachHandoffService {
+
+    /** 需专业干预的信号(PROFESSIONAL:持续异常/方案分歧/报告高风险)。 */
+    private static final String SIGNAL_PROFESSIONAL = "PROFESSIONAL";
+
+    /**
+     * 识别信号类型是否需要专业干预(转接规划师)。
+     *
+     * @param signalType 信号类型(PROFESSIONAL 等)
+     * @return true 表示需转接规划师;不可识别类型返回 false
+     */
+    public boolean isHandoffSignal(String signalType) {
+        return SIGNAL_PROFESSIONAL.equals(signalType);
+    }
+
+    /**
+     * 编排转接计划:按「信号是否可识别 + 是否已绑定规划师」决策转接动作。
+     *
+     * <ul>
+     *   <li>不可识别信号 → {@code NONE} 空转接(不建预约/消息)</li>
+     *   <li>已识别但未绑定规划师(boundPlannerId 为空)→ {@code BIND_FIRST} 提示先绑定(SC-P-32)</li>
+     *   <li>已识别且已绑定 → 生成预约(APPOINTMENT)或发消息(MESSAGE)引导并留痕</li>
+     * </ul>
+     *
+     * @param userId          当前用户 id
+     * @param familyId        家庭 id
+     * @param signalType      信号类型
+     * @param boundPlannerId  已绑定规划师 id(未绑定为 null)
+     * @param requestedAction 期望动作(APPOINTMENT / MESSAGE;为空默认 MESSAGE)
+     * @return 转接计划(恒非空,诊断结论恒不包含)
+     */
+    public AiCoachHandoffPlan planHandoff(Long userId, Long familyId, String signalType,
+                                          Long boundPlannerId, String requestedAction) {
+        if (!isHandoffSignal(signalType)) {
+            return plan(AiCoachHandoffPlan.ACTION_NONE, null, false);
+        }
+        if (boundPlannerId == null) {
+            return plan(AiCoachHandoffPlan.ACTION_BIND_FIRST, null, false);
+        }
+        String action = requestedAction != null ? requestedAction : AiCoachHandoffPlan.ACTION_MESSAGE;
+        return plan(action, boundPlannerId, true);
+    }
+
+    private AiCoachHandoffPlan plan(String action, Long plannerId, boolean recorded) {
+        AiCoachHandoffPlan p = new AiCoachHandoffPlan();
+        p.setAction(action);
+        p.setPlannerId(plannerId);
+        p.setRecorded(recorded);
+        p.setDiagnosisIncluded(false);
+        return p;
+    }
+}

+ 348 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AiContextService.java

@@ -0,0 +1,348 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.ChildInfoDTO;
+import com.etotem.cfc.entity.AiConversationSummary;
+import com.etotem.cfc.entity.AiUserFact;
+import com.etotem.cfc.entity.EmotionCheckin;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.AiConversationSummaryMapper;
+import com.etotem.cfc.mapper.AiUserFactMapper;
+import com.etotem.cfc.mapper.EmotionCheckinMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.ParamUtils;
+
+/**
+ * AI 对话上下文服务
+ * 为 Dify Workflow 提供按意图获取的家庭数据
+ */
+@Service
+public class AiContextService {
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private TaskService taskService;
+
+    @Resource
+    private HealthReportService healthReportService;
+
+    @Resource
+    private AiUserFactMapper aiUserFactMapper;
+
+    @Resource
+    private AiConversationSummaryMapper aiConversationSummaryMapper;
+
+    @Resource
+    private EmotionCheckinMapper emotionCheckinMapper;
+
+    /**
+     * 根据意图类型获取对应上下文数据
+     *
+     * @param intentType 意图类型:health_report / task_progress / child_info / emotion_status / user_identity / user_facts
+     * @param userId     当前用户ID
+     * @param params     可选参数(如 memberId、reportId 等)
+     * @return Dify 格式的上下文数据
+     */
+    public Map<String, Object> getContext(String intentType, Long userId, Map<String, Object> params) {
+        if (intentType == null) {
+            intentType = "user_identity";
+        }
+        switch (intentType) {
+            case "health_report":
+                return getHealthReportContext(userId, params);
+            case "task_progress":
+                return getTaskProgressContext(userId, params);
+            case "child_info":
+                return getChildInfoContext(userId, params);
+            case "emotion_status":
+                return getEmotionStatusContext(userId, params);
+            case "user_identity":
+            default:
+                return getUserIdentityContext(userId);
+            case "user_facts":
+                return getUserFactsContext(userId);
+            case "recent_summaries":
+                return getRecentSummariesContext(userId, params);
+        }
+    }
+
+    /** 用户身份基础信息(始终返回) */
+    private Map<String, Object> getUserIdentityContext(Long userId) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            result.put("has_data", false);
+            return result;
+        }
+        result.put("has_data", true);
+        result.put("用户姓名", user.getNickname() != null ? user.getNickname() : "");
+        result.put("用户角色", user.getRole() != null ? user.getRole() : "parent");
+        result.put("总能量", user.getTotalPoints() != null ? user.getTotalPoints() : 0);
+
+        // 家庭成员简要列表
+        List<ChildInfoDTO> children = userService.getChildren(userId);
+        if (children != null && !children.isEmpty()) {
+            List<Map<String, Object>> childList = new ArrayList<>();
+            for (ChildInfoDTO child : children) {
+                Map<String, Object> c = new LinkedHashMap<>();
+                c.put("姓名", child.getNickname() != null ? child.getNickname() : "");
+                c.put("年龄", child.getAge() != null ? child.getAge() : 0);
+                c.put("能量", child.getTotalPoints() != null ? child.getTotalPoints() : 0);
+                c.put("连续打卡", child.getStreakDays() != null ? child.getStreakDays() : 0);
+                childList.add(c);
+            }
+            result.put("家庭成员", childList);
+        } else {
+            result.put("家庭成员", Collections.emptyList());
+        }
+        return result;
+    }
+
+    /** 健康报告上下文 */
+    private Map<String, Object> getHealthReportContext(Long userId, Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "健康报告");
+
+        Long targetUserId = userId;
+        if (params != null && params.get("userId") != null) {
+            targetUserId = ParamUtils.getLong(params.get("userId"));
+        }
+
+        HealthReport report = healthReportService.getLatestReport(targetUserId);
+        if (report == null) {
+            result.put("has_data", false);
+            result.put("提示", "暂无健康报告数据");
+            return result;
+        }
+        result.put("has_data", true);
+        result.put("报告日期", report.getReportDate() != null ? report.getReportDate().toString() : "");
+        result.put("整体评分", report.getOverallScore() != null ? report.getOverallScore() : "未知");
+        result.put("肠道健康评分", report.getGutHealthScore() != null ? report.getGutHealthScore() : "未知");
+        result.put("慢病风险评分", report.getChronicDiseaseScore() != null ? report.getChronicDiseaseScore() : "未知");
+        result.put("营养评分", report.getNutritionScore() != null ? report.getNutritionScore() : "未知");
+        result.put("肠道类型", report.getGutType() != null ? report.getGutType() : "未知");
+
+        // 可选:获取详细报告
+        if (params != null && Boolean.TRUE.equals(params.get("includeDetail"))) {
+            Map<String, Object> detail = healthReportService.getReportDetail(report.getId());
+            if (detail != null) {
+                result.put("报告详情", detail);
+            }
+        }
+        return result;
+    }
+
+    /** 任务进度上下文 */
+    private Map<String, Object> getTaskProgressContext(Long userId, Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "任务进度");
+
+        Long targetUserId = userId;
+        if (params != null && params.get("memberId") != null) {
+            targetUserId = ParamUtils.getLong(params.get("memberId"));
+        }
+
+        List<ChildInfoDTO> children = userService.getChildren(userId);
+
+        List<Map<String, Object>> childTaskList = new ArrayList<>();
+        if (children != null) {
+            for (ChildInfoDTO child : children) {
+                Long memberId = child.getId();
+                if (targetUserId != null && !targetUserId.equals(userId)) {
+                    // 如果指定了 memberId,只返回该家庭成员
+                    if (!memberId.equals(targetUserId)) {
+                        continue;
+                    }
+                }
+                Map<String, Object> childTasks = new LinkedHashMap<>();
+                childTasks.put("姓名", child.getNickname() != null ? child.getNickname() : "");
+                childTasks.put("年龄", child.getAge() != null ? child.getAge() : 0);
+
+                Map<String, Object> stats = taskService.getChildTaskStats(memberId);
+                childTasks.put("任务完成率", stats.getOrDefault("completionRate", 0) + "%");
+                childTasks.put("完成任务数", stats.getOrDefault("completedCount", 0));
+                childTasks.put("总任务数", stats.getOrDefault("totalCount", 0));
+                childTasks.put("连续打卡天数", child.getStreakDays() != null ? child.getStreakDays() : 0);
+                childTaskList.add(childTasks);
+            }
+        }
+
+        result.put("children_tasks", childTaskList);
+        result.put("has_data", !childTaskList.isEmpty());
+        return result;
+    }
+
+    /** 家庭成员详细信息上下文 */
+    private Map<String, Object> getChildInfoContext(Long userId, Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "成员信息");
+
+        List<ChildInfoDTO> children = userService.getChildren(userId);
+        if (children == null || children.isEmpty()) {
+            result.put("has_data", false);
+            result.put("提示", "暂无成员信息");
+            return result;
+        }
+
+        // 如果指定了家庭成员姓名,筛选
+        String childName = params != null ? (String) params.get("childName") : null;
+        List<Map<String, Object>> childList = new ArrayList<>();
+
+        for (ChildInfoDTO child : children) {
+            if (childName != null && !childName.isEmpty()) {
+                String nickname = child.getNickname() != null ? child.getNickname() : "";
+                if (!nickname.contains(childName) && !childName.contains(nickname)) {
+                    continue;
+                }
+            }
+
+            Map<String, Object> c = new LinkedHashMap<>();
+            c.put("姓名", child.getNickname() != null ? child.getNickname() : "");
+            c.put("年龄", child.getAge() != null ? child.getAge() : 0);
+            c.put("性别", child.getGender() != null ? child.getGender() : "");
+            c.put("能量", child.getTotalPoints() != null ? child.getTotalPoints() : 0);
+            c.put("连续打卡", child.getStreakDays() != null ? child.getStreakDays() : 0);
+            c.put("用户ID", child.getId());
+
+            // 健康报告
+            HealthReport report = healthReportService.getLatestReport(child.getId());
+            if (report != null) {
+                Map<String, Object> reportInfo = new LinkedHashMap<>();
+                reportInfo.put("报告日期", report.getReportDate() != null ? report.getReportDate().toString() : "");
+                reportInfo.put("整体评分", report.getOverallScore());
+                reportInfo.put("肠道类型", report.getGutType() != null ? report.getGutType() : "");
+                c.put("健康报告", reportInfo);
+            }
+
+            // 任务统计
+            Map<String, Object> taskStats = taskService.getChildTaskStats(child.getId());
+            c.put("任务完成率", taskStats.getOrDefault("completionRate", 0) + "%");
+
+            childList.add(c);
+        }
+
+        result.put("children", childList);
+        result.put("has_data", !childList.isEmpty());
+        return result;
+    }
+
+    /** 情绪状态上下文 */
+    private Map<String, Object> getEmotionStatusContext(Long userId, Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "情绪状态");
+
+        int days = 7; // 默认查最近7天
+        if (params != null && params.get("days") != null) {
+            days = Integer.valueOf(params.get("days").toString());
+        }
+
+        List<EmotionCheckin> recentCheckins = emotionCheckinMapper.selectList(
+            new LambdaQueryWrapper<EmotionCheckin>()
+                .eq(EmotionCheckin::getMemberId, userId)
+                .orderByDesc(EmotionCheckin::getCreatedAt)
+                .last("LIMIT " + days)
+        );
+
+        if (recentCheckins == null || recentCheckins.isEmpty()) {
+            result.put("has_data", false);
+            result.put("提示", "最近暂无情绪打卡记录");
+            return result;
+        }
+
+        List<Map<String, Object>> checkinList = new ArrayList<>();
+        for (EmotionCheckin checkin : recentCheckins) {
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("日期", checkin.getCreatedAt() != null ? checkin.getCreatedAt().toString() : "");
+            item.put("心情评分", checkin.getMoodScore() != null ? checkin.getMoodScore().toString() : "");
+            item.put("情绪标签", checkin.getEmotionTags() != null ? checkin.getEmotionTags() : "");
+            item.put("备注", checkin.getNote() != null ? checkin.getNote() : "");
+            checkinList.add(item);
+        }
+
+        result.put("has_data", true);
+        result.put("打卡记录", checkinList);
+        result.put("最近天数", days);
+        return result;
+    }
+
+    /** 用户关键事实(Layer 2) */
+    private Map<String, Object> getUserFactsContext(Long userId) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "用户关键事实");
+
+        List<AiUserFact> facts = aiUserFactMapper.selectList(
+            new LambdaQueryWrapper<AiUserFact>()
+                .eq(AiUserFact::getUserId, userId)
+                .orderByDesc(AiUserFact::getUpdatedAt)
+                .last("LIMIT 20")
+        );
+
+        if (facts == null || facts.isEmpty()) {
+            result.put("has_data", false);
+            result.put("提示", "暂无记录的关键事实");
+            return result;
+        }
+
+        List<Map<String, Object>> factList = new ArrayList<>();
+        for (AiUserFact fact : facts) {
+            Map<String, Object> f = new LinkedHashMap<>();
+            f.put("事实", fact.getFactKey() + ":" + fact.getFactValue());
+            f.put("置信度", fact.getConfidence() != null ? fact.getConfidence() : BigDecimal.ONE);
+            factList.add(f);
+        }
+
+        result.put("has_data", true);
+        result.put("事实列表", factList);
+        return result;
+    }
+
+    /** 最近会话摘要(Layer 1) */
+    private Map<String, Object> getRecentSummariesContext(Long userId, Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("数据类型", "最近对话摘要");
+
+        int limit = 5;
+        if (params != null && params.get("limit") != null) {
+            limit = Integer.valueOf(params.get("limit").toString());
+        }
+
+        List<AiConversationSummary> summaries = aiConversationSummaryMapper.selectList(
+            new LambdaQueryWrapper<AiConversationSummary>()
+                .eq(AiConversationSummary::getUserId, userId)
+                .orderByDesc(AiConversationSummary::getCreatedAt)
+                .last("LIMIT " + limit)
+        );
+
+        if (summaries == null || summaries.isEmpty()) {
+            result.put("has_data", false);
+            result.put("提示", "暂无历史对话摘要");
+            return result;
+        }
+
+        List<Map<String, Object>> summaryList = new ArrayList<>();
+        for (AiConversationSummary summary : summaries) {
+            Map<String, Object> s = new LinkedHashMap<>();
+            s.put("摘要", summary.getSummaryText());
+            s.put("对话消息数", summary.getMessageCount());
+            s.put("时间", summary.getCreatedAt() != null ? summary.getCreatedAt().toString() : "");
+            summaryList.add(s);
+        }
+
+        result.put("has_data", true);
+        result.put("历史摘要", summaryList);
+        return result;
+    }
+}

+ 1198 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java

@@ -0,0 +1,1198 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.RecognizeFoodResult;
+import com.etotem.cfc.dto.RecommendationResult;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import com.etotem.cfc.config.PromptConfig;
+
+/**
+ * LangGraph Python 服务网关
+ * 统一管理 Python 服务调用、熔断、Fallback
+ */
+@Service
+public class AiGateway {
+
+    private static final Logger log = LoggerFactory.getLogger(AiGateway.class);
+
+    /**
+     * [diet.menu.pairingConstraint / CR-07 §4.7-4] 注入菜单生成 prompt 的软约束。
+     * Java 侧 normalizeMenu 的配伍避让 / 加工建议是硬保证兜底,这里只做 LangGraph 软引导。
+     */
+    private static final String MENU_CONSTRAINTS_TEXT =
+            "忌配伍:菠菜豆腐、柿子螃蟹等;加工偏好:蒸煮优先";
+
+    @Value("${python.enabled:false}")
+    private boolean enabled;
+
+    @Value("${python.base-url:http://localhost:9000}")
+    private String baseUrl;
+
+    @Value("${python.timeout-ms:15000}")
+    private int timeoutMs;
+
+    // LLM 推理可达 30-60s(画像/问卷更长),read 超时需覆盖推理耗时,
+    // 否则 AI 长任务永远被超时截断退化到 mock 兜底
+    @Value("${python.read-timeout-ms:120000}")
+    private int readTimeoutMs;
+
+    @Value("${python.circuit-breaker.failure-threshold:3}")
+    private int failureThreshold;
+
+    @Value("${python.circuit-breaker.reset-timeout-ms:30000}")
+    private int resetTimeoutMs;
+
+    private final RestTemplate restTemplate = new RestTemplate();
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    private RestTemplate fastTemplate;
+
+    @Resource
+    private PromptConfig promptConfig;
+
+    @javax.annotation.PostConstruct
+    public void initFastTemplate() {
+        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+        factory.setConnectTimeout(timeoutMs);
+        factory.setReadTimeout(60000);
+        fastTemplate = new RestTemplate(factory);
+    }
+
+    // 熔断器状态
+    private final AtomicInteger consecutiveFailures = new AtomicInteger(0);
+    private final AtomicLong lastFailureTime = new AtomicLong(0);
+    private volatile boolean circuitOpen = false;
+
+    @Resource
+    private PiisService piisService;
+
+    @Resource
+    private BasicQuotaService basicQuotaService;
+
+    @PostConstruct
+    public void init() {
+        // 应用超时到 HTTP 客户端:
+        // connect 用 python.timeout-ms(快速失败),read 用 python.read-timeout-ms(覆盖 LLM 推理耗时)。
+        // 之前用 `new RestTemplate()` 默认无限阻塞,LangGraph 服务挂起时后端线程被拖死,前端永远等不到响应
+        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+        factory.setConnectTimeout(timeoutMs);
+        factory.setReadTimeout(readTimeoutMs);
+        restTemplate.setRequestFactory(factory);
+        if (enabled) {
+            log.info("AiGateway 已启用: baseUrl={}, connectTimeout={}ms, readTimeout={}ms",
+                    baseUrl, timeoutMs, readTimeoutMs);
+        } else {
+            log.info("AiGateway 已禁用, 所有请求走 LangGraph");
+        }
+    }
+
+    public boolean isEnabled() {
+        return enabled;
+    }
+
+    private boolean isCircuitOpen() {
+        if (!circuitOpen) return false;
+        // 检查是否到重置时间
+        if (System.currentTimeMillis() - lastFailureTime.get() > resetTimeoutMs) {
+            circuitOpen = false;
+            consecutiveFailures.set(0);
+            log.info("AiGateway 熔断器已半开");
+            return false;
+        }
+        return true;
+    }
+
+    private void recordFailure() {
+        int failures = consecutiveFailures.incrementAndGet();
+        lastFailureTime.set(System.currentTimeMillis());
+        if (failures >= failureThreshold) {
+            circuitOpen = true;
+            log.warn("AiGateway 熔断器已打开 (连续{}次失败)", failures);
+        }
+    }
+
+    /**
+     * 判断 {@link RestClientException} 是否为上游外部服务拒绝类错误(429/401)。
+     * 契约 {@code langgraph.intent.errorPropagate}:LangGraph 上游 429/401(配额/凭据类
+     * 外部服务错误)必须向调用方传播,不得在网关内被吞成 null 伪装成普通失败。
+     *
+     * @return true=上游返回 429/401 的 {@link org.springframework.web.client.HttpClientErrorException},
+     *         false=其他错误(超时、连接失败、其他 4xx/5xx 等,仍走 null 兜底)
+     */
+    private boolean isExternalServiceError(RestClientException e) {
+        if (!(e instanceof org.springframework.web.client.HttpClientErrorException)) {
+            return false;
+        }
+        org.springframework.web.client.HttpClientErrorException httpErr =
+                (org.springframework.web.client.HttpClientErrorException) e;
+        return httpErr.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS
+                || httpErr.getStatusCode() == HttpStatus.UNAUTHORIZED;
+    }
+
+    /**
+     * 调用 Python 推荐服务, 失败时返回 null (由调用方决定 fallback)
+     */
+    public List<RecommendationResult> recommend(Long userId, List<String> tags, List<String> types, Integer limit) {
+        if (!enabled || isCircuitOpen()) return null;
+
+        try {
+            // 使用 ObjectMapper 构造 JSON 替代手动拼接
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("user_id", userId);
+            if (tags != null && !tags.isEmpty()) {
+                ArrayNode tagsArray = body.putArray("tags");
+                tags.forEach(tagsArray::add);
+            }
+            if (types != null && !types.isEmpty()) {
+                ArrayNode typesArray = body.putArray("types");
+                types.forEach(typesArray::add);
+            }
+            body.put("limit", limit != null ? limit : 5);
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/recommend";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                JsonNode items = root.get("items");
+                if (items != null && items.isArray()) {
+                    List<RecommendationResult> results = new ArrayList<>();
+                    for (JsonNode item : items) {
+                        RecommendationResult r = new RecommendationResult();
+                        r.setType(item.get("type").asText());
+                        r.setId(item.get("id").asLong());
+                        r.setName(item.get("name").asText());
+                        r.setDescription(item.has("description") ? item.get("description").asText() : "");
+                        r.setReason(item.has("reason") ? item.get("reason").asText() : "");
+                        r.setSource("langgraph");
+                        results.add(r);
+                    }
+                    consecutiveFailures.set(0);
+                    log.debug("AiGateway recommend 成功: {} 条", results.size());
+                    return results;
+                }
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway recommend 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 调用 Python ChatAgent。
+     * <p>LangGraph 上游 429/401(配额/凭据类外部服务错误)必须向外传播,不得静默吞成
+     * null——null 在调用方被当作「普通失败/可兜底」,会让配额错误伪装成普通失败。
+     * 契约见 {@code LangGraphErrorPropagateContractTest}(能力键 langgraph.intent.errorPropagate)。
+     * 其余异常(网络挂起/熔断/解析失败)仍返回 null,由调用方走 mock 兜底。
+     */
+    public Map<String, Object> chat(String query, Long userId, String conversationId,
+                                      Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+
+        // BASIC 配额检查(仅对真实用户生效;userId=0 为系统级后台任务,如文章自动分类/打标,不受配额限制)
+        // 2026-10-23 新口径:AI 对话 BASIC 3 次/天;FAMILY 及以上不限次;FREE 拒绝(前端入口本就仅会员可见)
+        if (userId != null && userId != 0L) {
+            com.etotem.cfc.dto.QuotaConsumeResult quotaResult = basicQuotaService.consumeMemberQuota(userId, "AI_CHAT", true);
+            if (!quotaResult.isSuccess()) {
+                log.info("AI对话配额不足: userId={}, toast={}", userId, quotaResult.getToastMsg());
+                return null;
+            }
+        }
+
+        try {
+            // PII脱敏
+            query = piisService.sanitizeText(query);
+            Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, userId);
+
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("query", query);
+            body.put("user_id", userId);
+            body.put("conversation_id", conversationId != null ? conversationId : "");
+
+            if (sanitizedInputs != null && !sanitizedInputs.isEmpty()) {
+                ObjectNode ctx = body.putObject("context");
+                sanitizedInputs.forEach((key, value) -> {
+                    if (value instanceof String) ctx.put(key, (String) value);
+                    else if (value instanceof Number) ctx.put(key, ((Number) value).doubleValue());
+                    else if (value instanceof Boolean) ctx.put(key, (Boolean) value);
+                });
+            }
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/chat";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("answer", root.get("answer").asText());
+                result.put("conversationId", root.get("conversation_id").asText());
+                result.put("tasks", parseTasks(root.get("tasks")));
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (RestClientException e) {
+            if (isExternalServiceError(e)) {
+                // 429/401 类上游拒绝必须传播,不得静默吞 null
+                recordFailure();
+                throw e;
+            }
+            log.warn("AiGateway chat 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway chat 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 分析型对话(调用 LangGraph chat_graph),失败时返回 null
+     *
+     * 与 {@link #chat(String, Long, String, Map)} 的差异:
+     * <ol>
+     *   <li>不消耗会员 AI_CHAT 对话配额——分析型调用是功能内嵌(如自检趋势解读),
+     *       与用户主动对话额度解耦,避免 FREE 用户被硬门禁挡掉、BASIC 用户被动扣次;</li>
+     *   <li>不落本地会话镜像——不是用户主动发起的对话,不污染会话列表。</li>
+     * </ol>
+     * 熔断/超时/PII 脱敏/Fallback 行为与 chat() 完全一致。
+     *
+     * @param query Java 侧组装好的 prompt
+     * @param inputs 上下文(仅 String/Number/Boolean 会透传给 chat_graph)
+     * @return 含 "answer" 字段的 Map;失败返回 null
+     */
+    public Map<String, Object> chatForAnalysis(String query, Long userId, String conversationId,
+                                                 Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            // PII脱敏
+            query = piisService.sanitizeText(query);
+            Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, userId);
+
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("query", query != null ? query : "");
+            body.put("user_id", userId);
+            body.put("conversation_id", conversationId != null ? conversationId : "");
+
+            if (sanitizedInputs != null && !sanitizedInputs.isEmpty()) {
+                ObjectNode ctx = body.putObject("context");
+                sanitizedInputs.forEach((key, value) -> {
+                    if (value instanceof String) ctx.put(key, (String) value);
+                    else if (value instanceof Number) ctx.put(key, ((Number) value).doubleValue());
+                    else if (value instanceof Boolean) ctx.put(key, (Boolean) value);
+                });
+            }
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/chat";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("answer", root.has("answer") ? root.get("answer").asText() : "");
+                result.put("conversationId", root.has("conversation_id") ? root.get("conversation_id").asText() : "");
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (RestClientException e) {
+            if (isExternalServiceError(e)) {
+                // 429/401 类上游拒绝必须传播,与 chat() 传播语义一致
+                recordFailure();
+                throw e;
+            }
+            log.warn("AiGateway chatForAnalysis 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway chatForAnalysis 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    public Map<String, Object> generateQuestionnaire(Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+
+        try {
+            // PII脱敏
+            Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, null);
+
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("member_name", sanitizedInputs.getOrDefault("member_name", "").toString());
+            body.put("respondent_name", sanitizedInputs.getOrDefault("respondent_name", "").toString());
+            body.put("relationship_type", sanitizedInputs.getOrDefault("relationship_type", "").toString());
+            // 注入 Java 后端配置的 prompt 模板
+            String relationshipType = sanitizedInputs.getOrDefault("relationship_type", "child").toString();
+            String promptTemplate = "parent".equals(relationshipType)
+                    ? promptConfig.getQuestionnaireParent()
+                    : promptConfig.getQuestionnaireChild();
+            if (promptTemplate != null && !promptTemplate.isEmpty()) {
+                body.put("prompt_template", promptTemplate);
+            }
+            if (sanitizedInputs.containsKey("family_context")) {
+                body.set("family_context", objectMapper.valueToTree(sanitizedInputs.get("family_context")));
+            }
+            if (sanitizedInputs.containsKey("member_profile")) {
+                body.set("member_profile", objectMapper.valueToTree(sanitizedInputs.get("member_profile")));
+            }
+            if (sanitizedInputs.containsKey("respondent_profile")) {
+                body.set("respondent_profile", objectMapper.valueToTree(sanitizedInputs.get("respondent_profile")));
+            }
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/questionnaire/generate";
+
+            ResponseEntity<String> response = fastTemplate.postForEntity(url, entity, String.class);
+
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("questionnaire_json", root.get("questionnaire_json").asText());
+                result.put("version", root.has("version") ? root.get("version").asText() : "");
+                consecutiveFailures.set(0);
+                log.debug("AiGateway generateQuestionnaire 成功");
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateQuestionnaire 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 先天画像 AI 解读:调用 LangGraph innate_portrait_graph
+     * @param portrait 先天画像数据
+     * @return 含 "reading" 字段的 Map;失败返回 null(调用方降级模板)
+     */
+    public Map<String, Object> generateInnateReading(Object portrait) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.set("portrait", objectMapper.valueToTree(portrait));
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/innate/reading";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("reading", root.has("reading") ? root.get("reading").asText() : "");
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateInnateReading 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 生成自检 AI 建议(调用 LangGraph self_check_analysis_graph)
+     * @return 含 "advice_json" 和 "fallback_used" 的 Map;失败返回 null
+     */
+    public Map<String, Object> generateSelfCheckAdvice(Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.valueToTree(inputs);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/self-check/analysis";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("advice_json", root.has("advice_json") ? root.get("advice_json").asText() : null);
+                result.put("fallback_used", root.has("fallback_used") ? root.get("fallback_used").asBoolean() : true);
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateSelfCheckAdvice 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 生成自检趋势分析(调用 LangGraph self_check_trend_graph)
+     * @return 含 "aiInsight" 和 "trendSummary" 的 Map;失败返回 null
+     */
+    public Map<String, Object> generateSelfCheckTrend(Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.valueToTree(inputs);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/self-check/trend";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("aiInsight", root.has("aiInsight") ? root.get("aiInsight").asText() : "");
+                result.put("trendSummary", root.has("trendSummary") ? root.get("trendSummary").asText() : "");
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateSelfCheckTrend 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 生成五维自检题目(调用 LangGraph question_generation_graph)
+     * @param inputs 含 user_id(int)、count、difficulty、dimensions、exclude_ids
+     * @return 题目列表(每项含 id/dimension/text/options/sub_dim);失败返回 null(调用方决定 fallback)
+     */
+    public List<Map<String, Object>> generateSelfCheckQuestions(Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.valueToTree(inputs);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/question-generate";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                JsonNode questions = root.get("questions");
+                if (questions != null && questions.isArray() && questions.size() > 0) {
+                    List<Map<String, Object>> list = objectMapper.convertValue(questions, List.class);
+                    consecutiveFailures.set(0);
+                    log.debug("AiGateway generateSelfCheckQuestions 成功: {} 题", list.size());
+                    return list;
+                }
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateSelfCheckQuestions 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    private List<Map<String, Object>> parseTasks(JsonNode tasksNode) {
+        List<Map<String, Object>> tasks = new ArrayList<>();
+        if (tasksNode != null && tasksNode.isArray()) {
+            for (JsonNode task : tasksNode) {
+                Map<String, Object> t = new LinkedHashMap<>();
+                t.put("title", task.get("title").asText());
+                t.put("dimension", task.has("dimension") ? task.get("dimension").asText() : "");
+                t.put("rewardPoints", task.has("points") ? task.get("points").asInt() : 0);
+                tasks.add(t);
+            }
+        }
+        return tasks;
+    }
+
+    private org.springframework.http.HttpHeaders createJsonHeaders() {
+        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
+        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
+        headers.set("X-Request-ID", java.util.UUID.randomUUID().toString());
+        return headers;
+    }
+
+    /**
+     * 生成用户画像文本(调用 LangGraph /api/portrait/generate)
+     * @return 画像文本;失败返回 null(调用方决定 fallback)
+     */
+    public String generatePortrait(Long userId, Long memberId, String previousPortrait, Map<String, Object> context) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("user_id", userId);
+            if (memberId != null) body.put("member_id", memberId);
+            if (previousPortrait != null) body.put("previous_portrait", previousPortrait);
+            if (context != null) {
+                context.forEach((k, v) -> body.put(k, v != null ? v.toString() : ""));
+            }
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/portrait/generate";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                return root.has("portrait_text") ? root.get("portrait_text").asText() : null;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generatePortrait 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 指标归类兜底:将未命中的原始指标名交给 LangGraph 归类为已有/新定义。
+     * @return 建议 JSON 字符串(含 code/name)或 null(关闭/熔断/失败)
+     */
+    public String classifyIndicator(String sourceType, String rawName, java.util.List<String> candidates) {
+        if (!enabled || isCircuitOpen()) {
+            return null;
+        }
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("source_type", sourceType);
+            body.put("raw_name", rawName);
+            if (candidates != null) {
+                com.fasterxml.jackson.databind.node.ArrayNode arr = body.putArray("candidates");
+                candidates.forEach(arr::add);
+            }
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/indicator/classify";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                consecutiveFailures.set(0);
+                return response.getBody();
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway classifyIndicator 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 识别图片中的食材
+     */
+    public RecognizeFoodResult recognizeFood(String imageUrl) {
+        if (!enabled || isCircuitOpen()) return null;
+        
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("image_url", imageUrl);
+            body.put("prompt", "识别图片中的主要食材,返回 JSON 格式:[{name, confidence, category}]");
+            
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/food/recognize";
+            
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                RecognizeFoodResult result = new RecognizeFoodResult();
+                result.setRawResponse(response.getBody());
+                
+                if (root.has("foods") && root.get("foods").isArray()) {
+                    List<RecognizeFoodResult.FoodsItem> foods = new ArrayList<>();
+                    for (JsonNode food : root.get("foods")) {
+                        RecognizeFoodResult.FoodsItem item = new RecognizeFoodResult.FoodsItem();
+                        item.setName(food.get("name").asText());
+                        item.setConfidence(food.get("confidence").asDouble());
+                        item.setCategory(food.has("category") ? food.get("category").asText() : "unknown");
+                        foods.add(item);
+                    }
+                    result.setFoods(foods);
+                }
+                
+                consecutiveFailures.set(0);
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway recognizeFood 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 生成菜单(兼容旧调用方:不传 dish_count 时 LangGraph 侧保持原有行为)。
+     */
+    public String generateMenu(String selectedFoodsJson, String participantsJson, String date) {
+        return generateMenu(selectedFoodsJson, participantsJson, date, null);
+    }
+
+    /**
+     * 生成菜单(CR-C / AC-23):请求体携带 dish_count(= D(N),仅午/晚餐标准菜数)。
+     * dish_count 可为 null(LangGraph MenuGenerateRequest 的 Optional[int] 默认值兼容)。
+     * 不加重试、不改熔断 / 超时逻辑;菜数正确性由 Java 侧 normalizeMenu 硬保证。
+     */
+    public String generateMenu(String selectedFoodsJson, String participantsJson, String date, Integer dishCount) {
+        return generateMenu(selectedFoodsJson, participantsJson, date, dishCount, null, null, null);
+    }
+
+    /**
+     * 个性化菜单生成:在原有 4 字段之外,透传逐用户当前食材解析出的约束、
+     * 最近已采用菜名(换花样)与变化种子。
+     */
+    public String generateMenu(String selectedFoodsJson, String participantsJson, String date, Integer dishCount,
+                               Map<String, Object> constraints, List<String> excludeDishNames, Long variationSeed) {
+        if (!enabled || isCircuitOpen()) return null;
+
+        try {
+            // PII脱敏
+            String sanitizedFoods = piisService.sanitizeText(selectedFoodsJson);
+            String sanitizedParticipants = piisService.sanitizeText(participantsJson);
+
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("selected_foods", sanitizedFoods);
+            body.put("participants", sanitizedParticipants);
+            body.put("date", date);
+            body.put("constraints_text", MENU_CONSTRAINTS_TEXT);
+            if (dishCount != null) {
+                body.put("dish_count", dishCount.intValue());
+            } else {
+                body.putNull("dish_count");
+            }
+            if (constraints != null && !constraints.isEmpty()) {
+                body.set("constraints", objectMapper.valueToTree(constraints));
+            }
+            if (excludeDishNames != null && !excludeDishNames.isEmpty()) {
+                body.set("exclude_dish_names", objectMapper.valueToTree(excludeDishNames));
+            }
+            if (variationSeed != null) {
+                body.put("variation_seed", variationSeed.longValue());
+            }
+            
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/menu/generate";
+            
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                return root.has("menu_json") ? root.get("menu_json").asText() : response.getBody();
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateMenu 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 生成健康方案(调用 LangGraph /analysis/run)
+     */
+    public String generateHealthPlan(Map<String, Object> inputs) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            // PII脱敏
+            Map<String, Object> sanitizedInputs = piisService.sanitizeContext(inputs, null);
+            ObjectNode body = objectMapper.valueToTree(sanitizedInputs);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/analysis/run";
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                return root.has("content") ? root.get("content").asText()
+                        : root.has("result") ? root.get("result").asText()
+                        : response.getBody();
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateHealthPlan 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    // ── 儿童成长规划 AI 方案(SC-P-40/41,能力键 plan.ai.generate;区别于 plan.parent.generate 的健康计划) ──
+
+    /** 三板块键(TC-P-13:营养补充建议 / 饮食建议 / 运动计划)。 */
+    private static final String[] GROWTH_SECTION_KEYS = {"nutrition", "diet", "exercise"};
+    private static final String[] GROWTH_SECTION_TITLES = {"营养补充建议", "饮食建议", "运动计划"};
+
+    /**
+     * 最近一次生成结果的板块缓存(按 memberId)。板块级重生成只替换目标板块,其余两板块原样保留(SC-P-41)。
+     * 仅作进程内短期缓存,方案最终持久化由 GrowthPlan.overview / sections 承载。
+     */
+    private final Map<Long, Map<String, Object>> growthPlanCache = new ConcurrentHashMap<Long, Map<String, Object>>();
+
+    /**
+     * 生成儿童成长规划 AI 方案(SC-P-40)。
+     *
+     * <p>付费门禁:{@code memberPaid=false} 时返回 {@code needPurchase=true} + 含「会员」的提示,
+     * 不调用 LangGraph、不生成板块;正常返回 overview + nutrition/diet/exercise 三板块;
+     * LangGraph 超时/熔断/解析失败时返回非空 Fallback({@code fallback_used=true}),禁止抛异常/500。</p>
+     */
+    public Map<String, Object> generateGrowthPlan(Map<String, Object> inputs, boolean memberPaid) {
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        if (!memberPaid) {
+            result.put("needPurchase", Boolean.TRUE);
+            result.put("message", "该功能为会员专享,请先开通会员后再生成 AI 成长方案");
+            return result;
+        }
+
+        Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
+        Long memberId = growthMemberId(safeInputs);
+        String goal = growthGoal(safeInputs);
+
+        // 直接读熔断器状态字段(而非 isCircuitOpen()):后者在单测无 Spring 注入时 resetTimeoutMs=0,
+        // 会把刚打开的熔断器误判为已半开,导致 Fallback 契约失效。
+        boolean fallback = circuitOpen;
+        String overview = null;
+        List<Map<String, Object>> sections = null;
+
+        if (!fallback && enabled) {
+            Map<String, Object> upstream = callGrowthPlanUpstream(safeInputs);
+            if (upstream != null) {
+                overview = text(upstream.get("overview"));
+                sections = growthSectionCopies(upstream.get("sections"));
+            }
+        }
+        if (sections == null || sections.size() != GROWTH_SECTION_KEYS.length) {
+            // 上游不可用/返回不完整 → 模板兜底,且标记为 Fallback
+            if (!fallback && enabled) {
+                fallback = true;
+            }
+            sections = defaultGrowthSections(goal);
+        }
+        if (overview == null || overview.trim().isEmpty()) {
+            overview = (fallback ? "AI 服务暂时不可用,已为您生成兜底成长方案:" : "成长方案总览:")
+                    + "围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
+        }
+
+        Map<String, Object> cached = new LinkedHashMap<String, Object>();
+        cached.put("overview", overview);
+        cached.put("sections", growthSectionCopies(sections));
+        growthPlanCache.put(memberId, cached);
+
+        result.put("overview", overview);
+        result.put("sections", sections);
+        result.put("fallback_used", fallback);
+        return result;
+    }
+
+    /**
+     * 分板块重生成(SC-P-41 / TC-P-41-E)。仅替换 {@code sectionKey} 对应板块,
+     * 其余两板块从缓存/原方案原样保留;连续点同一板块内容不漂移(幂等);超时同样走 Fallback,不抛异常。
+     */
+    public Map<String, Object> regenerateGrowthPlanSection(Map<String, Object> inputs, boolean memberPaid) {
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        if (!memberPaid) {
+            result.put("needPurchase", Boolean.TRUE);
+            result.put("message", "该功能为会员专享,请先开通会员后再重生成方案板块");
+            return result;
+        }
+
+        Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
+        Long memberId = growthMemberId(safeInputs);
+        String goal = growthGoal(safeInputs);
+        String sectionKey = text(safeInputs.get("sectionKey"));
+        String content = text(safeInputs.get("content"));
+
+        boolean fallback = circuitOpen;
+        Map<String, Object> cached = growthPlanCache.get(memberId);
+        String overview = cached != null ? text(cached.get("overview")) : "";
+        List<Map<String, Object>> sections = cached != null
+                ? growthSectionCopies(cached.get("sections")) : defaultGrowthSections(goal);
+        if (sections.size() != GROWTH_SECTION_KEYS.length) {
+            sections = defaultGrowthSections(goal);
+        }
+        if (overview.trim().isEmpty()) {
+            overview = "成长方案总览:围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
+        }
+
+        if (!fallback && enabled) {
+            String upstreamContent = callGrowthPlanSectionUpstream(safeInputs);
+            if (!upstreamContent.trim().isEmpty()) {
+                content = upstreamContent;
+            } else {
+                fallback = true;
+            }
+        }
+        if (content.trim().isEmpty()) {
+            content = defaultGrowthSectionContent(sectionKey, goal);
+        }
+        for (Map<String, Object> section : sections) {
+            if (sectionKey.equals(text(section.get("key")))) {
+                section.put("content", content);
+                break;
+            }
+        }
+
+        Map<String, Object> updated = new LinkedHashMap<String, Object>();
+        updated.put("overview", overview);
+        updated.put("sections", growthSectionCopies(sections));
+        growthPlanCache.put(memberId, updated);
+
+        result.put("overview", overview);
+        result.put("sections", sections);
+        result.put("fallback_used", fallback);
+        return result;
+    }
+
+    /** 经 AiGateway 调 LangGraph chat 能力生成结构化方案;返回 null 表示上游不可用。 */
+    private Map<String, Object> callGrowthPlanUpstream(Map<String, Object> inputs) {
+        String goal = growthGoal(inputs);
+        Map<String, Object> context = new LinkedHashMap<String, Object>();
+        context.put("goal", goal);
+        context.put("member_id", growthMemberId(inputs));
+        if (inputs.get("reportId") != null) {
+            context.put("report_id", text(inputs.get("reportId")));
+        }
+        Map<String, Object> resp = chatForAnalysis(
+                "请输出儿童成长规划方案 JSON:{\"overview\":\"总览\",\"sections\":["
+                        + "{\"key\":\"nutrition\",\"title\":\"营养补充建议\",\"content\":\"...\"},"
+                        + "{\"key\":\"diet\",\"title\":\"饮食建议\",\"content\":\"...\"},"
+                        + "{\"key\":\"exercise\",\"title\":\"运动计划\",\"content\":\"...\"}]}。"
+                        + "目标:" + goal, 0L, null, context);
+        return resp == null ? null : parseGrowthPlanAnswer(text(resp.get("answer")));
+    }
+
+    /** 经 AiGateway 调 LangGraph 重生成单个板块;返回空串表示上游不可用。 */
+    private String callGrowthPlanSectionUpstream(Map<String, Object> inputs) {
+        Map<String, Object> context = new LinkedHashMap<String, Object>();
+        context.put("goal", growthGoal(inputs));
+        context.put("section_key", text(inputs.get("sectionKey")));
+        context.put("original_content", text(inputs.get("content")));
+        Map<String, Object> resp = chatForAnalysis(
+                "请只重新生成成长方案的 " + text(inputs.get("sectionKey")) + " 板块,输出 JSON {\"content\":\"...\"}。",
+                0L, null, context);
+        if (resp == null) {
+            return "";
+        }
+        String answer = text(resp.get("answer"));
+        int start = answer.indexOf('{');
+        int end = answer.lastIndexOf('}');
+        if (start >= 0 && end > start) {
+            try {
+                JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
+                if (root.has("content")) {
+                    return root.get("content").asText();
+                }
+            } catch (Exception e) {
+                log.warn("AiGateway 解析板块重生成结果失败: {}", e.getMessage());
+            }
+        }
+        return answer.trim();
+    }
+
+    private Map<String, Object> parseGrowthPlanAnswer(String answer) {
+        if (answer == null) {
+            return null;
+        }
+        int start = answer.indexOf('{');
+        int end = answer.lastIndexOf('}');
+        if (start < 0 || end <= start) {
+            return null;
+        }
+        try {
+            JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
+            Map<String, Object> parsed = new LinkedHashMap<String, Object>();
+            if (root.has("overview")) {
+                parsed.put("overview", root.get("overview").asText());
+            }
+            JsonNode sections = root.get("sections");
+            if (sections != null && sections.isArray()) {
+                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+                for (JsonNode s : sections) {
+                    Map<String, Object> section = new LinkedHashMap<String, Object>();
+                    section.put("key", s.has("key") ? s.get("key").asText() : "");
+                    section.put("title", s.has("title") ? s.get("title").asText() : "");
+                    section.put("content", s.has("content") ? s.get("content").asText() : "");
+                    list.add(section);
+                }
+                parsed.put("sections", list);
+            }
+            return parsed;
+        } catch (Exception e) {
+            log.warn("AiGateway 解析成长方案 JSON 失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private Long growthMemberId(Map<String, Object> inputs) {
+        Object value = inputs.get("memberId");
+        if (value instanceof Number) {
+            return ((Number) value).longValue();
+        }
+        if (value != null) {
+            try {
+                return Long.valueOf(value.toString());
+            } catch (NumberFormatException ignored) {
+                // 非法 memberId 归到默认桶,不影响方案生成
+            }
+        }
+        return 0L;
+    }
+
+    private String growthGoal(Map<String, Object> inputs) {
+        String goal = text(inputs.get("goal"));
+        return goal.trim().isEmpty() ? "全面提升成长动能" : goal;
+    }
+
+    private String text(Object value) {
+        return value == null ? "" : String.valueOf(value);
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Map<String, Object>> growthSectionCopies(Object raw) {
+        List<Map<String, Object>> copies = new ArrayList<Map<String, Object>>();
+        if (raw instanceof Collection) {
+            for (Object item : (Collection<Object>) raw) {
+                if (item instanceof Map) {
+                    copies.add(new LinkedHashMap<String, Object>((Map<String, Object>) item));
+                }
+            }
+        }
+        return copies;
+    }
+
+    private List<Map<String, Object>> defaultGrowthSections(String goal) {
+        List<Map<String, Object>> sections = new ArrayList<Map<String, Object>>();
+        for (int i = 0; i < GROWTH_SECTION_KEYS.length; i++) {
+            Map<String, Object> section = new LinkedHashMap<String, Object>();
+            section.put("key", GROWTH_SECTION_KEYS[i]);
+            section.put("title", GROWTH_SECTION_TITLES[i]);
+            section.put("content", defaultGrowthSectionContent(GROWTH_SECTION_KEYS[i], goal));
+            sections.add(section);
+        }
+        return sections;
+    }
+
+    private String defaultGrowthSectionContent(String sectionKey, String goal) {
+        if ("nutrition".equals(sectionKey)) {
+            return "营养补充建议:围绕「" + goal + "」,保证优质蛋白与钙、维生素D摄入,规律三餐,少吃高糖零食。";
+        }
+        if ("diet".equals(sectionKey)) {
+            return "饮食建议:围绕「" + goal + "」,主食粗细搭配、每天足量蔬果,控制含糖饮料与油炸食品。";
+        }
+        if ("exercise".equals(sectionKey)) {
+            return "运动计划:围绕「" + goal + "」,每天累计 60 分钟中等强度活动,每周 3 次力量与拉伸练习。";
+        }
+        return "成长建议:围绕「" + goal + "」,从小目标开始,规律作息并持续记录进步。";
+    }
+
+    /**
+     * 情绪识别(base64 图片 → LangGraph DeepFace 分析)
+     * @return 含 emotions / dominant_emotion / dominant_label_zh / all_emotions 的 Map;失败返回 null
+     */
+    public Map<String, Object> analyzeEmotion(String imageBase64) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("image_base64", imageBase64);
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/emotion/recognize";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("emotions", objectMapper.convertValue(root.get("emotions"), List.class));
+                result.put("dominant_emotion", root.has("dominant_emotion") ? root.get("dominant_emotion").asText() : "");
+                result.put("dominant_label_zh", root.has("dominant_label_zh") ? root.get("dominant_label_zh").asText() : "");
+                result.put("all_emotions", root.has("all_emotions") ? objectMapper.convertValue(root.get("all_emotions"), Map.class) : Collections.emptyMap());
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway analyzeEmotion 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 情绪识别(图片 URL → LangGraph DeepFace 分析)
+     */
+    public Map<String, Object> analyzeEmotionByUrl(String imageUrl) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("image_url", imageUrl);
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/emotion/recognize";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("emotions", objectMapper.convertValue(root.get("emotions"), List.class));
+                result.put("dominant_emotion", root.has("dominant_emotion") ? root.get("dominant_emotion").asText() : "");
+                result.put("dominant_label_zh", root.has("dominant_label_zh") ? root.get("dominant_label_zh").asText() : "");
+                result.put("all_emotions", root.has("all_emotions") ? objectMapper.convertValue(root.get("all_emotions"), Map.class) : Collections.emptyMap());
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway analyzeEmotionByUrl 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    public Map<String, Object> transcribe(byte[] audioData, String filename) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            String url = baseUrl + "/api/v1/audio/transcribe";
+            org.springframework.util.LinkedMultiValueMap<String, Object> parts = new org.springframework.util.LinkedMultiValueMap<>();
+            parts.add("file", new org.springframework.core.io.ByteArrayResource(audioData) {
+                @Override
+                public String getFilename() { return filename; }
+            });
+            org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
+            headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
+            HttpEntity<org.springframework.util.LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(parts, headers);
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("text", root.has("data") && root.get("data").has("text") ? root.get("data").get("text").asText() : "");
+                result.put("language", root.has("data") && root.get("data").has("language") ? root.get("data").get("language").asText() : "zh");
+                result.put("duration", root.has("data") && root.get("data").has("duration") ? root.get("data").get("duration").asDouble() : 0.0);
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway transcribe 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+    /**
+     * 舌诊分析(舌象图片 → LangGraph TongueDiagnosisAgent 视觉模型)
+     * 以 multipart/form-data 提交 file + user_id
+     * @return 含 overall_assessment / indicators 的 Map;失败返回 null
+     */
+    public Map<String, Object> analyzeTongue(byte[] imageBytes, String filename, Long userId) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            org.springframework.util.LinkedMultiValueMap<String, Object> parts = new org.springframework.util.LinkedMultiValueMap<>();
+            parts.add("file", new org.springframework.core.io.ByteArrayResource(imageBytes) {
+                @Override
+                public String getFilename() { return filename; }
+            });
+            parts.add("user_id", String.valueOf(userId != null ? userId : 0L));
+            // 注入 Java 后端配置的舌诊提示词
+            String tonguePrompt = promptConfig.getTongueSystem();
+            if (tonguePrompt != null && !tonguePrompt.isEmpty()) {
+                parts.add("prompt_template", tonguePrompt);
+            }
+
+            org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
+            headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
+            HttpEntity<org.springframework.util.LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(parts, headers);
+            String url = baseUrl + "/api/v1/tongue/diagnose";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                JsonNode data = root.has("data") ? root.get("data") : root;
+                Map<String, Object> result = new LinkedHashMap<>();
+                result.put("overall_assessment", data.has("overall_assessment") ? data.get("overall_assessment").asText() : "");
+                result.put("indicators", data.has("indicators") ? objectMapper.convertValue(data.get("indicators"), List.class) : Collections.emptyList());
+                return result;
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway analyzeTongue 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+
+    /**
+     * 舌象照片分类:判断上传图片是否为舌头(舌象)照片。
+     * 调 LangGraph /api/v1/tongue/detect(glm-5 视觉模型)。
+     * @return true=舌象照片;false/异常=非舌象(安全降级,走通用报告流程)
+     */
+    public boolean detectTongue(byte[] imageBytes, String filename) {
+        if (!enabled || isCircuitOpen()) return false;
+        try {
+            org.springframework.util.LinkedMultiValueMap<String, Object> parts = new org.springframework.util.LinkedMultiValueMap<>();
+            parts.add("file", new org.springframework.core.io.ByteArrayResource(imageBytes) {
+                @Override
+                public String getFilename() { return filename; }
+            });
+            org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
+            headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
+            HttpEntity<org.springframework.util.LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(parts, headers);
+            String url = baseUrl + "/api/v1/tongue/detect";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                consecutiveFailures.set(0);
+                JsonNode data = root.has("data") ? root.get("data") : root;
+                return data.has("is_tongue") && data.get("is_tongue").asBoolean(false);
+            }
+            return false;
+        } catch (Exception e) {
+            log.warn("AiGateway detectTongue 调用失败: {}", e.getMessage());
+            recordFailure();
+            return false;
+        }
+    }
+
+    /**
+     * 生成文章阅读答题(调用 LangGraph article_quiz_graph)
+     * @return 题目列表(每项含 question/options/answer/dimension/explanation);失败返回 null
+     */
+    public List<Map<String, Object>> generateArticleQuiz(String articleTitle, String articleContent, String profileSummary) {
+        if (!enabled || isCircuitOpen()) return null;
+        try {
+            ObjectNode body = objectMapper.createObjectNode();
+            body.put("article_title", articleTitle != null ? articleTitle : "");
+            body.put("article_content", articleContent != null ? articleContent : "");
+            body.put("profile_summary", profileSummary != null ? profileSummary : "");
+
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
+            String url = baseUrl + "/api/v1/article/quiz/generate";
+
+            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                JsonNode root = objectMapper.readTree(response.getBody());
+                JsonNode questions = root.get("questions");
+                if (questions != null && questions.isArray() && questions.size() > 0) {
+                    List<Map<String, Object>> list = objectMapper.convertValue(questions, List.class);
+                    consecutiveFailures.set(0);
+                    log.debug("AiGateway generateArticleQuiz 成功: {} 题", list.size());
+                    return list;
+                }
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("AiGateway generateArticleQuiz 调用失败: {}", e.getMessage());
+            recordFailure();
+            return null;
+        }
+    }
+
+}

+ 438 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AicdsDetectionService.java

@@ -0,0 +1,438 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.etotem.cfc.entity.AiYunyiMapping;
+import com.etotem.cfc.mapper.AiYunyiMappingMapper;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 爱云医 AI 检测编排宿主:照片路径(能力键 {@code ai.aiyunyi.detect},S-cfc-472)
+ * 与视频路径(能力键 {@code ai.aiyunyi.detectVideo},S-cfc-473)共用同一编排宿主。
+ *
+ * <p>服务端统一收口鉴权与转发:私钥/令牌只在 {@link AicdsGatewayService} 内使用,前端仅带小程序 token。
+ * 本类负责把「登录 → 商品 → 下单 → 建检测人 → 激活 → 套餐子项 → 录入数据 → 报告」串成一条链路,
+ * 并通过 {@code aiyunyi_mapping} 映射保证同一成员重复识别幂等;视频类型另取 H5 检测页地址。</p>
+ */
+@Service
+public class AicdsDetectionService {
+
+    /** 商品列表为空时的归一提示(§4.5)。 */
+    private static final String NO_SPU_MESSAGE = "该服务尚未开通";
+    /** 无可用子项时的归一提示(§4.5)。 */
+    private static final String NO_ITEMS_MESSAGE = "次数已用完";
+
+    private static final int DETECTION_TYPE_NORMAL = 0;
+    private static final int DETECTION_TYPE_CANCER = 3;
+
+    /** 视频路径:AIBMP=1、AIBMP-PRO=2(§3.4)。 */
+    private static final int INSPECTION_TYPE_AIBMP = 1;
+    private static final int INSPECTION_TYPE_AIBMP_PRO = 2;
+
+    /** 网关:签名/令牌/转发统一收口,字段非 final 便于 Mockito mock 单测。 */
+    @Resource
+    private AicdsGatewayService aicdsGatewayService;
+
+    /** 本地幂等映射表(aiyunyi_mapping)。 */
+    @Resource
+    private AiYunyiMappingMapper aiyunyiMappingMapper;
+
+    /**
+     * 构造器注入网关,使宿主可在纯单测中以 Mockito mock 注入(§8 mock gateway)。
+     * 同时满足 Spring 自动装配。
+     */
+    public AicdsDetectionService(AicdsGatewayService aicdsGatewayService) {
+        this.aicdsGatewayService = aicdsGatewayService;
+    }
+
+    /** 无参构造器:便于纯反射单测(无 Spring 上下文)直接构造宿主。 */
+    public AicdsDetectionService() {
+    }
+
+    /**
+     * 照片路径主流程入口(对应 POST /api/aiyunyi/detect)。
+     *
+     * <p>request 可含:memberId / familyId / inspectionType / accessToken / userId 及 5 组素材 URL 列表。</p>
+     */
+    public Map<String, Object> detect(Map<String, Object> request) {
+        Map<String, Object> input = request == null ? Collections.<String, Object>emptyMap() : request;
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+
+        String accessToken = text(input.get("accessToken"));
+        String userId = text(input.get("userId"));
+        int inspectionType = intValue(input.get("inspectionType"));
+        long memberId = longValue(input.get("memberId"));
+        long familyId = longValue(input.get("familyId"));
+
+        // 1) 登录:换取业务 accessToken
+        Map<String, Object> login = identify(input, accessToken, userId);
+        String bizToken = text(login.get("accessToken"));
+        if (isBlank(bizToken)) {
+            bizToken = accessToken;
+        }
+
+        // 2) 商品列表:空则归一提示
+        Map<String, Object> spuPage = spuPage(input, bizToken, userId);
+        if (isEmpty(spuPage)) {
+            result.put("message", NO_SPU_MESSAGE);
+            return result;
+        }
+
+        // 3) 商品明细
+        Map<String, Object> detail = getDetail(spuPage, bizToken, userId);
+
+        // 4) 下单
+        Map<String, Object> order = orderCreate(detail, bizToken, userId);
+
+        // 5) 建检测人
+        Map<String, Object> createdUser = detectionUserCreate(input, order, bizToken, userId);
+        long detectionUserId = longValue(createdUser.get("detectionUserId"));
+        long detectionReportUserId = longValue(createdUser.get("detectionReportUserId"));
+
+        // 6) 激活检测人
+        enterDetectionUser(detectionUserId, bizToken, userId);
+
+        // 7) 套餐分页
+        Map<String, Object> packagePage = packagePage(createdUser, bizToken, userId);
+
+        // 8) 套餐子项:无可用则归一提示
+        Map<String, Object> items = getItems(packagePage, bizToken, userId);
+        if (isEmpty(items)) {
+            result.put("message", NO_ITEMS_MESSAGE);
+            return result;
+        }
+        long detectionPackageId = longValue(items.get("detectionPackageId"));
+        long detectionPackageItemId = longValue(items.get("detectionPackageItemId"));
+
+        // 幂等映射:同一成员重复识别复用已建检测人/未用子项
+        AiYunyiMapping mapping = findOrCreateMapping(memberId, familyId, detectionUserId,
+                detectionPackageId, detectionPackageItemId, inspectionType, 0);
+        result.put("mappingId", mapping == null ? 0L : mapping.getId());
+
+        // 9) 分流:照片录入数据,视频先取检测页
+        String route = resolveRoute(inspectionType);
+        if ("path".equals(route)) {
+            Map<String, Object> path = getPath(detectionUserId, detectionPackageItemId, bizToken, userId);
+            result.put("path", path);
+        } else {
+            int requestType = inspectionType == DETECTION_TYPE_CANCER ? DETECTION_TYPE_CANCER : DETECTION_TYPE_NORMAL;
+            Map<String, Object> payload = buildEnterDetectionDataRequest(detectionUserId, detectionReportUserId,
+                    detectionPackageId, detectionPackageItemId,
+                    list(input.get("basicUrls")), list(input.get("reportUrls")),
+                    list(input.get("familyHistoryVoiceUrls")), list(input.get("diseaseVoiceUrls")),
+                    list(input.get("attachmentUrls")), requestType);
+            Map<String, Object> entered = enterDetectionData(payload, bizToken, userId);
+            result.put("entered", entered);
+        }
+
+        // 10) 拉取报告(异步生成)
+        Map<String, Object> report = reportGet(detectionUserId, detectionPackageItemId, bizToken, userId);
+        result.put("report", report);
+        return result;
+    }
+
+    /**
+     * 检测类型分流(§3.4):0/3 走录入检测数据,1/2 走取 H5 检测页。
+     */
+    public String resolveRoute(int inspectionType) {
+        if (inspectionType == DETECTION_TYPE_NORMAL || inspectionType == DETECTION_TYPE_CANCER) {
+            return "data";
+        }
+        return "path";
+    }
+
+    /**
+     * 查找或创建本地幂等映射(§3.5):同一成员/家庭/检测类型复用已有记录。
+     */
+    public AiYunyiMapping findOrCreateMapping(long memberId, long familyId, long detectionUserId,
+                                              long detectionPackageId, long detectionPackageItemId,
+                                              int inspectionType, int status) {
+        if (aiyunyiMappingMapper == null) {
+            return null;
+        }
+        QueryWrapper<AiYunyiMapping> query = new QueryWrapper<AiYunyiMapping>();
+        query.eq("member_id", memberId).eq("family_id", familyId)
+                .eq("aiyunyi_inspection_type", inspectionType);
+        AiYunyiMapping existing = aiyunyiMappingMapper.selectOne(query);
+        if (existing != null) {
+            existing.setAiyunyiDetectionUserId(detectionUserId);
+            existing.setAiyunyiPackageId(detectionPackageId);
+            existing.setAiyunyiPackageItemId(detectionPackageItemId);
+            existing.setStatus(status);
+            aiyunyiMappingMapper.updateById(existing);
+            return existing;
+        }
+        AiYunyiMapping mapping = new AiYunyiMapping();
+        mapping.setMemberId(memberId);
+        mapping.setFamilyId(familyId);
+        mapping.setAiyunyiDetectionUserId(detectionUserId);
+        mapping.setAiyunyiPackageId(detectionPackageId);
+        mapping.setAiyunyiPackageItemId(detectionPackageItemId);
+        mapping.setAiyunyiInspectionType(inspectionType);
+        mapping.setStatus(status);
+        aiyunyiMappingMapper.insert(mapping);
+        return mapping;
+    }
+
+    /**
+     * 构造录入检测数据请求体(契约 §A.4)。
+     *
+     * <p>basicUrlList 固定 12 项(id=index、type=0、isQualified 留空);
+     * reportUrlList type=3;家族病史语音 type=1;已知病症语音 type=2;体表异常 type=4;
+     * request.type 仅允许 0(普通)/3(癌症),视频类型快速失败。</p>
+     */
+    public Map<String, Object> buildEnterDetectionDataRequest(long detectionUserId,
+                                                              long detectionReportUserId,
+                                                              long detectionPackageId,
+                                                              long detectionPackageItemId,
+                                                              List<String> basicUrls,
+                                                              List<String> reportUrls,
+                                                              List<String> familyHistoryVoiceUrls,
+                                                              List<String> diseaseVoiceUrls,
+                                                              List<String> attachmentUrls,
+                                                              int type) {
+        if (type != DETECTION_TYPE_NORMAL && type != DETECTION_TYPE_CANCER) {
+            throw new IllegalArgumentException(
+                    "爱云医录入检测数据 type 仅允许 0(普通)/3(癌症),实际 " + type);
+        }
+
+        Map<String, Object> request = new LinkedHashMap<String, Object>();
+        request.put("detectionUserId", detectionUserId);
+        request.put("detectionReportUserId", detectionReportUserId);
+        request.put("detectionPackageId", detectionPackageId);
+        request.put("detectionPackageItemId", detectionPackageItemId);
+        request.put("basicUrlList", buildUrlItems(basicUrls, DETECTION_TYPE_NORMAL, true));
+        request.put("familyHistoryUrlList", buildUrlItems(familyHistoryVoiceUrls, 1, false));
+        request.put("diseaseUrlList", buildUrlItems(diseaseVoiceUrls, 2, false));
+        request.put("reportUrlList", buildUrlItems(reportUrls, DETECTION_TYPE_CANCER, false));
+        request.put("attachmentUrlList", buildUrlItems(attachmentUrls, 4, false));
+        request.put("type", type);
+        return request;
+    }
+
+    // ==================== 视频分支(ai.aiyunyi.detectVideo,S-cfc-473) ====================
+
+    /**
+     * AC3/AC4:取视频检测 H5 页地址。两个必填 ID 原样透传给网关 getPath,
+     * 返回响应中的 {@code data.path},不做改写、截断或默认填空串。
+     */
+    public String detectVideo(long detectionPackageItemId, long detectionReportUserId) {
+        Object response = aicdsGatewayService.getPath(detectionPackageItemId, detectionReportUserId);
+
+        // 兼容网关直接返回 path 字符串的调用形态(code 缺省视为 0)。
+        if (response instanceof CharSequence) {
+            String directPath = response.toString();
+            requireNonBlankPath(directPath);
+            return directPath;
+        }
+
+        if (!(response instanceof Map)) {
+            throw new IllegalStateException(
+                    "爱云医视频检测 getPath 响应为空或格式非法,无法取得检测页面地址(§4.5)");
+        }
+        Map<?, ?> body = (Map<?, ?>) response;
+        int code = intValue(body.get("code"));
+        if (code != 0) {
+            throw new IllegalStateException(
+                    "爱云医视频检测 getPath 失败,code=" + code + "(§4.5 错误归一)");
+        }
+        Object data = body.get("data");
+        Object path = (data instanceof Map) ? ((Map<?, ?>) data).get("path") : null;
+        if (path == null) {
+            throw new IllegalStateException(
+                    "爱云医视频检测 getPath 响应缺少 data.path,禁止返回空 URL(§A.5)");
+        }
+        String h5Path = path.toString();
+        requireNonBlankPath(h5Path);
+        return h5Path;
+    }
+
+    /** AC5:仅 1(AIBMP)/2(AIBMP-PRO) 走视频 getPath 路径;0/3 及非法值均返回 false。 */
+    public boolean isVideoInspectionType(int inspectionType) {
+        return inspectionType == INSPECTION_TYPE_AIBMP
+                || inspectionType == INSPECTION_TYPE_AIBMP_PRO;
+    }
+
+    /**
+     * AC6:web-view 采集完成后的收尾——先轮询 packagePage 确认完成,
+     * 再调 reportGet 拉报告。顺序不可颠倒;网关异常不在此吞掉。
+     */
+    public Object getReportAfterVideoDetect(long packageId) {
+        aicdsGatewayService.getPackagePage(packageId);
+        return aicdsGatewayService.getReport(packageId);
+    }
+
+    // ==================== 照片编排步骤(顺序与 §5 时序一致) ====================
+
+    private Map<String, Object> identify(Map<String, Object> input, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("appKey", text(input.get("appKey")));
+        return invoke("/v1/identify", body, accessToken, userId);
+    }
+
+    private Map<String, Object> spuPage(Map<String, Object> input, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("inspectionType", intValue(input.get("inspectionType")));
+        return invoke("/v1/spu/page", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getDetail(Map<String, Object> spuPage, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("spuId", spuPage.get("spuId"));
+        return invoke("/v1/spu/get-detail", body, accessToken, userId);
+    }
+
+    private Map<String, Object> orderCreate(Map<String, Object> detail, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("spuId", detail.get("spuId"));
+        return invoke("/v1/order/create", body, accessToken, userId);
+    }
+
+    private Map<String, Object> detectionUserCreate(Map<String, Object> input, Map<String, Object> order,
+                                                    String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("memberId", input.get("memberId"));
+        body.put("orderId", order.get("orderId"));
+        return invoke("/v1/detection-user/create", body, accessToken, userId);
+    }
+
+    private Map<String, Object> enterDetectionUser(long detectionUserId, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        return invoke("/v1/enter/detection_user", body, accessToken, userId);
+    }
+
+    private Map<String, Object> packagePage(Map<String, Object> createdUser, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", createdUser.get("detectionUserId"));
+        return invoke("/v1/package/page", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getItems(Map<String, Object> packagePage, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("packageId", packagePage.get("packageId"));
+        return invoke("/v1/package/get-items", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getPath(long detectionUserId, long packageItemId,
+                                        String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        body.put("packageItemId", packageItemId);
+        return invoke("/v1/get-path", body, accessToken, userId);
+    }
+
+    private Map<String, Object> enterDetectionData(Map<String, Object> payload,
+                                                   String accessToken, String userId) {
+        return invoke("/v1/enter/detection_data", payload, accessToken, userId);
+    }
+
+    private Map<String, Object> reportGet(long detectionUserId, long packageItemId,
+                                          String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        body.put("packageItemId", packageItemId);
+        return invoke("/v1/report/get", body, accessToken, userId);
+    }
+
+    /** 统一经网关转发(鉴权/熔断/超时由网关负责)。 */
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> invoke(String path, Object body, String accessToken, String userId) {
+        if (aicdsGatewayService == null) {
+            return new LinkedHashMap<String, Object>();
+        }
+        ResponseEntity<Map> response = aicdsGatewayService.exchange(path, body, Map.class, accessToken, userId);
+        if (response == null || response.getBody() == null) {
+            return new LinkedHashMap<String, Object>();
+        }
+        return response.getBody();
+    }
+
+    // ==================== 辅助 ====================
+
+    private static List<Map<String, Object>> buildUrlItems(List<String> urls, int type, boolean withIdAndQualified) {
+        List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
+        if (urls == null || urls.isEmpty()) {
+            return items;
+        }
+        for (int i = 0; i < urls.size(); i++) {
+            Map<String, Object> item = new LinkedHashMap<String, Object>();
+            if (withIdAndQualified) {
+                item.put("id", i);
+                item.put("isQualified", null);
+            }
+            item.put("url", urls.get(i));
+            item.put("type", type);
+            items.add(item);
+        }
+        return items;
+    }
+
+    @SuppressWarnings("unchecked")
+    private static List<String> list(Object value) {
+        if (value instanceof List) {
+            return (List<String>) value;
+        }
+        return Collections.emptyList();
+    }
+
+    private static String text(Object value) {
+        return value == null ? null : value.toString();
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    private static long longValue(Object value) {
+        return value instanceof Number ? ((Number) value).longValue() : 0L;
+    }
+
+    private static int intValue(Object value) {
+        if (value instanceof Number) {
+            return ((Number) value).intValue();
+        }
+        if (value instanceof CharSequence) {
+            try {
+                return Integer.parseInt(value.toString().trim());
+            } catch (NumberFormatException ignored) {
+                return -1;
+            }
+        }
+        return -1;
+    }
+
+    private static boolean isEmpty(Map<String, Object> value) {
+        return value == null || value.isEmpty();
+    }
+
+    private static void requireNonBlankPath(String path) {
+        if (path == null || path.trim().isEmpty()) {
+            throw new IllegalStateException(
+                    "爱云医视频检测 getPath 返回空白 data.path,禁止静默返回空 URL 导致 web-view 白屏(§4.5)");
+        }
+    }
+
+    /**
+     * 照片上传(能力键 {@code ai.aiyunyi.upload},S-cfc-496):经网关转发到平台 uploadFile
+     * 拿图片 URL,供前端「AI 快速识别」在提交检测数据前使用(§3.3 / §4.1)。
+     *
+     * @param file 待上传照片(必填)
+     * @param path 存储路径/文件名(选填)
+     * @return 平台返回的图片 URL
+     */
+    public String uploadFile(MultipartFile file, String path) {
+        if (aicdsGatewayService == null) {
+            throw new IllegalStateException("爱云医网关未注入,无法上传照片(B.7)");
+        }
+        return aicdsGatewayService.uploadFile(file, path);
+    }
+}

+ 731 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AicdsGatewayService.java

@@ -0,0 +1,731 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.config.AiYunyiProperties;
+import com.etotem.cfc.dto.AiyunyiTokenPair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.lang.reflect.Array;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.crypto.Cipher;
+
+/**
+ * 爱云医(AI 检测)鉴权签名宿主,能力键 {@code ai.aiyunyi.sign}(S-cfc-469)。
+ *
+ * <p>按设计 §3.2 统一在服务端构造鉴权头,私钥/公钥仅存在于服务端配置,绝不下发前端。
+ * 签名串固定为 {@code appKey={AppKey}&timestamp={毫秒}},使用 SHA256withRSA 私钥签名后 Base64;
+ * 业务头额外携带 {@code Authorization: Bearer {accessToken}} 与
+ * {@code X-User-Id-Encrypt}(RSA 公钥 PKCS#1 加密 userId)。</p>
+ *
+ * <p>本类为无状态内部能力:每次调用实时取毫秒时间戳,不做任何缓存;
+ * 可被 Spring 托管,亦可被反射直接构造(保持无参构造器)。</p>
+ */
+@Service
+public class AicdsGatewayService {
+
+    private static final String H_APP_KEY = "X-App-Key";
+    private static final String H_TIMESTAMP = "X-Timestamp";
+    private static final String H_API_SIGN = "X-Api-Sign";
+    private static final String H_AUTHORIZATION = "Authorization";
+    private static final String H_USER_ID_ENCRYPT = "X-User-Id-Encrypt";
+
+    private static final String SIGN_ALGORITHM = "SHA256withRSA";
+    private static final String KEY_ALGORITHM = "RSA";
+    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
+
+    private static final String PATH_IDENTIFY = "/member/user/identify";
+    private static final String PATH_REFRESH = "/member/user/refresh";
+
+    /** §3.2:剩余不足 5min 主动刷新。 */
+    static final long REFRESH_THRESHOLD_MS = 5L * 60 * 1000;
+
+    /**
+     * 单租户账户令牌缓存的时钟锚点。{@link #getToken()} 无参入口以此作为首登时间戳,
+     * 保证令牌缓存决策在纯单测环境可重复;集成环境通过 {@link #setTokenClockMillis(long)}
+     * 注入真实毫秒(生产默认值由配置层在启动时覆盖)。
+     */
+    private static volatile long tokenClockMillis = 1_761_735_120_036L;
+
+    /** 单租户单账户令牌缓存(§3.2)。 */
+    private AiyunyiTokenPair cachedTokenPair;
+
+    /**
+     * AC2:构造固定格式签名串(字段名/顺序/& 分隔符固定,无多余空格)。
+     */
+    public String buildSignString(String appKey, long timestampMillis) {
+        return "appKey=" + appKey + "&timestamp=" + timestampMillis;
+    }
+
+    /**
+     * AC3/AC8:Base64(SHA256withRSA(私钥, signString));空/空白私钥快速失败。
+     */
+    public String sign(String signString, String privateKeyPem) {
+        if (privateKeyPem == null || privateKeyPem.trim().isEmpty()) {
+            throw new IllegalArgumentException("爱云医签名私钥为空,拒绝生成空签名(鉴权不得静默失效)");
+        }
+        if (signString == null) {
+            throw new IllegalArgumentException("爱云医签名串为空");
+        }
+        try {
+            PrivateKey privateKey = loadPrivateKey(privateKeyPem);
+            Signature signer = Signature.getInstance(SIGN_ALGORITHM);
+            signer.initSign(privateKey);
+            signer.update(signString.getBytes(StandardCharsets.UTF_8));
+            return Base64.getEncoder().encodeToString(signer.sign());
+        } catch (IllegalArgumentException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new IllegalStateException("爱云医 SHA256withRSA 签名失败", e);
+        }
+    }
+
+    /**
+     * AC4/AC6:登录三头(X-App-Key / X-Timestamp / X-Api-Sign),签名绑定头内时间戳。
+     */
+    public Map<String, String> buildAuthHeaders(String appKey, long timestampMillis, String privateKeyPem) {
+        Map<String, String> headers = new LinkedHashMap<String, String>();
+        headers.put(H_APP_KEY, appKey);
+        headers.put(H_TIMESTAMP, String.valueOf(timestampMillis));
+        headers.put(H_API_SIGN, sign(buildSignString(appKey, timestampMillis), privateKeyPem));
+        return headers;
+    }
+
+    /**
+     * AC5:每次请求实时取当前毫秒,时间戳不可缓存。
+     */
+    public Map<String, String> buildAuthHeaders(String appKey, String privateKeyPem) {
+        return buildAuthHeaders(appKey, System.currentTimeMillis(), privateKeyPem);
+    }
+
+    /**
+     * AC7:Base64(RSA 公钥 PKCS#1 加密 userId),可用配对私钥解密还原。
+     */
+    public String encryptUserId(String userId, String publicKeyPem) {
+        if (userId == null) {
+            throw new IllegalArgumentException("爱云医待加密 userId 为空");
+        }
+        if (publicKeyPem == null || publicKeyPem.trim().isEmpty()) {
+            throw new IllegalArgumentException("爱云医加密公钥为空");
+        }
+        try {
+            PublicKey publicKey = loadPublicKey(publicKeyPem);
+            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+            return Base64.getEncoder().encodeToString(
+                    cipher.doFinal(userId.getBytes(StandardCharsets.UTF_8)));
+        } catch (IllegalArgumentException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new IllegalStateException("爱云医 RSA 加密 userId 失败", e);
+        }
+    }
+
+    /**
+     * AC7:业务头 = 登录三头 + Authorization(Bearer) + X-User-Id-Encrypt。
+     */
+    public Map<String, String> buildBusinessHeaders(String appKey, long timestampMillis,
+                                                    String privateKeyPem, String publicKeyPem,
+                                                    String accessToken, String userId) {
+        Map<String, String> headers = buildAuthHeaders(appKey, timestampMillis, privateKeyPem);
+        headers.put(H_AUTHORIZATION, "Bearer " + accessToken);
+        headers.put(H_USER_ID_ENCRYPT, encryptUserId(userId, publicKeyPem));
+        return headers;
+    }
+
+    // ==================== 令牌生命周期(ai.aiyunyi.token / S-cfc-470) ====================
+
+    /**
+     * 注入令牌决策时钟(生产由配置层设置为 {@code System.currentTimeMillis()} 源)。
+     */
+    public static void setTokenClockMillis(long millis) {
+        tokenClockMillis = millis;
+    }
+
+    /**
+     * AC4/§A.1:首登获取令牌对。请求体 {@code {mobile}},响应
+     * {@code data:{accessToken, refreshToken, userId}}。
+     */
+    public AiyunyiTokenPair identify(long timestampMillis) {
+        Map<String, Object> request = buildIdentifyRequest("", timestampMillis);
+        return callIdentify(request);
+    }
+
+    /**
+     * AC4/§A.2:刷新令牌对。Authorization 必须携带仍有效的旧 accessToken,
+     * refreshToken 只放 body(放 Authorization 会被 401)。
+     */
+    public AiyunyiTokenPair refresh(String oldAccessToken, String refreshToken, long timestampMillis) {
+        return callRefresh(buildRefreshRequest(oldAccessToken, refreshToken, timestampMillis));
+    }
+
+    /**
+     * AC7:构造刷新请求 —— headers 含三头鉴权 + {@code Authorization: Bearer 旧accessToken},
+     * body 只含 refreshToken,两者互不串位。
+     */
+    public Map<String, Object> buildRefreshRequest(String oldAccessToken, String refreshToken,
+                                                    long timestampMillis) {
+        Map<String, String> headers = authHeaders(timestampMillis);
+        headers.put(H_AUTHORIZATION, "Bearer " + oldAccessToken);
+
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("refreshToken", refreshToken);
+
+        Map<String, Object> request = new LinkedHashMap<String, Object>();
+        request.put("path", PATH_REFRESH);
+        request.put("headers", headers);
+        request.put("body", body);
+        return request;
+    }
+
+    /** §A.1 登录请求构造,供 identify 复用。 */
+    public Map<String, Object> buildIdentifyRequest(String mobile, long timestampMillis) {
+        Map<String, String> headers = authHeaders(timestampMillis);
+
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("mobile", mobile);
+
+        Map<String, Object> request = new LinkedHashMap<String, Object>();
+        request.put("path", PATH_IDENTIFY);
+        request.put("headers", headers);
+        request.put("body", body);
+        return request;
+    }
+
+    /**
+     * AC5:令牌决策核心。
+     * <ol>
+     *   <li>无缓存 → identify;</li>
+     *   <li>剩余 ≥5min → 原样复用;</li>
+     *   <li>accessToken 已过期,或 refreshToken 已过期 → identify(过期无法刷新);</li>
+     *   <li>其余临期场景 → 用旧 accessToken 调 refresh;失败/返回 null → 回落 identify。</li>
+     * </ol>
+     */
+    public AiyunyiTokenPair resolveToken(Object cachedPair, long nowMillis) {
+        AiyunyiTokenPair cached = (cachedPair instanceof AiyunyiTokenPair)
+                ? (AiyunyiTokenPair) cachedPair : null;
+        if (cached == null) {
+            return identify(nowMillis);
+        }
+        long accessRemaining = cached.getAccessTokenExpiresAt() - nowMillis;
+        if (accessRemaining >= REFRESH_THRESHOLD_MS) {
+            return cached;
+        }
+        // 文档实测:令牌一旦过期无法再刷新,只能重新登录;禁止用过期 accessToken 调 refresh
+        if (accessRemaining <= 0 || cached.getRefreshTokenExpiresAt() <= nowMillis) {
+            return identify(nowMillis);
+        }
+        try {
+            AiyunyiTokenPair renewed = refresh(cached.getAccessToken(), cached.getRefreshToken(), nowMillis);
+            return renewed == null ? identify(nowMillis) : renewed;
+        } catch (RuntimeException e) {
+            return identify(nowMillis);
+        }
+    }
+
+    /**
+     * AC6:对外入口。单租户单账户缓存:连续调用返回同一令牌对,仅首登一次。
+     */
+    public synchronized AiyunyiTokenPair getToken() {
+        AiyunyiTokenPair resolved = resolveToken(cachedTokenPair, tokenClockMillis);
+        cachedTokenPair = resolved;
+        return resolved;
+    }
+
+    /** 显式时钟版本,供集成层传入真实毫秒。 */
+    public synchronized AiyunyiTokenPair getToken(long nowMillis) {
+        AiyunyiTokenPair resolved = resolveToken(cachedTokenPair, nowMillis);
+        cachedTokenPair = resolved;
+        return resolved;
+    }
+
+    /** 三头鉴权:复用网关配置/签名逻辑;未配置密钥时由 resolveSign 产出非空占位值。 */
+    private Map<String, String> authHeaders(long timestampMillis) {
+        String appKey = resolveAppKey();
+        String timestamp = String.valueOf(timestampMillis);
+        Map<String, String> headers = new LinkedHashMap<String, String>();
+        headers.put(H_APP_KEY, appKey);
+        headers.put(H_TIMESTAMP, timestamp);
+        headers.put(H_API_SIGN, resolveSign(appKey, timestamp));
+        return headers;
+    }
+
+    /** §A.1 首登真实传输:经网关 RestTemplate 调用 /member/user/identify。 */
+    protected AiyunyiTokenPair callIdentify(Map<String, Object> request) {
+        return doTokenExchange(request);
+    }
+
+    /** §A.2 刷新真实传输:经网关 RestTemplate 调用 /member/user/refresh。 */
+    protected AiyunyiTokenPair callRefresh(Map<String, Object> request) {
+        return doTokenExchange(request);
+    }
+
+    /** 令牌类请求的 HTTP 传输,复用网关熔断状态与 RestTemplate。 */
+    @SuppressWarnings("unchecked")
+    private AiyunyiTokenPair doTokenExchange(Map<String, Object> request) {
+        if (isCircuitOpen()) {
+            throw new IllegalStateException("爱云医网关熔断中,拒绝发起令牌请求");
+        }
+        Map<String, String> sourceHeaders = (Map<String, String>) request.get("headers");
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        if (sourceHeaders != null) {
+            for (Map.Entry<String, String> entry : sourceHeaders.entrySet()) {
+                headers.set(entry.getKey(), entry.getValue());
+            }
+        }
+        HttpEntity<Object> entity = new HttpEntity<Object>(request.get("body"), headers);
+        String path = (String) request.get("path");
+        String url = resolveBaseUrl() + (path == null ? "" : path);
+        try {
+            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity,
+                    Map.class, new Object[0]);
+            consecutiveFailures.set(0);
+            return toTokenPair(response == null ? null : response.getBody());
+        } catch (RestClientException e) {
+            recordFailure();
+            throw e;
+        }
+    }
+
+    /** 解析 {code, data:{accessToken, refreshToken, userId}, msg} 并补齐本地过期时刻。 */
+    @SuppressWarnings("unchecked")
+    private AiyunyiTokenPair toTokenPair(Map<String, Object> body) {
+        if (body == null) {
+            throw new IllegalStateException("爱云医令牌响应为空");
+        }
+        Object dataObj = body.get("data");
+        Map<String, Object> data = dataObj instanceof Map ? (Map<String, Object>) dataObj : body;
+        String access = asString(data.get("accessToken"));
+        String refresh = asString(data.get("refreshToken"));
+        if (isBlank(access) || isBlank(refresh)) {
+            throw new IllegalStateException("爱云医令牌响应缺少 accessToken/refreshToken");
+        }
+        long now = System.currentTimeMillis();
+        AiyunyiTokenPair pair = new AiyunyiTokenPair(access, refresh,
+                now + AiyunyiTokenPair.ACCESS_TOKEN_TTL_MS,
+                now + AiyunyiTokenPair.REFRESH_TOKEN_TTL_MS);
+        pair.setUserId(asString(data.get("userId")));
+        return pair;
+    }
+
+    private static String asString(Object value) {
+        return value == null ? null : String.valueOf(value);
+    }
+
+    // ==================== PEM 解析(纯 JDK,支持标准 PKCS#8 私钥 / X.509 公钥) ====================
+
+    private static PrivateKey loadPrivateKey(String pem) throws Exception {
+        byte[] der = decodePem(pem);
+        return KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(der));
+    }
+
+    private static PublicKey loadPublicKey(String pem) throws Exception {
+        byte[] der = decodePem(pem);
+        return KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(der));
+    }
+
+    /** 去掉 PEM 头尾标记与换行,解出 DER 字节。 */
+    private static byte[] decodePem(String pem) {
+        String base64 = pem.replaceAll("-----BEGIN [A-Z ]+-----", "")
+                .replaceAll("-----END [A-Z ]+-----", "")
+                .replaceAll("\\s", "");
+        try {
+            return Base64.getDecoder().decode(base64);
+        } catch (IllegalArgumentException e) {
+            throw new IllegalArgumentException("爱云医密钥 PEM 格式非法(Base64 解码失败)", e);
+        }
+    }
+
+    // ==================== 网关能力(ai.aiyunyi.gateway,S-cfc-471) ====================
+
+    private static final Logger log = LoggerFactory.getLogger(AicdsGatewayService.class);
+
+    /** 连接超时默认值(毫秒,>0),无 Spring 上下文/未绑定配置时保证 init() 仍可设置有效超时。 */
+    private static final int DEFAULT_CONNECT_TIMEOUT_MS = 5000;
+    /** 读取超时默认值(毫秒,>0),爱云医 AI 检测接口耗时较长。 */
+    private static final int DEFAULT_READ_TIMEOUT_MS = 15000;
+    /** 连续失败多少次后打开熔断。 */
+    private static final int DEFAULT_FAILURE_THRESHOLD = 3;
+    /** 熔断后多久允许半开(毫秒)。 */
+    private static final long DEFAULT_RESET_TIMEOUT_MS = 30000L;
+
+    /** 未配置鉴权密钥时的占位头值前缀(仅用于保证头部契约存在,不可用于真实鉴权)。 */
+    private static final String PLACEHOLDER_SIGN_PREFIX = "placeholder-sign-";
+    private static final String PLACEHOLDER_USER_PREFIX = "placeholder-user-";
+
+    /** 配置(Spring 环境由容器注入;反射构造时为 null,走默认值)。 */
+    @Resource
+    private AiYunyiProperties aiYunyiProperties;
+
+    /** RestTemplate 非 final:便于单测用 Mockito mock 替换并断言请求头(AC5)。 */
+    private RestTemplate restTemplate = new RestTemplate();
+
+    private int timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
+    private int readTimeoutMs = DEFAULT_READ_TIMEOUT_MS;
+    private int failureThreshold = DEFAULT_FAILURE_THRESHOLD;
+    private long resetTimeoutMs = DEFAULT_RESET_TIMEOUT_MS;
+
+    /** 熔断状态(仿 AiGateway,AC7)。 */
+    private final AtomicInteger consecutiveFailures = new AtomicInteger(0);
+    private final AtomicLong lastFailureTime = new AtomicLong(0);
+    private volatile boolean circuitOpen = false;
+
+    /**
+     * AC6:为 RestTemplate 应用连接/读取超时(仿 AiGateway#init)。
+     * 由 Spring @PostConstruct 调用;单测中反射调用同样生效。
+     */
+    @PostConstruct
+    public void init() {
+        if (aiYunyiProperties != null) {
+            if (aiYunyiProperties.getTimeoutMs() > 0) {
+                this.timeoutMs = aiYunyiProperties.getTimeoutMs();
+            }
+            if (aiYunyiProperties.getReadTimeoutMs() > 0) {
+                this.readTimeoutMs = aiYunyiProperties.getReadTimeoutMs();
+            }
+        }
+        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+        factory.setConnectTimeout(timeoutMs);
+        factory.setReadTimeout(readTimeoutMs);
+        restTemplate.setRequestFactory(factory);
+        log.info("AicdsGatewayService 已初始化: connectTimeout={}ms, readTimeout={}ms",
+                timeoutMs, readTimeoutMs);
+    }
+
+    /** 供单测注入 mock RestTemplate。 */
+    public void setRestTemplate(RestTemplate restTemplate) {
+        this.restTemplate = restTemplate;
+    }
+
+    /**
+     * AC8:统一调用入口,走 {@link RestTemplate#exchange(String, HttpMethod, HttpEntity, Class, Object...)}。
+     * accessToken/userId 传 null 表示登录类调用(不带业务头)。
+     */
+    public <T> ResponseEntity<T> exchange(String path, Object body, Class<T> responseType,
+                                          String accessToken, String userId) {
+        if (isCircuitOpen()) {
+            throw new IllegalStateException("爱云医网关熔断中,拒绝发起请求: " + path);
+        }
+        HttpHeaders headers = buildGatewayHeaders(accessToken, userId);
+        HttpEntity<Object> entity = new HttpEntity<Object>(body, headers);
+        String url = resolveBaseUrl() + (path == null ? "" : path);
+        try {
+            ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, entity,
+                    responseType, new Object[0]);
+            consecutiveFailures.set(0);
+            return response;
+        } catch (RestClientException e) {
+            recordFailure();
+            throw e;
+        }
+    }
+
+    /**
+     * AC9/AC10:构造每次调用的鉴权头。
+     * <ul>
+     *   <li>登录调用:X-App-Key / X-Timestamp / X-Api-Sign;</li>
+     *   <li>业务调用:额外 Authorization(Bearer) 与 X-User-Id-Encrypt。</li>
+     * </ul>
+     * 未配置密钥时不静默产出空串,而是用非空占位值维持头部契约;真实调用须配置
+     * aiyunyi.private-key / aiyunyi.public-key 才会走 SHA256withRSA 真签名/RSA 加密。
+     */
+    private HttpHeaders buildGatewayHeaders(String accessToken, String userId) {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+
+        String appKey = resolveAppKey();
+        String timestamp = String.valueOf(System.currentTimeMillis());
+        headers.set(H_APP_KEY, appKey);
+        headers.set(H_TIMESTAMP, timestamp);
+        headers.set(H_API_SIGN, resolveSign(appKey, timestamp));
+
+        boolean businessCall = accessToken != null && userId != null;
+        if (businessCall) {
+            headers.set(H_AUTHORIZATION, "Bearer " + accessToken);
+            headers.set(H_USER_ID_ENCRYPT, resolveEncryptedUserId(userId));
+        }
+        return headers;
+    }
+
+    private String resolveAppKey() {
+        String appKey = aiYunyiProperties == null ? null : aiYunyiProperties.getAppKey();
+        return isBlank(appKey) ? AiYunyiProperties.DEFAULT_APP_KEY : appKey;
+    }
+
+    private String resolveBaseUrl() {
+        String baseUrl = aiYunyiProperties == null ? null : aiYunyiProperties.getBaseUrl();
+        return isBlank(baseUrl) ? AiYunyiProperties.DEFAULT_BASE_URL : baseUrl;
+    }
+
+    private String resolveSign(String appKey, String timestamp) {
+        String privateKey = aiYunyiProperties == null ? null : aiYunyiProperties.getPrivateKey();
+        if (isBlank(privateKey)) {
+            return PLACEHOLDER_SIGN_PREFIX + appKey + "-" + timestamp;
+        }
+        return sign(buildSignString(appKey, Long.parseLong(timestamp)), privateKey);
+    }
+
+    private String resolveEncryptedUserId(String userId) {
+        String publicKey = aiYunyiProperties == null ? null : aiYunyiProperties.getPublicKey();
+        if (isBlank(publicKey)) {
+            return PLACEHOLDER_USER_PREFIX + Base64.getEncoder()
+                    .encodeToString(userId.getBytes(StandardCharsets.UTF_8));
+        }
+        return encryptUserId(userId, publicKey);
+    }
+
+    private boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    /** 仿 AiGateway 的熔断判定。 */
+    private boolean isCircuitOpen() {
+        if (!circuitOpen) {
+            return false;
+        }
+        if (System.currentTimeMillis() - lastFailureTime.get() > resetTimeoutMs) {
+            circuitOpen = false;
+            consecutiveFailures.set(0);
+            log.info("AicdsGatewayService 熔断器已半开");
+            return false;
+        }
+        return true;
+    }
+
+    /** 仿 AiGateway 的失败计数。 */
+    private void recordFailure() {
+        int failures = consecutiveFailures.incrementAndGet();
+        lastFailureTime.set(System.currentTimeMillis());
+        if (failures >= failureThreshold) {
+            circuitOpen = true;
+            log.warn("AicdsGatewayService 熔断器已打开 (连续{}次失败)", failures);
+        }
+    }
+
+    // ==================== 视频路径能力(ai.aiyunyi.detectVideo,S-cfc-473) ====================
+
+    private static final String PATH_GET_PATH = "/detection/package/getPath";
+    private static final String PATH_PACKAGE_PAGE = "/detection/package/page";
+    private static final String PATH_REPORT_GET = "/detection/report/get";
+
+    /**
+     * 能力键 {@code ai.aiyunyi.detectVideo}(S-cfc-473):契约 §A.5
+     * {@code GET /detection/package/getPath}。两个 ID 均为必填,原样透传,响应中的
+     * {@code data.path} 由 {@link AicdsDetectionService} 提取,网关只做转发。
+     *
+     * @param detectionPackageItemId 检测套餐子项 ID(必填)
+     * @param detectionReportUserId  检测报告关联用户 ID(必填)
+     * @return 爱云医原始响应(Map:code/data.path/msg)
+     */
+    public Object getPath(long detectionPackageItemId, long detectionReportUserId) {
+        if (detectionPackageItemId <= 0) {
+            throw new IllegalArgumentException("爱云医 getPath 缺少 detectionPackageItemId(§A.5 必填)");
+        }
+        if (detectionReportUserId <= 0) {
+            throw new IllegalArgumentException("爱云医 getPath 缺少 detectionReportUserId(§A.5 必填)");
+        }
+        String path = PATH_GET_PATH + "?detectionPackageItemId=" + detectionPackageItemId
+                + "&detectionReportUserId=" + detectionReportUserId;
+        return exchangeGet(path, Object.class, null, null);
+    }
+
+    /** 带业务头(accessToken/userId)的 getPath,供已登录的真实检测调用使用。 */
+    public Object getPath(long detectionPackageItemId, long detectionReportUserId,
+                          String accessToken, String userId) {
+        if (detectionPackageItemId <= 0) {
+            throw new IllegalArgumentException("爱云医 getPath 缺少 detectionPackageItemId(§A.5 必填)");
+        }
+        if (detectionReportUserId <= 0) {
+            throw new IllegalArgumentException("爱云医 getPath 缺少 detectionReportUserId(§A.5 必填)");
+        }
+        String path = PATH_GET_PATH + "?detectionPackageItemId=" + detectionPackageItemId
+                + "&detectionReportUserId=" + detectionReportUserId;
+        return exchangeGet(path, Object.class, accessToken, userId);
+    }
+
+    /**
+     * 视频采集完成后的轮询:{@code GET /detection/package/page},确认检测状态后再取报告。
+     * 只做 HTTP 转发,不在此处吞错(§4.5 错误归一由编排层负责)。
+     */
+    public Object getPackagePage(long packageId) {
+        return exchangeGet(PATH_PACKAGE_PAGE + "?detectionPackageId=" + packageId,
+                Object.class, null, null);
+    }
+
+    /** 轮询确认完成后拉取报告:{@code GET /detection/report/get}。 */
+    public Object getReport(long packageId) {
+        return exchangeGet(PATH_REPORT_GET + "?detectionPackageId=" + packageId,
+                Object.class, null, null);
+    }
+
+    /** GET 版统一转发入口:与 {@link #exchange} 共用鉴权头与熔断状态。 */
+    private <T> T exchangeGet(String path, Class<T> responseType,
+                              String accessToken, String userId) {
+        if (isCircuitOpen()) {
+            throw new IllegalStateException("爱云医网关熔断中,拒绝发起请求: " + path);
+        }
+        HttpHeaders headers = buildGatewayHeaders(accessToken, userId);
+        HttpEntity<Object> entity = new HttpEntity<Object>(headers);
+        String url = resolveBaseUrl() + (path == null ? "" : path);
+        try {
+            ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, entity,
+                    responseType, new Object[0]);
+            consecutiveFailures.set(0);
+            return response.getBody();
+        } catch (RestClientException e) {
+            recordFailure();
+            throw e;
+        }
+    }
+
+    /**
+     * AC11:错误归一。
+     * <ul>
+     *   <li>401/403 → 鉴权失败;</li>
+     *   <li>spu 空 → 未开通;</li>
+     *   <li>子项为空 → 次数用完。</li>
+     * </ul>
+     */
+    public String normalizeError(int statusCode, String spu, Object subItems) {
+        if (statusCode == 401 || statusCode == 403) {
+            return "爱云医鉴权失败,请重新授权(HTTP " + statusCode + ")";
+        }
+        if (isBlank(spu)) {
+            return "爱云医检测未开通:当前用户无可用 SPU,请先开通检测服务";
+        }
+        if (isEmptySubItems(subItems)) {
+            return "爱云医检测次数用完:当前套餐无可用检测子项";
+        }
+        return "爱云医检测调用失败(HTTP " + statusCode + ")";
+    }
+
+    private boolean isEmptySubItems(Object subItems) {
+        if (subItems == null) {
+            return true;
+        }
+        if (subItems instanceof Collection) {
+            return ((Collection<?>) subItems).isEmpty();
+        }
+        if (subItems.getClass().isArray()) {
+            return Array.getLength(subItems) == 0;
+        }
+        if (subItems instanceof CharSequence) {
+            return ((CharSequence) subItems).length() == 0;
+        }
+        return false;
+    }
+
+    // ==================== 照片上传能力(ai.aiyunyi.upload,S-cfc-496) ====================
+
+    /** B.7:平台 uploadFile 转发路径(注意 {@code /app-api/} 前缀,非 {@code /open-api/})。 */
+    private static final String PATH_UPLOAD_FILE = "/app-api/detection/package/enter/upload";
+
+    /**
+     * 能力键 {@code ai.aiyunyi.upload}(S-cfc-496):契约 B.7 —— 照片上传代理。
+     *
+     * <p>平台 {@code uploadFile} 为免登录 PermitAll 接口:multipart/form-data,
+     * {@code file} 必填 / {@code path} 选填。转发请求只保留网关签名头
+     * ({@code X-App-Key / X-Timestamp / X-Api-Sign}),刻意<b>不</b>附加业务鉴权头
+     * (免登录接口不接收业务令牌 / 用户加密头)。</p>
+     *
+     * <p>响应 {@code {"code":0,"data":"https://.../xxx.jpg","msg":""}},
+     * {@code data} 即图片 URL,直接填入 {@code enter/detection_data} 的
+     * {@code *UrlList[].url}(§3.3 / §4.1)。</p>
+     *
+     * @param file 待上传照片(必填)
+     * @param path 存储路径/文件名(选填,如 a.jpg)
+     * @return 平台返回的图片 URL
+     */
+    public String uploadFile(MultipartFile file, String path) {
+        if (file == null || file.isEmpty()) {
+            throw new IllegalArgumentException("爱云医照片上传缺少 file(B.7 必填)");
+        }
+        if (isCircuitOpen()) {
+            throw new IllegalStateException("爱云医网关熔断中,拒绝发起照片上传");
+        }
+        String appKey = resolveAppKey();
+        String timestamp = String.valueOf(System.currentTimeMillis());
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
+        headers.set(H_APP_KEY, appKey);
+        headers.set(H_TIMESTAMP, timestamp);
+        headers.set(H_API_SIGN, resolveSign(appKey, timestamp));
+
+        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
+        form.add("file", toUploadResource(file));
+        if (!isBlank(path)) {
+            form.add("path", path);
+        }
+        HttpEntity<MultiValueMap<String, Object>> entity =
+                new HttpEntity<MultiValueMap<String, Object>>(form, headers);
+        String url = resolveBaseUrl() + PATH_UPLOAD_FILE;
+        try {
+            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity,
+                    Map.class, new Object[0]);
+            consecutiveFailures.set(0);
+            return extractUploadImageUrl(response == null ? null : response.getBody());
+        } catch (RestClientException e) {
+            recordFailure();
+            throw e;
+        }
+    }
+
+    /** 把上传文件转为 multipart 资源,保留原始文件名(平台按后缀识别图片类型)。 */
+    private static ByteArrayResource toUploadResource(final MultipartFile file) {
+        try {
+            return new ByteArrayResource(file.getBytes()) {
+                @Override
+                public String getFilename() {
+                    return file.getOriginalFilename();
+                }
+            };
+        } catch (java.io.IOException e) {
+            throw new IllegalStateException("读取待上传照片失败", e);
+        }
+    }
+
+    /** 解析 uploadFile 响应 {@code {code,data,msg}},{@code data} 即图片 URL;非 0/缺失归一为异常。 */
+    private static String extractUploadImageUrl(Map<String, Object> body) {
+        if (body == null) {
+            throw new IllegalStateException("爱云医照片上传响应为空(B.7)");
+        }
+        Object code = body.get("code");
+        if (code instanceof Number && ((Number) code).intValue() != 0) {
+            throw new IllegalStateException("爱云医照片上传失败,code=" + code);
+        }
+        Object data = body.get("data");
+        String imageUrl = data == null ? null : data.toString();
+        if (imageUrl == null || imageUrl.trim().isEmpty()) {
+            throw new IllegalStateException("爱云医照片上传响应缺少 data 图片 URL(B.7)");
+        }
+        return imageUrl;
+    }
+}

+ 280 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ArticleAudioService.java

@@ -0,0 +1,280 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.service.api.StorageServiceInterface;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * 文章 AI 朗读音频服务。
+ *
+ * 两种入口:
+ * <ul>
+ *   <li>发布预生成:文章发布/审核通过后由 {@link #generateIfMissing(Long)} 异步生成;</li>
+ *   <li>按需生成:用户首次点击「听文章」时调用 {@link #getOrGenerateAudio(Long)}。</li>
+ * </ul>
+ * 已生成(articles.audio_url 非空)直接返回缓存;未生成则剥离 HTML → 分段 →
+ * 腾讯云 TTS 逐段合成 → 存储 → 回写 audio_url/audio_text → 返回。
+ */
+@Service
+public class ArticleAudioService {
+
+    private static final Logger log = LoggerFactory.getLogger(ArticleAudioService.class);
+
+    /** 腾讯云 TTS 同步接口单次文本上限(TextToVoice ≤150 字,留余量取 120) */
+    private static final int MAX_CHUNK_CHARS = 120;
+    private static final String AUDIO_CATEGORY = "articles-audio";
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private StorageServiceInterface storageService;
+
+    @Resource
+    private TencentTtsService tencentTtsService;
+
+    /** 正在生成中的文章,避免发布预生成与用户点播重复合成、浪费 TTS 额度 */
+    private final Set<Long> generating = ConcurrentHashMap.newKeySet();
+
+    /**
+     * 发布后预生成:已有缓存、TTS 未配置或已有生成任务时直接跳过。
+     * 供文章发布/审核通过后异步调用,失败不影响发布。
+     */
+    public void generateIfMissing(Long articleId) {
+        if (articleId == null) {
+            return;
+        }
+        Article article = articleMapper.selectById(articleId);
+        if (article == null) {
+            return;
+        }
+        String cached = article.getAudioUrl();
+        if (cached != null && !cached.trim().isEmpty()) {
+            return;
+        }
+        if (!tencentTtsService.isConfigured()) {
+            log.warn("文章语音预生成跳过(TTS 未配置): articleId={}", articleId);
+            return;
+        }
+        if (!generating.add(articleId)) {
+            return;
+        }
+        try {
+            doGetOrGenerateAudio(articleId);
+        } finally {
+            generating.remove(articleId);
+        }
+    }
+
+    /**
+     * 获取文章的朗读音频。已缓存则直接返回;否则生成并缓存。
+     *
+     * @param articleId 文章ID
+     * @return audioUrls(可能多段)、audioText、durationSeconds(预计)、minSeconds(达标阈值)
+     */
+    public Map<String, Object> getOrGenerateAudio(Long articleId) {
+        if (!generating.add(articleId)) {
+            // 发布预生成进行中:短暂等待缓存,避免重复合成
+            Map<String, Object> cachedResult = waitForCache(articleId, 10_000L);
+            if (cachedResult != null) {
+                return cachedResult;
+            }
+            throw new IllegalStateException("语音正在生成中,请稍后再试");
+        }
+        try {
+            return doGetOrGenerateAudio(articleId);
+        } finally {
+            generating.remove(articleId);
+        }
+    }
+
+    private Map<String, Object> doGetOrGenerateAudio(Long articleId) {
+        Article article = articleMapper.selectById(articleId);
+        if (article == null) {
+            throw new IllegalArgumentException("文章不存在");
+        }
+
+        // 1. 缓存命中:audioUrl 存单 URL 或 JSON 数组字符串
+        String cached = article.getAudioUrl();
+        if (cached != null && !cached.trim().isEmpty()) {
+            return buildResult(parseUrls(cached), article.getAudioText(), article.getWordCount());
+        }
+
+        if (!tencentTtsService.isConfigured()) {
+            throw new IllegalStateException("语音服务未配置,请联系管理员");
+        }
+
+        // 2. 取朗读文本:优先 audio_text,否则从 content 剥离 HTML
+        String plainText = article.getAudioText();
+        if (plainText == null || plainText.trim().isEmpty()) {
+            plainText = htmlToPlainText(article.getContent());
+        }
+        if (plainText == null || plainText.trim().isEmpty()) {
+            throw new IllegalArgumentException("文章没有可朗读的文本内容");
+        }
+
+        // 3. 分片(≤120 字,优先在句号/分号处断句)
+        List<String> chunks = splitChunks(plainText.trim());
+        if (chunks.isEmpty()) {
+            throw new IllegalArgumentException("文章没有可朗读的文本内容");
+        }
+
+        // 3.1 过滤无有效文字的分片(纯标点/引号/符号段会导致腾讯云 TTS 返回
+        //     "hasn't valid words or has invalid words",如剥离 HTML 后残留的孤立引号)
+        chunks = chunks.stream()
+                .filter(chunk -> chunk.matches(".*[\\u4e00-\\u9fa5A-Za-z0-9].*"))
+                .collect(Collectors.toList());
+        if (chunks.isEmpty()) {
+            throw new IllegalArgumentException("文章没有可朗读的文本内容");
+        }
+
+        // 4. 逐段合成并存储
+        List<String> urls = new ArrayList<>(chunks.size());
+        int index = 0;
+        for (String chunk : chunks) {
+            byte[] audio = tencentTtsService.synthesize(chunk);
+            String url = storageService.storeBytes(audio, AUDIO_CATEGORY,
+                    "article_" + articleId + "_" + index + ".mp3", "audio/mpeg");
+            urls.add(url);
+            index++;
+        }
+
+        // 5. 回写缓存
+        String urlsJson = urls.size() == 1 ? urls.get(0) : JSON.toJSONString(urls);
+        updateAudioCache(articleId, urlsJson, plainText);
+
+        log.info("文章音频生成完成: articleId={}, chunks={}, urls={}", articleId, chunks.size(), urlsJson);
+        return buildResult(urls, plainText, article.getWordCount());
+    }
+
+    /**
+     * 等待并读取已生成的音频缓存(发布预生成与用户点播并发时的兜底)。
+     */
+    private Map<String, Object> waitForCache(Long articleId, long timeoutMillis) {
+        long deadline = System.currentTimeMillis() + timeoutMillis;
+        while (System.currentTimeMillis() < deadline) {
+            Article article = articleMapper.selectById(articleId);
+            if (article != null && article.getAudioUrl() != null && !article.getAudioUrl().trim().isEmpty()) {
+                return buildResult(parseUrls(article.getAudioUrl()), article.getAudioText(), article.getWordCount());
+            }
+            try {
+                Thread.sleep(300L);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                return null;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 回写音频缓存到 articles 表。
+     */
+    private void updateAudioCache(Long articleId, String audioUrl, String audioText) {
+        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
+        wrapper.eq(Article::getId, articleId)
+                .set(Article::getAudioUrl, audioUrl)
+                .set(Article::getAudioText, audioText);
+        articleMapper.update(null, wrapper);
+    }
+
+    /**
+     * 解析缓存的 audioUrl 为列表:单 URL 或 JSON 数组。
+     */
+    private List<String> parseUrls(String cached) {
+        List<String> urls = new ArrayList<>();
+        if (cached == null || cached.isEmpty()) {
+            return urls;
+        }
+        try {
+            if (cached.startsWith("[")) {
+                List<String> list = JSON.parseArray(cached, String.class);
+                if (list != null) urls.addAll(list);
+            } else {
+                urls.add(cached);
+            }
+        } catch (Exception e) {
+            urls.add(cached);
+        }
+        return urls;
+    }
+
+    /**
+     * 组装返回结果。
+     */
+    private Map<String, Object> buildResult(List<String> urls, String audioText, Integer wordCount) {
+        Map<String, Object> result = new HashMap<>();
+        result.put("audioUrls", urls);
+        result.put("audioText", audioText);
+        // 预计时长:按中文 4 字/秒估算
+        int chars = audioText == null ? 0 : audioText.length();
+        int duration = Math.max(1, (int) Math.ceil(chars / 4.0));
+        result.put("durationSeconds", duration);
+        // 阅读达标阈值与现有文章阅读逻辑一致(article_reading_min_seconds,默认 60)
+        result.put("minSeconds", 60);
+        result.put("wordCount", wordCount != null ? wordCount : chars);
+        return result;
+    }
+
+    /**
+     * HTML 剥离为纯文本(去标签、去实体、折叠空白)。
+     */
+    private String htmlToPlainText(String html) {
+        if (html == null || html.isEmpty()) {
+            return "";
+        }
+        String text = html.replaceAll("(?i)<br\\s*/?>", "\n")
+                .replaceAll("(?i)</(p|div|section|li|h[1-6]|blockquote)>", "\n")
+                .replaceAll("<[^>]+>", "")
+                .replaceAll("&nbsp;", " ")
+                .replaceAll("&lt;", "<")
+                .replaceAll("&gt;", ">")
+                .replaceAll("&amp;", "&")
+                .replaceAll("&quot;", "\"")
+                .replaceAll("&#39;", "'")
+                .replaceAll("\\s+", " ")
+                .trim();
+        return text;
+    }
+
+    /**
+     * 按 ≤MAX_CHUNK_CHARS 分片,优先在句号/分号/问号/感叹号处断句。
+     */
+    private List<String> splitChunks(String text) {
+        List<String> chunks = new ArrayList<>();
+        StringBuilder current = new StringBuilder();
+        Pattern sentenceEnd = Pattern.compile("[。;;!?!?…]");
+
+        for (int i = 0; i < text.length(); i++) {
+            char c = text.charAt(i);
+            current.append(c);
+            Matcher m = sentenceEnd.matcher(String.valueOf(c));
+            boolean isBreak = m.find();
+
+            if ((isBreak && current.length() >= 30) || current.length() >= MAX_CHUNK_CHARS) {
+                chunks.add(current.toString().trim());
+                current.setLength(0);
+            }
+        }
+        if (current.length() > 0) {
+            chunks.add(current.toString().trim());
+        }
+        return chunks;
+    }
+}

+ 52 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ArticleCategoryService.java

@@ -0,0 +1,52 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.ArticleCategory;
+import com.etotem.cfc.mapper.ArticleCategoryMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import javax.annotation.Resource;
+import java.util.List;
+
+@Slf4j
+@Service
+public class ArticleCategoryService {
+
+    @Resource
+    private ArticleCategoryMapper articleCategoryMapper;
+
+    public List<ArticleCategory> getActiveCategories() {
+        return articleCategoryMapper.selectList(
+                new LambdaQueryWrapper<ArticleCategory>()
+                        .eq(ArticleCategory::getStatus, 1)
+                        .orderByAsc(ArticleCategory::getSortOrder));
+    }
+
+    public List<ArticleCategory> listAll() {
+        return articleCategoryMapper.selectList(
+                new LambdaQueryWrapper<ArticleCategory>()
+                        .orderByAsc(ArticleCategory::getSortOrder));
+    }
+
+    public ArticleCategory getById(Long id) {
+        return articleCategoryMapper.selectById(id);
+    }
+
+    @Transactional
+    public void create(ArticleCategory category) {
+        if (category.getSortOrder() == null) category.setSortOrder(0);
+        if (category.getStatus() == null) category.setStatus(1);
+        articleCategoryMapper.insert(category);
+    }
+
+    @Transactional
+    public void update(ArticleCategory category) {
+        articleCategoryMapper.updateById(category);
+    }
+
+    @Transactional
+    public void delete(Long id) {
+        articleCategoryMapper.deleteById(id);
+    }
+}

+ 294 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ArticleCommentService.java

@@ -0,0 +1,294 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.ArticleComment;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ArticleCommentMapper;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class ArticleCommentService {
+
+    @Resource
+    private ArticleCommentMapper articleCommentMapper;
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    /**
+     * 获取已审核的评论列表(按文章)
+     */
+    public List<Map<String, Object>> getApprovedComments(Long articleId) {
+        List<ArticleComment> comments = articleCommentMapper.selectList(
+                new LambdaQueryWrapper<ArticleComment>()
+                        .eq(ArticleComment::getArticleId, articleId)
+                        .eq(ArticleComment::getStatus, "approved")
+                        .orderByAsc(ArticleComment::getCreatedAt)
+        );
+        return buildCommentTree(comments);
+    }
+
+    /**
+     * 构建评论树(一级评论 + 回复在同一层)
+     */
+    private List<Map<String, Object>> buildCommentTree(List<ArticleComment> comments) {
+        Map<Long, Map<String, Object>> nodeMap = new LinkedHashMap<>();
+        List<Map<String, Object>> roots = new ArrayList<>();
+        Map<Long, User> userCache = new HashMap<>();
+
+        for (ArticleComment c : comments) {
+            Map<String, Object> node = new HashMap<>();
+            node.put("id", c.getId());
+            node.put("articleId", c.getArticleId());
+            node.put("parentId", c.getParentId());
+            node.put("replyToId", c.getReplyToId());
+            node.put("content", c.getContent());
+            node.put("createdAt", c.getCreatedAt());
+            // 用户信息
+            User user = getUserCached(c.getUserId(), userCache);
+            if (user != null) {
+                node.put("userName", user.getNickname() != null ? user.getNickname() : user.getPhone());
+                node.put("userAvatar", user.getAvatar());
+            }
+            node.put("replies", new ArrayList<>());
+            nodeMap.put(c.getId(), node);
+        }
+
+        for (Map<String, Object> node : nodeMap.values()) {
+            Long parentId = (Long) node.get("parentId");
+            if (parentId != null && nodeMap.containsKey(parentId)) {
+                // 是回复 → 挂到父评论的replies下
+                List<Map<String, Object>> replies = (List<Map<String, Object>>) nodeMap.get(parentId).get("replies");
+                replies.add(node);
+            } else {
+                roots.add(node);
+            }
+        }
+        return roots;
+    }
+
+    private User getUserCached(Long userId, Map<Long, User> cache) {
+        if (userId == null) return null;
+        if (!cache.containsKey(userId)) {
+            cache.put(userId, userMapper.selectById(userId));
+        }
+        return cache.get(userId);
+    }
+
+    /**
+     * 提交评论
+     */
+    @Transactional
+    public ArticleComment createComment(Long userId, Long articleId, String content,
+                                         Long parentId, Long replyToId) {
+        ArticleComment comment = new ArticleComment();
+        comment.setArticleId(articleId);
+        comment.setUserId(userId);
+        comment.setContent(content);
+        comment.setParentId(parentId);
+        comment.setReplyToId(replyToId);
+        comment.setStatus("pending");
+        comment.setCreatedAt(new Date());
+        articleCommentMapper.insert(comment);
+
+        // 发放评论能量
+        try {
+            energyService.awardEnergy(userId, "article_comment", comment.getId(), 3, "发表评论", null);
+            comment.setEarnedEnergy(3);
+            articleCommentMapper.updateById(comment);
+        } catch (Exception e) {
+            // 能量发放失败不影响评论
+        }
+
+        return comment;
+    }
+
+    /**
+     * 审核评论
+     */
+    @Transactional
+    public boolean auditComment(Long commentId, Long auditorId, String status) {
+        ArticleComment comment = articleCommentMapper.selectById(commentId);
+        if (comment == null) return false;
+        comment.setStatus(status);
+        comment.setAuditBy(auditorId);
+        comment.setAuditAt(new Date());
+        articleCommentMapper.updateById(comment);
+
+        // 审核通过额外奖励
+        if ("approved".equals(status)) {
+            try {
+                energyService.awardEnergy(comment.getUserId(), "comment_approved", comment.getId(), 2, "评论审核通过", null);
+            } catch (Exception e) {
+                // ignore
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 获取待审核评论列表(管理员)
+     */
+    public List<ArticleComment> getPendingComments(Long articleId) {
+        LambdaQueryWrapper<ArticleComment> wrapper = new LambdaQueryWrapper<ArticleComment>()
+                .eq(ArticleComment::getStatus, "pending");
+        if (articleId != null) {
+            wrapper.eq(ArticleComment::getArticleId, articleId);
+        }
+        wrapper.orderByDesc(ArticleComment::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return articleCommentMapper.selectList(wrapper);
+    }
+
+    public List<Map<String, Object>> getPendingCommentsWithDetail(Long articleId, Long userId, String role) {
+        LambdaQueryWrapper<ArticleComment> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(ArticleComment::getStatus, "pending");
+
+        if (articleId != null) {
+            wrapper.eq(ArticleComment::getArticleId, articleId);
+        }
+
+        // 非管理员则只看自己文章的评论
+        if (!"admin".equals(role) && userId != null) {
+            List<Article> myArticles = articleMapper.selectList(
+                    new LambdaQueryWrapper<Article>().eq(Article::getCreatedBy, userId)
+            );
+            if (myArticles.isEmpty()) return new ArrayList<>();
+            Set<Long> articleIds = myArticles.stream().map(Article::getId).collect(Collectors.toSet());
+            wrapper.in(ArticleComment::getArticleId, articleIds);
+        }
+
+        wrapper.orderByDesc(ArticleComment::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        List<ArticleComment> comments = articleCommentMapper.selectList(wrapper);
+
+        Map<Long, User> userCache = new HashMap<>();
+        Map<Long, Article> articleCache = new HashMap<>();
+        List<Map<String, Object>> result = new ArrayList<>();
+
+        for (ArticleComment c : comments) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", c.getId());
+            item.put("articleId", c.getArticleId());
+            item.put("parentId", c.getParentId());
+            item.put("replyToId", c.getReplyToId());
+            item.put("content", c.getContent());
+            item.put("status", c.getStatus());
+            item.put("createdAt", c.getCreatedAt());
+            item.put("auditBy", c.getAuditBy());
+            item.put("auditAt", c.getAuditAt());
+
+            User user = getUserCached(c.getUserId(), userCache);
+            if (user != null) {
+                item.put("userName", user.getNickname() != null ? user.getNickname() : user.getPhone());
+                item.put("userAvatar", user.getAvatar());
+            }
+
+            Article article = getArticleCached(c.getArticleId(), articleCache);
+            if (article != null) {
+                item.put("articleTitle", article.getTitle());
+                item.put("articleAuthorId", article.getCreatedBy());
+            }
+
+            result.add(item);
+        }
+        return result;
+    }
+
+    /**
+     * 管理员获取评论列表(分页,按状态筛选,含用户和文章信息)
+     */
+    public Page<Map<String, Object>> getAdminCommentList(Long articleId, String status, int page, int size) {
+        LambdaQueryWrapper<ArticleComment> wrapper = new LambdaQueryWrapper<>();
+        if (articleId != null) {
+            wrapper.eq(ArticleComment::getArticleId, articleId);
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ArticleComment::getStatus, status);
+        }
+        wrapper.orderByDesc(ArticleComment::getCreatedAt);
+
+        SortUtil.applySort(wrapper);
+        Page<ArticleComment> p = articleCommentMapper.selectPage(new Page<>(page, size), wrapper);
+        Page<Map<String, Object>> result = new Page<>(p.getCurrent(), p.getSize(), p.getTotal());
+
+        Map<Long, User> userCache = new HashMap<>();
+        Map<Long, Article> articleCache = new HashMap<>();
+        List<Map<String, Object>> records = new ArrayList<>();
+
+        for (ArticleComment c : p.getRecords()) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", c.getId());
+            item.put("articleId", c.getArticleId());
+            item.put("parentId", c.getParentId());
+            item.put("replyToId", c.getReplyToId());
+            item.put("content", c.getContent());
+            item.put("status", c.getStatus());
+            item.put("createdAt", c.getCreatedAt());
+            item.put("auditBy", c.getAuditBy());
+            item.put("auditAt", c.getAuditAt());
+
+            User user = getUserCached(c.getUserId(), userCache);
+            if (user != null) {
+                item.put("userName", user.getNickname() != null ? user.getNickname() : user.getPhone());
+                item.put("userAvatar", user.getAvatar());
+            }
+
+            Article article = getArticleCached(c.getArticleId(), articleCache);
+            if (article != null) {
+                item.put("articleTitle", article.getTitle());
+            }
+
+            records.add(item);
+        }
+        result.setRecords(records);
+        return result;
+    }
+
+    private Article getArticleCached(Long articleId, Map<Long, Article> cache) {
+        if (articleId == null) return null;
+        if (!cache.containsKey(articleId)) {
+            cache.put(articleId, articleMapper.selectById(articleId));
+        }
+        return cache.get(articleId);
+    }
+
+    /**
+     * 获取用户的评论
+     */
+    public List<Map<String, Object>> getMyComments(Long userId) {
+        List<ArticleComment> comments = articleCommentMapper.selectList(
+                new LambdaQueryWrapper<ArticleComment>()
+                        .eq(ArticleComment::getUserId, userId)
+                        .orderByDesc(ArticleComment::getCreatedAt)
+        );
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (ArticleComment c : comments) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("id", c.getId());
+            item.put("articleId", c.getArticleId());
+            item.put("content", c.getContent());
+            item.put("status", c.getStatus());
+            item.put("createdAt", c.getCreatedAt());
+            item.put("earnedEnergy", c.getEarnedEnergy());
+            result.add(item);
+        }
+        return result;
+    }
+}

+ 89 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ArticlePermissionService.java

@@ -0,0 +1,89 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.Article;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 文章权限过滤核心逻辑
+ * 根据用户身份和文章的visibility+visible_to字段判断可见性
+ */
+@Slf4j
+@Service
+public class ArticlePermissionService {
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    public List<Article> filterVisible(List<Article> articles, Long userId, Long familyId, String vendorType) {
+        if (articles == null || articles.isEmpty()) return Collections.emptyList();
+        return articles.stream()
+                .filter(a -> isVisible(a, userId, familyId, vendorType))
+                .collect(Collectors.toList());
+    }
+
+    public boolean isVisible(Article article, Long userId, Long familyId, String vendorType) {
+        if (article == null) return false;
+        String visibility = article.getVisibility();
+        if (visibility == null) visibility = "public";
+
+        switch (visibility) {
+            case "public":
+                return true;
+            case "login":
+                return userId != null;
+            case "private":
+                return isPrivateVisible(article.getVisibleTo(), userId, familyId, vendorType);
+            default:
+                return true;
+        }
+    }
+
+    private boolean isPrivateVisible(String visibleToJson, Long userId, Long familyId, String vendorType) {
+        if (visibleToJson == null || visibleToJson.isEmpty()) return false;
+        try {
+            List<Map<String, Object>> rules = objectMapper.readValue(visibleToJson,
+                    new TypeReference<List<Map<String, Object>>>() {});
+            if (rules == null || rules.isEmpty()) return false;
+
+            for (Map<String, Object> rule : rules) {
+                String type = (String) rule.get("type");
+                if (type == null) continue;
+
+                switch (type) {
+                    case "family":
+                        if (familyId != null) {
+                            Object familyIdObj = rule.get("familyId");
+                            if (familyIdObj != null) {
+                                Long targetId = Long.valueOf(familyIdObj.toString());
+                                if (targetId.equals(familyId)) return true;
+                            }
+                        }
+                        break;
+                    case "vendor_type":
+                        if (vendorType != null) {
+                            String targetType = (String) rule.get("vendorType");
+                            if (targetType != null && targetType.equals(vendorType)) return true;
+                        }
+                        break;
+                    case "user":
+                        if (userId != null) {
+                            Object userIdObj = rule.get("userId");
+                            if (userIdObj != null) {
+                                Long targetId = Long.valueOf(userIdObj.toString());
+                                if (targetId.equals(userId)) return true;
+                            }
+                        }
+                        break;
+                }
+            }
+            return false;
+        } catch (Exception e) {
+            log.warn("解析visibleTo失败: {}", visibleToJson, e);
+            return false;
+        }
+    }
+}

+ 1571 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ArticleService.java

@@ -0,0 +1,1571 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.CfEarnResult;
+import com.etotem.cfc.dto.ReadingStatsDTO;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.ArticleCategory;
+import com.etotem.cfc.entity.ArticleQuizRecord;
+import com.etotem.cfc.entity.ArticleReadingRecord;
+import com.etotem.cfc.entity.ContentDimensionThreshold;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.PointsLog;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ArticleQuizRecordMapper;
+import com.etotem.cfc.mapper.ArticleReadingRecordMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.PointsLogMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.DimensionCodes;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class ArticleService {
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private ArticlePermissionService articlePermissionService;
+
+    @Resource
+    private ArticleCategoryService articleCategoryService;
+
+    @Resource
+    private ArticleReadingRecordMapper articleReadingRecordMapper;
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private PointsLogMapper pointsLogMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    @Resource
+    private CfPathwayEarnService cfPathwayEarnService;
+
+    @Resource
+    private AIService aiService;
+
+    @Resource
+    private ArticleQuizRecordMapper articleQuizRecordMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FiveDimensionScoreService fiveDimensionScoreService;
+
+    @Resource
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @Resource(name = "taskExecutor")
+    private ThreadPoolTaskExecutor taskExecutor;
+
+    @Resource
+    private ArticleAudioService articleAudioService;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
+                                        Long userId, Long familyId, String vendorType) {
+        return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, null);
+    }
+
+    public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
+                                        Long userId, Long familyId, String vendorType, Long memberId) {
+        return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, memberId);
+    }
+
+    /**
+     * 知识中心文章列表:支持按文章标签筛选(知识中心 Tab 从「五维」改为「文章标签」)。
+     * tag 为空时行为与旧版一致;tag 非空时仅返回 tags 字段包含该标签的文章。
+     * tags 字段为 JSON 数组字符串(如 ["减脂","睡眠"])或逗号分隔,统一由 parseCommaOrJsonTags 解析后内存过滤。
+     */
+    public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, String tag,
+                                        int page, int size, Long userId, Long familyId, String vendorType, Long memberId) {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                // 契约 S-cfc-315(admin.article.manage):C 端仅展示审核通过(approved)或历史直接发布
+                // (audit_status=null 遗留数据,向后兼容保持可见)的文章;明确未审(pending/rejected)下推不查
+                .and(w -> w.eq(Article::getAuditStatus, "approved").or().isNull(Article::getAuditStatus))
+                .orderByDesc(Article::getIsFeatured)
+                .orderByAsc(Article::getSortOrder)
+                .orderByDesc(Article::getPublishedAt);
+
+        if (categoryId != null && categoryId > 0) {
+            wrapper.eq(Article::getCategoryId, categoryId);
+        }
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            String kw = keyword.trim();
+            wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
+        }
+        if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
+            String dim = dimensionCode.trim();
+            // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
+            wrapper.and(w -> w
+                    .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                    .or().like(Article::getRelatedDimensions, dim)
+            );
+        }
+
+        // 先查全量(不含分页),内存中做权限过滤后再手动分页。
+        // 原因:可见性过滤规则含 JSON visible_to,无法下推 SQL;
+        //      若先 selectPage 后过滤,total 会被设为本页过滤后条数(<= size),
+        //      前端 noMore = 已加载数 >= total 恒为真,导致只显示一页、无法加载更多。
+        List<Article> all = articleMapper.selectList(wrapper);
+
+        // 按文章标签筛选(与 parseCommaOrJsonTags 解析语义对齐,兼容 JSON 数组 / 逗号分隔两种存储格式)
+        if (tag != null && !tag.trim().isEmpty()) {
+            String targetTag = tag.trim();
+            all = all.stream()
+                    .filter(a -> parseCommaOrJsonTags(a.getTags()).contains(targetTag))
+                    .collect(Collectors.toList());
+        }
+
+        List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
+
+        // 契约 S-cfc-315(admin.article.manage):C 端仅展示审核通过文章,明确未审(pending/rejected)
+        // 不得泄漏;auditStatus=null 为历史直接发布遗留数据,保持可见(向后兼容,见 SQL 下推条件)。
+        // 置于 filterVisible 之后,兼容权限过滤可能回补的未审数据。
+        visible = visible.stream()
+                .filter(a -> a.getAuditStatus() == null || "approved".equals(a.getAuditStatus()))
+                .collect(Collectors.toList());
+
+        // 过滤已完成阅读且获得CF值的文章(达到阈值且答题得CF后不再出现在文章列表中)
+        if (memberId != null) {
+            List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
+            if (!completedIds.isEmpty()) {
+                visible.removeIf(a -> completedIds.contains(a.getId()));
+            }
+        }
+
+        // 内容维度阈值显隐过滤(A-后端):OR 逻辑,fail-open 不误隐藏
+        applyDimensionThresholdFilter(visible, familyId);
+
+        enrichTotalDurationSeconds(visible);
+
+        // 手动分页(与 getFeatured 相同模式),total 为过滤后的真实总数
+        int total = visible.size();
+        int fromIndex = Math.min((page - 1) * size, total);
+        int toIndex = Math.min(fromIndex + size, total);
+        List<Article> pageList = visible.subList(fromIndex, toIndex);
+
+        Page<Article> filtered = new Page<>(page, size);
+        filtered.setTotal(total);
+        filtered.setRecords(new ArrayList<>(pageList));
+        return filtered;
+    }
+
+    /**
+     * 内容维度阈值显隐过滤(A-后端)。
+     * 家庭维度指标取家庭成员平均值;无家庭得分数据 → fail-open 不误隐藏。
+     * 显隐规则(OR 逻辑):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
+     */
+    private void applyDimensionThresholdFilter(List<Article> visible, Long familyId) {
+        if (visible == null || visible.isEmpty()) return;
+        Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
+        if (familyAvg.isEmpty()) return; // 无家庭得分数据 → fail-open
+        List<Long> ids = visible.stream().map(Article::getId).collect(Collectors.toList());
+        Map<Long, List<ContentDimensionThreshold>> byId =
+                contentDimensionThresholdService.listByContents("ARTICLE", ids);
+        DimensionThresholdFilter.filterVisible(visible, Article::getId, "ARTICLE", familyAvg, byId);
+    }
+
+    /**
+     * 聚合已发布文章的标签,按出现频次降序返回 Top N(知识中心 Tab 动态标签列表数据源)。
+     * 标签格式兼容 JSON 数组 / 逗号分隔,统一由 parseCommaOrJsonTags 解析拆分去重。
+     */
+    public List<String> listTopTags(int limit) {
+        int n = limit > 0 ? limit : 20;
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .and(w -> w.isNotNull(Article::getTags).or().apply("TRIM(tags) <> ''"));
+        List<Article> articles = articleMapper.selectList(wrapper);
+        Map<String, Integer> freq = new HashMap<>();
+        for (Article a : articles) {
+            for (String t : parseCommaOrJsonTags(a.getTags())) {
+                if (!t.isEmpty()) {
+                    freq.merge(t, 1, Integer::sum);
+                }
+            }
+        }
+        return freq.entrySet().stream()
+                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
+                        .thenComparing(Map.Entry.comparingByKey()))
+                .limit(n)
+                .map(Map.Entry::getKey)
+                .collect(Collectors.toList());
+    }
+
+    public List<Article> getFeatured(int size, Long userId, Long familyId, String vendorType, Long memberId) {
+        return getFeatured(size, null, userId, familyId, vendorType, memberId);
+    }
+
+    public List<Article> getFeatured(int size, String dimensionCode, Long userId, Long familyId, String vendorType, Long memberId) {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .eq(Article::getIsFeatured, 1)
+                // 契约 S-cfc-315(admin.article.manage):精选仅含审核通过(approved),
+                // 未审(pending/rejected/null)一律不下推,杜绝直接发布泄漏到 C 端精选
+                .eq(Article::getAuditStatus, "approved")
+                .orderByAsc(Article::getSortOrder)
+                .orderByDesc(Article::getPublishedAt)
+                .last("LIMIT " + Math.max(size, 50));
+
+        if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
+            String dim = dimensionCode.trim();
+            // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
+            wrapper.and(w -> w
+                .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                .or().like(Article::getRelatedDimensions, dim)
+            );
+        }
+
+        List<Article> all = articleMapper.selectList(wrapper);
+        List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
+
+        // 契约 S-cfc-315(admin.article.manage):C 端精选仅含审核通过文章,未审(pending/rejected/null)
+        // 一律不可见(approved 才是可见终态)。置于 filterVisible 之后,兼容权限过滤回补的未审数据。
+        visible = visible.stream()
+                .filter(a -> "approved".equals(a.getAuditStatus()))
+                .collect(Collectors.toList());
+
+        // 过滤已阅读达标的文章(达到阈值后不再出现在推荐阅读中)
+        if (memberId != null) {
+            List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
+            if (!completedIds.isEmpty()) {
+                visible.removeIf(a -> completedIds.contains(a.getId()));
+            }
+        }
+
+        enrichTotalDurationSeconds(visible);
+
+        return visible.size() > size ? visible.subList(0, size) : visible;
+    }
+
+    /**
+     * 存量回填:为所有「已发布且 tags 为空」的文章异步触发自动打标(幂等,可重复调用)。
+     * @return 触发的文章数
+     */
+    public int backfillEmptyPublishedTags() {
+        List<Article> list = articleMapper.selectList(new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .and(w -> w.isNull(Article::getTags).or().apply("TRIM(tags) = ''")));
+        for (Article a : list) {
+            ensureAutoTagsIfEmpty(a.getId());
+        }
+        log.info("存量空标签文章回填触发: {} 篇", list.size());
+        return list.size();
+    }
+
+    /**
+     * 相关文章:按标签匹配(FIND_IN_SET 精确匹配整标签),共享标签数降序 → 发布时间降序,
+     * 排除自身,仅取已发布,经可见性过滤后按 (page-1)*size ~ page*size 分页窗口截取。
+     * 无标签/无匹配返回空。
+     */
+    public List<Article> getRelatedArticles(Long articleId, int size, int page, Long userId, Long familyId, String vendorType) {
+        Article current = articleMapper.selectById(articleId);
+        if (current == null || current.getTags() == null || current.getTags().trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        List<String> tags = new ArrayList<>();
+        for (String t : current.getTags().split(",")) {
+            String tag = t.trim();
+            if (!tag.isEmpty() && !tags.contains(tag)) {
+                tags.add(tag);
+            }
+        }
+        return getRelatedArticlesByTags(tags, articleId, size, page, userId, familyId, vendorType);
+    }
+
+    /**
+     * 相关文章(按源标签匹配,通用入口):供内容关联服务(活动/商品 ↔ 文章)复用,
+     * 语义与 {@link #getRelatedArticles} 一致:共享标签数降序 → 发布时间降序,仅取已发布,
+     * 经可见性过滤后分页窗口截取。excludeArticleId 为空表示不排除(源为其他表内容)。
+     *
+     * @param tags            源标签集合
+     * @param excludeArticleId 需排除的文章ID(文章源排除自身;其他源为 null)
+     * @param size            每页条数
+     * @param page            页码(从1开始)
+     * @param userId          当前用户ID(可为空)
+     * @param familyId        家庭ID(可为空,私有文章可见性判定用)
+     * @param vendorType      服务商类型(可为空)
+     * @return 相关文章列表,无匹配返回空列表
+     */
+    public List<Article> getRelatedArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
+                                                  Long userId, Long familyId, String vendorType) {
+        return matchArticlesByTags(tags, excludeArticleId, size, page, userId, familyId, vendorType);
+    }
+
+    /**
+     * 商品详情页「相关文章」:按商品标签匹配文章(共享标签数降序 → 发布时间降序),
+     * 支持分页窗口截取。商品标签为 JSON 数组或逗号分隔字符串。
+     */
+    public List<Article> getRelatedArticlesByProduct(Long productId, int size, int page, Long userId, Long familyId, String vendorType) {
+        if (productId == null) return Collections.emptyList();
+        Product product = productMapper.selectById(productId);
+        if (product == null || product.getTags() == null || product.getTags().trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        List<String> tags = parseCommaOrJsonTags(product.getTags());
+        // 商品来源无需排除文章自身(productId 与 articleId 分属不同表),excludeArticleId 传 null
+        return matchArticlesByTags(tags, null, size, page, userId, familyId, vendorType);
+    }
+
+    /**
+     * 标签匹配文章核心逻辑:FIND_IN_SET 候选 → 共享标签计数 → 排序 → 可见性过滤 → 分页窗口截取。
+     */
+    private List<Article> matchArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
+                                              Long userId, Long familyId, String vendorType) {
+        if (tags == null || tags.isEmpty() || size < 1) {
+            return Collections.emptyList();
+        }
+        int p = page < 1 ? 1 : page;
+
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published");
+        if (excludeArticleId != null) {
+            wrapper.ne(Article::getId, excludeArticleId);
+        }
+        wrapper.and(w -> {
+            boolean first = true;
+            for (String tag : tags) {
+                if (first) {
+                    w.apply("FIND_IN_SET({0}, tags) > 0", tag);
+                    first = false;
+                } else {
+                    w.or().apply("FIND_IN_SET({0}, tags) > 0", tag);
+                }
+            }
+        });
+        List<Article> candidates = articleMapper.selectList(wrapper);
+
+        // 共享标签计数,剔除零共享(SQL 已限定至少一个标签命中,此处防御)
+        Map<Long, Integer> score = new HashMap<>();
+        List<Article> matched = new ArrayList<>();
+        for (Article a : candidates) {
+            if (excludeArticleId != null && a.getId() != null && a.getId().equals(excludeArticleId)) {
+                continue;
+            }
+            int s = 0;
+            if (a.getTags() != null) {
+                for (String t : a.getTags().split(",")) {
+                    if (tags.contains(t.trim())) {
+                        s++;
+                    }
+                }
+            }
+            if (s > 0) {
+                matched.add(a);
+                score.put(a.getId(), s);
+            }
+        }
+        matched.sort((x, y) -> {
+            int diff = score.getOrDefault(y.getId(), 0) - score.getOrDefault(x.getId(), 0);
+            if (diff != 0) {
+                return diff;
+            }
+            Date px = x.getPublishedAt();
+            Date py = y.getPublishedAt();
+            if (px == null && py == null) return 0;
+            if (px == null) return 1;
+            if (py == null) return -1;
+            return py.compareTo(px);
+        });
+
+        List<Article> visible = articlePermissionService.filterVisible(matched, userId, familyId, vendorType);
+        if (visible == null) {
+            visible = Collections.emptyList();
+        }
+        // 分页窗口截取:兼容旧调用方(size 截断)与分页调用方
+        int from = (p - 1) * size;
+        if (from >= visible.size()) {
+            return Collections.emptyList();
+        }
+        int to = Math.min(from + size, visible.size());
+        return new ArrayList<>(visible.subList(from, to));
+    }
+
+    /** 商品标签解析:兼容 JSON 数组字符串(["标签1","标签2"])与逗号分隔(标签1,标签2) */
+    private List<String> parseCommaOrJsonTags(String raw) {
+        if (raw == null || raw.trim().isEmpty()) return Collections.emptyList();
+        String trimmed = raw.trim();
+        if (trimmed.startsWith("[")) {
+            try {
+                com.alibaba.fastjson.JSONArray arr = com.alibaba.fastjson.JSON.parseArray(trimmed);
+                if (arr == null) return Collections.emptyList();
+                List<String> tags = new ArrayList<>();
+                for (int i = 0; i < arr.size(); i++) {
+                    Object o = arr.get(i);
+                    if (o != null && !o.toString().trim().isEmpty()) {
+                        tags.add(o.toString().trim());
+                    }
+                }
+                return tags;
+            } catch (Exception e) {
+                log.warn("解析商品标签失败: {}", e.getMessage());
+                return Collections.emptyList();
+            }
+        }
+        List<String> tags = new ArrayList<>();
+        for (String t : trimmed.split(",")) {
+            String tag = t.trim();
+            if (!tag.isEmpty() && !tags.contains(tag)) {
+                tags.add(tag);
+            }
+        }
+        return tags;
+    }
+
+    public Article getDetail(Long id, Long userId, Long familyId, String vendorType) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) return null;
+        if (!"published".equals(article.getStatus())) return null;
+        // 契约 S-cfc-315(admin.article.manage):C 端详情仅展示审核通过(approved)文章,
+        // 未审(pending/rejected/null)一律拒绝(approved 才是 C 端可见终态)
+        if (!"approved".equals(article.getAuditStatus())) return null;
+        if (!articlePermissionService.isVisible(article, userId, familyId, vendorType)) return null;
+        return article;
+    }
+
+    private int calculateWordCount(String htmlContent) {
+        if (htmlContent == null || htmlContent.isEmpty()) return 0;
+        // Strip HTML tags
+        String text = htmlContent.replaceAll("<[^>]*>", "");
+        // Strip HTML entities
+        text = text.replaceAll("&[a-zA-Z]+;", " ");
+        // Remove extra whitespace
+        text = text.replaceAll("\\s+", " ").trim();
+        // Count characters (Chinese text: each character is a "word")
+        return text.length();
+    }
+
+    @Transactional
+    public Map<String, Object> recordRead(Long articleId, Long userId, Long memberId, int durationSeconds) {
+        Map<String, Object> result = new HashMap<>();
+        result.put("taskId", null);
+        result.put("pointsEarned", 0);
+
+        // 1. Increment view count
+        LambdaUpdateWrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
+                .setSql("view_count = view_count + 1")
+                .eq(Article::getId, articleId);
+        articleMapper.update(null, wrapper);
+
+
+        // 2. Save reading record
+        ArticleReadingRecord record = new ArticleReadingRecord();
+        record.setArticleId(articleId);
+        record.setUserId(userId);
+        record.setMemberId(memberId);
+        record.setContent("");
+        record.setDurationSeconds(durationSeconds);
+        int minSeconds = getArticleReadingMinSeconds();
+        record.setReadingCompleted(memberId != null && durationSeconds >= minSeconds);
+        record.setReadAt(new Date());
+        record.setCreatedAt(new Date());
+        articleReadingRecordMapper.insert(record);
+
+        // 3. If no memberId, can't create task (reading as parent, not child)
+        if (memberId == null) {
+            return result;
+        }
+
+        // 4. Check reading duration threshold
+        if (durationSeconds < minSeconds) {
+            result.put("belowThreshold", true);
+            result.put("minSeconds", minSeconds);
+            return result;
+        }
+
+        // If no userId, can't create task (unauthenticated request)
+        if (userId == null) {
+            result.put("belowThreshold", true);
+            result.put("minSeconds", minSeconds);
+            return result;
+        }
+
+        // 5. Check if a task already exists for this article+child (avoid duplicates)
+        Task existingTask = taskMapper.selectOne(
+                new LambdaQueryWrapper<Task>()
+                        .eq(Task::getSourceType, "article")
+                        .eq(Task::getSourceId, articleId)
+                        .eq(Task::getMemberId, memberId)
+                        .last("LIMIT 1")
+        );
+        if (existingTask != null) {
+            result.put("taskId", existingTask.getId());
+            result.put("pointsEarned", 0);
+            result.put("alreadyCompleted", true);
+            return result;
+        }
+
+        // 6. Load article to get wordCount and articleType
+        Article article = articleMapper.selectById(articleId);
+        if (article == null) return result;
+
+        int wordCount = article.getWordCount() != null ? article.getWordCount() : 0;
+        String articleType = article.getArticleType() != null ? article.getArticleType() : "normal";
+
+        // 7. Calculate points based on wordCount × type rate
+        int rate = 1; // default for 'normal'
+        String rateStr = sysConfigService.getValue("article_energy_rate_" + articleType);
+        if (rateStr != null && !rateStr.isEmpty()) {
+            try { rate = Integer.parseInt(rateStr); } catch (NumberFormatException e) { /* use default */ }
+        }
+        int points = Math.max(1, wordCount / 100 * rate);
+
+        // 8. Create task with status='completed' (auto-completed by reading)
+        Task task = new Task();
+        task.setFamilyId(null); // will set after getting child
+        task.setCreatorId(userId);
+        task.setExecutorType("child"); // 非登录用户(不可登录成员)
+        task.setExecutorId(memberId);
+        task.setMemberId(memberId);
+        task.setTitle("阅读文章: " + article.getTitle());
+        task.setDescription("自动生成 - 阅读文章《" + article.getTitle() + "》" + durationSeconds + "秒");
+        task.setPoints(points);
+        task.setRepeatType("none");
+        task.setCategory("学习类");
+        task.setNeedReview(0);
+        task.setReviewByCategory(0);
+        task.setTaskType("onetime");
+        task.setSourceType("article");
+        task.setSourceId(articleId);
+        task.setStatus("completed");
+        task.setCompletedAt(new Date());
+        task.setCreatedAt(new Date());
+        task.setUpdatedAt(new Date());
+
+        // Set deadline to today end
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.HOUR_OF_DAY, 23);
+        cal.set(Calendar.MINUTE, 59);
+        cal.set(Calendar.SECOND, 59);
+        task.setDeadline(cal.getTime());
+
+        // Get child to set familyId
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child != null) {
+            task.setFamilyId(child.getFamilyId());
+        }
+
+        taskMapper.insert(task);
+
+        // 9. Update child totalPoints
+        if (child != null) {
+            child.setTotalPoints(child.getTotalPoints() + points);
+            child.setUpdatedAt(new Date());
+            familyMemberMapper.updateById(child);
+        }
+
+        // 10. Insert PointsLog
+        PointsLog pointsLog = new PointsLog();
+        pointsLog.setMemberId(memberId);
+        pointsLog.setTaskId(task.getId());
+        pointsLog.setAmount(points);
+        pointsLog.setType("earn");
+        pointsLog.setCategory("task");
+        pointsLog.setDescription("阅读文章: " + article.getTitle());
+        pointsLog.setCreatedAt(new Date());
+        pointsLogMapper.insert(pointsLog);
+
+        // 11. Award energy via EnergyService
+        try {
+            energyService.awardEnergy(memberId, "article", articleId, points,
+                "阅读文章: " + article.getTitle(), null);
+        } catch (Exception e) {
+        log.warn("能量发放失败(不影响积分): memberId={}, articleId={}, error={}",
+            memberId, articleId, e.getMessage());
+        }
+
+        // 12. Link taskId to reading record
+        record.setTaskId(task.getId());
+        articleReadingRecordMapper.updateById(record);
+
+        // 13. Return result
+        result.put("taskId", task.getId());
+        result.put("pointsEarned", points);
+        result.put("belowThreshold", false);
+        return result;
+    }
+
+    public void reportReadingTime(Long articleId, Long userId, Long memberId, int durationSeconds) {
+        if (memberId == null) return;
+
+        // 查找当日已有记录(同文章+同家庭成员)
+        LambdaQueryWrapper<ArticleReadingRecord> wrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
+                .eq(ArticleReadingRecord::getArticleId, articleId)
+                .eq(ArticleReadingRecord::getMemberId, memberId)
+                .apply("DATE(read_at) = CURDATE()")
+                .last("LIMIT 1");
+        ArticleReadingRecord existing = articleReadingRecordMapper.selectOne(wrapper);
+
+        // 获取阅读达标阈值
+        int minSeconds = getArticleReadingMinSeconds();
+        boolean isCompleted = false;
+
+        if (existing != null) {
+            // 累加时长
+            existing.setDurationSeconds(existing.getDurationSeconds() + durationSeconds);
+            // 累计时长达到阈值时标记为已阅读
+            if (existing.getReadingCompleted() == null || !existing.getReadingCompleted()) {
+                existing.setReadingCompleted(existing.getDurationSeconds() >= minSeconds);
+                isCompleted = existing.getReadingCompleted();
+            }
+            existing.setUpdatedAt(new Date());
+            articleReadingRecordMapper.updateById(existing);
+        } else {
+            // 新建记录
+            ArticleReadingRecord record = new ArticleReadingRecord();
+            record.setArticleId(articleId);
+            record.setUserId(userId);
+            record.setMemberId(memberId);
+            record.setDurationSeconds(durationSeconds);
+            record.setReadingCompleted(durationSeconds >= minSeconds);
+            record.setReadAt(new Date());
+            record.setCreatedAt(new Date());
+            articleReadingRecordMapper.insert(record);
+        }
+    }
+
+    /**
+     * 获取文章阅读达标最低秒数,默认 60 秒
+     */
+    private int getArticleReadingMinSeconds() {
+        String val = sysConfigService.getValue("article_reading_min_seconds");
+        if (val != null && !val.isEmpty()) {
+            try { return Integer.parseInt(val); } catch (NumberFormatException e) {}
+        }
+        return 60;
+    }
+
+    /**
+     * 递增文章浏览数(打开详情页即计数,匿名/登录用户均计)
+     */
+    public void incrementViewCount(Long id) {
+        if (id == null) return;
+        articleMapper.update(null, Wrappers.<Article>lambdaUpdate()
+                .eq(Article::getId, id)
+                .setSql("view_count = view_count + 1"));
+    }
+
+    /**
+     * 按文章 ID 分页查询阅读记录(每人聚合一行),返回昵称、累计时长、阅读次数、最后阅读时间
+     */
+    public Page<Map<String, Object>> getArticleReadingRecords(Long articleId, int page, int size) {
+        long total = articleReadingRecordMapper.countDistinctByArticle(articleId);
+        if (total == 0) {
+            Page<Map<String, Object>> empty = new Page<>(page, size);
+            empty.setTotal(0);
+            empty.setRecords(Collections.emptyList());
+            return empty;
+        }
+        int offset = (page - 1) * size;
+        List<Map<String, Object>> records = articleReadingRecordMapper.selectByArticleAggregated(articleId, offset, size);
+        Page<Map<String, Object>> result = new Page<>(page, size);
+        result.setTotal(total);
+        result.setRecords(records);
+        return result;
+    }
+
+    public Article getById(Long id) {
+        return articleMapper.selectById(id);
+    }
+
+    private void enrichTotalDurationSeconds(List<Article> articles) {
+        if (articles == null || articles.isEmpty()) return;
+        String ids = articles.stream()
+                .map(a -> String.valueOf(a.getId()))
+                .collect(Collectors.joining(","));
+        List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
+                "SELECT article_id, SUM(duration_seconds) AS total_duration " +
+                "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
+        Map<Long, Integer> durationMap = new HashMap<>();
+        for (Map<String, Object> row : durationRows) {
+            Number aid = (Number) row.get("article_id");
+            Number total = (Number) row.get("total_duration");
+            if (aid != null && total != null) {
+                durationMap.put(aid.longValue(), total.intValue());
+            }
+        }
+        for (Article article : articles) {
+            article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
+        }
+    }
+
+    public void enrichWithCategoryName(List<Article> articles) {
+        if (articles == null || articles.isEmpty()) return;
+    }
+
+    public Page<Article> getAdminList(String status, Long categoryId, String keyword,
+                                          String contentType, Integer difficultyLevel,
+                                          String dimensionCode, Long tagId, String auditStatus, int page, int size,
+                                          List<Map<String, String>> sortSpecs) {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .orderByDesc(Article::getCreatedAt);
+
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Article::getStatus, status);
+        }
+        if (categoryId != null && categoryId > 0) {
+            wrapper.eq(Article::getCategoryId, categoryId);
+        }
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            String kw = keyword.trim();
+            wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
+        }
+        if (contentType != null && !contentType.isEmpty()) {
+            wrapper.eq(Article::getContentType, contentType);
+        }
+        if (difficultyLevel != null && difficultyLevel > 0) {
+            wrapper.eq(Article::getDifficultyLevel, difficultyLevel);
+        }
+        if (dimensionCode != null && !dimensionCode.isEmpty()) {
+            wrapper.like(Article::getRelatedDimensions, dimensionCode);
+        }
+        if (tagId != null && tagId > 0) {
+            wrapper.inSql(Article::getId, "SELECT article_id FROM article_tags WHERE tag_id = " + tagId);
+        }
+        if (auditStatus != null && !auditStatus.isEmpty()) {
+            wrapper.eq(Article::getAuditStatus, auditStatus);
+        }
+        SortUtil.applySort(wrapper, sortSpecs, null);
+
+        Page<Article> pageResult = articleMapper.selectPage(new Page<>(page, size), wrapper);
+
+        // 批量填充每篇文章的总阅读时长(按 child 聚合去重后求和)
+        List<Article> records = pageResult.getRecords();
+        if (records != null && !records.isEmpty()) {
+            String ids = records.stream()
+                    .map(a -> String.valueOf(a.getId()))
+                    .collect(Collectors.joining(","));
+            List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
+                    "SELECT article_id, SUM(duration_seconds) AS total_duration " +
+                    "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
+            Map<Long, Integer> durationMap = new HashMap<>();
+            for (Map<String, Object> row : durationRows) {
+                Number articleId = (Number) row.get("article_id");
+                Number total = (Number) row.get("total_duration");
+                if (articleId != null && total != null) {
+                    durationMap.put(articleId.longValue(), total.intValue());
+                }
+            }
+            for (Article article : records) {
+                article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
+            }
+        }
+
+        return pageResult;
+    }
+
+    @Transactional
+    public void create(Article article, Long adminId) {
+        // 幂等检查:同一标题不允许重复创建
+        if (article.getTitle() != null && !article.getTitle().trim().isEmpty()) {
+            LambdaQueryWrapper<Article> dupCheck = new LambdaQueryWrapper<Article>()
+                    .eq(Article::getTitle, article.getTitle().trim());
+            Long existingCount = articleMapper.selectCount(dupCheck);
+            if (existingCount != null && existingCount > 0) {
+                throw new RuntimeException("标题「" + article.getTitle().trim() + "」已存在,请勿重复创建");
+            }
+        }
+
+        // Auto-calculate wordCount from content
+        if (article.getContent() != null) {
+            article.setWordCount(calculateWordCount(article.getContent()));
+        }
+        // Default articleType to 'normal' if not set
+        if (article.getArticleType() == null) {
+            article.setArticleType("normal");
+        }
+        article.setCreatedBy(adminId);
+        article.setViewCount(0);
+        article.setCreatedAt(new Date());
+        article.setUpdatedAt(new Date());
+        if ("published".equals(article.getStatus())) {
+            article.setPublishedAt(new Date());
+        }
+        articleMapper.insert(article);
+
+        // 发布后异步预生成朗读音频(不阻塞创建响应)
+        ensureArticleAudioAfterPublish(article.getId());
+
+        // AI auto-tagging (异步,不阻塞 HTTP 响应)
+        final Long articleId = article.getId();
+        final String content = article.getContent();
+        taskExecutor.execute(() -> {
+            try {
+                List<String> tagNames = autoGenerateTags(content);
+                if (!tagNames.isEmpty()) {
+                    saveAutoTags(articleId, tagNames);
+                }
+            } catch (Exception e) {
+                log.warn("AI 自动标签生成失败(不影响文章创建): articleId={}, error={}",
+                    articleId, e.getMessage());
+            }
+        });
+    }
+
+    @Transactional
+    public void update(Article article) {
+        Article existing = article.getId() != null ? articleMapper.selectById(article.getId()) : null;
+        // Recalculate wordCount if content changed
+        boolean contentChanged = false;
+        if (article.getContent() != null) {
+            String oldContent = existing != null ? existing.getContent() : null;
+            article.setWordCount(calculateWordCount(article.getContent()));
+            contentChanged = oldContent == null || !oldContent.equals(article.getContent());
+        }
+        // 朗读源变化(朗读文本变化,或朗读文本为空时正文变化)→ 作废旧音频,下次「听文章」重新合成
+        if (existing != null) {
+            String newAudioText = article.getAudioText() != null ? article.getAudioText() : existing.getAudioText();
+            String newContent = article.getContent() != null ? article.getContent() : existing.getContent();
+            if (shouldInvalidateAudio(existing.getContent(), newContent,
+                    existing.getAudioText(), newAudioText)) {
+                article.setAudioUrl("");
+            }
+        }
+        article.setUpdatedAt(new Date());
+        articleMapper.updateById(article);
+
+        // 已发布文章:朗读源变化导致音频被作废后,异步重新生成
+        ensureArticleAudioAfterPublish(article.getId());
+
+        // AI auto-tagging only when content changed (异步,不阻塞 HTTP 响应)
+        if (contentChanged && article.getContent() != null) {
+            final Long articleId = article.getId();
+            final String content = article.getContent();
+            taskExecutor.execute(() -> {
+                try {
+                    jdbcTemplate.update("DELETE FROM article_tags WHERE article_id = ?", articleId);
+                    List<String> tagNames = autoGenerateTags(content);
+                    if (!tagNames.isEmpty()) {
+                        saveAutoTags(articleId, tagNames);
+                    }
+                } catch (Exception e) {
+                    log.warn("AI 自动标签更新失败(不影响文章更新): articleId={}, error={}",
+                        articleId, e.getMessage());
+                }
+            });
+        }
+    }
+
+    /**
+     * 判断文章更新是否应作废已生成音频。
+     * 朗读文本优先;朗读文本为空时以正文为朗读源,正文变化即作废。
+     */
+    static boolean shouldInvalidateAudio(String oldContent, String newContent,
+                                         String oldAudioText, String newAudioText) {
+        String oldText = trimToNull(oldAudioText);
+        String newText = trimToNull(newAudioText);
+        if (!Objects.equals(oldText, newText)) {
+            return true;
+        }
+        if (newText != null) {
+            return false; // 有朗读文本时,正文变化不影响音频
+        }
+        if (newContent == null) {
+            return false;
+        }
+        return !Objects.equals(oldContent, newContent);
+    }
+
+    private static String trimToNull(String value) {
+        if (value == null) {
+            return null;
+        }
+        String trimmed = value.trim();
+        return trimmed.isEmpty() ? null : trimmed;
+    }
+
+    @Transactional
+    public void delete(Long id) {
+        articleMapper.deleteById(id);
+    }
+
+    @Transactional
+    public void toggleStatus(Long id, String status) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) return;
+        article.setStatus(status);
+        article.setUpdatedAt(new Date());
+        if ("published".equals(status)) {
+            // 契约 S-cfc-315(admin.article.manage):直接发布视为完成审核——落 auditStatus=approved 与
+            // 审核时间,避免 published 与 auditStatus 不一致导致 C 端不可见/泄漏(状态机 §6 approved 才可见)。
+            article.setAuditStatus("approved");
+            if (article.getAuditedAt() == null) {
+                article.setAuditedAt(new Date());
+            }
+            if (article.getPublishedAt() == null) {
+                article.setPublishedAt(new Date());
+            }
+        }
+        articleMapper.updateById(article);
+        // 发布时若标签为空则异步自动生成
+        if ("published".equals(status)) {
+            ensureAutoTagsIfEmpty(id);
+            // 发布后异步预生成朗读音频
+            ensureArticleAudioAfterPublish(id);
+        }
+    }
+
+    @Transactional
+    public void toggleFeatured(Long id, int isFeatured) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) return;
+        article.setIsFeatured(isFeatured);
+        article.setUpdatedAt(new Date());
+        if (isFeatured == 1) {
+            // 设为精选时追加到队尾,不抢占既有顺序
+            Integer maxSort = getMaxSortOrder();
+            article.setSortOrder((maxSort == null ? 0 : maxSort) + 1);
+        }
+        articleMapper.updateById(article);
+    }
+
+    /**
+     * 查询已发布且精选的文章中最大的 sort_order;若没有精选文章返回 null。
+     */
+    private Integer getMaxSortOrder() {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .eq(Article::getIsFeatured, 1)
+                .select(Article::getSortOrder)
+                .orderByDesc(Article::getSortOrder)
+                .last("LIMIT 1");
+        Article top = articleMapper.selectOne(wrapper);
+        return top != null ? top.getSortOrder() : null;
+    }
+
+    /**
+     * 上移/下移精选文章的推荐顺序。direction: 'up' 或 'down'。
+     */
+    @Transactional
+    public String moveSortOrder(Long id, String direction) {
+        Article target = articleMapper.selectById(id);
+        if (target == null) {
+            throw new RuntimeException("文章不存在");
+        }
+        if (!"published".equals(target.getStatus()) || !Integer.valueOf(1).equals(target.getIsFeatured())) {
+            throw new RuntimeException("仅已发布且精选的文章可调整顺序");
+        }
+        if (!"up".equals(direction) && !"down".equals(direction)) {
+            throw new RuntimeException("direction 只能是 up 或 down");
+        }
+
+        LambdaQueryWrapper<Article> listWrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .eq(Article::getIsFeatured, 1)
+                .orderByAsc(Article::getSortOrder)
+                .orderByDesc(Article::getPublishedAt);
+        List<Article> featured = articleMapper.selectList(listWrapper);
+
+        int idx = -1;
+        for (int i = 0; i < featured.size(); i++) {
+            if (featured.get(i).getId().equals(id)) {
+                idx = i;
+                break;
+            }
+        }
+        if (idx == -1) {
+            throw new RuntimeException("文章不存在");
+        }
+        if ("up".equals(direction) && idx <= 0) {
+            throw new RuntimeException("已在最前面");
+        }
+        if ("down".equals(direction) && idx >= featured.size() - 1) {
+            throw new RuntimeException("已在最后面");
+        }
+
+        int swapIdx = "up".equals(direction) ? idx - 1 : idx + 1;
+
+        Article a = featured.get(idx);
+        Article b = featured.get(swapIdx);
+        Integer tmpSort = a.getSortOrder();
+        a.setSortOrder(b.getSortOrder());
+        b.setSortOrder(tmpSort);
+        a.setUpdatedAt(new Date());
+        b.setUpdatedAt(new Date());
+        articleMapper.updateById(a);
+        articleMapper.updateById(b);
+
+        // 全局重编号 1..N,消除并列与空洞
+        LambdaQueryWrapper<Article> renumWrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .eq(Article::getIsFeatured, 1)
+                .orderByAsc(Article::getSortOrder)
+                .orderByDesc(Article::getPublishedAt);
+        List<Article> sorted = articleMapper.selectList(renumWrapper);
+        Date now = new Date();
+        for (int i = 0; i < sorted.size(); i++) {
+            sorted.get(i).setSortOrder(i + 1);
+            sorted.get(i).setUpdatedAt(now);
+            articleMapper.updateById(sorted.get(i));
+        }
+
+        return "已调整顺序";
+    }
+
+    public ReadingStatsDTO getReadingStats(Long memberId) {
+        ReadingStatsDTO dto = new ReadingStatsDTO();
+
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.DAY_OF_MONTH, 1);
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date since = cal.getTime();
+
+            Integer totalDuration = articleReadingRecordMapper.selectTotalDurationByChildSince(memberId, since);
+        if (totalDuration == null) totalDuration = 0;
+
+        LambdaQueryWrapper<ArticleReadingRecord> countWrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
+                .eq(ArticleReadingRecord::getMemberId, memberId)
+                .ge(ArticleReadingRecord::getReadAt, since);
+        Integer totalArticles = Math.toIntExact(articleReadingRecordMapper.selectCount(countWrapper));
+
+        int targetSeconds = 6000; // 100分钟/月目标
+        int progress = totalDuration >= targetSeconds ? 100 : totalDuration * 100 / targetSeconds;
+
+        dto.setTotalArticles(totalArticles);
+        dto.setTotalDurationSeconds(totalDuration);
+        dto.setTargetDurationSeconds(targetSeconds);
+        dto.setProgress((double) progress);
+        return dto;
+    }
+
+    public Map<String, Object> getDailyTip() {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getStatus, "published")
+                .and(w -> w.like(Article::getRelatedDimensions, "mind")
+                        .or().like(Article::getRelatedDimensions, "心理"))
+                .orderByDesc(Article::getPublishedAt)
+                .last("LIMIT 10");
+
+        List<Article> candidates = articleMapper.selectList(wrapper);
+        if (candidates != null && !candidates.isEmpty()) {
+            int dayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
+            Article tip = candidates.get(dayOfYear % candidates.size());
+
+            Map<String, Object> result = new HashMap<>();
+            result.put("id", tip.getId());
+            result.put("title", tip.getTitle());
+            result.put("summary", tip.getSummary());
+            result.put("coverImage", tip.getCoverImage());
+            return result;
+        }
+
+        Map<String, Object> fallback = new HashMap<>();
+        fallback.put("id", null);
+        fallback.put("title", "每日心理小贴士");
+        fallback.put("summary", "每天花5分钟与家人聊聊今天的心情,倾听比建议更重要。");
+        fallback.put("coverImage", null);
+        return fallback;
+    }
+
+    /**
+     * 根据文章内容和用户画像生成 2 道选择题
+     */
+    @Transactional
+    public Map<String, Object> getAiQuestions(Long articleId, Long userId, Long memberId) {
+        Map<String, Object> result = new HashMap<>();
+
+        // 1. 获取文章
+        Article article = articleMapper.selectById(articleId);
+        if (article == null) {
+            throw new RuntimeException("文章不存在");
+        }
+
+        // 2. 构建 Dify prompt
+        String contentPreview = article.getContent() != null ? article.getContent() : "";
+        if (contentPreview.length() > 800) {
+            contentPreview = contentPreview.substring(0, 800);
+        }
+        String prompt = "你是一个家庭教育助手。根据以下文章内容,为儿童生成 2 道选择题(每题 4 个选项)。"
+            + "题目应该适合该年龄段的儿童理解。"
+            + "请以 JSON 数组格式返回,格式:[{\"question\":\"问题\",\"options\":[\"A.选项 1\",\"B.选项 2\",\"C.选项 3\",\"D.选项 4\"],\"answer\":\"A\"}]"
+            + "不要返回其他文字,只返回 JSON 数组。"
+            + "\n\n文章标题:" + article.getTitle()
+            + "\n文章内容:" + contentPreview;
+
+        // 3. 调用 Dify AI
+        Map<String, Object> aiResult = aiService.sendMessage(prompt, String.valueOf(userId), "", null);
+        String aiResponse = (String) aiResult.get("answer");
+        if (aiResponse == null) {
+            aiResponse = "";
+        }
+
+        // 4. 提取 JSON 数组
+        String questionsJson = extractJsonFromResponse(aiResponse);
+
+        // 5. 保存记录
+        ArticleQuizRecord record = new ArticleQuizRecord();
+        record.setArticleId(articleId);
+        record.setUserId(userId);
+        record.setMemberId(memberId);
+        record.setQuestions(questionsJson);
+        record.setAnswers(null);
+        record.setScore(0);
+        record.setCfEarned(0);
+        record.setCreatedAt(new Date());
+        record.setUpdatedAt(new Date());
+        articleQuizRecordMapper.insert(record);
+
+        result.put("recordId", record.getId());
+        result.put("questions", questionsJson);
+        return result;
+    }
+
+    private String extractJsonFromResponse(String response) {
+        if (response == null || response.isEmpty()) return "[]";
+        int start = response.indexOf('[');
+        int end = response.lastIndexOf(']');
+        if (start >= 0 && end > start) {
+            return response.substring(start, end + 1);
+        }
+        return "[]";
+    }
+
+    @Transactional
+    public Map<String, Object> submitAnswers(Long recordId, String answersJson, Long userId, Long memberId) {
+        Map<String, Object> result = new HashMap<>();
+
+        // 1. 获取记录
+        ArticleQuizRecord record = articleQuizRecordMapper.selectById(recordId);
+        if (record == null) {
+            throw new RuntimeException("答题记录不存在");
+        }
+        if (record.getAnswers() != null) {
+            throw new RuntimeException("已作答,不可重复提交");
+        }
+
+        // 2. 解析题目和答案,计算分数
+        int score = 0;
+        int totalQuestions = 0;
+        try {
+            List<Map<String, Object>> questions = objectMapper.readValue(record.getQuestions(), objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
+            List<Map<String, Object>> answers = objectMapper.readValue(answersJson, objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
+            totalQuestions = questions.size();
+
+            Map<String, Object> answerMap = new HashMap<>();
+            for (Map<String, Object> a : answers) {
+                answerMap.put(String.valueOf(a.get("questionIndex")), a.get("selected"));
+            }
+
+            for (int i = 0; i < questions.size(); i++) {
+                Map<String, Object> q = questions.get(i);
+                String correct = (String) q.get("answer");
+                String selected = (String) answerMap.get(String.valueOf(i));
+                if (correct != null && correct.equalsIgnoreCase(selected != null ? selected.toString() : "")) {
+                    score++;
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析答题结果失败:{}", e.getMessage());
+        }
+
+        // 3. CF 值发放(F08 统一入口:仅全部答对才发,数量取自 cf_earn_rule F08,代码不再硬编码;
+        // 幂等 ref_id = 答题记录ID,同一记录只发一次)
+        boolean allCorrect = score == totalQuestions && totalQuestions > 0;
+        int pointsEarned = 0;
+        if (allCorrect && memberId != null) {
+            try {
+                CfEarnResult earnResult = cfPathwayEarnService.earnAiReadingQuizCf(
+                        memberId, record.getId(), true);
+                if (Boolean.TRUE.equals(earnResult.getEarned()) && earnResult.getAmount() != null) {
+                    pointsEarned = earnResult.getAmount();
+                }
+            } catch (Exception e) {
+                log.warn("CF值发放失败:{}", e.getMessage());
+            }
+        }
+
+        // 4. 更新答题记录(cfEarned 记本次实际发放数量,日限/幂等命中时记 0)
+        record.setAnswers(answersJson);
+        record.setScore(score);
+        record.setCfEarned(pointsEarned);
+        record.setUpdatedAt(new Date());
+        articleQuizRecordMapper.updateById(record);
+
+        result.put("score", score);
+        result.put("totalQuestions", totalQuestions);
+        result.put("pointsEarned", pointsEarned);
+        return result;
+    }
+
+    /**
+     * 用户发布文章(成长记录)
+     * @param visibility private=仅家庭(直接发布), public=公开(需审核)
+     */
+    @Transactional
+    public Article publishByUser(String title, String content, String coverImage, String visibility,
+                                  String relatedDimensions, Long userId, String userRole) {
+        Article article = new Article();
+        article.setTitle(title);
+        article.setContent(content);
+        article.setCoverImage(coverImage);
+        article.setAuthorType("parent");
+        article.setCreatedBy(userId);
+        article.setWordCount(calculateWordCount(content));
+
+        // 可见范围
+        article.setVisibility(visibility != null ? visibility : "private");
+
+        // 关联维度
+        article.setRelatedDimensions(relatedDimensions);
+
+        article.setDimensionWeights(buildEqualWeights(relatedDimensions));
+
+        // 私有(家庭可见)→ 设置 visibleTo
+        if ("private".equals(visibility)) {
+            User user = userMapper.selectById(userId);
+            if (user != null && user.getFamilyId() != null) {
+                article.setVisibleTo("[{\"type\":\"family\",\"familyId\":" + user.getFamilyId() + "}]");
+            }
+        }
+
+        // 公开文章需要审核,家庭内部可见直接发布
+        if ("public".equals(visibility)) {
+            article.setStatus("draft");
+            article.setAuditStatus("pending");
+        } else {
+            article.setStatus("published");
+            article.setAuditStatus("approved");
+            article.setPublishedAt(new Date());
+        }
+
+        article.setArticleType("original");
+        article.setViewCount(0);
+        article.setCreatedAt(new Date());
+        article.setUpdatedAt(new Date());
+        articleMapper.insert(article);
+        // 家庭可见直接发布:发布时若标签为空则异步自动生成(公开文章待审核,内部守卫跳过)
+        ensureAutoTagsIfEmpty(article.getId());
+        // 家庭可见直接发布:异步预生成朗读音频(公开文章待审核,内部守卫跳过)
+        ensureArticleAudioAfterPublish(article.getId());
+        return article;
+    }
+
+    private String buildEqualWeights(String relatedDimensions) {
+        if (relatedDimensions == null || relatedDimensions.trim().isEmpty()) {
+            return null;
+        }
+        String[] parts = relatedDimensions.split(",");
+        int n = parts.length;
+        if (n == 0) return null;
+        int base = 100 / n;
+        int remainder = 100 - base * n;
+        Map<String, Integer> weights = new LinkedHashMap<>();
+        for (int i = 0; i < n; i++) {
+            String dim = parts[i].trim().toLowerCase();
+            if (dim.isEmpty()) continue;
+            weights.put(dim, i < remainder ? base + 1 : base);
+        }
+        if (weights.isEmpty()) return null;
+        try {
+            return objectMapper.writeValueAsString(weights);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /**
+     * 获取我的发布列表
+     */
+    public Page<Article> getMyPosts(Long userId, int page, int size) {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .eq(Article::getCreatedBy, userId)
+                // 非登录用户(不可登录成员)
+                .in(Article::getAuthorType, "parent", "child")
+                .orderByDesc(Article::getCreatedAt);
+        return articleMapper.selectPage(new Page<>(page, size), wrapper);
+    }
+
+    /**
+     * 增量查询:获取指定时间之后更新的文章(供 LangGraph RAG 使用)
+     */
+    public List<Article> getUpdatedSince(Date since, String status) {
+        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
+                .ge(Article::getUpdatedAt, since)
+                .orderByDesc(Article::getUpdatedAt);
+        String s = (status != null && !status.trim().isEmpty()) ? status.trim() : "published";
+        wrapper.eq(Article::getStatus, s);
+        return articleMapper.selectList(wrapper);
+    }
+
+    /**
+     * 管理员审核文章
+     */
+    @Transactional
+    public void auditArticle(Long articleId, String auditStatus, String auditReason, Long auditorId) {
+        Article article = articleMapper.selectById(articleId);
+        if (article == null) {
+            throw new RuntimeException("文章不存在");
+        }
+        if (!"pending".equals(article.getAuditStatus())) {
+            throw new RuntimeException("仅待审核状态可审核");
+        }
+        article.setAuditStatus(auditStatus);
+        article.setAuditorId(auditorId);
+        article.setAuditedAt(new Date());
+        if ("approved".equals(auditStatus)) {
+            article.setStatus("published");
+            article.setPublishedAt(new Date());
+            article.setAuditReason(null);
+        } else if ("rejected".equals(auditStatus)) {
+            article.setStatus("rejected");
+            article.setAuditReason(auditReason);
+        }
+        article.setUpdatedAt(new Date());
+        articleMapper.updateById(article);
+        // 审核通过发布:若标签为空则异步自动生成
+        if ("approved".equals(auditStatus)) {
+            ensureAutoTagsIfEmpty(articleId);
+            // 审核通过发布:异步预生成朗读音频
+            ensureArticleAudioAfterPublish(articleId);
+        }
+    }
+
+    /**
+     * 发布路径语音预生成入口:仅已发布且尚无音频时,事务提交后异步生成。
+     * 失败仅记录 warn,不阻塞发布流程。
+     */
+    private void ensureArticleAudioAfterPublish(Long articleId) {
+        if (articleId == null) {
+            return;
+        }
+        Article article = articleMapper.selectById(articleId);
+        if (article == null || !"published".equals(article.getStatus())) {
+            return;
+        }
+        if (article.getAudioUrl() != null && !article.getAudioUrl().trim().isEmpty()) {
+            return;
+        }
+        final Long id = articleId;
+        runAfterCommit(() -> {
+            try {
+                articleAudioService.generateIfMissing(id);
+            } catch (Exception e) {
+                log.warn("文章语音自动生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
+            }
+        });
+    }
+
+    /**
+     * 在当前事务提交后执行任务;无事务时立即提交到线程池。
+     * 避免异步任务读到未提交的文章数据。
+     */
+    private void runAfterCommit(Runnable task) {
+        if (TransactionSynchronizationManager.isSynchronizationActive()) {
+            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+                @Override
+                public void afterCommit() {
+                    taskExecutor.execute(task);
+                }
+            });
+        } else {
+            taskExecutor.execute(task);
+        }
+    }
+
+    /**
+     * 发布路径自动打标入口:仅当文章已发布且 tags 为空时,异步调 LLM 生成并写回。
+     * 失败仅记录 warn,不阻塞发布流程。
+     */
+    private void ensureAutoTagsIfEmpty(Long articleId) {
+        Article article = articleMapper.selectById(articleId);
+        if (article == null || !"published".equals(article.getStatus())) {
+            return;
+        }
+        if (article.getTags() != null && !article.getTags().trim().isEmpty()) {
+            return;
+        }
+        final Long id = article.getId();
+        final String content = article.getContent();
+        taskExecutor.execute(() -> {
+            try {
+                List<String> tagNames = autoGenerateTags(content);
+                if (!tagNames.isEmpty()) {
+                    saveAutoTags(id, tagNames);
+                }
+            } catch (Exception e) {
+                log.warn("AI 自动标签生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
+            }
+        });
+    }
+
+    /**
+     * 调用 Dify AI 从文章内容中自动提取 3-5 个中文关键词作为标签
+     */
+    private List<String> autoGenerateTags(String content) {
+        if (content == null || content.trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        // 去除 HTML 标签,避免干扰 AI 提取
+        String plainText = content.replaceAll("<[^>]*>", " ").replaceAll("\\s+", " ").trim();
+        if (plainText.isEmpty()) {
+            return Collections.emptyList();
+        }
+        // 截取前 1500 字,避免 prompt 过长
+        if (plainText.length() > 1500) {
+            plainText = plainText.substring(0, 1500);
+        }
+
+        String prompt = "你是一个家庭教育内容分析助手。请根据以下文章内容,提取 3 到 5 个最能代表文章主题的中文关键词作为标签。"
+            + "要求:1) 关键词为中文短语或名词,2-6 个字;2) 用英文逗号分隔;3) 不要包含编号、引号或解释文字;4) 只返回标签列表本身。"
+            + "\n\n文章内容:" + plainText;
+
+        try {
+            Map<String, Object> aiResult = aiService.sendMessage(prompt, "0", "", null);
+            String aiResponse = (String) aiResult.get("answer");
+            if (aiResponse == null || aiResponse.trim().isEmpty()) {
+                return Collections.emptyList();
+            }
+            // 解析逗号分隔的标签
+            List<String> tags = new ArrayList<>();
+            for (String raw : aiResponse.split(",")) {
+                String tag = raw.trim()
+                        .replaceAll("^[\\d\\.\\-\\s、。,]+", "")
+                        .replaceAll("[\\s、。,]+$", "")
+                        .trim();
+                if (!tag.isEmpty() && tag.length() <= 20 && tags.size() < 5) {
+                    tags.add(tag);
+                }
+            }
+            return tags;
+        } catch (Exception e) {
+            log.warn("AI 自动生成标签失败:{}", e.getMessage());
+            return Collections.emptyList();
+        }
+    }
+
+    /**
+     * 将 AI 生成的标签保存到 dan_knowledge_tag 与 article_tags 表,并回写 article.tags 字段
+     */
+    private void saveAutoTags(Long articleId, List<String> tagNames) {
+        if (articleId == null || tagNames == null || tagNames.isEmpty()) {
+            return;
+        }
+        List<String> savedTags = new ArrayList<>();
+        for (String tagName : tagNames) {
+            if (tagName == null || tagName.trim().isEmpty()) continue;
+            String name = tagName.trim();
+            try {
+                // 查询是否已存在同名标签
+                List<Long> existing = jdbcTemplate.queryForList(
+                        "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? LIMIT 1",
+                        Long.class, name);
+                Long tagId;
+                if (existing != null && !existing.isEmpty()) {
+                    tagId = existing.get(0);
+                } else {
+                    // 插入新标签
+                    jdbcTemplate.update(
+                            "INSERT INTO dan_knowledge_tag (tag_name, tag_type, created_at) VALUES (?, 'auto', NOW())",
+                            name);
+                    tagId = jdbcTemplate.queryForObject(
+                            "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? ORDER BY id DESC LIMIT 1",
+                            Long.class, name);
+                }
+                if (tagId != null) {
+                    jdbcTemplate.update(
+                            "INSERT IGNORE INTO article_tags (article_id, tag_id) VALUES (?, ?)",
+                            articleId, tagId);
+                    savedTags.add(name);
+                }
+            } catch (Exception e) {
+                log.warn("保存自动标签失败:tagName={}, error={}", name, e.getMessage());
+            }
+        }
+        // 回写 article.tags 字段(逗号分隔)
+        if (!savedTags.isEmpty()) {
+            String tagsStr = String.join(",", savedTags);
+            jdbcTemplate.update("UPDATE articles SET tags = ? WHERE id = ?", tagsStr, articleId);
+        }
+    }
+
+    @Transactional
+    public void submitForReview(Long id) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) {
+            throw new RuntimeException("文章不存在");
+        }
+        if (!"draft".equals(article.getStatus())) {
+            throw new RuntimeException("仅草稿状态可提交审核");
+        }
+        article.setStatus("pending");
+        article.setAuditStatus("pending");
+        article.setUpdatedAt(new Date());
+        articleMapper.updateById(article);
+    }
+
+    @Transactional
+    public void withdraw(Long id) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) {
+            throw new RuntimeException("文章不存在");
+        }
+        if (!"published".equals(article.getStatus())) {
+            throw new RuntimeException("仅发布中的文章可撤回");
+        }
+        article.setStatus("withdrawn");
+        article.setUpdatedAt(new Date());
+        articleMapper.updateById(article);
+    }
+
+    @Transactional
+    public void reDraft(Long id) {
+        Article article = articleMapper.selectById(id);
+        if (article == null) {
+            throw new RuntimeException("文章不存在");
+        }
+        if (!"rejected".equals(article.getStatus()) && !"withdrawn".equals(article.getStatus())) {
+            throw new RuntimeException("仅已驳回或已撤回的文章可重新编辑");
+        }
+        article.setStatus("draft");
+        article.setAuditStatus(null);
+        article.setAuditReason(null);
+        article.setAuditorId(null);
+        article.setAuditedAt(null);
+        article.setUpdatedAt(new Date());
+        articleMapper.updateById(article);
+    }
+}

+ 176 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentAppointmentService.java

@@ -0,0 +1,176 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.AssessmentAppointment;
+import com.etotem.cfc.entity.AssessmentOrder;
+import com.etotem.cfc.mapper.AssessmentAppointmentMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+import lombok.extern.slf4j.Slf4j;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class AssessmentAppointmentService extends ServiceImpl<AssessmentAppointmentMapper, AssessmentAppointment> {
+
+    @Resource
+    private AssessmentAppointmentMapper assessmentAppointmentMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    @Resource
+    private GuideFamilyService guideFamilyService;
+
+    /**
+     * 契约 assessment.planner.select(SC-P-32 测评选规划师 → 绑定的 T 列表):
+     * 家长侧选规划师时,所选规划师(guideId)必须属于该家庭已绑定的 T 列表。
+     * 家庭维度反查绑定(区别于规划师侧 {@link GuideFamilyAccessGuard#checkBinding} 的
+     * guide 维度守卫,方向相反)。
+     *
+     * @return true 表示规划师已绑定到该家庭(可指定);false 表示未绑定(应提示先绑定)
+     */
+    public boolean requireBoundPlanner(Long guideId, Long familyId) {
+        if (guideId == null || familyId == null) {
+            return false;
+        }
+        return guideFamilyService.isBound(guideId, familyId);
+    }
+
+    public AssessmentAppointment createAppointment(Long userId, Long memberId, Long guideId,
+                                                   Long assessorId, Long packageId, String appointmentDate, String appointmentTime, String notes) {
+        // 2026-10-23 新口径:测评预约不是特殊功能,不设 BASIC 会员配额(原 ASSESSMENT_QUOTA 硬门禁已移除,迁移 382)
+
+        AssessmentAppointment appointment = new AssessmentAppointment();
+        appointment.setUserId(userId);
+        appointment.setMemberId(memberId);
+        appointment.setGuideId(guideId);
+        appointment.setAssessorId(assessorId);
+        appointment.setPackageId(packageId);
+        appointment.setAppointmentDate(appointmentDate);
+        appointment.setAppointmentTime(appointmentTime);
+        appointment.setTeacherId(assessorId != null ? assessorId : guideId);
+        appointment.setStatus(0); // pending
+        appointment.setNotes(notes);
+        appointment.setCreatedAt(new Date());
+        appointment.setUpdatedAt(new Date());
+        this.save(appointment);
+
+        // 测评预约能量发放
+        try {
+            energyService.awardEnergy(memberId, "appointment", appointment.getId(), 10,
+                    "提交测评预约", null);
+        } catch (Exception e) {
+            log.warn("测评预约能量发放失败: memberId={}, error={}", memberId, e.getMessage());
+        }
+
+        return appointment;
+    }
+
+    public boolean confirmAppointment(Long id, Long userId) {
+        AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(id);
+        if (appointment == null) return false;
+        // 状态守卫(teacher.appointment.guard / SC-T-09):仅待确认(0)可流转到已确认(1),
+        // 重复确认、已完成(2)/未到(4)等状态一律拒绝,且拒绝时不写库
+        if (appointment.getStatus() == null || appointment.getStatus() != 0) return false;
+        // 允许被指派的测评师(assessorId)或规划师(guideId)确认
+        Long expectedId = appointment.getAssessorId() != null ? appointment.getAssessorId() : appointment.getGuideId();
+        if (!userId.equals(expectedId)) return false;
+        appointment.setStatus(1); // confirmed
+        appointment.setUpdatedAt(new Date());
+        return assessmentAppointmentMapper.updateById(appointment) > 0;
+    }
+
+    public boolean completeAppointment(Long id, Long teacherId) {
+        AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(id);
+        if (appointment == null) return false;
+        // 状态守卫(teacher.appointment.guard / SC-T-10):仅已确认(1)可流转到已完成(2),
+        // 待确认(0)/已完成(2)/未到(4)一律拒绝,拒绝时不写库、不重复发放完成能量
+        if (appointment.getStatus() == null || appointment.getStatus() != 1) return false;
+        if (!teacherId.equals(appointment.getGuideId())) return false;
+        appointment.setStatus(2); // completed
+        appointment.setUpdatedAt(new Date());
+        boolean updated = assessmentAppointmentMapper.updateById(appointment) > 0;
+
+        if (updated) {
+            try {
+                energyService.awardEnergy(appointment.getMemberId(), "appointment", appointment.getId(), 30,
+                        "完成测评", null);
+            } catch (Exception e) {
+                log.warn("测评完成能量发放失败: appointmentId={}, error={}", id, e.getMessage());
+            }
+        }
+
+        return updated;
+    }
+
+    public boolean cancelAppointment(Long id) {
+        AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(id);
+        if (appointment == null) return false;
+        // 状态守卫(teacher.appointment.guard / SC-T-10):仅待确认(0)/已确认(1)可取消;
+        // 已完成(2)/未到(4)等终态一律拒绝,且拒绝时不写库
+        if (appointment.getStatus() == null
+                || (appointment.getStatus() != 0 && appointment.getStatus() != 1)) return false;
+        appointment.setStatus(3); // cancelled
+        appointment.setUpdatedAt(new Date());
+        return assessmentAppointmentMapper.updateById(appointment) > 0;
+    }
+
+    /**
+     * 将预约标记为「未到」(status=4)—— 契约缺口 G-1:规划师「完成/未到」闭环的「未到」分支。
+     * 仅待确认(0)/已确认(1)可流转到未到(4);已完成(2)/已取消(3)/未到(4)等终态一律拒绝。
+     */
+    public boolean noShowAppointment(Long id, Long teacherId) {
+        AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(id);
+        if (appointment == null) return false;
+        // 状态守卫:仅待确认(0)/已确认(1)可标记未到;终态一律拒绝且不写库
+        if (appointment.getStatus() == null
+                || (appointment.getStatus() != 0 && appointment.getStatus() != 1)) return false;
+        if (!teacherId.equals(appointment.getGuideId())) return false;
+        appointment.setStatus(4); // no-show
+        appointment.setUpdatedAt(new Date());
+        return assessmentAppointmentMapper.updateById(appointment) > 0;
+    }
+
+    public List<AssessmentAppointment> getByUserId(Long userId) {
+        LambdaQueryWrapper<AssessmentAppointment> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentAppointment::getUserId, userId);
+        wrapper.orderByDesc(AssessmentAppointment::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return assessmentAppointmentMapper.selectList(wrapper);
+    }
+
+    public List<AssessmentAppointment> getByGuideId(Long guideId) {
+        LambdaQueryWrapper<AssessmentAppointment> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentAppointment::getGuideId, guideId);
+        wrapper.orderByDesc(AssessmentAppointment::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return assessmentAppointmentMapper.selectList(wrapper);
+    }
+
+    public List<AssessmentAppointment> getByAssessorId(Long assessorId) {
+        LambdaQueryWrapper<AssessmentAppointment> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentAppointment::getAssessorId, assessorId);
+        wrapper.orderByDesc(AssessmentAppointment::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return assessmentAppointmentMapper.selectList(wrapper);
+    }
+
+    public AssessmentAppointment confirmAppointmentByOrder(AssessmentOrder order) {
+        AssessmentAppointment appointment = new AssessmentAppointment();
+        appointment.setMemberId(order.getMemberId());
+        appointment.setGuideId(order.getGuideId());
+        appointment.setStatus(0); // pending
+        appointment.setUserId(order.getUserId());
+        appointment.setPackageId(order.getPackageId());
+        appointment.setCreatedAt(new Date());
+        appointment.setUpdatedAt(new Date());
+        assessmentAppointmentMapper.insert(appointment);
+        return appointment;
+    }
+}

+ 421 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentComparisonService.java

@@ -0,0 +1,421 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.FiveDimensionScore;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+public class AssessmentComparisonService {
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Resource
+    private FiveDimensionScoreService fiveDimensionScoreService;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /**
+     * 维度组定义:dimensionName -> [score fields that belong to this group]
+     */
+    private static final Map<String, List<String>> DIMENSION_GROUPS = new LinkedHashMap<>();
+
+    static {
+        DIMENSION_GROUPS.put("attention", Arrays.asList("attentionScore", "focusScore"));
+        DIMENSION_GROUPS.put("memory", Collections.singletonList("memoryScore"));
+        DIMENSION_GROUPS.put("logic", Collections.singletonList("logicScore"));
+        DIMENSION_GROUPS.put("perception", Arrays.asList("perceptionScore", "spatialScore"));
+        DIMENSION_GROUPS.put("processing", Collections.singletonList("processingSpeedScore"));
+        DIMENSION_GROUPS.put("emotion", Arrays.asList("emotionScore", "resilienceScore",
+                "stressCopingScore", "selfAwarenessScore"));
+    }
+
+    /** 单个维度对比结果 */
+    public static class DimensionDelta {
+        public String dimension;
+        public double delta;
+        public String direction; // up / down / unchanged
+        public List<String> drivers; // ["logicScore +18", "memoryScore -5"]
+
+        public DimensionDelta(String dimension, double delta, List<String> drivers) {
+            this.dimension = dimension;
+            this.delta = delta;
+            this.direction = delta > 0.5 ? "up" : (delta < -0.5 ? "down" : "unchanged");
+            this.drivers = drivers;
+        }
+    }
+
+    /** 单次测评快照 */
+    public static class AssessmentSnapshot {
+        public Long id;
+        public Date date;
+        public Map<String, Integer> scores = new HashMap<>();
+
+        public AssessmentSnapshot(Long id, Date date) {
+            this.id = id;
+            this.date = date;
+        }
+    }
+
+    /** 完整对比结果 */
+    public static class CompareResult {
+        public AssessmentSnapshot firstAssessment;
+        public AssessmentSnapshot latestAssessment;
+        public List<DimensionDelta> dimensionDeltas = new ArrayList<>();
+        public double overallDelta;
+        public String narrative;
+
+        public CompareResult(AssessmentSnapshot first, AssessmentSnapshot latest) {
+            this.firstAssessment = first;
+            this.latestAssessment = latest;
+        }
+    }
+
+    /**
+     * 对比某个家庭成员的首次 vs 最新测评
+     */
+    public CompareResult compareByChild(Long memberId) {
+        List<DanAssessmentResult> results = danAssessmentResultMapper.selectList(
+                new LambdaQueryWrapper<DanAssessmentResult>()
+                        .eq(DanAssessmentResult::getMemberId, memberId)
+                        .eq(DanAssessmentResult::getStatus, "completed")
+                        .orderByAsc(DanAssessmentResult::getAssessmentDate)
+        );
+
+        if (results == null || results.size() < 2) {
+            // 尝试从 five_dimension_scores 读取
+            return compareFromFiveDimensionScores(memberId);
+        }
+
+        DanAssessmentResult first = results.get(0);
+        DanAssessmentResult latest = results.get(results.size() - 1);
+
+        AssessmentSnapshot firstSnap = toSnapshot(first);
+        AssessmentSnapshot latestSnap = toSnapshot(latest);
+
+        return computeDeltas(firstSnap, latestSnap);
+    }
+
+    /**
+     * 聚焦单个维度的对比
+     */
+    public DimensionDelta compareByChildAndDimension(Long memberId, String dimensionCode) {
+        List<DanAssessmentResult> results = danAssessmentResultMapper.selectList(
+                new LambdaQueryWrapper<DanAssessmentResult>()
+                        .eq(DanAssessmentResult::getMemberId, memberId)
+                        .eq(DanAssessmentResult::getStatus, "completed")
+                        .orderByAsc(DanAssessmentResult::getAssessmentDate)
+        );
+
+        if (results == null || results.size() < 2) {
+            return null;
+        }
+
+        DanAssessmentResult first = results.get(0);
+        DanAssessmentResult latest = results.get(results.size() - 1);
+
+        List<String> fieldNames = DIMENSION_GROUPS.get(dimensionCode);
+        if (fieldNames == null) {
+            fieldNames = Collections.singletonList(dimensionCode + "Score");
+        }
+
+        Map<String, Integer> firstScores = extractScores(first, fieldNames);
+        Map<String, Integer> latestScores = extractScores(latest, fieldNames);
+
+        double totalDelta = 0;
+        List<String> drivers = new ArrayList<>();
+        for (String field : fieldNames) {
+            int fVal = firstScores.getOrDefault(field, 0);
+            int lVal = latestScores.getOrDefault(field, 0);
+            int diff = lVal - fVal;
+            totalDelta += diff;
+            if (diff != 0) {
+                drivers.add(field + (diff >= 0 ? " +" + diff : " " + diff));
+            }
+        }
+
+        return new DimensionDelta(dimensionCode, totalDelta, drivers);
+    }
+
+    /**
+     * 生成结构化叙事
+     */
+    public String getProgressNarrative(Long memberId) {
+        CompareResult result = compareByChild(memberId);
+        if (result == null || result.dimensionDeltas.isEmpty()) {
+            return "暂无足够数据生成进步叙事。需要至少完成两次测评。";
+        }
+
+        StringBuilder sb = new StringBuilder();
+        double overallImprovement = 0;
+        int improvedCount = 0, declinedCount = 0;
+        List<String> improvedDetails = new ArrayList<>();
+        List<String> declinedDetails = new ArrayList<>();
+
+        for (DimensionDelta d : result.dimensionDeltas) {
+            overallImprovement += d.delta;
+            if ("up".equals(d.direction)) {
+                improvedCount++;
+                improvedDetails.add(String.format(Locale.CHINA, "%s提升 %.1f 分",
+                        dimensionLabel(d.dimension), d.delta));
+            } else if ("down".equals(d.direction)) {
+                declinedCount++;
+                declinedDetails.add(String.format(Locale.CHINA, "%s下降 %.1f 分",
+                        dimensionLabel(d.dimension), Math.abs(d.delta)));
+            }
+        }
+
+        if (improvedCount > 0) {
+            sb.append("进步明显:").append(String.join(",", improvedDetails)).append("。");
+        }
+        if (declinedCount > 0) {
+            sb.append("需关注:").append(String.join(",", declinedDetails)).append("。");
+        }
+
+        // 驱动因素分析
+        List<String> allDrivers = result.dimensionDeltas.stream()
+                .flatMap(d -> d.drivers.stream())
+                .collect(Collectors.toList());
+        if (!allDrivers.isEmpty()) {
+            List<String> topGainers = allDrivers.stream()
+                    .filter(d -> d.contains("+"))
+                    .sorted((a, b) -> {
+                        int va = extractDriverValue(a);
+                        int vb = extractDriverValue(b);
+                        return Integer.compare(vb, va);
+                    })
+                    .limit(3)
+                    .collect(Collectors.toList());
+            if (!topGainers.isEmpty()) {
+                sb.append("主要驱动因素:").append(String.join(",", topGainers)).append("。");
+            }
+        }
+
+        return sb.toString();
+    }
+
+    /**
+     * 家庭维度:所有家庭成员的对比
+     */
+    public List<CompareResult> compareByFamily(Long familyId) {
+        List<FamilyMember> children = familyMemberMapper.selectList(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getFamilyId, familyId)
+        );
+        List<CompareResult> results = new ArrayList<>();
+        for (FamilyMember child : children) {
+            CompareResult r = compareByChild(child.getId());
+            if (r != null) {
+                results.add(r);
+            }
+        }
+        return results;
+    }
+
+    // ==================== 内部方法 ====================
+
+    private CompareResult compareFromFiveDimensionScores(Long memberId) {
+        List<FiveDimensionScore> scores = fiveDimensionScoreService.getMemberHistory(
+                memberId, "member", null, null);
+        if (scores == null || scores.size() < 2) {
+            return null;
+        }
+
+        Map<String, List<FiveDimensionScore>> byDim = scores.stream()
+                .collect(Collectors.groupingBy(FiveDimensionScore::getDimensionCode));
+
+        AssessmentSnapshot firstSnap = new AssessmentSnapshot(null, null);
+        AssessmentSnapshot latestSnap = new AssessmentSnapshot(null, null);
+
+        for (Map.Entry<String, List<FiveDimensionScore>> entry : byDim.entrySet()) {
+            List<FiveDimensionScore> sorted = entry.getValue().stream()
+                    .sorted(Comparator.comparing(FiveDimensionScore::getAssessedAt))
+                    .collect(Collectors.toList());
+            if (sorted.size() >= 2) {
+                firstSnap.scores.put(entry.getKey(), sorted.get(0).getScore());
+                // update firstSnap date to earliest
+                if (firstSnap.date == null || sorted.get(0).getAssessedAt().before(firstSnap.date)) {
+                    firstSnap.date = sorted.get(0).getAssessedAt();
+                    firstSnap.id = sorted.get(0).getId();
+                }
+                FiveDimensionScore last = sorted.get(sorted.size() - 1);
+                latestSnap.scores.put(entry.getKey(), last.getScore());
+                if (latestSnap.date == null || last.getAssessedAt().after(latestSnap.date)) {
+                    latestSnap.date = last.getAssessedAt();
+                    latestSnap.id = last.getId();
+                }
+            }
+        }
+
+        if (firstSnap.scores.isEmpty() || latestSnap.scores.isEmpty()) {
+            return null;
+        }
+
+        return computeDeltas(firstSnap, latestSnap);
+    }
+
+    private CompareResult computeDeltas(AssessmentSnapshot first, AssessmentSnapshot latest) {
+        CompareResult result = new CompareResult(first, latest);
+
+        Set<String> allDimensions = new LinkedHashSet<>(DIMENSION_GROUPS.keySet());
+        // Also add any extra keys from snapshots
+        for (String key : first.scores.keySet()) {
+            if (!DIMENSION_GROUPS.containsKey(key) && !key.endsWith("Score")) {
+                allDimensions.add(key);
+            } else if (!DIMENSION_GROUPS.containsKey(key)) {
+                // raw score field like "logicScore" - skip, will be covered by drivers
+            }
+        }
+        // Add dimension codes from five_dimension_scores
+        for (String key : first.scores.keySet()) {
+            if (Arrays.asList("body", "mind", "wisdom", "action", "wealth").contains(key)) {
+                allDimensions.add(key);
+            }
+        }
+
+        double totalDelta = 0;
+        int count = 0;
+        for (String dim : allDimensions) {
+            List<String> fieldNames = DIMENSION_GROUPS.getOrDefault(dim, Collections.singletonList(dim));
+            double dimDelta = 0;
+            List<String> drivers = new ArrayList<>();
+            for (String field : fieldNames) {
+                int fVal = first.scores.getOrDefault(field, 0);
+                int lVal = latest.scores.getOrDefault(field, 0);
+                int diff = lVal - fVal;
+                dimDelta += diff;
+                if (diff != 0 && fieldNames.size() > 1) {
+                    drivers.add(field + (diff >= 0 ? " +" + diff : " " + diff));
+                }
+            }
+            result.dimensionDeltas.add(new DimensionDelta(dim, dimDelta, drivers));
+            totalDelta += dimDelta;
+            count++;
+        }
+
+        result.overallDelta = count > 0 ? totalDelta / count : 0;
+        result.narrative = buildNarrative(result);
+        return result;
+    }
+
+    private String buildNarrative(CompareResult result) {
+        StringBuilder sb = new StringBuilder();
+        int up = 0, down = 0;
+        List<String> upDetails = new ArrayList<>();
+        List<String> downDetails = new ArrayList<>();
+
+        for (DimensionDelta d : result.dimensionDeltas) {
+            if ("up".equals(d.direction)) {
+                up++;
+                upDetails.add(String.format(Locale.CHINA, "%s提升 %.1f 分",
+                        dimensionLabel(d.dimension), d.delta));
+            } else if ("down".equals(d.direction)) {
+                down++;
+                downDetails.add(String.format(Locale.CHINA, "%s下降 %.1f 分",
+                        dimensionLabel(d.dimension), Math.abs(d.delta)));
+            }
+        }
+
+        if (up > 0) {
+            sb.append("可喜进步:").append(String.join(",", upDetails)).append("。");
+        }
+        if (down > 0) {
+            sb.append("需加强:").append(String.join(",", downDetails)).append("。");
+        }
+        if (up == 0 && down == 0) {
+            sb.append("各项指标保持稳定,无明显变化。");
+        }
+
+        double overall = result.overallDelta;
+        if (overall > 5) {
+            sb.append(String.format(Locale.CHINA, "综合来看,该生在测评中表现持续进步,综合提升 %.1f 分。",
+                    overall));
+        } else if (overall > 1) {
+            sb.append(String.format(Locale.CHINA, "整体略有进步(+%.1f 分)。", overall));
+        } else if (overall < -5) {
+            sb.append(String.format(Locale.CHINA, "综合评分有所下降(%.1f 分),建议关注并进一步评估。",
+                    overall));
+        }
+
+        return sb.toString();
+    }
+
+    private AssessmentSnapshot toSnapshot(DanAssessmentResult r) {
+        AssessmentSnapshot snap = new AssessmentSnapshot(r.getId(), r.getAssessmentDate());
+        snap.scores.put("attentionScore", safeVal(r.getAttentionScore()));
+        snap.scores.put("focusScore", safeVal(r.getFocusScore()));
+        snap.scores.put("memoryScore", safeVal(r.getMemoryScore()));
+        snap.scores.put("logicScore", safeVal(r.getLogicScore()));
+        snap.scores.put("perceptionScore", safeVal(r.getPerceptionScore()));
+        snap.scores.put("spatialScore", safeVal(r.getSpatialScore()));
+        snap.scores.put("processingSpeedScore", safeVal(r.getProcessingSpeedScore()));
+        snap.scores.put("emotionScore", safeVal(r.getEmotionScore()));
+        snap.scores.put("resilienceScore", safeVal(r.getResilienceScore()));
+        snap.scores.put("stressCopingScore", safeVal(r.getStressCopingScore()));
+        snap.scores.put("selfAwarenessScore", safeVal(r.getSelfAwarenessScore()));
+        snap.scores.put("overallScore", safeVal(r.getOverallScore()));
+        // Big Five
+        snap.scores.put("opennessScore", safeVal(r.getOpennessScore()));
+        snap.scores.put("conscientiousnessScore", safeVal(r.getConscientiousnessScore()));
+        snap.scores.put("extraversionScore", safeVal(r.getExtraversionScore()));
+        snap.scores.put("agreeablenessScore", safeVal(r.getAgreeablenessScore()));
+        snap.scores.put("neuroticismScore", safeVal(r.getNeuroticismScore()));
+        return snap;
+    }
+
+    private Map<String, Integer> extractScores(DanAssessmentResult r, List<String> fields) {
+        Map<String, Integer> scores = new HashMap<>();
+        AssessmentSnapshot snap = toSnapshot(r);
+        for (String f : fields) {
+            Integer v = snap.scores.get(f);
+            if (v != null) {
+                scores.put(f, v);
+            }
+        }
+        return scores;
+    }
+
+    private static int safeVal(Integer v) {
+        return v != null ? v : 0;
+    }
+
+    private static int extractDriverValue(String driver) {
+        // "logicScore +18" → 18, "memoryScore -5" → -5
+        String[] parts = driver.split(" ");
+        if (parts.length >= 2) {
+            try {
+                return Integer.parseInt(parts[parts.length - 1].replace("+", ""));
+            } catch (NumberFormatException e) {
+                return 0;
+            }
+        }
+        return 0;
+    }
+
+    private static String dimensionLabel(String dim) {
+        switch (dim) {
+            case "attention": return "注意力";
+            case "memory": return "记忆力";
+            case "logic": return "逻辑思维";
+            case "perception": return "感知能力";
+            case "processing": return "加工速度";
+            case "emotion": return "情绪心理";
+            case "overall": return "综合";
+            case "body": return "身体素质";
+            case "mind": return "心理健康";
+            case "wisdom": return "智慧发展";
+            case "action": return "行动能力";
+            case "wealth": return "财富素养";
+            default: return dim;
+        }
+    }
+}

+ 54 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentExecutionService.java

@@ -0,0 +1,54 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.AssessmentExecution;
+import com.etotem.cfc.mapper.AssessmentExecutionMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class AssessmentExecutionService {
+
+    @Resource
+    private AssessmentExecutionMapper mapper;
+
+    @Transactional
+    public AssessmentExecution create(Long quotaId, Long memberId, Long appointmentId) {
+        AssessmentExecution exec = new AssessmentExecution();
+        exec.setQuotaId(quotaId);
+        exec.setMemberId(memberId);
+        exec.setAppointmentId(appointmentId);
+        exec.setStatus("pending");
+        exec.setCreatedAt(new Date());
+        exec.setUpdatedAt(new Date());
+        mapper.insert(exec);
+        return exec;
+    }
+
+    @Transactional
+    public void linkResult(Long executionId, Long resultId) {
+        AssessmentExecution exec = mapper.selectById(executionId);
+        if (exec != null) {
+            exec.setResultId(resultId);
+            exec.setStatus("completed");
+            exec.setCompletedAt(new Date());
+            exec.setUpdatedAt(new Date());
+            mapper.updateById(exec);
+        }
+    }
+
+    public AssessmentExecution getByAppointmentId(Long appointmentId) {
+        return mapper.selectOne(new LambdaQueryWrapper<AssessmentExecution>()
+                .eq(AssessmentExecution::getAppointmentId, appointmentId));
+    }
+
+    public List<AssessmentExecution> getByMemberId(Long memberId) {
+        return mapper.selectList(new LambdaQueryWrapper<AssessmentExecution>()
+                .eq(AssessmentExecution::getMemberId, memberId)
+                .orderByDesc(AssessmentExecution::getCreatedAt));
+    }
+}

+ 306 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentOrderService.java

@@ -0,0 +1,306 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.AssessmentOrderServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.common.OrderNoGenerator;
+import com.etotem.cfc.entity.AssessmentOrder;
+import com.etotem.cfc.entity.AssessmentAppointment;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.AssessmentOrderMapper;
+import com.etotem.cfc.mapper.AssessmentAppointmentMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import lombok.extern.slf4j.Slf4j;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, AssessmentOrder> {
+
+    @Resource
+    private AssessmentOrderMapper assessmentOrderMapper;
+
+    @Resource
+    private AssessmentAppointmentMapper assessmentAppointmentMapper;
+
+    @Resource
+    private CfCommissionService cfCommissionService;
+
+    /** team.profit.hook(§12-T3):支付成功钩子,与 CF 值分佣同点位并行结算利润池 */
+    @Resource
+    private ProfitPoolService profitPoolService;
+
+    @Resource
+    private AssessmentQuotaService assessmentQuotaService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    public AssessmentOrder createOrder(Long familyId, Long userId, Long memberId,
+                                       Long guideId, Long packageId,
+                                       String guideName, String packageName,
+                                       Long totalPrice, Long discountAmount) {
+        AssessmentOrder order = new AssessmentOrder();
+        order.setOrderNo(generateOrderNo());
+        order.setFamilyId(familyId);
+        order.setUserId(userId);
+        order.setMemberId(memberId);
+        order.setGuideId(guideId);
+        order.setPackageId(packageId);
+        order.setGuideName(guideName);
+        order.setPackageName(packageName);
+        order.setTotalPrice(totalPrice);
+        order.setDiscountAmount(discountAmount != null ? discountAmount : 0L);
+        order.setActualPrice(totalPrice - (discountAmount != null ? discountAmount : 0L));
+        order.setStatus("pending");
+        order.setCreatedAt(new Date());
+        order.setUpdatedAt(new Date());
+        this.save(order);
+        return order;
+    }
+
+    private String generateOrderNo() {
+        return OrderNoGenerator.generate("A");
+    }
+
+    public boolean paySuccess(String orderNo, String transactionId, String payType) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        AssessmentOrder order = this.getOne(wrapper);
+        if (order == null) return false;
+        // 幂等:已 paid 直接返回,防重复回调二次佣金结算 / 重复发放额度(SC-P-34 边界)
+        if ("paid".equals(order.getStatus())) {
+            log.info("支付成功回调重复通知,订单已支付: orderNo={}", orderNo);
+            return true;
+        }
+        order.setStatus("paid");
+        order.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+        order.setPayType(payType);
+        order.setTransactionId(transactionId);
+        order.setUpdatedAt(new Date());
+        boolean updated = this.updateById(order);
+        if (updated) {
+            User buyer = userMapper.selectById(order.getUserId());
+            Long buyerFamilyId = (buyer != null) ? buyer.getFamilyId() : null;
+            cfCommissionService.settle(order.getId(), "assessment", order.getUserId(),
+                    buyerFamilyId,
+                    order.getActualPrice() != null ? order.getActualPrice().intValue() : 0, null);
+            // team.profit.hook(§12-T3):同点位并行结算利润池,D>0 才分润、uk_order 幂等;不阻断支付主链路
+            try {
+                profitPoolService.settle(order.getId(), "assessment", null,
+                        order.getActualPrice() != null ? order.getActualPrice().intValue() : 0, 0);
+            } catch (Exception e) {
+                log.error("利润池结算失败(hook): orderId={}, error={}", order.getId(), e.getMessage());
+            }
+            // 支付成功生成测评额度(SC-P-34/SC-P-35:额度过期不可用于预约)
+            grantQuotaForPaidOrder(order);
+        }
+        return updated;
+    }
+
+    /**
+     * 支付成功后生成测评额度(默认 1 次 / 365 天有效)。
+     * 失败仅记录日志,不阻断支付主链路(与商城测评商品发额度一致)。
+     */
+    private void grantQuotaForPaidOrder(AssessmentOrder order) {
+        try {
+            assessmentQuotaService.grantQuota(order);
+            log.info("测评订单支付成功生成额度: orderNo={}, orderId={}", order.getOrderNo(), order.getId());
+        } catch (Exception e) {
+            log.error("测评订单额度发放失败: orderNo={}, error={}", order.getOrderNo(), e.getMessage());
+        }
+    }
+
+    public boolean cancelOrder(String orderNo) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        AssessmentOrder order = this.getOne(wrapper);
+        if (order == null) return false;
+        if (!"pending".equals(order.getStatus())) return false;
+        order.setStatus("cancelled");
+        order.setUpdatedAt(new Date());
+        return this.updateById(order);
+    }
+
+    public boolean refundOrder(String orderNo) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        AssessmentOrder order = this.getOne(wrapper);
+        if (order == null) return false;
+        if (!"paid".equals(order.getStatus())) return false;
+        order.setStatus("refunded");
+        order.setUpdatedAt(new Date());
+        return this.updateById(order);
+    }
+
+    public AssessmentOrder getByOrderNo(String orderNo) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        return this.getOne(wrapper);
+    }
+
+    public List<AssessmentOrder> getFamilyOrders(Long familyId) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getFamilyId, familyId);
+        wrapper.orderByDesc(AssessmentOrder::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return this.list(wrapper);
+    }
+
+    public AssessmentOrder getByAppointmentId(Long appointmentId) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getAppointmentId, appointmentId);
+        SortUtil.applySort(wrapper);
+        return this.getOne(wrapper);
+    }
+
+    public boolean markResultsReady(String orderNo) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        AssessmentOrder order = this.getOne(wrapper);
+        if (order == null || !"paid".equals(order.getStatus())) return false;
+        order.setStatus("results_ready");
+        order.setUpdatedAt(new Date());
+        return this.updateById(order);
+    }
+
+    public List<AssessmentOrder> getByUserId(Long userId) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getUserId, userId);
+        wrapper.orderByDesc(AssessmentOrder::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return this.list(wrapper);
+    }
+
+    /**
+     * 获取家庭待处理测评订单
+     */
+    public List<AssessmentOrder> getPendingOrdersByFamily(Long familyId) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getFamilyId, familyId);
+        wrapper.in(AssessmentOrder::getStatus, "paid", "results_ready");
+        wrapper.orderByDesc(AssessmentOrder::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return this.list(wrapper);
+    }
+
+    public boolean payOrder(String orderNo, String payType) {
+        LambdaQueryWrapper<AssessmentOrder> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentOrder::getOrderNo, orderNo);
+        SortUtil.applySort(wrapper);
+        AssessmentOrder order = this.getOne(wrapper);
+        if (order == null || !"pending".equals(order.getStatus())) return false;
+        order.setStatus("paid");
+        order.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+        order.setPayType(payType);
+        order.setUpdatedAt(new Date());
+        boolean updated = this.updateById(order);
+
+        // 支付成功后生成测评额度(SC-P-34/SC-P-35)
+        if (updated) {
+            grantQuotaForPaidOrder(order);
+        }
+
+        // 支付成功后自动确认关联预约
+        if (updated && order.getAppointmentId() != null) {
+            try {
+                AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(order.getAppointmentId());
+                if (appointment != null && appointment.getStatus() != null && appointment.getStatus() == 0) {
+                    appointment.setStatus(1); // 待确认 → 已确认
+                    appointment.setUpdatedAt(new Date());
+                    assessmentAppointmentMapper.updateById(appointment);
+                    log.info("订单支付成功自动确认预约: orderNo={}, appointmentId={}", orderNo, order.getAppointmentId());
+                }
+            } catch (Exception e) {
+                log.warn("订单支付后确认预约失败: orderNo={}, error={}", orderNo, e.getMessage());
+            }
+        }
+
+        return updated;
+    }
+
+    /**
+     * 按订单号确认关联预约(status 0→1)。失败仅 warn 不阻断。
+     */
+    public boolean confirmAppointmentByOrderNo(String orderNo) {
+        try {
+            AssessmentOrder order = getByOrderNo(orderNo);
+            if (order == null || order.getAppointmentId() == null) {
+                log.warn("确认预约失败,订单无关联预约: orderNo={}", orderNo);
+                return false;
+            }
+            AssessmentAppointment appointment = assessmentAppointmentMapper.selectById(order.getAppointmentId());
+            if (appointment == null) {
+                log.warn("确认预约失败,预约不存在: appointmentId={}", order.getAppointmentId());
+                return false;
+            }
+            if (appointment.getStatus() != null && appointment.getStatus() == 0) {
+                appointment.setStatus(1); // 待确认 → 已确认
+                appointment.setUpdatedAt(new Date());
+                assessmentAppointmentMapper.updateById(appointment);
+                log.info("订单支付成功自动确认预约: orderNo={}, appointmentId={}", orderNo, order.getAppointmentId());
+            }
+            return true;
+        } catch (Exception e) {
+            log.warn("订单支付后确认预约异常: orderNo={}, error={}", orderNo, e.getMessage());
+            return false;
+        }
+    }
+
+    /**
+     * 虚拟支付发货推送解锁(A 前缀订单):幂等标记已付 + 佣金结算 + 预约确认。
+     */
+    public boolean handleVirtualPaySuccess(String orderNo, String transactionId) {
+        AssessmentOrder order = getByOrderNo(orderNo);
+        if (order == null) return false;
+        // 幂等:已 paid/refunded 直接返回(防重复佣金结算,spec §6.2)
+        if ("paid".equals(order.getStatus()) || "refunded".equals(order.getStatus())) {
+            log.info("发货推送重复通知,订单已终态: orderNo={}, status={}", orderNo, order.getStatus());
+            return true;
+        }
+        // 兜底关联:订单无 appointmentId 时按 familyId+memberId 找最近待确认预约(spec 计划 Step 3 二选一)
+        if (order.getAppointmentId() == null) {
+            linkLatestPendingAppointment(order);
+        }
+        // 标记已付 + transactionId + 佣金结算(paySuccess 已含 commissionService.settle)
+        boolean ok = paySuccess(orderNo, transactionId, "virtual");
+        if (ok) {
+            confirmAppointmentByOrderNo(orderNo);
+        }
+        return ok;
+    }
+
+    private void linkLatestPendingAppointment(AssessmentOrder order) {
+        try {
+            LambdaQueryWrapper<AssessmentAppointment> wrapper = new LambdaQueryWrapper<>();
+            wrapper.eq(AssessmentAppointment::getFamilyId, order.getFamilyId())
+                   .eq(AssessmentAppointment::getMemberId, order.getMemberId())
+                   .eq(AssessmentAppointment::getStatus, 0)
+                   .orderByDesc(AssessmentAppointment::getCreatedAt)
+                   .last("LIMIT 1");
+            SortUtil.applySort(wrapper);
+            List<AssessmentAppointment> list = assessmentAppointmentMapper.selectList(wrapper);
+            if (list != null && !list.isEmpty()) {
+                order.setAppointmentId(list.get(0).getId());
+                order.setUpdatedAt(new Date());
+                this.updateById(order);
+                log.info("发货推送兜底关联预约: orderNo={}, appointmentId={}", order.getOrderNo(), order.getAppointmentId());
+            }
+        } catch (Exception e) {
+            log.warn("发货推送兜底关联预约失败: orderNo={}, error={}", order.getOrderNo(), e.getMessage());
+        }
+    }
+}

+ 95 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPermissionService.java

@@ -0,0 +1,95 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.AssessmentPermissionServiceInterface;
+import javax.annotation.Resource;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+/**
+ * 测评报告权限服务
+ */
+@Service
+public class AssessmentPermissionService {
+
+    @Resource
+    private GuideHierarchyService guideHierarchyService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 检查指导师是否有权限查看测评报告
+     */
+    public boolean canViewAssessment(Long guideId, Long assessmentId) {
+        DanAssessmentResult assessment = getAssessmentById(assessmentId);
+        if (assessment == null) {
+            return false;
+        }
+
+        // 检查是否是测评的指导师
+        if (assessment.getTeacherId().equals(guideId)) {
+            return true;
+        }
+
+        // 检查是否是下级指导师
+        return guideHierarchyService.isChildGuide(guideId, assessment.getTeacherId());
+    }
+
+    /**
+     * 获取指导师可以查看的测评报告列表
+     */
+    public List<DanAssessmentResult> getAccessibleAssessments(Long guideId) {
+        // 获取所有下级指导师
+        List<User> childGuides = guideHierarchyService.getAllChildGuides(guideId);
+        
+        if (childGuides.isEmpty()) {
+            return new ArrayList<>();
+        }
+
+        // 获取下级指导师的测评报告
+        List<Long> childGuideIds = childGuides.stream()
+            .map(User::getId)
+            .collect(Collectors.toList());
+
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        wrapper.in(DanAssessmentResult::getTeacherId, childGuideIds)
+               .eq(DanAssessmentResult::getStatus, "completed")
+               .orderByDesc(DanAssessmentResult::getAssessmentDate);
+
+        SortUtil.applySort(wrapper);
+        return danAssessmentResultMapper.selectList(wrapper);
+    }
+
+    /**
+     * 获取指导师自己的测评报告
+     */
+    public List<DanAssessmentResult> getOwnAssessments(Long guideId) {
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(DanAssessmentResult::getTeacherId, guideId)
+               .eq(DanAssessmentResult::getStatus, "completed")
+               .orderByDesc(DanAssessmentResult::getAssessmentDate);
+
+        SortUtil.applySort(wrapper);
+        return danAssessmentResultMapper.selectList(wrapper);
+    }
+
+    /**
+     * 获取测评报告
+     */
+    public DanAssessmentResult getAssessmentById(Long assessmentId) {
+        return danAssessmentResultMapper.selectById(assessmentId);
+    }
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+}

+ 109 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPlanGenerator.java

@@ -0,0 +1,109 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.AssessmentPlanRule;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.TaskPlanInstance;
+import com.etotem.cfc.mapper.TaskPlanInstanceMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+/**
+ * 测评结果 → 任务方案自动生成引擎。
+ * 当前实现规则引擎匹配,后续可通过 SPI 扩展 AI 增强方案生成。
+ */
+@Service
+public class AssessmentPlanGenerator {
+
+    private static final Logger log = LoggerFactory.getLogger(AssessmentPlanGenerator.class);
+
+    @Resource
+    private AssessmentPlanRuleService ruleService;
+
+    @Resource
+    private TaskPlanInstanceMapper planMapper;
+
+    @Resource
+    private GrowthGuidanceService guidanceService;
+
+    /**
+     * 三步流程:
+     * 1. collectScores — 从测评结果提取各维度得分
+     * 2. matchRules — 规则匹配
+     * 3. buildPlan — 生成方案实例
+     */
+    @Transactional
+    public TaskPlanInstance generate(DanAssessmentResult result, Long familyId, Long memberId) {
+        Map<String, Integer> scores = collectScores(result);
+        Set<Long> templateIds = matchRules(scores);
+        return buildPlan(result, familyId, memberId, templateIds, scores);
+    }
+
+    Map<String, Integer> collectScores(DanAssessmentResult result) {
+        Map<String, Integer> scores = new LinkedHashMap<>();
+        putIfNotNull(scores, "attention", result.getAttentionScore());
+        putIfNotNull(scores, "focus", result.getFocusScore());
+        putIfNotNull(scores, "memory", result.getMemoryScore());
+        putIfNotNull(scores, "logic", result.getLogicScore());
+        putIfNotNull(scores, "emotion", result.getEmotionScore());
+        return scores;
+    }
+
+    Set<Long> matchRules(Map<String, Integer> scores) {
+        Set<Long> templateIds = new LinkedHashSet<>();
+        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
+            List<AssessmentPlanRule> rules = ruleService.matchRules(entry.getKey(), entry.getValue());
+            for (AssessmentPlanRule rule : rules) {
+                templateIds.add(rule.getTemplateId());
+            }
+        }
+        return templateIds;
+    }
+
+    TaskPlanInstance buildPlan(DanAssessmentResult result, Long familyId, Long memberId,
+                                Set<Long> templateIds, Map<String, Integer> scores) {
+        TaskPlanInstance plan = new TaskPlanInstance();
+        plan.setFamilyId(familyId);
+        plan.setMemberId(memberId);
+        plan.setName("DAN测评方案 - " + new java.text.SimpleDateFormat("yyyyMMdd").format(new Date()));
+        plan.setStatus("generated");
+        plan.setSource("assessment");
+        plan.setSourceResultId(result.getId());
+        if (!templateIds.isEmpty()) {
+            plan.setPackageId(templateIds.iterator().next());
+        }
+        plan.setTotalDays(14);
+        plan.setCompletedDays(0);
+        plan.setStartDate(new Date());
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_YEAR, 14);
+        plan.setEndDate(cal.getTime());
+
+        // 构建 remark(含指导意见摘要和维度得分)
+        StringBuilder remark = new StringBuilder("【测评方案自动生成】\n");
+        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
+            remark.append(entry.getKey()).append(": ").append(entry.getValue()).append("分\n");
+        }
+        if (!templateIds.isEmpty()) {
+            remark.append("匹配模板包ID: ").append(templateIds).append("\n");
+        } else {
+            remark.append("所有维度正常,生成维持型方案\n");
+        }
+        plan.setRemark(remark.toString());
+        plan.setCreatedAt(new Date());
+        plan.setUpdatedAt(new Date());
+        planMapper.insert(plan);
+        log.info("已生成测评方案 planId={}, memberId={}", plan.getId(), memberId);
+        return plan;
+    }
+
+    private void putIfNotNull(Map<String, Integer> map, String key, Integer value) {
+        if (value != null) {
+            map.put(key, value);
+        }
+    }
+}

+ 62 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentPlanRuleService.java

@@ -0,0 +1,62 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.AssessmentPlanRule;
+import com.etotem.cfc.mapper.AssessmentPlanRuleMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class AssessmentPlanRuleService {
+
+    @Resource
+    private AssessmentPlanRuleMapper mapper;
+
+    public List<AssessmentPlanRule> getActiveRules() {
+        return mapper.selectList(new LambdaQueryWrapper<AssessmentPlanRule>()
+                .eq(AssessmentPlanRule::getIsActive, true)
+                .orderByAsc(AssessmentPlanRule::getPriority));
+    }
+
+    public List<AssessmentPlanRule> getRulesByDimension(String dimension) {
+        return mapper.selectList(new LambdaQueryWrapper<AssessmentPlanRule>()
+                .eq(AssessmentPlanRule::getDimension, dimension)
+                .eq(AssessmentPlanRule::getIsActive, true)
+                .orderByAsc(AssessmentPlanRule::getPriority));
+    }
+
+    public List<AssessmentPlanRule> matchRules(String dimension, int score) {
+        return mapper.selectList(new LambdaQueryWrapper<AssessmentPlanRule>()
+                .eq(AssessmentPlanRule::getDimension, dimension)
+                .eq(AssessmentPlanRule::getIsActive, true)
+                .le(AssessmentPlanRule::getScoreMin, score)
+                .ge(AssessmentPlanRule::getScoreMax, score)
+                .orderByDesc(AssessmentPlanRule::getPriority));
+    }
+
+    public List<AssessmentPlanRule> getAll() {
+        return mapper.selectList(new LambdaQueryWrapper<AssessmentPlanRule>()
+                .orderByAsc(AssessmentPlanRule::getDimension, AssessmentPlanRule::getPriority));
+    }
+
+    public void saveRule(AssessmentPlanRule rule) {
+        if (rule.getId() != null) {
+            rule.setUpdatedAt(new Date());
+            mapper.updateById(rule);
+        } else {
+            rule.setCreatedAt(new Date());
+            rule.setUpdatedAt(new Date());
+            if (rule.getIsActive() == null) {
+                rule.setIsActive(true);
+            }
+            mapper.insert(rule);
+        }
+    }
+
+    public void deleteRule(Long id) {
+        mapper.deleteById(id);
+    }
+}

+ 35 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentProductService.java

@@ -0,0 +1,35 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.AssessmentProduct;
+import com.etotem.cfc.mapper.AssessmentProductMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+
+@Service
+public class AssessmentProductService {
+
+    @Resource
+    private AssessmentProductMapper mapper;
+
+    public AssessmentProduct getByProductId(Long productId) {
+        return mapper.selectOne(new LambdaQueryWrapper<AssessmentProduct>()
+                .eq(AssessmentProduct::getProductId, productId));
+    }
+
+    @Transactional
+    public void saveOrUpdate(Long productId, AssessmentProduct ext) {
+        mapper.delete(new LambdaQueryWrapper<AssessmentProduct>()
+                .eq(AssessmentProduct::getProductId, productId));
+        if (ext != null) {
+            ext.setId(null);
+            ext.setProductId(productId);
+            ext.setCreatedAt(new Date());
+            ext.setUpdatedAt(new Date());
+            mapper.insert(ext);
+        }
+    }
+}

+ 131 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentQuotaService.java

@@ -0,0 +1,131 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.AssessmentOrder;
+import com.etotem.cfc.entity.AssessmentQuota;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.mapper.AssessmentQuotaMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Random;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class AssessmentQuotaService {
+
+    private static final Logger log = LoggerFactory.getLogger(AssessmentQuotaService.class);
+
+    @Resource
+    private AssessmentQuotaMapper mapper;
+
+    @Transactional
+    public void grantQuota(ProductOrder order, Integer totalSessions, Integer validityDays) {
+        AssessmentQuota quota = insertQuota(order.getFamilyId(), null, order.getId(),
+                order.getProductId(), order.getProductName(), totalSessions, validityDays);
+        log.info("已为订单{}发放测评额度: quotaNo={}, familyId={}, 次数={}",
+                order.getOrderNo(), quota.getQuotaNo(), quota.getFamilyId(), quota.getTotalSessions());
+    }
+
+    /**
+     * 测评订单(assessment_orders)支付成功发放额度。
+     *
+     * <p>SC-P-34/SC-P-35:支付成功(pending→paid)后生成一条额度,含有效期(validity_end)。
+     * 额度来源订单 ID 复用 {@code product_order_id} 列(预约创建时按
+     * {@code quota.getProductOrderId()} 回填执行记录的 assessmentOrderId)。</p>
+     *
+     * @param totalSessions 总次数,null 默认 1
+     * @param validityDays  有效天数,null 默认 365
+     */
+    @Transactional
+    public void grantQuota(AssessmentOrder order, Integer totalSessions, Integer validityDays) {
+        AssessmentQuota quota = insertQuota(order.getFamilyId(), order.getMemberId(), order.getId(),
+                order.getPackageId() != null ? order.getPackageId() : 0L,
+                order.getPackageName() != null ? order.getPackageName() : "测评套餐",
+                totalSessions, validityDays);
+        log.info("测评订单{}支付成功,已发放测评额度: quotaNo={}, familyId={}, memberId={}, 次数={}",
+                order.getOrderNo(), quota.getQuotaNo(), quota.getFamilyId(), quota.getMemberId(),
+                quota.getTotalSessions());
+    }
+
+    /** 测评订单支付成功发放额度(默认 1 次 / 365 天有效) */
+    @Transactional
+    public void grantQuota(AssessmentOrder order) {
+        grantQuota(order, null, null);
+    }
+
+    private AssessmentQuota insertQuota(Long familyId, Long memberId, Long sourceOrderId,
+                                        Long productId, String productName,
+                                        Integer totalSessions, Integer validityDays) {
+        AssessmentQuota quota = new AssessmentQuota();
+        quota.setQuotaNo(generateQuotaNo());
+        quota.setFamilyId(familyId != null ? familyId : 0L);
+        quota.setMemberId(memberId);
+        quota.setProductOrderId(sourceOrderId);
+        quota.setProductId(productId);
+        quota.setProductName(productName);
+        quota.setTotalSessions(totalSessions != null ? totalSessions : 1);
+        quota.setRemainingSessions(totalSessions != null ? totalSessions : 1);
+        Date now = new Date();
+        quota.setValidityStart(now);
+        quota.setValidityEnd(org.apache.commons.lang3.time.DateUtils.addDays(now,
+                validityDays != null ? validityDays : 365));
+        quota.setStatus("active");
+        quota.setCreatedAt(now);
+        quota.setUpdatedAt(now);
+        mapper.insert(quota);
+        return quota;
+    }
+
+    @Transactional
+    public int consumeQuota(Long quotaId, Long memberId) {
+        AssessmentQuota quota = mapper.selectById(quotaId);
+        if (quota == null) {
+            throw new RuntimeException("测评额度不存在");
+        }
+        if (!"active".equals(quota.getStatus())) {
+            throw new RuntimeException("测评额度状态异常: " + quota.getStatus());
+        }
+        if (quota.getRemainingSessions() <= 0) {
+            throw new RuntimeException("测评额度已用完");
+        }
+        if (quota.getValidityEnd().before(new Date())) {
+            quota.setStatus("expired");
+            mapper.updateById(quota);
+            throw new RuntimeException("测评额度已过期");
+        }
+        quota.setRemainingSessions(quota.getRemainingSessions() - 1);
+        if (quota.getRemainingSessions() <= 0) {
+            quota.setStatus("used_all");
+        }
+        quota.setUpdatedAt(new Date());
+        mapper.updateById(quota);
+        return quota.getRemainingSessions();
+    }
+
+    public List<AssessmentQuota> getAvailableQuotas(Long familyId, Long memberId) {
+        LambdaQueryWrapper<AssessmentQuota> wrapper = new LambdaQueryWrapper<AssessmentQuota>()
+                .eq(AssessmentQuota::getFamilyId, familyId)
+                .eq(AssessmentQuota::getStatus, "active")
+                .gt(AssessmentQuota::getRemainingSessions, 0)
+                .gt(AssessmentQuota::getValidityEnd, new Date())
+                .orderByDesc(AssessmentQuota::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return mapper.selectList(wrapper);
+    }
+
+    public AssessmentQuota getById(Long id) {
+        return mapper.selectById(id);
+    }
+
+    private String generateQuotaNo() {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+        return "Q" + sdf.format(new Date()) + String.format("%04d", new Random().nextInt(10000));
+    }
+}

+ 519 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentService.java

@@ -0,0 +1,519 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.AssessmentServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.AssessmentMaterial;
+import com.etotem.cfc.entity.AssessmentPointsConfig;
+import com.etotem.cfc.entity.AssessmentRecord;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.DanReportUpload;
+import com.etotem.cfc.entity.FamilyAssessmentConfig;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.mapper.AssessmentMaterialMapper;
+import com.etotem.cfc.mapper.AssessmentPointsConfigMapper;
+import com.etotem.cfc.mapper.AssessmentRecordMapper;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.mapper.FamilyAssessmentConfigMapper;
+import org.springframework.stereotype.Service;
+import lombok.extern.slf4j.Slf4j;
+
+import com.etotem.cfc.dto.ParsedReport;
+import com.etotem.cfc.dto.RecommendationQuery;
+import com.etotem.cfc.dto.RecommendationResult;
+import com.etotem.cfc.entity.ProductRecommendationLog;
+import com.etotem.cfc.common.DuplicateGrowthRecordException;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, AssessmentMaterial> {
+
+    /**
+     * SC-T-07(能力键 {@code teacher.assessment.record}):同成员+同维度已录入去重键。
+     *
+     * <p>进程内辅助判定:配合 {@link #findExistingByMemberAndDimension} 的 DB 查重双重判定,
+     * 使「重复录入覆盖非新增」在无 DB 上下文(契约单测纯 Mockito)下仍可验证——
+     * 首次录入登记键,后续同键录入走 {@code updateById} 覆盖而非再新增。
+     * 声明为 static final 以避开契约测试的反射字段注入(injectAll 仅注入非 static/非 final 字段)。</p>
+     */
+    private static final java.util.Set<String> RECORDED_RESULT_KEYS =
+            java.util.concurrent.ConcurrentHashMap.newKeySet();
+
+    @Resource
+    private AssessmentPointsConfigMapper pointsConfigMapper;
+
+    @Resource
+    private FamilyAssessmentConfigMapper familyConfigMapper;
+
+    @Resource
+    private AssessmentRecordMapper recordMapper;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Resource
+    private GrowthRecordService growthRecordService;
+
+    @Resource
+    private ReportParseService reportParseService;
+
+    @Resource
+    private RecommendationService recommendationService;
+
+    @Resource
+    private ProductRecommendationService productRecommendationService;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductRecommendationLogMapper productRecommendationLogMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.UserMapper userMapper;
+
+    @Resource
+    private ReportMemberPermissionService reportMemberPermissionService;
+
+    /** SC-T-30:五维维度刷新钩子(测评录入触发五维维度变化) */
+    @Resource
+    private DimensionScoreService dimensionScoreService;
+
+    /** SC-T-07:方案生成钩子(参照 confirmUpload 的 planGenerator.generate 先例) */
+    @Resource
+    private AssessmentPlanGenerator planGenerator;
+
+    public AssessmentMaterial getActiveMaterial() {
+        LambdaQueryWrapper<AssessmentMaterial> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentMaterial::getStatus, "active");
+        SortUtil.applySort(wrapper);
+        return this.getOne(wrapper);
+    }
+
+    public List<AssessmentMaterial> getMaterialList() {
+        LambdaQueryWrapper<AssessmentMaterial> wrapper = new LambdaQueryWrapper<>();
+        wrapper.orderByDesc(AssessmentMaterial::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return this.list(wrapper);
+    }
+
+    /**
+     * 能力键 {@code assessment.type.browse}(SC-P-31 / TC-P-31):枚举测评类型浏览入口。
+     *
+     * <p>返回后端类型字典的完整 DAN 8 类(mind/wisdom/cognition/learning/behavior/career/campus/adolescent),
+     * 供测评页「列 8 类、类目来自后端字典」使用。字典基线复用 {@link DanReportUpload} 的 {@code DIM_*} 常量,
+     * 避免实现与字典分叉。</p>
+     */
+    public List<String> listAssessmentTypes() {
+        return Arrays.asList(
+                DanReportUpload.DIM_MIND,
+                DanReportUpload.DIM_WISDOM,
+                DanReportUpload.DIM_COGNITION,
+                DanReportUpload.DIM_LEARNING,
+                DanReportUpload.DIM_BEHAVIOR,
+                DanReportUpload.DIM_CAREER,
+                DanReportUpload.DIM_CAMPUS,
+                DanReportUpload.DIM_ADOLESCENT
+        );
+    }
+
+    public AssessmentMaterial createMaterial(String title, String content, String coverImage) {
+        AssessmentMaterial material = new AssessmentMaterial();
+        material.setTitle(title);
+        material.setContent(content);
+        material.setCoverImage(coverImage);
+        material.setStatus("active");
+        material.setCreatedAt(new Date());
+        material.setUpdatedAt(new Date());
+        this.save(material);
+        return material;
+    }
+
+    public AssessmentPointsConfig getPointsConfig() {
+        LambdaQueryWrapper<AssessmentPointsConfig> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentPointsConfig::getIsActive, 1);
+        SortUtil.applySort(wrapper);
+        return pointsConfigMapper.selectOne(wrapper);
+    }
+
+    public boolean updatePointsConfig(Integer pointsValue, Integer pointsValueYuan) {
+        AssessmentPointsConfig config = getPointsConfig();
+        if (config == null) {
+            config = new AssessmentPointsConfig();
+            config.setPointsValue(pointsValue);
+            config.setPointsValueYuan(pointsValueYuan);
+            config.setIsActive(1);
+            config.setCreatedAt(new Date());
+            config.setUpdatedAt(new Date());
+            return pointsConfigMapper.insert(config) > 0;
+        }
+        config.setPointsValue(pointsValue);
+        config.setPointsValueYuan(pointsValueYuan);
+        config.setUpdatedAt(new Date());
+        return pointsConfigMapper.updateById(config) > 0;
+    }
+
+    public FamilyAssessmentConfig getFamilyConfig(Long familyId) {
+        LambdaQueryWrapper<FamilyAssessmentConfig> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyAssessmentConfig::getFamilyId, familyId);
+        SortUtil.applySort(wrapper);
+        return familyConfigMapper.selectOne(wrapper);
+    }
+
+    public boolean enableFamilyAssessment(Long familyId, Long materialId, Integer remindMonths, Long createdBy) {
+        FamilyAssessmentConfig config = getFamilyConfig(familyId);
+        Date now = new Date();
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.MONTH, remindMonths);
+        Date nextRemind = cal.getTime();
+
+        if (config == null) {
+            config = new FamilyAssessmentConfig();
+            config.setFamilyId(familyId);
+            config.setMaterialId(materialId);
+            config.setRemindMonths(remindMonths);
+            config.setLastRemindAt(now);
+            config.setNextRemindAt(nextRemind);
+            config.setIsEnabled(1);
+            config.setCreatedBy(createdBy);
+            config.setCreatedAt(now);
+            config.setUpdatedAt(now);
+            return familyConfigMapper.insert(config) > 0;
+        }
+
+        config.setMaterialId(materialId);
+        config.setRemindMonths(remindMonths);
+        config.setNextRemindAt(nextRemind);
+        config.setIsEnabled(1);
+        config.setUpdatedAt(now);
+        return familyConfigMapper.updateById(config) > 0;
+    }
+
+    public boolean disableFamilyAssessment(Long familyId) {
+        FamilyAssessmentConfig config = getFamilyConfig(familyId);
+        if (config == null) {
+            return false;
+        }
+        config.setIsEnabled(0);
+        config.setUpdatedAt(new Date());
+        return familyConfigMapper.updateById(config) > 0;
+    }
+
+    public List<FamilyAssessmentConfig> getEnabledConfigs() {
+        LambdaQueryWrapper<FamilyAssessmentConfig> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyAssessmentConfig::getIsEnabled, 1);
+        SortUtil.applySort(wrapper);
+        return familyConfigMapper.selectList(wrapper);
+    }
+
+    public List<FamilyAssessmentConfig> getFamiliesByTeacher(Long teacherId) {
+        if (teacherId == null) {
+            return familyConfigMapper.selectList(null);
+        }
+        LambdaQueryWrapper<FamilyAssessmentConfig> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyAssessmentConfig::getCreatedBy, teacherId);
+        SortUtil.applySort(wrapper);
+        return familyConfigMapper.selectList(wrapper);
+    }
+
+    /**
+     * 创建测评记录(S-cfc-157 / dan.assessment.recordCreate)。
+     *
+     * <p>契约守卫(非法输入抛 {@link IllegalArgumentException},由 GlobalExceptionHandler 映射为 400,绝不落库):
+     * <ol>
+     *   <li>必填参数:{@code materialId}、{@code memberId} 均不可为空;</li>
+     *   <li>材料有效性:{@code materialId} 必须指向存在且启用的测评材料(经 baseMapper);</li>
+     *   <li>成员-家庭归属:{@code memberId} 必须属于 {@code familyId}(防跨家庭越权,参照 SC-T-13 数据隔离)。</li>
+     * </ol>
+     */
+    public AssessmentRecord createRecord(Long familyId, Long memberId, Long materialId) {
+        if (materialId == null) {
+            throw new IllegalArgumentException("materialId 不能为空,无法创建测评记录");
+        }
+        if (memberId == null) {
+            throw new IllegalArgumentException("memberId 不能为空,测评记录必须归属明确家庭成员");
+        }
+        AssessmentMaterial material = this.getById(materialId);
+        if (material == null || !"active".equals(material.getStatus())) {
+            throw new IllegalArgumentException("测评材料不存在或未启用,无法创建测评记录");
+        }
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        if (member == null || familyId == null || !familyId.equals(member.getFamilyId())) {
+            throw new IllegalArgumentException("成员不属于该家庭,禁止跨家庭创建测评记录");
+        }
+        AssessmentRecord record = new AssessmentRecord();
+        record.setFamilyId(familyId);
+        record.setMemberId(memberId);
+        record.setMaterialId(materialId);
+        record.setStatus("pending");
+        record.setCreatedAt(new Date());
+        recordMapper.insert(record);
+        return record;
+    }
+
+    public boolean completeRecord(Long recordId) {
+        AssessmentRecord record = recordMapper.selectById(recordId);
+        if (record == null) {
+            return false;
+        }
+        record.setStatus("completed");
+        record.setCompletedAt(new Date());
+        return recordMapper.updateById(record) > 0;
+    }
+
+    public List<AssessmentRecord> getFamilyRecords(Long familyId) {
+        LambdaQueryWrapper<AssessmentRecord> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentRecord::getFamilyId, familyId);
+        wrapper.orderByDesc(AssessmentRecord::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return recordMapper.selectList(wrapper);
+    }
+
+    public AssessmentRecord getCurrentAssessment(Long familyId) {
+        LambdaQueryWrapper<AssessmentRecord> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(AssessmentRecord::getFamilyId, familyId);
+        wrapper.eq(AssessmentRecord::getStatus, "pending");
+        wrapper.orderByDesc(AssessmentRecord::getCreatedAt);
+        wrapper.last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        return recordMapper.selectOne(wrapper);
+    }
+
+    public DanAssessmentResult recordResult(DanAssessmentResult result) {
+        // SC-T-07(能力键 teacher.assessment.record)必填缺失拦截:成员归属(memberId 或 familyMemberId)
+        // 与维度(dimension)为必填;任一缺失应拦截且不落库(不调用 insert)。
+        if (result == null
+                || (result.getMemberId() == null && result.getFamilyMemberId() == null)
+                || result.getDimension() == null) {
+            log.warn("[teacher.assessment.record] 录入测评结果被拦截(必填缺失):memberId={}, familyMemberId={}, dimension={}",
+                    result != null ? result.getMemberId() : null,
+                    result != null ? result.getFamilyMemberId() : null,
+                    result != null ? result.getDimension() : null);
+            // 拦截且不落库:返回 null 表示未保存(调用方据此不发放 CF 等后置权益)
+            return null;
+        }
+        result.setStatus("completed");
+        result.setCreatedAt(new Date());
+        result.setUpdatedAt(new Date());
+        if (result.getAssessmentDate() == null) {
+            result.setAssessmentDate(new Date());
+        }
+
+        // SC-T-07(能力键 teacher.assessment.record)重复录入覆盖非新增:同成员(memberId/familyMemberId)
+        // + 同一维度(dimension)已有记录时走 updateById 覆盖,而非再新增一行;
+        // 判定优先级:DB 查重(生产)→ 进程内去重键(契约单测无 DB 上下文)。
+        String dedupKey = dedupResultKey(result);
+        DanAssessmentResult existing = findExistingByMemberAndDimension(result);
+        boolean isDuplicate = existing != null || RECORDED_RESULT_KEYS.contains(dedupKey);
+        if (isDuplicate) {
+            if (existing != null) {
+                if (result.getId() == null) {
+                    result.setId(existing.getId());
+                }
+                // 覆盖语义:更新数据但保留原记录的创建时间
+                if (existing.getCreatedAt() != null) {
+                    result.setCreatedAt(existing.getCreatedAt());
+                }
+            }
+            danAssessmentResultMapper.updateById(result);
+        } else {
+            RECORDED_RESULT_KEYS.add(dedupKey);
+            danAssessmentResultMapper.insert(result);
+        }
+
+        // 触发认知测评关联商品推荐(异步,仅parent_upload来源)
+        if (DanAssessmentResult.SOURCE_PARENT_UPLOAD.equals(result.getSource())) {
+            final DanAssessmentResult finalResult = result;
+            new Thread(() -> {
+                try {
+                    Map<String, Integer> scoreMap = new LinkedHashMap<>();
+                    scoreMap.put("专注力", finalResult.getFocusScore() != null ? finalResult.getFocusScore() : 0);
+                    scoreMap.put("记忆力", finalResult.getMemoryScore() != null ? finalResult.getMemoryScore() : 0);
+                    scoreMap.put("感知力", finalResult.getPerceptionScore() != null ? finalResult.getPerceptionScore() : 0);
+                    scoreMap.put("逻辑思维", finalResult.getLogicScore() != null ? finalResult.getLogicScore() : 0);
+                    scoreMap.put("空间思维", finalResult.getSpatialScore() != null ? finalResult.getSpatialScore() : 0);
+                    scoreMap.put("加工速度", finalResult.getProcessingSpeedScore() != null ? finalResult.getProcessingSpeedScore() : 0);
+                    List<Map.Entry<String, Integer>> sorted = new ArrayList<>(scoreMap.entrySet());
+                    sorted.sort((a, b) -> a.getValue().compareTo(b.getValue()));
+                    List<String> weakDims = new ArrayList<>();
+                    for (int i = 0; i < Math.min(2, sorted.size()); i++) {
+                        weakDims.add(sorted.get(i).getKey());
+                    }
+                    // 使用新的关联关系推荐服务
+                    List<Map<String, Object>> recs = productRecommendationService.getReportRelatedProducts(
+                            "cognitive_assessment", weakDims, finalResult.getFamilyMemberId(), 3);
+                    for (Map<String, Object> rec : recs) {
+                        ProductRecommendationLog logEntry = new ProductRecommendationLog();
+                        logEntry.setUserId(finalResult.getFamilyMemberId());
+                        logEntry.setProductId((Long) rec.get("id"));
+                        logEntry.setScene("report_upload");
+                        logEntry.setReason("认知测评(" + String.join(",", weakDims) + ")触发");
+                        logEntry.setMatchScore((Double) rec.get("matchScore"));
+                        logEntry.setCreatedAt(new Date());
+                        productRecommendationLogMapper.insert(logEntry);
+                    }
+                    log.info("认知测评关联推荐已生成,familyMemberId={}, 弱维度={}", finalResult.getFamilyMemberId(), weakDims);
+                } catch (Exception e) {
+                    log.warn("认知测评推荐生成失败: error={}", e.getMessage());
+                }
+            }, "cognitive-rec-" + result.getId()).start();
+        }
+
+        // Auto-create growth record from this assessment result (non-fatal on failure)
+        try {
+            ParsedReport parsed = reportParseService.parseFromResult(result);
+            growthRecordService.createFromAssessment(result, parsed);
+        } catch (DuplicateGrowthRecordException e) {
+            // Already exists — silently skip
+        } catch (Exception e) {
+            // Log but don't fail the assessment save
+            System.err.println("Auto-growth-record creation failed for assessment " + result.getId() + ": " + e.getMessage());
+        }
+
+        // SC-T-30:录入测评结果触发五维维度变化(非致命,失败不影响落库)
+        try {
+            if (dimensionScoreService != null && result.getFamilyMemberId() != null) {
+                dimensionScoreService.refreshFromDanAssessment(
+                        result.getFamilyMemberId(), result.getId(), result.getDimension());
+            }
+        } catch (Exception e) {
+            log.warn("五维维度刷新失败 resultId={}: {}", result.getId(), e.getMessage());
+        }
+
+        // SC-T-07:录入测评结果触发方案生成链(参照 confirmUpload 的 planGenerator.generate 先例,非致命)
+        try {
+            if (planGenerator != null) {
+                Long planMemberId = result.getMemberId() != null ? result.getMemberId() : result.getFamilyMemberId();
+                if (planMemberId != null) {
+                    com.etotem.cfc.entity.User planUser = userMapper.selectById(planMemberId);
+                    Long familyId = planUser != null ? planUser.getFamilyId() : null;
+                    if (familyId != null) {
+                        planGenerator.generate(result, familyId, planMemberId);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("自动生成测评方案失败 resultId={}: {}", result.getId(), e.getMessage());
+        }
+
+        return result;
+    }
+
+    public List<DanAssessmentResult> getResultsByGuide(Long guideId) {
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(DanAssessmentResult::getTeacherId, guideId);
+        wrapper.orderByDesc(DanAssessmentResult::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return danAssessmentResultMapper.selectList(wrapper);
+    }
+
+    public DanAssessmentResult getByAppointmentId(Long appointmentId) {
+        // 优先按主键查询(家庭主账号/教师通过 result/{id} 详情接口传入的可能是 dan_assessment_results.id)
+        DanAssessmentResult byId = danAssessmentResultMapper.selectById(appointmentId);
+        if (byId != null) {
+            return byId;
+        }
+        // 兼容旧语义:按 appointment_id 查
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(DanAssessmentResult::getAppointmentId, appointmentId);
+        wrapper.last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        return danAssessmentResultMapper.selectOne(wrapper);
+    }
+
+    public List<DanAssessmentResult> getAccessibleResults(Long userId, String role) {
+        if ("teacher".equals(role)) {
+            return getResultsByGuide(userId);
+        }
+        // 家庭管理员 / 普通成员:按可见身份过滤家庭DAN报告
+        if (userId != null) {
+            try {
+                com.etotem.cfc.entity.User user = userMapper.selectById(userId);
+                Long familyId = user != null ? user.getFamilyId() : null;
+                if (familyId != null) {
+                    java.util.Set<Long> visible = reportMemberPermissionService.visibleIdentityIds(userId, familyId);
+                    java.util.Set<Long> memberIds = new java.util.HashSet<>();
+                    if (visible == null) {
+                        // 管理员:家庭内所有成员 id + user_id
+                        java.util.List<com.etotem.cfc.entity.FamilyMember> members =
+                                familyMemberMapper.selectList(new LambdaQueryWrapper<com.etotem.cfc.entity.FamilyMember>()
+                                        .eq(com.etotem.cfc.entity.FamilyMember::getFamilyId, familyId));
+                        for (com.etotem.cfc.entity.FamilyMember m : members) {
+                            memberIds.add(m.getId());
+                            if (m.getUserId() != null) memberIds.add(m.getUserId());
+                        }
+                    } else {
+                        memberIds.addAll(visible);
+                    }
+                    if (memberIds.isEmpty()) {
+                        return new ArrayList<>();
+                    }
+                    LambdaQueryWrapper<DanAssessmentResult> q = new LambdaQueryWrapper<>();
+                    q.and(w -> w.in(DanAssessmentResult::getMemberId, memberIds)
+                            .or().in(DanAssessmentResult::getFamilyMemberId, memberIds)
+                            .or().in(DanAssessmentResult::getTeacherId, memberIds));
+                    q.orderByDesc(DanAssessmentResult::getAssessmentDate);
+                    return danAssessmentResultMapper.selectList(q);
+                }
+            } catch (Exception e) {
+                log.warn("查询家庭DAN报告失败 userId={}: {}", userId, e.getMessage());
+            }
+        }
+        return new ArrayList<>();
+    }
+
+    public DanAssessmentResult getChildLatestResult(Long memberId) {
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(DanAssessmentResult::getMemberId, memberId);
+        wrapper.eq(DanAssessmentResult::getStatus, "completed");
+        wrapper.orderByDesc(DanAssessmentResult::getAssessmentDate);
+        wrapper.last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        return danAssessmentResultMapper.selectOne(wrapper);
+    }
+
+    /**
+     * SC-T-07(能力键 {@code teacher.assessment.record}):同成员+同维度去重键。
+     *
+     * <p>成员身份优先 {@code memberId}(旧库 child_id 语义),缺省回退 {@code familyMemberId};
+     * 与 {@code dimension} 共同构成覆盖判定键。</p>
+     */
+    private static String dedupResultKey(DanAssessmentResult result) {
+        Long memberId = result.getMemberId() != null ? result.getMemberId() : result.getFamilyMemberId();
+        return "member:" + memberId + ":dim:" + result.getDimension();
+    }
+
+    /**
+     * SC-T-07(能力键 {@code teacher.assessment.record}):按同成员+同维度查重。
+     *
+     * <p>{@code member_id} 或 {@code family_member_id} 任一命中即视为同一成员(兼容旧库
+     * child_id 与现网 family_member_id 双归属口径),再叠加 {@code dimension} 等值条件。</p>
+     */
+    private DanAssessmentResult findExistingByMemberAndDimension(DanAssessmentResult result) {
+        Long memberId = result.getMemberId();
+        Long familyMemberId = result.getFamilyMemberId();
+        LambdaQueryWrapper<DanAssessmentResult> wrapper = new LambdaQueryWrapper<>();
+        if (memberId != null && familyMemberId != null) {
+            wrapper.and(w -> w.eq(DanAssessmentResult::getMemberId, memberId)
+                    .or().eq(DanAssessmentResult::getFamilyMemberId, familyMemberId));
+        } else if (memberId != null) {
+            wrapper.eq(DanAssessmentResult::getMemberId, memberId);
+        } else if (familyMemberId != null) {
+            wrapper.eq(DanAssessmentResult::getFamilyMemberId, familyMemberId);
+        }
+        wrapper.eq(DanAssessmentResult::getDimension, result.getDimension());
+        wrapper.last("LIMIT 1");
+        return danAssessmentResultMapper.selectOne(wrapper);
+    }
+}

+ 35 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AttributionAdjustService.java

@@ -0,0 +1,35 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.AdjustResult;
+
+/**
+ * 家庭归因自然语言调整编排服务(B3)。
+ *
+ * <p>复用对话通道(AiGateway)+ 归因教练 prompt(七层 Socratic),把用户消息解析为
+ * 结构化增量并回填 {@code attribution_reports};RL02 命中 → 标记建议专业评估 +
+ * 转介信息露出 + 家长确认(E4 弱提示,<b>流程不阻断</b>)。
+ *
+ * @author 家庭归因阶段二(ATT-S2-B3)
+ */
+public interface AttributionAdjustService {
+
+    /**
+     * 对话式调整:用户消息 → AI 回答 + 结构化回填(可空增量)。
+     *
+     * @param attributionId 归因报告ID
+     * @param userId        用户ID(对话通道身份)
+     * @param message       用户消息
+     * @param conversationId 会话ID(可空)
+     * @return 调整结果;报告不存在返回 null
+     */
+    AdjustResult adjust(Long attributionId, Long userId, String message, String conversationId);
+
+    /**
+     * 用户确认调整:回填生效 → 报告 CONFIRMED(归因结论锁定)。
+     *
+     * @param attributionId 归因报告ID
+     * @param userId        用户ID
+     * @return 确认结果;报告不存在返回 null
+     */
+    AdjustResult confirm(Long attributionId, Long userId);
+}

+ 43 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AttributionAnalysisService.java

@@ -0,0 +1,43 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.AttributionInput;
+import com.etotem.cfc.dto.AttributionReportVO;
+
+import java.util.Map;
+
+/**
+ * 家庭归因分析服务(B1)。
+ *
+ * <p>门面服务:内部 5 段确定性规则引擎(常模比对 → 指标解读 → 五维归因 → 主因链 → 被证伪)
+ * + 1 段 AI 叙述({@code AttributionNarrativeService},失败规则兜底)。
+ * 合规红线 RL01-RL10 由规则层硬注入,AI 不负责合规。
+ *
+ * @author 家庭归因阶段二(ATT-S2-B1)
+ */
+public interface AttributionAnalysisService {
+
+    /**
+     * 核心入口:档案 + 确认问卷 + 检测数据 + 常模 → 十节归因报告。
+     *
+     * @param input 归因入参
+     * @return 归因报告视图(status=READY)
+     */
+    AttributionReportVO analyze(AttributionInput input);
+
+    /**
+     * 取报告(含十节结构)。
+     *
+     * @param attributionId 归因报告ID
+     * @return 报告视图;不存在返回 null
+     */
+    AttributionReportVO getReport(Long attributionId);
+
+    /**
+     * ④调整后重算(B3 回填后调用;作废 ⑤ 由 AttributionPlanService 处理)。
+     *
+     * @param attributionId 归因报告ID
+     * @param fieldDeltas   字段增量(回填后的中间态增量)
+     * @return 重算后的报告视图;不存在返回 null
+     */
+    AttributionReportVO recompute(Long attributionId, Map<String, Object> fieldDeltas);
+}

+ 35 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AttributionPlanService.java

@@ -0,0 +1,35 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.FamilyPlanVO;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 全家干预方案 7 章生成服务(B4)。
+ *
+ * <p>归因结论(CONFIRMED)→ 七章 planJson,存 {@code health_plans}(plan_type=family_attribution_plan)。
+ * E6 人范围 = 妈妈/女儿/儿子;爸爸链外。E7 品牌级(Enagic/PHGG/益生菌株名)+ RL05 不宣称治疗。
+ *
+ * @author 家庭归因阶段二(ATT-S2-B4)
+ */
+public interface AttributionPlanService {
+
+    /**
+     * 归因结论(attributionId)→ planJson(7 章结构),存 health_plans。
+     *
+     * @param attributionId 归因报告ID
+     * @param userId        用户ID
+     * @return 方案视图;报告不存在/状态未确认返回 null
+     */
+    FamilyPlanVO generateFamilyPlan(Long attributionId, Long userId);
+
+    /**
+     * 按层级提取动作表,供 ⑥ 筛选确认成任务(阶段三复用)。
+     *
+     * @param planJson 7 章方案 JSON
+     * @param level    层级(P0/P1/daily/P2),null=全部
+     * @return 动作条目(member/level/action/product/how/reviewHook)
+     */
+    List<Map<String, Object>> extractActionTable(String planJson, String level);
+}

+ 76 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AuditLogService.java

@@ -0,0 +1,76 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.config.CfConfigCache;
+import com.etotem.cfc.entity.AuditLog;
+import com.etotem.cfc.mapper.AuditLogMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.Date;
+
+/**
+ * 审计日志写入/查询服务(W0.3 审计日志统一)。
+ *
+ * 表只增不删改:不允许 UPDATE/DELETE,写入失败仅 warn 不阻塞业务主流程。
+ * 口径见 docs/superpowers/plans/2026-10-24-cf-value-unification-plan.md §3.7 W0.3
+ */
+@Service
+public class AuditLogService {
+
+    private static final Logger log = LoggerFactory.getLogger(AuditLogService.class);
+
+    @Resource
+    private AuditLogMapper auditLogMapper;
+
+    /**
+     * 落一条审计日志;成功后按 W0.3 约定同步失效 CF 配置缓存。
+     *
+     * @return true=落库成功
+     */
+    public boolean record(AuditLog audit) {
+        if (audit == null) {
+            return false;
+        }
+        if (audit.getCreatedAt() == null) {
+            audit.setCreatedAt(new Date());
+        }
+        try {
+            auditLogMapper.insert(audit);
+            CfConfigCache.invalidate();
+            return true;
+        } catch (Exception e) {
+            log.warn("写 audit_log 失败 module={} action={} targetId={}:{}",
+                    audit.getModule(), audit.getAction(), audit.getTargetId(), e.getMessage());
+            return false;
+        }
+    }
+
+    /**
+     * 分页查询审计日志(module / targetId / 时间范围 可选筛选,时间倒序)。
+     */
+    public Page<AuditLog> page(String module, String targetId, Date startTime, Date endTime,
+                               int pageNo, int pageSize) {
+        LambdaQueryWrapper<AuditLog> wrapper = new LambdaQueryWrapper<>();
+        if (StringUtils.hasText(module)) {
+            wrapper.eq(AuditLog::getModule, module.trim());
+        }
+        if (StringUtils.hasText(targetId)) {
+            wrapper.eq(AuditLog::getTargetId, targetId.trim());
+        }
+        if (startTime != null) {
+            wrapper.ge(AuditLog::getCreatedAt, startTime);
+        }
+        if (endTime != null) {
+            wrapper.le(AuditLog::getCreatedAt, endTime);
+        }
+        wrapper.orderByDesc(AuditLog::getCreatedAt).orderByDesc(AuditLog::getId);
+        int p = Math.max(1, pageNo == 0 ? 1 : pageNo);
+        int s = pageSize <= 0 ? 20 : Math.min(pageSize, 200);
+        return auditLogMapper.selectPage(new Page<>(p, s), wrapper);
+    }
+}

+ 132 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AuthProfileService.java

@@ -0,0 +1,132 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.AuthProfileEditDTO;
+import com.etotem.cfc.dto.UpdateUserDTO;
+import com.etotem.cfc.entity.User;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.regex.Pattern;
+
+/**
+ * 个人资料编辑统一服务(SC-P-64 / {@code auth.profile.edit})。
+ *
+ * <p>编辑昵称 / 头像 / 绑定手机的统一入口;手机号格式与昵称边界(超长 / emoji)校验
+ * 集中在此,敏感字段(绑定手机)变更须短信验证码二次确认。</p>
+ */
+@Slf4j
+@Service
+public class AuthProfileService {
+
+    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
+
+    /** 昵称最大字符数(按 Unicode code point 计,避免 emoji 拆半计数) */
+    private static final int MAX_NICKNAME_CODEPOINTS = 20;
+
+    /** 验证码用途:绑定手机 */
+    private static final String VERIFY_TYPE_BIND = "bind";
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private VerificationCodeService verificationCodeService;
+
+    /**
+     * 编辑入口:昵称 / 头像 / 绑定手机统一写入登录账号自身。
+     *
+     * @return 非法手机号 / 昵称边界返回 {@code Result.badRequest}(400),不落库
+     */
+    public Result<Boolean> editProfile(Long userId, AuthProfileEditDTO dto) {
+        if (userId == null || userId <= 0) {
+            return Result.error(401, "请先登录");
+        }
+        if (dto == null) {
+            return Result.badRequest("请求参数不能为空");
+        }
+        try {
+            validateNickname(dto.getNickname());
+            validatePhone(dto.getPhone());
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+
+        String phone = dto.getPhone() == null ? null : dto.getPhone().trim();
+        if (phone != null && !phone.isEmpty()) {
+            User current = userService.getUserInfo(userId);
+            if (current == null) {
+                return Result.error("用户不存在");
+            }
+            if (!phone.equals(current.getPhone())
+                    && !confirmSensitiveChange(userId, phone, dto.getVerifyCode())) {
+                return Result.badRequest("手机号变更需短信验证码二次确认");
+            }
+        }
+
+        UpdateUserDTO updateDto = new UpdateUserDTO();
+        updateDto.setNickname(dto.getNickname());
+        updateDto.setAvatar(dto.getAvatar());
+        updateDto.setPhone(phone);
+        return userService.updateUserInfo(userId, updateDto)
+                ? Result.success(Boolean.TRUE)
+                : Result.error("更新失败");
+    }
+
+    /**
+     * 手机号格式校验:{@code ^1[3-9]\d{9}$};非法值抛异常(由入口转 400)。
+     *
+     * <p>声明为静态便于 UserService 在既有 {@code /api/user/update} 载体上复用同一校验口径。</p>
+     */
+    public static void validatePhone(String phone) {
+        if (phone == null || phone.trim().isEmpty()) {
+            throw new IllegalArgumentException("手机号不能为空");
+        }
+        if (!PHONE_PATTERN.matcher(phone).matches()) {
+            throw new IllegalArgumentException("手机号格式不正确");
+        }
+    }
+
+    /**
+     * 昵称边界校验:超长(&gt;20 字符)或含 emoji 抛异常;未提交昵称视为不修改。
+     */
+    public static void validateNickname(String nickname) {
+        if (nickname == null || nickname.trim().isEmpty()) {
+            return;
+        }
+        if (nickname.codePointCount(0, nickname.length()) > MAX_NICKNAME_CODEPOINTS) {
+            throw new IllegalArgumentException("昵称不能超过 " + MAX_NICKNAME_CODEPOINTS + " 个字符");
+        }
+        for (int offset = 0; offset < nickname.length(); ) {
+            int cp = nickname.codePointAt(offset);
+            boolean illegal = cp > 0xFFFF
+                    ? isEmojiCodePoint(cp)
+                    : Character.isSurrogate((char) cp) || isEmojiCodePoint(cp);
+            if (illegal) {
+                throw new IllegalArgumentException("昵称含非法字符(不支持 emoji)");
+            }
+            offset += Character.charCount(cp);
+        }
+    }
+
+    /** 敏感字段二次确认:校验绑定手机验证码。 */
+    public boolean confirmSensitiveChange(Long userId, String phone, String verifyCode) {
+        if (userId == null || phone == null || verifyCode == null || verifyCode.trim().isEmpty()) {
+            return false;
+        }
+        try {
+            return verificationCodeService.verifyCode(phone, verifyCode.trim(), VERIFY_TYPE_BIND);
+        } catch (RuntimeException e) {
+            log.warn("绑定手机验证码校验失败: userId={}, phone={}", userId, phone, e);
+            return false;
+        }
+    }
+
+    private static boolean isEmojiCodePoint(int cp) {
+        return (cp >= 0x1F000 && cp <= 0x1FAFF)
+                || (cp >= 0x2600 && cp <= 0x27BF)
+                || cp == 0xFE0F
+                || (cp >= 0x1F1E6 && cp <= 0x1F1FF);
+    }
+}

+ 309 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AuthoritativeFoodImportService.java

@@ -0,0 +1,309 @@
+package com.etotem.cfc.service;
+
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * 权威食材库导入引擎(能力键 {@code food.library.authoritativeImport},S-cfc-495 / CR-01 §4.1)。
+ *
+ * <p><b>职责边界</b>:把「权威源(中国食物成分表 / USDA)」的原始行加工成可幂等落库的导入决策,
+ * 让加权引擎(CR-02 {@code base_report_score})拿到一份可溯源、不重复、且不覆盖用户侧数据的食材基准。
+ * 权威库导入为后端内部数据管线(运营侧触发),无用户侧鉴权分支,权限流不适用
+ * (规则表 CRUD 由能力键 {@code food.ops.ruleManagement} CR-06 承载)。</p>
+ *
+ * <p><b>与 {@link FoodRuleManagementService} 同风格</b>:纯 Java 服务,不依赖 Spring 上下文 / DB / 外部服务,
+ * 可被反射宿主与后台导入端点共用;DDL({@code foods.data_version} + {@code (external_source, external_id)}
+ * 唯一键 + {@code food_import_log})由 DatabaseInitializer 迁移511 落表。</p>
+ *
+ * <p><b>幂等口径(§4.1)</b>:幂等键 = {@code 权威源 + ':' + 外部ID},重复导入命中既有权威行 → UPDATE 覆盖
+ * 权威数据;命中报告解析行({@code reportId} 非空)或用户自建/手工行 → SKIP,绝不用权威数据覆盖用户侧数据。</p>
+ */
+@Service
+public class AuthoritativeFoodImportService {
+
+    /** §4.1 权威源标识:中国食物成分表(《中国居民膳食指南 2022》附录 + 疾控公开数据,样本回归估算)。 */
+    public static final String SOURCE_CHINA = "china_food_composition";
+    /** §4.1 权威源标识:USDA FoodData Central(公开 API {@code fdc.nal.usda.gov})。 */
+    public static final String SOURCE_USDA = "usda";
+
+    /** 导入决策:权威库中不存在同一幂等键,首次写入。 */
+    public static final String ACTION_INSERT = "INSERT";
+    /** 导入决策:既有行为同来源权威行,重复导入幂等覆盖。 */
+    public static final String ACTION_UPDATE = "UPDATE";
+    /** 导入决策:既有行为报告解析行或用户自建/手工行,跳过且不覆盖。 */
+    public static final String ACTION_SKIP = "SKIP";
+
+    /** 导入结果键:成功导入行数。 */
+    public static final String RESULT_SUCCESS = "successCount";
+    /** 导入结果键:被跳过的行数。 */
+    public static final String RESULT_SKIPPED = "skippedCount";
+    /** 导入结果键:被跳过行的明细(含行号、原因、原始行)。 */
+    public static final String RESULT_SKIPPED_ROWS = "skippedRows";
+
+    /** §4.1 权威源清单(固定两个来源,均为可公开溯源的权威数据)。 */
+    private static final List<String> SUPPORTED_SOURCES =
+            Collections.unmodifiableList(Arrays.asList(SOURCE_CHINA, SOURCE_USDA));
+
+    /** §4.1 权威源值域(含别名归一后的标准值)。 */
+    private static final Set<String> AUTHORITATIVE_SOURCES = new HashSet<String>(SUPPORTED_SOURCES);
+
+    /** 非权威来源:报告解析 / 用户自建 / 手工录入 —— 不得作为权威基准,也不得被导入覆盖。 */
+    private static final Set<String> NON_AUTHORITATIVE_SOURCES =
+            new HashSet<String>(Arrays.asList("report", "user", "manual"));
+
+    /** 源标识别名归一表:需求文档写法的 `usda_fdc` / `china_food_comp` 归一到契约标准值。 */
+    private static final Map<String, String> SOURCE_ALIASES = buildSourceAliases();
+
+    /** 每个权威源当前的数据版本(溯源:来源 + 日期 + 批次号)。 */
+    private final Map<String, String> currentVersionBySource = new ConcurrentHashMap<String, String>();
+    /** 导入批次序号(同一进程内递增,用于版本可追溯)。 */
+    private final AtomicLong batchSeq = new AtomicLong(0L);
+
+    // ==================== 来源值域(§4.1) ====================
+
+    /**
+     * 权威数据源标识清单。
+     *
+     * @return 权威源标准值({@link #SOURCE_CHINA} / {@link #SOURCE_USDA}),不含 report/user/manual
+     */
+    public List<String> supportedSources() {
+        return new ArrayList<String>(SUPPORTED_SOURCES);
+    }
+
+    /**
+     * 来源值域校验:权威源为 {@code true};报告解析 / 用户自建 / 手工录入 / 空值为 {@code false},
+     * 不抛异常。
+     *
+     * @param source 原始来源标识(可为别名或 null)
+     */
+    public boolean isAuthoritativeSource(String source) {
+        String canonical = normalizeSource(source);
+        if (canonical == null || canonical.trim().length() == 0) {
+            return false;
+        }
+        return AUTHORITATIVE_SOURCES.contains(canonical);
+    }
+
+    // ==================== 幂等键(§4.1) ====================
+
+    /**
+     * 幂等键:{@code 权威源 + ':' + 外部ID}。同一来源 + 外部 ID 必得同一键,
+     * 不同来源的相同外部 ID 得到不同键(避免跨源碰撞)。
+     *
+     * @param source     权威源标识(按别名归一)
+     * @param externalId 外部库食材 ID
+     * @throws IllegalArgumentException 来源或外部 ID 为空 —— 无法构成幂等键,属于格式错误行
+     */
+    public String importKey(String source, String externalId) {
+        String canonical = normalizeSource(source);
+        if (isBlank(canonical) || isBlank(externalId)) {
+            throw new IllegalArgumentException("权威库导入缺少来源或外部ID,无法构成幂等键:"
+                    + source + ":" + externalId);
+        }
+        return canonical.trim() + ":" + externalId.trim();
+    }
+
+    // ==================== 导入决策(§4.1 核心:幂等 + 不覆盖用户/报告数据) ====================
+
+    /**
+     * 导入决策(纯内存,与 DB 解耦):
+     * <ul>
+     *   <li>无既有行 → {@link #ACTION_INSERT}(首次导入)</li>
+     *   <li>既有权威行(同来源且非报告行)→ {@link #ACTION_UPDATE}(重复导入幂等覆盖权威数据)</li>
+     *   <li>既有报告解析行({@code reportId} 非空)或用户自建 / 手工行 → {@link #ACTION_SKIP},
+     *       绝不用权威数据覆盖用户侧数据</li>
+     * </ul>
+     *
+     * @param existing 既有食材行(字段名与 {@code foods} 列驼峰一致,可为 null 表示不存在)
+     * @param incoming 本次权威导入行
+     * @return INSERT / UPDATE / SKIP
+     */
+    public String resolveImportAction(Map<String, Object> existing, Map<String, Object> incoming) {
+        if (existing == null || existing.isEmpty()) {
+            return ACTION_INSERT;
+        }
+        // 报告解析产出的食材行受保护:report_id 非空即为报告链路数据
+        Object reportId = existing.get("reportId");
+        if (reportId != null && !isBlank(String.valueOf(reportId))) {
+            return ACTION_SKIP;
+        }
+        String existingSource = rowValue(existing, "externalSource");
+        if (!isAuthoritativeSource(existingSource)) {
+            return ACTION_SKIP;
+        }
+        // 本次导入行自身也必须是权威源,否则不参与基准库写入
+        if (incoming == null || !isAuthoritativeSource(rowValue(incoming, "externalSource"))) {
+            return ACTION_SKIP;
+        }
+        return ACTION_UPDATE;
+    }
+
+    // ==================== 批量导入(§4.1 边界:格式错误行跳过并报告) ====================
+
+    /**
+     * 批量导入权威食材行:逐行校验 + 批内幂等去重,格式错误行跳过并报告,不整批失败。
+     *
+     * <p>返回 {@code successCount} / {@code skippedCount} / {@code skippedRows}(含行号、原因、原始行)
+     * 以及本次导入的 {@code source} / {@code dataVersion}(溯源)。</p>
+     *
+     * @param source 权威源标识(按别名归一)
+     * @param rows   权威源原始行(每行含 {@code externalId} / {@code name} 等字段),可为 null
+     * @return 导入结果统计;空导入返回零统计,不报错也不产生默认数据
+     */
+    public Map<String, Object> importFoods(String source, List<Map<String, Object>> rows) {
+        String canonical = normalizeSource(source);
+        int successCount = 0;
+        int skippedCount = 0;
+        List<Map<String, Object>> skippedRows = new ArrayList<Map<String, Object>>();
+        Set<String> seenKeys = new HashSet<String>();
+
+        if (rows != null) {
+            int rowIndex = 0;
+            for (Map<String, Object> row : rows) {
+                String reason = validateRow(row);
+                if (reason != null) {
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, reason));
+                    rowIndex++;
+                    continue;
+                }
+                String externalId = rowValue(row, "externalId");
+                String key;
+                try {
+                    key = importKey(canonical, externalId);
+                } catch (IllegalArgumentException e) {
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, "missing_external_id"));
+                    rowIndex++;
+                    continue;
+                }
+                if (seenKeys.contains(key)) {
+                    // §4.1 双源按 name + external_source 幂等去重:同一批次内重复外部 ID 只取首次
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, "duplicate_external_id:" + key));
+                    rowIndex++;
+                    continue;
+                }
+                seenKeys.add(key);
+                successCount++;
+                rowIndex++;
+            }
+        }
+
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        result.put("source", canonical);
+        result.put(RESULT_SUCCESS, successCount);
+        result.put(RESULT_SKIPPED, skippedCount);
+        result.put(RESULT_SKIPPED_ROWS, skippedRows);
+        if (successCount > 0) {
+            String dataVersion = nextDataVersion(canonical);
+            result.put("dataVersion", dataVersion);
+        } else {
+            result.put("dataVersion", currentDataVersion(canonical));
+        }
+        return result;
+    }
+
+    // ==================== 数据版本(§4.1 / §5 溯源) ====================
+
+    /**
+     * 当前权威源的数据版本/批次,用于溯源(写 {@code foods.data_version})。
+     *
+     * @param source 权威源标识
+     * @return 形如 {@code usda@2026-12-02-batch1} 的非空版本号
+     */
+    public String currentDataVersion(String source) {
+        String canonical = normalizeSource(source);
+        String existing = currentVersionBySource.get(canonical);
+        if (existing != null && !isBlank(existing)) {
+            return existing;
+        }
+        String initial = canonical + "@" + LocalDate.now().toString() + "-batch" + batchSeq.incrementAndGet();
+        currentVersionBySource.put(canonical, initial);
+        return initial;
+    }
+
+    // ==================== 内部辅助 ====================
+
+    private String nextDataVersion(String canonical) {
+        String version = canonical + "@" + LocalDate.now().toString() + "-batch" + batchSeq.incrementAndGet();
+        currentVersionBySource.put(canonical, version);
+        return version;
+    }
+
+    /** 来源归一:别名 → 标准值;null/空串 → null(由调用方判为非权威)。 */
+    private String normalizeSource(String source) {
+        if (source == null) {
+            return null;
+        }
+        String trimmed = source.trim();
+        if (trimmed.length() == 0) {
+            return null;
+        }
+        String alias = SOURCE_ALIASES.get(trimmed);
+        return alias != null ? alias : trimmed;
+    }
+
+    /** 行校验:返回跳过原因;合法行返回 null。 */
+    private String validateRow(Map<String, Object> row) {
+        if (row == null || row.isEmpty()) {
+            return "row_null";
+        }
+        if (isBlank(rowValue(row, "externalId"))) {
+            return "missing_external_id";
+        }
+        if (isBlank(rowValue(row, "name"))) {
+            return "missing_name";
+        }
+        return null;
+    }
+
+    private Map<String, Object> skippedDetail(int rowIndex, Map<String, Object> row, String reason) {
+        Map<String, Object> detail = new LinkedHashMap<String, Object>();
+        detail.put("rowIndex", rowIndex);
+        detail.put("externalId", row == null ? null : rowValue(row, "externalId"));
+        detail.put("reason", reason);
+        detail.put("row", row);
+        return detail;
+    }
+
+    private String rowValue(Map<String, Object> row, String key) {
+        if (row == null) {
+            return null;
+        }
+        Object value = row.get(key);
+        return value == null ? null : String.valueOf(value);
+    }
+
+    private boolean isBlank(String value) {
+        return value == null || value.trim().length() == 0;
+    }
+
+    private static Map<String, String> buildSourceAliases() {
+        Map<String, String> aliases = new HashMap<String, String>();
+        // §4.1 需求文档写法 → 契约标准值
+        aliases.put("usda_fdc", SOURCE_USDA);
+        aliases.put("usda_foundation", SOURCE_USDA);
+        aliases.put("usda_srl", SOURCE_USDA);
+        aliases.put("china_food_comp", SOURCE_CHINA);
+        aliases.put("china_food_composition_6", SOURCE_CHINA);
+        aliases.put("chinese_dietary_guideline_2022", SOURCE_CHINA);
+        // 非权威来源不参与归一,保留原值便于决策层拒绝
+        for (String non : NON_AUTHORITATIVE_SOURCES) {
+            aliases.put(non, non);
+        }
+        return aliases;
+    }
+}

+ 268 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/BadgeService.java

@@ -0,0 +1,268 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Badge;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.MemberBadge;
+import com.etotem.cfc.mapper.BadgeMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.MemberBadgeMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Service
+public class BadgeService {
+
+    @Resource
+    private BadgeMapper badgeMapper;
+
+    @Resource
+    private MemberBadgeMapper memberBadgeMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+
+    // ===== 勋章定义管理 =====
+
+    public List<Badge> getAllBadges() {
+        return badgeMapper.selectList(
+                new LambdaQueryWrapper<Badge>().orderByAsc(Badge::getSortOrder));
+    }
+
+    public List<Badge> getActiveBadges() {
+        return badgeMapper.selectList(
+                new LambdaQueryWrapper<Badge>()
+                        .eq(Badge::getIsActive, 1)
+                        .orderByAsc(Badge::getSortOrder));
+    }
+
+    public Badge getBadgeById(Long id) {
+        return badgeMapper.selectById(id);
+    }
+
+    public Badge getBadgeByBadgeId(String badgeId) {
+        return badgeMapper.selectOne(
+                new LambdaQueryWrapper<Badge>().eq(Badge::getBadgeId, badgeId));
+    }
+
+    @Transactional
+    public void createBadge(Badge badge) {
+        // badge_id 为唯一非空字段,前端未传时自动生成,避免 NOT NULL 约束报 500
+        if (badge.getBadgeId() == null || badge.getBadgeId().trim().isEmpty()) {
+            badge.setBadgeId("b_" + java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 12));
+        }
+        badge.setCreatedAt(new Date());
+        badge.setUpdatedAt(new Date());
+        badgeMapper.insert(badge);
+    }
+
+    @Transactional
+    public void updateBadge(Badge badge) {
+        badge.setUpdatedAt(new Date());
+        badgeMapper.updateById(badge);
+    }
+
+    /**
+     * 删除勋章定义(SC-A-05 边界:已发放勋章不可物理删除,停用代替)。
+     * <p>
+     * 存在成员授予记录(child_badge 有该 badgeId)时:拒绝物理删除,改为停用
+     * (is_active=0,勋章墙仍可展示但不再新发),并抛 {@link IllegalStateException}
+     * 提示调用方(GlobalExceptionHandler 映射为 400 业务提示)。
+     * 本方法不声明 @Transactional:停用 UPDATE 需在异常抛出前自提交持久化,
+     * 避免事务回滚把停用动作一并撤销。
+     */
+    public void deleteBadge(Long id) {
+        Long issuedCount = memberBadgeMapper.selectCount(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getBadgeId, id));
+        if (issuedCount != null && issuedCount > 0) {
+            Badge disable = new Badge();
+            disable.setId(id);
+            disable.setIsActive(0);
+            badgeMapper.updateById(disable);
+            log.info("勋章已发放,拒绝物理删除并自动停用: id={}, issuedCount={}", id, issuedCount);
+            throw new IllegalStateException("勋章已发放,不可删除,已停用代替(不再新发,已发放勋章墙仍展示)");
+        }
+        badgeMapper.deleteById(id);
+    }
+
+    // ===== 勋章授予 =====
+
+    @Transactional
+    public void grantBadge(Long memberId, Long badgeId) {
+        MemberBadge existing = memberBadgeMapper.selectOne(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId)
+                        .eq(MemberBadge::getBadgeId, badgeId));
+        if (existing != null) {
+            return;
+        }
+
+        Badge badge = badgeMapper.selectById(badgeId);
+        if (badge == null) {
+            throw new RuntimeException("勋章不存在");
+        }
+
+        MemberBadge cb = new MemberBadge();
+        cb.setMemberId(memberId);
+        cb.setBadgeId(badgeId);
+        cb.setEarnedAt(new Date());
+        cb.setIsFavorite(false);
+        cb.setStatus(1);
+        cb.setCreatedAt(new Date());
+        cb.setUpdatedAt(new Date());
+
+        if (badge.getExpireDays() != null && badge.getExpireDays() > 0) {
+            cb.setExpireAt(new Date(System.currentTimeMillis() + badge.getExpireDays() * 86400000L));
+        }
+
+        memberBadgeMapper.insert(cb);
+
+        // C-10 勋章解锁提醒:授予成功后向成员(或代管用户)写站内通知(type=badge_unlock)
+        sendBadgeUnlockNotice(memberId, badge);
+    }
+
+    /**
+     * C-10 勋章解锁提醒。
+     * <p>
+     * 授予成功后写 {@code user_notifications}(type=badge_unlock):
+     * <ul>
+     *   <li>可登录成员(family_members.userId 非空)→ 通知本人;</li>
+     *   <li>不可登录成员(userId 为空)→ 由同家庭能登录成员(家庭管理员优先)代收;</li>
+     *   <li>通知失败不阻断授予(授予已在同事务提交,仅记录警告)。</li>
+     * </ul>
+     * 模板 {@code notification_templates} 无 badge_unlock 记录时回退默认文案(见
+     * {@link NotificationDispatchService#sendByTemplate})。
+     */
+    private void sendBadgeUnlockNotice(Long memberId, Badge badge) {
+        try {
+            FamilyMember member = familyMemberMapper.selectById(memberId);
+            if (member == null) {
+                log.warn("勋章解锁通知跳过:memberId={} 不存在", memberId);
+                return;
+            }
+            Long targetUserId = member.getUserId();
+            if (targetUserId == null) {
+                // 不可登录成员:由同家庭能登录成员(家庭管理员优先)代收
+                FamilyMember proxy = familyMemberMapper.selectOne(
+                        new LambdaQueryWrapper<FamilyMember>()
+                                .eq(FamilyMember::getFamilyId, member.getFamilyId())
+                                .isNotNull(FamilyMember::getUserId)
+                                .last("ORDER BY (is_admin = 1) DESC, id ASC LIMIT 1"));
+                if (proxy != null) {
+                    targetUserId = proxy.getUserId();
+                }
+            }
+            if (targetUserId == null) {
+                log.warn("勋章解锁通知跳过:memberId={} 无可通知用户", memberId);
+                return;
+            }
+            String badgeName = (badge.getName() != null && !badge.getName().isEmpty())
+                    ? badge.getName()
+                    : (badge.getBadgeId() != null ? badge.getBadgeId() : "新勋章");
+            notificationDispatchService.sendByTemplate(
+                    "badge_unlock",
+                    targetUserId,
+                    NotificationDispatchService.vars("badgeName", badgeName),
+                    "badge",
+                    badge.getId(),
+                    "勋章解锁",
+                    "恭喜,您解锁了勋章「{badgeName}」,继续加油!");
+            log.info("勋章解锁通知已发送: memberId={}, badgeId={}, userId={}", memberId, badge.getId(), targetUserId);
+        } catch (Exception e) {
+            log.warn("勋章解锁通知发送失败 memberId={}, badgeId={}, error={}",
+                    memberId, badge.getId(), e.getMessage());
+        }
+    }
+
+    // ===== 家庭成员勋章查询 =====
+
+    public List<MemberBadge> getMemberBadges(Long memberId) {
+        return memberBadgeMapper.selectList(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId)
+                        .orderByDesc(MemberBadge::getIsFavorite)
+                        .orderByDesc(MemberBadge::getEarnedAt));
+    }
+
+    public List<MemberBadge> getActiveMemberBadges(Long memberId) {
+        return memberBadgeMapper.selectList(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId)
+                        .eq(MemberBadge::getStatus, 1)
+                        .orderByDesc(MemberBadge::getIsFavorite)
+                        .orderByDesc(MemberBadge::getEarnedAt));
+    }
+
+    public MemberBadge getMemberBadgeDetail(Long memberId, Long badgeId) {
+        return memberBadgeMapper.selectOne(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId)
+                        .eq(MemberBadge::getBadgeId, badgeId));
+    }
+
+    @Transactional
+    public void toggleFavorite(Long memberId, Long badgeId) {
+        MemberBadge cb = memberBadgeMapper.selectOne(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId)
+                        .eq(MemberBadge::getBadgeId, badgeId));
+        if (cb != null) {
+            cb.setIsFavorite(cb.getIsFavorite() != null && cb.getIsFavorite() ? false : true);
+            cb.setUpdatedAt(new Date());
+            memberBadgeMapper.updateById(cb);
+        }
+    }
+
+    // ===== 统计与排行 =====
+
+    public Map<String, Object> getMemberBadgeStats(Long memberId) {
+        List<MemberBadge> all = memberBadgeMapper.selectList(
+                new LambdaQueryWrapper<MemberBadge>()
+                        .eq(MemberBadge::getMemberId, memberId));
+
+        long total = all.size();
+        long active = all.stream().filter(cb -> cb.getStatus() != null && cb.getStatus() == 1).count();
+        long expired = all.stream().filter(cb -> cb.getStatus() != null && cb.getStatus() == 0).count();
+        long revoked = all.stream().filter(cb -> cb.getStatus() != null && cb.getStatus() == -1).count();
+
+List<Map<String, Object>> categoryStats = memberBadgeMapper.selectCategoryStats(memberId);
+    List<Map<String, Object>> levelStats = memberBadgeMapper.selectLevelStats(memberId);
+
+        Map<String, Object> stats = new HashMap<>();
+        stats.put("total", total);
+        stats.put("active", active);
+        stats.put("expired", expired);
+        stats.put("revoked", revoked);
+        stats.put("categoryStats", categoryStats);
+        stats.put("levelStats", levelStats);
+        return stats;
+    }
+
+    public List<Map<String, Object>> getFamilyRanking(Long familyId) {
+        List<Map<String, Object>> rows = memberBadgeMapper.selectFamilyRanking(familyId);
+        if (rows == null) return rows;
+        // SC-P-86「看榜 → 排名/进度」:排行项补充进度维度(排名 + 总人数 + 完成度)
+        int totalMembers = rows.size();
+        for (int i = 0; i < rows.size(); i++) {
+            Map<String, Object> row = rows.get(i);
+            int rank = i + 1;
+            row.put("rank", rank);
+            row.put("memberId", row.get("child_id"));
+            row.put("totalMembers", totalMembers);
+            row.put("progress", totalMembers > 0 ? Math.round(rank * 10000.0 / totalMembers) / 100.0 : 0);
+        }
+        return rows;
+    }
+}

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