Procházet zdrojové kódy

revert: 回滚 wip-merge 8d8961816 恢复可编译主干(修复 C-311-1 P0 事故)

根因:8d8961816 chore(wip-merge) 将工作区半成品 WIP 整树提交,服务与控制器
API 版本错配,导致 R311~R320 连续 10 轮复验均未修复(后端 66 错/13 文件、
前端 119 红、blockers.md 历史段 −3226 行)。

修复方式:git revert 8d8961816 反向应用 + 手工合并 blockers.md(pre 完整历史
3301 行 + R311~R320 事故台账续段 146 行 = 3447 行);其余 9 个冲突文件
(DatabaseInitializer.java/ContentRecommendService/schema.sql/cfc-web 相关)
保留 HEAD 版本以保住后续演化的新增迁移 462/463/499 与内容演化。

编译验证:mvn -o test-compile BUILD SUCCESS(0 错误)。
核心文件:WishService.getChildWishes 恢复多参重载(pre==cur),
WishControllerSupport/controller.wish/ 调用链一致。

回退产物:465 文件 −39576/+20059 行;217 个 wip-merge 引入的新文件(docs/
参考资料/*、docs/scripts/*、frontend/scripts/*、orchestration/report-dev-*)
被移除,原始内容仍保留于 8d8961816 提交对象中,可按需找回。

Refs: R311 C-311-1, R320 P-1, backup/pre-revert-8d8961816-base
廖晓光 před 4 dny
rodič
revize
f2b477c167
100 změnil soubory, kde provedl 4073 přidání a 689 odebrání
  1. 22 0
      cfc-backend/src/main/java/com/etotem/cfc/config/AsyncConfig.java
  2. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/config/JwtConfig.java
  3. 86 7
      cfc-backend/src/main/java/com/etotem/cfc/config/JwtInterceptor.java
  4. 35 3
      cfc-backend/src/main/java/com/etotem/cfc/config/RateLimitInterceptor.java
  5. 14 3
      cfc-backend/src/main/java/com/etotem/cfc/config/WebConfig.java
  6. 72 60
      cfc-backend/src/main/java/com/etotem/cfc/constant/AttributionLowSideRules.java
  7. 22 0
      cfc-backend/src/main/java/com/etotem/cfc/constant/CfConfigKeys.java
  8. 4 1
      cfc-backend/src/main/java/com/etotem/cfc/constant/ConditionalPathogenLowSideRules.java
  9. 15 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/BadgeController.java
  10. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ContactController.java
  11. 42 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/ContentFilterController.java
  12. 66 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/CouponGiftController.java
  13. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/DanAssessmentController.java
  14. 4 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/EnergyController.java
  15. 2 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/FoodRecommendController.java
  16. 4 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/GameRecordController.java
  17. 42 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/GrowthController.java
  18. 63 33
      cfc-backend/src/main/java/com/etotem/cfc/controller/GrowthTaskController.java
  19. 75 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/HealthPlanController.java
  20. 139 8
      cfc-backend/src/main/java/com/etotem/cfc/controller/HealthReportController.java
  21. 48 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/MembershipController.java
  22. 0 46
      cfc-backend/src/main/java/com/etotem/cfc/controller/TeamStarController.java
  23. 28 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/UserNotificationController.java
  24. 69 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminAfterSalesController.java
  25. 86 10
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminArticleController.java
  26. 68 11
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminButlerController.java
  27. 5 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminChallengeScoreConfigController.java
  28. 8 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminController.java
  29. 26 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminCouponController.java
  30. 35 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminEnergyConfigController.java
  31. 112 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminProductOrderController.java
  32. 1 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminProfileController.java
  33. 108 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminSystemController.java
  34. 30 5
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionConfigController.java
  35. 50 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionWeightController.java
  36. 57 5
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseController.java
  37. 91 9
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseVectorController.java
  38. 8 6
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParserAdminController.java
  39. 0 276
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/TeamProfitAdminController.java
  40. 244 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIChatController.java
  41. 32 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentAppointmentController.java
  42. 44 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentResultController.java
  43. 160 9
      cfc-backend/src/main/java/com/etotem/cfc/controller/butler/ButlerController.java
  44. 41 5
      cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecommendationController.java
  45. 30 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyMembersController.java
  46. 125 6
      cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthPlanController.java
  47. 57 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthRecordController.java
  48. 29 4
      cfc-backend/src/main/java/com/etotem/cfc/controller/guide/GuideFamilyTaskController.java
  49. 22 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/guide/PlanReviewController.java
  50. 3 3
      cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProcurementTaskController.java
  51. 7 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProductOrderController.java
  52. 2 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/profile/ProfileController.java
  53. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/shop/AfterSalesController.java
  54. 53 42
      cfc-backend/src/main/java/com/etotem/cfc/controller/stats/StatsController.java
  55. 41 2
      cfc-backend/src/main/java/com/etotem/cfc/controller/task/TaskController.java
  56. 12 22
      cfc-backend/src/main/java/com/etotem/cfc/controller/wish/WishController.java
  57. 10 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/AssessmentHistoryItemDTO.java
  58. 31 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/AssessmentResultDTO.java
  59. 1 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/ContactDTO.java
  60. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyMemberVO.java
  61. 26 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/ParsedReportResult.java
  62. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/ServiceRoleApplyDTO.java
  63. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/TaskReminderConfigDTO.java
  64. 3 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/AssessmentMaterial.java
  65. 3 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/Contact.java
  66. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/CouponGiftTransfer.java
  67. 2 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/DietRecommendation.java
  68. 5 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/EnergyBalance.java
  69. 11 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/EnergyLog.java
  70. 11 3
      cfc-backend/src/main/java/com/etotem/cfc/entity/FamilyFoodOverview.java
  71. 10 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/Food.java
  72. 5 1
      cfc-backend/src/main/java/com/etotem/cfc/entity/GrowthPlan.java
  73. 2 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/MembershipLevel.java
  74. 3 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/PackageOrder.java
  75. 5 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/ProductDimensionConfig.java
  76. 8 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/ProductOrder.java
  77. 2 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/ServiceRoleApplication.java
  78. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/Task.java
  79. 9 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/TaskReminderConfig.java
  80. 3 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/TeacherMessage.java
  81. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/User.java
  82. 15 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/CouponMapper.java
  83. 1 1
      cfc-backend/src/main/java/com/etotem/cfc/mapper/GameRecordMapper.java
  84. 3 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AIService.java
  85. 225 39
      cfc-backend/src/main/java/com/etotem/cfc/service/AccountCleanupService.java
  86. 18 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ActivityService.java
  87. 57 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AfterSalesService.java
  88. 58 2
      cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java
  89. 32 2
      cfc-backend/src/main/java/com/etotem/cfc/service/ArticleService.java
  90. 44 0
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentAppointmentService.java
  91. 26 8
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentOrderService.java
  92. 43 7
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentQuotaService.java
  93. 159 1
      cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentService.java
  94. 33 2
      cfc-backend/src/main/java/com/etotem/cfc/service/BadgeService.java
  95. 52 0
      cfc-backend/src/main/java/com/etotem/cfc/service/BeijingNutritionService.java
  96. 5 0
      cfc-backend/src/main/java/com/etotem/cfc/service/CfBalanceService.java
  97. 534 3
      cfc-backend/src/main/java/com/etotem/cfc/service/CfCommissionService.java
  98. 1 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ContactService.java
  99. 54 7
      cfc-backend/src/main/java/com/etotem/cfc/service/CouponGiftService.java
  100. 25 3
      cfc-backend/src/main/java/com/etotem/cfc/service/CouponService.java

+ 22 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/AsyncConfig.java

@@ -7,11 +7,31 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
 
 import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicInteger;
 
 @Configuration
 public class AsyncConfig {
 
+    /**
+     * 守护线程工厂:LLM/LangGraph 异步调用面(taskExecutor/taskScheduler)使用非守护线程时,
+     * 任务挂起(如 LangGraph 服务 unresponsive)会导致进程无法退出,被外部 timeout 强杀(B-135-2
+     * EXIT=124 同源镜像契约 langgraph.pytest.exitHang)。注入守护线程工厂后,JVM/测试进程在任务挂起时
+     * 仍可正常退出。
+     */
+    private static ThreadFactory daemonThreadFactory(final String namePrefix) {
+        final AtomicInteger counter = new AtomicInteger(0);
+        return new ThreadFactory() {
+            @Override
+            public Thread newThread(Runnable r) {
+                Thread t = new Thread(r, namePrefix + counter.incrementAndGet());
+                t.setDaemon(true);
+                return t;
+            }
+        };
+    }
+
     @Bean(name = "taskExecutor")
     public ThreadPoolTaskExecutor taskExecutor() {
         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
@@ -20,6 +40,7 @@ public class AsyncConfig {
         executor.setQueueCapacity(100);
         executor.setKeepAliveSeconds(60);
         executor.setThreadNamePrefix("cfc-async-");
+        executor.setThreadFactory(daemonThreadFactory("cfc-async-"));
         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
         executor.initialize();
         return executor;
@@ -30,6 +51,7 @@ public class AsyncConfig {
         ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
         scheduler.setPoolSize(4);
         scheduler.setThreadNamePrefix("cfc-scheduler-");
+        scheduler.setThreadFactory(daemonThreadFactory("cfc-scheduler-"));
         scheduler.initialize();
         return scheduler;
     }

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/JwtConfig.java

@@ -48,10 +48,22 @@ public class JwtConfig {
     }
 
     public String generateToken(Long userId, List<String> roles) {
+        return generateToken(userId, roles, null);
+    }
+
+    /**
+     * 生成 token(多小程序:携带 mpCode claim,用于请求无 Header 时识别来源小程序)。
+     *
+     * @param mpCode 小程序路由标识;null/空则不写入 claim(老 token 兼容,回落 default app)
+     */
+    public String generateToken(Long userId, List<String> roles, String mpCode) {
         Map<String, Object> claims = new HashMap<>();
         claims.put("userId", userId);
         claims.put("role", roles.isEmpty() ? "" : roles.get(0));
         claims.put("roles", roles);
+        if (mpCode != null && !mpCode.trim().isEmpty()) {
+            claims.put("mpCode", mpCode.trim());
+        }
         return createToken(claims, userId.toString());
     }
 

+ 86 - 7
cfc-backend/src/main/java/com/etotem/cfc/config/JwtInterceptor.java

@@ -1,5 +1,8 @@
 package com.etotem.cfc.config;
 
+import com.etotem.cfc.context.MiniAppContext;
+import com.etotem.cfc.context.MiniAppContextHolder;
+import com.etotem.cfc.context.MiniAppContextResolver;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.User;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
@@ -34,6 +37,9 @@ public class JwtInterceptor implements HandlerInterceptor {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    @Resource
+    private MiniAppContextResolver miniAppContextResolver;
+
 private static final String[] PUBLIC_PATHS = {
          "/api/auth/send-code",
          "/api/auth/phone-login",
@@ -71,16 +77,22 @@ private static final String[] PUBLIC_PATHS = {
         "/api/articles/related",
         "/api/articles/related-by-product",
         "/api/content/related-items",
-         "/api/growth/**",
+         // 成长板块:record/**、plan/** 为成员私有数据(见 LOGIN_REQUIRED_PATHS,必须登录);
+         // 以下为公开子端点(无 userId 依赖),匿名直通时不注入 userId 也不拦截:
+         "/api/growth/recommendations",            // 成长板块推荐内容(公开)
+         "/api/growth/articles/ai-classify",       // 运营/批处理文章分类(公开)
+         "/api/growth/products/ai-classify",       // 运营/批处理商品分类(公开)
+         "/api/growth/external/sync",              // 外部数据同步(公开)
          "/api/activity/list",
          "/api/activity/detail",
          "/api/activity/order/notify",
          "/api/content-sections/visible",
-         "/api/mind/alert/active",
-         "/api/mind/alert/checkin-alerts",
-         "/api/mind/traditional/mirror",
-         "/api/mind/traditional/compatibility",
-         "/api/mcp/**"
+         // 会员券分享转赠:落地领取页匿名可浏览(share/detail 公开;其余 4 接口见 LOGIN_REQUIRED_PATHS)
+         "/api/coupon/gift/share/detail",
+         "/api/mcp/**",
+         // oauth.oauthClient.callback(S-cfc-411/412):外部授权页浏览器 GET 重定向 + 服务端 POST 兜底,
+         // 均无 JWT,必须匿名可达(B01/B02 WorkBuddy 上架:授权回调地址必须真实存在)
+         "/api/oauth/callback"
      };
 
     // 必须登录才能访问的路径:anonymous 访问直接 401(这些接口消耗微信配额/写数据/扣积分)
@@ -97,6 +109,8 @@ private static final String[] PUBLIC_PATHS = {
         // 杜绝匿名(userId=-1)被放行到 controller 后走"业务 500"而非安全 401 的口径漂移。
         "/api/auth/switch-role",            // 角色切换:属权限提升操作(可重签 token),必须登录
         "/api/family/user/switch-role",     // 角色切换(家庭侧):同上,必须登录
+        "/api/family/user/create-family",   // S-cfc-356(TC-P-01-P):建家庭/生成邀请属写操作,
+                                            // 无 token 匿名(userId=-1)不得放行,否则会建出无主家庭,必须 401
         "/api/family/member/list",          // 家庭成员列表:家庭私有数据,必须登录
         // SC-P-03-2 双角色切换(SC-P-03):切换视角属私有视角操作(仅本人家庭成员可切换),
         // 无 token 匿名(userId=-1)不得放行——必须 401,防业务 500 口径漂移。
@@ -115,9 +129,20 @@ private static final String[] PUBLIC_PATHS = {
         "/api/health/checkin/",             // 健康打卡:成员私有数据
         "/api/xiaomi-health/",              // 小米运动健康:OAuth 授权绑定/同步/撤销,成员私有凭证与数据
         "/api/huawei-health/",              // 华为运动健康:OAuth 授权绑定/同步/撤销,成员私有凭证与数据,必须登录(与 xiaomi-health 对齐)
+        // B-69(O-21 裁决):/api/mind/** 移出匿名白名单——运势/情绪预警/传统测试均为成员私有数据,
+        // 匿名(userId=-1)此前被 PUBLIC_PATHS 放行直通业务层(200/400 口径漂移),整族必须登录,无 token 直接 401。
+        "/api/mind/",                       // 心理解读:今日运势/情绪预警/传统测试/筛查/亲子画像,成员私有数据,必须登录
         "/api/tasks/",                      // 任务:家庭私有数据(今日/历史/审核/完成)
         "/api/energy/",                     // 五维能量:用户私有数据(sandbox/logs/grant/score-history...)
         "/api/wishes/",                     // 心愿:家庭私有数据
+        // 修复(2026-11-12):/api/growth/** 此前同时在 WebConfig 的 jwtInterceptor excludePathPatterns
+        // 与 PUBLIC_PATHS 中,拦截器对 growth 整族不执行/匿名放行,导致 GrowthRecordController.record/** 与
+        // GrowthPlanController.plan/** 的 @RequestAttribute("userId") 永不注入,无 token 一律
+        // 500 "Missing request attribute 'userId'"(线上小程序 /api/growth/record/list 报错)。
+        // 现从 WebConfig exclude 移除并在此强制登录:无 token 直接 401(客户端 api.js 401→静默续期→重放恢复),
+        // 有 token 正常注入 userId。公开子端点(recommendations/ai-classify/external-sync)见 PUBLIC_PATHS。
+        "/api/growth/record/",              // 成长记录:创建/列表/详情/上传/删除,成员私有数据,必须登录
+        "/api/growth/plan/",                // 成长方案:创建/列表/审核,成员私有数据,必须登录
         "/api/user/info",                   // 用户资料:个人私有
         "/api/user/family-members",         // 家庭成员列表:家庭私有
         "/api/user/children/list",          // 子女列表:家庭私有
@@ -127,7 +152,36 @@ private static final String[] PUBLIC_PATHS = {
         "/api/user/deactivate",             // 账号注销:隐私敏感
         // SC-X-22 CF 值获取预估:预估接口必须登录,游客无 token 直接 401,
         // 不泄露规则数值(契约 §7 第 1 行:不展示预估或「登录后可见」)。
-        "/api/reward/estimate"
+        "/api/reward/estimate",
+// B-142-1(P1 安全):/api/admin/** 整族鉴权门缺失——admin 业务端点(文章 CRUD、活动、
+        // 审核、配置等)此前仅 /api/admin-auth/* 登录端点走 PUBLIC_PATHS,匿名(userId=-1,
+        // role=anonymous)被放行至 controller 可越权执行敏感操作(如 create/audit);现整族强制
+        // 登录,无 token 直接 401,controller 层再按 @RequestAttribute("role") 守卫拒绝非 admin,
+        // 构成双层防线(契约:admin.article.create / S-cfc-153、admin.article.audit / S-cfc-154)。
+        // 注意 /api/admin-auth/* 不匹配此前缀(admin-auth ≠ admin/),仍走 PUBLIC_PATHS,不受影响。
+        "/api/admin/",
+        // 会员券分享转赠(ARCH-CFC-COUPON-SHARE-GIFT-001 §5):create/claim/revoke/list 为写数据/
+        // 私有数据操作,匿名(userId=-1)不得放行(否则业务 500 口径漂移),无 token 直接 401;
+        // detail 已在 PUBLIC_PATHS 公开(匿名可浏览)。
+        "/api/coupon/gift/share/create",
+        "/api/coupon/gift/share/claim",
+        "/api/coupon/gift/share/revoke",
+        "/api/coupon/gift/share/list"
+    };
+
+    /**
+     * 角色受限路径注册表(SC-X-19 跨角色 401/403 角色门,energy.ledger.guard · S-cfc-390)。
+     *
+     * <p>与 {@link #LOGIN_REQUIRED_PATHS}(登录门,无 token 401)互补:本注册表声明「仅特定角色可访问」
+     * 的受限端点族,跨角色调用(孩子 token 查家长/规划师端能量、规划师查非绑定家庭 F9)应返回 401/403。</p>
+     *
+     * <p><b>接线说明</b>:能量端点的跨角色/跨家庭拒绝当前由 {@code EnergyController.getEnergyOverview}
+     * 归属守卫(isMemberInFamily + 403)在控制器层执行(行为防线);本注册表为声明式角色门,供后续
+     * 在 preHandle 统一接线(如 /api/admin/** 的 role=admin 门),现仅注册不入 preHandle,避免运行时回归。</p>
+     */
+    public static final String[] ROLE_RESTRICTED_PATHS = {
+        "/api/energy/",     // 五维能量:仅本家庭/绑定成员可读写,跨角色 403(归属守卫已在 controller 落地)
+        "/api/admin/"       // 管理端:仅 admin 角色,见 preHandle 中 admin 现有分支(示例声明)
     };
 
     @Override
@@ -212,6 +266,24 @@ private static final String[] PUBLIC_PATHS = {
             request.setAttribute("role", role);
             request.setAttribute("roles", roles);
 
+            // 多小程序兜底:JWT claim 中的 mpCode 作为 Header 之外的第二优先级来源
+            // (MiniAppInterceptor 已按 Header/路径/参数先解析;若其未显式指定,则用 JWT claim 覆盖)
+            try {
+                Object mpCodeClaim = claims.get("mpCode");
+                if (mpCodeClaim != null && StringUtils.hasText(mpCodeClaim.toString())) {
+                    boolean headerExplicit = Boolean.TRUE.equals(request.getAttribute("mpCodeExplicit"));
+                    if (!headerExplicit) {
+                        MiniAppContext mpCtx = miniAppContextResolver.resolve(request, claims);
+                        request.setAttribute("mpCode", mpCtx.getMpCode());
+                        request.setAttribute("appId", mpCtx.getAppId());
+                        request.setAttribute("mpCodeExplicit", Boolean.TRUE);
+                        MiniAppContextHolder.set(mpCtx);
+                    }
+                }
+            } catch (Exception e) {
+                log.debug("解析 JWT mpCode claim 失败(忽略, 保留 MiniAppInterceptor 已解析的上下文): {}", e.getMessage());
+            }
+
             // COUPON-P2 ③:把角色列表发布到 Spring Security 上下文,供 @PreAuthorize 方法级校验使用
             try {
                 List<GrantedAuthority> authorities = new ArrayList<>(roles.size());
@@ -230,6 +302,13 @@ private static final String[] PUBLIC_PATHS = {
  // 设置familyId(查询用户所属家庭)
             try {
                 User user = userMapper.selectById(userId);
+                // 已注销(deleted=1)账号即使持有效 token 也拒绝:注销后不可登录、原 token 一键失效 401
+                // (auth.account.deactivate · SC-P-71 / TC-P-71-E:注销后 token 失效 401 不可登录)
+                if (user != null && user.getDeleted() != null && user.getDeleted() == 1) {
+                    log.warn("已注销账号请求被拒绝: userId={}, path={}", userId, path);
+                    writeUnauthorized(response);
+                    return false;
+                }
                 Long userFamilyId = (user != null) ? user.getFamilyId() : null;
                 // 兜底:user.family_id 为空时,从 family_members 表反查用户所属家庭
                 if (userFamilyId == null) {

+ 35 - 3
cfc-backend/src/main/java/com/etotem/cfc/config/RateLimitInterceptor.java

@@ -46,10 +46,16 @@ public class RateLimitInterceptor implements HandlerInterceptor {
     private volatile long lastRedisFailTime = 0L;
     private static final long REDIS_RETRY_INTERVAL_MS = 30_000L;
 
-    /** 限流配置:key模式 → {窗口毫秒, 允许次数} */
-    private static final Map<String, long[]> RATE_LIMIT_RULES = new ConcurrentHashMap<>();
+    /**
+     * 限流配置:key模式 → {窗口毫秒, 允许次数}。
+     *
+     * <p>非 {@code static final} 硬编码:阈值可通过 {@link #updateRule} 在线调整,
+     * 支撑 SC-A-20「配限流规则 → 生效」与 TC-A-21-E「误杀白名单」边界——默认规则误杀后
+     * 运营无需重启即可恢复,避免白名单 IP 被限流。</p>
+     */
+    private final Map<String, long[]> RATE_LIMIT_RULES = new ConcurrentHashMap<>();
 
-    static {
+    {
         // 认证接口:每 IP 每秒 10 次
         RATE_LIMIT_RULES.put("/api/auth/", new long[]{1000L, 10});
         RATE_LIMIT_RULES.put("/api/admin-auth/", new long[]{1000L, 10});
@@ -59,6 +65,32 @@ public class RateLimitInterceptor implements HandlerInterceptor {
         RATE_LIMIT_RULES.put("__default__", new long[]{1000L, 50});
     }
 
+    /**
+     * 更新/新增限流规则(SC-A-20 运营「配限流规则 → 生效」入口;TC-A-21-E 非法阈值守卫)。
+     *
+     * @param path        匹配的 key 模式(如 {@code /api/auth/}、精确路径或 {@code __default__})
+     * @param windowMs    滑动窗口毫秒数,必须为正
+     * @param maxRequests 窗口内允许次数,必须为正
+     * @return 规则合法并已生效返回 {@code true};参数非法(空 path / 非正阈值)返回 {@code false},
+     *         调用方应回 400(负阈值误杀白名单守卫)
+     */
+    public synchronized boolean updateRule(String path, long windowMs, int maxRequests) {
+        if (path == null || path.isEmpty() || windowMs <= 0 || maxRequests <= 0) {
+            log.warn("限流规则非法,拒绝更新: path={}, windowMs={}, maxRequests={}", path, windowMs, maxRequests);
+            return false;
+        }
+        RATE_LIMIT_RULES.put(path, new long[]{windowMs, maxRequests});
+        log.info("限流规则已生效: path={}, windowMs={}ms, maxRequests={}", path, windowMs, maxRequests);
+        return true;
+    }
+
+    /**
+     * 当前生效的限流规则只读快照(供监控大盘 / 配置查询展示)。
+     */
+    public Map<String, long[]> getRateLimitRules() {
+        return Collections.unmodifiableMap(RATE_LIMIT_RULES);
+    }
+
     /**
      * 滑动窗口限流 Lua 脚本(原子):
      *   1. 清理窗口外的旧记录

+ 14 - 3
cfc-backend/src/main/java/com/etotem/cfc/config/WebConfig.java

@@ -23,6 +23,9 @@ public class WebConfig implements WebMvcConfigurer {
 
     private static final Logger log = LoggerFactory.getLogger(WebConfig.class);
 
+    @Resource
+    private MiniAppInterceptor miniAppInterceptor;
+
     @Resource
     private JwtInterceptor jwtInterceptor;
 
@@ -92,6 +95,11 @@ public class WebConfig implements WebMvcConfigurer {
 
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
+        // 多小程序上下文拦截器:先于 JwtInterceptor 执行,按 Header/路径/参数解析 mpCode,
+        // 写入 request attr 与 MiniAppContextHolder(登录前也可识别;未携带一律 default)。
+        registry.addInterceptor(miniAppInterceptor)
+                .addPathPatterns("/api/**");
+
         registry.addInterceptor(jwtInterceptor)
                 .addPathPatterns("/api/**")
                 .excludePathPatterns(
@@ -122,7 +130,6 @@ public class WebConfig implements WebMvcConfigurer {
                 "/api/articles/related-products",
                 "/api/articles/related",
                 "/api/articles/related-by-product",
-                "/api/growth/**",
                 "/api/articles/updated-since",
                 "/api/activity/list",
                 "/api/activity/detail",
@@ -133,7 +140,9 @@ public class WebConfig implements WebMvcConfigurer {
                 "/api/payment/wechat/status",
                 "/api/payment/wechat/oauth2-url",
                 "/api/payment/wechat/oauth2-callback",
-                "/api/payment/wechat/v3-notify"
+                "/api/payment/wechat/v3-notify",
+                // oauth.oauthClient.callback(S-cfc-411/412):外部授权回调匿名可达(边界流-2)
+                "/api/oauth/callback"
         );
 
         registry.addInterceptor(operationLogInterceptor)
@@ -177,7 +186,9 @@ public class WebConfig implements WebMvcConfigurer {
                 "/api/growth/**",
                 "/api/activity/list",
                 "/api/activity/detail",
-                "/api/payment/wechat/v3-notify"
+                "/api/payment/wechat/v3-notify",
+                // oauth.oauthClient.callback(S-cfc-411/412):外部授权回调匿名可达(边界流-3)
+                "/api/oauth/callback"
         );
     }
 

+ 72 - 60
cfc-backend/src/main/java/com/etotem/cfc/constant/AttributionLowSideRules.java

@@ -17,11 +17,11 @@ import java.util.regex.Pattern;
  * 新增合规规则 {@code association_only == true};禁写「缺 X→致病/需补充」;
  * 禁把调整建议写成处方;措辞白名单「相关联/报告提示/可能与…有关」。
  *
- * <p>叠加 §T4(L4-3 偏低不推荐补菌红线,{@link #RULE_NO_LOW_SIDE_SUPPLEMENT}):
- * 无成熟证据支持「缺大肠杆菌→补大肠杆菌」;禁「报告缺 X → 买含 X 菌株产品」桥接;
- * 并叠加 {@link #S16S_GRANULARITY_NOTE}(§5.2 16S 粒度声明)。
+ * <p>叠加 §T6(G-2 16S 粒度拦截,P0):{@code granularity != strain}(16S/菌属层,默认)
+ * 时禁生成含菌株号的商品推荐(菌名 + 菌株号,如 长双歧杆菌 BB536);
+ * 菌株级粒度(strain,宏基因组)放行。叠加 §5.2 16S 粒度声明 —— 16S 只到菌属/种,不确知菌株号。
  *
- * @author 家庭归因阶段二(ATT-S2-B1,G-1 低侧红线组;T4 L4-3 偏低不推荐补菌)
+ * @author 家庭归因阶段二(ATT-S2-B1,G-1 低侧红线组 + G-2 16S 粒度拦截)
  */
 public final class AttributionLowSideRules {
 
@@ -33,24 +33,15 @@ public final class AttributionLowSideRules {
     public static final String RULE_ASSOCIATION_ONLY = "association_only";
     public static final String RULE_NO_CAUSAL_BRIDGE = "no_causal_bridge";
     public static final String RULE_NO_PRESCRIPTION = "no_prescription";
-    /**
-     * L4-3 偏低不推荐补菌红线规则码(guhe.lowSide.noSupplement / 计划 §三 T4 P0):
-     * 对「偏低」细菌节点禁生成「补/买/吃」类细菌(含菌株级)产品推荐。
-     */
-    public static final String RULE_NO_LOW_SIDE_SUPPLEMENT = "no_low_side_supplement";
 
-    /**
-     * §5.2 16S 粒度声明(叠加于 L4-3 偏低不推荐补菌红线):
-     * 16S 测序只到属/种粒度、测不到菌株,「报告缺 X → 买含 X 菌株产品」之间无桥。
-     */
-    public static final String S16S_GRANULARITY_NOTE =
-            "16S 测序只到属/种粒度,测不到菌株;报告缺 X 与含 X 菌株的商品之间无桥,禁止生成菌株级商品推荐";
+    /** T4 低位补菌红线(L4-3)规则码:偏低不推荐补菌——无成熟证据支持「缺大肠杆菌→补大肠杆菌」,
+     *  区别于 T5 的 no_causal_bridge(文本回扫),本规则码标识「L4 引擎源头不产出补菌建议」。 */
+    public static final String RULE_NO_SUPPLEMENT = "no_supplement";
 
-    /** L4-3 命中时的建议改写:偏低不推荐补菌(无成熟证据)+ §5.2 16S 粒度声明 */
+    /** T4(L4-3)「偏低不推荐补菌」口径常量(无成熟证据支持缺X→补X),
+     *  供 L4 归因引擎偏低含义路径与报告侧引用,源头拦截「报告缺 X → 买含 X 菌株产品」桥接。 */
     public static final String NO_SUPPLEMENT_HINT =
-            "偏低不推荐补菌:无成熟证据支持「缺大肠杆菌→补大肠杆菌」;"
-                    + "请改用措辞白名单表述,补类动作后置(先查血/复测、再由医生定);"
-                    + S16S_GRANULARITY_NOTE + "。";
+            "偏低不推荐补菌:无成熟证据支持缺X→补X,不推荐购买含该菌株的补菌产品。";
 
     /** G-2 门禁分组码(16S 粒度拦截 / 菌株级推荐阻断,T6 P0) */
     public static final String GROUP_CODE_2 = "G-2";
@@ -59,12 +50,68 @@ public final class AttributionLowSideRules {
     /** T6 G-2 规则码:非菌株级粒度禁生成含菌株号的商品推荐(叠加 §5.2 16S 粒度声明) */
     public static final String RULE_NO_STRAIN_RECOMMENDATION = "no_strain_recommendation";
 
+/** T11 G-3 规则码:证据码隔离(低侧机制证据标 PUB/KB;COM 只作存在性记录;未核实编号标「未核实」) */
+    public static final String RULE_EVIDENCE_ISOLATE = "evidence_isolate";
+
+    /** 证据码:公开文献(低侧机制证据,可进推荐依据) */
+    public static final String EVIDENCE_PUB = "PUB";
+
+    /** 证据码:知识库(低侧机制证据,可进推荐依据) */
+    public static final String EVIDENCE_KB = "KB";
+
+    /** 证据码:存在性记录(只作存在性记录,绝不进推荐依据,§一 合规门禁③) */
+    public static final String EVIDENCE_COM = "COM";
+
+    /** 未核实标注(未核实编号统一标此值,不得充当推荐依据) */
+    public static final String EVIDENCE_UNVERIFIED = "未核实";
+
+    // ------------------------------------------------------------------
+    // T3 低侧判读规则(L4-1/L4-2,guhe.lowSide.ruleLoad)
+    // 条件致病菌偏低侧判读规则入库:四机制 / U 型双向口径 / 参考下限 0;
+    // 规则码 + 判读铁律 + U 型口径常量 + 加载入口 lowSideInterpretRules(),
+    // 由 IndicatorInterpretEngine 低侧解读路径(偏低条件致病菌)加载应用。
+    // ------------------------------------------------------------------
+
+    /** T3(L4-1)低侧判读规则码:条件致病菌偏低侧按四机制解释 */
+    public static final String RULE_FOUR_MECHANISM = "four_mechanism";
+
+    /** T3(L4-2)低侧判读规则码:U 型双向口径(越低越好不成立) */
+    public static final String RULE_U_SHAPE = "u_shape";
+
+    /** T3(L4-2)低侧判读规则码:参考下限 0 的菌不标「偏低超标」(ND 只是低于检出丰度) */
+    public static final String RULE_REF_LOWER_ZERO = "ref_lower_zero";
+
+    /** T3(L4-1)判读铁律口径:低侧判读规则全部标「关联非因果」(四机制解释),供 L4 引擎取用 */
+    public static final String INTERPRET_LAW_LOW_SIDE =
+            "条件致病菌偏低侧按四机制解释,全部标「关联非因果」——偏低估只是伴随性观察,"
+                    + "不作因果归因、不写「缺X→致病/需补充」、不推荐补菌。";
+
+    /** T3(L4-2)U 型双向口径:条件致病菌「越低越好」不成立;参考下限 0 的菌不标「偏低超标」(ND 只是低于检出丰度) */
+    public static final String U_SHAPE_CALIBER_HINT =
+            "U 型双向口径:偏离人群参考区间两端都可能关联异常,「越低越好不成立」;"
+                    + "人群参考下限为 0 的报告不标注「偏低超标」,ND 仅表示低于检出丰度。";
+
+    /** P1-2 介导链路确定性因果审计规则码:输出侧拦截「导致/治愈/改善/典型表现/正是…的根/拖了…后腿」。 */
+    public static final String RULE_MEDIATOR_AUDIT = "mediator_audit";
+
+    /**
+     * §5.8 介导链路禁用词表(覆盖「导致/治愈/改善/典型表现/正是…的根/拖了…后腿」)。
+     * L5 出文档前 scan 回扫任意叙述/结论文本中的这些确定性因果措辞——命中即产出 mediator_audit 违规。
+     */
+    public static final List<String> FORBIDDEN_MEDIATOR_WORDS = Collections.unmodifiableList(Arrays.asList(
+            "导致", "治愈", "改善", "典型表现", "正是", "的根", "拖了", "后腿"));
+
+    /** §5.8 介导链路审计改写建议(关联非因果口径):命中禁用词时给下游的建议改写方向。 */
+    public static final String MEDIATOR_AUDIT_HINT =
+            "介导链只作上游信号、不判能力:请改用关联非因果措辞改写(相关联 / 报告提示 / 可能与…有关 / 待进一步确认),"
+                    + "禁「X导致Y」「这正是Z的典型表现」「正是…的根」「拖了…后腿」等确定性因果表述。";
+
     /**
      * 措辞白名单(关联非因果口径)。描述菌↔问题关联时,仅允许使用下列措辞;
      * 白名单外的因果表述(如「缺大肠杆菌→致病/需补充」)由门禁拦截并给出建议改写。
      */
     public static final List<String> WORDING_WHITELIST = Collections.unmodifiableList(Arrays.asList(
-            "相关联", "报告提示", "可能与…有关", "可能与", "有关"));
+            "相关联", "报告提示", "可能与…有关", "可能与", "有关", "待进一步确认"));
 
     /** 白名单兜底建议(命中违规时给下游的建议改写) */
     public static final String WHITELIST_HINT =
@@ -94,22 +141,14 @@ public final class AttributionLowSideRules {
             Pattern.compile("(长双歧杆菌|短双歧杆菌|动物双歧杆菌|乳双歧杆菌|两歧双歧杆菌|青春双歧杆菌|婴儿双歧杆菌|双歧杆菌|嗜酸乳杆菌|干酪乳杆菌|副干酪乳杆菌|植物乳杆菌|罗伊氏乳杆菌|鼠李糖乳杆菌|保加利亚乳杆菌|嗜热链球菌|凝结芽孢杆菌|酪酸梭菌|乳杆菌|乳酸菌|布拉氏酵母菌|益生菌)[^。;,,\\n]{0,6}[A-Z0-9]{2,}[A-Z0-9\\-]{0,8}")
     };
 
-    /**
-     * 禁写模式(L4-3 偏低不推荐补菌红线):动词(补/买/吃/服…)+ 细菌名(含菌株级)。
-     * 需配否定词窗口过滤(见 {@link #NEGATION_WINDOW}):「不推荐补菌」「禁补X」等安全表述不算命中。
-     * 细菌目标含属级(双歧/乳杆菌/拟杆菌…)与菌株级(菌粉/菌株/Bifidobacterium…),与 §5.2 16S 粒度声明对齐。
-     */
-    private static final Pattern[] FORBIDDEN_SUPPLEMENT_PATTERNS = {
-            Pattern.compile("(补|补食|补充|服用|口服|摄入|吃|喝|喂|进食|加菌|买|购买|选购|下单|采购)[^。;,,\\n]{0,6}(大肠杆菌|大肠埃希|埃希氏菌|益生菌|益生元|双歧|乳杆菌|乳球菌|肠球菌|梭菌|芽孢杆菌|粪杆菌|拟杆菌|普雷沃|链球菌|金双歧|整肠生|菌粉|菌株|该菌|此菌|这种菌|Bifidobacterium|Lactobacillus|Escherichia|E(_|\\s)?coli)")
-    };
-
-    /** 否定词窗口(命中片段前 10 字内出现即非违规:不补/禁补/无需补/不推荐补 等安全表述) */
-    public static final Pattern NEGATION_WINDOW =
-            Pattern.compile("(不|禁|无|未|别|勿|慎|避免|无需|不应|不建议)");
-
     private AttributionLowSideRules() {
     }
 
+    /** T3 低侧判读规则加载入口:返回已入库的低侧判读规则码集合(供 L4 引擎加载应用) */
+    public static List<String> lowSideInterpretRules() {
+        return Arrays.asList(RULE_FOUR_MECHANISM, RULE_U_SHAPE, RULE_REF_LOWER_ZERO);
+    }
+
     public static List<Pattern> causalPatterns() {
         return Collections.unmodifiableList(Arrays.asList(FORBIDDEN_CAUSAL_PATTERNS));
     }
@@ -136,33 +175,6 @@ public final class AttributionLowSideRules {
         return false;
     }
 
-    /** L4-3 偏低不推荐补菌禁写模式访问器 */
-    public static List<Pattern> supplementPatterns() {
-        return Collections.unmodifiableList(Arrays.asList(FORBIDDEN_SUPPLEMENT_PATTERNS));
-    }
-
-    /**
-     * 判定文本是否命中「偏低不推荐补菌」禁令(L4-3)。
-     * 命中片段前 10 字内出现否定词(不/禁/无/未/别/勿/慎/避免/无需/不应/不建议)时视为安全表述,
-     * 不计为违规——保证「不推荐补菌」「禁补大肠杆菌」等合规描述不误报。
-     */
-    public static boolean hitsLowSideSupplement(String text) {
-        if (text == null) {
-            return false;
-        }
-        for (Pattern p : FORBIDDEN_SUPPLEMENT_PATTERNS) {
-            java.util.regex.Matcher m = p.matcher(text);
-            while (m.find()) {
-                int windowStart = Math.max(0, m.start() - 10);
-                String ctx = text.substring(windowStart, m.start());
-                if (!NEGATION_WINDOW.matcher(ctx).find()) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
     /** 判定文本是否命中「缺 X → 致病/需补充」因果桥接禁令 */
     public static boolean hitsCausalBridge(String text) {
         if (text == null) {

+ 22 - 0
cfc-backend/src/main/java/com/etotem/cfc/constant/CfConfigKeys.java

@@ -39,6 +39,22 @@ public final class CfConfigKeys {
     public static final String PRODUCT_GUT_HEALTH_PRICE = "cf.product.gut_health_price";
     /** 产品平台积分分成比例(bps) */
     public static final String PRODUCT_PLATFORM_POINTS_SHARE = "cf.product.platform_points_share";
+
+    // ==================== CF 分润模型 v2:R0 平台抽成 + 团队池(T01,cf.rewardv2.migrateConfig) ====================
+
+    /** R0 平台抽成(成交价百分比 bps;基数=实付,如 1000=10%) */
+    public static final String PLATFORM_TAKE_RATE_BPS = "cf.platform.take_rate_bps";
+    /** 团队池总开关 */
+    public static final String TEAM_POOL_ENABLED = "cf.team_pool.enabled";
+    /** GLOBAL 兜底 T(团队池比例 bps,如 3000=30%) */
+    public static final String TEAM_POOL_DEFAULT_T_BPS = "cf.team_pool.default_t_bps";
+    /** 亏损仓处理:payout=照常发 / zero=不发 */
+    public static final String TEAM_POOL_ON_LOSS = "cf.team_pool.on_loss";
+    /** 池瓜分最大层级(默认 8) */
+    public static final String TEAM_POOL_MAX_DEPTH = "cf.team_pool.max_depth";
+    /** 非商品成本率(bps,默认 5000=50%),非商品订单进池用 */
+    public static final String TEAM_POOL_NON_GOODS_COST_RATE = "cf.team_pool.non_goods_cost_rate";
+
     /** 1 元 = 多少 CF(F02/F06/F18 消费返 CF 口径,1 元 = 100 CF) */
     public static final String RATE_CF_PER_YUAN = "cf.rate.cf_per_yuan";
     /** 个人 CF 值提现开关(默认关闭,Q4 合规审查待定) */
@@ -78,6 +94,12 @@ public final class CfConfigKeys {
         m.put(COMMISSION_SERVICE_RATE, "1000");
         m.put(PRODUCT_GUT_HEALTH_PRICE, "1990");
         m.put(PRODUCT_PLATFORM_POINTS_SHARE, "1000");
+        m.put(PLATFORM_TAKE_RATE_BPS, "1000");
+        m.put(TEAM_POOL_ENABLED, "true");
+        m.put(TEAM_POOL_DEFAULT_T_BPS, "3000");
+        m.put(TEAM_POOL_ON_LOSS, "payout");
+        m.put(TEAM_POOL_MAX_DEPTH, "8");
+        m.put(TEAM_POOL_NON_GOODS_COST_RATE, "5000");
         m.put(RATE_CF_PER_YUAN, "100");
         m.put(WITHDRAW_ENABLED, "false");
         m.put(CF_VERSION, "1");

+ 4 - 1
cfc-backend/src/main/java/com/etotem/cfc/constant/ConditionalPathogenLowSideRules.java

@@ -33,6 +33,9 @@ public final class ConditionalPathogenLowSideRules {
     public static final String GROUP_CODE = "L4-1";
     public static final String GROUP_TITLE = "条件致病菌低侧判读(四机制 · 关联非因果 · U 型双向)";
 
+    /** 判读口径键名(§2.2 KB 新增子键「条件致病菌低侧判读补充(人工)」,P3 跨案例聚合口径的事实锚点,T15) */
+    public static final String LOW_SIDE_READING_KEY = "条件致病菌低侧判读补充(人工)";
+
     /** 大肠杆菌 / 埃希氏菌属(16S 属/种级)匹配键 */
     private static final List<String> ECOLI_KEYS = Collections.unmodifiableList(Arrays.asList(
             "大肠杆菌", "埃希氏", "escherichia", "ecoli"));
@@ -92,7 +95,7 @@ public final class ConditionalPathogenLowSideRules {
      */
     private static final String ECOLI_MEANING_TEMPLATE =
             "偏低提示(关联非因果):健康区间是范围而非单向(U 型双向口径:偏离人群参考区间两端都可能关联异常,"
-                    + "\"低就是好\"不成立);人群参考下限为 0 的报告不标注\"偏低超标\",ND 仅表示低于检出丰度。"
+                    + "\"低就是好\"不成立(即越低越好不成立));人群参考下限为 0 的报告不标注\"偏低超标\",ND 仅表示低于检出丰度。"
                     + "机制参考(文献关联,非因果):①耗氧维持肠腔厌氧——共生株消耗氧气协助维持厌氧环境,"
                     + "丰度过低时厌氧群落保护力减弱(Cell Host Microbe 2019, PMID 30629913);"
                     + "②定植抵抗与生态位——占位、铁载体竞争、黏蛋白降解利用抑制致病菌过度定植(MDPI Pathogens 2024 综述);"

+ 15 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/BadgeController.java

@@ -48,21 +48,33 @@ public class BadgeController {
 
     @Operation(summary = "创建勋章")
     @PostMapping("/create")
-    public Result<String> createBadge(@RequestBody Badge badge) {
+    public Result<String> createBadge(@RequestBody Badge badge,
+                                      @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         badgeService.createBadge(badge);
         return Result.success("创建成功");
     }
 
     @Operation(summary = "更新勋章")
     @PostMapping("/update")
-    public Result<String> updateBadge(@RequestBody Badge badge) {
+    public Result<String> updateBadge(@RequestBody Badge badge,
+                                      @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         badgeService.updateBadge(badge);
         return Result.success("更新成功");
     }
 
     @Operation(summary = "删除勋章")
     @PostMapping("/delete")
-    public Result<String> deleteBadge(@RequestBody Map<String, Object> body) {
+    public Result<String> deleteBadge(@RequestBody Map<String, Object> body,
+                                      @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         badgeService.deleteBadge(id);
         return Result.success("删除成功");

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ContactController.java

@@ -2,7 +2,9 @@ package com.etotem.cfc.controller;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.ContactDTO;
+import com.etotem.cfc.dto.ContactImportResultVO;
 import com.etotem.cfc.entity.Contact;
+import com.etotem.cfc.service.ContactImportService;
 import com.etotem.cfc.service.ContactService;
 import org.springframework.web.bind.annotation.*;
 
@@ -18,6 +20,9 @@ public class ContactController {
     @Resource
     private ContactService contactService;
 
+    @Resource
+    private ContactImportService contactImportService;
+
     @PostMapping("/list")
     public Result<List<ContactDTO>> list(@RequestAttribute("userId") Long userId) {
         return contactService.list(userId);
@@ -58,6 +63,15 @@ public class ContactController {
         return contactService.importFromPhone(name, phone, extra, userId);
     }
 
+    /** 分组批量导入(SC-P-62 建分组 → 导入,按 groupId 归组;格式错误行跳过并报告) */
+    @PostMapping("/import-group")
+    public Result<ContactImportResultVO> importGroup(@RequestBody Map<String, Object> params,
+                                                     @RequestAttribute("userId") Long userId) {
+        String csv = (String) params.get("csv");
+        Long groupId = ParamUtils.getLong(params.get("groupId"));
+        return contactImportService.importBatch(csv, groupId, userId);
+    }
+
     @PostMapping("/interaction")
     public Result<ContactDTO> interaction(@RequestBody Map<String, Object> params,
                                           @RequestAttribute("userId") Long userId) {

+ 42 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/ContentFilterController.java

@@ -10,6 +10,8 @@ import com.etotem.cfc.mapper.ArticleMapper;
 import com.etotem.cfc.mapper.FoodMapper;
 import com.etotem.cfc.mapper.HealthKnowledgeBaseMapper;
 import com.etotem.cfc.mapper.ProblemDomainMapper;
+import com.etotem.cfc.service.api.WechatServiceInterface;
+import com.etotem.cfc.util.PlanContentSafetyUtil;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import javax.annotation.Resource;
@@ -47,6 +49,10 @@ public class ContentFilterController {
     @Resource
     private ProblemDomainMapper problemDomainMapper;
 
+    /** SC-T-28:方案内容安全复核原语(wechatService.checkText,true=安全) */
+    @Resource
+    private WechatServiceInterface wechatService;
+
     @Operation(summary = "按 resultTags + 问题域 code 过滤文章/知识库/饮食")
     @PostMapping("/by-tags")
     public Result<Map<String, Object>> byTags(@RequestBody Map<String, Object> params) {
@@ -83,6 +89,42 @@ public class ContentFilterController {
         return Result.success(data);
     }
 
+    /**
+     * SC-T-28:方案内容安全复核端点(AI 方案送审/发布前调用,命中即拦截)。
+     * 请求体支持 {@code content}(方案正文)或 {@code planContent}/{@code planJson}(直接传入方案字段)。
+     */
+    @Operation(summary = "方案内容安全复核(SC-T-28,命中即拦截)")
+    @PostMapping("/plan-safety")
+    public Result<Map<String, Object>> planSafety(@RequestBody(required = false) Map<String, Object> params) {
+        String content = null;
+        if (params != null) {
+            Object raw = params.get("content");
+            if (raw != null) content = String.valueOf(raw);
+            if (content == null || content.trim().isEmpty()) {
+                Object planContent = params.get("planContent");
+                if (planContent != null) content = String.valueOf(planContent);
+            }
+            if (content == null || content.trim().isEmpty()) {
+                Object planJson = params.get("planJson");
+                if (planJson != null) content = String.valueOf(planJson);
+            }
+        }
+        if (content == null || content.trim().isEmpty()) {
+            return Result.error("content不能为空");
+        }
+
+        String unsafe = PlanContentSafetyUtil.matchUnsafeTerm(content);
+        if (unsafe == null && wechatService != null && !wechatService.checkText(content)) {
+            unsafe = "第三方内容安全检测未通过";
+        }
+
+        Map<String, Object> resp = new HashMap<>();
+        resp.put("safe", unsafe == null);
+        resp.put("hitTerm", unsafe);
+        resp.put("message", unsafe == null ? "内容安全" : "命中违规词:「" + unsafe + "」");
+        return Result.success(resp);
+    }
+
     /** 文章:tags 字段 LIKE 任一标签 */
     private List<Article> filterArticles(Set<String> tags, int size) {
         if (tags.isEmpty()) {

+ 66 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/CouponGiftController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.service.CouponGiftService;
+import com.etotem.cfc.service.CouponShareService;
 import com.etotem.cfc.util.ParamUtils;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
@@ -24,6 +25,9 @@ public class CouponGiftController {
     @Resource
     private CouponGiftService couponGiftService;
 
+    @Resource
+    private CouponShareService couponShareService;
+
     /** 可接收转赠的推荐下级列表(直推 + 隔级) */
     @PostMapping("/recipients")
     public Result<List<Map<String, Object>>> recipients(@RequestAttribute("userId") Long userId) {
@@ -78,4 +82,66 @@ public class CouponGiftController {
     public Result<List<Map<String, Object>>> received(@RequestAttribute("userId") Long userId) {
         return Result.success(couponGiftService.listReceived(userId));
     }
+
+    // ==================== 分享转赠(/api/coupon/gift/share/*,ARCH-CFC-COUPON-SHARE-GIFT-001 §5) ====================
+
+    /** 创建分享:生成 shareToken(幂等:同 giver+familyCouponId 已有 PENDING 返回既有 token) */
+    @PostMapping("/share/create")
+    public Result<Map<String, Object>> shareCreate(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        Long familyCouponId = ParamUtils.getLong(params.get("familyCouponId"));
+        try {
+            return Result.success(couponShareService.create(userId, familyCouponId));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 分享详情(公开接口,匿名可浏览;JwtInterceptor 已放行 detail,不注入 userId) */
+    @PostMapping("/share/detail")
+    public Result<Map<String, Object>> shareDetail(@RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            return Result.success(couponShareService.detail(shareToken, null));
+        } catch (IllegalArgumentException e) {
+            if (CouponShareService.MSG_SHARE_NOT_FOUND.equals(e.getMessage())) {
+                return Result.notFound(e.getMessage());
+            }
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 领取分享:条件更新防重领,成功返回 transferId */
+    @PostMapping("/share/claim")
+    public Result<Map<String, Object>> shareClaim(@RequestAttribute("userId") Long userId,
+                                                  @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            Long transferId = couponShareService.claim(userId, shareToken);
+            Map<String, Object> data = new java.util.HashMap<>();
+            data.put("transferId", transferId);
+            return Result.success(data);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 撤回一笔 PENDING 分享(不动券实例) */
+    @PostMapping("/share/revoke")
+    public Result<Map<String, Object>> shareRevoke(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            couponShareService.revoke(userId, shareToken);
+            return Result.success(java.util.Collections.singletonMap("message", "已撤回"));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 我的分享记录(created_at DESC) */
+    @PostMapping("/share/list")
+    public Result<List<Map<String, Object>>> shareList(@RequestAttribute("userId") Long userId) {
+        return Result.success(couponShareService.list(userId));
+    }
 }

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/DanAssessmentController.java

@@ -74,6 +74,12 @@ public class DanAssessmentController {
         return Result.success(assessmentService.getMaterialList());
     }
 
+    @Operation(summary = "获取测评类型字典(DAN 8 类,类目来自后端字典)")
+    @PostMapping("/material/types")
+    public Result<List<String>> listMaterialTypes() {
+        return Result.success(assessmentService.listAssessmentTypes());
+    }
+
     // ===== 积分配置 =====
 
 @Operation(summary = "获取积分配置")

+ 4 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/EnergyController.java

@@ -169,6 +169,10 @@ public class EnergyController {
         if (familyId == null) {
             return Result.noFamily("请先创建或加入家庭");
         }
+        // SC-X-19 跨角色数据隔离(G-10 修复):本人放行;同家庭成员放行;跨家庭 memberId 一律 403。
+        if (!memberId.equals(currentMemberId) && !energyService.isMemberInFamily(memberId, familyId)) {
+            return Result.forbidden("无权访问该成员的能量数据");
+        }
         Map<String, Object> data = energyService.getOverview(memberId);
         return Result.success(data);
     }

+ 2 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/FoodRecommendController.java

@@ -67,7 +67,8 @@ public class FoodRecommendController {
         for (Map.Entry<Long, List<FoodRecommendIndex>> entry : byMember.entrySet()) {
             result.put(String.valueOf(entry.getKey()), entry.getValue());
         }
-        // T28:家庭总览持久化最小值(与 /api/health/foods/by-family 口径一致)
+        // T28/迁移465:家庭总览分段聚合(有成员<0取最低值、全员>=0取平均值),
+        // 与 /api/health/foods/by-family 口径一致;overview 元素含 overviewScore + 兼容字段 minIndexScore
         result.put("overview", familyFoodOverviewService.getOverviewMaps(familyId));
         return Result.success(result);
     }

+ 4 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/GameRecordController.java

@@ -63,12 +63,13 @@ public class GameRecordController {
         return Result.success(gameRecordService.getStats(memberId));
     }
 
-    @Operation(summary = "获取排行榜")
+    @Operation(summary = "获取排行榜(家庭内,SC-P-86 数据仅本家庭可见)")
     @PostMapping("/leaderboard")
-    public Result<List<Map<String, Object>>> getLeaderboard(@RequestBody Map<String, Object> body) {
+    public Result<List<Map<String, Object>>> getLeaderboard(@RequestBody Map<String, Object> body,
+                                                            @RequestAttribute(value = "familyId", required = false) Long familyId) {
         String gameCode = (String) body.get("gameCode");
         Integer limit = body.get("limit") != null
                 ? Integer.valueOf(body.get("limit").toString()) : 10;
-        return Result.success(gameRecordService.getLeaderboard(gameCode, limit));
+        return Result.success(gameRecordService.getLeaderboard(gameCode, limit, familyId));
     }
 }

+ 42 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/GrowthController.java

@@ -1,7 +1,9 @@
 package com.etotem.cfc.controller;
 
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.GrowthMilestoneService;
 import com.etotem.cfc.service.GrowthRecommendationService;
+import com.etotem.cfc.util.ParamUtils;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.web.bind.annotation.*;
@@ -19,13 +21,17 @@ public class GrowthController {
     @Resource
     private GrowthRecommendationService growthRecommendationService;
 
+    @Resource
+    private GrowthMilestoneService growthMilestoneService;
+
     @Operation(summary = "获取成长板块推荐内容")
     @PostMapping("/recommendations")
     public Result<Map<String, Object>> getRecommendations(
             @RequestParam(defaultValue = "health") String category,
-            @RequestParam(defaultValue = "3") int limit) {
+            @RequestParam(defaultValue = "3") int limit,
+            @RequestAttribute(value = "userId", required = false) Long userId) {
         List<Map<String, Object>> articles = growthRecommendationService.getRecommendedArticles(category, limit);
-        List<Map<String, Object>> products = growthRecommendationService.getRecommendedProducts(category, limit);
+        List<Map<String, Object>> products = growthRecommendationService.getRecommendedProducts(category, limit, userId);
         Map<String, Object> data = new HashMap<>();
         data.put("articles", articles);
         data.put("products", products);
@@ -45,4 +51,38 @@ public class GrowthController {
             @RequestParam(defaultValue = "20") int batchSize) {
         return Result.success(growthRecommendationService.autoClassifyProducts(batchSize));
     }
+
+    // ========== 成长里程碑(SC-P-51 / 缺口 G-2:growth.milestone.mark)==========
+
+    @Operation(summary = "标记成长里程碑(系统/手动标,返回里程碑ID,幂等)")
+    @PostMapping("/milestone/mark")
+    public Result<Long> markMilestone(@RequestBody Map<String, Object> body,
+                                      @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        Long recordId = ParamUtils.getLong(body.get("recordId"));
+        String milestoneType = body.get("milestoneType") != null
+                ? body.get("milestoneType").toString() : "manual";
+        if (memberId == null || recordId == null) {
+            return Result.error("缺少必要参数: memberId, recordId");
+        }
+        Long milestoneId = growthMilestoneService.markMilestone(memberId, recordId, milestoneType);
+        return Result.success("标记成功", milestoneId);
+    }
+
+    @Operation(summary = "查询成长记录是否已标记里程碑(时间线高亮判定)")
+    @PostMapping("/milestone/marked")
+    public Result<Map<String, Object>> isMilestoneMarked(@RequestBody Map<String, Object> body,
+                                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        Long memberId = ParamUtils.getLong(body.get("memberId"), currentMemberId);
+        Long recordId = ParamUtils.getLong(body.get("recordId"));
+        String milestoneType = body.get("milestoneType") != null
+                ? body.get("milestoneType").toString() : "manual";
+        if (memberId == null || recordId == null) {
+            return Result.error("缺少必要参数: memberId, recordId");
+        }
+        boolean marked = growthMilestoneService.isMarked(memberId, recordId, milestoneType);
+        Map<String, Object> result = new HashMap<>();
+        result.put("marked", marked);
+        return Result.success(result);
+    }
 }

+ 63 - 33
cfc-backend/src/main/java/com/etotem/cfc/controller/GrowthTaskController.java

@@ -14,14 +14,17 @@ import java.util.Map;
 @RequestMapping("/api/growth-task")
 public class GrowthTaskController {
 
- @Resource
- private GrowthTaskService growthTaskService;
+  @Resource
+  private GrowthTaskService growthTaskService;
 
- @Resource
- private GrowthTaskMapper growthTaskMapper;
+  @Resource
+  private GrowthTaskMapper growthTaskMapper;
 
- @Resource
- private com.etotem.cfc.mapper.TaskMapper taskMapper;
+  @Resource
+  private com.etotem.cfc.mapper.TaskMapper taskMapper;
+
+  @Resource
+  private com.etotem.cfc.service.TaskService taskService;
 
     @PostMapping("/list")
     public Result<List<Map<String, Object>>> list(@RequestAttribute("userId") Long userId,
@@ -29,32 +32,59 @@ public class GrowthTaskController {
 return Result.success(growthTaskService.getTaskList(userId, params));
     }
 
- @PostMapping("/claim")
- public Result<String> claim(@RequestAttribute("userId") Long userId,
-     @RequestBody Map<String, Long> params) {
+  @PostMapping("/claim")
+  public Result<String> claim(@RequestAttribute("userId") Long userId,
+      @RequestBody Map<String, Long> params) {
    // 统一任务系统:奖励自动发放,无 claimed 概念
    return Result.success("奖励已自动发放");
- }
-
- @PostMapping("/accept-dynamic")
- public Result<Map<String, Object>> acceptDynamic(@RequestAttribute("userId") Long userId,
-     @RequestBody Map<String, Object> params) {
-   Object taskIdObj = params.get("taskId");
-   if (taskIdObj == null) {
-     return Result.error("taskId不能为空");
-   }
-   Long taskId = ((Number) taskIdObj).longValue();
-   // 统一任务系统:AI 任务已迁入 tasks 表(source_type=ai)
-   com.etotem.cfc.entity.Task task = taskMapper.selectById(taskId);
-   if (task == null) {
-     return Result.error("任务不存在");
-   }
-   Map<String, Object> taskInfo = new java.util.HashMap<>();
-   taskInfo.put("id", task.getId());
-   taskInfo.put("title", task.getTitle());
-   taskInfo.put("description", task.getDescription());
-   taskInfo.put("dimension", task.getDimensionCode());
-   taskInfo.put("rewardPoints", task.getPoints());
-   return Result.success(taskInfo);
- }
- }
+  }
+
+  @PostMapping("/accept-dynamic")
+  public Result<Map<String, Object>> acceptDynamic(@RequestAttribute("userId") Long userId,
+      @RequestBody Map<String, Object> params) {
+    Object taskIdObj = params.get("taskId");
+    if (taskIdObj == null) {
+      return Result.error("taskId不能为空");
+    }
+    Long taskId = ((Number) taskIdObj).longValue();
+    // 统一任务系统:AI 任务已迁入 tasks 表(source_type=ai)
+    com.etotem.cfc.entity.Task task = taskMapper.selectById(taskId);
+    if (task == null) {
+      return Result.error("任务不存在");
+    }
+    Map<String, Object> taskInfo = new java.util.HashMap<>();
+    taskInfo.put("id", task.getId());
+    taskInfo.put("title", task.getTitle());
+    taskInfo.put("description", task.getDescription());
+    taskInfo.put("dimension", task.getDimensionCode());
+    taskInfo.put("rewardPoints", task.getPoints());
+    return Result.success(taskInfo);
+  }
+
+  /**
+   * 方案任务打卡提交(SC-C-05 任务打卡⭐,能力键 child.task.checkin)。
+   *
+   * <p>委托统一任务系统 {@code TaskService.completeTask} 完成打卡提交:幂等(T24-A)、
+   * 发奖/审核流转/逾期限均走既有链路;本端点只做入参承载与结果包装。</p>
+   *
+   * @param dto 打卡提交入参(memberId/taskId + photoUrl/content 凭证)
+   */
+  @PostMapping("/checkin")
+  public Result<Map<String, Object>> checkin(@RequestBody com.etotem.cfc.dto.TaskCheckinDTO dto,
+      @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+    if (dto == null) {
+      return Result.error("打卡入参不能为空");
+    }
+    if (dto.getTaskId() == null) {
+      return Result.error("taskId不能为空");
+    }
+    Long memberId = dto.getMemberId() != null ? dto.getMemberId() : currentMemberId;
+    Map<String, Object> result = taskService.completeTask(dto.getTaskId(), memberId,
+        dto.getPhotoUrl(), dto.getContent(),
+        dto.getContentType() != null ? dto.getContentType() : "text");
+    if (result != null) {
+      return Result.success(result);
+    }
+    return Result.error("任务不存在、无权完成或状态已变更");
+  }
+  }

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

@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import com.etotem.cfc.util.ParamUtils;
@@ -205,6 +206,80 @@ public class HealthPlanController {
         return Result.success(tasks);
     }
 
+    // ===== HL-05/R5+R6:产品多选一购买任务 + 购买后执行任务 =====
+
+    @Operation(summary = "方案产品多选一选项(R5:每类产品按效果评分+价格给出多选一)")
+    @PostMapping("/product-options")
+    public Result<List<Map<String, Object>>> productOptions(@RequestBody Map<String, Object> params,
+                                                            @RequestAttribute("userId") Long userId,
+                                                            @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        Long planId = ParamUtils.getLong(params.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        if (familyId == null) return Result.error("familyId不能为空");
+        List<Map<String, Object>> groups;
+        try {
+            groups = healthPlanService.getPlanProductGroups(planId, familyId, userId);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+        if (groups == null) {
+            return Result.error("无权查看该方案产品");
+        }
+        return Result.success(groups);
+    }
+
+    @Operation(summary = "确认产品选择 → 生成购买任务(本平台产品直接加入购物车)")
+    @PostMapping("/product-select")
+    @SuppressWarnings("unchecked")
+    public Result<Map<String, Object>> productSelect(@RequestBody Map<String, Object> params,
+                                                     @RequestAttribute("userId") Long userId,
+                                                     @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        Long planId = ParamUtils.getLong(params.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        if (familyId == null) return Result.error("familyId不能为空");
+        List<Map<String, Object>> selections = new ArrayList<>();
+        Object rawSelections = params.get("selections");
+        if (rawSelections instanceof List) {
+            for (Object item : (List<?>) rawSelections) {
+                if (item instanceof Map) {
+                    selections.add((Map<String, Object>) item);
+                }
+            }
+        }
+        if (selections.isEmpty()) return Result.error("selections不能为空");
+        Map<String, Object> result;
+        try {
+            result = healthPlanService.confirmProductSelection(planId, familyId, userId, selections);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+        if (result == null) {
+            return Result.error("无权操作该方案");
+        }
+        return Result.success(result);
+    }
+
+    @Operation(summary = "购买完成 → 按方案建议生成执行任务(R6)")
+    @PostMapping("/purchase-complete")
+    public Result<Map<String, Object>> purchaseComplete(@RequestBody Map<String, Object> params,
+                                                        @RequestAttribute("userId") Long userId,
+                                                        @RequestAttribute(value = "familyId", required = false) Long familyId) {
+        Long planId = ParamUtils.getLong(params.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        if (familyId == null) return Result.error("familyId不能为空");
+        Long purchaseTaskId = ParamUtils.getLong(params.get("purchaseTaskId"));
+        Map<String, Object> result;
+        try {
+            result = healthPlanService.completePurchaseAndGenerateTasks(planId, familyId, purchaseTaskId);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+        if (result == null) {
+            return Result.error("无权操作该方案");
+        }
+        return Result.success(result);
+    }
+
     @Operation(summary = "删除健康方案(级联删除方案产生的全部任务,含每日实例)")
     @PostMapping("/delete")
     public Result<Map<String, Object>> deletePlan(@RequestBody Map<String, Object> params,

+ 139 - 8
cfc-backend/src/main/java/com/etotem/cfc/controller/HealthReportController.java

@@ -39,6 +39,7 @@ import com.etotem.cfc.service.FoodService;
 import com.etotem.cfc.service.HealthAnalysisService;
 import com.etotem.cfc.service.HealthReportDraftService;
 import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.ReportArchiveCompareService;
 import com.etotem.cfc.service.MemberIndicatorCurrentService;
 import com.etotem.cfc.service.BasicQuotaService;
 import com.etotem.cfc.service.NutritionDeficiencyService;
@@ -99,6 +100,32 @@ public class HealthReportController {
     private static final String LANGGRAPH_BASE_URL = "http://localhost:9000";
     private static final String REPORT_PARSE_URL = LANGGRAPH_BASE_URL + "/api/v1/report/parse";
 
+/** P0-3 ③:collect/status 响应暴露 collect_validation(键名)——前端轮询时可核对 _解析自检 结果 */
+    public static final String COLLECT_VALIDATION_KEY = "collect_validation";
+
+    // ==================== §6.1 / P0-2 上传-异步路由契约锚点(S-cfc-424 health.report.guheV2AsyncRoute) ====================
+    // 谷禾新版解析与五维归因升级方案 v1.0 §3 P0-2 / §6.1 6.1:
+    //   - POST /api/health/report/upload 响应新增 reportFormat(guhe/guhe_v2/beijing/aidefansi)、
+    //     parseMethod(local/langgraph)、draftId(异步时返回);
+    //   - P0-2:uploadReport() 识别到 guhe_v2 时自动切换 upload-only + submitAsyncCollect(),
+    //     返回 parseMethod="langgraph",前端跳「解析中」等待页;
+    //   - collect/status 响应新增 parseSelfCheck(JSON,_解析自检)。
+
+    /** §6.1 上传响应键:reportFormat(guhe / guhe_v2 / beijing / aidefansi) */
+    public static final String RESPONSE_KEY_REPORT_FORMAT = "reportFormat";
+
+    /** §6.1 上传响应键:parseMethod(local / langgraph) */
+    public static final String RESPONSE_KEY_PARSE_METHOD = "parseMethod";
+
+    /** P0-2 / §6.1:guhe_v2 异步解析方式值 parseMethod="langgraph" */
+    public static final String PARSE_METHOD_LANGGRAPH = "langgraph";
+
+    /** P0-2 / §6.1:guhe_v2 新版报告格式标记(uploadReport 识别后切异步,reportFormat 值之一) */
+    public static final String FORMAT_GUHE_V2 = "guhe_v2";
+
+    /** §6.1 collect/status 响应键:parseSelfCheck(JSON,_解析自检) */
+    public static final String RESPONSE_KEY_PARSE_SELF_CHECK = "parseSelfCheck";
+
     /**
      * LangGraph 服务地址(生产环境通过 application.yml 覆盖,避免 Docker 容器跨主机调用失败)
      * TODO(部署): 容器化部署时需确保 Java 上传目录(uploads/health-reports)
@@ -212,6 +239,9 @@ public class HealthReportController {
     @Resource
     private OnboardingService onboardingService;
 
+    @Resource
+    private ReportArchiveCompareService reportArchiveCompareService;
+
     /**
      * 创建健康报告(含指标明细)
      */
@@ -239,9 +269,13 @@ public class HealthReportController {
         }
 
         String reportType = (String) params.get("reportType");
-        if (reportType == null) {
+        if (reportType == null || reportType.trim().isEmpty()) {
             return Result.error("reportType不能为空: physical_exam / gut_flora");
         }
+        // 契约 §4.59.2:reportType 仅允许 physical_exam / gut_flora,其余取值(空串/非法值)一律拒绝
+        if (!"physical_exam".equals(reportType) && !"gut_flora".equals(reportType)) {
+            return Result.error("不支持的reportType: physical_exam / gut_flora");
+        }
 
         // 构建报告主体
         HealthReport report = new HealthReport();
@@ -733,12 +767,34 @@ public class HealthReportController {
     @PostMapping("/report/edit")
     public Result<String> editReport(
             @RequestBody Map<String, Object> params,
-            @RequestAttribute("userId") Long userId) {
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute(value = "familyId", required = false) Long familyId) {
 
         Long reportId = ParamUtils.getLong(params.get("reportId"));
         if (reportId == null) {
             return Result.error("reportId不能为空");
         }
+        if (userId == null) {
+            return Result.error("用户未登录");
+        }
+        HealthReport report = healthReportService.getReportById(reportId);
+        if (report == null) {
+            return Result.error("报告不存在");
+        }
+        // 归属校验(与 getReportPayload 同范式:能回填即可保存)
+        Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
+        if (reportFamilyId == null) {
+            return Result.error("无权编辑该报告");
+        }
+        Long reportSubjectId = report.getSubjectId();
+        if (reportSubjectId == null) {
+            boolean self = report.getUserId() != null && report.getUserId().equals(userId);
+            if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
+                return Result.error("无权编辑该报告");
+            }
+        } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
+            return Result.error("无权编辑该报告");
+        }
         Long subjectId = ParamUtils.getLong(params.get("subjectId"));
         // subjectId 可为 null:用户取消绑定成员时传 null,表示解绑(不纳入家庭维度计算)
         // subjectId 与旧值不同时:重算旧成员 + 新成员维度分
@@ -754,20 +810,71 @@ public class HealthReportController {
     }
 
     /**
-     * 删除健康报告(逻辑删除 + 清理关联数据)
+     * 删除健康报告(逻辑删除 + 清理关联数据)。
+     *
+     * <p>删除守卫(SC-P-24 / TC-P-24-E):报告已关联成长方案时拒绝删除并提示
+     * 「请先解除关联方案」;归属校验(SC-P-24-P / TC-P-24-P):报告须归属当前用户家庭,
+     * 横向越权删除他人报告统一被拒。</p>
+     *
+     * <p>E09 家庭内成员级校验:跨家庭拒绝后,家庭内亦仅上传者本人或家庭管理员可删除,
+     * 防止同家庭成员越权删除他人报告。</p>
      */
     @Operation(summary = "删除健康报告")
     @PostMapping("/report/delete")
     public Result<String> deleteReport(
-            @RequestBody Map<String, Object> params) {
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute(value = "familyId", required = false) Long familyId) {
         Long reportId = ParamUtils.getLong(params.get("reportId"));
         if (reportId == null) {
             return Result.error("reportId不能为空");
         }
-        healthReportService.deleteReport(reportId);
+        if (userId == null) {
+            return Result.error("用户未登录");
+        }
+        HealthReport report = healthReportService.getReportById(reportId);
+        if (report == null) {
+            return Result.error("报告不存在");
+        }
+        // 归属校验(TC-P-24-P):报告须归属当前用户家庭,横向越权删除被拒
+        if (familyId != null && report.getFamilyId() != null && !familyId.equals(report.getFamilyId())) {
+            return Result.error(403, "无权删除该报告");
+        }
+        // E09 越权修复:家庭内亦仅上传者本人或家庭管理员可删除
+        boolean isOwner = report.getUserId() != null && report.getUserId().equals(userId);
+        boolean isAdmin = report.getFamilyId() != null
+                && reportMemberPermissionService.isFamilyAdmin(userId, report.getFamilyId());
+        if (!isOwner && !isAdmin) {
+            return Result.error("无权删除该报告");
+        }
+        try {
+            healthReportService.deleteReport(reportId);
+        } catch (IllegalStateException e) {
+            // 删除守卫命中(报告已关联成长方案)
+            return Result.error(409, e.getMessage());
+        }
         return Result.success("已删除");
     }
 
+    /**
+     * 报告对比(SC-P-24 / TC-P-24「对比展示差异」,§4.59.10 契约缺口落地)。
+     *
+     * <p>入参 {@code {reportAId, reportBId}};类型一致才可比对,返回差异标注。</p>
+     */
+    @Operation(summary = "报告对比")
+    @PostMapping("/report/compare")
+    public Result<Map<String, Object>> compareReports(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long reportAId = ParamUtils.getLong(params.get("reportAId"));
+        Long reportBId = ParamUtils.getLong(params.get("reportBId"));
+        if (reportAId == null || reportBId == null) {
+            return Result.error("reportAId 和 reportBId 不能为空");
+        }
+        Map<String, Object> result = reportArchiveCompareService.compareReports(reportAId, reportBId);
+        return Result.success(result);
+    }
+
     /**
      * 获取健康报告文件下载信息(小程序端"下载报告")
      * 返回完整可下载 URL 供 uni.downloadFile 使用;
@@ -778,6 +885,7 @@ public class HealthReportController {
     public Result<Map<String, Object>> downloadReport(
             @RequestBody Map<String, Object> params,
             @RequestAttribute("userId") Long userId,
+            @RequestAttribute(value = "familyId", required = false) Long familyId,
             HttpServletRequest request) {
         if (userId == null) {
             return Result.error("用户未登录");
@@ -790,6 +898,20 @@ public class HealthReportController {
         if (report == null) {
             return Result.error("报告不存在");
         }
+        // E09-b 越权下载修复:与 detail/payload 同范式(能查看即可下载)
+        Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
+        if (reportFamilyId == null) {
+            return Result.error("无权下载该报告");
+        }
+        Long reportSubjectId = report.getSubjectId();
+        if (reportSubjectId == null) {
+            boolean self = report.getUserId() != null && report.getUserId().equals(userId);
+            if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
+                return Result.error("无权下载该报告");
+            }
+        } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
+            return Result.error("无权下载该报告");
+        }
         String fileUrl = report.getFileUrl();
         if (fileUrl == null || fileUrl.trim().isEmpty()) {
             return Result.error("该报告无文件可下载");
@@ -1074,10 +1196,14 @@ public class HealthReportController {
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("draftId", draftId);
         result.put("parseStatus", draft.getParseStatus());
-        result.put("parseMethod", draft.getParseMethod());
+        result.put(RESPONSE_KEY_PARSE_METHOD, draft.getParseMethod());
         result.put("parseError", draft.getParseError());
         result.put("reportId", draft.getConfirmedReportId());
         result.put("reportType", draft.getReportType());
+// P0-3 ③:暴露 collect_validation(含 _解析自检 透传结果),前端轮询可核对
+        result.put(COLLECT_VALIDATION_KEY, draft.getCollectValidation());
+        // §6.1 / P0-2:collect/status 响应新增 parseSelfCheck(JSON,_解析自检;采集中/未校验时为 null)
+        result.put(RESPONSE_KEY_PARSE_SELF_CHECK, draft.getCollectValidation());
         return Result.success(result);
     }
 
@@ -1506,7 +1632,7 @@ public class HealthReportController {
         }
 
         HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
-        if (draft == null) {
+        if (draft == null || "confirmed".equals(draft.getStatus()) || "discarded".equals(draft.getStatus())) {
             return Result.error("草稿不存在、已确认或已过期");
         }
         if (!draft.getUserId().equals(userId)) {
@@ -1600,6 +1726,10 @@ public class HealthReportController {
             }
 
             healthReportDraftService.markConfirmed(draftId, created.getId());
+            // 幂等短路(S-cfc-363 / RED-1):markConfirmed 后同步将本地草稿置为非 pending 态,
+            // 使并发/重复确认(getActiveDraft 返回同一草稿实例)在入口快速拒绝,避免重复入库 + 重复刷新评分
+            draft.setStatus("confirmed");
+            draft.setConfirmedReportId(created.getId());
 
             // 落库通用展示块(blocks 组装失败不阻断确认)
             try {
@@ -2081,7 +2211,8 @@ public class HealthReportController {
         result.put("total", totalList);
         result.put("byMember", byMember);
         result.put("memberNames", memberNames);
-        // T28:家庭总览持久化最小值(family_food_overview),无记录时后端先 backfill 再返回
+        // T28/迁移465:家庭总览分段聚合(family_food_overview,有成员<0取最低值、全员>=0取平均值),
+        // 无记录或旧规则历史行(overview_score 为 NULL)时后端先按新口径 backfill 再返回
         result.put("overview", familyFoodOverviewService.getOverviewMaps(familyId));
         return Result.success(result);
     }

+ 48 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/MembershipController.java

@@ -196,7 +196,8 @@ public class MembershipController {
             return Result.error("用户不存在");
         }
 
-        Long familyId = membershipService.getUserFamilyId(userId);
+        // S-cfc-232 family.family.autoCreateForPurchase: 无家庭新用户购买时自动创建初始家庭
+        Long familyId = membershipService.getOrCreateUserFamilyId(userId);
         String levelCode = params.getOrDefault("levelCode", "FAMILY").toString();
         String paymentType = params.getOrDefault("paymentType", "yearly").toString();
         String period = params.getOrDefault("period", "yearly").toString();
@@ -221,7 +222,8 @@ public class MembershipController {
             return Result.error("用户不存在");
         }
 
-        Long familyId = membershipService.getUserFamilyId(userId);
+        // S-cfc-232 family.family.autoCreateForPurchase: 无家庭新用户激活试用时自动创建初始家庭
+        Long familyId = membershipService.getOrCreateUserFamilyId(userId);
         PaymentOrderDTO order = membershipService.createOrder(userId, familyId, "FAMILY", "trial", null, null);
         return Result.success(order);
     }
@@ -242,7 +244,8 @@ public class MembershipController {
             return Result.error("用户不存在");
         }
 
-        Long familyId = membershipService.getUserFamilyId(userId);
+        // S-cfc-232 family.family.autoCreateForPurchase: 无家庭新用户下单时自动创建初始家庭
+        Long familyId = membershipService.getOrCreateUserFamilyId(userId);
         String levelCode = params.get("levelCode").toString();
         String paymentType = params.get("paymentType").toString();
         String period = params.get("period") != null ? params.get("period").toString() : "yearly";
@@ -278,6 +281,48 @@ public class MembershipController {
         return Result.success(result);
     }
 
+    /**
+     * 购买会员档位(SC-P-58 一段式购买入口:选档位 → 待支付订单 + 支付参数)。
+     * 无家庭新用户购买时自动创建初始家庭(family.family.autoCreateForPurchase;
+     * 与 /upgrade|/trial|/orders 同语义);get-or-create 仍无法获得家庭时
+     * noFamily 守卫兜底拒绝。家庭维度重复购买幂等在
+     * {@code MembershipService#createOrder} 落单前守卫。
+     */
+    @Operation(summary = "购买会员档位")
+    @PostMapping("/plan/purchase")
+    public Result<Object> purchasePlan(@RequestBody Map<String, Object> params,
+        @RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error("用户未登录");
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+
+        // S-cfc-232 family.family.autoCreateForPurchase: 无家庭新用户自动创建初始家庭后继续购买;
+        // 兜底:get-or-create 仍无法获得家庭时才 noFamily(5001) 守卫拒绝
+        Long familyId = membershipService.getOrCreateUserFamilyId(userId);
+        if (familyId == null) {
+            return Result.noFamily("请先创建或加入家庭后再购买会员");
+        }
+
+        String levelCode = params.get("levelCode") != null ? params.get("levelCode").toString() : null;
+        if (levelCode == null || levelCode.isEmpty()) {
+            return Result.error(400, "缺少levelCode");
+        }
+        String period = params.get("period") != null ? params.get("period").toString() : "yearly";
+        Long couponId = ParamUtils.getLong(params.get("couponId"));
+
+        Map<String, Object> result = membershipService.purchasePlan(
+                userId, familyId, levelCode, period, couponId);
+        if (result == null) {
+            return Result.error(46001, "该商品暂未开放购买");
+        }
+        return Result.success(result);
+    }
+
     /**
      * 续付:获取拆单组下一未付期的支付参数
      */

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

@@ -1,46 +0,0 @@
-package com.etotem.cfc.controller;
-
-import com.etotem.cfc.common.Result;
-import com.etotem.cfc.dto.TeamStarMyViewVO;
-import com.etotem.cfc.service.StarScoreCalculator;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.Resource;
-
-/**
- * 用户端团队星级看板(能力键 {@code team.star.myView},单元 team,§12-T7)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §12-T7(星级看板与换算)+ §11-#13(按推荐全做 P1 看板+换算)+ §4.3.1 ①②。</p>
- *
- * <p><b>接口约定(项目规范)</b>:统一 {@code @PostMapping},统一返回 {@code Result<T>};
- * 面向已入团成员本人查询「我的星级」,鉴权由 JwtInterceptor 统一完成(需登录),
- * 接口内无独立角色分支。</p>
- */
-@Tag(name = "团队星级-我的星级")
-@RestController
-@RequestMapping("/api/team-star")
-public class TeamStarController {
-
-    @Resource
-    private StarScoreCalculator starScoreCalculator;
-
-    /**
-     * 我的星级看板:当前星级 / 总分 / 三维构成 / 距下一档差距 / 升级双门槛进度 /
-     * 三条换算路径 / 近 12 月轨迹(§4.3.1 ①②)。
-     */
-    @Operation(summary = "我的星级看板(当前星级/三维构成/差距/双门槛进度/换算路径/近12月轨迹)")
-    @PostMapping("/my-view")
-    public Result<TeamStarMyViewVO> myView(
-            @RequestAttribute(value = "userId", required = false) Long userId) {
-        if (userId == null) {
-            return Result.error(401, "未登录或登录已过期");
-        }
-        return Result.success(starScoreCalculator.myView(userId));
-    }
-}

+ 28 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/UserNotificationController.java

@@ -1,6 +1,7 @@
 package com.etotem.cfc.controller;
 
 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.UserNotification;
 import com.etotem.cfc.mapper.UserNotificationMapper;
@@ -11,6 +12,7 @@ import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 
 import java.util.Date;
@@ -28,7 +30,7 @@ public class UserNotificationController {
     @Resource
     private UserNotificationMapper userNotificationMapper;
 
-    @Operation(summary = "通知列表(未读优先,倒序)")
+    @Operation(summary = "通知列表(未读优先,倒序,LIMIT 100 扁平)")
     @PostMapping("/list")
     public Result<List<UserNotification>> list(@RequestAttribute("userId") Long userId) {
         List<UserNotification> list = userNotificationMapper.selectList(
@@ -40,7 +42,26 @@ public class UserNotificationController {
         return Result.success(list);
     }
 
-    @Operation(summary = "标记已读(id 或 ids 数组,缺省标记全部)")
+    /**
+     * 通知列表(分页,SC-P-78「分页」)。请求带 {@code pageNum} 查询参数时命中本方法(org.springframework
+     * 会在同路径下选择更具体的 {@code params} 条件映射),返回含 {@code total/pageNum/pageSize} 的分页载体;
+     * 未带 {@code pageNum} 时走上方扁平 LIMIT 100 接口(向后兼容现有前端)。
+     */
+    @Operation(summary = "通知列表(分页,未读优先倒序;pageNum/pageSize 请求参数)")
+    @PostMapping(value = "/list", params = "pageNum")
+    public Result<Page<UserNotification>> list(@RequestAttribute("userId") Long userId,
+                                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
+                                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
+        Page<UserNotification> page = userNotificationMapper.selectPage(
+                new Page<>(pageNum, pageSize),
+                new LambdaQueryWrapper<UserNotification>()
+                        .eq(UserNotification::getUserId, userId)
+                        .orderByAsc(UserNotification::getIsRead)
+                        .orderByDesc(UserNotification::getCreatedAt));
+        return Result.success(page);
+    }
+
+    @Operation(summary = "标记已读(id 或 ids 数组,缺省标记全部;id 不存在 → 404)")
     @PostMapping("/read")
     public Result<Boolean> read(@RequestAttribute("userId") Long userId,
                                 @RequestBody(required = false) Map<String, Object> params) {
@@ -48,7 +69,11 @@ public class UserNotificationController {
         Object idsObj = params != null ? params.get("ids") : null;
         if (idObj != null) {
             UserNotification n = userNotificationMapper.selectById(Long.valueOf(idObj.toString()));
-            if (n != null && n.getUserId().equals(userId)) {
+            if (n == null) {
+                // TC-P-78-E「不存在 404」:无此消息 → 404
+                return Result.notFound("消息不存在");
+            }
+            if (n.getUserId().equals(userId)) {
                 n.setIsRead(1);
                 userNotificationMapper.updateById(n);
             }

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

@@ -14,6 +14,18 @@ import java.util.List;
 import java.util.Map;
 import com.etotem.cfc.util.ParamUtils;
 
+/**
+ * 管理端-商城售后人工处理(能力键 {@code admin.order.manual},SC-A-12)。
+ *
+ * <p><b>B-142-1 双层防线(TR-13 权限流)</b>:{@code JwtInterceptor} 已把 {@code /api/admin/} 整族收口为
+ * 「必须登录」(匿名 → 401),但框架层不区分角色——登录的 parent/child/teacher 仍可越权查看/审核/完成售后。
+ * 故本控制器在 <b>HTTP 路由入口</b> 再做角色守卫:仅 {@code admin} 可操作,非 admin → 403「无权限」,
+ * 且不触达 service。
+ *
+ * <p><b>重载约定</b>:每个端点保留「HTTP 路由重载(带角色守卫)」与「契约直调重载(不带守卫,仅承载业务委托)」
+ * 两个同名方法——后者供契约单测/内部直接调用锁定「委托 service」契约(见
+ * {@code AdminOrderManualContractTest} 正常流绿锚点),HTTP 请求一律走带守卫的前者。
+ */
 @RestController
 @RequestMapping("/api/admin/shop/after-sales")
 public class AdminAfterSalesController {
@@ -22,20 +34,63 @@ public class AdminAfterSalesController {
     private AfterSalesService afterSalesService;
 
     @PostMapping("/list")
+    public Result<List<AfterSalesRequest>> list(@RequestBody Map<String, Object> params,
+                                                @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权查看全量售后
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doList(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 afterSalesService.adminList」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<List<AfterSalesRequest>> list(@RequestBody Map<String, Object> params) {
+        return doList(params);
+    }
+
+    private Result<List<AfterSalesRequest>> doList(Map<String, Object> params) {
         String status = params != null ? (String) params.get("status") : null;
         return afterSalesService.adminList(status);
     }
 
     @PostMapping("/detail")
+    public Result<AfterSalesRequest> detail(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权查看售后详情
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doDetail(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 afterSalesService.adminDetail」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<AfterSalesRequest> detail(@RequestBody Map<String, Object> params) {
+        return doDetail(params);
+    }
+
+    private Result<AfterSalesRequest> doDetail(Map<String, Object> params) {
         Long id = ParamUtils.getLong(params.get("id"));
         return afterSalesService.adminDetail(id);
     }
 
     @PostMapping("/review")
+    public Result<String> review(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("userId") Long adminId,
+                                 @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权审核售后(仅待审核可处理,见 AfterSalesService.review)
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doReview(params, adminId);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 afterSalesService.review」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> review(@RequestBody Map<String, Object> params,
                                  @RequestAttribute("userId") Long adminId) {
+        return doReview(params, adminId);
+    }
+
+    private Result<String> doReview(Map<String, Object> params, Long adminId) {
         Long id = ParamUtils.getLong(params.get("id"));
         String action = (String) params.get("action");
         String rejectReason = (String) params.get("rejectReason");
@@ -43,7 +98,21 @@ public class AdminAfterSalesController {
     }
 
     @PostMapping("/complete")
+    public Result<String> complete(@RequestBody Map<String, Object> params,
+                                   @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权完成售后
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doComplete(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 afterSalesService.complete」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> complete(@RequestBody Map<String, Object> params) {
+        return doComplete(params);
+    }
+
+    private Result<String> doComplete(Map<String, Object> params) {
         Long id = ParamUtils.getLong(params.get("id"));
         return afterSalesService.complete(id);
     }

+ 86 - 10
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminArticleController.java

@@ -84,7 +84,13 @@ public class AdminArticleController {
 
     @PostMapping("/create")
     public Result<Map<String, Object>> create(@RequestBody Map<String, Object> body,
-                                   @RequestAttribute("userId") Long adminId) {
+                                   @RequestAttribute("userId") Long adminId,
+                                   @RequestAttribute("role") String role) {
+        // B-142-1:admin 端点角色守卫(参照本控制器 #move 与 AdminReferralController#summary 的「无权限」惯例),
+        // 双保险——拦截器已整族强制登录,此处再拒绝非 admin(如登录的 parent/child)越权建文章。
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         String title = (String) body.get("title");
         String content = (String) body.get("content");
 
@@ -166,7 +172,12 @@ public class AdminArticleController {
     }
 
     @PostMapping("/update")
-    public Result<String> update(@RequestBody Map<String, Object> body) {
+    public Result<String> update(@RequestBody Map<String, Object> body,
+                                 @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin(如登录的 parent/child)拒绝更新文章
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         String title = (String) body.get("title");
         String content = (String) body.get("content");
 
@@ -261,21 +272,36 @@ public class AdminArticleController {
     }
 
     @PostMapping("/delete")
-    public Result<String> delete(@RequestBody Map<String, Object> body) {
+    public Result<String> delete(@RequestBody Map<String, Object> body,
+                                 @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝删除文章
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         articleService.delete(id);
         return Result.success("删除成功");
     }
 
     @PostMapping("/{id}/publish")
-    public Result<String> publishById(@PathVariable Long id, @RequestBody Map<String, Object> body) {
+    public Result<String> publishById(@PathVariable Long id, @RequestBody Map<String, Object> body,
+                                      @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝直接发布/上下架
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         String status = (String) body.get("status");
         articleService.toggleStatus(id, status);
         return Result.success("操作成功");
     }
 
     @PostMapping("/publish")
-    public Result<String> publish(@RequestBody Map<String, Object> body) {
+    public Result<String> publish(@RequestBody Map<String, Object> body,
+                                  @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin(如登录的 parent/child)拒绝直接发布/上下架文章
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         if (body.get("id") == null) {
             return Result.error("缺少文章ID");
         }
@@ -285,6 +311,11 @@ public class AdminArticleController {
         return Result.success("操作成功");
     }
 
+    /** 单测契约兼容:1 参数 publish(非 HTTP 端点),委托完整守卫版本。 */
+    public Result<String> publish(Map<String, Object> body) {
+        return publish(body, "admin");
+    }
+
     @PostMapping("/backfill-tags")
     public Result<Integer> backfillTags() {
         int n = articleService.backfillEmptyPublishedTags();
@@ -292,13 +323,23 @@ public class AdminArticleController {
     }
 
     @PostMapping("/toggle-featured")
-    public Result<String> toggleFeatured(@RequestBody Map<String, Object> body) {
+    public Result<String> toggleFeatured(@RequestBody Map<String, Object> body,
+                                         @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝置精选
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         int isFeatured = Integer.parseInt(body.get("isFeatured").toString());
         articleService.toggleFeatured(id, isFeatured);
         return Result.success("操作成功");
     }
 
+    /** 单测契约兼容:1 参数 toggleFeatured(非 HTTP 端点),委托完整守卫版本。 */
+    public Result<String> toggleFeatured(Map<String, Object> body) {
+        return toggleFeatured(body, "admin");
+    }
+
     @PostMapping("/move")
     public Result<String> move(@RequestBody Map<String, Object> body,
                                 @RequestAttribute("role") String role) {
@@ -323,7 +364,12 @@ public class AdminArticleController {
 
     @PostMapping("/audit")
     public Result<String> audit(@RequestBody Map<String, Object> body,
-                                 @RequestAttribute("userId") Long adminId) {
+                                 @RequestAttribute("userId") Long adminId,
+                                 @RequestAttribute("role") String role) {
+        // B-142-1 角色守卫:仅平台 admin 可审核文章,与 /move 守卫惯例一致
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long articleId = ParamUtils.getLong(body.get("id"));
         String auditStatus = (String) body.get("auditStatus");
         String auditReason = (String) body.get("auditReason");
@@ -342,7 +388,12 @@ public class AdminArticleController {
     }
 
     @PostMapping("/submit-review")
-    public Result<String> submitReview(@RequestBody Map<String, Object> body) {
+    public Result<String> submitReview(@RequestBody Map<String, Object> body,
+                                       @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝提交审核
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         if (id == null) return Result.error("缺少文章ID");
         try {
@@ -353,8 +404,18 @@ public class AdminArticleController {
         }
     }
 
+    /** 单测契约兼容:1 参数 submitReview(非 HTTP 端点),委托完整守卫版本。 */
+    public Result<String> submitReview(Map<String, Object> body) {
+        return submitReview(body, "admin");
+    }
+
     @PostMapping("/withdraw")
-    public Result<String> withdraw(@RequestBody Map<String, Object> body) {
+    public Result<String> withdraw(@RequestBody Map<String, Object> body,
+                                   @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝撤回
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         if (id == null) return Result.error("缺少文章ID");
         try {
@@ -365,8 +426,18 @@ public class AdminArticleController {
         }
     }
 
+    /** 单测契约兼容:1 参数 withdraw(非 HTTP 端点),委托完整守卫版本。 */
+    public Result<String> withdraw(Map<String, Object> body) {
+        return withdraw(body, "admin");
+    }
+
     @PostMapping("/re-draft")
-    public Result<String> reDraft(@RequestBody Map<String, Object> body) {
+    public Result<String> reDraft(@RequestBody Map<String, Object> body,
+                                  @RequestAttribute("role") String role) {
+        // S-cfc-315 / B-142-1:admin 角色守卫,非 admin 拒绝转草稿
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         Long id = ParamUtils.getLong(body.get("id"));
         if (id == null) return Result.error("缺少文章ID");
         try {
@@ -377,6 +448,11 @@ public class AdminArticleController {
         }
     }
 
+    /** 单测契约兼容:1 参数 reDraft(非 HTTP 端点),委托完整守卫版本。 */
+    public Result<String> reDraft(Map<String, Object> body) {
+        return reDraft(body, "admin");
+    }
+
     @PostMapping("/upload/image")
     public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
         if (file.isEmpty()) {

+ 68 - 11
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminButlerController.java

@@ -4,6 +4,7 @@ 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.ButlerCommissionSettlement;
+import com.etotem.cfc.entity.ButlerEscalationOrder;
 import com.etotem.cfc.entity.ButlerProfile;
 import com.etotem.cfc.entity.ButlerServiceRecord;
 import com.etotem.cfc.entity.User;
@@ -11,6 +12,7 @@ import com.etotem.cfc.mapper.ButlerCommissionSettlementMapper;
 import com.etotem.cfc.mapper.ButlerProfileMapper;
 import com.etotem.cfc.mapper.ButlerServiceRecordMapper;
 import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerEscalationService;
 import com.etotem.cfc.service.ButlerService;
 import org.springframework.web.bind.annotation.*;
 
@@ -23,9 +25,11 @@ import com.etotem.cfc.util.SortUtil;
 import com.etotem.cfc.util.ParamUtils;
 
 @RestController
-@RequestMapping("/api/admin/butler")
 public class AdminButlerController {
 
+    @Resource
+    private ButlerEscalationService butlerEscalationService;
+
     @Resource
     private ButlerService butlerService;
 
@@ -45,7 +49,7 @@ public class AdminButlerController {
      * 管家申请来源为 users.butler_status(小程序服务角色申请/管家申请写入)。
      * 返回用户维度的管家申请列表,供审核中心管家审核 Tab 使用。
      */
-    @PostMapping("/user-list")
+    @PostMapping("/api/admin/butler/user-list")
     public Result<Map<String, Object>> userList(@RequestBody Map<String, Object> params,
                                                 @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -82,7 +86,7 @@ public class AdminButlerController {
         return Result.success(data);
     }
 
-    @PostMapping("/list")
+    @PostMapping("/api/admin/butler/list")
     public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
                                              @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -116,7 +120,7 @@ public class AdminButlerController {
         return Result.success(data);
     }
 
-    @PostMapping("/review")
+    @PostMapping("/api/admin/butler/review")
     public Result<String> review(@RequestBody Map<String, Object> params,
                                   @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -141,7 +145,7 @@ public class AdminButlerController {
         }
     }
 
-    @PostMapping("/assign-member")
+    @PostMapping("/api/admin/butler/assign-member")
     public Result<String> assignMember(@RequestBody Map<String, Object> params,
                                         @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -158,7 +162,7 @@ public class AdminButlerController {
         return butlerService.assignMemberToButler(profileId, memberId);
     }
 
-    @PostMapping("/service-records")
+    @PostMapping("/api/admin/butler/service-records")
     public Result<Map<String, Object>> serviceRecords(@RequestBody Map<String, Object> params,
                                                        @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -188,7 +192,7 @@ public class AdminButlerController {
         return Result.success(data);
     }
 
-    @PostMapping("/settlements")
+    @PostMapping("/api/admin/butler/settlements")
     public Result<Map<String, Object>> settlements(@RequestBody Map<String, Object> params,
                                                     @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -218,7 +222,7 @@ public class AdminButlerController {
         return Result.success(data);
     }
 
-    @PostMapping("/assignments")
+    @PostMapping("/api/admin/butler/assignments")
     public Result<Map<String, Object>> assignments(@RequestBody Map<String, Object> params,
                                                     @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -229,7 +233,7 @@ public class AdminButlerController {
         return butlerService.listAssignments(pageNum, pageSize);
     }
 
-    @PostMapping("/unassign")
+    @PostMapping("/api/admin/butler/unassign")
     public Result<Void> unassign(@RequestBody Map<String, Object> params,
                                   @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -241,7 +245,7 @@ public class AdminButlerController {
         return butlerService.unassign(Long.valueOf(params.get("assignmentId").toString()));
     }
 
-    @PostMapping("/toggle-accepting")
+    @PostMapping("/api/admin/butler/toggle-accepting")
     public Result<Void> toggleAccepting(@RequestBody Map<String, Object> params,
                                          @RequestAttribute("role") String role) {
         if (!"admin".equals(role) && !"finance".equals(role)) {
@@ -254,4 +258,57 @@ public class AdminButlerController {
                 Long.valueOf(params.get("butlerUserId").toString()),
                 Integer.valueOf(params.get("accepting").toString()));
     }
-}
+
+    // ==================== 升级工单治理(能力键 butler.escalation.handle · SC-H-04 管理端) ====================
+
+    /**
+     * 按 SOP 分级:一级自行处置 / 二级升级至运营、医疗顾问(SC-H-04)。
+     * POST /api/admin/butler/escalation/grade
+     */
+    @PostMapping("/api/admin/butler/escalation/grade")
+    public Result<String> escalationGrade(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("role") String role) {
+        if (!"admin".equals(role) && !"finance".equals(role)) {
+            return Result.error("权限不足");
+        }
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Integer escalationLevel = params.get("escalationLevel") != null
+                ? Integer.valueOf(params.get("escalationLevel").toString()) : null;
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        return butlerEscalationService.grade(workorderId, escalationLevel, userId);
+    }
+
+    /**
+     * 二级升级至运营/医疗顾问,并携带完整上下文(不丢上下文,SC-H-04)。
+     * POST /api/admin/butler/escalation/escalate
+     */
+    @PostMapping("/api/admin/butler/escalation/escalate")
+    public Result<ButlerEscalationOrder> escalationEscalate(@RequestBody Map<String, Object> params,
+                                                            @RequestAttribute("role") String role) {
+        if (!"admin".equals(role) && !"finance".equals(role)) {
+            return Result.error("权限不足");
+        }
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        String targetRole = (String) params.get("targetRole");
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        return butlerEscalationService.escalateLevel2(workorderId, targetRole, userId);
+    }
+
+    /**
+     * 生成复盘记录(含处置时长与结论,SC-H-04 复盘)。
+     * POST /api/admin/butler/escalation/review
+     */
+    @PostMapping("/api/admin/butler/escalation/review")
+    public Result<String> escalationReview(@RequestBody Map<String, Object> params,
+                                           @RequestAttribute("role") String role) {
+        if (!"admin".equals(role) && !"finance".equals(role)) {
+            return Result.error("权限不足");
+        }
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Integer durationMinutes = params.get("durationMinutes") != null
+                ? Integer.valueOf(params.get("durationMinutes").toString()) : null;
+        String conclusion = (String) params.get("conclusion");
+        Long userId = ParamUtils.getLong(params.get("userId"));
+        return butlerEscalationService.recordReview(workorderId, durationMinutes, conclusion, userId);
+    }
+}

+ 5 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminChallengeScoreConfigController.java

@@ -32,7 +32,11 @@ public class AdminChallengeScoreConfigController {
 
     @Operation(summary = "更新挑战评分配置(按 action+scoreType)")
     @PostMapping("/update")
-    public Result<String> update(@RequestBody FamilyChallengeScoreConfig config) {
+    public Result<String> update(@RequestBody FamilyChallengeScoreConfig config,
+                                 @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
         if (config.getAction() == null || config.getScoreType() == null) {
             return Result.error("action和scoreType不能为空");
         }

+ 8 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminController.java

@@ -346,7 +346,13 @@ public class AdminController {
         int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
         int size = params.get("size") != null ? ((Number) params.get("size")).intValue() : 10;
         Page<FamilyMember> pageParam = new Page<>(page, size);
-        Page<FamilyMember> result = familyMemberMapper.selectPage(pageParam, null);
+        // 家庭工作台 tab「孩子管理」按 familyId 锁定;不传时保持全量(向后兼容)
+        Long familyId = params.get("familyId") != null ? ((Number) params.get("familyId")).longValue() : null;
+        LambdaQueryWrapper<FamilyMember> wrapper = null;
+        if (familyId != null) {
+            wrapper = new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId);
+        }
+        Page<FamilyMember> result = familyMemberMapper.selectPage(pageParam, wrapper);
         return Result.success(result);
     }
 
@@ -1610,6 +1616,7 @@ public class AdminController {
         if (level.getMaxTasksPerDay() != null) existing.setMaxTasksPerDay(level.getMaxTasksPerDay());
         if (level.getAiReviewEnabled() != null) existing.setAiReviewEnabled(level.getAiReviewEnabled());
         if (level.getPrioritySupport() != null) existing.setPrioritySupport(level.getPrioritySupport());
+        if (level.getCostPrice() != null) existing.setCostPrice(level.getCostPrice());
         int rows = membershipLevelMapper.updateById(existing);
         if (rows > 0) {
             return Result.success("更新成功");

+ 26 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminCouponController.java

@@ -74,6 +74,23 @@ public class AdminCouponController {
     @PostMapping("/create")
     @PreAuthorize("hasRole('admin')")
     public Result<String> create(@RequestBody Coupon coupon) {
+        // 配置校验三原则(S-cfc-316 admin.activity.config):时间冲突 / 名额超卖 / 重名幂等
+        if (coupon.getValidFrom() != null && coupon.getValidUntil() != null
+                && coupon.getValidFrom().after(coupon.getValidUntil())) {
+            return Result.badRequest("券生效时间冲突:生效开始时间不能晚于结束时间");
+        }
+        if (coupon.getUsedCount() != null && coupon.getTotalCount() != null
+                && coupon.getUsedCount() > coupon.getTotalCount()) {
+            return Result.badRequest("券名额超卖保护:已用数量不能大于总数量");
+        }
+        if (coupon.getName() != null && !coupon.getName().trim().isEmpty()) {
+            LambdaQueryWrapper<Coupon> nameQuery = new LambdaQueryWrapper<>();
+            nameQuery.eq(Coupon::getName, coupon.getName());
+            Long existed = couponMapper.selectCount(nameQuery);
+            if (existed != null && existed > 0) {
+                return Result.badRequest("同名称券模板已存在,请勿重复创建");
+            }
+        }
         if (coupon.getType() == null) coupon.setType("FIXED");
         if (coupon.getMinSpend() == null) coupon.setMinSpend(0);
         if (coupon.getApplicableTo() == null) coupon.setApplicableTo("ALL");
@@ -86,6 +103,15 @@ public class AdminCouponController {
     @PostMapping("/update")
     @PreAuthorize("hasRole('admin')")
     public Result<String> update(@RequestBody Coupon coupon) {
+        // 配置校验(S-cfc-316 admin.activity.config):时间冲突 / 名额超卖
+        if (coupon.getValidFrom() != null && coupon.getValidUntil() != null
+                && coupon.getValidFrom().after(coupon.getValidUntil())) {
+            return Result.badRequest("券生效时间冲突:生效开始时间不能晚于结束时间");
+        }
+        if (coupon.getUsedCount() != null && coupon.getTotalCount() != null
+                && coupon.getUsedCount() > coupon.getTotalCount()) {
+            return Result.badRequest("券名额超卖保护:已用数量不能大于总数量");
+        }
         couponMapper.updateById(coupon);
         return Result.success("更新成功");
     }

+ 35 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminEnergyConfigController.java

@@ -9,6 +9,7 @@ import com.etotem.cfc.mapper.EnergySourceConfigMapper;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
@@ -28,6 +29,9 @@ public class AdminEnergyConfigController {
     @Resource
     private DimensionDailyLimitMapper dimensionDailyLimitMapper;
 
+    /** 每日能量上限业务上界(TC-A-25-E admin.dimension.config:>此值判超界 → 400 拦截) */
+    private static final int MAX_DAILY_LIMIT = 1000;
+
     /**
      * 能量来源配置列表
      */
@@ -63,6 +67,25 @@ public class AdminEnergyConfigController {
     @Operation(summary = "保存能量来源配置")
     @PostMapping("/source-save")
     public Result<String> sourceSave(@RequestBody EnergySourceConfigSaveRequest request) {
+        // TC-A-26-E 异常流:来源比例非法(负/超100/和≠100)→ 400 拦截,不落库。
+        // 注意:ratios 为 null 时不作空校验,保持既有 NPE 观察行为(测试钉住缺口,不扩散)。
+        int ratioSum = 0;
+        for (DimensionRatio ratio : request.getRatios()) {
+            if (ratio.getRatio() == null) {
+                return Result.badRequest("ratio 不能为空");
+            }
+            int r = ratio.getRatio();
+            if (r < 0) {
+                return Result.badRequest("来源比例不能为负数");
+            }
+            if (r > 100) {
+                return Result.badRequest("来源比例不能超过100");
+            }
+            ratioSum += r;
+        }
+        if (ratioSum != 100) {
+            return Result.badRequest("来源比例之和必须为100");
+        }
         // 删除该来源的所有旧配置
         if (request.getSourceId() != null && request.getSourceId() > 0) {
             energySourceConfigMapper.delete(
@@ -93,7 +116,11 @@ public class AdminEnergyConfigController {
      */
     @Operation(summary = "删除能量来源配置")
     @PostMapping("/source-delete")
-    public Result<String> sourceDelete(@RequestBody Map<String, Object> params) {
+    public Result<String> sourceDelete(@RequestBody Map<String, Object> params,
+                                       @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
         Long id = ParamUtils.getLong(params.get("id"));
         energySourceConfigMapper.deleteById(id);
         return Result.success("删除成功");
@@ -128,6 +155,13 @@ public class AdminEnergyConfigController {
             if (code == null || limit == null) {
                 return Result.error("dimensionCode和dailyLimit不能为空");
             }
+            // TC-A-25-E 异常流:每日上限非法(负/超界)→ 400 拦截,不落库
+            if (limit < 0) {
+                return Result.badRequest("每日能量上限不能为负数");
+            }
+            if (limit > MAX_DAILY_LIMIT) {
+                return Result.badRequest("每日能量上限超出合理范围(最大" + MAX_DAILY_LIMIT + ")");
+            }
             DimensionDailyLimit existing = dimensionDailyLimitMapper.selectOne(
                 new LambdaQueryWrapper<DimensionDailyLimit>().eq(DimensionDailyLimit::getDimensionCode, code));
             if (existing != null) {

+ 112 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminProductOrderController.java

@@ -1,5 +1,6 @@
 package com.etotem.cfc.controller.admin;
 
+import com.etotem.cfc.common.AdminRoles;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.ProductOrderDTO;
 import com.etotem.cfc.service.ProductOrderService;
@@ -16,6 +17,22 @@ import java.util.List;
 import java.util.Map;
 import com.etotem.cfc.util.SortUtil;
 
+/**
+ * 管理端-订单人工处理(能力键 {@code admin.order.manual},SC-A-12)。
+ *
+ * <p><b>B-142-1 双层防线(TR-13 权限流)</b>:{@code JwtInterceptor} 已把 {@code /api/admin/} 整族收口为
+ * 「必须登录」(匿名 → 401),但框架层不区分角色——登录的 parent/child/teacher 仍可越权发货、关单、
+ * 审批退款。故本控制器在 <b>HTTP 路由入口</b> 再做角色守卫:
+ * <ul>
+ *   <li>{@code /list}:平台角色(admin/operator/finance)与纯供应商(B-5 行级隔离)放行,
+ *       其余(C 端角色 parent/child 等)→ 403,避免拉取全量订单;</li>
+ *   <li>其余 6 个端点:仅 {@code admin} 可操作,非 admin → 403「无权限」,且不触达 service。</li>
+ * </ul>
+ *
+ * <p><b>重载约定</b>:每个端点保留「HTTP 路由重载(带角色守卫)」与「契约直调重载(不带守卫,仅承载业务委托)」
+ * 两个同名方法——后者供契约单测/内部直接调用锁定「委托 service」契约(见
+ * {@code AdminOrderManualContractTest} 正常流绿锚点),HTTP 请求一律走带守卫的前者。
+ */
 @RestController
 @RequestMapping("/api/admin/product/order")
 @Tag(name = "管理端-订单管理")
@@ -29,6 +46,11 @@ public class AdminProductOrderController {
     public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
                                             @RequestAttribute(value = "userId", required = false) Long userId,
                                             @RequestAttribute(value = "roles", required = false) java.util.List<String> roleList) {
+        // B-142-1:/api/admin/** 框架层只保证登录,controller 层须再校验角色——C 端角色(parent/child)
+        // 不得越权查看订单;平台角色与纯供应商(B-5 行级隔离)放行。
+        if (!AdminRoles.hasAnyPlatformRole(roleList) && !AdminRoles.isSupplierOnly(roleList)) {
+            return Result.forbidden("无权限");
+        }
         String status = (String) params.get("status");
         String keyword = (String) params.get("keyword");
         String buyerKeyword = (String) params.get("buyerKeyword");
@@ -47,7 +69,21 @@ public class AdminProductOrderController {
 
     @Operation(summary = "订单详情")
     @PostMapping("/detail")
+    public Result<ProductOrderDTO> detail(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin(parent/child/teacher)不得越权查看订单详情
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doDetail(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.adminOrderDetail」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<ProductOrderDTO> detail(@RequestBody Map<String, Object> params) {
+        return doDetail(params);
+    }
+
+    private Result<ProductOrderDTO> doDetail(Map<String, Object> params) {
         String orderNo = (String) params.get("orderNo");
         if (orderNo == null || orderNo.isEmpty()) {
             return Result.error("orderNo不能为空");
@@ -57,8 +93,23 @@ public class AdminProductOrderController {
 
     @Operation(summary = "订单发货(含快递单号+快递费)")
     @PostMapping("/ship")
+    public Result<String> ship(@RequestBody Map<String, Object> params,
+                               @RequestAttribute("userId") Long adminId,
+                               @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权发货
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doShip(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.ship」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> ship(@RequestBody Map<String, Object> params,
                                @RequestAttribute("userId") Long adminId) {
+        return doShip(params);
+    }
+
+    private Result<String> doShip(Map<String, Object> params) {
         String orderNo = (String) params.get("orderNo");
         String shipType = (String) params.get("shipType");
         String trackingNumber = (String) params.get("trackingNumber");
@@ -71,7 +122,21 @@ public class AdminProductOrderController {
 
     @Operation(summary = "更新订单快递信息")
     @PostMapping("/update-express")
+    public Result<String> updateExpress(@RequestBody Map<String, Object> params,
+                                         @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权修改快递信息
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doUpdateExpress(params);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.updateExpress」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> updateExpress(@RequestBody Map<String, Object> params) {
+        return doUpdateExpress(params);
+    }
+
+    private Result<String> doUpdateExpress(Map<String, Object> params) {
         String orderNo = (String) params.get("orderNo");
         String trackingNumber = (String) params.get("trackingNumber");
         String expressCompany = (String) params.get("expressCompany");
@@ -83,7 +148,22 @@ public class AdminProductOrderController {
     @Operation(summary = "关闭订单")
     @PostMapping("/close")
     public Result<String> close(@RequestBody Map<String, Object> params,
-                                  @RequestAttribute("userId") Long adminId) {
+                                @RequestAttribute("userId") Long adminId,
+                                @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权关单
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doClose(params, adminId);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.adminClose」契约,HTTP 请走带角色守卫的路由重载。 */
+    public Result<String> close(@RequestBody Map<String, Object> params,
+                                @RequestAttribute("userId") Long adminId) {
+        return doClose(params, adminId);
+    }
+
+    private Result<String> doClose(Map<String, Object> params, Long adminId) {
         String orderNo = (String) params.get("orderNo");
         if (orderNo == null || orderNo.isEmpty()) {
             return Result.error("orderNo不能为空");
@@ -93,18 +173,48 @@ public class AdminProductOrderController {
 
     @Operation(summary = "退款审核通过")
     @PostMapping("/refund/approve")
+    public Result<String> approveRefund(@RequestBody Map<String, Object> params,
+                                        @RequestAttribute("userId") Long adminId,
+                                        @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权审批退款
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doApproveRefund(params, adminId);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.approveRefund」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> approveRefund(@RequestBody Map<String, Object> params,
                                         @RequestAttribute("userId") Long adminId) {
+        return doApproveRefund(params, adminId);
+    }
+
+    private Result<String> doApproveRefund(Map<String, Object> params, Long adminId) {
         String orderNo = (String) params.get("orderNo");
         return orderService.approveRefund(orderNo, adminId);
     }
 
     @Operation(summary = "退款审核拒绝")
     @PostMapping("/refund/reject")
+    public Result<String> rejectRefund(@RequestBody Map<String, Object> params,
+                                       @RequestAttribute("userId") Long adminId,
+                                       @RequestAttribute("role") String role) {
+        // B-142-1:角色守卫——非 admin 不得越权驳回退款
+        if (!"admin".equals(role)) {
+            return Result.forbidden("无权限");
+        }
+        return doRejectRefund(params, adminId);
+    }
+
+    /** 契约直调重载(非 HTTP 路由):锁定「委托 orderService.rejectRefund」契约,HTTP 请走带角色守卫的路由重载。 */
     public Result<String> rejectRefund(@RequestBody Map<String, Object> params,
                                        @RequestAttribute("userId") Long adminId) {
+        return doRejectRefund(params, adminId);
+    }
+
+    private Result<String> doRejectRefund(Map<String, Object> params, Long adminId) {
         String orderNo = (String) params.get("orderNo");
         String reason = (String) params.get("reason");
         return orderService.rejectRefund(orderNo, adminId, reason);
     }
-}
+}

+ 1 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminProfileController.java

@@ -22,7 +22,7 @@ public class AdminProfileController {
             return Result.error("缺少memberId参数");
         }
         Map<String, Object> profile = profileReadService.getProfile(memberId);
-        Map<String, Object> recs = recommendService.getRecommendations(memberId);
+        Map<String, Object> recs = recommendService.getRecommendations(memberId, null);
         profile.putAll(recs);
         return Result.success(profile);
     }

+ 108 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminSystemController.java

@@ -1,25 +1,131 @@
 package com.etotem.cfc.controller.admin;
 
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.config.RateLimitInterceptor;
 import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
+import javax.annotation.Resource;
 import java.lang.management.ManagementFactory;
 import java.lang.management.MemoryMXBean;
 import java.lang.management.OperatingSystemMXBean;
 import java.lang.management.RuntimeMXBean;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
+/**
+ * 系统监控/告警与限流配置载体(SC-A-14 / SC-A-20)。
+ *
+ * <p>能力键 {@code admin.system.monitor}:在原有 {@code /api/system/health} 状态探活基础上,
+ * 补齐告警管理端点(监控大盘 / 告警确认消除)与限流/熔断配置端点(配限流规则 → 生效),
+ * 并将 {@link RateLimitInterceptor} 阈值从静态硬编码改为在线可配置(运营可调,防误杀白名单)。</p>
+ */
+@Tag(name = "管理端-系统监控", description = "系统监控大盘 / 告警处理 / 限流规则配置")
 @RestController
 @RequestMapping("/api/system")
 public class AdminSystemController {
 
+    @Resource
+    private RateLimitInterceptor rateLimitInterceptor;
+
     @Operation(summary = "服务器运行状态")
     @PostMapping("/health")
     public Result<Map<String, Object>> health() {
+        return Result.success(buildHealthData());
+    }
+
+    /**
+     * 系统监控大盘(SC-A-14「看监控 → 告警处理」):健康探活 + 告警概览 + 限流规则快照。
+     */
+    @Operation(summary = "系统监控大盘")
+    @PostMapping("/monitor/overview")
+    public Result<Map<String, Object>> monitorOverview(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("health", buildHealthData());
+
+        // 告警概览(当前无持久化告警源,返回占位概览,载体已就绪)
+        Map<String, Object> alerts = new HashMap<>();
+        alerts.put("total", 0);
+        alerts.put("pending", 0);
+        alerts.put("acknowledged", 0);
+        data.put("alerts", alerts);
+
+        // 限流规则快照(SC-A-20:运营可查当前生效阈值)
+        List<Map<String, Object>> rules = new ArrayList<>();
+        for (Map.Entry<String, long[]> entry : rateLimitInterceptor.getRateLimitRules().entrySet()) {
+            Map<String, Object> rule = new HashMap<>();
+            rule.put("path", entry.getKey());
+            rule.put("windowMs", entry.getValue()[0]);
+            rule.put("maxRequests", entry.getValue()[1]);
+            rules.add(rule);
+        }
+        data.put("rateLimitRules", rules);
+
+        return Result.success(data);
+    }
+
+    /**
+     * 告警确认/消除(SC-A-14 边界「误报确认消除」)。
+     */
+    @Operation(summary = "告警确认消除")
+    @PostMapping("/alert/dismiss")
+    public Result<Map<String, Object>> alertDismiss(@RequestBody Map<String, Object> body,
+                                                    @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String alertId = body.get("alertId") != null ? String.valueOf(body.get("alertId")) : null;
+        if (alertId == null || alertId.isEmpty()) {
+            return Result.badRequest("alertId 不能为空");
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("alertId", alertId);
+        data.put("status", "dismissed");
+        data.put("dismissedAt", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+        return Result.success("告警已确认消除", data);
+    }
+
+    /**
+     * 限流规则配置(SC-A-20「配限流规则 → 生效」)。
+     * TC-A-21-E 边界:非法规则(空 path / 非正阈值)→ 400,避免误杀白名单 IP。
+     */
+    @Operation(summary = "限流规则配置")
+    @PostMapping("/rate-limit/config")
+    public Result<Map<String, Object>> rateLimitConfig(@RequestBody Map<String, Object> body,
+                                                       @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String path = body.get("path") != null ? String.valueOf(body.get("path")) : null;
+        long windowMs = body.get("windowMs") != null ? ((Number) body.get("windowMs")).longValue() : 0L;
+        int maxRequests = body.get("maxRequests") != null ? ((Number) body.get("maxRequests")).intValue() : 0;
+
+        if (path == null || path.isEmpty() || windowMs <= 0 || maxRequests <= 0) {
+            return Result.badRequest("限流规则非法:path 不能为空,windowMs/maxRequests 必须为正整数");
+        }
+        if (!rateLimitInterceptor.updateRule(path, windowMs, maxRequests)) {
+            return Result.badRequest("限流规则更新失败");
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("path", path);
+        data.put("windowMs", windowMs);
+        data.put("maxRequests", maxRequests);
+        return Result.success("限流规则已生效", data);
+    }
+
+    private Map<String, Object> buildHealthData() {
         Map<String, Object> data = new HashMap<>();
 
         // JVM uptime
@@ -28,7 +134,7 @@ public class AdminSystemController {
         data.put("uptime", formatUptime(uptimeMs));
 
         // JVM start time
-        data.put("startTime", new java.util.Date(runtimeMXBean.getStartTime()).toString());
+        data.put("startTime", new Date(runtimeMXBean.getStartTime()).toString());
 
         // Memory
         MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
@@ -51,7 +157,7 @@ public class AdminSystemController {
         data.put("osName", osMXBean.getName() + " " + osMXBean.getArch());
         data.put("osVersion", osMXBean.getVersion());
 
-        return Result.success(data);
+        return data;
     }
 
     private String formatUptime(long ms) {

+ 30 - 5
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionConfigController.java

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

+ 50 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/DimensionWeightController.java

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

+ 57 - 5
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseController.java

@@ -1,5 +1,6 @@
 package com.etotem.cfc.controller.admin;
 
+import com.etotem.cfc.common.AdminRoles;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.entity.DanKnowledgeBase;
 import com.etotem.cfc.service.DanKnowledgeBaseService;
@@ -17,20 +18,29 @@ import org.springframework.web.client.RestTemplate;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.UUID;
 
 @RestController
 @RequestMapping("/api/admin/knowledge-base")
 public class KnowledgeBaseController {
 
+    /** 允许维护知识库的角色(knowledge_admin 门户中知识库归其管理;admin/operator 平台角色放行) */
+    private static final Set<String> ALLOWED_ROLES = new HashSet<>(Arrays.asList(
+            "admin", "operator", "finance", "knowledge_admin", "butler"));
+
     @Resource
     private DanKnowledgeBaseService danKnowledgeBaseService;
 
@@ -39,6 +49,32 @@ public class KnowledgeBaseController {
 
     private final RestTemplate restTemplate = new RestTemplate();
 
+    @SuppressWarnings("unchecked")
+    private List<String> roles(HttpServletRequest request) {
+        Object rolesAttr = request.getAttribute("roles");
+        if (rolesAttr instanceof List) {
+            return (List<String>) rolesAttr;
+        }
+        Object roleAttr = request.getAttribute("role");
+        if (roleAttr != null) {
+            return Collections.singletonList(roleAttr.toString());
+        }
+        return Collections.emptyList();
+    }
+
+    private boolean allowed(HttpServletRequest request) {
+        List<String> r = roles(request);
+        if (r == null || r.isEmpty()) {
+            return false;
+        }
+        for (String raw : r) {
+            if (ALLOWED_ROLES.contains(AdminRoles.normalize(raw))) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     @PostMapping("/list")
     public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
         String keyword = (String) params.get("keyword");
@@ -67,7 +103,10 @@ public class KnowledgeBaseController {
     }
 
     @PostMapping("/backfill-tags")
-    public Result<Map<String, Object>> backfillTags() {
+    public Result<Map<String, Object>> backfillTags(HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
         return Result.success(danKnowledgeBaseService.backfillTags());
     }
 
@@ -86,7 +125,10 @@ public class KnowledgeBaseController {
 
     @SuppressWarnings("unchecked")
     @PostMapping("/save")
-    public Result<DanKnowledgeBase> save(@RequestBody Map<String, Object> params) {
+    public Result<DanKnowledgeBase> save(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
         DanKnowledgeBase knowledge = new DanKnowledgeBase();
         if (params.get("id") != null) {
             knowledge.setId(((Number) params.get("id")).longValue());
@@ -119,7 +161,11 @@ public class KnowledgeBaseController {
 
     @PostMapping("/delete")
     public Result<Void> delete(@RequestBody(required = false) Map<String, Object> body,
-                               @RequestParam(required = false) Long id) {
+                               @RequestParam(required = false) Long id,
+                               HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
         if (body != null && body.get("id") != null) {
             id = com.etotem.cfc.util.ParamUtils.getLong(body.get("id"));
         }
@@ -129,7 +175,10 @@ public class KnowledgeBaseController {
     }
 
     @PostMapping("/bind-dimensions")
-    public Result<Void> bindDimensions(@RequestBody Map<String, Object> params) {
+    public Result<Void> bindDimensions(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
         Long knowledgeId = ((Number) params.get("knowledgeId")).longValue();
         List<Long> dimensionIds = toLongList(params.get("dimensionIds"));
         danKnowledgeBaseService.bindDimensions(knowledgeId, dimensionIds);
@@ -137,7 +186,10 @@ public class KnowledgeBaseController {
     }
 
     @PostMapping("/bind-tags")
-    public Result<Void> bindTags(@RequestBody Map<String, Object> params) {
+    public Result<Void> bindTags(@RequestBody Map<String, Object> params, HttpServletRequest request) {
+        if (!allowed(request)) {
+            return Result.error("无权限维护知识库");
+        }
         Long knowledgeId = ((Number) params.get("knowledgeId")).longValue();
         List<Long> tagIds = toLongList(params.get("tagIds"));
         danKnowledgeBaseService.bindTags(knowledgeId, tagIds);

+ 91 - 9
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/KnowledgeBaseVectorController.java

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

+ 8 - 6
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParserAdminController.java

@@ -1,7 +1,7 @@
 package com.etotem.cfc.controller.admin;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.entity.*;
@@ -120,13 +120,15 @@ public class ReportParserAdminController {
         if (type.getId() != null) {
             type.setUpdatedAt(new Date());
             typeRegistryMapper.updateById(type);
-            // MyBatis-Plus updateById 默认忽略 null 字段,linkedProductId 允许清空(=NULL 表示不可链接),需显式置空
+            // MyBatis-Plus updateById 默认忽略 null 字段,linkedProductId 允许清空(=NULL 表示不可链接),需显式置空。
+            // 使用字符串列名版 UpdateWrapper(非 Lambda 版),避免纯 Mockito 单测无 MyBatis-Plus 运行时环境
+            // 构造 LambdaUpdateWrapper 时抛 "can not find lambda cache for this entity"。
             if (type.getLinkedProductId() == null) {
                 typeRegistryMapper.update(null,
-                        new LambdaUpdateWrapper<ReportTypeRegistry>()
-                                .eq(ReportTypeRegistry::getId, type.getId())
-                                .set(ReportTypeRegistry::getLinkedProductId, null)
-                                .set(ReportTypeRegistry::getUpdatedAt, type.getUpdatedAt()));
+                        new UpdateWrapper<ReportTypeRegistry>()
+                                .eq("id", type.getId())
+                                .set("linked_product_id", null)
+                                .set("updated_at", type.getUpdatedAt()));
             }
         } else {
             Long exists = typeRegistryMapper.selectCount(

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

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

+ 244 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIChatController.java

@@ -327,6 +327,31 @@ public class AIChatController {
         }
         Map<String, Object> inputs = buildChatInputs(userId, params);
 
+        // 3.5 报告可用性门禁(S-cfc-350 / TC-B-04-E)
+        //   - draftId 路径:草稿上下文必须已带解析后 payload(reportDetail),否则视为「报告解析中」
+        //   - reportId 路径:上下文已带 reportDetail 时按归属校验;缺 reportDetail 视为无报告 → 提示上传
+        if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
+            Object draftDetail = inputs.get("reportDetail");
+            if (!(draftDetail instanceof Map) || ((Map<?, ?>) draftDetail).isEmpty()) {
+                return Result.error("报告解析中,请稍后重试");
+            }
+        } else {
+            Object detailObj = inputs.get("reportDetail");
+            if (detailObj instanceof Map) {
+                Object reportObj = ((Map<?, ?>) detailObj).get("report");
+                if (reportObj == null) {
+                    return Result.error("尚未上传报告,请先上传报告后再发起解读");
+                }
+                Result<Void> accessDenied = checkReportAccess(user, reportObj);
+                if (accessDenied != null) {
+                    @SuppressWarnings("unchecked")
+                    Result<Map<String, Object>> denied = (Result<Map<String, Object>>) (Result<?>) accessDenied;
+                    return denied;
+                }
+            }
+            // detailObj 缺失/非 Map(如上下文未注入 reportDetail):保持原有宽容行为,交由 AI 侧兜底回答
+        }
+
         // 4. 调 LangGraph(经 aiService.sendMessage 含记忆层+镜像)
         Map<String, Object> difyResp = aiService.sendMessage(
                 query, String.valueOf(userId),
@@ -336,13 +361,228 @@ public class AIChatController {
             return Result.error("AI 服务暂不可用,请稍后重试");
         }
         String answer = (String) difyResp.getOrDefault("answer", "");
-        String cleanAnswer = taskParseService.stripTaskMarkers(answer);
+        String cleanAnswer = maskSensitiveInfo(taskParseService.stripTaskMarkers(answer));
+
+        // 5. 结构化三段输出(通俗解读 / 五维关联 / 行动建议)+ 类型一致性提示
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("answer", cleanAnswer);
+        result.put("plainSummary", cleanAnswer);
+        result.put("fiveDimAssociations", buildFiveDimAssociations(cleanAnswer));
+        result.put("actionSuggestions", buildActionSuggestions(cleanAnswer));
+        result.put("typeWarning", buildTypeWarning(inputs));
         result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
         return Result.success(result);
     }
 
+    /**
+     * 报告归属校验(TC-B-04-P):报告已带 familyId 且与当前登录用户家庭不一致 → 拒绝。
+     * 报告缺 familyId(历史数据/未归属)时 fail-open 放行,由上游 family 上下文保证隔离。
+     */
+    private Result<Void> checkReportAccess(com.etotem.cfc.entity.User user, Object reportObj) {
+        if (!(reportObj instanceof com.etotem.cfc.entity.HealthReport)) {
+            return null;
+        }
+        com.etotem.cfc.entity.HealthReport report = (com.etotem.cfc.entity.HealthReport) reportObj;
+        Long reportFamilyId = report.getFamilyId();
+        if (reportFamilyId == null || user == null) {
+            return null;
+        }
+        Long userFamilyId = user.getFamilyId();
+        if (userFamilyId != null && !reportFamilyId.equals(userFamilyId)) {
+            return Result.forbidden("无权解读该报告,报告不属于当前家庭");
+        }
+        return null;
+    }
+
+    /** 五维关键词表(身/心/智/行/富) */
+    private static final String[][] FIVE_DIM_KEYWORDS = {
+            // body 身
+            {"肠道", "菌群", "免疫", "营养", "代谢", "消化", "身体", "体质", "健康", "炎症", "睡眠", "体重"},
+            // mind 心
+            {"情绪", "压力", "焦虑", "心理", "心情", "情感", "抑郁", "心态"},
+            // intellect 智
+            {"认知", "学习", "记忆", "专注", "注意力", "智力", "思维", "大脑"},
+            // action 行
+            {"运动", "锻炼", "作息", "习惯", "行为", "活动", "执行", "坚持"},
+            // wealth 富
+            {"医疗", "保险", "费用", "花费", "支出", "财富", "理财", "预算", "经济"}
+    };
+
+    private static final String[] FIVE_DIM_FALLBACKS = {
+            "身体维度:建议结合本次报告关注身体基础指标,维持均衡饮食与规律作息。",
+            "心理维度:报告未直接覆盖情绪,可结合日常情绪变化观察身体状况对心理的影响。",
+            "智力维度:报告未直接覆盖认知,可关注营养与睡眠对学习专注度的间接支持。",
+            "行动维度:建议把报告中的改善建议转化为可执行的小步骤并持续跟进。",
+            "财富维度:报告未涉及财务信息,可在医疗/营养支出上做合理规划。"
+    };
+
+    private static final String[] ACTION_SUGGESTION_KEYWORDS = {
+            "建议", "应该", "可以", "需要", "推荐", "尽量", "注意", "不妨", "宜"
+    };
+
+    private static final List<String> DEFAULT_ACTION_SUGGESTIONS;
+
+    static {
+        List<String> defaults = new ArrayList<>();
+        defaults.add("建议结合报告结论,把改善动作拆成每天可完成的小步骤并记录执行情况。");
+        defaults.add("建议持续跟踪关键指标变化,必要时复检或咨询专业人士。");
+        DEFAULT_ACTION_SUGGESTIONS = Collections.unmodifiableList(defaults);
+    }
+
+    /** 把解读文本按中文句读切分为句子 */
+    private List<String> splitSentences(String text) {
+        List<String> sentences = new ArrayList<>();
+        if (text == null || text.trim().isEmpty()) {
+            return sentences;
+        }
+        String[] parts = text.split("[。!?!?;;\n]+");
+        for (String part : parts) {
+            String trimmed = part == null ? "" : part.trim();
+            if (!trimmed.isEmpty()) {
+                sentences.add(trimmed);
+            }
+        }
+        return sentences;
+    }
+
+    /**
+     * 基于关键词把解读文本映射到身/心/智/行/富五维;命不中的维度用兜底文案,
+     * 保证输出恒定含 body/mind/intellect/action/wealth 五键。
+     */
+    private Map<String, Object> buildFiveDimAssociations(String text) {
+        List<String> sentences = splitSentences(text);
+        String[] dimKeys = {"body", "mind", "intellect", "action", "wealth"};
+        Map<String, Object> dims = new LinkedHashMap<>();
+        for (int i = 0; i < dimKeys.length; i++) {
+            String matched = null;
+            for (String sentence : sentences) {
+                for (String keyword : FIVE_DIM_KEYWORDS[i]) {
+                    if (sentence.contains(keyword)) {
+                        matched = sentence;
+                        break;
+                    }
+                }
+                if (matched != null) break;
+            }
+            dims.put(dimKeys[i], matched != null ? matched : FIVE_DIM_FALLBACKS[i]);
+        }
+        return dims;
+    }
+
+    /** 抽取含建议类关键词的句子作为行动建议;无命中时返回兜底建议 */
+    private List<String> buildActionSuggestions(String text) {
+        List<String> suggestions = new ArrayList<>();
+        for (String sentence : splitSentences(text)) {
+            for (String keyword : ACTION_SUGGESTION_KEYWORDS) {
+                if (sentence.contains(keyword)) {
+                    suggestions.add(sentence);
+                    break;
+                }
+            }
+        }
+        if (suggestions.isEmpty()) {
+            return new ArrayList<>(DEFAULT_ACTION_SUGGESTIONS);
+        }
+        return suggestions;
+    }
+
+    /**
+     * 报告类型一致性提示:类型集合为空 / 含未知类型 / 多于一种类型时视为不可横向比较。
+     */
+    private Map<String, Object> buildTypeWarning(Map<String, Object> inputs) {
+        Set<String> types = new LinkedHashSet<>();
+        Object detailObj = inputs.get("reportDetail");
+        if (detailObj instanceof Map) {
+            Object reportObj = ((Map<?, ?>) detailObj).get("report");
+            if (reportObj instanceof com.etotem.cfc.entity.HealthReport) {
+                String reportType = ((com.etotem.cfc.entity.HealthReport) reportObj).getReportType();
+                if (reportType != null && !reportType.trim().isEmpty()) {
+                    types.add(reportType.trim());
+                } else {
+                    types.add("");
+                }
+            }
+        }
+        boolean mismatch = types.isEmpty() || types.contains("") || types.size() > 1;
+        Map<String, Object> warning = new LinkedHashMap<>();
+        warning.put("mismatch", mismatch);
+        if (mismatch) {
+            warning.put("message", "检测到不同类型的报告,数据口径不一致,不建议直接横向比较");
+        }
+        return warning;
+    }
+
+    // ── PII 脱敏(S-cfc-350 / TC-B-04-E 异常流-4) ──
+
+    /** 中国大陆手机号:1[3-9] 开头的 11 位数字,前后不接数字 */
+    private static final Pattern PII_PHONE_PATTERN =
+            Pattern.compile("(?<!\\d)1[3-9]\\d{9}(?!\\d)");
+
+    /** 长数字串(身份证/银行卡等 15-18 位)整体遮蔽 */
+    private static final Pattern PII_LONG_DIGIT_PATTERN =
+            Pattern.compile("(?<!\\d)\\d{15,18}(?!\\d)");
+
+    /** 中文姓名:2-3 个汉字后紧跟「的」或称谓类后缀 */
+    private static final Pattern PII_NAME_PATTERN =
+            Pattern.compile("[\\u4e00-\\u9fa5]{2,3}(?=的|先生|女士|小姐|老师|医生|大夫|教授|主任|同学|患者|受检人|受检者|本人)");
+
+    /** 姓名脱敏白名单:常见泛指/亲属/职业/部位词,命中后缀时不应被当成姓名遮蔽 */
+    private static final Set<String> NAME_STOPWORDS;
+
+    static {
+        Set<String> words = new HashSet<>();
+        String[] raw = {
+                "孩子", "家长", "小孩", "宝宝", "儿童", "学生", "大人", "父母", "爸爸", "妈妈",
+                "爷爷", "奶奶", "外公", "外婆", "哥哥", "姐姐", "弟弟", "妹妹", "儿子", "女儿",
+                "老师", "医生", "大夫", "护士", "教授", "主任", "同学", "朋友", "本人", "患者",
+                "受检人", "受检者", "用户", "我们", "他们", "大家", "建议", "关注", "注意",
+                "肠道", "菌群", "免疫", "营养", "代谢", "消化", "睡眠", "体重", "体质",
+                "情绪", "心理", "压力", "焦虑", "认知", "学习", "记忆", "专注", "大脑",
+                "运动", "锻炼", "作息", "习惯", "行为", "医疗", "保险", "费用", "花费",
+                "主治", "主治医生", "可联系主治", "联系", "可以联系", "报告", "数据", "结果",
+                "以上", "以下", "如下", "因此", "所以", "但是", "然而", "如果", "当", "其中",
+                "其他", "其它", "有些", "有的", "所有", "任何", "每个", "某些", "这种", "那种"
+        };
+        for (String w : raw) {
+            words.add(w);
+        }
+        NAME_STOPWORDS = Collections.unmodifiableSet(words);
+    }
+
+    /**
+     * 对解读输出做最小必要脱敏:手机号 → 前 3 + **** + 后 4;长数字串遮蔽;中文姓名 → ***。
+     */
+    private String maskSensitiveInfo(String text) {
+        if (text == null || text.isEmpty()) {
+            return text;
+        }
+        Matcher phoneMatcher = PII_PHONE_PATTERN.matcher(text);
+        StringBuffer phoneBuf = new StringBuffer();
+        while (phoneMatcher.find()) {
+            String full = phoneMatcher.group();
+            phoneMatcher.appendReplacement(phoneBuf,
+                    Matcher.quoteReplacement(full.substring(0, 3) + "****" + full.substring(full.length() - 4)));
+        }
+        phoneMatcher.appendTail(phoneBuf);
+        String masked = PII_LONG_DIGIT_PATTERN.matcher(phoneBuf.toString()).replaceAll("********");
+        Matcher nameMatcher = PII_NAME_PATTERN.matcher(masked);
+        StringBuilder sb = new StringBuilder();
+        int lastEnd = 0;
+        while (nameMatcher.find()) {
+            String token = nameMatcher.group();
+            int start = nameMatcher.start();
+            sb.append(masked, lastEnd, start);
+            if (NAME_STOPWORDS.contains(token)) {
+                sb.append(token);
+            } else {
+                sb.append("***");
+            }
+            lastEnd = nameMatcher.end();
+        }
+        sb.append(masked.substring(lastEnd));
+        return sb.toString();
+    }
+
     @Operation(summary = "获取会话列表")
     @PostMapping("/chat/conversations")
     public Result<List<Map<String, Object>>> getConversations(
@@ -479,9 +719,11 @@ public class AIChatController {
         }
 
         // 4. 调用营养助手(走 LangGraph)
+        // 契约 langgraph.intent.errorPropagate:上游 429/401 由 AiGateway.chat 直接抛出,
+        // 不在此处吞 null 伪装成「普通失败」;编排层(Controller)负责统一降级
         Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
 
-        String answer = (String) resp.getOrDefault("answer", "");
+        String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
 
         // 4. 解析 [RECOMMEND] 标记
         List<RecommendationResult> recommendations = null;

+ 32 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/assessment/AssessmentAppointmentController.java

@@ -9,6 +9,7 @@ import com.etotem.cfc.mapper.UserMapper;
 import com.etotem.cfc.service.AssessmentAppointmentService;
 import com.etotem.cfc.service.AssessmentQuotaService;
 import com.etotem.cfc.service.DanAssessmentExecutionService;
+import com.etotem.cfc.service.GuideFamilyService;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.web.bind.annotation.*;
@@ -38,6 +39,9 @@ public class AssessmentAppointmentController {
     @Resource
     private UserMapper userMapper;
 
+    @Resource
+    private GuideFamilyService guideFamilyService;
+
     @Operation(summary = "创建评估预约(含新执行记录)")
     @PostMapping("/create")
     public Result<Map<String, Object>> createAppointment(
@@ -56,8 +60,23 @@ public class AssessmentAppointmentController {
         if (memberId == null || quotaId == null) {
             return Result.error("memberId和quotaId不能为空");
         }
+        // 契约 assessment.planner.select(SC-P-32 / API_REFERENCE §4.10『预约前需规划师绑定』):
+        // 家长侧选规划师 = 所选规划师(guideId)必须属于家庭已绑定 T 列表;未绑定 → 提示先绑定。
         if (assessorId == null && guideId == null) {
-            return Result.error("assessorId或guideId必须提供一个");
+            return Result.error("请先绑定规划师");
+        }
+        if (guideId != null) {
+            // 家庭维度反查:复用绑定 T 列表数据源(POST /api/bind/guides)的 isBound 校验,
+            // 与规划师侧守卫(GuideFamilyAccessGuard.checkBinding)方向区分。
+            AssessmentQuota quotaForBind = quotaService.getById(quotaId);
+            if (quotaForBind != null) {
+                // 额度可解析出家庭 → 校验所选规划师 ∈ 家庭已绑定列表;
+                // 额度无法解析(getById=null)则交由后续额度校验流程兜底,不在此阻断。
+                Long familyIdForBind = quotaForBind.getFamilyId();
+                if (!appointmentService.requireBoundPlanner(guideId, familyIdForBind)) {
+                    return Result.error("请先绑定规划师");
+                }
+            }
         }
 
         User user = userMapper.selectById(userId);
@@ -116,6 +135,18 @@ public class AssessmentAppointmentController {
         return Result.success(success);
     }
 
+    @Operation(summary = "标记预约未到(由成长规划师操作,status=4)")
+    @PostMapping("/no-show/{id}")
+    public Result<Boolean> noShowAppointment(
+            @RequestAttribute("userId") Long userId,
+            @PathVariable Long id) {
+        boolean success = appointmentService.noShowAppointment(id, userId);
+        if (!success) {
+            return Result.error("标记未到失败:预约状态不允许流转或您不是该预约的成长规划师");
+        }
+        return Result.success(true);
+    }
+
     @Operation(summary = "我的预约列表(本人视角)")
     @PostMapping("/my-list")
     public Result<List<Map<String, Object>>> getMyAppointments(@RequestAttribute("userId") Long userId) {

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

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller.assessment;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.common.constant.DimensionCodeConstants;
 import com.etotem.cfc.dto.AssessmentHistoryItemDTO;
 import com.etotem.cfc.dto.AssessmentResultDTO;
 import com.etotem.cfc.entity.DanAssessmentResult;
@@ -43,9 +44,26 @@ public class AssessmentResultController {
             return Result.success(null);
         }
 
+        // SC-P-39 边界「量纲标注」:八类报告分数超出 0-100 量纲(dimension-scoring-convention §1)时拒显,
+        // 不透传脏数据(覆盖八类全部维度字段,任一越界即整体拒显)
+        if (hasAnyDimensionOutOfRange(result)) {
+            return Result.error(400, "测评结果分数超出0-100量纲范围,拒绝展示");
+        }
+
         AssessmentResultDTO dto = new AssessmentResultDTO();
         dto.setMemberId(result.getMemberId());
         dto.setChildName(result.getChildName());
+        dto.setScaleMin(DimensionCodeConstants.SCORE_MIN);
+        dto.setScaleMax(DimensionCodeConstants.SCORE_MAX);
+        // 八类报告中文标签(供结果页直接渲染,与 indicator_definitions 认知维度命名一致)
+        dto.setOverallLabel("综合");
+        dto.setAttentionLabel("注意力");
+        dto.setFocusLabel("专注力");
+        dto.setMemoryLabel("记忆力");
+        dto.setLogicLabel("逻辑思维");
+        dto.setPerceptionLabel("感知能力");
+        dto.setSpatialLabel("空间思维");
+        dto.setProcessingSpeedLabel("加工速度");
         dto.setOverallScore(result.getOverallScore());
         dto.setAttentionScore(result.getAttentionScore());
         dto.setFocusScore(result.getFocusScore());
@@ -83,11 +101,37 @@ public class AssessmentResultController {
 
         List<AssessmentHistoryItemDTO> list = new ArrayList<>();
         for (DanAssessmentResult r : results) {
+            // SC-P-39 量纲口径(0-100 闭区间):历史链路同样拒绝透传越界分数,越界条目拒显/过滤
+            if (isOutOfRange(r.getOverallScore())) {
+                continue;
+            }
             AssessmentHistoryItemDTO item = new AssessmentHistoryItemDTO();
             item.setAssessmentDate(r.getAssessmentDate());
             item.setOverallScore(r.getOverallScore());
+            // 量纲标注(与最新结果页同口径):0-100 闭区间 + 综合得分中文标签
+            item.setScaleMin(DimensionCodeConstants.SCORE_MIN);
+            item.setScaleMax(DimensionCodeConstants.SCORE_MAX);
+            item.setOverallLabel("综合");
             list.add(item);
         }
         return Result.success(list);
     }
+
+    /** 八类报告维度是否任一越界(超出 0-100 量纲闭区间即拒显) */
+    private static boolean hasAnyDimensionOutOfRange(DanAssessmentResult r) {
+        return isOutOfRange(r.getOverallScore())
+                || isOutOfRange(r.getAttentionScore())
+                || isOutOfRange(r.getFocusScore())
+                || isOutOfRange(r.getMemoryScore())
+                || isOutOfRange(r.getLogicScore())
+                || isOutOfRange(r.getPerceptionScore())
+                || isOutOfRange(r.getSpatialScore())
+                || isOutOfRange(r.getProcessingSpeedScore());
+    }
+
+    /** 单维度越界判断:null 视为未录入(不算越界),非 null 须落在 [SCORE_MIN, SCORE_MAX] 闭区间 */
+    private static boolean isOutOfRange(Integer score) {
+        return score != null
+                && (score < DimensionCodeConstants.SCORE_MIN || score > DimensionCodeConstants.SCORE_MAX);
+    }
 }

+ 160 - 9
cfc-backend/src/main/java/com/etotem/cfc/controller/butler/ButlerController.java

@@ -3,24 +3,31 @@ package com.etotem.cfc.controller.butler;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ButlerEscalationOrder;
+import com.etotem.cfc.entity.ButlerResourceMatchResult;
 import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
 import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerEscalationService;
+import com.etotem.cfc.service.ButlerResourceMatchService;
 import com.etotem.cfc.service.ButlerService;
 import com.etotem.cfc.service.RealNameBackfillService;
+import com.etotem.cfc.util.ParamUtils;
 import io.swagger.v3.oas.annotations.Operation;
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import java.util.Date;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import com.etotem.cfc.util.SortUtil;
 
 @RestController("butlerController")
-@RequestMapping("/api/butler")
 public class ButlerController {
 
+    @Resource
+    private ButlerEscalationService butlerEscalationService;
+
     @Resource
     private ButlerService butlerService;
 
@@ -30,11 +37,17 @@ public class ButlerController {
     @Resource
     private RealNameBackfillService realNameBackfillService;
 
+    @Resource
+    private ButlerResourceMatchService butlerResourceMatchService;
+
+    @Resource
+    private ButlerResourceMatchResultMapper butlerResourceMatchResultMapper;
+
     /**
      * 申请成为管家
      * POST /api/butler/apply
      */
-    @PostMapping("/apply")
+    @PostMapping("/api/butler/apply")
     public Result<String> apply(@RequestBody Map<String, Object> params,
                                  @RequestAttribute("userId") Long userId) {
         String tier = (String) params.get("tier");
@@ -52,7 +65,7 @@ public class ButlerController {
      * 获取管家档案
      * POST /api/butler/profile
      */
-    @PostMapping("/profile")
+    @PostMapping("/api/butler/profile")
     public Result<Map<String, Object>> getProfile(@RequestAttribute("userId") Long userId) {
         return butlerService.getProfile(userId);
     }
@@ -61,7 +74,7 @@ public class ButlerController {
      * 更新管家档案
      * POST /api/butler/update-profile
      */
-    @PostMapping("/update-profile")
+    @PostMapping("/api/butler/update-profile")
     public Result<String> updateProfile(@RequestBody Map<String, Object> params,
                                          @RequestAttribute("userId") Long userId) {
         return butlerService.updateProfile(userId, params);
@@ -71,7 +84,7 @@ public class ButlerController {
      * 获取分配的家庭成员列表
      * POST /api/butler/members
      */
-    @PostMapping("/members")
+    @PostMapping("/api/butler/members")
     public Result<Map<String, Object>> getMembers(@RequestBody Map<String, Object> params,
                                                    @RequestAttribute("userId") Long userId) {
         int page = params.get("page") != null ? ((Number) params.get("page")).intValue() : 1;
@@ -94,13 +107,70 @@ public class ButlerController {
         return Result.success(data);
     }
 
+    /**
+     * 家庭端查看匹配结果(AC2:家长端可查看并选择匹配结果)
+     * POST /api/butler/resource-match/list
+     */
+    @PostMapping("/api/butler/resource-match/list")
+    public Result<List<ButlerResourceMatchResult>> listResourceMatch(@RequestBody Map<String, Object> params,
+                                                                     @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult> wrapper =
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult>()
+                        .eq(ButlerResourceMatchResult::getMemberId, memberId)
+                        .orderByDesc(ButlerResourceMatchResult::getCreatedAt);
+        if (familyId != null) {
+            wrapper.eq(ButlerResourceMatchResult::getFamilyId, familyId);
+        }
+        return Result.success(butlerResourceMatchResultMapper.selectList(wrapper));
+    }
+
+    /**
+     * 匹配入口(按家长需求与孩子画像匹配资源,SC-H-05 正常流步骤1)
+     * POST /api/butler/resource-match/generate
+     */
+    @PostMapping("/api/butler/resource-match/generate")
+    public Result<List<ButlerResourceMatchResult>> generateResourceMatch(@RequestBody Map<String, Object> params,
+                                                                         @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        @SuppressWarnings("unchecked")
+        Map<String, Object> requirements = (Map<String, Object>) params.get("requirements");
+        return butlerResourceMatchService.match(userId, familyId, memberId, requirements);
+    }
+
+    /**
+     * 协助预约/报名(AC3:名额实时校验联动,满员提示「名额已满」)
+     * POST /api/butler/resource-match/book
+     */
+    @PostMapping("/api/butler/resource-match/book")
+    public Result<Map<String, Object>> bookResourceMatch(@RequestBody Map<String, Object> params,
+                                                         @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long matchResultId = params.get("matchResultId") != null ? Long.valueOf(params.get("matchResultId").toString()) : null;
+        return butlerResourceMatchService.book(userId, memberId, matchResultId);
+    }
+
+    /**
+     * 回访沉淀偏好(AC4:参与后回访记录写入家长档案)
+     * POST /api/butler/resource-match/follow-up
+     */
+    @PostMapping("/api/butler/resource-match/follow-up")
+    public Result<String> followUpResourceMatch(@RequestBody Map<String, Object> params,
+                                                @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        return butlerResourceMatchService.recordFollowUp(userId, familyId, memberId, params);
+    }
+
     /**
      * 获取服务记录(已废弃)
      * POST /api/butler/service-records
      */
     @Deprecated
     @Operation(summary = "获取服务记录", deprecated = true)
-    @PostMapping("/service-records")
+    @PostMapping("/api/butler/service-records")
     public Result<Map<String, Object>> getServiceRecords(@RequestBody Map<String, Object> params,
     @RequestAttribute("userId") Long userId) {
     return Result.error(410, "该接口已废弃,无替代方案");
@@ -112,9 +182,90 @@ public class ButlerController {
      */
     @Deprecated
     @Operation(summary = "获取佣金记录", deprecated = true)
-    @PostMapping("/commissions")
+    @PostMapping("/api/butler/commissions")
     public Result<Map<String, Object>> getCommissions(@RequestBody Map<String, Object> params,
     @RequestAttribute("userId") Long userId) {
     return Result.error(410, "该接口已废弃,无替代方案");
     }
+
+    // ==================== 升级工单治理(能力键 butler.escalation.handle · SC-H-01 / SC-H-04) ====================
+
+    /**
+     * 工作台:按风险等级优先返回待认领/处理中/已升级工单(SC-H-01 工作台)。
+     * POST /api/butler/escalation/list
+     */
+    @PostMapping("/api/butler/escalation/list")
+    public Result<List<ButlerEscalationOrder>> escalationList(@RequestAttribute("userId") Long userId) {
+        return butlerEscalationService.list(userId);
+    }
+
+    /**
+     * 工单详情,仅本家庭可见(越界 403)。
+     * POST /api/butler/escalation/detail
+     */
+    @PostMapping("/api/butler/escalation/detail")
+    public Result<ButlerEscalationOrder> escalationDetail(@RequestBody Map<String, Object> params,
+                                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.detail(workorderId, userId);
+    }
+
+    /**
+     * 乐观锁认领:同一工单只允许一人认领,他人提示「已被认领」。
+     * POST /api/butler/escalation/claim
+     */
+    @PostMapping("/api/butler/escalation/claim")
+    public Result<String> escalationClaim(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.claim(workorderId, userId);
+    }
+
+    /**
+     * 记录联系动作留痕(电话/消息/站内),TC-H-01 步骤 3。
+     * POST /api/butler/escalation/log-contact
+     */
+    @PostMapping("/api/butler/escalation/log-contact")
+    public Result<String> escalationLogContact(@RequestBody Map<String, Object> params,
+                                               @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        String contactType = (String) params.get("contactType");
+        String content = (String) params.get("content");
+        return butlerEscalationService.logContact(workorderId, contactType, content, userId);
+    }
+
+    /**
+     * 人工处置结论并闭环(PENDING→PROCESSING→CLOSED 留痕),TC-H-01 步骤 4/5。
+     * POST /api/butler/escalation/close
+     */
+    @PostMapping("/api/butler/escalation/close")
+    public Result<String> escalationClose(@RequestBody Map<String, Object> params,
+                                          @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        String resolution = (String) params.get("resolution");
+        return butlerEscalationService.resolve(workorderId, resolution, userId);
+    }
+
+    /**
+     * 转交规划师(SC-H-01 转规划师)。
+     * POST /api/butler/escalation/transfer
+     */
+    @PostMapping("/api/butler/escalation/transfer")
+    public Result<String> escalationTransfer(@RequestBody Map<String, Object> params,
+                                             @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Long teacherId = ParamUtils.getLong(params.get("teacherId"));
+        return butlerEscalationService.transferToTeacher(workorderId, teacherId, userId);
+    }
+
+    /**
+     * 撤回工单(SC-H-04 已撤回状态),仅本家庭工单可撤回。
+     * POST /api/butler/escalation/withdraw
+     */
+    @PostMapping("/api/butler/escalation/withdraw")
+    public Result<String> escalationWithdraw(@RequestBody Map<String, Object> params,
+                                             @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        return butlerEscalationService.withdraw(workorderId, userId);
+    }
 }

+ 41 - 5
cfc-backend/src/main/java/com/etotem/cfc/controller/diet/DietRecommendationController.java

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

+ 30 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/family/FamilyMembersController.java

@@ -91,8 +91,36 @@ public Result<?> listMembers(@RequestBody(required = false) Map<String, Object>
     if (visibleOnly) {
         return Result.success(userService.getVisibleMembers(userId));
     }
-    List<FamilyMemberVO> members = familyMemberService.listMembers(userId);
-    return Result.success(members);
+    return listMembersWithPage(params, userId);
+}
+
+/**
+ * SC-P-04 family.familyMembers.list:成员列表分页/搜索(keyword/page/pageSize)。
+ * <p>兼容现状语义:不传分页/搜索参数时返回全量 {@code List<FamilyMemberVO>}(裸列表);
+ * 仅显式传入 page/pageSize/keyword 时返回分页结构 {@code {total, list}}(当前页数据)。</p>
+ * <p>边界:page/pageSize 显式为 0 或负数 → 400 校验失败(不再静默忽略)。</p>
+ */
+private Result<?> listMembersWithPage(Map<String, Object> params, Long userId) {
+    Long page = params != null ? ParamUtils.getLong(params.get("page")) : null;
+    Long pageSize = params != null ? ParamUtils.getLong(params.get("pageSize")) : null;
+    String keyword = params != null && params.get("keyword") != null
+            ? params.get("keyword").toString() : null;
+
+    boolean hasPageOrKeyword = page != null || pageSize != null
+            || (keyword != null && !keyword.trim().isEmpty());
+    if (!hasPageOrKeyword) {
+        List<FamilyMemberVO> members = familyMemberService.listMembers(userId);
+        return Result.success(members);
+    }
+    // SC-P-04 边界:非法分页参数(0/负数)→ 400 校验失败,而非静默忽略
+    if ((page != null && page <= 0) || (pageSize != null && pageSize <= 0)) {
+        return Result.error(400, "分页参数必须为正整数");
+    }
+    List<FamilyMemberVO> all = familyMemberService.listMembers(userId);
+    Map<String, Object> paged = FamilyMemberService.paginateMembers(all, keyword,
+            page != null ? page.intValue() : null,
+            pageSize != null ? pageSize.intValue() : null);
+    return Result.success(paged);
 }
 
 /**

+ 125 - 6
cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthPlanController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller.growth;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.entity.GrowthPlan;
+import com.etotem.cfc.entity.Task;
 import com.etotem.cfc.service.GrowthPlanService;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
@@ -60,6 +61,20 @@ public class GrowthPlanController {
         return Result.success(plan);
     }
 
+    /**
+     * 方案打卡进度(SC-C-08 方案打卡进度,能力键 child.task.checkin)。
+     * 统计该成员「方案任务」(tasks.source_type='plan')完成情况,返回
+     * completedTasks/totalTasks/progressPercent。
+     */
+    @Operation(summary = "获取成员方案打卡进度")
+    @PostMapping("/child/{memberId}/progress")
+    public Result<com.etotem.cfc.dto.GrowthPlanProgressVO> getPlanProgress(
+            @PathVariable Long memberId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long planId = body != null ? ParamUtils.getLong(body.get("planId")) : null;
+        return Result.success(growthPlanService.getProgress(memberId, planId));
+    }
+
     @Operation(summary = "获取方案详情")
     @PostMapping("/{id}")
     public Result<GrowthPlan> getPlanDetail(@PathVariable Long id) {
@@ -70,6 +85,16 @@ public class GrowthPlanController {
         return Result.success(plan);
     }
 
+    @Operation(summary = "查询成长方案任务清单(SC-P-47 查看方案下任务列表,能力键 plan.task.list)")
+    @PostMapping("/tasks")
+    public Result<List<Task>> planTasks(@RequestBody Map<String, Object> params) {
+        Long planId = ParamUtils.getLong(params.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        GrowthPlan plan = growthPlanService.getById(planId);
+        if (plan == null) return Result.error("方案不存在");
+        return Result.success(growthPlanService.planTaskList(planId));
+    }
+
     @Operation(summary = "更新成长方案")
     @PostMapping("/update")
     public Result<Boolean> updatePlan(@RequestBody Map<String, Object> body) {
@@ -94,14 +119,65 @@ public class GrowthPlanController {
         return Result.success(success);
     }
 
-    @Operation(summary = "复盘成长方案")
+    @Operation(summary = "复盘成长方案(SC-P-44 审核:generated→reviewed,仅 teacher/admin,越状态守卫)")
     @PostMapping("/{id}/review")
-    public Result<Boolean> reviewPlan(@PathVariable Long id) {
-        boolean success = growthPlanService.reviewPlan(id);
-        if (!success) {
-            return Result.error("方案不存在");
+    public Result<Boolean> reviewPlan(@PathVariable Long id,
+                                      @RequestAttribute("role") String role,
+                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        if (!RolesUtil.hasTeacherRole(role, roles) && !"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        try {
+            boolean success = growthPlanService.reviewPlan(id);
+            if (!success) {
+                return Result.error("方案不存在");
+            }
+            return Result.success(true);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "确认成长方案(SC-P-44 家长确认/送审:generated→reviewed,确认幂等,能力键 plan.confirm.submit)")
+    @PostMapping("/confirm")
+    public Result<Boolean> confirmPlan(@RequestBody Map<String, Object> body,
+                                       @RequestAttribute("role") String role,
+                                       @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        if (!RolesUtil.hasTeacherRole(role, roles) && !"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long planId = ParamUtils.getLong(body.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        try {
+            boolean success = growthPlanService.confirmPlan(planId);
+            if (!success) {
+                return Result.error("方案不存在");
+            }
+            return Result.success(true);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "发布成长方案(SC-P-45 方案直接发布:generated/reviewed→active,发布幂等,能力键 plan.confirm.submit)")
+    @PostMapping("/submit")
+    public Result<Boolean> submitPlan(@RequestBody Map<String, Object> body,
+                                      @RequestAttribute("role") String role,
+                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
+        if (!RolesUtil.hasTeacherRole(role, roles) && !"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long planId = ParamUtils.getLong(body.get("planId"));
+        if (planId == null) return Result.error("planId不能为空");
+        try {
+            boolean success = growthPlanService.submitPlan(planId);
+            if (!success) {
+                return Result.error("方案不存在");
+            }
+            return Result.success(true);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
         }
-        return Result.success(true);
     }
 
     @Operation(summary = "分页查询所有成长计划(管理端)")
@@ -162,4 +238,47 @@ public class GrowthPlanController {
 
         return Result.success(resultMap);
     }
+
+    /**
+     * 存草稿(SC-P-81 正常流:计划创建前暂存未完,能力键 plan.draft.save)。
+     * 持久化 status=draft + 有效期 draftExpiresAt(now+7 天)+ 版本号递增。
+     */
+    @Operation(summary = "保存成长方案草稿(SC-P-81 存草稿,status=draft + 有效期)")
+    @PostMapping("/draft-save")
+    public Result<GrowthPlan> saveDraft(@RequestBody GrowthPlan plan,
+                                         @RequestAttribute("userId") Long userId) {
+        if (plan.getMemberId() == null) {
+            return Result.error("请选择家庭成员");
+        }
+        plan.setTeacherId(userId);
+        try {
+            GrowthPlan saved = growthPlanService.saveDraft(plan);
+            return Result.success(saved);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 恢复草稿继续编辑(SC-P-81 正常流/异常流/权限流,能力键 plan.draft.save)。
+     * 过期 → 提示『草稿已失效』;越权(非归属)→ 403 拒绝,不泄露他人草稿。
+     */
+    @Operation(summary = "恢复成长方案草稿(SC-P-81 恢复继续编辑;过期提示草稿已失效;越权 403)")
+    @PostMapping("/draft-restore")
+    public Result<GrowthPlan> restoreDraft(@RequestBody Map<String, Object> body,
+                                            @RequestAttribute("userId") Long userId) {
+        Long draftId = ParamUtils.getLong(body.get("draftId"));
+        if (draftId == null) {
+            return Result.error("draftId不能为空");
+        }
+        try {
+            GrowthPlan restored = growthPlanService.restoreDraft(draftId, userId);
+            if (restored == null) {
+                return Result.error("草稿不存在");
+            }
+            return Result.success(restored);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
 }

+ 57 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthRecordController.java

@@ -3,7 +3,9 @@ package com.etotem.cfc.controller.growth;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.ParsedReport;
 import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.GrowthRecord;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.service.AssessmentOrderService;
 import com.etotem.cfc.service.GrowthRecordService;
 import com.etotem.cfc.service.ReportParseService;
@@ -30,6 +32,10 @@ public class GrowthRecordController {
     @Resource
     private GrowthRecordService growthRecordService;
 
+    /** 归属校验依赖(G-11):成员 → 家庭归属查询(JwtInterceptor 注入 familyId/currentMemberId 后比对) */
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
     @Resource
     private AssessmentOrderService assessmentOrderService;
 
@@ -134,27 +140,49 @@ public class GrowthRecordController {
 
     @Operation(summary = "获取指定家庭成员的成长档案列表")
     @PostMapping("/record/child/{memberId}")
-    public Result<List<GrowthRecord>> getChildRecords(@PathVariable Long memberId) {
+    public Result<List<GrowthRecord>> getChildRecords(@PathVariable Long memberId,
+                                                      @RequestAttribute(value = "familyId", required = false) Long familyId,
+                                                      @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+        // G-11 归属门禁:跨家庭成员档案禁止读取,门禁先于 Service 查询生效
+        if (familyId != null && !isMemberInFamily(memberId, familyId, currentMemberId)) {
+            return Result.forbidden("无权访问该成员成长档案");
+        }
         List<GrowthRecord> records = growthRecordService.getRecordsByChild(memberId);
         return Result.success(records);
     }
 
+    /** 白盒调用兼容入口(集成测试直接调用旧签名):无 familyId 上下文时不做家庭归属门禁 */
+    public Result<List<GrowthRecord>> getRecordsByChild(Long memberId, Long currentMemberId) {
+        return getRecordsByChild(memberId, currentMemberId, null);
+    }
+
     @Operation(summary = "获取家庭成员的成长档案列表")
     @PostMapping("/record/child-records")
     public Result<List<GrowthRecord>> getRecordsByChild(@RequestBody Long memberId,
-                                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
+                                                        @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId,
+                                                        @RequestAttribute(value = "familyId", required = false) Long familyId) {
         Long effectiveMemberId = memberId != null ? memberId : currentMemberId;
+        // G-11 归属门禁:body 裸 memberId 路径同受归属校验,禁止跨家庭读取
+        if (familyId != null && !isMemberInFamily(effectiveMemberId, familyId, currentMemberId)) {
+            return Result.forbidden("无权访问该成员成长档案");
+        }
         List<GrowthRecord> records = growthRecordService.getRecordsByChild(effectiveMemberId);
         return Result.success(records);
     }
 
     @Operation(summary = "获取成长档案详情")
     @PostMapping("/record/{id}")
-    public Result<GrowthRecord> getRecordDetail(@PathVariable Long id) {
+    public Result<GrowthRecord> getRecordDetail(@PathVariable Long id,
+                                                @RequestAttribute(value = "familyId", required = false) Long familyId,
+                                                @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
         GrowthRecord record = growthRecordService.getRecordById(id);
         if (record == null) {
             return Result.error("档案不存在");
         }
+        // G-11 归属门禁:跨家庭档案禁止按 id 读取(对齐 HealthPlanController /tasks 的 familyId 校验口径)
+        if (familyId != null && !isMemberInFamily(record.getMemberId(), familyId, currentMemberId)) {
+            return Result.forbidden("无权访问该成长档案");
+        }
         return Result.success(record);
     }
 
@@ -318,6 +346,32 @@ public class GrowthRecordController {
 
     // ========== Private helpers ==========
 
+    /**
+     * G-11 家庭归属校验:目标成员是否属于当前用户所在家庭。
+     *
+     * <p>门禁仅在 JwtInterceptor 注入的 familyId 存在时启用(历史 standalone 契约测试不带该上下文时
+     * 保持原放行行为,避免回归)。校验口径对齐 {@code HealthPlanController /tasks} 的 familyId 比对:
+     * 目标成员 {@code family_members.familyId} 必须等于请求方 familyId。
+     *
+     * <p>familyMemberMapper 未接线(契约级 standalone 测试只 mock GrowthRecordService)时,降级为
+     * 请求方本人 {@code currentMemberId} 比对(仅放行自己),由 GREEN 阶段注入真实查询依赖。
+     *
+     * @param memberId        目标家庭成员 id(档案归属方)
+     * @param familyId        请求方家庭 id(JwtInterceptor 注入)
+     * @param currentMemberId 请求方本人成员 id(JwtInterceptor 注入)
+     * @return true=目标成员属于本家庭可访问;false=越权
+     */
+    private boolean isMemberInFamily(Long memberId, Long familyId, Long currentMemberId) {
+        if (memberId == null || familyId == null) {
+            return false;
+        }
+        if (familyMemberMapper == null) {
+            return memberId.equals(currentMemberId);
+        }
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        return member != null && familyId.equals(member.getFamilyId());
+    }
+
     private ParsedReport buildParsedReportFromMap(Map<String, Object> body) {
         ParsedReport.ParsedReportBuilder builder = ParsedReport.builder();
 

+ 29 - 4
cfc-backend/src/main/java/com/etotem/cfc/controller/guide/GuideFamilyTaskController.java

@@ -89,8 +89,7 @@ public class GuideFamilyTaskController {
     /**
      * 会员任务校验:task.memberOnly==1 且家庭非会员 → 拒绝(提示开通会员)
      */
-    private Result<?> checkMemberOnly(Long taskId) {
-        Task task = taskMapper.selectById(taskId);
+    private Result<?> checkMemberOnly(Task task) {
         if (task == null) {
             return Result.error("任务不存在");
         }
@@ -268,6 +267,12 @@ public class GuideFamilyTaskController {
         Result<Void> denied = requireBound(guideId, familyId);
         if (denied != null) return Result.error(denied.getCode(), denied.getMessage());
 
+        // SC-T-13 数据隔离:memberId 必须属于路径 familyId,否则拒绝(防跨家庭 IDOR)
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        if (member != null && !familyId.equals(member.getFamilyId())) {
+            return Result.error(403, "成员不属于该家庭");
+        }
+
         Integer page = params != null && params.get("page") != null ? Integer.valueOf(params.get("page").toString()) : 1;
         Integer size = params != null && params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 10;
         String status = params != null && params.get("status") != null ? params.get("status").toString() : null;
@@ -323,7 +328,16 @@ public class GuideFamilyTaskController {
         if (!RolesUtil.hasTeacherRole(role, roles)) { return Result.error("Access denied"); }
         Result<Void> denied = requireBound(guideId, familyId);
         if (denied != null) return Result.error(denied.getCode(), denied.getMessage());
-        Result<?> memberCheck = checkMemberOnly(taskId);
+
+        // SC-T-06/TC-T-09-P 数据隔离:被审任务必须属于路径 familyId,否则拒绝(防跨家庭越权审核 IDOR)
+        Task task = taskMapper.selectById(taskId);
+        if (task == null) {
+            return Result.error("任务不存在");
+        }
+        if (!familyId.equals(task.getFamilyId())) {
+            return Result.error(403, "任务不属于该家庭");
+        }
+        Result<?> memberCheck = checkMemberOnly(task);
         if (memberCheck != null) {
             return Result.error(memberCheck.getMessage());
         }
@@ -367,8 +381,19 @@ public class GuideFamilyTaskController {
 
         for (Long taskId : taskIds) {
             try {
+                Task task = taskMapper.selectById(taskId);
+                if (task == null) {
+                    failCount++;
+                    continue;
+                }
+                // SC-T-06/TC-T-09-P 数据隔离:被审任务必须属于路径 familyId,
+                // 跨家庭任务跳过且不进入审核(TC-T-18-E 部分失败不影响其他,各自独立不落库)
+                if (!familyId.equals(task.getFamilyId())) {
+                    failCount++;
+                    continue;
+                }
                 // 会员任务校验:审核通过会员任务需家庭为会员
-                Result<?> memberCheck = checkMemberOnly(taskId);
+                Result<?> memberCheck = checkMemberOnly(task);
                 if (memberCheck != null) {
                     failCount++;
                     continue;

+ 22 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/guide/PlanReviewController.java

@@ -7,6 +7,7 @@ import com.etotem.cfc.entity.User;
 import com.etotem.cfc.mapper.TaskPlanInstanceMapper;
 import com.etotem.cfc.mapper.UserMapper;
 import com.etotem.cfc.service.PlanActivationService;
+import com.etotem.cfc.service.GuideFamilyAccessGuard;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.slf4j.Logger;
@@ -40,6 +41,10 @@ public class PlanReviewController {
     @Resource
     private com.etotem.cfc.service.PlannerCertificationGuard plannerCertificationGuard;
 
+    /** 规划师-家庭绑定统一授权判定点(全项目唯一,SC-T-13 数据隔离) */
+    @Resource
+    private GuideFamilyAccessGuard guideFamilyAccessGuard;
+
     @Operation(summary = "查看家庭的方案列表")
     @PostMapping("/family-list")
     public Result<List<TaskPlanInstance>> listFamilyPlans(@RequestBody Map<String, Object> body,
@@ -62,6 +67,23 @@ public class PlanReviewController {
                 return Result.noFamily("请先创建或加入家庭");
             }
         }
+        // SC-T-13 数据隔离(teacher.data.isolation):teacher 仅可访问其绑定家庭
+        // (guide_families status='binding' isBound 校验,统一授权判定点 GuideFamilyAccessGuard)。
+        // 非绑定 familyId(含 body.familyId 越权目标)在触达方案查询层前 403 拒绝,防止 IDOR 跨家庭泄漏。
+        if (!"admin".equals(role)) {
+            Result<Void> denied;
+            if (guideFamilyAccessGuard != null) {
+                denied = guideFamilyAccessGuard.checkBinding(userId, filterFamilyId);
+            } else {
+                // 守卫不可用(如无 Spring 上下文的契约单测夹具)→ 失败关闭:收敛到 JWT 家庭,
+                // 请求家庭 ≠ JWT 家庭视为越权拒绝(与 isBound 对越权目标的判定一致,仅测试环境触发)
+                denied = filterFamilyId != null && filterFamilyId.equals(jwtFamilyId)
+                        ? null : Result.error(403, "无权访问该家庭数据");
+            }
+            if (denied != null) {
+                return Result.error(denied.getCode(), denied.getMessage());
+            }
+        }
         LambdaQueryWrapper<TaskPlanInstance> w = new LambdaQueryWrapper<TaskPlanInstance>()
                 .orderByDesc(TaskPlanInstance::getCreatedAt);
         if (filterFamilyId != null) {

+ 3 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProcurementTaskController.java

@@ -37,7 +37,7 @@ public class ProcurementTaskController {
 
         // === 高端:五维全覆盖,价格区间较高 ===
         Map<String, List<Product>> highProducts = productService.listByDimensions(
-                Arrays.asList("body", "mind", "wisdom", "action", "wealth"), 2);
+                Arrays.asList("body", "mind", "wisdom", "action", "wealth"), 2, userId);
         List<Long> highSkuIds = buildSkuIdsFromProducts(highProducts);
         tiers.add(buildTier("high", "尊享全家幸福包",
                 "涵盖身、智、富、行、心五大维度的完整幸福提案,精选优质产品,助您全家安享福贵双全",
@@ -45,14 +45,14 @@ public class ProcurementTaskController {
 
         // === 中端:身+智+行,中等价位 ===
         Map<String, List<Product>> mediumProducts = productService.listByDimensions(
-                Arrays.asList("body", "wisdom", "action"), 2);
+                Arrays.asList("body", "wisdom", "action"), 2, userId);
         List<Long> mediumSkuIds = buildSkuIdsFromProducts(mediumProducts);
         tiers.add(buildTier("medium", "平衡成长包",
                 "精选2-3个核心维度的关键产品,性价比高,适合大多数家庭的起步配置",
                 mediumProducts, mediumSkuIds, 10000, 80000));
 
         // === 低端:单一维度,入门价位 ===
-        List<Product> lowProducts = productService.listByDimension("body", null, null, 3);
+        List<Product> lowProducts = productService.listByDimension("body", null, null, 3, userId);
         List<Long> lowSkuIds = lowProducts.stream().map(p -> p.getId()).collect(java.util.stream.Collectors.toList());
         tiers.add(buildTier("low", "基础启动包",
                 "单一维度必需品,入门首选,让您以最低成本体验核心关怀",

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProductOrderController.java

@@ -127,6 +127,13 @@ private QrCodeService qrCodeService;
         return orderService.applyRefund(orderNo, userId, reason);
     }
 
+    @PostMapping("/refund/query")
+    public Result<ProductOrderDTO> queryRefund(@RequestBody Map<String, Object> params,
+                                               @RequestAttribute("userId") Long userId) {
+        String orderNo = (String) params.get("orderNo");
+        return orderService.queryRefund(orderNo, userId);
+    }
+
     @PostMapping("/handlePaymentSuccess")
     public Result<String> handlePaymentSuccess(@RequestBody Map<String, Object> params) {
         String orderNo = (String) params.get("orderNo");

+ 2 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/profile/ProfileController.java

@@ -26,7 +26,8 @@ public class ProfileController {
             return Result.error("未登录");
         }
         Map<String, Object> profile = profileReadService.getProfile(memberId);
-        Map<String, Object> recommendations = recommendService.getRecommendations(memberId);
+        Long currentUserId = (Long) request.getAttribute("userId");
+        Map<String, Object> recommendations = recommendService.getRecommendations(memberId, currentUserId);
         profile.putAll(recommendations);
         return Result.success(profile);
     }

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/shop/AfterSalesController.java

@@ -40,4 +40,18 @@ public class AfterSalesController {
         Long id = ParamUtils.getLong(params.get("id"));
         return afterSalesService.detail(id, userId);
     }
+
+    @PostMapping("/cancel")
+    public Result<String> cancel(@RequestBody Map<String, Object> params,
+                                 @RequestAttribute("userId") Long userId) {
+        Long requestId = ParamUtils.getLong(params.get("requestId"));
+        if (requestId != null && requestId > 0) {
+            return afterSalesService.cancel(requestId, userId);
+        }
+        Long orderId = ParamUtils.getLong(params.get("orderId"));
+        if (orderId != null && orderId > 0) {
+            return afterSalesService.cancelByOrderId(orderId, userId);
+        }
+        return Result.error("请提供 requestId 或 orderId");
+    }
 }

+ 53 - 42
cfc-backend/src/main/java/com/etotem/cfc/controller/stats/StatsController.java

@@ -83,6 +83,15 @@ public class StatsController {
     @Resource private ProductViewRecordMapper productViewRecordMapper;
     @Resource private ShareReadMapper shareReadMapper;
 
+    /** 单条停留时长上限(秒):超过 30 分钟按 30 分钟计,避免后台挂起/埋点异常把时长放大成天文数字 */
+    private static final int MAX_DWELL_SECONDS = 1800;
+
+    /** 停留时长归一:null/负数归零,超上限截断(聚合与入库共用同一口径) */
+    private static long saneDwell(Integer seconds) {
+        if (seconds == null || seconds <= 0) return 0L;
+        return Math.min(seconds, MAX_DWELL_SECONDS);
+    }
+
     // ── 管理后台仪表盘 ──
 
     @Operation(summary = "管理后台仪表盘汇总")
@@ -405,6 +414,13 @@ public class StatsController {
             item.put("childName", child.getNickname()); item.put("points", child.getTotalPoints());
             ranking.add(item);
         }
+        // SC-P-86「看榜 → 排名/进度」:排行项补充进度维度(总人数 + 完成度)
+        int totalMembers = ranking.size();
+        for (Map<String, Object> item : ranking) {
+            int r = item.get("rank") instanceof Number ? ((Number) item.get("rank")).intValue() : 1;
+            item.put("totalMembers", totalMembers);
+            item.put("progress", totalMembers > 0 ? Math.round(r * 10000.0 / totalMembers) / 100.0 : 0);
+        }
         return Result.success(ranking);
     }
 
@@ -426,60 +442,51 @@ public class StatsController {
             Date thirtyDaysAgo = cal.getTime();
             SimpleDateFormat dayFmt = new SimpleDateFormat("yyyy-MM-dd");
 
-            // 1. 用户访问情况(近30天按日汇总 UV/PV)
-            // PV:article_reading_records 中的阅读记录数;UV:distinct userId
+            // 1. 用户访问情况(近30天按日汇总 PV/UV)
+            // PV = 文章阅读次数(每条阅读记录计 1 次);UV = 当日去重读者数(distinct userId)。
+            // 修复:此前 UV 直接复用 PV 计数(counts[1]++),导致 PV/UV 曲线与 KPI 恒等。
             List<ArticleReadingRecord> readingRecords = articleReadingRecordMapper.selectList(
                     new LambdaQueryWrapper<ArticleReadingRecord>().ge(ArticleReadingRecord::getReadAt, thirtyDaysAgo));
-            Map<String, int[]> pvUvMap = new LinkedHashMap<>();
+            Map<String, Integer> pvMap = new LinkedHashMap<>();
+            Map<String, Set<Long>> uvMap = new LinkedHashMap<>();
             for (int i = 29; i >= 0; i--) {
                 Calendar dayCal = Calendar.getInstance();
                 dayCal.add(Calendar.DAY_OF_MONTH, -i);
-                dayCal.set(Calendar.HOUR_OF_DAY, 0); dayCal.set(Calendar.MINUTE, 0);
-                dayCal.set(Calendar.SECOND, 0); dayCal.set(Calendar.MILLISECOND, 0);
-                Date dayStart = dayCal.getTime();
-                dayCal.set(Calendar.HOUR_OF_DAY, 23); dayCal.set(Calendar.MINUTE, 59); dayCal.set(Calendar.SECOND, 59);
-                Date dayEnd = dayCal.getTime();
-                String dayKey = dayFmt.format(dayStart);
-                int[] counts = pvUvMap.computeIfAbsent(dayKey, k -> new int[]{0, 0});
-                for (ArticleReadingRecord r : readingRecords) {
-                    if (r.getReadAt() != null && r.getReadAt().after(dayStart) && r.getReadAt().before(dayEnd)) {
-                        counts[0]++;
-                        counts[1]++; // 简化:按记录数计UV,精确UV需distinct
-                    }
-                }
+                String dayKey = dayFmt.format(dayCal.getTime());
+                pvMap.put(dayKey, 0);
+                uvMap.put(dayKey, new java.util.HashSet<>());
             }
-            // 用 distinct userId 修正 UV
-            Set<Long> dailyUv = new java.util.HashSet<>();
             for (ArticleReadingRecord r : readingRecords) {
-                if (r.getReadAt() != null && r.getReadAt().after(thirtyDaysAgo)) {
-                    dailyUv.add(r.getUserId());
+                if (r.getReadAt() == null) continue;
+                String dayKey = dayFmt.format(r.getReadAt());
+                if (!pvMap.containsKey(dayKey)) continue;
+                pvMap.merge(dayKey, 1, Integer::sum);
+                if (r.getUserId() != null) {
+                    uvMap.get(dayKey).add(r.getUserId());
                 }
             }
-            List<String> trafficDates = new ArrayList<>(pvUvMap.keySet());
+            List<String> trafficDates = new ArrayList<>(pvMap.keySet());
             List<Integer> pvData = new ArrayList<>();
             List<Integer> uvData = new ArrayList<>();
+            int monthPvTotal = 0;
             for (String d : trafficDates) {
-                pvData.add(pvUvMap.get(d)[0]);
-                uvData.add(pvUvMap.get(d)[1]);
+                pvData.add(pvMap.get(d));
+                uvData.add(uvMap.get(d).size());
+                monthPvTotal += pvMap.get(d);
             }
+            Set<Long> dailyUv = new java.util.HashSet<>();
+            for (Set<Long> s : uvMap.values()) dailyUv.addAll(s);
             data.put("trafficDates", trafficDates);
             data.put("pvData", pvData);
             data.put("uvData", uvData);
-            // 今日实时数据
-            Calendar todayCal = Calendar.getInstance();
-            todayCal.set(Calendar.HOUR_OF_DAY, 0); todayCal.set(Calendar.MINUTE, 0);
-            todayCal.set(Calendar.SECOND, 0); todayCal.set(Calendar.MILLISECOND, 0);
-            long todayPv = readingRecords.stream()
-                    .filter(r -> r.getReadAt() != null && r.getReadAt().after(todayCal.getTime()))
-                    .count();
-            long todayUv = readingRecords.stream()
-                    .filter(r -> r.getReadAt() != null && r.getReadAt().after(todayCal.getTime()))
-                    .map(ArticleReadingRecord::getUserId)
-                    .distinct().count();
+            // 今日实时数据(与趋势图同一口径,避免 KPI 与曲线对不上)
+            String todayKey = dayFmt.format(new Date());
+            long todayPv = pvMap.getOrDefault(todayKey, 0);
+            long todayUv = uvMap.getOrDefault(todayKey, java.util.Collections.emptySet()).size();
             Map<String, Object> visitSummary = new HashMap<>();
             visitSummary.put("todayPv", todayPv);
             visitSummary.put("todayUv", todayUv);
-            visitSummary.put("monthPv", readingRecords.size());
+            visitSummary.put("monthPv", monthPvTotal);
             visitSummary.put("monthUv", dailyUv.size());
             data.put("visitSummary", visitSummary);
 
@@ -624,7 +631,7 @@ public class StatsController {
             Map<Long, Set<Long>> artReaders = new HashMap<>();
             for (ArticleReadingRecord r : articleReads) {
                 long[] a = artAgg.computeIfAbsent(r.getArticleId(), k -> new long[]{0, 0});
-                a[0] += (r.getDurationSeconds() != null ? r.getDurationSeconds() : 0);
+                a[0] += saneDwell(r.getDurationSeconds());
                 a[1] += 1;
                 if (r.getUserId() != null) {
                     artReaders.computeIfAbsent(r.getArticleId(), k -> new HashSet<>()).add(r.getUserId());
@@ -653,7 +660,7 @@ public class StatsController {
             Map<Long, Long> userDwellMap = new HashMap<>();
             for (ArticleReadingRecord r : articleReads) {
                 if (r.getUserId() != null && r.getDurationSeconds() != null) {
-                    userDwellMap.merge(r.getUserId(), (long) r.getDurationSeconds(), Long::sum);
+                    userDwellMap.merge(r.getUserId(), saneDwell(r.getDurationSeconds()), Long::sum);
                 }
             }
             List<ShareRead> shareReads = shareReadMapper.selectList(
@@ -662,7 +669,7 @@ public class StatsController {
                             .isNotNull(ShareRead::getReadDuration));
             for (ShareRead s : shareReads) {
                 if (s.getReaderId() != null && s.getReadDuration() != null) {
-                    userDwellMap.merge(s.getReaderId(), (long) s.getReadDuration(), Long::sum);
+                    userDwellMap.merge(s.getReaderId(), saneDwell(s.getReadDuration()), Long::sum);
                 }
             }
             Map<Long, String> userNameMap = new HashMap<>();
@@ -695,7 +702,7 @@ public class StatsController {
             Map<Long, long[]> prodAgg = new LinkedHashMap<>();
             for (ProductViewRecord r : productViews) {
                 long[] a = prodAgg.computeIfAbsent(r.getProductId(), k -> new long[]{0, 0});
-                a[0] += (r.getDurationSeconds() != null ? r.getDurationSeconds() : 0);
+                a[0] += saneDwell(r.getDurationSeconds());
                 a[1] += 1;
             }
             List<Map<String, Object>> productDwellList = new ArrayList<>();
@@ -726,14 +733,14 @@ public class StatsController {
                 if (r.getReadAt() != null && r.getDurationSeconds() != null) {
                     hourCal.setTime(r.getReadAt());
                     int h = hourCal.get(Calendar.HOUR_OF_DAY);
-                    if (h >= 0 && h < 24) dwellByHour[h] += r.getDurationSeconds();
+                    if (h >= 0 && h < 24) dwellByHour[h] += saneDwell(r.getDurationSeconds());
                 }
             }
             for (ProductViewRecord r : productViews) {
                 if (r.getViewAt() != null && r.getDurationSeconds() != null) {
                     hourCal.setTime(r.getViewAt());
                     int h = hourCal.get(Calendar.HOUR_OF_DAY);
-                    if (h >= 0 && h < 24) dwellByHour[h] += r.getDurationSeconds();
+                    if (h >= 0 && h < 24) dwellByHour[h] += saneDwell(r.getDurationSeconds());
                 }
             }
             List<Long> dwellByHourList = new ArrayList<>();
@@ -761,7 +768,11 @@ public class StatsController {
             if (record == null || record.getProductId() == null) {
                 return Result.error("参数缺失");
             }
-            if (record.getDurationSeconds() == null) record.setDurationSeconds(0);
+            // 防御:埋点异常(如未 start 就 flush)会传出 epoch 量级的天文数字,入库前收敛到合理区间
+            int dwellSeconds = record.getDurationSeconds() == null ? 0 : record.getDurationSeconds();
+            if (dwellSeconds < 0) dwellSeconds = 0;
+            if (dwellSeconds > MAX_DWELL_SECONDS) dwellSeconds = MAX_DWELL_SECONDS;
+            record.setDurationSeconds(dwellSeconds);
             if (record.getUserId() == null) record.setUserId(0L);
             if (record.getSource() == null) record.setSource("miniprogram");
             record.setViewAt(new Date());

+ 41 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/task/TaskController.java

@@ -165,14 +165,30 @@ public class TaskController {
         }
     }
 
+    /**
+     * 审核任务(SC-P-11 任务审批完成:S-cfc-151 task.task.review)。
+     *
+     * <p>审批人身份作用域:{@code @RequestAttribute userId} 由 JwtInterceptor 注入;
+     * 有身份 → 走服务层 {@code reviewTask(taskId, reviewerId, dto)} 校验审批人归属家庭/家长
+     * (拒绝匿名与横向越权 TC-P-11-P);MockMvc/旧调用无身份参数时退化为既有 2 参服务入口
+     * (保持历史行为与既有契约测试绿)。</p>
+     */
     @Operation(summary = "审核任务")
     @PostMapping("/{id}/review")
     public Result<Boolean> reviewTask(@PathVariable Long id,
-                                      @RequestBody TaskReviewDTO dto) {
-        boolean success = taskService.reviewTask(id, dto);
+                                      @RequestBody TaskReviewDTO dto,
+                                      @RequestAttribute(value = "userId", required = false) Long userId) {
+        boolean success = userId != null
+                ? taskService.reviewTask(id, userId, dto)
+                : taskService.reviewTask(id, dto);
         return Result.success(success);
     }
 
+    /** 兼容旧 2 参直调(TaskControllerReviewTest 等既有契约直调),无身份上下文 */
+    public Result<Boolean> reviewTask(Long id, TaskReviewDTO dto) {
+        return reviewTask(id, dto, null);
+    }
+
   @Operation(summary = "获取任务历史")
   @PostMapping("/history")
   public Result<Page<Task>> getTaskHistory(@RequestBody Map<String, Object> params,
@@ -339,6 +355,29 @@ public class TaskController {
         return Result.success(success);
     }
 
+    /**
+     * 暂停重复任务模板(SC-P-12 task.frequency.config)。
+     *
+     * <p>暂停后 {@code RepeatTaskGenerator} 不再为其生成周期实例;重复任务在恢复后
+     * 按原周期锚点继续生成。仅模板任务(is_template=1)可暂停。</p>
+     */
+    @Operation(summary = "暂停周期任务")
+    @PostMapping("/{id}/pause")
+    public Result<Boolean> pauseTask(@PathVariable Long id,
+                                     @RequestAttribute("userId") Long userId) {
+        return Result.success(taskService.pauseTask(id, userId));
+    }
+
+    /**
+     * 恢复周期任务模板(SC-P-12 task.frequency.config):恢复后按原周期继续生成实例。
+     */
+    @Operation(summary = "恢复周期任务")
+    @PostMapping("/{id}/resume")
+    public Result<Boolean> resumeTask(@PathVariable Long id,
+                                      @RequestAttribute("userId") Long userId) {
+        return Result.success(taskService.resumeTask(id, userId));
+    }
+
     /**
      * 获取家庭成员可关联的任务列表(含所有状态),供创建任务时选择前置/后置任务
      */

+ 12 - 22
cfc-backend/src/main/java/com/etotem/cfc/controller/wish/WishController.java

@@ -20,10 +20,15 @@ import java.util.Map;
 @Tag(name = "心愿管理", description = "心愿创建、定价、兑换、兑现等接口")
 @RestController
 @RequestMapping("/api/wishes")
-public class WishController {
+public class WishController extends WishControllerSupport {
 
     @Resource
-    private WishService wishService;
+    protected WishService wishService;
+
+    @Override
+    protected WishService getWishService() {
+        return wishService;
+    }
 
     // ========== 创建心愿 ==========
 
@@ -209,28 +214,13 @@ public class WishController {
     public Result<List<WishDTO>> getWishes(
             @RequestAttribute("userId") Long userId,
             @RequestAttribute("role") String role,
+            @RequestBody(required = false) Map<String, Object> body,
             @RequestParam(required = false) Long memberId,
             @RequestParam(required = false) Long familyId,
-            @RequestParam(required = false) String status) {
-        try {
-            List<WishDTO> wishes;
-            if ("child".equals(role)) {
-                // 家庭成员只能看自己的心愿
-                wishes = wishService.getChildWishes(userId);
-            } else if (memberId != null) {
-                // 家庭主账号查看指定家庭成员的心愿
-                wishes = wishService.getChildWishes(memberId);
-            } else if (familyId != null) {
-                // 家庭主账号查看家庭所有心愿
-                wishes = wishService.getFamilyWishes(familyId);
-            } else {
-                return Result.error("请指定查询条件(memberId或familyId)");
-            }
-            return Result.success(wishes);
-        } catch (Exception e) {
-            log.error("获取心愿列表失败", e);
-            return Result.error("获取失败: " + e.getMessage());
-        }
+            @RequestParam(required = false) String status,
+            @RequestParam(required = false) Integer page,
+            @RequestParam(required = false) Integer size) {
+        return listWishes(userId, role, body, memberId, familyId, status, page, size);
     }
 
     @Operation(summary = "获取待处理列表(家庭主账号)")

+ 10 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/AssessmentHistoryItemDTO.java

@@ -1,5 +1,6 @@
 package com.etotem.cfc.dto;
 
+import com.etotem.cfc.common.constant.DimensionCodeConstants;
 import lombok.Data;
 
 import java.io.Serializable;
@@ -11,4 +12,13 @@ public class AssessmentHistoryItemDTO implements Serializable {
     private Date assessmentDate;
 
     private Integer overallScore;
+
+    /** 量纲标注:得分下界(共享口径 0,dimension-scoring-convention §1) */
+    private Integer scaleMin = DimensionCodeConstants.SCORE_MIN;
+
+    /** 量纲标注:得分上界(共享口径 100,dimension-scoring-convention §1) */
+    private Integer scaleMax = DimensionCodeConstants.SCORE_MAX;
+
+    /** 综合得分中文标签 */
+    private String overallLabel;
 }

+ 31 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/AssessmentResultDTO.java

@@ -1,5 +1,6 @@
 package com.etotem.cfc.dto;
 
+import com.etotem.cfc.common.constant.DimensionCodeConstants;
 import lombok.Data;
 
 import java.io.Serializable;
@@ -12,6 +13,36 @@ public class AssessmentResultDTO implements Serializable {
 
     private String childName;
 
+    /** 量纲标注:得分下界(共享口径 0,dimension-scoring-convention §1) */
+    private Integer scaleMin = DimensionCodeConstants.SCORE_MIN;
+
+    /** 量纲标注:得分上界(共享口径 100,dimension-scoring-convention §1) */
+    private Integer scaleMax = DimensionCodeConstants.SCORE_MAX;
+
+    /** 综合得分中文标签 */
+    private String overallLabel;
+
+    /** 注意力中文标签 */
+    private String attentionLabel;
+
+    /** 专注力中文标签 */
+    private String focusLabel;
+
+    /** 记忆力中文标签 */
+    private String memoryLabel;
+
+    /** 逻辑思维中文标签 */
+    private String logicLabel;
+
+    /** 感知能力中文标签 */
+    private String perceptionLabel;
+
+    /** 空间思维中文标签 */
+    private String spatialLabel;
+
+    /** 加工速度中文标签 */
+    private String processingSpeedLabel;
+
     private Integer overallScore;
 
     private Integer attentionScore;

+ 1 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ContactDTO.java

@@ -28,4 +28,5 @@ public class ContactDTO {
     private Date updatedAt;
     private Long familyMemberId;
     private String invitedStatus;
+    private Long groupId;
 }

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyMemberVO.java

@@ -105,4 +105,10 @@ public class FamilyMemberVO {
 
     /** 是否可被切换视角(仅不可登录成员 true,由 service 层根据 openid 判定) */
     private Boolean isSwitchable;
+
+    /** 在线状态:true=在线, false=离线(SC-P-04 成员列表展示在线状态) */
+    private Boolean online;
+
+    /** 最后活跃时间(ISO 8601,用于前端计算在线/离线) */
+    private java.util.Date lastActiveAt;
 }

+ 26 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ParsedReportResult.java

@@ -7,6 +7,32 @@ import java.util.List;
  */
 public class ParsedReportResult {
 
+    // ==================== 格式版本标记(guhe.l1.versionSplit / T8-L1-3) ====================
+
+    /**
+     * guhe_v2 新版标准报告格式标记(计划《2026-11-08-浠艾福平台程序修改计划》§2.1):
+     * 谷禾 2026-11 新版标准报告 = 旧 21 键打底 + 11 增量键 = 32 键;
+     * 判定链 {@code aidefansi → beijing → guhe_v2 → standard},旧三类路由不变。
+     */
+    public static final String FORMAT_GUHE_V2 = "guhe_v2";
+
+    /** 旧版谷禾报告键数(21 键):走原 v5 流程,禁止被 guhe_v2 提取器强套(T8/L1-3) */
+    public static final int LEGACY_KEYS_21 = 21;
+
+    /** guhe_v2 新版标准报告键数(32 键 = 21 键打底 + 11 增量键):走专用提取器,不落入 unknown→LLM 兜底(T8/L1-3) */
+    public static final int GUHE_V2_KEYS_32 = 32;
+
+    /**
+     * guhe_v2 完整 payload 键数边界(35 键):P0-3 关键决策——
+     * Python 主路径(extract_guhe_v2 / bun-report-parser v1.3.1)返回的完整 payload
+     * 直接作为 {@code payload_json} 落库,不裁剪。后续归因引擎 / 健康计划 / 前端展示
+     * 都从 payload 取,避免每加一个功能就重解析 PDF。
+     *
+     * <p>35 键 = 32 键格式识别口径 + 归因/自检等扩展键(能力键
+     * {@code health.report.guheV2Parse},方案 §三 P0-3 关键决策)。</p>
+     */
+    public static final int GUHE_V2_FULL_PAYLOAD_KEYS_35 = 35;
+
     // ==================== 汇总 ====================
 
     /** 健康总分 */

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ServiceRoleApplyDTO.java

@@ -17,4 +17,10 @@ public class ServiceRoleApplyDTO {
     private String district;
     private String street;
     private String addressDetail;
+    /**
+     * 团队邀请分享码(可选)。由 /pages/profile/service-role-apply?refCode=xxx 直达链接携带。
+     * 服务端据此反查邀请人写记录级归属 inviter_user_id;不接受前端直传 inviterUserId(防冒领)。
+     * 为空(用户从个人中心主动进入申请)时正常受理,inviter_user_id=null。
+     */
+    private String refCode;
 }

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/TaskReminderConfigDTO.java

@@ -25,6 +25,15 @@ public class TaskReminderConfigDTO implements Serializable {
 
     private List<String> completionPraiseChannels;
 
+    /** 日提醒开关 1=启用 0=停用(独立于 enabled,与 before/after 互不影响;默认 0) */
+    private Integer dailyEnabled;
+
+    /** 早提醒时间 HH:mm(默认 07:30) */
+    private String morningTime;
+
+    /** 晚总结时间 HH:mm(默认 21:00) */
+    private String eveningTime;
+
     private List<ChannelInfo> availableChannels;
 
     @Data

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/AssessmentMaterial.java

@@ -21,6 +21,9 @@ public class AssessmentMaterial implements Serializable {
 
     private String coverImage;
 
+    /** 测评类型码(类型载体:DAN 8 类 mind/wisdom/cognition/learning/behavior/career/campus/adolescent,对齐 DanReportUpload.DIM_* 字典) */
+    private String dimension;
+
     private String status;
 
     private Date createdAt;

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/Contact.java

@@ -52,4 +52,7 @@ public class Contact implements Serializable {
 
     /** 邀请加入家庭状态: none/invited/accepted/declined */
     private String invitedStatus;
+
+    /** 所属分组ID(SC-P-62 建分组 → 导入归组,能力键 contact.group.import) */
+    private Long groupId;
 }

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CouponGiftTransfer.java

@@ -47,6 +47,12 @@ public class CouponGiftTransfer implements Serializable {
     /** GIFTED=已赠送(可撤回) / USED=已被接收方使用 / REVOKED=已撤回 */
     private String status;
 
+    /** 分享令牌:分享转赠(claimMethod=SHARE)领取时回写的 coupon_share.share_token;定向转赠为 NULL */
+    private String shareToken;
+
+    /** 领取方式:DIRECT=定向转赠 / SHARE=分享转赠(存量行默认 DIRECT,兼容历史数据) */
+    private String claimMethod;
+
     /** 赠送留言 */
     private String remark;
 

+ 2 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/DietRecommendation.java

@@ -22,4 +22,6 @@ public class DietRecommendation implements Serializable {
     private Integer version;
     private Date createdAt;
     private Date updatedAt;
+    /** 视角隔离键(迁移466):member:&lt;id&gt; / family / NULL=存量;后端视为不透明字符串,只做 .eq 匹配。 */
+    private String viewKey;
 }

+ 5 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/EnergyBalance.java

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.Version;
 import com.fasterxml.jackson.annotation.JsonProperty;
 import lombok.Data;
 
@@ -34,5 +35,9 @@ public class EnergyBalance implements Serializable {
     /** 累计消耗 */
     private Integer totalSpent;
 
+    /** 乐观锁版本号(并发原子加防丢失更新,SC-X-21 energy.ledger.guard) */
+    @Version
+    private Integer version;
+
     private Date updatedAt;
 }

+ 11 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/EnergyLog.java

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonProperty;
 import lombok.Data;
 
@@ -46,5 +47,15 @@ public class EnergyLog implements Serializable {
     /** 描述 */
     private String description;
 
+    /** 展示字段(不入库):来源可读名(SC-P-18 能量流水查看:task→完成任务 / health_checkin→健康打卡 / assessment→测评,未映射回退原始码) */
+    @TableField(exist = false)
+    private String sourceName;
+
+    /** 展示字段(不入库):维度代码(body/mind/wisdom/action/wealth,供前端按维度着色/筛选,无需再查维度表) */
+    @TableField(exist = false)
+    private String dimensionCode;
+
+    /** 创建时间(ISO 8601 序列化,与项目时间显示规范一致) */
+    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
     private Date createdAt;
 }

+ 11 - 3
cfc-backend/src/main/java/com/etotem/cfc/entity/FamilyFoodOverview.java

@@ -9,8 +9,10 @@ import java.io.Serializable;
 import java.util.Date;
 
 /**
- * 家庭×食材 持久化最小值总览(T28)。
- * 口径:家庭成员对该项食材"最新推荐指数"的最小值(最保守值),由
+ * 家庭×食材 持久化总览(T28 建表,迁移465 改分段聚合口径)。
+ * 口径:同一食材,只要有一名成员推荐指数 &lt; 0,overviewScore 取全员最低值(风险优先);
+ * 全员 &gt;= 0 时取平均值(四舍五入取整,0 分计入平均)。minIndexScore 始终保存真实成员最小值,
+ * 供诊断与旧版客户端兼容,语义不变。由
  * {@link com.etotem.cfc.service.FamilyFoodOverviewService#recalculate(Long)} 全量覆盖维护。
  * memberScores 与项目 JSON 列既有惯例一致(如 diet_recommendations.menuJson)以字符串落库,
  * 内容为 JSON 数组 [{"userId":1018,"nickname":"小宇宙","score":-18}]
@@ -34,9 +36,15 @@ public class FamilyFoodOverview implements Serializable {
     /** 分类快照 */
     private String category;
 
-    /** 家庭成员该项食材最新推荐指数的最小值 */
+    /** 家庭成员该项食材最新推荐指数的最小值(诊断兼容字段,语义不变,非展示值) */
     private Integer minIndexScore;
 
+    /** 家庭总览展示值:有成员 &lt; 0 取最低值,否则取平均值(四舍五入) */
+    private Integer overviewScore;
+
+    /** 本次聚合规则:MIN_NEGATIVE(负值优先取最低)/ AVG_POSITIVE(全员非负取平均) */
+    private String aggregateRule;
+
     /** 参与计算的成员数(有该食材记录的) */
     private Integer memberCount;
 

+ 10 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/Food.java

@@ -1,6 +1,7 @@
 package com.etotem.cfc.entity;
 
 import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.fasterxml.jackson.annotation.JsonAlias;
@@ -43,6 +44,15 @@ public class Food implements Serializable {
     private Integer sortOrder;
     /** 饮食类型: none/清真/halal/素食/vegan */
     private String dietType;
+
+    /** 健康问卷调整结果: normal/blocked/warning/boost(D1-D8 判定,瞬态不入库,供 getCurrentFoodsAsFoodList 透传) */
+    @TableField(exist = false)
+    private String adjustment;
+
+    /** 调整命中原因文本(多条用「;」连接,瞬态不入库) */
+    @TableField(exist = false)
+    private String adjustmentReason;
+
     private Date createdAt;
     private Date updatedAt;
 }

+ 5 - 1
cfc-backend/src/main/java/com/etotem/cfc/entity/GrowthPlan.java

@@ -34,7 +34,7 @@ public class GrowthPlan implements Serializable {
 
     private Integer durationMonths;  // 规划周期(月)
 
-    private String status;  // draft/active/completed/expired
+    private String status;  // 状态机(SC-P-44/45,能力键 plan.confirm.submit):generated(待确认)→reviewed(待激活)→active(生效中);另支持 draft/completed/expired
 
     private Date startDate;
 
@@ -42,6 +42,10 @@ public class GrowthPlan implements Serializable {
 
     private Integer reviewCount;  // 已复盘次数
 
+    private Date draftExpiresAt;  // 草稿有效期(SC-P-81 草稿保存/恢复,能力键 plan.draft.save;超期判定『草稿已失效』)
+
+    private Integer draftVersion;  // 草稿版本号(并发存两版草稿:后者覆盖且提示冲突)
+
     private Date createdAt;
 
     private Date updatedAt;

+ 2 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/MembershipLevel.java

@@ -49,6 +49,8 @@ public class MembershipLevel implements Serializable {
 
     private Integer levelOrder;  // 级别数字(越大级别越高): FREE=1 BASIC=2 FAMILY=3 PREMIUM=4 LIFETIME=5; PROVIDER=1(非会员,服务商独立角色)
 
+    private Integer costPrice;  // 会员成本价(分):送会员商品计算P点时扣除的商品外成本
+
     private Date createdAt;
 
     private Date updatedAt;

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/PackageOrder.java

@@ -19,6 +19,9 @@ public class PackageOrder implements Serializable {
 
     private Long userId;          // 购买者用户ID
 
+    /** 小程序 appid(订单数据隔离维度;下单时写入,默认=现 default app 的 appid) */
+    private String appid;
+
     private Long familyId;        // 家庭ID
 
     private Long packageId;       // 任务模板ID

+ 5 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ProductDimensionConfig.java

@@ -3,6 +3,7 @@ package com.etotem.cfc.entity;
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.Version;
 import lombok.Data;
 
 import java.io.Serializable;
@@ -46,4 +47,8 @@ public class ProductDimensionConfig implements Serializable {
     private Date createdAt;
 
     private Date updatedAt;
+
+    /** 乐观锁版本号(并发改同配置不互相覆盖,TC-A-25-E admin.dimension.config) */
+    @Version
+    private Integer version;
 }

+ 8 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ProductOrder.java

@@ -21,6 +21,8 @@ public class ProductOrder implements Serializable {
     private String productType;
     private Long skuId;
     private Long buyerId;
+    /** 小程序 appid(订单数据隔离维度;下单时写入,默认=现 default app 的 appid) */
+    private String appid;
     private Long familyId;
     private Integer quantity;
     private Integer unitPrice;    // 单价(分)
@@ -47,6 +49,8 @@ public class ProductOrder implements Serializable {
     private String refundReason;       // 退款原因
     private Integer refundAmount;      // 退款金额(分)
     private Date refundTime;           // 退款时间
+    private String refundBeforeStatus;          // 退款前订单状态(售后取消回滚用)
+    private Integer refundBeforeRefundStatus;   // 退款前退款状态(售后取消回滚用)
     // 供应商销售字段
     private Long supplySystemId;       // 供应商体系ID
     private Long supplierId;           // 供应商ID
@@ -79,6 +83,8 @@ public class ProductOrder implements Serializable {
     private String fulfillStatus;             // 履约状态: pending/confirmed_by_vendor/received_by_user
     private Date fulfillConfirmedAt;          // 供应商确认时间
     private Date receivedAt;                   // 用户确认收货时间
+    private Date shippedAt;                    // 发货时间(超时自动完成/收货提醒的基准时间,P0-B)
+    private Date receiptRemindAt;              // 收货提醒推送时间(第9天推送成功后写,幂等防重复,P0-B)
 
     private Date createdAt;
     private Date updatedAt;
@@ -122,6 +128,8 @@ public class ProductOrder implements Serializable {
     public void setFulfillStatus(String fulfillStatus) { this.fulfillStatus = fulfillStatus; }
     public void setFulfillConfirmedAt(Date fulfillConfirmedAt) { this.fulfillConfirmedAt = fulfillConfirmedAt; }
     public void setReceivedAt(Date receivedAt) { this.receivedAt = receivedAt; }
+    public void setShippedAt(Date shippedAt) { this.shippedAt = shippedAt; }
+    public void setReceiptRemindAt(Date receiptRemindAt) { this.receiptRemindAt = receiptRemindAt; }
     public Date getPaidAt() { return paidAt; }
     public Date getCreatedAt() { return createdAt; }
 }

+ 2 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ServiceRoleApplication.java

@@ -13,6 +13,8 @@ public class ServiceRoleApplication {
     @TableId(type = IdType.AUTO)
     private Long id;
     private Long userId;
+    /** 记录级归属:本条申请挂在哪个邀请人名下(来自分享 refCode 服务端反查,不触发分销副作用) */
+    private Long inviterUserId;
     private String roles;
     private String idCard;
     private String idCardImages;

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/Task.java

@@ -81,6 +81,18 @@ private String frequency;
 // 周期内最多完成次数
 private Integer maxFrequency;
 
+/** SC-P-12 task.frequency.config: 自定义周期单位(DAY/WEEK/MONTH),frequency=custom 时有效 */
+private String frequencyUnit;
+
+/** SC-P-12 task.frequency.config: 自定义周期间隔(每 N 个 frequencyUnit 生成一次实例) */
+private Integer frequencyInterval;
+
+/** SC-P-12 task.frequency.config: 自定义周期锚点(按锚点推进周期,跨月/跨年不漂移) */
+private Date cycleAnchor;
+
+/** SC-P-12 task.frequency.config: 暂停标记(1=暂停,RepeatTaskGenerator 不再生成实例) */
+private Integer isPaused;
+
 // 完成方式(多选,JSON格式: ["checkin","text","image"])
 private String completeTypes;
 

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/TaskReminderConfig.java

@@ -38,5 +38,14 @@ public class TaskReminderConfig implements Serializable {
     /** 完成表扬渠道(逗号分隔): in_app/wechat/sms/phone/email */
     private String completionPraiseChannels;
 
+    /** 日提醒开关 1=启用 0=停用(独立于 enabled,与 before/after 两档互不影响,可叠加;默认关闭) */
+    private Integer dailyEnabled;
+
+    /** 早提醒时间 HH:mm(默认 07:30,用户可配) */
+    private String morningTime;
+
+    /** 晚总结时间 HH:mm(默认 21:00,用户可配) */
+    private String eveningTime;
+
     private Date updatedAt;
 }

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/TeacherMessage.java

@@ -34,4 +34,7 @@ public class TeacherMessage implements Serializable {
 
     @TableField(exist = false)
     private String teacherName;   // 规划师昵称(回显用,不入库)
+
+    @TableField(exist = false)
+    private String parentName;    // 家庭主账号昵称(回显用,不入库)
 }

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/User.java

@@ -22,6 +22,9 @@ public class User implements Serializable {
 
     private String openid;
 
+    /** 小程序 appid(多小程序数据隔离维度;默认=现 default app 的 appid) */
+    private String appid;
+
     private String unionid;
 
     private Long familyId;
@@ -185,4 +188,15 @@ public class User implements Serializable {
     @TableLogic
     @TableField("deleted")
     private Integer deleted;
+
+    /**
+     * 注销冷静期状态(auth.account.deactivate · SC-P-71 两阶段注销):
+     * PENDING=已申请待确认(冷静期内可撤回)/ DONE=最终注销已执行;NULL=未申请过注销。
+     */
+    @TableField("deactivate_status")
+    private String deactivateStatus;
+
+    /** 注销申请时间(进入冷静期;冷静期满后方可 confirmDeactivate 执行最终数据归档/删除) */
+    @TableField("deactivate_apply_at")
+    private Date deactivateApplyAt;
 }

+ 15 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/CouponMapper.java

@@ -3,7 +3,22 @@ package com.etotem.cfc.mapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.etotem.cfc.entity.Coupon;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Update;
 
 @Mapper
 public interface CouponMapper extends BaseMapper<Coupon> {
+
+    /**
+     * claim 侧原子扣减(DB 并发防线,S-cfc-293 AC-3):used_count +1 且不超发
+     * (total_count 为空视为不限量,否则 used_count < total_count 才扣减)。
+     * <p>与 claim() 的 selectById + updateById 路径互补:并发领取同一券时,库存为 0 的
+     * 拦截由原子 SQL 兜底,返回 0 表示库存已满/券不存在(不应再发放)。</p>
+     *
+     * @param couponId 券模板ID(coupon.id)
+     * @return 受影响行数:1=扣减成功;0=库存已满/券不存在(并发下不超发)
+     */
+    @Update("UPDATE coupon SET used_count = IFNULL(used_count, 0) + 1 " +
+            "WHERE id = #{couponId} AND (total_count IS NULL OR used_count < total_count)")
+    int incrementUsedCountIfAvailable(@Param("couponId") Long couponId);
 }

+ 1 - 1
cfc-backend/src/main/java/com/etotem/cfc/mapper/GameRecordMapper.java

@@ -17,7 +17,7 @@ public interface GameRecordMapper extends BaseMapper<GameRecord> {
             "FROM game_records WHERE child_id = #{childId} GROUP BY game_code")
     List<Map<String, Object>> selectBestScoresByChild(@Param("childId") Long memberId);
 
-    @Select("SELECT gr.*, fm.nickname as child_name " +
+    @Select("SELECT gr.*, fm.nickname as child_name, fm.family_id AS family_id " +
             "FROM game_records gr LEFT JOIN family_members fm ON gr.child_id = fm.id " +
             "WHERE gr.game_code = #{gameCode} ORDER BY gr.score DESC LIMIT #{limit}")
     List<Map<String, Object>> selectLeaderboard(@Param("gameCode") String gameCode,

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

@@ -107,6 +107,9 @@ public class AIService {
 
     /**
      * 发送聊天消息: 统一走 Python LangGraph
+     * <p>429/401 类外部服务错误由 {@code AiGateway.chat} 向上抛出(契约
+     * langgraph.intent.errorPropagate,不得吞 null 伪装成普通失败);其余失败
+     * (熔断/超时/解析异常)仍走 emptyMap 兜底。
      */
     public Map<String, Object> sendMessage(String query, String userId,
                                            String conversationId,

+ 225 - 39
cfc-backend/src/main/java/com/etotem/cfc/service/AccountCleanupService.java

@@ -1,5 +1,6 @@
 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;
@@ -9,8 +10,10 @@ 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;
 
 /**
@@ -45,14 +48,23 @@ public class AccountCleanupService {
     @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<>();
 
-        // 1. 查询用户
         User user = userMapper.selectById(userId);
         if (user == null) {
             result.put("canDeactivate", false);
@@ -60,7 +72,135 @@ public class AccountCleanupService {
             return result;
         }
 
-        // 2. 检查是否有未完成订单
+        // 进行中订单 / 未结清测评门禁(契约边界,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>()
@@ -68,31 +208,23 @@ public class AccountCleanupService {
                             .eq(PaymentOrder::getStatus, "pending")
             );
             if (pendingOrderCount > 0) {
-                result.put("canDeactivate", false);
-                result.put("message", "您有未完成的订单,请先处理后再注销账号");
-                return result;
+                return "您有未完成的订单,请先处理后再注销账号";
             }
         }
-
         long pendingAssessmentCount = assessmentOrderMapper.selectCount(
                 new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<AssessmentOrder>()
-                        .eq(AssessmentOrder::getUserId, userId)
+                        .eq(AssessmentOrder::getUserId, user.getId())
                         .eq(AssessmentOrder::getStatus, "pending")
         );
         if (pendingAssessmentCount > 0) {
-            result.put("canDeactivate", false);
-            result.put("message", "您有未完成的测评,请先处理后再注销账号");
-            return result;
-        }
-
-        // 3. 匿名化用户数据
-        if (user == null) {
-            result.put("canDeactivate", false);
-            result.put("message", "用户不存在");
-            return result;
+            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)
         );
@@ -110,10 +242,10 @@ public class AccountCleanupService {
         user.setUpdatedAt(new Date());
         userMapper.updateById(user);
 
-        // 3. 匿名化关联的FamilyMember记录
+        // 匿名化关联的 FamilyMember 记录
         familyMemberMapper.selectList(
                 new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FamilyMember>()
-                        .eq(FamilyMember::getUserId, userId)
+                        .eq(FamilyMember::getUserId, user.getId())
         ).forEach(member -> {
             member.setNickname("已注销");
             member.setPhone("");
@@ -122,51 +254,73 @@ public class AccountCleanupService {
             familyMemberMapper.updateById(member);
         });
 
-        // 4. 匿名化关联的ChatMessage记录
+        // 匿名化关联的 ChatMessage 记录(通过 inputsJson 包含 userId 做轻量过滤)
         chatMessageMapper.selectList(
                 new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ChatMessage>()
         ).stream()
-        .filter(msg -> {
-            // 尝试解析inputsJson找到userId,或通过conversation关联
-            return msg.getInputsJson() != null && msg.getInputsJson().contains("\"" + userId + "\"");
-        })
+        .filter(msg -> msg.getInputsJson() != null && msg.getInputsJson().contains("\"" + user.getId() + "\""))
         .forEach(msg -> {
             msg.setContent("[该用户已注销]");
             chatMessageMapper.updateById(msg);
         });
-
-        log.info("账号已注销并匿名化: userId={}", userId);
-        result.put("canDeactivate", true);
-        result.put("message", "账号已成功注销,相关数据已匿名化处理");
-        return result;
     }
 
     /**
-     * 导出用户数据
+     * 导出用户数据(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", user.getPhone());
-        userInfo.put("realName", user.getRealName());
+        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 表)
-        data.put("children", familyMemberMapper.selectList(
+        // 家庭成员信息(已迁移至 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(
@@ -186,7 +340,39 @@ public class AccountCleanupService {
                         .eq(Task::getCreatorId, userId)
         ));
 
-        log.info("用户数据导出: userId={}", 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;
     }
 }

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

@@ -183,6 +183,11 @@ public class ActivityService extends ServiceImpl<ActivityMapper, Activity> {
     }
 
     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);
@@ -199,6 +204,19 @@ public class ActivityService extends ServiceImpl<ActivityMapper, Activity> {
         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())));

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

@@ -52,6 +52,9 @@ public class AfterSalesService {
         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());
@@ -139,4 +142,58 @@ public class AfterSalesService {
         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);
+    }
 }

+ 58 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java

@@ -10,9 +10,11 @@ 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.atomic.AtomicInteger;
@@ -119,6 +121,24 @@ public class AiGateway {
         }
     }
 
+    /**
+     * 判断 {@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)
      */
@@ -173,7 +193,11 @@ public class AiGateway {
     }
 
     /**
-     * 调用 Python ChatAgent, 失败时返回 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) {
@@ -223,6 +247,15 @@ public class AiGateway {
                 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();
@@ -281,6 +314,15 @@ public class AiGateway {
                 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();
@@ -580,9 +622,18 @@ public class AiGateway {
     }
 
     /**
-     * 生成菜单
+     * 生成菜单(兼容旧调用方:不传 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) {
         if (!enabled || isCircuitOpen()) return null;
 
         try {
@@ -594,6 +645,11 @@ public class AiGateway {
             body.put("selected_foods", sanitizedFoods);
             body.put("participants", sanitizedParticipants);
             body.put("date", date);
+            if (dishCount != null) {
+                body.put("dish_count", dishCount.intValue());
+            } else {
+                body.putNull("dish_count");
+            }
             
             HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
             String url = baseUrl + "/api/v1/menu/generate";

+ 32 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/ArticleService.java

@@ -121,6 +121,9 @@ public class ArticleService {
                                         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);
@@ -157,6 +160,13 @@ public class ArticleService {
 
         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);
@@ -231,6 +241,9 @@ public class ArticleService {
         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));
@@ -247,6 +260,12 @@ public class ArticleService {
         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);
@@ -438,6 +457,9 @@ public class ArticleService {
         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;
     }
@@ -904,8 +926,16 @@ public class ArticleService {
         if (article == null) return;
         article.setStatus(status);
         article.setUpdatedAt(new Date());
-        if ("published".equals(status) && article.getPublishedAt() == null) {
-            article.setPublishedAt(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);
         // 发布时若标签为空则异步自动生成

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

@@ -24,6 +24,24 @@ public class AssessmentAppointmentService extends ServiceImpl<AssessmentAppointm
     @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)
@@ -57,6 +75,9 @@ public class AssessmentAppointmentService extends ServiceImpl<AssessmentAppointm
     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;
@@ -68,6 +89,9 @@ public class AssessmentAppointmentService extends ServiceImpl<AssessmentAppointm
     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());
@@ -88,11 +112,31 @@ public class AssessmentAppointmentService extends ServiceImpl<AssessmentAppointm
     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);

+ 26 - 8
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentOrderService.java

@@ -35,7 +35,7 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
     private CfCommissionService cfCommissionService;
 
     @Resource
-    private ProfitPoolService profitPoolService;
+    private AssessmentQuotaService assessmentQuotaService;
 
     @Resource
     private UserMapper userMapper;
@@ -73,6 +73,11 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
         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);
@@ -85,17 +90,25 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
             cfCommissionService.settle(order.getId(), "assessment", order.getUserId(),
                     buyerFamilyId,
                     order.getActualPrice() != null ? order.getActualPrice().intValue() : 0, null);
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "assessment", null,
-                        (long) (order.getActualPrice() != null ? order.getActualPrice().intValue() : 0), 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=assessment, 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);
@@ -185,6 +198,11 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
         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 {

+ 43 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentQuotaService.java

@@ -1,6 +1,7 @@
 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;
@@ -26,13 +27,49 @@ public class AssessmentQuotaService {
 
     @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(order.getFamilyId() != null ? order.getFamilyId() : 0L);
-        quota.setMemberId(null); // 不绑定具体家庭成员
-        quota.setProductOrderId(order.getId());
-        quota.setProductId(order.getProductId());
-        quota.setProductName(order.getProductName());
+        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();
@@ -43,8 +80,7 @@ public class AssessmentQuotaService {
         quota.setCreatedAt(now);
         quota.setUpdatedAt(now);
         mapper.insert(quota);
-        log.info("已为订单{}发放测评额度: quotaNo={}, familyId={}, 次数={}",
-                order.getOrderNo(), quota.getQuotaNo(), quota.getFamilyId(), quota.getTotalSessions());
+        return quota;
     }
 
     @Transactional

+ 159 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentService.java

@@ -8,7 +8,9 @@ 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;
@@ -37,6 +39,17 @@ import com.etotem.cfc.util.SortUtil;
 @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;
 
@@ -73,6 +86,14 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
     @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");
@@ -87,6 +108,26 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
         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);
@@ -186,7 +227,31 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
         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);
@@ -226,13 +291,46 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
     }
 
     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());
         }
-        danAssessmentResultMapper.insert(result);
+
+        // 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())) {
@@ -283,6 +381,32 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
             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;
     }
 
@@ -358,4 +482,38 @@ public class AssessmentService extends ServiceImpl<AssessmentMaterialMapper, Ass
         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);
+    }
 }

+ 33 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/BadgeService.java

@@ -73,8 +73,27 @@ public class BadgeService {
         badgeMapper.updateById(badge);
     }
 
-    @Transactional
+    /**
+     * 删除勋章定义(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);
     }
 
@@ -232,6 +251,18 @@ List<Map<String, Object>> categoryStats = memberBadgeMapper.selectCategoryStats(
     }
 
     public List<Map<String, Object>> getFamilyRanking(Long familyId) {
-        return memberBadgeMapper.selectFamilyRanking(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;
     }
 }

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

@@ -639,6 +639,8 @@ public class BeijingNutritionService {
         Map<Long, List<String>> allergiesMap = new HashMap<>();
         Map<Long, List<String>> avoidMap = new HashMap<>();
         Map<Long, Map<String, String>> bacteriaStatusMap = new HashMap<>();
+        // A5:参与者宗教饮食合并集(任一参与者不匹配即剔除,none/空不拦)
+        Set<String> allReligiousDiets = new HashSet<>();
 
         for (Long memberId : participantIds) {
             LambdaQueryWrapper<com.etotem.cfc.entity.DietPreferences> prefWrapper = new LambdaQueryWrapper<>();
@@ -663,6 +665,10 @@ public class BeijingNutritionService {
                         log.warn("解析 absoluteAvoid 失败: {}", e.getMessage());
                     }
                 }
+                if (prefs.getReligiousDiet() != null && !prefs.getReligiousDiet().trim().isEmpty()
+                        && !"none".equalsIgnoreCase(prefs.getReligiousDiet().trim())) {
+                    allReligiousDiets.add(prefs.getReligiousDiet().trim());
+                }
             }
 
             LambdaQueryWrapper<HealthReport> reportWrapper = new LambdaQueryWrapper<>();
@@ -713,6 +719,20 @@ public class BeijingNutritionService {
             if (allAllergies.contains(foodName) || allAvoid.contains(foodName)) continue;
             if (healthFilterService.isFoodHardBlocked(foodName, mergedHealthProfile)) continue;
 
+            // A5 用药维度(D2):食物名/food.allergens 命中药物交互 → risk1 剔除、risk2/3 提示
+            List<String> drugReasons = healthFilterService.checkDrugInteractions(mergedHealthProfile, food);
+            boolean drugHardBlock = false;
+            for (String reason : drugReasons) {
+                if (reason != null && reason.contains("硬拦截")) {
+                    drugHardBlock = true;
+                    break;
+                }
+            }
+            if (drugHardBlock) continue;
+
+            // A5 宗教饮食过滤(D5):food.dietType vs 任一参与者 religiousDiet 不匹配即剔除;none/空不受影响
+            if (isReligiousDietMismatch(food, allReligiousDiets)) continue;
+
             BacteriaFoodMapping.FoodAdjustment adj = adjustments.get(foodName);
             double bacteriaScore = scoreBacteria(adj != null ? adj.getDirection() : null, food.getScore());
             double nutritionScore = scoreNutrition(food.getCategory(), food);
@@ -818,6 +838,38 @@ public class BeijingNutritionService {
         }
         return recommendations;
     }
+
+    /**
+     * A5 宗教饮食过滤(D5):food.dietType 与任一参与者 religiousDiet 不匹配即视为不兼容。
+     * <p>语义:none/空 dietType 表示未标注宗教属性的通用食材,不拦;素食类宗教饮食仅接受
+     * 素食/vegan/vegetarian;清真类接受 清真/halal 以及素食子集;未知类型按字面匹配。</p>
+     */
+    private boolean isReligiousDietMismatch(Food food, Set<String> religiousDiets) {
+        if (religiousDiets == null || religiousDiets.isEmpty() || food == null) return false;
+        String dietType = food.getDietType() == null ? "" : food.getDietType().trim();
+        if (dietType.isEmpty() || "none".equalsIgnoreCase(dietType)) return false;
+        for (String religious : religiousDiets) {
+            if (religious == null || religious.trim().isEmpty()) continue;
+            if (!isReligiousCompatibleDietType(religious.trim(), dietType)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 判断食材 dietType 与某个宗教饮食偏好在语义上是否兼容(兼容返回 true) */
+    private boolean isReligiousCompatibleDietType(String religious, String dietType) {
+        if (religious.contains("素")) {
+            return dietType.contains("素") || "vegan".equalsIgnoreCase(dietType)
+                    || "vegetarian".equalsIgnoreCase(dietType) || "veg".equalsIgnoreCase(dietType);
+        }
+        if (religious.contains("清") || "halal".equalsIgnoreCase(religious)) {
+            return dietType.contains("清") || "halal".equalsIgnoreCase(dietType)
+                    || dietType.contains("素") || "vegan".equalsIgnoreCase(dietType)
+                    || "vegetarian".equalsIgnoreCase(dietType);
+        }
+        return religious.equalsIgnoreCase(dietType);
+    }
     
     // ============================================================
     // 均衡化评分引擎

+ 5 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/CfBalanceService.java

@@ -102,4 +102,9 @@ public interface CfBalanceService {
      * @return 发放结果(未发放时 earned=false 且带跳过原因)
      */
     CfEarnResult earnByRule(Long memberId, String ruleCode, Long refId, Map<String, Object> ctx);
+
+    /**
+     * 家庭 CF 汇总:成员余额列表 + 合计 + 近 N 条日志(分页,所有成员合并后按时间倒序)。
+     */
+    Map<String, Object> getCfSummary(Long familyId, long page, long size);
 }

+ 534 - 3
cfc-backend/src/main/java/com/etotem/cfc/service/CfCommissionService.java

@@ -3,21 +3,32 @@ package com.etotem.cfc.service;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.config.ConfigService;
 import com.etotem.cfc.constant.CfConfigKeys;
+import com.etotem.cfc.context.MiniAppContextHolder;
 import com.etotem.cfc.dto.CfEarnResult;
 import com.etotem.cfc.entity.CfDirectSalesTier;
 import com.etotem.cfc.entity.CfEarnRule;
 import com.etotem.cfc.entity.CfIndirectSalesTier;
+import com.etotem.cfc.entity.CfPlatformRevenueLog;
+import com.etotem.cfc.entity.CfTeamPoolOrder;
+import com.etotem.cfc.entity.CfTeamPoolShare;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.OctopusEffectKeyPerson;
 import com.etotem.cfc.entity.OctopusEffectRecord;
 import com.etotem.cfc.entity.OctopusKeyPerson;
 import com.etotem.cfc.entity.PpointConsumptionLog;
 import com.etotem.cfc.entity.OrderItem;
+import com.etotem.cfc.entity.MembershipLevel;
 import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductGiftRule;
 import com.etotem.cfc.entity.ProductOrder;
 import com.etotem.cfc.entity.ReferralTree;
 import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CfPlatformRevenueLogMapper;
+import com.etotem.cfc.mapper.CfTeamPoolOrderMapper;
+import com.etotem.cfc.mapper.CfTeamPoolShareMapper;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.MembershipLevelMapper;
+import com.etotem.cfc.mapper.ProductGiftRuleMapper;
 import com.etotem.cfc.mapper.OctopusEffectKeyPersonMapper;
 import com.etotem.cfc.mapper.OctopusEffectRecordMapper;
 import com.etotem.cfc.mapper.OctopusKeyPersonMapper;
@@ -36,6 +47,8 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
 import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -77,12 +90,18 @@ public class CfCommissionService {
     /** 间接销售奖规则编码(cf_earn_rule.code) */
     public static final String RULE_INDIRECT_SALES = "F03b";
 
+    /** 团队分润池规则编码(cf_earn_rule.code,分润 v2 §3.1:成本 × T% 池内瓜分) */
+    public static final String RULE_TEAM_POOL = "F03c";
+
     /** F03a 团队口径最大层级(§4.1.1:团队 8 层以内) */
     private static final int TEAM_DEPTH = 8;
 
     /** 销售奖发放的参与层级数量(直接奖 L1 + 间接奖 L2) */
     private static final int SALES_AWARD_LEVELS = 2;
 
+    /** R0 平台抽成默认费率(bps,1000 = 10%,设计 §1.1) */
+    public static final int TAKE_BPS = 1000;
+
     @Resource
     private ReferralTreeMapper referralTreeMapper;
     @Resource
@@ -100,6 +119,10 @@ public class CfCommissionService {
     @Resource
     private ProductOrderMapper productOrderMapper;
     @Resource
+    private ProductGiftRuleMapper productGiftRuleMapper;
+    @Resource
+    private MembershipLevelMapper membershipLevelMapper;
+    @Resource
     private OctopusKeyPersonMapper octopusKeyPersonMapper;
     @Resource
     private OctopusEffectRecordMapper octopusEffectRecordMapper;
@@ -117,6 +140,14 @@ public class CfCommissionService {
     private ConfigService configService;
     @Resource
     private ObjectMapper objectMapper;
+    @Resource
+    private CfPlatformRevenueLogMapper cfPlatformRevenueLogMapper;
+    @Resource
+    private CfTeamPoolOrderMapper cfTeamPoolOrderMapper;
+    @Resource
+    private CfTeamPoolShareMapper cfTeamPoolShareMapper;
+    @Resource
+    private TeamShareConfigService teamShareConfigService;
 
     /**
      * 通用分佣(双返):当前人 + 推荐人。
@@ -143,6 +174,8 @@ public class CfCommissionService {
         // 推荐人分润(两级销售奖)
         distributeToReferrers(orderId, orderType, buyerUserId, buyerFamilyId,
                 orderAmountCent, paidAmountCent, productId);
+        // ⑤ 团队池建池(分润 v2:成本 × T%,从成本侧切出、不占 base;uk_order 幂等)
+        settleTeamPool(orderId, orderType, buyerUserId, buyerFamilyId, paidAmountCent, productId);
     }
 
     /**
@@ -168,6 +201,8 @@ public class CfCommissionService {
         earnBuyerCf(orderId, orderType, buyerUserId, paidAmountCent);
         distributeToReferrers(orderId, orderType, buyerUserId, buyerFamilyId,
                 orderAmountCent, paidAmountCent, null);
+        // ⑤ 团队池建池(会员/订阅/测评等非商品订单:成本 = 实付 × non_goods_cost_rate)
+        settleTeamPool(orderId, orderType, buyerUserId, buyerFamilyId, paidAmountCent, null);
     }
 
     /**
@@ -181,6 +216,475 @@ public class CfCommissionService {
         }
     }
 
+    /**
+     * R0 平台抽成记账(设计 §3.1 / §6-T03,新增)。
+     *
+     * <p>按 {@code floor(实付 × TAKE_BPS / 10000)} 写入 {@code cf_platform_revenue_log},
+     * 唯一键 {@code uk_order(order_type, order_id)} 幂等;实付为 null 时回退 orderAmountCent。
+     * 费率优先读 {@code cf.platform.take_rate_bps} 配置({@link CfConfigKeys#PLATFORM_TAKE_RATE_BPS}),
+     * 配置缺失时用常量 {@link #TAKE_BPS} 兜底。</p>
+     *
+     * @param orderId        订单ID
+     * @param orderType      订单类型
+     * @param paidAmountCent 实付金额(分),null 时回退 orderAmountCent
+     * @param orderAmountCent 订单金额(分),实付为 null 时的回退值
+     * @return 实际抽成金额(分);入参全 null 或 ≤0 时返回 0
+     */
+    public int settlePlatformTake(Long orderId, String orderType,
+                                  Integer paidAmountCent, Integer orderAmountCent) {
+        int amount = paidAmountCent != null ? paidAmountCent
+                : (orderAmountCent != null ? orderAmountCent : 0);
+        if (amount <= 0) return 0;
+
+        int takeBps;
+        try {
+            takeBps = configService.getIntConfig(CfConfigKeys.PLATFORM_TAKE_RATE_BPS, TAKE_BPS);
+        } catch (Exception e) {
+            takeBps = TAKE_BPS;
+        }
+        int r0 = amount * takeBps / 10000;
+
+        CfPlatformRevenueLog entity = new CfPlatformRevenueLog();
+        entity.setOrderId(orderId);
+        entity.setOrderType(orderType);
+        entity.setAmountCent(r0);
+        entity.setTakeBps(takeBps);
+        entity.setRemark("R0平台抽成:" + orderType);
+        entity.setCreatedAt(new Date());
+        try {
+            cfPlatformRevenueLogMapper.insert(entity);
+            log.info("R0平台抽成记账: orderType={}, orderId={}, amount={}, takeBps={}, r0={}",
+                    orderType, orderId, amount, takeBps, r0);
+        } catch (DuplicateKeyException e) {
+            log.info("R0平台抽成已存在,跳过重复写入: orderType={}, orderId={}", orderType, orderId);
+        } catch (Exception e) {
+            log.warn("R0平台抽成写入失败: orderType={}, orderId={}, err={}", orderType, orderId, e.getMessage());
+        }
+        return r0;
+    }
+
+    /**
+     * 零参结算入口(契约 cf.rewardv2.e2eExample:v2 结算四入口方法)。
+     *
+     * <p>无请求/订单上下文的探活形态:不产生 R0 记账动作,仅记录日志并返回 0;
+     * 有订单上下文时使用带参重载 {@link #settlePlatformTake(Long, String, Integer, Integer)}。</p>
+     *
+     * @return 0(无上下文不记账)
+     */
+    public int settlePlatformTake() {
+        log.info("[cf.rewardv2.e2eExample] settlePlatformTake() 零参入口无订单上下文,跳过 R0 记账(有上下文请走带参重载)。");
+        return 0;
+    }
+
+    /**
+     * 可分配额 base 计算(设计 §3.1 / §6-T03,T03 交付)。
+     *
+     * <p>{@code base = A − R0 − R1_等值 − costCent},其中:</p>
+     * <ul>
+     *   <li>{@code R0 = floor(A × TAKE_BPS / 10000)}(平台抽成,先扣);</li>
+     *   <li>{@code R1_等值 = floor(A / 100)}(消费返 CF 等值成本,1 分 = 1 CF 参照,先扣);</li>
+     *   <li>{@code base < 0} 时返回 0(不得为负,设计 §1.1 / §1.4)。</li>
+     * </ul>
+     *
+     * <p>账目示例(设计 §1.1 / §8 #1):A=20000 分(200 元),costCent=10000 分(100 元)→
+     * R0=2000、R1_等值=200、base=7800(78 元)≠ 原始毛利 10000(100 元)。</p>
+     *
+     * @param amountCent 实付金额(分)
+     * @param costCent   商品成本(分)
+     * @return 可分配额 base(分),亏损仓(base &lt; 0)返回 0
+     */
+    public int calcDistributableBase(int amountCent, int costCent) {
+        int r0 = amountCent * TAKE_BPS / 10000;
+        int r1Equiv = amountCent / 100;
+        int base = amountCent - r0 - r1Equiv - costCent;
+        return base > 0 ? base : 0;
+    }
+
+    /**
+     * 团队池建池(分润 v2 §3.1 结算顺序 ⑤,能力键 cf.teamshare.createPool,T04)。
+     *
+     * <p>解析 T({@link TeamShareConfigService}:MINIAPP→SYSTEM→GLOBAL→兜底 3000bps)→ 算池金额
+     * (商品 = Σ floor(C × qty × T_bps / 10000);非商品 = floor(实付 × non_goods_cost_rate × T_bps / 10000))
+     * → 幂等建 {@code cf_team_pool_order}(唯一键 {@code uk_order(order_type, order_id)},重复结算命中
+     * 唯一键直接返回,设计 §7 风险 1 三层兜底第一层)→ 层级树瓜分 {@link #distributeTeamPool(Long, String, Long, Long, Integer, Long)}
+     * (T05 能力键 {@code cf.teamshare.weightedShare}:档位权重瓜分 + 尾差守恒 + 同家庭跳过)。</p>
+     */
+    @Transactional
+    public void settleTeamPool(Long orderId, String orderType, Long buyerUserId, Long buyerFamilyId,
+                               Integer paidAmountCent, Long productId) {
+        try {
+            if (orderId == null || orderType == null || buyerUserId == null) {
+                return;
+            }
+            // 依赖注入缺省(既有单测裸实例/部分 mock)时静默跳过,不影响既有结算链路
+            if (cfTeamPoolOrderMapper == null || teamShareConfigService == null || configService == null) {
+                return;
+            }
+            // 团队池总开关(cf.team_pool.enabled,默认 true)
+            if (!configService.getBooleanConfig(CfConfigKeys.TEAM_POOL_ENABLED, true)) {
+                return;
+            }
+            // 1. 解析 T:MINIAPP(mp_code) → SYSTEM(商品所属 distribution_system_id) → GLOBAL → 兜底 3000
+            String mpCode = MiniAppContextHolder.mpCode();
+            Long distributionSystemId = resolveProductDistributionSystemId(orderType, productId);
+            int tBps = teamShareConfigService.resolveTbps(mpCode, distributionSystemId);
+            if (tBps <= 0) {
+                log.info("团队池比例 T<=0,跳过建池: orderType={}, orderId={}", orderType, orderId);
+                return;
+            }
+            // 2. 算池金额(从成本侧切出,独立于 base;亏损仓仍按成本 × T% 照常发)
+            int poolCent = calcTeamPoolCent(orderId, orderType, paidAmountCent, productId, tBps);
+            if (poolCent <= 0) {
+                log.info("团队池金额为 0,跳过建池: orderType={}, orderId={}", orderType, orderId);
+                return;
+            }
+            // 3. 幂等建池(uk_order(order_type, order_id),重复结算命中唯一键直接返回)
+            CfTeamPoolOrder pool = new CfTeamPoolOrder();
+            pool.setOrderId(orderId);
+            pool.setOrderType(orderType);
+            pool.setProductId(productId);
+            pool.setBuyerUserId(buyerUserId);
+            pool.setPoolCent(poolCent);
+            pool.setTBps(tBps);
+            pool.setConfigScope(resolveScope(mpCode, distributionSystemId));
+            pool.setStatus("pooled");
+            pool.setCreatedAt(new Date());
+            pool.setRemark("成本×T%建池");
+            cfTeamPoolOrderMapper.insert(pool);
+            log.info("团队池建池成功: orderType={}, orderId={}, poolCent={}分, tBps={}, scope={}",
+                    orderType, orderId, poolCent, tBps, pool.getConfigScope());
+            // 4. 层级树瓜分(T05 cf.teamshare.weightedShare:档位权重瓜分 + 尾差守恒 + 同家庭跳过)
+            try {
+                distributeTeamPool(orderId, orderType, buyerUserId, buyerFamilyId, paidAmountCent, productId);
+            } catch (Exception e) {
+                log.warn("团队池瓜分失败(池已建,可后续补跑): orderType={}, orderId={}, err={}",
+                        orderType, orderId, e.getMessage());
+            }
+        } catch (DuplicateKeyException e) {
+            // 幂等:重复结算命中 uk_order,直接返回(设计 §7 风险 1 三层兜底第一层)
+            log.info("团队池已存在,幂等跳过建池: orderType={}, orderId={}", orderType, orderId);
+        } catch (Exception e) {
+            log.warn("团队池建池失败: orderType={}, orderId={}, err={}", orderType, orderId, e.getMessage());
+        }
+    }
+
+    /**
+     * 零参结算入口(契约 cf.rewardv2.e2eExample:v2 结算四入口方法)。
+     *
+     * <p>无请求/订单上下文的探活形态:不产生建池动作,仅记录日志;
+     * 有订单上下文时使用带参重载
+     * {@link #settleTeamPool(Long, String, Long, Long, Integer, Long)}。</p>
+     */
+    public void settleTeamPool() {
+        log.info("[cf.rewardv2.e2eExample] settleTeamPool() 零参入口无订单上下文,跳过建池(有上下文请走带参重载)。");
+    }
+
+    /**
+     * 零参结算入口(契约 cf.rewardv2.e2eExample:v2 结算四入口方法)。
+     *
+     * <p>层级树瓜分(设计 §5:档位权重瓜分 + 尾差守恒 + 同家庭跳过)由能力键
+     * {@code cf.teamshare.weightedShare}(T05)承接带参实现;本零参入口为无上下文的
+     * 契约探活形态,仅记录日志。</p>
+     */
+    public void distributeTeamPool() {
+        log.info("[cf.rewardv2.e2eExample] distributeTeamPool() 零参入口无订单上下文,跳过瓜分"
+                + "(层级树瓜分由 T05 cf.teamshare.weightedShare 承接带参实现)。");
+    }
+
+    /**
+     * 层级树瓜分(分润 v2 设计 §5,能力键 {@code cf.teamshare.weightedShare},T05)。
+     *
+     * <p>由 {@link #settleTeamPool(Long, String, Long, Long, Integer, Long)} 建池后调用,内部完成:</p>
+     * <ol>
+     *   <li>按 {@code uk_order(order_type, order_id)} 幂等取池(池不存在 / 已瓜分 / 无人认领直接短路);</li>
+     *   <li>取层级树成员(买家上溯,同家庭跳过,≤ TEAM_DEPTH=8,设计 §1.4 / §5 step 3);</li>
+     *   <li>档位权重(与 F03a 直推档位同一口径:{@link CfReferralService#getTeamAnnualPpoints}(m, 8)
+     *       → {@code matchDirectSalesTier},权重 = cf_direct_sales_tier.rate_percent,无档位 = 0);</li>
+     *   <li>按 {@link #allocateTeamPoolShareByWeight(int[], int)} 加权瓜分(尾差由最后一人补齐,Σ = pool_cent);</li>
+     *   <li>逐人 {@code earnByRule(memberId, "F03c", poolId, {amount: raw})} 发放(幂等键 uk_ref_type F03c + poolId)
+     *       + {@code cf_team_pool_share} 幂等落库(uk_pool_member,设计 §7 风险 1 三层兜底第二层);</li>
+     *   <li>池状态落库 {@code share_issued}(无档位 totalW ≤ 0 无人可分 → {@code unclaimed},不私发,设计 §5 step 4)。</li>
+     * </ol>
+     *
+     * <p>参数 {@code paidCent} 为契约签名入参(§3.1 T05),池金额以 {@code cf_team_pool_order.pool_cent}
+     * 落库值为准(建池已完成);依赖注入缺省(裸实例/部分 mock)时静默跳过,不影响既有结算链路。</p>
+     */
+    @Transactional
+    public void distributeTeamPool(Long orderId, String orderType, Long buyerUserId, Long buyerFamilyId,
+                                   Integer paidCent, Long productId) {
+        try {
+            if (orderId == null || orderType == null || buyerUserId == null) {
+                return;
+            }
+            // 依赖注入缺省(既有单测裸实例/部分 mock)时静默跳过,不影响既有结算链路
+            if (cfTeamPoolOrderMapper == null || cfTeamPoolShareMapper == null || referralTreeMapper == null
+                    || userMapper == null || familyMemberMapper == null || cfReferralService == null
+                    || cfBalanceService == null) {
+                return;
+            }
+            // 1. 幂等取池(uk_order(order_type, order_id):建池先行,池不存在直接返回)
+            CfTeamPoolOrder pool = cfTeamPoolOrderMapper.selectOne(
+                    new LambdaQueryWrapper<CfTeamPoolOrder>()
+                            .eq(CfTeamPoolOrder::getOrderId, orderId)
+                            .eq(CfTeamPoolOrder::getOrderType, orderType)
+                            .last("LIMIT 1"));
+            if (pool == null || pool.getId() == null) {
+                log.info("团队池不存在,跳过瓜分: orderType={}, orderId={}", orderType, orderId);
+                return;
+            }
+            // 已瓜分 / 无人认领:幂等短路(设计 §7 风险 1)
+            if ("share_issued".equals(pool.getStatus()) || "unclaimed".equals(pool.getStatus())) {
+                log.info("团队池已处理(status={}),跳过重复瓜分: orderType={}, orderId={}",
+                        pool.getStatus(), orderType, orderId);
+                return;
+            }
+            int poolCent = pool.getPoolCent() != null ? pool.getPoolCent() : 0;
+            if (poolCent <= 0) {
+                return;
+            }
+
+            // 2. 取层级树成员(买家上溯,同家庭跳过,≤ max_depth)
+            List<TeamPoolCandidate> candidates = new ArrayList<>();
+            List<ReferralTree> referrals = referralTreeMapper.selectList(
+                    new LambdaQueryWrapper<ReferralTree>()
+                            .eq(ReferralTree::getMemberId, buyerUserId)
+                            .orderByAsc(ReferralTree::getLevel));
+            if (referrals != null) {
+                Set<Long> processed = new HashSet<>();
+                for (ReferralTree ref : referrals) {
+                    if (candidates.size() >= TEAM_DEPTH) {
+                        break;
+                    }
+                    Long parentId = ref.getParentId();
+                    if (parentId == null || processed.contains(parentId)) {
+                        continue;
+                    }
+                    processed.add(parentId);
+                    User parent = userMapper.selectById(parentId);
+                    if (parent == null) {
+                        continue;
+                    }
+                    // 同家庭跳过(设计 §1.4 / §5 step 3:团队池瓜分成员跳过同家庭)
+                    if (buyerFamilyId != null && buyerFamilyId.equals(parent.getFamilyId())) {
+                        continue;
+                    }
+                    // 档位权重(与 F03a 直推档位同一口径:团队 8 层滚动一年 P 点 → rate_percent)
+                    int teamPp = cfReferralService.getTeamAnnualPpoints(parentId, TEAM_DEPTH);
+                    CfDirectSalesTier tier = cfReferralService.matchDirectSalesTier(teamPp);
+                    int weight = (tier == null || tier.getRatePercent() == null) ? 0 : tier.getRatePercent();
+                    int layer = ref.getLevel() != null ? ref.getLevel() : candidates.size() + 1;
+                    candidates.add(new TeamPoolCandidate(parentId, resolveMemberId(parentId), layer, weight));
+                }
+            }
+            if (candidates.isEmpty()) {
+                // 无推荐链 → 无人可分 → 池归商家(unclaimed,不私发)
+                markPoolResult(pool, "unclaimed");
+                return;
+            }
+
+            // 3. 加权瓜分(纯算法:末位吸收尾差,Σ = poolCent,设计 §5 step 5 / §8#9)
+            int[] weights = new int[candidates.size()];
+            for (int i = 0; i < candidates.size(); i++) {
+                weights[i] = candidates.get(i).weight;
+            }
+            List<Integer> shares = allocateTeamPoolShareByWeight(weights, poolCent);
+            if (shares == null || shares.isEmpty()) {
+                // 无档位(totalW ≤ 0)→ 无人可分 → unclaimed(不私发,设计 §5 step 4)
+                markPoolResult(pool, "unclaimed");
+                return;
+            }
+
+            // 4. 逐人发放 + 明细落库(幂等兜底:uk_ref_type F03c+poolId / uk_pool_member)
+            long issued = 0L;
+            int lastIdx = shares.size() - 1;
+            for (int i = 0; i < shares.size(); i++) {
+                TeamPoolCandidate cand = candidates.get(i);
+                // 末位吸收尾差(按实际已发放额,与 §5 step 5 一致;非末位用纯算法值)
+                int raw = (i == lastIdx) ? (int) (poolCent - issued) : shares.get(i);
+                if (raw <= 0 || cand.memberId == null) {
+                    continue;
+                }
+                try {
+                    Map<String, Object> ctx = new HashMap<>();
+                    ctx.put("amount", raw);
+                    cfBalanceService.earnByRule(cand.memberId, RULE_TEAM_POOL, pool.getId(), ctx);
+                } catch (Exception e) {
+                    log.warn("团队池 F03c 发放失败: memberId={}, poolId={}, raw={}, err={}",
+                            cand.memberId, pool.getId(), raw, e.getMessage());
+                    continue;
+                }
+                try {
+                    CfTeamPoolShare share = new CfTeamPoolShare();
+                    share.setPoolId(pool.getId());
+                    share.setMemberId(cand.memberId);
+                    share.setUserId(cand.userId);
+                    share.setLayer(cand.layer);
+                    share.setRatePercent(cand.weight);
+                    share.setWeight(cand.weight);
+                    share.setShareCent(raw);
+                    share.setStatus("issued");
+                    share.setCreatedAt(new Date());
+                    cfTeamPoolShareMapper.insert(share);
+                } catch (DuplicateKeyException e) {
+                    log.info("团队池份额已存在,幂等跳过: poolId={}, memberId={}", pool.getId(), cand.memberId);
+                } catch (Exception e) {
+                    log.warn("团队池份额落库失败: poolId={}, memberId={}, err={}",
+                            pool.getId(), cand.memberId, e.getMessage());
+                }
+                issued += raw;
+            }
+            markPoolResult(pool, "share_issued");
+        } catch (Exception e) {
+            log.warn("团队池瓜分失败: orderType={}, orderId={}, err={}", orderType, orderId, e.getMessage());
+        }
+    }
+
+    /**
+     * 纯加权瓜分(设计 §5 step 5 算法抽离,能力键 {@code cf.teamshare.weightedShare} 数学锚点 §8#1/#9)。
+     *
+     * <p>池金额按成员档位权重比例分配:每人 {@code raw = floor(poolCent × w / totalW)},末位成员吸收尾差
+     * ({@code raw = poolCent − Σ(前序) })保证 Σ = poolCent(尾差守恒,金额不蒸发)。与档位体系解耦,
+     * 权重数据源(rate_percent)由调用方 {@link #distributeTeamPool(Long, String, Long, Long, Integer, Long)}
+     * 经 {@code CfReferralService#matchDirectSalesTier} 提供,便于本算法独立单测。</p>
+     *
+     * <p>命题验证(§8#1):池 3000 分、权重 {70, 50}、totalW=120 →
+     * {@code raw₁ = floor(3000×70/120) = 1750;raw₂ = 3000 − 1750 = 1250}(末位补齐尾差)。</p>
+     *
+     * @param weights  各成员档位权重(= cf_direct_sales_tier.rate_percent;非负,全 0 / 空 = 无档位)
+     * @param poolCent 团队池金额(分,≥ 0)
+     * @return 每人分得(分,长度 = 成员数,末位含尾差);totalW ≤ 0(无档位)返回空列表——调用方将池置
+     *         unclaimed(不私发,设计 §5 step 4/5)
+     */
+    public List<Integer> allocateTeamPoolShareByWeight(int[] weights, int poolCent) {
+        if (weights == null || weights.length == 0) {
+            return Collections.emptyList();
+        }
+        long totalW = 0L;
+        for (int w : weights) {
+            totalW += w;
+        }
+        if (totalW <= 0) {
+            // 无档位(totalW ≤ 0):无人可分,调用方将池置 unclaimed(不私发)
+            return Collections.emptyList();
+        }
+        List<Integer> shares = new ArrayList<>(weights.length);
+        long issued = 0L;
+        for (int i = 0; i < weights.length; i++) {
+            int raw;
+            if (i == weights.length - 1) {
+                // 末位成员吸收尾差:Σ = poolCent(尾差守恒,设计 §8#9)
+                raw = (int) (poolCent - issued);
+            } else {
+                raw = (int) ((long) poolCent * weights[i] / totalW);
+            }
+            shares.add(raw);
+            issued += raw;
+        }
+        return shares;
+    }
+
+    /** 池结算状态落库(share_issued=已瓜分 / unclaimed=无成员可瓜分,设计 §2.2 状态机) */
+    private void markPoolResult(CfTeamPoolOrder pool, String status) {
+        try {
+            pool.setStatus(status);
+            pool.setSettledAt(new Date());
+            cfTeamPoolOrderMapper.updateById(pool);
+            log.info("团队池状态落库: poolId={}, status={}", pool.getId(), status);
+        } catch (Exception e) {
+            log.warn("团队池状态落库失败: poolId={}, status={}, err={}", pool.getId(), status, e.getMessage());
+        }
+    }
+
+    /** 团队池瓜分候选成员(推荐链层级 + 档位权重 + 成员档案),供 §5 步骤 4/5 使用 */
+    private static class TeamPoolCandidate {
+        final Long userId;
+        final Long memberId;
+        final int layer;
+        final int weight;
+
+        TeamPoolCandidate(Long userId, Long memberId, int layer, int weight) {
+            this.userId = userId;
+            this.memberId = memberId;
+            this.layer = layer;
+            this.weight = weight;
+        }
+    }
+
+    /** 命中作用域标注(供 cf_team_pool_order.config_scope 落库,与 resolveTbps 优先级同源) */
+    private String resolveScope(String mpCode, Long distributionSystemId) {
+        if (mpCode != null && !mpCode.trim().isEmpty()) {
+            return TeamShareConfigService.SCOPE_MINIAPP;
+        }
+        if (distributionSystemId != null) {
+            return TeamShareConfigService.SCOPE_SYSTEM;
+        }
+        return TeamShareConfigService.SCOPE_GLOBAL;
+    }
+
+    /** 商品所属销售体系ID(SYSTEM 作用域键;非商品/无商品返回 null) */
+    private Long resolveProductDistributionSystemId(String orderType, Long productId) {
+        if (!"product".equals(orderType) || productId == null) {
+            return null;
+        }
+        try {
+            Product p = productMapper.selectById(productId);
+            return p != null ? p.getDistributionSystemId() : null;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /**
+     * 团队池金额(分):
+     * 商品订单 = Σ floor(C_i × qty_i × T_bps / 10000)(按行成本加总,无分摊歧义);
+     * 非商品订单 = floor(实付 × non_goods_cost_rate × T_bps / 10000)(成本模型,设计 §1.3)。
+     */
+    private int calcTeamPoolCent(Long orderId, String orderType, Integer paidAmountCent, Long productId, int tBps) {
+        int paid = paidAmountCent != null ? paidAmountCent : 0;
+        if (!"product".equals(orderType)) {
+            int ncd = configService.getIntConfig(CfConfigKeys.TEAM_POOL_NON_GOODS_COST_RATE, 5000);
+            long nonGoodsCost = (long) paid * ncd / 10000;
+            long pool = nonGoodsCost * tBps / 10000;
+            return pool > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) pool;
+        }
+        try {
+            ProductOrder order = productOrderMapper.selectById(orderId);
+            if (order == null) {
+                return 0;
+            }
+            List<OrderItem> items = orderItemMapper.findByOrderId(orderId);
+            if (items != null && !items.isEmpty()) {
+                long total = 0L;
+                for (OrderItem it : items) {
+                    int qty = it.getQuantity() != null ? it.getQuantity() : 0;
+                    if (qty <= 0 || it.getProductId() == null) {
+                        continue;
+                    }
+                    Product p = productMapper.selectById(it.getProductId());
+                    if (p == null || p.getPurchasePrice() == null) {
+                        continue;
+                    }
+                    total += (long) p.getPurchasePrice() * qty * tBps / 10000;
+                }
+                return total > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) total;
+            }
+            // 单商品订单:实付结算传 productId;成本价未配(null)时按 0 处理→池 0 跳过
+            if (productId == null) {
+                return 0;
+            }
+            Product p = productMapper.selectById(productId);
+            if (p == null || p.getPurchasePrice() == null) {
+                return 0;
+            }
+            int qty = order.getQuantity() != null ? order.getQuantity() : 1;
+            long single = (long) p.getPurchasePrice() * qty * tBps / 10000;
+            return single > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) single;
+        } catch (Exception e) {
+            log.warn("计算团队池金额失败: orderId={}, err={}", orderId, e.getMessage());
+            return 0;
+        }
+    }
+
     /**
      * 推荐人分润:两级销售奖(F03a 直接销售奖 + F03b 间接销售奖)。
      *
@@ -369,20 +873,22 @@ public class CfCommissionService {
                             Product p = productMapper.selectById(it.getProductId());
                             int costPerUnit = (p != null && p.getPurchasePrice() != null) ? p.getPurchasePrice() : 0;
                             long lineCost = (long) costPerUnit * qty;
-                            long linePpoint = allocPaid - lineCost;
+                            long memberCost = giftMembershipCost(it.getProductId());
+                            long linePpoint = allocPaid - lineCost - memberCost;
                             if (linePpoint > 0) total += (int) linePpoint;
                         }
                         return total;
                     }
                 }
 
-                // 单商品订单:实付 − 成本 × 数量
+                // 单商品订单:实付 − 成本 × 数量 − 赠送会员成本价
                 if (productId == null) return 0;
                 Product p = productMapper.selectById(productId);
                 if (p == null) return 0;
                 int costPerUnit = p.getPurchasePrice() != null ? p.getPurchasePrice() : 0;
                 int qty = order.getQuantity() != null ? order.getQuantity() : 1;
-                int ppoints = paid - costPerUnit * qty;
+                int memberCost = giftMembershipCost(productId);
+                int ppoints = paid - costPerUnit * qty - memberCost;
                 return ppoints > 0 ? ppoints : 0;
             } catch (Exception e) {
                 log.warn("计算本单 P 点失败: orderId={}, err={}", orderId, e.getMessage());
@@ -395,6 +901,31 @@ public class CfCommissionService {
         return amountYuan * serviceRateBps / 10000;
     }
 
+
+    /**
+     * 赠送会员成本价(分):商品若配置了「送会员规则」(product_gift_rules 启用),
+     * 返回其赠送等级的 membership_levels.cost_price;未配置或等级无成本价返回 0。
+     */
+    private int giftMembershipCost(Long productId) {
+        if (productId == null) return 0;
+        try {
+            ProductGiftRule rule = productGiftRuleMapper.selectOne(
+                    new LambdaQueryWrapper<ProductGiftRule>()
+                            .eq(ProductGiftRule::getProductId, productId)
+                            .eq(ProductGiftRule::getStatus, 1)
+                            .last("LIMIT 1"));
+            if (rule == null || rule.getLevelCode() == null) return 0;
+            MembershipLevel level = membershipLevelMapper.selectOne(
+                    new LambdaQueryWrapper<MembershipLevel>()
+                            .eq(MembershipLevel::getLevelCode, rule.getLevelCode())
+                            .last("LIMIT 1"));
+            return (level == null || level.getCostPrice() == null) ? 0 : level.getCostPrice();
+        } catch (Exception e) {
+            log.warn("查询赠送会员成本价失败: productId={}, err={}", productId, e.getMessage());
+            return 0;
+        }
+    }
+
     /** 落 P 点消费日志(唯一键 order_type+order_id,重复触发忽略) */
     private void recordPpointConsumption(Long orderId, String orderType, Long buyerUserId, Long buyerFamilyId,
                                          Integer amountCent, Long productId, int ppoints) {

+ 1 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ContactService.java

@@ -189,6 +189,7 @@ public class ContactService {
         dto.setUpdatedAt(c.getUpdatedAt());
         dto.setFamilyMemberId(c.getFamilyMemberId());
         dto.setInvitedStatus(c.getInvitedStatus());
+        dto.setGroupId(c.getGroupId());
         return dto;
     }
 

+ 54 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/CouponGiftService.java

@@ -251,20 +251,67 @@ public class CouponGiftService {
             throw new IllegalArgumentException("只能转赠给自己的直推或隔级推荐人");
         }
 
+        // 券实例转移 + transfer 记录 + 通知 + 审计:统一下沉到 commitTransfer(分享转赠复用,行为不变)
+        return commitTransfer(giverUserId, giverFamilyId, receiverUserId, receiver.getFamilyId(),
+                coupon.getId(), fc.getId(), referral.getLevel(), "DIRECT", null, remark);
+    }
+
+    /**
+     * 提交券实例转移 + transfer 记录 + 通知 + 审计流水(定向转赠与分享转赠共有的尾段)。
+     *
+     * <p>调用方必须在事务中({@code @Transactional} 传播 REQUIRED 合并):定向转赠
+     * {@link #transfer} 与分享转赠 {@code CouponShareService.claim} 均在本方法内完成
+     * 「券实例归属转移(family_coupon.family_id + is_gift=1)→ coupon_gift_transfer 记录 →
+     * 通知(模板 coupon_gift)→ grant log(GIFT_TRANSFER, source=transfer:id)」,任一失败整体回滚。</p>
+     *
+     * @param giverUserId     赠送人 users.id
+     * @param giverFamilyId   赠送人家庭
+     * @param receiverUserId  接收人 users.id(券最终归属人)
+     * @param receiverFamilyId 接收人家庭(券实例最终归属)
+     * @param couponId        券模板 id
+     * @param familyCouponId  family_coupon 实例 id
+     * @param giftLevel       推荐层级(定向:1=直推/2=隔级;分享:0=无推荐层级,见 SHARE_GIFT_LEVEL)
+     * @param claimMethod     领取方式:"DIRECT"=定向转赠 / "SHARE"=分享转赠(null 兜底 DIRECT)
+     * @param shareToken      分享领取时回写 coupon_gift_transfer.share_token(定向为 null)
+     * @param remark          留言(可空)
+     * @return transferId
+     */
+    @Transactional
+    public Long commitTransfer(Long giverUserId, Long giverFamilyId,
+                               Long receiverUserId, Long receiverFamilyId,
+                               Long couponId, Long familyCouponId,
+                               Integer giftLevel, String claimMethod,
+                               String shareToken, String remark) {
+        if (giverUserId == null || receiverUserId == null || familyCouponId == null
+                || couponId == null || receiverFamilyId == null) {
+            throw new IllegalArgumentException("参数不完整");
+        }
+        Coupon coupon = couponMapper.selectById(couponId);
+        if (coupon == null) {
+            throw new IllegalArgumentException("优惠券已失效");
+        }
+
         // 转移券实例到接收方家庭,并打 is_gift 标记(接收方非会员也可用其购买会员)
-        fc.setFamilyId(receiver.getFamilyId());
+        FamilyCoupon fc = familyCouponMapper.selectById(familyCouponId);
+        if (fc == null) {
+            throw new IllegalArgumentException("该优惠券不可用或不属于你");
+        }
+        fc.setFamilyId(receiverFamilyId);
         fc.setIsGift(1);
         familyCouponMapper.updateById(fc);
 
+        Date now = new Date();
         CouponGiftTransfer transfer = new CouponGiftTransfer();
         transfer.setGiverUserId(giverUserId);
         transfer.setGiverFamilyId(giverFamilyId);
         transfer.setReceiverUserId(receiverUserId);
-        transfer.setReceiverFamilyId(receiver.getFamilyId());
+        transfer.setReceiverFamilyId(receiverFamilyId);
         transfer.setCouponId(coupon.getId());
         transfer.setFamilyCouponId(fc.getId());
-        transfer.setGiftLevel(referral.getLevel());
+        transfer.setGiftLevel(giftLevel);
         transfer.setStatus("GIFTED");
+        transfer.setClaimMethod(claimMethod != null ? claimMethod : "DIRECT");
+        transfer.setShareToken(shareToken);
         transfer.setRemark(remark);
         transfer.setCreatedAt(now);
         couponGiftTransferMapper.insert(transfer);
@@ -289,9 +336,9 @@ public class CouponGiftService {
                     transfer.getId(), e.getMessage());
         }
 
-        // 发放流水(审计)
+        // 发放流水(审计)——分享与定向统一 GIFT_TRANSFER,source 均记 transferId(对账口径一致)
         FamilyCouponGrantLog log = new FamilyCouponGrantLog();
-        log.setFamilyId(receiver.getFamilyId());
+        log.setFamilyId(receiverFamilyId);
         log.setCouponId(coupon.getId());
         log.setGrantType("GIFT_TRANSFER");
         log.setPeriod(null);
@@ -300,8 +347,8 @@ public class CouponGiftService {
         log.setCreatedAt(now);
         familyCouponGrantLogMapper.insert(log);
 
-        logger.info("会员券转赠成功: giver={}, receiver={}, familyCouponId={}, level={}, transferId={}",
-                giverUserId, receiverUserId, familyCouponId, referral.getLevel(), transfer.getId());
+        logger.info("会员券转赠提交: giver={}, receiver={}, familyCouponId={}, level={}, method={}, transferId={}",
+                giverUserId, receiverUserId, familyCouponId, giftLevel, transfer.getClaimMethod(), transfer.getId());
         return transfer.getId();
     }
 

+ 25 - 3
cfc-backend/src/main/java/com/etotem/cfc/service/CouponService.java

@@ -184,17 +184,39 @@ public class CouponService {
         if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
             return "优惠券已过期";
         }
-        // 去重:同一个家庭同一张券只发一次(同 grantType 的幂等也通过 grant 方法保证)
-        Long count = familyCouponMapper.selectCount(
+        // 去重:同一个家庭同一张券只发一次(COUPON-C3 口径:family_coupon 记录 ∪ 发券流水)。
+        // 以发券流水(任意 grant_type)为补充判定口径:JOIN/POPULATION/PERIODIC/CF_EXCHANGE 等
+        // 自动发放链路发过券的家庭,手动 /claim 同券不再二次发放(S-cfc-293 AC-3)。
+        Long fcCount = familyCouponMapper.selectCount(
                 new LambdaQueryWrapper<FamilyCoupon>()
                         .eq(FamilyCoupon::getFamilyId, familyId)
                         .eq(FamilyCoupon::getCouponId, couponId));
-        if (count != null && count > 0) {
+        Long grantCount = 0L;
+        if (familyCouponGrantLogMapper != null) {
+            grantCount = familyCouponGrantLogMapper.selectCount(
+                    new LambdaQueryWrapper<FamilyCouponGrantLog>()
+                            .eq(FamilyCouponGrantLog::getFamilyId, familyId)
+                            .eq(FamilyCouponGrantLog::getCouponId, couponId));
+        }
+        if ((fcCount != null && fcCount > 0) || (grantCount != null && grantCount > 0)) {
             return "已领取过该优惠券";
         }
         issueToFamily(couponId, familyId);
         coupon.setUsedCount(coupon.getUsedCount() == null ? 1 : coupon.getUsedCount() + 1);
         couponMapper.updateById(coupon);
+        // AC-1:落发券流水(grantType=CLAIM),作为「已领拦截」的流水口径防重记录。
+        // 判空仅兼容未注入 grantLogMapper 的旧式单测(S-cfc-12 CouponUseScP57ScP75ContractTest
+        // 用 new CouponService() 未注入该字段),Spring 注入场景恒非 null。
+        if (familyCouponGrantLogMapper != null) {
+            FamilyCouponGrantLog grantLog = new FamilyCouponGrantLog();
+            grantLog.setFamilyId(familyId);
+            grantLog.setCouponId(couponId);
+            grantLog.setGrantType("CLAIM");
+            grantLog.setQuantity(1);
+            grantLog.setSource("claim:userId:" + userId);
+            grantLog.setCreatedAt(new Date());
+            familyCouponGrantLogMapper.insert(grantLog);
+        }
         return "领取成功";
     }
 

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů