Преглед изворни кода

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

Agnes Agent пре 2 часа
родитељ
комит
864095100f
100 измењених фајлова са 28399 додато и 0 уклоњено
  1. 191 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PpointService.java
  2. 140 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PrivacySettingService.java
  3. 166 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProblemCompletionService.java
  4. 301 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProcurementTaskService.java
  5. 167 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductCategoryService.java
  6. 299 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductDeliveryConfigService.java
  7. 85 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductDimensionConfigService.java
  8. 93 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductGiftRuleService.java
  9. 184 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductGiftService.java
  10. 2395 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductOrderService.java
  11. 136 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductPurchaseFieldService.java
  12. 1122 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductRecommendationService.java
  13. 80 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewService.java
  14. 292 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewServiceImpl.java
  15. 808 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductService.java
  16. 219 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductSkuService.java
  17. 8 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProfileComputeService.java
  18. 10 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProfileReadService.java
  19. 283 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProfitPoolService.java
  20. 54 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PromotionBindingService.java
  21. 45 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PromotionCommissionService.java
  22. 77 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PromotionMaterialService.java
  23. 123 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PromotionTierEvalService.java
  24. 189 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PromotionTierService.java
  25. 33 0
      cfc-backend/src/main/java/com/etotem/cfc/service/PurchaseService.java
  26. 95 0
      cfc-backend/src/main/java/com/etotem/cfc/service/QrCodeService.java
  27. 57 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RealNameBackfillService.java
  28. 49 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RecipeService.java
  29. 8 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RecommendService.java
  30. 104 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RecommendationRuleService.java
  31. 387 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RecommendationService.java
  32. 196 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReferralLeaderboardService.java
  33. 305 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RelationshipQualityService.java
  34. 424 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RelationshipQuestionnaireService.java
  35. 269 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportAnalyzeQuotaService.java
  36. 199 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportArchiveCompareService.java
  37. 814 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportBlockAssembler.java
  38. 72 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportBlockService.java
  39. 1558 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportCollectService.java
  40. 146 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportDateExtractor.java
  41. 256 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportFeedbackService.java
  42. 208 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportFingerprintService.java
  43. 265 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportImportService.java
  44. 359 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportMemberPermissionService.java
  45. 164 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportParseService.java
  46. 515 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportParserDispatchService.java
  47. 438 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportScriptGeneratorService.java
  48. 574 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportSummaryService.java
  49. 178 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportSurveyService.java
  50. 78 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportTemplateService.java
  51. 327 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReportTransferService.java
  52. 309 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RepurchaseMiningService.java
  53. 176 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RepurchaseReminderService.java
  54. 479 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ResourceService.java
  55. 16 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReviewOrderService.java
  56. 114 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ReviewOrderServiceImpl.java
  57. 993 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RewardRuleService.java
  58. 374 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RewardService.java
  59. 125 0
      cfc-backend/src/main/java/com/etotem/cfc/service/RewardWishlistService.java
  60. 49 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SeasonalFoodService.java
  61. 248 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SelfCheckAnalysisService.java
  62. 387 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SelfCheckTrendService.java
  63. 43 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ServiceContentService.java
  64. 92 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ServiceCostConfigService.java
  65. 18 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ServiceRoleApplicationService.java
  66. 35 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ServiceTypeService.java
  67. 261 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ShareService.java
  68. 153 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SpecialPriceService.java
  69. 95 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SsoService.java
  70. 325 0
      cfc-backend/src/main/java/com/etotem/cfc/service/StarDigestService.java
  71. 512 0
      cfc-backend/src/main/java/com/etotem/cfc/service/StarScoreCalculator.java
  72. 53 0
      cfc-backend/src/main/java/com/etotem/cfc/service/StorageService.java
  73. 225 0
      cfc-backend/src/main/java/com/etotem/cfc/service/StreakService.java
  74. 160 0
      cfc-backend/src/main/java/com/etotem/cfc/service/StreetService.java
  75. 43 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SubscriptionBenefitLogService.java
  76. 189 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SupplyCustomerRelationService.java
  77. 302 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SupplyHierarchyService.java
  78. 320 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SupplySettlementService.java
  79. 362 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SupplySystemService.java
  80. 51 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SurveyService.java
  81. 100 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SysConfigService.java
  82. 250 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SysMenuService.java
  83. 40 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SystemConfigService.java
  84. 28 0
      cfc-backend/src/main/java/com/etotem/cfc/service/SystemPromptService.java
  85. 73 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskParseService.java
  86. 57 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskPlanInstanceService.java
  87. 401 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskPlanService.java
  88. 252 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderConfigService.java
  89. 283 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderService.java
  90. 2707 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java
  91. 173 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskStatsService.java
  92. 263 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskTemplatePackageService.java
  93. 197 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeacherFamilyBindingRequestService.java
  94. 113 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeacherMessageService.java
  95. 345 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeacherService.java
  96. 282 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitConfigService.java
  97. 92 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitFlowService.java
  98. 316 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitService.java
  99. 141 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TeamShareConfigService.java
  100. 232 0
      cfc-backend/src/main/java/com/etotem/cfc/service/TencentTtsService.java

+ 191 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PpointService.java

@@ -0,0 +1,191 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductPpoint;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductPpointMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class PpointService {
+
+    private static final Logger log = LoggerFactory.getLogger(PpointService.class);
+
+    @Resource
+    private ProductPpointMapper productPpointMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    /**
+     * Get effective P-point for a product.
+     * First checks product_ppoint table for a date-valid record (startDate <= today <= endDate).
+     * Falls back to Product.profitRate if no valid product_ppoint record exists.
+     * Returns 0 if neither exists.
+     * @param productId product ID
+     * @return effective ppoint value in basis points (e.g., 1000 = 10%)
+     */
+    public int getEffectivePpoint(Long productId) {
+        if (productId == null) {
+            return 0;
+        }
+
+        Date now = new Date();
+
+        // Check product_ppoint table for a date-valid record (startDate <= now AND (endDate is null OR endDate >= now))
+        LambdaQueryWrapper<ProductPpoint> wrapper = new LambdaQueryWrapper<ProductPpoint>()
+                .eq(ProductPpoint::getProductId, productId)
+                .le(ProductPpoint::getStartDate, now)
+                .and(w -> w.isNull(ProductPpoint::getEndDate).or().ge(ProductPpoint::getEndDate, now))
+                .orderByDesc(ProductPpoint::getStartDate)
+                .last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        ProductPpoint record = productPpointMapper.selectOne(wrapper);
+
+        if (record != null && record.getPpoint() != null && record.getPpoint() > 0) {
+            return record.getPpoint();
+        }
+
+        // Fallback to Product.profitRate (千分比 → 基点: *100)
+        Product product = productMapper.selectById(productId);
+        if (product != null && product.getProfitRate() != null) {
+            return product.getProfitRate() * 100;
+        }
+
+        return 0;
+    }
+
+    /**
+     * Save or update P-point config for a product (admin operation).
+     * If a valid record already exists for the product, update it; otherwise insert.
+     */
+    public void savePpoint(Long productId, Integer ppoint, Date startDate, Date endDate, Long adminUserId) {
+        // Check if an existing record exists for this product
+        LambdaQueryWrapper<ProductPpoint> wrapper = new LambdaQueryWrapper<ProductPpoint>()
+                .eq(ProductPpoint::getProductId, productId);
+        SortUtil.applySort(wrapper);
+        ProductPpoint existing = productPpointMapper.selectOne(wrapper);
+
+        if (existing != null) {
+            existing.setPpoint(ppoint);
+            existing.setStartDate(startDate);
+            existing.setEndDate(endDate);
+            existing.setCreatedBy(adminUserId);
+            productPpointMapper.updateById(existing);
+        } else {
+            ProductPpoint record = new ProductPpoint();
+            record.setProductId(productId);
+            record.setPpoint(ppoint);
+            record.setStartDate(startDate);
+            record.setEndDate(endDate);
+            record.setCreatedBy(adminUserId);
+            record.setCreatedAt(new Date());
+            productPpointMapper.insert(record);
+        }
+    }
+
+    /**
+     * Delete P-point config by ID (admin operation).
+     */
+    public void deleteById(Long id) {
+        productPpointMapper.deleteById(id);
+    }
+
+    /**
+     * Get P-point record by product ID (all records, not just effective one).
+     */
+    public List<ProductPpoint> getByProductId(Long productId) {
+        return productPpointMapper.selectList(
+                new LambdaQueryWrapper<ProductPpoint>()
+                        .eq(ProductPpoint::getProductId, productId)
+                        .orderByDesc(ProductPpoint::getStartDate)
+        );
+    }
+
+    /**
+     * Admin list: paginated P-point configs with product name.
+     */
+    public Map<String, Object> adminList(Page<ProductPpoint> pageParam, String keyword, Long productId, List<Map<String, String>> sortSpecs) {
+        LambdaQueryWrapper<ProductPpoint> wrapper = new LambdaQueryWrapper<ProductPpoint>()
+                .orderByDesc(ProductPpoint::getCreatedAt);
+
+        if (productId != null) {
+            wrapper.eq(ProductPpoint::getProductId, productId);
+        }
+
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        Page<ProductPpoint> page = productPpointMapper.selectPage(pageParam, wrapper);
+        List<ProductPpoint> records = page.getRecords();
+
+        // Filter by keyword (product name) in memory
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            String kw = keyword.trim().toLowerCase();
+            List<Long> matchedIds = records.stream()
+                    .map(ProductPpoint::getProductId)
+                    .distinct()
+                    .collect(Collectors.toList());
+            if (!matchedIds.isEmpty()) {
+                List<Product> products = productMapper.selectBatchIds(matchedIds);
+                List<Long> filterIds = products.stream()
+                        .filter(p -> p.getName() != null && p.getName().toLowerCase().contains(kw))
+                        .map(Product::getId)
+                        .collect(Collectors.toList());
+                records = records.stream()
+                        .filter(r -> filterIds.contains(r.getProductId()))
+                        .collect(Collectors.toList());
+            } else {
+                records = new java.util.ArrayList<>();
+            }
+        }
+
+        Map<Long, Product> productMap = new HashMap<>();
+        if (!records.isEmpty()) {
+            List<Long> productIds = records.stream()
+                    .map(ProductPpoint::getProductId)
+                    .distinct()
+                    .collect(Collectors.toList());
+            List<Product> products = productMapper.selectBatchIds(productIds);
+            for (Product p : products) {
+                productMap.put(p.getId(), p);
+            }
+        }
+
+        final Map<Long, Product> pm = productMap;
+        List<Map<String, Object>> enriched = records.stream().map(r -> {
+            Map<String, Object> m = new HashMap<>();
+            m.put("id", r.getId());
+            m.put("productId", r.getProductId());
+            m.put("ppoint", r.getPpoint());
+            m.put("startDate", r.getStartDate());
+            m.put("endDate", r.getEndDate());
+            m.put("createdBy", r.getCreatedBy());
+            m.put("createdAt", r.getCreatedAt());
+            Product p = pm.get(r.getProductId());
+            if (p != null) {
+                m.put("productName", p.getName());
+                m.put("productProfitRate", p.getProfitRate());
+                m.put("effectivePpoint", getEffectivePpoint(r.getProductId()));
+            }
+            return m;
+        }).collect(Collectors.toList());
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("records", enriched);
+        result.put("total", page.getTotal());
+        result.put("page", page.getCurrent());
+        result.put("size", page.getSize());
+        return result;
+    }
+}

+ 140 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PrivacySettingService.java

@@ -0,0 +1,140 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.PrivacySettingDTO;
+import com.etotem.cfc.entity.PrivacySetting;
+import com.etotem.cfc.mapper.PrivacySettingMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+
+/**
+ * 隐私设置 / 数据共享范围服务(能力键 {@code privacy.setting.config},SC-P-66)。
+ *
+ * <p>核心契约:最小权限保底。{@link #effectiveSharingScope(Long, int)} 返回
+ * {@code min(用户配置范围, 请求范围)},不得超过用户配置;未配置 / 脏数据(超范围值如 99)
+ * 一律降级为 0(仅自己)。{@link #isSensitiveFieldExposed(Long)} 恒返回 false——
+ * 即使落库被脏写为 sensitiveFieldsExposed=1,敏感字段也不外露(TC-P-66-E)。</p>
+ */
+@Slf4j
+@Service
+public class PrivacySettingService {
+
+    /** 数据共享范围枚举:0=仅自己(最小权限)/ 1=家庭成员 / 2=全部 */
+    private static final int SCOPE_PRIVATE = 0;
+    private static final int SCOPE_FAMILY = 1;
+    private static final int SCOPE_ALL = 2;
+
+    private static final String MSG_BAD_SCOPE = "数据共享范围不合法";
+    private static final String MSG_SENSITIVE = "敏感字段不可外露";
+
+    @Resource
+    private PrivacySettingMapper privacySettingMapper;
+
+    /** 读取用户隐私配置;未配置回显最小权限默认值(全 0)。 */
+    public PrivacySettingDTO getConfig(Long userId) {
+        PrivacySetting setting = selectByUserId(userId);
+        PrivacySettingDTO dto = new PrivacySettingDTO();
+        dto.setUserId(userId);
+        dto.setDataSharingScope(normalizeScope(setting == null ? null : setting.getDataSharingScope()));
+        // 敏感字段恒不外露(最小权限保底)
+        dto.setSensitiveFieldsExposed(0);
+        dto.setAllowFamilyView(setting == null ? 0 : clampBinary(setting.getAllowFamilyView()));
+        dto.setNotifyOnScopeChange(setting == null ? 0 : clampBinary(setting.getNotifyOnScopeChange()));
+        return dto;
+    }
+
+    /**
+     * 保存用户数据共享范围配置。userId 以登录态入参为准(禁止按 DTO 内 userId 跨用户写入)。
+     * dataSharingScope 仅允许 0/1/2,其他(含 -1/3)拒绝;sensitiveFieldsExposed=1 一律拒绝
+     * (敏感字段最小权限保底不外露,TC-P-66-E)。
+     */
+    public void saveConfig(Long userId, PrivacySettingDTO dto) {
+        if (dto == null) {
+            throw new IllegalArgumentException("隐私配置不能为空");
+        }
+        Integer scope = dto.getDataSharingScope();
+        if (scope == null || (scope != SCOPE_PRIVATE && scope != SCOPE_FAMILY && scope != SCOPE_ALL)) {
+            throw new IllegalArgumentException(MSG_BAD_SCOPE);
+        }
+        if (dto.getSensitiveFieldsExposed() != null && dto.getSensitiveFieldsExposed() == 1) {
+            throw new IllegalArgumentException(MSG_SENSITIVE);
+        }
+
+        PrivacySetting setting = selectByUserId(userId);
+        boolean isNew = (setting == null);
+        if (isNew) {
+            setting = new PrivacySetting();
+            setting.setUserId(userId);
+            setting.setCreatedAt(new Date());
+        }
+        setting.setUserId(userId);
+        setting.setDataSharingScope(scope);
+        // 敏感字段恒不外露:即便 DTO 请求外露也强制落 0
+        setting.setSensitiveFieldsExposed(0);
+        setting.setAllowFamilyView(clampBinary(dto.getAllowFamilyView()));
+        setting.setNotifyOnScopeChange(clampBinary(dto.getNotifyOnScopeChange()));
+        setting.setUpdatedAt(new Date());
+        if (isNew) {
+            privacySettingMapper.insert(setting);
+        } else {
+            privacySettingMapper.updateById(setting);
+        }
+    }
+
+    /**
+     * 下游实际生效的数据共享范围:{@code min(用户配置范围, 请求范围)}。
+     * 未配置 / 脏数据(超范围值如 99)一律降级为 0(仅自己),不得放大共享范围。
+     */
+    public int effectiveSharingScope(Long userId, int requestedScope) {
+        PrivacySetting setting = selectByUserId(userId);
+        int configured = normalizeScope(setting == null ? null : setting.getDataSharingScope());
+        int requested = Math.max(SCOPE_PRIVATE, requestedScope);
+        return Math.min(configured, requested);
+    }
+
+    /**
+     * 敏感字段是否可外露:恒返回 false(最小权限保底,TC-P-66-E)。
+     * 即使落库脏数据 sensitiveFieldsExposed=1,也不外露。
+     */
+    public boolean isSensitiveFieldExposed(Long userId) {
+        return false;
+    }
+
+    /** dataSharingScope 仅接受 0/1/2;null / 越界 / 脏值一律降级为 0(仅自己)。 */
+    private int normalizeScope(Integer scope) {
+        if (scope == null) {
+            return SCOPE_PRIVATE;
+        }
+        return (scope == SCOPE_PRIVATE || scope == SCOPE_FAMILY || scope == SCOPE_ALL)
+                ? scope : SCOPE_PRIVATE;
+    }
+
+    /** 二值开关归一:null / 非 0/1 一律按 0(关闭,最小权限)。 */
+    private int clampBinary(Integer value) {
+        return (value != null && value == 1) ? 1 : 0;
+    }
+
+    private PrivacySetting selectByUserId(Long userId) {
+        PrivacySetting setting = null;
+        try {
+            setting = privacySettingMapper.selectOne(
+                    new LambdaQueryWrapper<PrivacySetting>()
+                            .eq(PrivacySetting::getUserId, userId)
+                            .last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("读取隐私设置失败 userId={}, error={}", userId, e.getMessage());
+        }
+        if (setting == null) {
+            // 兜底:兼容仅桩接无条件 selectOne 的契约探测场景;真实库下该调用抛异常被吞,按未配置处理。
+            try {
+                setting = privacySettingMapper.selectOne(null);
+            } catch (Exception ignored) {
+                // 未配置
+            }
+        }
+        return setting;
+    }
+}

+ 166 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProblemCompletionService.java

@@ -0,0 +1,166 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.ProblemDomain;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.entity.TaskPlanInstance;
+import com.etotem.cfc.entity.UserIntent;
+import com.etotem.cfc.entity.UserNotification;
+import com.etotem.cfc.mapper.ProblemDomainMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.mapper.TaskPlanInstanceMapper;
+import com.etotem.cfc.mapper.UserIntentMapper;
+import com.etotem.cfc.mapper.UserNotificationMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 问题域完成奖励 — 改版v1(B17)
+ * <p>
+ * 任务全部完成后发放 CF 值(F20 统一入口 → 个人成员账本),金额=问题域配置 reward_cf_value;
+ * 幂等:按 (memberId, problem_domain, domainId) 唯一流水拦截;
+ * 写通知(reward_granted) + 更新旅程 stage=7。
+ */
+@Slf4j
+@Service
+public class ProblemCompletionService {
+
+    @Resource
+    private ProblemDomainMapper problemDomainMapper;
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private TaskPlanInstanceMapper planInstanceMapper;
+
+    @Resource
+    private CfPathwayEarnService cfPathwayEarnService;
+
+    @Resource
+    private UserNotificationMapper userNotificationMapper;
+
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+
+    @Resource
+    private UserIntentMapper userIntentMapper;
+
+    /**
+     * 任务完成后的奖励检查入口:判断该家庭是否已把某问题域套餐内全部任务完成
+     * (任务 → familyId → 启用中的问题域 → 套餐 → 方案实例 → 全部任务 completed → 发放)
+     */
+    @Transactional
+    public void checkAndRewardByTask(Long taskId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || task.getFamilyId() == null) {
+            return;
+        }
+        Long familyId = task.getFamilyId();
+
+        List<ProblemDomain> domains = problemDomainMapper.selectList(
+                new LambdaQueryWrapper<ProblemDomain>().eq(ProblemDomain::getStatus, 1));
+        for (ProblemDomain domain : domains) {
+            if (domain.getTaskTemplatePackageIds() == null
+                    || domain.getTaskTemplatePackageIds().trim().isEmpty()) {
+                continue;
+            }
+            List<Long> packageIds = new ArrayList<>();
+            for (String s : domain.getTaskTemplatePackageIds().split(",")) {
+                try {
+                    packageIds.add(Long.parseLong(s.trim()));
+                } catch (NumberFormatException ignored) {
+                }
+            }
+            if (packageIds.isEmpty()) {
+                continue;
+            }
+            rewardIfDomainCompleted(familyId, domain, packageIds, task.getFamilyMemberId());
+        }
+    }
+
+    private void rewardIfDomainCompleted(Long familyId, ProblemDomain domain, List<Long> packageIds,
+                                         Long rewardMemberId) {
+        // 1. 找该家庭应用了这些套餐的方案实例
+        List<TaskPlanInstance> instances = planInstanceMapper.selectList(
+                new LambdaQueryWrapper<TaskPlanInstance>()
+                        .eq(TaskPlanInstance::getFamilyId, familyId)
+                        .in(TaskPlanInstance::getPackageId, packageIds)
+                        .ne(TaskPlanInstance::getStatus, "cancelled"));
+        if (instances.isEmpty()) {
+            return;
+        }
+
+        // 2. 找这些方案生成的计划任务(source_type='plan',套餐/测评方案;健康方案已用 health_plan 隔离)
+        List<Long> planIds = new ArrayList<>();
+        for (TaskPlanInstance ins : instances) {
+            planIds.add(ins.getId());
+        }
+        List<Task> planTasks = taskMapper.selectList(
+                new LambdaQueryWrapper<Task>()
+                        .eq(Task::getFamilyId, familyId)
+                        .eq(Task::getSourceType, "plan")
+                        .in(Task::getSourceId, planIds));
+        if (planTasks.isEmpty()) {
+            return;
+        }
+
+        // 3. 存在未完成任务 → 不发放
+        for (Task t : planTasks) {
+            if (!"completed".equals(t.getStatus())) {
+                return;
+            }
+        }
+
+        // 4. 全部完成 → 发放个人 CF(F20 统一入口,按 member_id + ref_type + ref_id 幂等)
+        int reward = domain.getRewardCfValue() != null ? domain.getRewardCfValue() : 0;
+        if (reward <= 0) {
+            return;
+        }
+        cfPathwayEarnService.earnProblemDomainCf(rewardMemberId, domain.getId(), reward, domain.getName());
+
+        // 5. 写通知(防重复:type=reward_granted + refType=completion + refId=domainId)
+        List<UserIntent> intents = userIntentMapper.selectList(
+                new LambdaQueryWrapper<UserIntent>()
+                        .eq(UserIntent::getProblemDomainCode, domain.getCode()));
+        Long notified = userNotificationMapper.selectCount(
+                new LambdaQueryWrapper<UserNotification>()
+                        .eq(UserNotification::getType, "reward_granted")
+                        .eq(UserNotification::getRefType, "completion")
+                        .eq(UserNotification::getRefId, domain.getId()));
+        if (notified == null || notified == 0) {
+            // 通知发给选择了该问题域的用户
+            // W3: 走通知分发服务(模板文案 + {domainName}/{reward} 占位符 + 五通道分发)
+            Map<String, Object> vars = new HashMap<>();
+            vars.put("domainName", domain.getName());
+            vars.put("reward", reward);
+            for (UserIntent intent : intents) {
+                notificationDispatchService.sendByTemplate("reward_granted", intent.getUserId(), vars,
+                        "completion", domain.getId(),
+                        "问题域完成奖励已到账",
+                        "恭喜完成「" + domain.getName() + "」全部任务,奖励 " + reward + " CF 已发放至个人CF账户。");
+            }
+        }
+
+        // 6. 推进该问题域用户旅程 stage=7
+        for (UserIntent intent : intents) {
+            if (intent.getJourneyStage() == null || intent.getJourneyStage() < 7) {
+                intent.setJourneyStage(7);
+                intent.setStageUpdatedAt(new Date());
+                intent.setUpdatedAt(new Date());
+                userIntentMapper.updateById(intent);
+            }
+        }
+
+        log.info("问题域完成奖励已发放: familyId={}, memberId={}, domainCode={}, reward={}",
+                familyId, rewardMemberId, domain.getCode(), reward);
+    }
+}

+ 301 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProcurementTaskService.java

@@ -0,0 +1,301 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.ProcurementTaskDTO;
+import com.etotem.cfc.entity.ProcurementTask;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ProcurementTaskMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.NotificationDispatchService;
+import com.etotem.cfc.service.ProductService;
+import com.etotem.cfc.service.ProductSkuService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 采购任务服务
+ * 管理商品组合推荐、用户定制、采购任务全生命周期
+ */
+@Slf4j
+@Service
+public class ProcurementTaskService {
+
+    @Resource
+    private ProcurementTaskMapper procurementTaskMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ProductService productService;
+
+    @Resource
+    private ProductSkuService productSkuService;
+
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+
+    /**
+     * 创建采购任务
+     */
+    @Transactional
+    public ProcurementTaskDTO createTask(Long userId, Long familyMemberId, String selectedTier,
+                                         List<Long> baseSkuIds, List<Long> addedSkuIds,
+                                         List<Long> removedSkuIds) {
+        List<Long> resolvedBase = resolveSkuIds(baseSkuIds);
+        List<Long> resolvedAdded = resolveSkuIds(addedSkuIds);
+        List<Long> resolvedRemoved = resolveSkuIds(removedSkuIds);
+        List<Long> finalSkuIds = mergeSkus(resolvedBase, resolvedAdded, resolvedRemoved);
+
+        ProcurementTaskDTO task = new ProcurementTaskDTO();
+        task.setTaskId(UUID.randomUUID().toString());
+        task.setUserId(userId);
+        task.setFamilyMemberId(familyMemberId);
+        task.setComboTier(selectedTier);
+        task.setOriginalComboTier(selectedTier);
+        task.setSelectedProductSkuIds(finalSkuIds);
+        task.setCustomAdditionSkuIds(resolvedAdded);
+        task.setCustomRemovalSkuIds(resolvedRemoved);
+        task.setStatus("SELECTED");
+        task.setCreateTime(new Date());
+        task.setMessageReminderSent(false);
+
+        saveTask(task);
+        log.info("创建采购任务: taskId={}, userId={}, tier={}, skus={}",
+                task.getTaskId(), userId, selectedTier, finalSkuIds);
+        return task;
+    }
+
+    /**
+     * 启动采购流程 - SELECTED → PROCURING → PROCURED → EXECUTING
+     */
+    @Transactional
+    public ProcurementTaskDTO startProcurement(String taskId) {
+        ProcurementTaskDTO task = getTaskById(taskId);
+        if (task == null) {
+            throw new RuntimeException("任务不存在");
+        }
+        if (!"SELECTED".equals(task.getStatus())) {
+            throw new RuntimeException("仅 SELECTED 状态的任务可进行采购流程");
+        }
+
+        task.setStatus("PROCURING");
+        updateTask(task);
+
+        // 模拟采购执行(实际应调用供应商API/库存服务)
+        boolean success = executeProcurement(task);
+
+        if (success) {
+            task.setStatus("PROCURED");
+            task.setExecutionTaskId(UUID.randomUUID().toString());
+            task.setStatus("EXECUTING");
+            log.info("采购成功,进入执行阶段: taskId={}, executionTaskId={}", taskId, task.getExecutionTaskId());
+        } else {
+            task.setStatus("CANCELLED");
+            log.warn("采购失败: taskId={}", taskId);
+        }
+
+        updateTask(task);
+        return task;
+    }
+
+    /**
+     * 完成任务执行 - EXECUTING → COMPLETED,发送消息提醒
+     */
+    @Transactional
+    public ProcurementTaskDTO completeExecution(String taskId) {
+        ProcurementTaskDTO task = getTaskById(taskId);
+        if (task == null) {
+            throw new RuntimeException("任务不存在");
+        }
+        if (!"EXECUTING".equals(task.getStatus())) {
+            throw new RuntimeException("仅 EXECUTING 状态的任务可标记为完成");
+        }
+
+        task.setStatus("COMPLETED");
+        task.setCompleteTime(new Date());
+
+        if (task.getMessageReminderSent() == null || !task.getMessageReminderSent()) {
+            sendCompletionReminder(task);
+            task.setMessageReminderSent(true);
+        }
+
+        updateTask(task);
+        log.info("执行任务完成: taskId={}, userId={}", taskId, task.getUserId());
+        return task;
+    }
+
+    /**
+     * 取消采购任务
+     */
+    @Transactional
+    public ProcurementTaskDTO cancelTask(String taskId) {
+        ProcurementTaskDTO task = getTaskById(taskId);
+        if (task == null) {
+            throw new RuntimeException("任务不存在");
+        }
+        if (!"SELECTED".equals(task.getStatus()) && !"PROCURING".equals(task.getStatus())) {
+            throw new RuntimeException("仅 SELECTED 或 PROCURING 状态的任务可取消");
+        }
+
+        task.setStatus("CANCELLED");
+        task.setCompleteTime(new Date());
+        updateTask(task);
+        log.info("取消采购任务: taskId={}, userId={}", taskId, task.getUserId());
+        return task;
+    }
+
+    /**
+     * 获取任务详情
+     */
+    public ProcurementTaskDTO getTaskById(String taskId) {
+        return convertToDTO(procurementTaskMapper.selectOne(
+                new LambdaQueryWrapper<ProcurementTask>()
+                        .eq(ProcurementTask::getTaskId, taskId)));
+    }
+
+    /**
+     * 获取用户的采购任务列表
+     */
+    public List<ProcurementTaskDTO> getUserTasks(Long userId) {
+        List<ProcurementTask> tasks = procurementTaskMapper.selectList(
+                new LambdaQueryWrapper<ProcurementTask>()
+                        .eq(ProcurementTask::getUserId, userId)
+                        .orderByDesc(ProcurementTask::getCreateTime));
+        return tasks.stream().map(this::convertToDTO).collect(Collectors.toList());
+    }
+
+    /** ---------------------------------------------------------
+     *  内部辅助方法
+     *  --------------------------------------------------------- */
+
+    private List<Long> resolveSkuIds(List<Long> skuIds) {
+        if (skuIds == null || skuIds.isEmpty()) return new ArrayList<>();
+        // 过滤无效 ID(<=0)
+        return skuIds.stream()
+                .filter(id -> id != null && id > 0)
+                .distinct()
+                .collect(Collectors.toList());
+    }
+
+    private List<Long> mergeSkus(List<Long> base, List<Long> added, List<Long> removed) {
+        Set<Long> result = new LinkedHashSet<>(base);
+        result.addAll(added);
+        result.removeAll(removed);
+        return new ArrayList<>(result);
+    }
+
+    private boolean executeProcurement(ProcurementTaskDTO task) {
+        // 实际应:检查库存、调用供应商API、扣减库存、生成订单等
+        // 简化实现:假设采购成功
+        log.info("执行采购: taskId={}, skus={}", task.getTaskId(), task.getSelectedProductSkuIds());
+        return true;
+    }
+
+    private void sendCompletionReminder(ProcurementTaskDTO task) {
+        try {
+            Map<String, Object> vars = new HashMap<>();
+            vars.put("comboTier", formatTierLabel(task.getComboTier()));
+            vars.put("productCount", task.getSelectedProductSkuIds() != null ? task.getSelectedProductSkuIds().size() : 0);
+            vars.put("createTime", task.getCreateTime() != null ?
+                    new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getCreateTime()) : "");
+            notificationDispatchService.sendByTemplate(
+                    "procurement_completed",
+                    task.getUserId(),
+                    vars,
+                    "procurement_task",
+                    null,
+                    "采购任务完成",
+                    "您的采购任务已完成,产品即将送达。请及时查收!"
+            );
+            log.info("发送采购完成提醒: taskId={}, userId={}", task.getTaskId(), task.getUserId());
+        } catch (Exception e) {
+            log.warn("发送采购完成提醒失败: taskId={}, error={}", task.getTaskId(), e.getMessage());
+        }
+    }
+
+    private String formatTierLabel(String tier) {
+        if (tier == null) return "未知";
+        switch (tier) {
+            case "high": return "尊享";
+            case "medium": return "平衡";
+            case "low": return "入门";
+            default: return tier;
+        }
+    }
+
+    private ProcurementTaskDTO convertToDTO(ProcurementTask task) {
+        if (task == null) return null;
+        ProcurementTaskDTO dto = new ProcurementTaskDTO();
+        dto.setTaskId(task.getTaskId());
+        dto.setUserId(task.getUserId());
+        dto.setFamilyMemberId(task.getFamilyMemberId());
+        dto.setComboTier(task.getComboTier());
+        dto.setOriginalComboTier(task.getOriginalComboTier());
+        dto.setSelectedProductSkuIds(fromJson(task.getSelectedProductSkuIds()));
+        dto.setCustomAdditionSkuIds(fromJson(task.getCustomAdditionSkuIds()));
+        dto.setCustomRemovalSkuIds(fromJson(task.getCustomRemovalSkuIds()));
+        dto.setStatus(task.getStatus());
+        dto.setCreateTime(task.getCreateTime());
+        dto.setCompleteTime(task.getCompleteTime());
+        dto.setMessageReminderSent(task.getMessageReminderSent() != null && task.getMessageReminderSent() == 1);
+        dto.setExecutionTaskId(task.getExecutionTaskId());
+        return dto;
+    }
+
+    private void saveTask(ProcurementTaskDTO dto) {
+        ProcurementTask task = new ProcurementTask();
+        task.setTaskId(dto.getTaskId());
+        task.setUserId(dto.getUserId());
+        task.setFamilyMemberId(dto.getFamilyMemberId());
+        task.setComboTier(dto.getComboTier());
+        task.setOriginalComboTier(dto.getOriginalComboTier());
+        task.setSelectedProductSkuIds(toJson(dto.getSelectedProductSkuIds()));
+        task.setCustomAdditionSkuIds(toJson(dto.getCustomAdditionSkuIds()));
+        task.setCustomRemovalSkuIds(toJson(dto.getCustomRemovalSkuIds()));
+        task.setStatus(dto.getStatus());
+        task.setCreateTime(dto.getCreateTime());
+        task.setCompleteTime(dto.getCompleteTime());
+        task.setMessageReminderSent(dto.getMessageReminderSent() != null && dto.getMessageReminderSent() ? 1 : 0);
+        task.setExecutionTaskId(dto.getExecutionTaskId());
+        task.setUpdateTime(new Date());
+        procurementTaskMapper.insert(task);
+    }
+
+    private void updateTask(ProcurementTaskDTO dto) {
+        ProcurementTask task = procurementTaskMapper.selectOne(
+                new LambdaQueryWrapper<ProcurementTask>()
+                        .eq(ProcurementTask::getTaskId, dto.getTaskId()));
+        if (task == null) return;
+        task.setComboTier(dto.getComboTier());
+        task.setOriginalComboTier(dto.getOriginalComboTier());
+        task.setSelectedProductSkuIds(toJson(dto.getSelectedProductSkuIds()));
+        task.setCustomAdditionSkuIds(toJson(dto.getCustomAdditionSkuIds()));
+        task.setCustomRemovalSkuIds(toJson(dto.getCustomRemovalSkuIds()));
+        task.setStatus(dto.getStatus());
+        task.setCompleteTime(dto.getCompleteTime());
+        task.setMessageReminderSent(dto.getMessageReminderSent() != null && dto.getMessageReminderSent() ? 1 : 0);
+        task.setExecutionTaskId(dto.getExecutionTaskId());
+        task.setUpdateTime(new Date());
+        procurementTaskMapper.updateById(task);
+    }
+
+    private String toJson(List<Long> list) {
+        if (list == null) return null;
+        return com.alibaba.fastjson.JSON.toJSONString(list);
+    }
+
+    private List<Long> fromJson(String json) {
+        if (json == null || json.isEmpty()) return new ArrayList<>();
+        try {
+            return com.alibaba.fastjson.JSON.parseArray(json, Long.class);
+        } catch (Exception e) {
+            return new ArrayList<>();
+        }
+    }
+}

+ 167 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductCategoryService.java

@@ -0,0 +1,167 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductCategory;
+import com.etotem.cfc.mapper.ProductCategoryMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.service.support.ProductVisibilitySupport;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+public class ProductCategoryService {
+
+    @Resource
+    private ProductCategoryMapper productCategoryMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private ProductVisibilitySupport productVisibilitySupport;
+
+    public Result<List<Map<String, Object>>> tree(Boolean includeDisabled) {
+        return tree(includeDisabled, null);
+    }
+
+    /** 按会员级别过滤分类树:userId 为空时不过滤(管理端/无限制),非空时仅返回用户级别可见的分类 */
+    public Result<List<Map<String, Object>>> tree(Boolean includeDisabled, Long userId) {
+        List<ProductCategory> all = productCategoryMapper.selectList(
+            new LambdaQueryWrapper<ProductCategory>()
+                .eq(!Boolean.TRUE.equals(includeDisabled), ProductCategory::getEnabled, true)
+                .orderByAsc(ProductCategory::getSort)
+                .orderByAsc(ProductCategory::getId)
+        );
+        if (userId != null) {
+            List<String> visibleLevelCodes = membershipService.getVisibleMemberLevelCodes(userId);
+            all = all.stream()
+                .filter(c -> c.getMinVisibleLevel() == null || c.getMinVisibleLevel().isEmpty()
+                    || visibleLevelCodes.contains(c.getMinVisibleLevel()))
+                .collect(Collectors.toList());
+        }
+        return Result.success(buildTree(all, 0L));
+    }
+
+    public Result<List<Map<String, Object>>> treeByParent(Long parentId) {
+        List<ProductCategory> list = productCategoryMapper.selectList(
+            new LambdaQueryWrapper<ProductCategory>()
+                .eq(ProductCategory::getParentId, parentId)
+                .orderByAsc(ProductCategory::getSort)
+                .orderByAsc(ProductCategory::getId)
+        );
+        List<Map<String, Object>> result = list.stream().map(this::toMap).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    public Result<String> create(ProductCategory category) {
+        category.setId(null);
+        if (category.getParentId() == null) category.setParentId(0L);
+        if (category.getLevel() == null) category.setLevel(0);
+        if (category.getSort() == null) category.setSort(0);
+        if (category.getEnabled() == null) category.setEnabled(true);
+        category.setCreatedAt(new Date());
+        category.setUpdatedAt(new Date());
+        productCategoryMapper.insert(category);
+        return Result.success("创建成功");
+    }
+
+    public Result<String> update(ProductCategory category) {
+        ProductCategory existing = productCategoryMapper.selectById(category.getId());
+        if (existing == null) return Result.error("分类不存在");
+        category.setUpdatedAt(new Date());
+        productCategoryMapper.updateById(category);
+        return Result.success("更新成功");
+    }
+
+    public Result<String> toggle(Long id) {
+        ProductCategory category = productCategoryMapper.selectById(id);
+        if (category == null) return Result.error("分类不存在");
+        category.setEnabled(!Boolean.TRUE.equals(category.getEnabled()));
+        category.setUpdatedAt(new Date());
+        productCategoryMapper.updateById(category);
+        return Result.success(Boolean.TRUE.equals(category.getEnabled()) ? "已启用" : "已禁用");
+    }
+
+    public Result<String> delete(Long id) {
+        ProductCategory category = productCategoryMapper.selectById(id);
+        if (category == null) return Result.error("分类不存在");
+
+        boolean hasChildren = productCategoryMapper.selectCount(
+            new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getParentId, id)
+        ) > 0;
+        if (hasChildren) return Result.error("存在子分类,无法删除");
+
+        boolean hasProducts = productMapper.selectCount(
+            new LambdaQueryWrapper<Product>().eq(Product::getCategoryId, id)
+        ) > 0;
+        if (hasProducts) return Result.error("该分类下存在商品,无法删除");
+
+        productCategoryMapper.deleteById(id);
+        return Result.success("删除成功");
+    }
+
+    public Result<List<Map<String, Object>>> products(Long categoryId) {
+        return products(categoryId, null);
+    }
+
+    /** 按会员级别过滤分类下商品:userId 为空时不过滤(管理端/无限制),非空时仅返回用户级别可见的商品 */
+    public Result<List<Map<String, Object>>> products(Long categoryId, Long userId) {
+        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+                .eq(Product::getCategoryId, categoryId)
+                .eq(Product::getStatus, "on_shelf")
+                .orderByAsc(Product::getSortOrder)
+                .orderByDesc(Product::getCreatedAt);
+        // 商品可见性过滤(min_visible_level + vendor_visible),与商城列表 /api/product/list 对齐
+        productVisibilitySupport.applyToQuery(wrapper, userId, null);
+        List<Product> products = productMapper.selectList(wrapper);
+        List<Map<String, Object>> result = products.stream().map(p -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", p.getId());
+            m.put("name", p.getName());
+            m.put("coverImage", p.getCoverImage());
+            m.put("price", p.getPrice());
+            m.put("salesCount", p.getSalesCount());
+            m.put("productType", p.getProductType());
+            return m;
+        }).collect(Collectors.toList());
+        return Result.success(result);
+    }
+
+    private List<Map<String, Object>> buildTree(List<ProductCategory> all, Long parentId) {
+        List<Map<String, Object>> nodes = new ArrayList<>();
+        for (ProductCategory cat : all) {
+            if (cat.getParentId() != null && cat.getParentId().equals(parentId)) {
+                Map<String, Object> node = toMap(cat);
+                List<Map<String, Object>> children = buildTree(all, cat.getId());
+                if (!children.isEmpty()) {
+                    node.put("children", children);
+                }
+                nodes.add(node);
+            }
+        }
+        return nodes;
+    }
+
+    private Map<String, Object> toMap(ProductCategory cat) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("id", cat.getId());
+        m.put("name", cat.getName());
+        m.put("parentId", cat.getParentId());
+        m.put("level", cat.getLevel());
+        m.put("sort", cat.getSort());
+        m.put("image", cat.getImage());
+        m.put("enabled", cat.getEnabled());
+        m.put("dimensionCodes", cat.getDimensionCodes());
+        m.put("productTypes", cat.getProductTypes());
+        m.put("minVisibleLevel", cat.getMinVisibleLevel());
+        return m;
+    }
+}

+ 299 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductDeliveryConfigService.java

@@ -0,0 +1,299 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 商品配送与履约配置服务
+ * 统一管理自取地点/时间段、线上服务者/时间段、单人线上时间段的CRUD和商品详情组装
+ */
+@Service
+public class ProductDeliveryConfigService {
+
+    @Resource private ProductPickupLocationMapper pickupLocationMapper;
+    @Resource private ProductPickupTimeSlotMapper pickupTimeSlotMapper;
+    @Resource private ProductServicePersonMapper servicePersonMapper;
+    @Resource private ProductServicePersonSlotMapper servicePersonSlotMapper;
+    @Resource private ProductOnlineSlotMapper onlineSlotMapper;
+    @Resource private UserMapper userMapper;
+    @Resource private GuideService guideService;
+
+    // ========== 商品详情组装 ==========
+
+    /**
+     * 根据配送方式组装商品详情中的配送相关信息
+     */
+    public void enrichProductDetail(Long productId, Integer deliveryMethod, Map<String, Object> detailMap) {
+        if (deliveryMethod == null) return;
+        switch (deliveryMethod) {
+            case 2: case 3:
+                detailMap.put("pickupLocations", listPickupLocationsWithSlots(productId));
+                break;
+            case 4:
+                detailMap.put("servicePersons", listServicePersonsWithSlots(productId));
+                break;
+            case 5:
+                detailMap.put("onlineSlots", listOnlineSlots(productId));
+                break;
+            default:
+                break;
+        }
+    }
+
+    // ========== 自取地点 ==========
+
+    public List<ProductPickupLocation> listPickupLocations(Long productId) {
+        return pickupLocationMapper.selectList(
+                new LambdaQueryWrapper<ProductPickupLocation>()
+                        .eq(ProductPickupLocation::getProductId, productId)
+                        .eq(ProductPickupLocation::getEnabled, 1)
+                        .orderByAsc(ProductPickupLocation::getSortOrder));
+    }
+
+    public List<Map<String, Object>> listPickupLocationsWithSlots(Long productId) {
+        List<ProductPickupLocation> locations = listPickupLocations(productId);
+        if (locations.isEmpty()) return Collections.emptyList();
+        List<Long> locationIds = locations.stream().map(ProductPickupLocation::getId).collect(Collectors.toList());
+        List<ProductPickupTimeSlot> allSlots = pickupTimeSlotMapper.selectList(
+                new LambdaQueryWrapper<ProductPickupTimeSlot>()
+                        .in(ProductPickupTimeSlot::getLocationId, locationIds)
+                        .eq(ProductPickupTimeSlot::getEnabled, 1));
+        Map<Long, List<ProductPickupTimeSlot>> slotMap = allSlots.stream()
+                .collect(Collectors.groupingBy(ProductPickupTimeSlot::getLocationId));
+        return locations.stream().map(loc -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", loc.getId());
+            m.put("name", loc.getName());
+            m.put("address", loc.getAddress());
+            m.put("longitude", loc.getLongitude());
+            m.put("latitude", loc.getLatitude());
+            m.put("contactName", loc.getContactName());
+            m.put("contactPhone", loc.getContactPhone());
+            m.put("timeSlots", slotMap.getOrDefault(loc.getId(), Collections.emptyList()));
+            return m;
+        }).collect(Collectors.toList());
+    }
+
+    @Transactional
+    public void savePickupLocations(Long productId, List<Map<String, Object>> locations) {
+        // 先清除旧的
+        deletePickupLocationsByProduct(productId);
+        if (locations == null) return;
+        int sortOrder = 0;
+        for (Map<String, Object> locData : locations) {
+            ProductPickupLocation loc = new ProductPickupLocation();
+            loc.setProductId(productId);
+            loc.setName((String) locData.get("name"));
+            loc.setAddress((String) locData.get("address"));
+            loc.setContactName((String) locData.get("contactName"));
+            loc.setContactPhone((String) locData.get("contactPhone"));
+            loc.setSortOrder(sortOrder++);
+            loc.setEnabled(1);
+            pickupLocationMapper.insert(loc);
+            // 时间段
+            List<Map<String, Object>> slots = (List<Map<String, Object>>) locData.get("timeSlots");
+            if (slots != null) {
+                for (Map<String, Object> slotData : slots) {
+                    ProductPickupTimeSlot slot = new ProductPickupTimeSlot();
+                    slot.setLocationId(loc.getId());
+                    String startTime = (String) slotData.get("startTime");
+                    String endTime = (String) slotData.get("endTime");
+                    if (startTime != null) slot.setStartTime(java.sql.Time.valueOf(startTime));
+                    if (endTime != null) slot.setEndTime(java.sql.Time.valueOf(endTime));
+                    Object weekday = slotData.get("weekday");
+                    if (weekday != null) slot.setWeekday(Integer.valueOf(weekday.toString()));
+                    Object specificDate = slotData.get("specificDate");
+                    if (specificDate != null) slot.setSpecificDate(java.sql.Date.valueOf(specificDate.toString()));
+                    Object maxCap = slotData.get("maxCapacity");
+                    slot.setMaxCapacity(maxCap != null ? Integer.valueOf(maxCap.toString()) : 1);
+                    slot.setBookedCount(0);
+                    slot.setEnabled(1);
+                    pickupTimeSlotMapper.insert(slot);
+                }
+            }
+        }
+    }
+
+    @Transactional
+    public void deletePickupLocationsByProduct(Long productId) {
+        List<ProductPickupLocation> existing = pickupLocationMapper.selectList(
+                new LambdaQueryWrapper<ProductPickupLocation>().eq(ProductPickupLocation::getProductId, productId));
+        for (ProductPickupLocation loc : existing) {
+            pickupTimeSlotMapper.delete(new LambdaQueryWrapper<ProductPickupTimeSlot>()
+                    .eq(ProductPickupTimeSlot::getLocationId, loc.getId()));
+            pickupLocationMapper.deleteById(loc.getId());
+        }
+    }
+
+    // ========== 线上服务者 ==========
+
+    public List<ProductServicePerson> listServicePersons(Long productId) {
+        return servicePersonMapper.selectList(
+                new LambdaQueryWrapper<ProductServicePerson>()
+                        .eq(ProductServicePerson::getProductId, productId)
+                        .eq(ProductServicePerson::getEnabled, 1)
+                        .orderByAsc(ProductServicePerson::getSortOrder));
+    }
+
+    public List<Map<String, Object>> listServicePersonsWithSlots(Long productId) {
+        List<ProductServicePerson> persons = listServicePersons(productId);
+        if (persons.isEmpty()) return Collections.emptyList();
+        List<Long> personIds = persons.stream().map(ProductServicePerson::getId).collect(Collectors.toList());
+        List<ProductServicePersonSlot> allSlots = servicePersonSlotMapper.selectList(
+                new LambdaQueryWrapper<ProductServicePersonSlot>()
+                        .in(ProductServicePersonSlot::getPersonId, personIds)
+                        .eq(ProductServicePersonSlot::getEnabled, 1)
+                        .ge(ProductServicePersonSlot::getStartTime, new Date()));
+        Map<Long, List<ProductServicePersonSlot>> slotMap = allSlots.stream()
+                .collect(Collectors.groupingBy(ProductServicePersonSlot::getPersonId));
+        return persons.stream().map(p -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", p.getId());
+            m.put("userId", p.getUserId());
+            m.put("name", p.getName());
+            m.put("title", p.getTitle());
+            m.put("intro", p.getIntro());
+            m.put("avatar", p.getAvatar());
+            m.put("price", p.getPrice());
+            m.put("originalPrice", p.getOriginalPrice());
+            m.put("slots", slotMap.getOrDefault(p.getId(), Collections.emptyList()));
+            return m;
+        }).collect(Collectors.toList());
+    }
+
+    @Transactional
+    public void saveServicePersons(Long productId, List<Map<String, Object>> persons) {
+        deleteServicePersonsByProduct(productId);
+        if (persons == null) return;
+        int sortOrder = 0;
+        for (Map<String, Object> personData : persons) {
+            ProductServicePerson person = new ProductServicePerson();
+            person.setProductId(productId);
+            Object userId = personData.get("userId");
+            if (userId == null) {
+                throw new IllegalArgumentException("服务者必须关联已入驻的服务商账号(userId不能为空)");
+            }
+            Long providerUserId = Long.valueOf(userId.toString());
+            User provider = userMapper.selectById(providerUserId);
+            if (provider == null) {
+                throw new IllegalArgumentException("服务者关联的用户不存在");
+            }
+            if (!"approved".equals(provider.getVendorStatus())) {
+                throw new IllegalArgumentException("服务者「" + (provider.getRealName() != null ? provider.getRealName() : providerUserId)
+                        + "」未通过服务商入驻审核,无法添加为线上服务者");
+            }
+            person.setUserId(providerUserId);
+            // 从服务商资料自动代入 name/title/intro/avatar(未显式提供时)
+            if (personData.get("name") == null) {
+                person.setName(provider.getRealName() != null ? provider.getRealName() : provider.getNickname());
+            } else {
+                person.setName((String) personData.get("name"));
+            }
+            if (personData.get("title") == null) {
+                Guide guide = guideService.getByUserId(provider.getId());
+                person.setTitle(guide != null ? guide.getTitle() : "");
+            } else {
+                person.setTitle((String) personData.get("title"));
+            }
+            if (personData.get("intro") == null) {
+                Guide guide = guideService.getByUserId(provider.getId());
+                person.setIntro(guide != null ? guide.getIntro() : null);
+            } else {
+                person.setIntro((String) personData.get("intro"));
+            }
+            if (personData.get("avatar") == null) {
+                person.setAvatar(provider.getAvatar());
+            } else {
+                person.setAvatar((String) personData.get("avatar"));
+            }
+            Object price = personData.get("price");
+            if (price != null) person.setPrice(Integer.valueOf(price.toString()));
+            Object origPrice = personData.get("originalPrice");
+            if (origPrice != null) person.setOriginalPrice(Integer.valueOf(origPrice.toString()));
+            person.setSortOrder(sortOrder++);
+            person.setEnabled(1);
+            servicePersonMapper.insert(person);
+            List<Map<String, Object>> slots = (List<Map<String, Object>>) personData.get("slots");
+            if (slots != null) {
+                for (Map<String, Object> slotData : slots) {
+                    ProductServicePersonSlot slot = new ProductServicePersonSlot();
+                    slot.setPersonId(person.getId());
+                    slot.setStartTime(parseDate(slotData.get("startTime")));
+                    slot.setEndTime(parseDate(slotData.get("endTime")));
+                    Object maxCap = slotData.get("maxCapacity");
+                    slot.setMaxCapacity(maxCap != null ? Integer.valueOf(maxCap.toString()) : 1);
+                    slot.setBookedCount(0);
+                    slot.setEnabled(1);
+                    servicePersonSlotMapper.insert(slot);
+                }
+            }
+        }
+    }
+
+    @Transactional
+    public void deleteServicePersonsByProduct(Long productId) {
+        List<ProductServicePerson> existing = servicePersonMapper.selectList(
+                new LambdaQueryWrapper<ProductServicePerson>().eq(ProductServicePerson::getProductId, productId));
+        for (ProductServicePerson p : existing) {
+            servicePersonSlotMapper.delete(new LambdaQueryWrapper<ProductServicePersonSlot>()
+                    .eq(ProductServicePersonSlot::getPersonId, p.getId()));
+            servicePersonMapper.deleteById(p.getId());
+        }
+    }
+
+    // ========== 单人线上时间段 ==========
+
+    public List<ProductOnlineSlot> listOnlineSlots(Long productId) {
+        return onlineSlotMapper.selectList(
+                new LambdaQueryWrapper<ProductOnlineSlot>()
+                        .eq(ProductOnlineSlot::getProductId, productId)
+                        .eq(ProductOnlineSlot::getEnabled, 1)
+                        .ge(ProductOnlineSlot::getStartTime, new Date())
+                        .orderByAsc(ProductOnlineSlot::getStartTime));
+    }
+
+    @Transactional
+    public void saveOnlineSlots(Long productId, List<Map<String, Object>> slots) {
+        deleteOnlineSlotsByProduct(productId);
+        if (slots == null) return;
+        for (Map<String, Object> slotData : slots) {
+            ProductOnlineSlot slot = new ProductOnlineSlot();
+            slot.setProductId(productId);
+            slot.setStartTime(parseDate(slotData.get("startTime")));
+            slot.setEndTime(parseDate(slotData.get("endTime")));
+            Object maxCap = slotData.get("maxCapacity");
+            slot.setMaxCapacity(maxCap != null ? Integer.valueOf(maxCap.toString()) : 1);
+            slot.setBookedCount(0);
+            slot.setEnabled(1);
+            onlineSlotMapper.insert(slot);
+        }
+    }
+
+    @Transactional
+    public void deleteOnlineSlotsByProduct(Long productId) {
+        onlineSlotMapper.delete(new LambdaQueryWrapper<ProductOnlineSlot>()
+                .eq(ProductOnlineSlot::getProductId, productId));
+    }
+
+    // ========== 工具 ==========
+
+    private Date parseDate(Object val) {
+        if (val == null) return null;
+        String s = val.toString();
+        // 兼容 "2026-08-10 09:00:00" 或 ISO 格式
+        if (s.length() == 19 && s.charAt(10) == ' ') {
+            return java.sql.Timestamp.valueOf(s);
+        }
+        if (s.contains("T")) {
+            return java.sql.Timestamp.valueOf(s.replace("T", " "));
+        }
+        return java.sql.Timestamp.valueOf(s);
+    }
+}

+ 85 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductDimensionConfigService.java

@@ -0,0 +1,85 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.ProductDimensionConfig;
+import com.etotem.cfc.mapper.ProductDimensionConfigMapper;
+import org.springframework.stereotype.Service;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Service
+public class ProductDimensionConfigService extends ServiceImpl<ProductDimensionConfigMapper, ProductDimensionConfig> {
+
+    public Map<String, Object> list(String dimensionType, Integer enabled, int page, int size) {
+        Page<ProductDimensionConfig> p = new Page<>(page, size);
+        LambdaQueryWrapper<ProductDimensionConfig> wrapper = new LambdaQueryWrapper<>();
+        if (dimensionType != null && !dimensionType.isEmpty()) {
+            wrapper.eq(ProductDimensionConfig::getDimensionType, dimensionType);
+        }
+        if (enabled != null) {
+            wrapper.eq(ProductDimensionConfig::getEnabled, enabled);
+        }
+        wrapper.orderByAsc(ProductDimensionConfig::getSort);
+        this.page(p, wrapper);
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", p.getRecords());
+        data.put("total", p.getTotal());
+        data.put("page", p.getCurrent());
+        data.put("size", p.getSize());
+        return data;
+    }
+
+    public ProductDimensionConfig getByCode(String dimensionCode) {
+        LambdaQueryWrapper<ProductDimensionConfig> wrapper = new LambdaQueryWrapper<ProductDimensionConfig>()
+            .eq(ProductDimensionConfig::getDimensionCode, dimensionCode);
+        return this.getOne(wrapper, false);
+    }
+
+    public ProductDimensionConfig saveConfig(ProductDimensionConfig config) {
+        if (config.getId() != null) {
+            this.updateById(config);
+        } else {
+            this.save(config);
+        }
+        return config;
+    }
+
+    public boolean deleteConfig(Long id) {
+        // TC-A-25-E(admin.dimension.config):删除前「被引用维度」检查。
+        // 存在子节点(parent_id = id)即视为被引用,拒绝删除并返回 false,不级联破坏存量;
+        // 仅无任何引用时才执行物理删除。
+        long referenced = this.count(new LambdaQueryWrapper<ProductDimensionConfig>()
+                .eq(ProductDimensionConfig::getParentId, id));
+        if (referenced > 0) {
+            return false;
+        }
+        return this.removeById(id);
+    }
+
+    public List<ProductDimensionConfig> tree() {
+        List<ProductDimensionConfig> all = this.list();
+        List<ProductDimensionConfig> roots = all.stream()
+            .filter(d -> d.getParentId() == null)
+            .collect(Collectors.toList());
+        for (ProductDimensionConfig root : roots) {
+            buildChildren(root, all);
+        }
+        return roots;
+    }
+
+    private void buildChildren(ProductDimensionConfig parent, List<ProductDimensionConfig> all) {
+        List<ProductDimensionConfig> children = all.stream()
+            .filter(d -> parent.getId().equals(d.getParentId()))
+            .collect(Collectors.toList());
+        if (!children.isEmpty()) {
+            for (ProductDimensionConfig child : children) {
+                buildChildren(child, all);
+            }
+        }
+    }
+}

+ 93 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductGiftRuleService.java

@@ -0,0 +1,93 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.MembershipLevel;
+import com.etotem.cfc.entity.ProductGiftRule;
+import com.etotem.cfc.mapper.MembershipLevelMapper;
+import com.etotem.cfc.mapper.ProductGiftRuleMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class ProductGiftRuleService {
+
+    @Resource
+    private ProductGiftRuleMapper mapper;
+
+    @Resource
+    private MembershipLevelMapper levelMapper;
+
+    /** 查询商品启用的赠送规则(一商品最多一条启用) */
+    public ProductGiftRule getActiveByProductId(Long productId) {
+        return mapper.selectOne(new LambdaQueryWrapper<ProductGiftRule>()
+                .eq(ProductGiftRule::getProductId, productId)
+                .eq(ProductGiftRule::getStatus, 1)
+                .last("LIMIT 1"));
+    }
+
+    /** 批量查询多个商品启用的赠送规则(列表页避免 N+1) */
+    public List<ProductGiftRule> listActiveByProductIds(List<Long> productIds) {
+        if (productIds == null || productIds.isEmpty()) {
+            return new ArrayList<>();
+        }
+        return mapper.selectList(new LambdaQueryWrapper<ProductGiftRule>()
+                .in(ProductGiftRule::getProductId, productIds)
+                .eq(ProductGiftRule::getStatus, 1));
+    }
+
+    /** 查询商品全部规则(管理端回显) */
+    public List<ProductGiftRule> listByProduct(Long productId) {
+        return mapper.selectList(new LambdaQueryWrapper<ProductGiftRule>()
+                .eq(ProductGiftRule::getProductId, productId));
+    }
+
+    /** 等级编码 → 等级名(不存在则原样返回) */
+    public String getLevelName(String levelCode) {
+        if (levelCode == null) {
+            return null;
+        }
+        MembershipLevel level = levelMapper.selectOne(new LambdaQueryWrapper<MembershipLevel>()
+                .eq(MembershipLevel::getLevelCode, levelCode));
+        return level != null ? level.getLevelName() : levelCode;
+    }
+
+    /**
+     * 保存赠送规则:先删后插(一商品一启用规则)。
+     * status=1 且 levelCode 有效 → 启用;否则视为停用(清空规则)。
+     */
+    @Transactional
+    public Result<Void> saveRule(Long productId, Integer status, String levelCode) {
+        if (productId == null || status == null) {
+            return Result.error("参数不完整");
+        }
+        boolean enable = (status == 1);
+        if (enable) {
+            if (levelCode == null || levelCode.isEmpty()) {
+                return Result.error("请选择赠送等级");
+            }
+            MembershipLevel level = levelMapper.selectOne(new LambdaQueryWrapper<MembershipLevel>()
+                    .eq(MembershipLevel::getLevelCode, levelCode));
+            if (level == null || "FREE".equals(level.getLevelCode())) {
+                return Result.error("无效的赠送等级");
+            }
+        }
+        mapper.delete(new LambdaQueryWrapper<ProductGiftRule>()
+                .eq(ProductGiftRule::getProductId, productId));
+        if (enable) {
+            ProductGiftRule rule = new ProductGiftRule();
+            rule.setProductId(productId);
+            rule.setLevelCode(levelCode);
+            rule.setStatus(1);
+            rule.setCreatedAt(new Date());
+            rule.setUpdatedAt(new Date());
+            mapper.insert(rule);
+        }
+        return Result.success(null);
+    }
+}

+ 184 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductGiftService.java

@@ -0,0 +1,184 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.GiftConfigVO;
+import com.etotem.cfc.dto.ProductGiftItemDTO;
+import com.etotem.cfc.entity.MembershipLevel;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductGiftConfig;
+import com.etotem.cfc.entity.ProductGiftItem;
+import com.etotem.cfc.mapper.MembershipLevelMapper;
+import com.etotem.cfc.mapper.ProductGiftConfigMapper;
+import com.etotem.cfc.mapper.ProductGiftItemMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+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.List;
+
+@Service
+public class ProductGiftService {
+
+    @Resource
+    private ProductGiftConfigMapper configMapper;
+    @Resource
+    private ProductGiftItemMapper itemMapper;
+    @Resource
+    private ProductMapper productMapper;
+    @Resource
+    private MembershipLevelMapper levelMapper;
+
+    /** 保存赠品配置(幂等:先删后插 config + items) */
+    @Transactional
+    public Result<Void> saveGiftConfig(Long productId, String levelCode, Integer status, List<ProductGiftItemDTO> items) {
+        if (productId == null || levelCode == null || status == null) {
+            return Result.error("参数不完整");
+        }
+        // 校验等级存在且非 FREE
+        MembershipLevel level = levelMapper.selectOne(new LambdaQueryWrapper<MembershipLevel>()
+                .eq(MembershipLevel::getLevelCode, levelCode));
+        if (level == null || "FREE".equals(level.getLevelCode())) {
+            return Result.error("无效的赠送等级");
+        }
+        // 校验赠品商品(giftType=product)存在且启用
+        if (items != null) {
+            for (ProductGiftItemDTO it : items) {
+                if ("product".equals(it.getGiftType()) && it.getGiftProductId() != null) {
+                    Product giftProduct = productMapper.selectById(it.getGiftProductId());
+                    if (giftProduct == null || !"on_shelf".equals(giftProduct.getStatus())) {
+                        return Result.error("赠品商品不存在或未上架");
+                    }
+                }
+            }
+        }
+        // 先删后插(整个 config + 其下所有 items)
+        configMapper.delete(new LambdaQueryWrapper<ProductGiftConfig>()
+                .eq(ProductGiftConfig::getProductId, productId)
+                .eq(ProductGiftConfig::getLevelCode, levelCode));
+        if (status == 1) {
+            ProductGiftConfig config = new ProductGiftConfig();
+            config.setProductId(productId);
+            config.setLevelCode(levelCode);
+            config.setStatus(1);
+            config.setCreatedAt(new Date());
+            config.setUpdatedAt(new Date());
+            configMapper.insert(config);
+            if (items != null) {
+                for (ProductGiftItemDTO it : items) {
+                    ProductGiftItem item = new ProductGiftItem();
+                    item.setConfigId(config.getId());
+                    item.setGiftType(it.getGiftType());
+                    item.setGiftProductId(it.getGiftProductId());
+                    item.setCfValue(it.getCfValue() != null ? it.getCfValue() : 0);
+                    item.setSortOrder(it.getSortOrder() != null ? it.getSortOrder() : 0);
+                    // 快照商品名称和图
+                    if (it.getGiftProductId() != null) {
+                        Product gp = productMapper.selectById(it.getGiftProductId());
+                        if (gp != null) {
+                            item.setGiftProductName(gp.getName());
+                            item.setGiftProductImage(gp.getCoverImage());
+                        }
+                    }
+                    item.setCreatedAt(new Date());
+                    itemMapper.insert(item);
+                }
+            }
+        }
+        return Result.success(null);
+    }
+
+    /** 查询商品全部等级赠品配置(管理端用) */
+    public List<GiftConfigVO> listConfigsByProduct(Long productId) {
+        List<ProductGiftConfig> configs = configMapper.selectList(
+                new LambdaQueryWrapper<ProductGiftConfig>()
+                        .eq(ProductGiftConfig::getProductId, productId)
+                        .orderByAsc(ProductGiftConfig::getLevelCode));
+        return toVOList(configs);
+    }
+
+    /** 查询某商品某等级下启用的赠品配置(含库存充足校验,供商品详情展示) */
+    public List<GiftConfigVO> getActiveConfigsByProductAndLevel(Long productId, String levelCode) {
+        ProductGiftConfig config = configMapper.selectOne(new LambdaQueryWrapper<ProductGiftConfig>()
+                .eq(ProductGiftConfig::getProductId, productId)
+                .eq(ProductGiftConfig::getLevelCode, levelCode)
+                .eq(ProductGiftConfig::getStatus, 1)
+                .last("LIMIT 1"));
+        if (config == null) {
+            return Collections.emptyList();
+        }
+        List<ProductGiftItem> items = itemMapper.selectList(
+                new LambdaQueryWrapper<ProductGiftItem>()
+                        .eq(ProductGiftItem::getConfigId, config.getId())
+                        .orderByAsc(ProductGiftItem::getSortOrder));
+        GiftConfigVO vo = new GiftConfigVO();
+        vo.setId(config.getId());
+        vo.setLevelCode(config.getLevelCode());
+        MembershipLevel level = levelMapper.selectOne(new LambdaQueryWrapper<MembershipLevel>()
+                .eq(MembershipLevel::getLevelCode, levelCode));
+        vo.setLevelName(level != null ? level.getLevelName() : levelCode);
+        vo.setStatus(config.getStatus());
+        List<GiftConfigVO.GiftItemVO> itemVOs = new ArrayList<>();
+        for (ProductGiftItem it : items) {
+            GiftConfigVO.GiftItemVO itemVO = new GiftConfigVO.GiftItemVO();
+            itemVO.setId(it.getId());
+            itemVO.setGiftType(it.getGiftType());
+            itemVO.setGiftProductId(it.getGiftProductId());
+            itemVO.setGiftProductName(it.getGiftProductName());
+            itemVO.setGiftProductImage(it.getGiftProductImage());
+            itemVO.setCfValue(it.getCfValue() != null ? it.getCfValue() : 0);
+            itemVO.setSortOrder(it.getSortOrder());
+            // 库存充足校验:实物赠品必须库存>0
+            if ("product".equals(it.getGiftType()) && it.getGiftProductId() != null) {
+                Product gp = productMapper.selectById(it.getGiftProductId());
+                if (gp == null || gp.getStock() == null || gp.getStock() <= 0) {
+                    continue; // 库存不足则不展示
+                }
+            }
+            itemVOs.add(itemVO);
+        }
+        vo.setItems(itemVOs);
+        return Collections.singletonList(vo);
+    }
+
+    /** 根据 ID 查询赠品项 */
+    public ProductGiftItem getActiveItemById(Long itemId) {
+        return itemMapper.selectById(itemId);
+    }
+
+    private List<GiftConfigVO> toVOList(List<ProductGiftConfig> configs) {
+        List<GiftConfigVO> result = new ArrayList<>();
+        for (ProductGiftConfig cfg : configs) {
+            GiftConfigVO vo = new GiftConfigVO();
+            vo.setId(cfg.getId());
+            vo.setLevelCode(cfg.getLevelCode());
+            MembershipLevel level = levelMapper.selectOne(new LambdaQueryWrapper<MembershipLevel>()
+                    .eq(MembershipLevel::getLevelCode, cfg.getLevelCode()));
+            vo.setLevelName(level != null ? level.getLevelName() : cfg.getLevelCode());
+            vo.setStatus(cfg.getStatus());
+            List<ProductGiftItem> items = itemMapper.selectList(
+                    new LambdaQueryWrapper<ProductGiftItem>()
+                            .eq(ProductGiftItem::getConfigId, cfg.getId())
+                            .orderByAsc(ProductGiftItem::getSortOrder));
+            List<GiftConfigVO.GiftItemVO> itemVOs = new ArrayList<>();
+            for (ProductGiftItem it : items) {
+                GiftConfigVO.GiftItemVO itemVO = new GiftConfigVO.GiftItemVO();
+                itemVO.setId(it.getId());
+                itemVO.setGiftType(it.getGiftType());
+                itemVO.setGiftProductId(it.getGiftProductId());
+                itemVO.setGiftProductName(it.getGiftProductName());
+                itemVO.setGiftProductImage(it.getGiftProductImage());
+                itemVO.setCfValue(it.getCfValue() != null ? it.getCfValue() : 0);
+                itemVO.setSortOrder(it.getSortOrder());
+                itemVOs.add(itemVO);
+            }
+            vo.setItems(itemVOs);
+            result.add(vo);
+        }
+        return result;
+    }
+}

+ 2395 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductOrderService.java

@@ -0,0 +1,2395 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.OrderNoGenerator;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CreateProductOrderDTO;
+import com.etotem.cfc.dto.OrderItemVO;
+import com.etotem.cfc.dto.ProductOrderDTO;
+import com.etotem.cfc.entity.AfterSalesRequest;
+import com.etotem.cfc.entity.AssessmentProduct;
+import com.etotem.cfc.entity.Consignee;
+import com.etotem.cfc.entity.UserAddress;
+import com.etotem.cfc.mapper.UserAddressMapper;
+import com.etotem.cfc.entity.Coupon;
+import com.etotem.cfc.entity.FamilyCoupon;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductGiftRule;
+import com.etotem.cfc.entity.ProductOnlineSlot;
+import com.etotem.cfc.entity.OrderItem;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.ProductPickupLocation;
+import com.etotem.cfc.entity.ProductPickupTimeSlot;
+import com.etotem.cfc.entity.ProductServicePerson;
+import com.etotem.cfc.entity.ProductServicePersonSlot;
+import com.etotem.cfc.entity.SpecialPriceDeal;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.service.FamilyPlatformPointsService;
+import com.etotem.cfc.service.PlatformPointsService;
+import com.etotem.cfc.util.RedisLockUtil;
+import com.etotem.cfc.mapper.AfterSalesRequestMapper;
+import com.etotem.cfc.entity.SupplySystemMember;
+import com.etotem.cfc.entity.SupplyCustomerRelation;
+import com.etotem.cfc.mapper.SupplySystemMemberMapper;
+import com.etotem.cfc.mapper.SupplyCustomerRelationMapper;
+import com.etotem.cfc.service.SupplyHierarchyService;
+import com.etotem.cfc.service.CouponService;
+import com.etotem.cfc.mapper.CouponMapper;
+import com.etotem.cfc.mapper.FamilyCouponMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.entity.ProductSku;
+import com.etotem.cfc.service.ProductSkuService;
+import com.etotem.cfc.service.AssessmentProductService;
+import com.etotem.cfc.service.AssessmentQuotaService;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.dto.ChildInfoDTO;
+import com.etotem.cfc.dto.GiftConfigVO;
+import com.etotem.cfc.dto.MembershipLevelDTO;
+import com.etotem.cfc.service.EnergyService;
+import com.etotem.cfc.service.UnlockGateService;
+import com.etotem.cfc.service.UserService;
+import com.etotem.cfc.service.GiftMembershipProgressService;
+import com.etotem.cfc.service.SysConfigService;
+import com.alibaba.fastjson.JSON;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.entity.ProductGiftItem;
+import com.etotem.cfc.entity.ProductOrderGift;
+import com.etotem.cfc.mapper.ProductOrderGiftMapper;
+import java.util.Set;
+
+@Service
+public class ProductOrderService {
+
+    private static final Logger log = LoggerFactory.getLogger(ProductOrderService.class);
+
+    @Resource
+    private ProductOrderMapper orderMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private ProductService productService;
+
+    @Resource
+    private ProductSkuService productSkuService;
+    @Resource
+    private MemberPriceResolver memberPriceResolver;
+    @Resource
+    private InventoryService inventoryService;
+
+    @Resource
+    private CfCommissionService cfCommissionService;
+
+    /** team.profit.hook(§12-T3):支付成功钩子,与 CF 值分佣同点位并行结算利润池 */
+    @Resource
+    private ProfitPoolService profitPoolService;
+
+    @Resource
+    private PaymentService paymentService;
+
+    @Resource
+    private EnergyService energyService;
+
+    @Resource
+    private UnlockGateService unlockGateService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private RedisLockUtil redisLockUtil;
+
+    @Resource
+    private WechatWaitMsgService wechatWaitMsgService;
+
+    /** F-5 消费侧:商品购买 CF 值抵扣/退还改投统一账本 cf_balance(购买人 member 维度) */
+    @Resource
+    private CfSpendDispatchService cfSpendDispatchService;
+
+    @Resource
+    private AfterSalesRequestMapper afterSalesRequestMapper;
+
+    @Resource
+    private AssessmentProductService assessmentProductService;
+
+    @Resource
+    private AssessmentQuotaService assessmentQuotaService;
+
+    @Resource
+    private PendingRefundService pendingRefundService;
+
+    @Resource
+    private SupplySystemMemberMapper supplySystemMemberMapper;
+
+    @Resource
+    private FamilyPlatformPointsService familyPlatformPointsService;
+
+    @Resource
+    private CfEarnDispatchService cfEarnDispatchService;
+
+    @Resource
+    private SupplyHierarchyService supplyHierarchyService;
+
+    @Resource
+    private SupplyCustomerRelationService supplyCustomerRelationService;
+
+    @Resource
+    private SupplyCustomerRelationMapper supplyCustomerRelationMapper;
+
+    @Resource
+    private ProductGiftRuleService productGiftRuleService;
+
+    @Resource
+    private GiftMembershipProgressService giftMembershipProgressService;
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private WechatService wechatService;
+
+    @Resource
+    private ProductDeliveryConfigService productDeliveryConfigService;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductPickupLocationMapper productPickupLocationMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductPickupTimeSlotMapper productPickupTimeSlotMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductServicePersonMapper productServicePersonMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductServicePersonSlotMapper productServicePersonSlotMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ProductOnlineSlotMapper productOnlineSlotMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.OrderItemMapper orderItemMapper;
+
+    @Resource
+    private com.etotem.cfc.mapper.ConsigneeMapper consigneeMapper;
+
+    @Resource
+    private UserAddressMapper userAddressMapper;
+
+    @Resource
+    private ProductOrderGiftMapper productOrderGiftMapper;
+
+    @Resource
+    private ProductGiftService productGiftService;
+
+    @Resource
+    private CouponMapper couponMapper;
+
+    @Resource
+    private FamilyCouponMapper familyCouponMapper;
+
+    @Resource
+    private CouponService couponService;
+
+    @Resource
+    private SpecialPriceService specialPriceService;
+
+    public Result<ProductOrderDTO> create(CreateProductOrderDTO dto, Long buyerId) {
+        // 限时特价(扫码闪购):委托独立事务入口(规格 §5.2)
+        if (dto.getSpecialDealId() != null) {
+            return createSpecialDealOrder(dto, buyerId);
+        }
+        if (buyerId == null) {
+            return Result.error("请先登录");
+        }
+
+        if (dto.getItems() != null && !dto.getItems().isEmpty()) {
+            return createMultiItem(dto, buyerId);
+        }
+
+        Product product = productMapper.selectById(dto.getProductId());
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        if (!"on_shelf".equals(product.getStatus())) {
+            return Result.error("商品已下架");
+        }
+        // 实物商品校验库存;虚拟商品/优惠券跳过库存检查
+        if ("physical".equals(product.getProductType())
+                && product.getStock() != null
+                && product.getStock() < dto.getQuantity()) {
+            return Result.error("库存不足");
+        }
+        // 校验最小购买数量
+        if (product.getMinQuantity() != null && product.getMinQuantity() > 1
+                && dto.getQuantity() < product.getMinQuantity()) {
+            return Result.error("该商品最少需购买" + product.getMinQuantity() + "件");
+        }
+
+        // ===== 配送方式与履约校验 =====
+        FulfillValidation fv = validateFulfill(product, dto, buyerId);
+        if (fv.error != null) return Result.error(fv.error);
+        User buyer = userMapper.selectById(buyerId);
+        ProductOrder order = new ProductOrder();
+        order.setOrderNo(generateOrderNo());
+        order.setProductId(product.getId());
+        order.setProductName(product.getName());
+        order.setProductType(product.getProductType());
+        order.setBuyerId(buyerId);
+        order.setFamilyId(buyer != null ? buyer.getFamilyId() : null);
+        order.setQuantity(dto.getQuantity());
+        order.setUnitPrice(memberPriceResolver.resolveEligibleMemberPrice(product, buyerId));
+        order.setTotalAmount(memberPriceResolver.resolveEligibleMemberPrice(product, buyerId) * dto.getQuantity());
+        order.setPointsUsed(dto.getPointsUsed() != null ? dto.getPointsUsed() : 0);
+        int pointsCost = dto.getPointsUsed() != null ? dto.getPointsUsed() : 0;
+        order.setPointsCost(pointsCost);
+        int discountAmount = (dto.getDiscountAmount() != null ? dto.getDiscountAmount() : 0);
+        // 优惠券抵扣:校验并计入优惠金额(orderType=PRODUCT)
+        Long appliedCouponId = null;
+        if (dto.getCouponId() != null) {
+            Integer couponDiscount = couponService.apply(buyerId, dto.getCouponId(), "PRODUCT", order.getTotalAmount(),
+                    java.util.Collections.singleton(order.getProductId()));
+            if (couponDiscount != null && couponDiscount > 0) {
+                discountAmount += couponDiscount;
+                appliedCouponId = dto.getCouponId();
+            }
+        }
+        int moneyAmount = order.getTotalAmount() - pointsCost - discountAmount;
+        order.setMoneyAmount(moneyAmount > 0 ? moneyAmount : 0);
+        order.setGiftAmount(productGiftRuleService.getActiveByProductId(product.getId()) != null
+                ? product.getPrice() * dto.getQuantity() : 0);
+        order.setStatus("pending");
+        order.setPaymentMethod(dto.getPaymentMethod() != null ? dto.getPaymentMethod() : "wechat");
+        order.setRemark(dto.getRemark());
+        order.setCoverImage(product.getCoverImage());
+        order.setDiscountAmount(discountAmount);
+        order.setCouponId(appliedCouponId);
+        resolveOrderAddress(order, dto, buyerId);
+        if (dto.getPurchaseInfo() != null && !dto.getPurchaseInfo().isEmpty()) {
+            order.setPurchaseInfo(JSON.toJSONString(dto.getPurchaseInfo()));
+        }
+        order.setDeliveryMethod(fv.deliveryMethod != null ? fv.deliveryMethod
+                : (dto.getDeliveryMethod() != null ? dto.getDeliveryMethod() : 1));
+        // 应用配送扩展校验结果
+        if (fv.unitPrice != null) {
+            order.setUnitPrice(fv.unitPrice);
+            order.setTotalAmount(fv.unitPrice * dto.getQuantity());
+            int ma = order.getTotalAmount() - order.getPointsCost() - discountAmount;
+            order.setMoneyAmount(ma > 0 ? ma : 0);
+        }
+        if (fv.pickupLocationId != null) order.setPickupLocationId(fv.pickupLocationId);
+        if (fv.pickupLocationSnapshot != null) order.setPickupLocationSnapshot(fv.pickupLocationSnapshot);
+        if (fv.timeSlotId != null) order.setTimeSlotId(fv.timeSlotId);
+        if (fv.timeSlotSnapshot != null) order.setTimeSlotSnapshot(fv.timeSlotSnapshot);
+        if (fv.servicePersonId != null) order.setServicePersonId(fv.servicePersonId);
+        if (fv.servicePersonSnapshot != null) order.setServicePersonSnapshot(fv.servicePersonSnapshot);
+        order.setFulfillStatus("pending");
+        // Generate pickup code for self-pickup orders
+        if (order.getDeliveryMethod() != null && order.getDeliveryMethod() == 2) {
+            order.setPickupCode(generatePickupCode());
+        }
+        order.setCancelAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
+        order.setCreatedAt(new Date());
+        order.setUpdatedAt(new Date());
+        orderMapper.insert(order);
+        // 占用已选优惠券(避免 pending 期间其他订单重复使用同一张)
+        if (appliedCouponId != null) {
+            try {
+                couponService.reserve(appliedCouponId, order.getId());
+            } catch (Exception e) {
+                log.error("占用优惠券失败: orderNo={}, couponId={}, error={}", order.getOrderNo(), appliedCouponId, e.getMessage());
+            }
+        }
+        // ===== 赠品校验与记录 =====
+        Result<Void> giftResult = processGifts(order, dto, product);
+        if (giftResult.getCode() != 200) {
+            return Result.error(giftResult.getMessage());
+        }
+        return Result.success(ProductOrderDTO.from(order));
+    }
+
+    /**
+     * 限时特价下单(扫码闪购):独立事务入口(规格 §5.2)。
+     * - 特价覆盖会员价,保留积分抵扣与赠品;优惠券按 allow_coupon 开关
+     * - 原子扣量 + 订单插入同一事务(任一异常整体回滚)
+     *
+     * <p>校验顺序裁决(2026-10-21):先做全部可失败前校验(每人限购/券开关/商品/履约/赠品),
+     * 原子扣量紧跟订单 insert 之前 —— 规格 §5.2「每人限购(先查再扣,与扣量同事务)」,
+     * 避免"扣量成功但后续校验失败返回 Result.error"导致的额度泄漏(@Transactional 仅对异常回滚,
+     * Result.error 返回会提交事务)。</p>
+     */
+    @Transactional(rollbackFor = Exception.class)
+    private Result<ProductOrderDTO> createSpecialDealOrder(CreateProductOrderDTO dto, Long buyerId) {
+        if (buyerId == null) {
+            return Result.error("请先登录");
+        }
+        // 1. 特价仅支持单商品直购,不走购物车
+        if (dto.getItems() != null && !dto.getItems().isEmpty()) {
+            return Result.error("特价商品请单独购买");
+        }
+        Long dealId = dto.getSpecialDealId();
+        SpecialPriceDeal deal = specialPriceService.getById(dealId);
+        if (deal == null) {
+            return Result.error("特价活动不存在");
+        }
+        if (!"active".equals(deal.getStatus())) {
+            return Result.error("特价活动已结束或不存在");
+        }
+        Date now = new Date();
+        if (deal.getStartTime() != null && now.before(deal.getStartTime())) {
+            return Result.error("特价活动未开始/已结束");
+        }
+        if (deal.getEndTime() != null && now.after(deal.getEndTime())) {
+            return Result.error("特价活动未开始/已结束");
+        }
+        if (deal.getSpecialPrice() == null) {
+            return Result.error("特价价格异常");
+        }
+        if (dto.getQuantity() == null || dto.getQuantity() < 1) {
+            return Result.error("购买数量不合法");
+        }
+        int quantity = dto.getQuantity();
+        if (dto.getProductId() == null || !dto.getProductId().equals(deal.getProductId())) {
+            return Result.error("该特价活动不适用于此商品");
+        }
+        // 2. 每人限购(先查再扣)
+        int perUserLimit = deal.getPerUserLimit() != null ? deal.getPerUserLimit() : 1;
+        int userPurchased = specialPriceService.getUserPurchased(dealId, buyerId);
+        if (userPurchased + quantity > perUserLimit) {
+            return Result.error("每人限购" + perUserLimit + "件,您已购买" + userPurchased + "件");
+        }
+        // 3. 优惠券开关
+        if ((deal.getAllowCoupon() == null || deal.getAllowCoupon() == 0) && dto.getCouponId() != null) {
+            return Result.error("该特价商品不可使用优惠券");
+        }
+        // 4. 商品校验(复用 create 单商品逻辑:在架/库存/套餐/最低购买量)
+        Product product = productMapper.selectById(dto.getProductId());
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        if (!"on_shelf".equals(product.getStatus())) {
+            return Result.error("商品已下架");
+        }
+        if ("physical".equals(product.getProductType())
+                && product.getStock() != null
+                && product.getStock() < quantity) {
+            return Result.error("库存不足");
+        }
+        if (product.getMinQuantity() != null && product.getMinQuantity() > 1
+                && quantity < product.getMinQuantity()) {
+            return Result.error("该商品最少需购买" + product.getMinQuantity() + "件");
+        }
+        // 5. 配送方式与履约校验
+        FulfillValidation fv = validateFulfill(product, dto, buyerId);
+        if (fv.error != null) return Result.error(fv.error);
+
+        // 6. 构建订单(定价=特价,覆盖会员价)
+        User buyer = userMapper.selectById(buyerId);
+        ProductOrder order = new ProductOrder();
+        order.setOrderNo(generateOrderNo());
+        order.setProductId(product.getId());
+        order.setProductName(product.getName());
+        order.setProductType(product.getProductType());
+        order.setBuyerId(buyerId);
+        order.setFamilyId(buyer != null ? buyer.getFamilyId() : null);
+        order.setQuantity(quantity);
+        order.setUnitPrice(deal.getSpecialPrice());
+        order.setTotalAmount(deal.getSpecialPrice() * quantity);
+        order.setPointsUsed(dto.getPointsUsed() != null ? dto.getPointsUsed() : 0);
+        int pointsCost = dto.getPointsUsed() != null ? dto.getPointsUsed() : 0;
+        order.setPointsCost(pointsCost);
+        int discountAmount = dto.getDiscountAmount() != null ? dto.getDiscountAmount() : 0;
+        Long appliedCouponId = null;
+        if (dto.getCouponId() != null) {
+            Integer couponDiscount = couponService.apply(buyerId, dto.getCouponId(), "PRODUCT", order.getTotalAmount(),
+                    java.util.Collections.singleton(order.getProductId()));
+            if (couponDiscount != null && couponDiscount > 0) {
+                discountAmount += couponDiscount;
+                appliedCouponId = dto.getCouponId();
+            }
+        }
+        int moneyAmount = order.getTotalAmount() - pointsCost - discountAmount;
+        order.setMoneyAmount(moneyAmount > 0 ? moneyAmount : 0);
+        order.setGiftAmount(productGiftRuleService.getActiveByProductId(product.getId()) != null
+                ? product.getPrice() * quantity : 0);
+        order.setStatus("pending");
+        order.setPaymentMethod(dto.getPaymentMethod() != null ? dto.getPaymentMethod() : "wechat");
+        order.setRemark(dto.getRemark());
+        order.setCoverImage(product.getCoverImage());
+        order.setDiscountAmount(discountAmount);
+        order.setCouponId(appliedCouponId);
+        resolveOrderAddress(order, dto, buyerId);
+        if (dto.getPurchaseInfo() != null && !dto.getPurchaseInfo().isEmpty()) {
+            order.setPurchaseInfo(JSON.toJSONString(dto.getPurchaseInfo()));
+        }
+        order.setDeliveryMethod(fv.deliveryMethod != null ? fv.deliveryMethod
+                : (dto.getDeliveryMethod() != null ? dto.getDeliveryMethod() : 1));
+        // 履约扩展校验结果:特价单定价固定为特价(规格 §5.2 unitPrice = specialPrice,覆盖会员价),
+        // 不复用 create() 的 fv.unitPrice 覆盖——线上可选人(服务者)等履约扩展价不适用于特价单,
+        // 否则会顶替特价破坏扫码闪购定价。fv.unitPrice 为空时不做任何覆盖,保持上方特价结算。
+        if (fv.pickupLocationId != null) order.setPickupLocationId(fv.pickupLocationId);
+        if (fv.pickupLocationSnapshot != null) order.setPickupLocationSnapshot(fv.pickupLocationSnapshot);
+        if (fv.timeSlotId != null) order.setTimeSlotId(fv.timeSlotId);
+        if (fv.timeSlotSnapshot != null) order.setTimeSlotSnapshot(fv.timeSlotSnapshot);
+        if (fv.servicePersonId != null) order.setServicePersonId(fv.servicePersonId);
+        if (fv.servicePersonSnapshot != null) order.setServicePersonSnapshot(fv.servicePersonSnapshot);
+        order.setFulfillStatus("pending");
+        if (order.getDeliveryMethod() != null && order.getDeliveryMethod() == 2) {
+            order.setPickupCode(generatePickupCode());
+        }
+        order.setSpecialDealId(dealId);
+        order.setCancelAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
+        order.setCreatedAt(new Date());
+        order.setUpdatedAt(new Date());
+
+        // 7. 原子扣量(紧跟 insert 之前;insert 或其后异常由事务整体回滚,扣量一并回滚)
+        try {
+            specialPriceService.consumeQuota(dealId, quantity);
+        } catch (IllegalStateException e) {
+            // 并发售罄/状态漂移:重查活动给出明确原因(规格 §5.2:影响行数=0 时重查判定原因)
+            return Result.error(specialDealUnavailableReason(dealId));
+        }
+        orderMapper.insert(order);
+        // 占用已选优惠券(避免 pending 期间其他订单重复使用同一张)
+        if (appliedCouponId != null) {
+            try {
+                couponService.reserve(appliedCouponId, order.getId());
+            } catch (Exception e) {
+                log.error("占用优惠券失败: orderNo={}, couponId={}, error={}", order.getOrderNo(), appliedCouponId, e.getMessage());
+            }
+        }
+        return Result.success(ProductOrderDTO.from(order));
+    }
+
+    /**
+     * 扣量失败后的原因判定(规格 §5.2:影响行数=0 → 重查活动判定已售罄/已结束/未开始/非活动期)。
+     */
+    private String specialDealUnavailableReason(Long dealId) {
+        SpecialPriceDeal deal = specialPriceService.getById(dealId);
+        if (deal == null) {
+            return "特价活动不存在";
+        }
+        String runStatus = SpecialPriceService.computeRunStatus(
+                deal.getStatus(),
+                deal.getStartTime(),
+                deal.getEndTime(),
+                deal.getSoldQuantity() != null ? deal.getSoldQuantity() : 0,
+                deal.getTotalQuantity() != null ? deal.getTotalQuantity() : 0);
+        if ("NOT_STARTED".equals(runStatus)) return "特价活动未开始";
+        if ("ENDED".equals(runStatus)) return "特价活动已结束";
+        if ("SOLD_OUT".equals(runStatus)) return "特价活动已售罄";
+        if ("DRAFT".equals(runStatus)) return "特价活动待启用";
+        if ("DISABLED".equals(runStatus)) return "特价活动已停用";
+        return "特价活动不可用";
+    }
+
+    /**
+     * 配送方式与履约校验(设计文档十一节)
+     * 分支校验 + 生成快照 + 扣减时间段余量;返回 error!=null 表示校验失败
+     */
+    /** 落库前统一整理收货地址:优先直接快照,其次 addressId(user_address),最后 consigneeId(consignees) */
+    private void resolveOrderAddress(ProductOrder order, CreateProductOrderDTO dto, Long buyerId) {
+        String snapshot = dto.getAddressSnapshot();
+        Long consigneeId = dto.getConsigneeId();
+        if ((snapshot == null || snapshot.isEmpty()) && dto.getAddressId() != null) {
+            UserAddress ua = userAddressMapper.selectById(dto.getAddressId());
+            if (ua != null && buyerId.equals(ua.getUserId())) {
+                Map<String, Object> snap = new HashMap<>();
+                snap.put("receiverName", ua.getReceiverName());
+                snap.put("phone", ua.getPhone());
+                snap.put("province", ua.getProvince());
+                snap.put("city", ua.getCity());
+                snap.put("district", ua.getDistrict());
+                snap.put("street", ua.getStreet());
+                snap.put("isDefault", ua.getIsDefault());
+                snap.put("source", "user_address");
+                snapshot = JSON.toJSONString(snap);
+                consigneeId = ua.getId();
+            }
+        } else if ((snapshot == null || snapshot.isEmpty()) && dto.getConsigneeId() != null) {
+            Consignee c = consigneeMapper.selectById(dto.getConsigneeId());
+            if (c != null && buyerId.equals(c.getUserId())) {
+                Map<String, Object> snap = new HashMap<>();
+                snap.put("receiverName", c.getName());
+                snap.put("phone", c.getPhone());
+                snap.put("province", c.getProvince());
+                snap.put("city", c.getCity());
+                snap.put("district", c.getDistrict());
+                snap.put("street", c.getStreet());
+                snap.put("source", "consignee");
+                snapshot = JSON.toJSONString(snap);
+                consigneeId = c.getId();
+            }
+        }
+        order.setAddressSnapshot(snapshot);
+        order.setConsigneeId(consigneeId);
+    }
+
+    private FulfillValidation validateFulfill(Product product, CreateProductOrderDTO dto, Long buyerId) {
+        FulfillValidation fv = new FulfillValidation();
+        Integer productMethod = product.getDeliveryMethod() != null ? product.getDeliveryMethod() : 1;
+        Integer chosen = dto.getDeliveryMethod();
+        int actualMethod;
+        if (productMethod == 3) {
+            // 两者皆可:必须由用户明确选择快递(1)或自提(2)
+            if (chosen == null || (chosen != 1 && chosen != 2)) {
+                fv.error = "请选择配送方式";
+                return fv;
+            }
+            actualMethod = chosen;
+        } else {
+            actualMethod = productMethod;
+        }
+        fv.deliveryMethod = actualMethod;
+
+        switch (actualMethod) {
+            case 1:
+                // 快递:收货地址三选一校验:直接快照 > addressId(user_address) > consigneeId(consignees)
+                if (dto.getAddressSnapshot() != null && !dto.getAddressSnapshot().isEmpty()) {
+                    // 直接提供快照,校验通过
+                } else if (dto.getAddressId() != null) {
+                    UserAddress ua = userAddressMapper.selectById(dto.getAddressId());
+                    if (ua == null || !buyerId.equals(ua.getUserId())) {
+                        fv.error = "收货地址不存在";
+                        return fv;
+                    }
+                } else if (dto.getConsigneeId() != null) {
+                    Consignee consignee = consigneeMapper.selectById(dto.getConsigneeId());
+                    if (consignee == null || !buyerId.equals(consignee.getUserId())) {
+                        fv.error = "收货地址不存在";
+                        return fv;
+                    }
+                } else {
+                    fv.error = "请选择收货地址";
+                    return fv;
+                }
+                break;
+            case 2: {
+                // 自提:校验自取地点 + 时间段
+                if (dto.getPickupLocationId() == null) {
+                    fv.error = "请选择自取地点";
+                    return fv;
+                }
+                ProductPickupLocation loc = productPickupLocationMapper.selectById(dto.getPickupLocationId());
+                if (loc == null || !product.getId().equals(loc.getProductId())
+                        || loc.getEnabled() == null || loc.getEnabled() != 1) {
+                    fv.error = "自取地点不存在或已停用";
+                    return fv;
+                }
+                Map<String, Object> locSnap = new HashMap<>();
+                locSnap.put("name", loc.getName());
+                locSnap.put("address", loc.getAddress());
+                locSnap.put("contactName", loc.getContactName());
+                locSnap.put("contactPhone", loc.getContactPhone());
+                locSnap.put("longitude", loc.getLongitude());
+                locSnap.put("latitude", loc.getLatitude());
+                fv.pickupLocationId = loc.getId();
+                fv.pickupLocationSnapshot = JSON.toJSONString(locSnap);
+                // 时间段校验
+                if (dto.getTimeSlotId() != null) {
+                    ProductPickupTimeSlot slot = productPickupTimeSlotMapper.selectById(dto.getTimeSlotId());
+                    if (slot == null || !loc.getId().equals(slot.getLocationId())
+                            || slot.getEnabled() == null || slot.getEnabled() != 1) {
+                        fv.error = "时间段不存在或已停用";
+                        return fv;
+                    }
+                    if (slot.getBookedCount() != null && slot.getMaxCapacity() != null
+                            && slot.getBookedCount() >= slot.getMaxCapacity()) {
+                        fv.error = "该时间段已约满";
+                        return fv;
+                    }
+                    Map<String, Object> slotSnap = new HashMap<>();
+                    slotSnap.put("startTime", slot.getStartTime());
+                    slotSnap.put("endTime", slot.getEndTime());
+                    slotSnap.put("weekday", slot.getWeekday());
+                    slotSnap.put("specificDate", slot.getSpecificDate());
+                    fv.timeSlotId = slot.getId();
+                    fv.timeSlotSnapshot = JSON.toJSONString(slotSnap);
+                    // 扣减余量
+                    slot.setBookedCount((slot.getBookedCount() == null ? 0 : slot.getBookedCount()) + 1);
+                    productPickupTimeSlotMapper.updateById(slot);
+                }
+                break;
+            }
+            case 4: {
+                // 线上-可选人:校验服务者 + 该服务者的时间段,价格取服务者价格
+                if (dto.getServicePersonId() == null) {
+                    fv.error = "请选择服务者";
+                    return fv;
+                }
+                ProductServicePerson person = productServicePersonMapper.selectById(dto.getServicePersonId());
+                if (person == null || !product.getId().equals(person.getProductId())
+                        || person.getEnabled() == null || person.getEnabled() != 1) {
+                    fv.error = "服务者不存在或已停用";
+                    return fv;
+                }
+                Map<String, Object> personSnap = new HashMap<>();
+                personSnap.put("name", person.getName());
+                personSnap.put("title", person.getTitle());
+                personSnap.put("intro", person.getIntro());
+                personSnap.put("avatar", person.getAvatar());
+                personSnap.put("price", person.getPrice());
+                fv.servicePersonId = person.getId();
+                fv.servicePersonSnapshot = JSON.toJSONString(personSnap);
+                fv.unitPrice = person.getPrice();
+                // 时间段校验
+                if (dto.getTimeSlotId() == null) {
+                    fv.error = "请选择预约时间段";
+                    return fv;
+                }
+                ProductServicePersonSlot personSlot = productServicePersonSlotMapper.selectById(dto.getTimeSlotId());
+                if (personSlot == null || !person.getId().equals(personSlot.getPersonId())
+                        || personSlot.getEnabled() == null || personSlot.getEnabled() != 1) {
+                    fv.error = "预约时间段不存在或已停用";
+                    return fv;
+                }
+                if (personSlot.getBookedCount() != null && personSlot.getMaxCapacity() != null
+                        && personSlot.getBookedCount() >= personSlot.getMaxCapacity()) {
+                    fv.error = "该时间段已约满";
+                    return fv;
+                }
+                Map<String, Object> slotSnap = new HashMap<>();
+                slotSnap.put("startTime", personSlot.getStartTime());
+                slotSnap.put("endTime", personSlot.getEndTime());
+                fv.timeSlotId = personSlot.getId();
+                fv.timeSlotSnapshot = JSON.toJSONString(slotSnap);
+                // 扣减余量
+                personSlot.setBookedCount((personSlot.getBookedCount() == null ? 0 : personSlot.getBookedCount()) + 1);
+                productServicePersonSlotMapper.updateById(personSlot);
+                break;
+            }
+            case 5: {
+                // 线上-单人:校验商品的时间段
+                if (dto.getTimeSlotId() == null) {
+                    fv.error = "请选择预约时间段";
+                    return fv;
+                }
+                ProductOnlineSlot onlineSlot = productOnlineSlotMapper.selectById(dto.getTimeSlotId());
+                if (onlineSlot == null || !product.getId().equals(onlineSlot.getProductId())
+                        || onlineSlot.getEnabled() == null || onlineSlot.getEnabled() != 1) {
+                    fv.error = "预约时间段不存在或已停用";
+                    return fv;
+                }
+                if (onlineSlot.getBookedCount() != null && onlineSlot.getMaxCapacity() != null
+                        && onlineSlot.getBookedCount() >= onlineSlot.getMaxCapacity()) {
+                    fv.error = "该时间段已约满";
+                    return fv;
+                }
+                Map<String, Object> slotSnap = new HashMap<>();
+                slotSnap.put("startTime", onlineSlot.getStartTime());
+                slotSnap.put("endTime", onlineSlot.getEndTime());
+                fv.timeSlotId = onlineSlot.getId();
+                fv.timeSlotSnapshot = JSON.toJSONString(slotSnap);
+                // 扣减余量
+                onlineSlot.setBookedCount((onlineSlot.getBookedCount() == null ? 0 : onlineSlot.getBookedCount()) + 1);
+                productOnlineSlotMapper.updateById(onlineSlot);
+                break;
+            }
+            default:
+                break;
+        }
+        return fv;
+    }
+
+    /** 配送校验结果载体 */
+    static class FulfillValidation {
+        String error;
+        Integer deliveryMethod;      // 实际生效的配送方式
+        Integer unitPrice;           // 线上-可选人时为服务者价格
+        Long pickupLocationId;
+        String pickupLocationSnapshot;
+        Long timeSlotId;
+        String timeSlotSnapshot;
+        Long servicePersonId;
+        String servicePersonSnapshot;
+    }
+
+    private Result<ProductOrderDTO> createMultiItem(CreateProductOrderDTO dto, Long buyerId) {
+        int totalAmount = 0;
+        int totalQuantity = 0;
+        int giftAmount = 0;
+        OrderItemVO firstItem = dto.getItems().get(0);
+        java.util.List<OrderItem> orderItemRecords = new java.util.ArrayList<>();
+        Product firstProduct = null;
+        int firstUnitPrice = 0;
+
+        for (OrderItemVO item : dto.getItems()) {
+            ProductSku itemSku = item.getSkuId() != null ? productSkuService.getById(item.getSkuId()) : null;
+            Product product = productMapper.selectById(item.getProductId());
+            if (product == null) {
+                return Result.error("商品不存在: " + item.getProductId());
+            }
+            if (!"on_shelf".equals(product.getStatus())) {
+                return Result.error("商品已下架: " + product.getName());
+            }
+            // 实物商品校验库存;虚拟商品/优惠券跳过库存检查
+            if ("physical".equals(product.getProductType())
+                    && product.getStock() != null
+                    && product.getStock() < item.getQuantity()) {
+                return Result.error("库存不足: " + product.getName());
+            }
+            // 套餐商品:校验套餐SKU库存(只扣套餐SKU,不扣子商品)
+            if ("bundle".equals(product.getProductType())
+                    && itemSku != null
+                    && !productSkuService.hasStock(itemSku.getId(), item.getQuantity())) {
+                return Result.error("套餐库存不足: " + product.getName());
+            }
+            int unitPrice = memberPriceResolver.resolveEligibleMemberPrice(product, buyerId);
+            if (itemSku != null) {
+                if (itemSku.getLinkedProductId() != null) {
+                    // Linked SKU: 转发到关联商品
+                    Product linkedProduct = productMapper.selectById(itemSku.getLinkedProductId());
+                    if (linkedProduct != null) {
+                        product = linkedProduct;
+                        unitPrice = linkedProduct.getPrice() != null ? linkedProduct.getPrice() : 0;
+                    }
+                } else {
+                    // Legacy SKU: 用 SKU 价格
+                    if (itemSku.getMinQuantity() != null && item.getQuantity() < itemSku.getMinQuantity()) {
+                        return Result.error(product.getName() + " 该规格最低需购买" + itemSku.getMinQuantity() + "件");
+                    }
+                    if (itemSku.getPrice() != null) {
+                        unitPrice = itemSku.getPrice();
+                    }
+                }
+            }
+            // 产品级最小购买数量检查(当没有SKU或SKU不限制时)
+            if (item.getSkuId() == null && product.getMinQuantity() != null && item.getQuantity() < product.getMinQuantity()) {
+                return Result.error(product.getName() + " 最低需购买" + product.getMinQuantity() + "件");
+            }
+            totalAmount += unitPrice * item.getQuantity();
+            totalQuantity += item.getQuantity();
+            // 送会员商品:累计原价金额(用于赠送会员额度判定)
+            if (product != null && productGiftRuleService.getActiveByProductId(product.getId()) != null) {
+                giftAmount += unitPrice * item.getQuantity();
+            }
+            if (firstProduct == null) {
+                firstProduct = product;
+                firstUnitPrice = unitPrice;
+            }
+            // 订单明细行(多商品 P 点按行分摊的依据;单价/小计单位:分)
+            OrderItem itemRecord = new OrderItem();
+            itemRecord.setProductId(product.getId());
+            itemRecord.setSkuId(item.getSkuId());
+            itemRecord.setProductName(product.getName());
+            itemRecord.setProductImage(product.getCoverImage());
+            itemRecord.setSkuSpecs(item.getSpecOptionIds());
+            itemRecord.setPrice(java.math.BigDecimal.valueOf(unitPrice));
+            itemRecord.setQuantity(item.getQuantity());
+            itemRecord.setSubtotal(java.math.BigDecimal.valueOf((long) unitPrice * item.getQuantity()));
+            orderItemRecords.add(itemRecord);
+        }
+
+        User buyer = userMapper.selectById(buyerId);
+        ProductOrder order = new ProductOrder();
+        order.setOrderNo(generateOrderNo());
+        order.setProductId(firstProduct.getId());
+        order.setProductName(firstProduct.getName() + "等多件");
+        order.setProductType(firstProduct.getProductType());
+        order.setSkuId(firstItem.getSkuId());
+        order.setBuyerId(buyerId);
+        order.setFamilyId(buyer != null ? buyer.getFamilyId() : null);
+        order.setQuantity(totalQuantity);
+        order.setUnitPrice(firstUnitPrice);
+        order.setTotalAmount(totalAmount);
+        order.setGiftAmount(giftAmount > 0 ? giftAmount : 0);
+        order.setPointsUsed(dto.getPointsUsed() != null ? dto.getPointsUsed() : 0);
+        int pointsCost = dto.getPointsUsed() != null ? dto.getPointsUsed() : 0;
+        order.setPointsCost(pointsCost);
+        // 套餐自动定价优惠(服务端权威):前端 discountAmount 仅含规则优惠,套餐部分由服务端重算加入
+        int multiDiscountAmount = (dto.getDiscountAmount() != null ? dto.getDiscountAmount() : 0);
+        // 优惠券抵扣:校验并计入优惠金额(orderType=PRODUCT)
+        Long appliedCouponId = null;
+        if (dto.getCouponId() != null) {
+            Integer couponDiscount = couponService.apply(buyerId, dto.getCouponId(), "PRODUCT", totalAmount,
+                    dto.getItems().stream().map(OrderItemVO::getProductId).collect(java.util.stream.Collectors.toSet()));
+            if (couponDiscount != null && couponDiscount > 0) {
+                multiDiscountAmount += couponDiscount;
+                appliedCouponId = dto.getCouponId();
+            }
+        }
+        int moneyAmount = totalAmount - pointsCost - multiDiscountAmount;
+        order.setMoneyAmount(moneyAmount > 0 ? moneyAmount : 0);
+        order.setStatus("pending");
+        order.setPaymentMethod(dto.getPaymentMethod() != null ? dto.getPaymentMethod() : "wechat");
+        order.setRemark(dto.getRemark());
+        order.setCoverImage(firstItem.getCoverImage() != null ? firstItem.getCoverImage() : firstProduct.getCoverImage());
+        order.setDiscountAmount(multiDiscountAmount);
+        order.setCouponId(appliedCouponId);
+        resolveOrderAddress(order, dto, buyerId);
+        if (dto.getPurchaseInfo() != null && !dto.getPurchaseInfo().isEmpty()) {
+            order.setPurchaseInfo(JSON.toJSONString(dto.getPurchaseInfo()));
+        }
+        order.setCancelAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
+        order.setCreatedAt(new Date());
+        order.setUpdatedAt(new Date());
+        orderMapper.insert(order);
+        // 多商品订单明细分行落库(结算 P 点按行成本分摊,见 CfCommissionService.calcOrderPpoints)
+        if (!orderItemRecords.isEmpty()) {
+            for (OrderItem itemRecord : orderItemRecords) {
+                itemRecord.setOrderId(order.getId());
+                orderItemMapper.insert(itemRecord);
+            }
+        }
+        // 占用已选优惠券(避免 pending 期间其他订单重复使用同一张)
+        if (appliedCouponId != null) {
+            try {
+                couponService.reserve(appliedCouponId, order.getId());
+            } catch (Exception e) {
+                log.error("占用优惠券失败: orderNo={}, couponId={}, error={}", order.getOrderNo(), appliedCouponId, e.getMessage());
+            }
+        }
+        // ===== 赠品校验与记录(仅单商品下单支持赠品) =====
+        if (dto.getGiftItemIds() != null && !dto.getGiftItemIds().isEmpty()) {
+            if (dto.getItems().size() > 1) {
+                return Result.error("赠品仅支持单商品下单");
+            }
+            Result<Void> giftResult = processGifts(order, dto, firstProduct);
+            if (giftResult.getCode() != 200) {
+                return Result.error(giftResult.getMessage());
+            }
+        }
+        return Result.success(ProductOrderDTO.from(order));
+    }
+
+    /**
+     * 赠品校验与记录:校验 giftItemIds 属于该商品该等级启用配置,写入 product_order_gifts(fulfilled=0)。
+     * 返回 code!=200 表示校验失败(调用方返回 Result.error(message))。
+     */
+    private Result<Void> processGifts(ProductOrder order, CreateProductOrderDTO dto, Product product) {
+        if (dto.getGiftItemIds() == null || dto.getGiftItemIds().isEmpty()) {
+            return Result.success(null);
+        }
+        // 家庭创建者等级(MembershipService.getCurrentLevel 无会员时返回 FREE)
+        MembershipLevelDTO currentLevel = order.getFamilyId() != null
+                ? membershipService.getCurrentLevel(order.getFamilyId())
+                : null;
+        String userLevel = currentLevel != null ? currentLevel.getLevelCode() : null;
+        if (userLevel == null || "FREE".equals(userLevel)) {
+            return Result.error("您暂无会员等级,无法享受赠品");
+        }
+        // 查询该商品该等级下启用的赠品项(含库存校验)
+        List<GiftConfigVO> activeConfigs = productGiftService.getActiveConfigsByProductAndLevel(
+                product.getId(), userLevel);
+        if (activeConfigs.isEmpty()) {
+            return Result.error("您所在等级暂无该商品赠品");
+        }
+        Set<Long> allowedItemIds = activeConfigs.stream()
+                .flatMap(c -> c.getItems().stream())
+                .map(GiftConfigVO.GiftItemVO::getId)
+                .collect(Collectors.toSet());
+        for (Long itemId : dto.getGiftItemIds()) {
+            if (!allowedItemIds.contains(itemId)) {
+                return Result.error("赠品项不存在或超出权限");
+            }
+            ProductGiftItem giftItem = productGiftService.getActiveItemById(itemId);
+            if (giftItem == null) {
+                return Result.error("赠品项不存在");
+            }
+            // 赠品商品库存复核(下单时再次校验,防止详情页与下单之间库存耗尽)
+            if ("product".equals(giftItem.getGiftType()) && giftItem.getGiftProductId() != null) {
+                Product gp = productMapper.selectById(giftItem.getGiftProductId());
+                if (gp == null || gp.getStock() == null || gp.getStock() <= 0) {
+                    return Result.error("赠品商品库存不足: " + (giftItem.getGiftProductName() != null ? giftItem.getGiftProductName() : "赠品"));
+                }
+            }
+            ProductOrderGift orderGift = new ProductOrderGift();
+            orderGift.setOrderId(order.getId());
+            orderGift.setOrderNo(order.getOrderNo());
+            orderGift.setGiftType(giftItem.getGiftType());
+            orderGift.setGiftProductId(giftItem.getGiftProductId());
+            orderGift.setGiftProductName(giftItem.getGiftProductName());
+            orderGift.setGiftProductImage(giftItem.getGiftProductImage());
+            orderGift.setCfValue(giftItem.getCfValue() != null ? giftItem.getCfValue() : 0);
+            orderGift.setQuantity(1);
+            orderGift.setFulfilled(0);
+            orderGift.setCreatedAt(new Date());
+            productOrderGiftMapper.insert(orderGift);
+        }
+        return Result.success(null);
+    }
+
+    public Result<Map<String, Object>> pay(String orderNo, Long userId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        if (!"pending".equals(order.getStatus())) {
+            return Result.error("订单状态异常");
+        }
+        int pointsUsed = order.getPointsUsed() != null ? order.getPointsUsed() : 0;
+        if (pointsUsed > 0) {
+            // F-5:积分抵扣改扣统一账本 cf_balance(购买人 member 维度),幂等 refId = 商品订单 ID
+            try {
+                cfSpendDispatchService.spendForUser(userId, pointsUsed, "product_order_points", order.getId(),
+                        "商品购买:" + orderNo);
+            } catch (IllegalStateException e) {
+                return Result.error("积分不足,无法使用积分支付");
+            }
+        }
+        Integer moneyAmount = order.getMoneyAmount();
+        if (moneyAmount != null && moneyAmount > 0) {
+            User user = userMapper.selectById(userId);
+            String openid = user == null ? null : user.getOpenid();
+            boolean invalidOpenid = openid == null || openid.isEmpty()
+                    || openid.startsWith("phone:") || openid.startsWith("mock_openid_");
+            if (invalidOpenid) {
+                if (pointsUsed > 0) {
+                    // F-5:原路退还(ref_type 与扣减不同,幂等键独立;重复退由账本唯一键拦截)
+                    try {
+                        cfSpendDispatchService.refundForUser(userId, pointsUsed, "product_order_points_refund",
+                                order.getId(), "支付失败退款:" + orderNo);
+                    } catch (Exception e) {
+                        log.warn("商品订单积分退还失败: orderNo={}, error={}", orderNo, e.getMessage());
+                    }
+                }
+                return Result.error("未绑定微信账号,请通过微信登录后再支付");
+            }
+            List<Map<String, Object>> goodsDetail = new ArrayList<>();
+            Map<String, Object> goods = new HashMap<>();
+            goods.put("merchant_goods_id", String.valueOf(order.getProductId()));
+            goods.put("goods_name", order.getProductName());
+            goods.put("quantity", order.getQuantity() != null ? order.getQuantity() : 1);
+            goods.put("unit_price", order.getUnitPrice() != null ? order.getUnitPrice() : moneyAmount);
+            goodsDetail.add(goods);
+            Map<String, Object> wechatPayParams = paymentService.createWechatPrepay(
+                    orderNo, order.getProductName(), moneyAmount, user.getOpenid(), goodsDetail);
+            Map<String, Object> result = new HashMap<>();
+            result.put("wechatPayParams", wechatPayParams);
+            result.put("pointsUsed", pointsUsed);
+            return Result.success(result);
+        }
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsUsed", pointsUsed);
+        result.put("noMoneyPayment", true);
+        return Result.success(result);
+    }
+
+    /**
+     * 支付成功处理:扣减库存(physical 单商品 / bundle 穿透子商品)+ 更新订单状态
+     * 事务保证 bundle 多子商品扣减的原子性——任一子商品库存不足时整体回滚,
+     * 避免部分出库(已扣子商品库存 + 已写 outbound 流水残留)
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public Result<String> handlePaymentSuccess(String orderNo, String transactionId) {
+        // 分布式锁:防止支付回调并发重复处理(重复扣库存/重复结算佣金)
+        String lockKey = "lock:order:" + orderNo;
+        if (!redisLockUtil.tryLock(lockKey, 30)) {
+            log.warn("订单支付回调处理中,跳过重复请求: orderNo={}", orderNo);
+            return Result.success("处理中,请勿重复操作");
+        }
+        try {
+            return doHandlePaymentSuccess(orderNo, transactionId);
+        } finally {
+            redisLockUtil.unlock(lockKey);
+        }
+    }
+
+    private Result<String> doHandlePaymentSuccess(String orderNo, String transactionId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!"pending".equals(order.getStatus())) {
+            return Result.success("订单状态非待支付,跳过");
+        }
+        // 仅对实物商品扣减库存;虚拟商品/优惠券无库存概念
+        Product paidProduct = productMapper.selectById(order.getProductId());
+        ProductSku paidSku = order.getSkuId() != null ? productSkuService.getById(order.getSkuId()) : null;
+        if (paidProduct != null && "physical".equals(paidProduct.getProductType())) {
+            boolean stockOk = productService.decreaseStock(order.getProductId(), order.getQuantity());
+            if (!stockOk) {
+                log.error("库存扣减失败: orderNo={}, productId={}, quantity={}",
+                        orderNo, order.getProductId(), order.getQuantity());
+                order.setRemark("库存扣减失败");
+                order.setUpdatedAt(new Date());
+                orderMapper.updateById(order);
+                throw new RuntimeException("库存不足");
+            }
+            // 记录出库流水
+            inventoryService.recordOutbound(order.getProductId(), null, order.getQuantity(),
+                    "order", order.getId(), null, "订单支付:" + orderNo);
+        } else if (paidProduct != null && "bundle".equals(paidProduct.getProductType()) && paidSku != null) {
+            // 套餐商品:只扣套餐SKU库存,不扣子商品库存
+            boolean stockOk = productSkuService.decreaseStock(paidSku.getId(), order.getQuantity());
+            if (!stockOk) {
+                log.error("套餐库存扣减失败: orderNo={}, skuId={}, quantity={}",
+                        orderNo, paidSku.getId(), order.getQuantity());
+                order.setRemark("套餐库存扣减失败");
+                order.setUpdatedAt(new Date());
+                orderMapper.updateById(order);
+                throw new RuntimeException("套餐库存不足");
+            }
+            inventoryService.recordOutbound(order.getProductId(), paidSku.getId(), order.getQuantity(),
+                    "order", order.getId(), null, "订单支付:" + orderNo);
+        }
+        order.setStatus("paid");
+        order.setTransactionId(transactionId);
+        order.setPaidAt(new Date());
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+
+        // 核销优惠券:订单支付成功后标记为已使用
+        if (order.getCouponId() != null) {
+            try {
+                couponService.markUsed(order.getCouponId(), order.getId());
+            } catch (Exception e) {
+                log.error("优惠券核销失败: orderNo={}, couponId={}, error={}", orderNo, order.getCouponId(), e.getMessage());
+            }
+        }
+
+        // CF值:统一分佣(当前人 F02 按实付 + 推荐人按订单金额)
+        try {
+            Integer paidCent = order.getMoneyAmount() != null ? order.getMoneyAmount() : order.getTotalAmount();
+            cfCommissionService.settle(order.getId(), "product", order.getBuyerId(),
+                    userMapper.selectById(order.getBuyerId()).getFamilyId(),
+                    order.getTotalAmount(), order.getProductId(), paidCent);
+            // team.profit.hook(§12-T3):同点位并行结算利润池,D>0 才分润、uk_order 幂等;不阻断支付主链路
+            try {
+                profitPoolService.settle(order.getId(), "product", order.getProductId(), (long) paidCent, 0L);
+            } catch (Exception e) {
+                log.error("利润池结算失败(hook): orderId={}, error={}", order.getId(), e.getMessage());
+            }
+        } catch (Exception e) {
+            log.error("CF值分佣失败: orderId={}, error={}", order.getId(), e.getMessage());
+        }
+
+        // 原佣金结算标记为废弃,保留兼容
+        // commissionService.settle(order.getId(), "product", order.getBuyerId(),
+        //        order.getTotalAmount(), order.getProductId());
+        try {
+            if (order.getSupplySystemId() != null) {
+                User buyer = userMapper.selectById(order.getBuyerId());
+                if (buyer != null && buyer.getReferrerId() != null) {
+                    SupplySystemMember referrerMember = supplySystemMemberMapper.selectOne(
+                        new LambdaQueryWrapper<SupplySystemMember>()
+                            .eq(SupplySystemMember::getSystemId, order.getSupplySystemId())
+                            .eq(SupplySystemMember::getUserId, buyer.getReferrerId())
+                    );
+                    if (referrerMember != null) {
+                        supplyHierarchyService.addRelation(order.getSupplySystemId(), buyer.getReferrerId(), order.getBuyerId());
+                        // 同时记录供应商团队客户归属
+                        supplyCustomerRelationService.autoBindOnOrder(order.getSupplySystemId(), buyer.getReferrerId(), order.getFamilyId(), order.getBuyerId());
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("绑定供应商上下级关系失败: orderNo={}", orderNo, e);
+        }
+        // Award energy for product purchase
+        try {
+            User buyer_user = userMapper.selectById(order.getBuyerId());
+            Long memberId = null;
+            if ("child".equals(buyer_user.getRole())) {
+                memberId = buyer_user.getId();
+            } else {
+                List<ChildInfoDTO> children = userService.getChildren(order.getBuyerId());
+                if (children != null && !children.isEmpty()) {
+                    memberId = children.get(0).getId();
+                }
+            }
+            if (memberId != null) {
+                energyService.awardEnergy(memberId, "product", order.getId(),
+                    order.getTotalAmount(), "商品购买能量奖励", 30);
+            }
+        } catch (Exception e) {
+            // Do not block payment flow
+        }
+        // 测评商品:支付成功后自动发放测评额度
+        try {
+            if (paidProduct != null && Product.TYPE_ASSESSMENT.equals(paidProduct.getProductType())) {
+                AssessmentProduct ext = assessmentProductService.getByProductId(paidProduct.getId());
+                if (ext != null) {
+                    assessmentQuotaService.grantQuota(order,
+                            ext.getTotalSessions(), ext.getValidityDays());
+                    log.info("测评商品订单{}已发放额度", orderNo);
+                }
+            }
+        } catch (Exception e) {
+            log.error("发放测评额度失败: orderNo={}", orderNo, e);
+            // 不阻塞支付流程
+        }
+        // 赠送会员:单笔订单送会员商品原价合计达标即赠送会员
+        try {
+            if (order.getGiftAmount() != null && order.getGiftAmount() > 0 && order.getFamilyId() != null) {
+                String origThresholdStr = sysConfigService.getValue("gift_membership_original_threshold");
+                int origThreshold;
+                try {
+                    origThreshold = origThresholdStr != null ? Integer.parseInt(origThresholdStr) : 0;
+                } catch (NumberFormatException e) {
+                    origThreshold = 0;
+                }
+                // 只要单笔订单送会员商品原价合计>=阈值,即直接赠送会员(不再受是否有折扣/积分/优惠券限制)
+                if (origThreshold > 0 && order.getGiftAmount() >= origThreshold) {
+                    String levelCode = sysConfigService.getValue("gift_membership_level");
+                    if (levelCode == null || levelCode.isEmpty()) {
+                        levelCode = "FAMILY";
+                    }
+                    boolean granted = membershipService.grantMembershipByGift(
+                            order.getFamilyId(), order.getBuyerId(), levelCode, null, null);
+                    if (granted) {
+                        // 同步记录进度(已赠送标记)
+                        giftMembershipProgressService.accumulate(
+                                order.getFamilyId(), order.getBuyerId(), order.getGiftAmount());
+                        log.info("商品订单{}单笔达标送会员: giftAmount={}, threshold={}, granted={}", orderNo, order.getGiftAmount(), origThreshold, granted);
+                    }
+                }
+                // 兼容原有累计进度展示(仅统计无折扣/无券/无积分的订单)
+                boolean fullPrice = (order.getPointsUsed() == null || order.getPointsUsed() == 0)
+                        && order.getCouponId() == null
+                        && (order.getDiscountAmount() == null || order.getDiscountAmount() == 0);
+                if (fullPrice) {
+                    boolean granted = giftMembershipProgressService.accumulate(
+                            order.getFamilyId(), order.getBuyerId(), order.getGiftAmount());
+                    if (granted) {
+                        log.info("商品订单{}累计送会员金额={}, 触发赠送={}", orderNo, order.getGiftAmount(), granted);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("商品赠送会员失败: orderNo={}", orderNo, e);
+            // 不阻塞支付流程
+        }
+        // 发放订单赠品(CF值 + 实物库存扣减)
+        try {
+            List<ProductOrderGift> pendingGifts = productOrderGiftMapper.selectList(
+                    new LambdaQueryWrapper<ProductOrderGift>()
+                            .eq(ProductOrderGift::getOrderId, order.getId())
+                            .eq(ProductOrderGift::getFulfilled, 0));
+            for (ProductOrderGift gift : pendingGifts) {
+                if ("cf".equals(gift.getGiftType()) && gift.getCfValue() != null && gift.getCfValue() > 0) {
+                    // F04 商品赠品 CF:数量取赠品配置,统一账本发放(幂等键:赠品 ID)
+                    try {
+                        cfEarnDispatchService.earnGiftCf(order.getBuyerId(), gift.getId(), gift.getCfValue());
+                    } catch (Exception e) {
+                        log.error("赠品CF值发放失败: orderId={}, giftId={}, error={}",
+                                order.getId(), gift.getId(), e.getMessage());
+                    }
+                } else if ("product".equals(gift.getGiftType()) && gift.getGiftProductId() != null) {
+                    int qty = gift.getQuantity() != null ? gift.getQuantity() : 1;
+                    boolean stockOk = productService.decreaseStock(gift.getGiftProductId(), qty);
+                    if (!stockOk) {
+                        log.error("赠品库存扣减失败: orderNo={}, giftProductId={}", orderNo, gift.getGiftProductId());
+                    } else {
+                        inventoryService.recordOutbound(gift.getGiftProductId(), null, qty,
+                                "gift", order.getId(), null, "商品赠品:" + orderNo);
+                    }
+                }
+                gift.setFulfilled(1);
+                productOrderGiftMapper.updateById(gift);
+            }
+        } catch (Exception e) {
+            log.error("订单{}赠品发放异常: {}", orderNo, e.getMessage());
+        }
+        // 触发通关解锁刷新:购物成功(PURCHASE 关卡)
+        try {
+            if (order.getFamilyId() != null) {
+                unlockGateService.refreshFamilyGates(order.getFamilyId(), order.getBuyerId());
+            }
+        } catch (Exception e) {
+            log.error("刷新通关解锁进度失败: orderNo={}", orderNo, e);
+        }
+        // 虚拟商品自动发货(规格 §3.3):支付成功即置 completed + 同步微信 logistics_type=3(fail-open 幂等)
+        try {
+            if (isVirtualProduct(order)) {
+                Result<String> r = autoShipVirtualOrder(order);
+                log.info("虚拟商品订单支付成功自动发货: orderNo={}, result={}", orderNo, r != null ? r.getMessage() : "null");
+            }
+        } catch (Exception e) {
+            log.error("虚拟商品自动发货失败(不阻塞支付): orderNo={}, error={}", orderNo, e.getMessage(), e);
+        }
+        // 订单支付成功 webhook 通知(不阻塞支付流程)
+        try {
+            notifyOrderPaidWebhook(order);
+        } catch (Exception e) {
+            log.warn("订单支付成功 webhook 通知异常(不阻塞): orderNo={}, error={}", orderNo, e.getMessage());
+        }
+        return Result.success("支付成功");
+    }
+
+    /**
+     * 订单支付成功 webhook 通知:组装订单信息(含收件人)推送微信待办。
+     * 金额单位:数据库存分为单位,推送转元。失败仅记录 WARN,不抛异常。
+     */
+    private void notifyOrderPaidWebhook(ProductOrder order) {
+        try {
+            StringBuilder sb = new StringBuilder();
+            String buyerName = "";
+            try {
+                User buyer = userMapper.selectById(order.getBuyerId());
+                if (buyer != null) {
+                    buyerName = buyer.getNickname() != null ? buyer.getNickname() : "";
+                }
+            } catch (Exception e) {
+                log.warn("查询下单人昵称失败: buyerId={}", order.getBuyerId());
+            }
+
+            Integer payCent = order.getMoneyAmount() != null ? order.getMoneyAmount() : order.getTotalAmount();
+            double yuan = (payCent != null ? payCent : 0) / 100.0;
+            sb.append("【新订单】").append(order.getOrderNo()).append("\n");
+            sb.append("商品: ").append(order.getProductName() != null ? order.getProductName() : "")
+              .append(" x").append(order.getQuantity() != null ? order.getQuantity() : 1).append("\n");
+            sb.append(String.format("金额: ¥%.2f", yuan)).append("\n");
+            sb.append("下单人: ").append(buyerName == null || buyerName.isEmpty() ? "用户" + order.getBuyerId() : buyerName).append("\n");
+
+            // 收件人信息(addressSnapshot JSON 快照)
+            String addrJson = order.getAddressSnapshot();
+            if (addrJson != null && !addrJson.trim().isEmpty()) {
+                try {
+                    com.alibaba.fastjson.JSONObject addr = com.alibaba.fastjson.JSON.parseObject(addrJson);
+                    String receiver = addr.getString("receiverName");
+                    String phone = addr.getString("phone");
+                    String region = (addr.getString("province") == null ? "" : addr.getString("province"))
+                            + (addr.getString("city") == null ? "" : addr.getString("city"))
+                            + (addr.getString("district") == null ? "" : addr.getString("district"))
+                            + (addr.getString("street") == null ? "" : addr.getString("street"));
+                    sb.append("收件人: ").append(receiver == null ? "" : receiver)
+                      .append(" | ").append(phone == null ? "" : phone)
+                      .append(" | ").append(region);
+                } catch (Exception e) {
+                    log.warn("解析收件人信息失败: orderNo={}", order.getOrderNo());
+                }
+            } else {
+                sb.append("收件人: 自提/无需配送");
+            }
+
+            wechatWaitMsgService.sendWaitMsg(sb.toString(), "cfOrder");
+        } catch (Exception e) {
+            log.warn("订单 webhook 通知失败: orderNo={}, error={}", order.getOrderNo(), e.getMessage());
+        }
+    }
+
+    public Result<String> cancel(String orderNo, Long userId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        if (!"pending".equals(order.getStatus())) {
+            return Result.error("仅待支付订单可取消");
+        }
+        order.setStatus("cancelled");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        // 取消订单:归还优惠券;CF 兑换来的券同时退还 CF 值
+        releaseCouponForCancelledOrder(order.getCouponId());
+        // F-5:退还下单时抵扣的 CF 值(原路返还到购买人 member 账本,幂等 refId = 商品订单 ID)
+        refundOrderPoints(order, "取消订单退还CF值:" + orderNo);
+        // Restore stock on cancel
+        if ("bundle".equals(order.getProductType()) && order.getSkuId() != null) {
+            productSkuService.increaseStock(order.getSkuId(), order.getQuantity());
+        } else {
+            productService.increaseStock(order.getProductId(), order.getQuantity());
+        }
+        // 记录退款入库流水
+        inventoryService.recordRefundInbound(order.getProductId(), null, order.getQuantity(),
+                "order", order.getId(), null, "取消订单:" + orderNo);
+        // 特价订单回滚扣量(与恢复库存并列,失败仅记日志不阻断取消)
+        try {
+            specialPriceService.releaseQuota(order.getSpecialDealId(), order.getQuantity());
+        } catch (Exception ex) {
+            log.warn("特价扣量回滚失败: dealId={}, orderNo={}, err={}",
+                    order.getSpecialDealId(), order.getOrderNo(), ex.getMessage());
+        }
+        return Result.success("订单已取消");
+    }
+
+    /**
+     * 订单取消/退款时的优惠券释放:先退还 CF 值(若该券为用户 CF 兑换而来),再归还券实例。
+     *
+     * 规则:
+     * <ul>
+     *   <li>券实例在 family_platform_exchange_record 有 completed 兑换记录 → 用户用 CF 值兑换而来,
+     *       按原始消耗 cfCost 原路退还到兑换人个人统一账本 cf_balance(ref_type=coupon_refund,退还幂等,同一券实例只退一次);</li>
+     *   <li>无兑换记录 → 平台赠送券(JOIN 开通会员 / POPULATION 新增成员 / MANUAL 手动发放 /
+     *       供应商临时券等),只归还券,不退还 CF 值。</li>
+     * </ul>
+     *
+     * 券归还与 CF 退还放在同一事务,避免「券已归还但 CF 未退」或相反的不一致。
+     * 与商品主流程解耦:优惠券释放失败只记日志,不阻断订单取消/退款主流程。
+     *
+     * @param userCouponId 券实例ID(family_coupon.id,即下单时保存的 product_orders.coupon_id)
+     */
+    @Transactional
+    public void releaseCouponForCancelledOrder(Long userCouponId) {
+        if (userCouponId == null) {
+            return;
+        }
+        try {
+            // 先退 CF:查询与 family_coupon 状态无关,顺序不影响判断结果
+            int cfRefunded = familyPlatformPointsService.refundCouponCf(userCouponId);
+            // 再归还券实例(USED → AVAILABLE)
+            couponService.revert(userCouponId);
+            if (cfRefunded > 0) {
+                log.info("取消/退款订单:优惠券已归还并退还CF值: familyCouponId={}, cfRefunded={}", userCouponId, cfRefunded);
+            }
+        } catch (Exception e) {
+            log.error("取消/退款订单:释放优惠券失败: familyCouponId={}, error={}", userCouponId, e.getMessage());
+        }
+    }
+
+    /**
+     * F-5:退还订单下单时抵扣的 CF 值(原路返还到购买人 member 的 cf_balance 账本)。
+     *
+     * <p>幂等:ref_type={@code product_order_points_refund}、ref_id=商品订单 ID,与扣减
+     * (ref_type={@code product_order_points})分属不同幂等键,因此「取消」与「退款」两路都可退,
+     * 同一订单重复退只生效一次(账本唯一键兜底)。失败只记日志,不阻断取消/退款主流程。</p>
+     */
+    private void refundOrderPoints(ProductOrder order, String reason) {
+        int pointsUsed = order.getPointsUsed() != null ? order.getPointsUsed() : 0;
+        if (pointsUsed <= 0 || order.getBuyerId() == null) {
+            return;
+        }
+        try {
+            cfSpendDispatchService.refundForUser(order.getBuyerId(), pointsUsed,
+                    "product_order_points_refund", order.getId(), reason);
+            log.info("订单CF值已退还: orderNo={}, buyerId={}, pointsUsed={}", order.getOrderNo(), order.getBuyerId(), pointsUsed);
+        } catch (Exception e) {
+            log.warn("订单CF值退还失败: orderNo={}, buyerId={}, error={}", order.getOrderNo(), order.getBuyerId(), e.getMessage());
+        }
+    }
+
+    public Result<String> ship(String orderNo, String trackingNumber, String expressCompany) {
+        return ship(orderNo, trackingNumber, expressCompany, null);
+    }
+
+    public Result<String> ship(String orderNo, String trackingNumber, String expressCompany, Integer shippingCost) {
+        return ship(orderNo, null, trackingNumber, expressCompany, shippingCost, null);
+    }
+
+    /**
+     * 多渠道履约发货(自提 / 快递 / 同城 / 虚拟商品),行为矩阵见
+     * docs/superpowers/specs/2026-10-22-fulfillment-multi-mode-design.md §3.2。
+     *
+     * @param orderNo         订单号
+     * @param shipType        发货方式:express/local/selfPickup/virtual;null 时按订单推导(见 resolveShipType)
+     * @param trackingNumber  物流单号(express/local 必填;selfPickup/virtual 拒收)
+     * @param expressCompany  物流公司/同城运力商(express/local 必填;selfPickup/virtual 拒收)
+     * @param shippingCost    快递费(分)
+     * @param receiverContact 收货人电话(快递/同城同步微信时透传,自提/虚拟不传)
+     */
+    public Result<String> ship(String orderNo, String shipType,
+                               String trackingNumber, String expressCompany,
+                               Integer shippingCost, String receiverContact) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        boolean isVirtual = isVirtualProduct(order);
+        // 虚拟商品:已终态(completed)或无实体配送 → 补发货走幂等自动发货;其余分支校验
+        if ("completed".equals(order.getStatus()) && isVirtual) {
+            return autoShipVirtualOrder(order);
+        }
+        if (!"paid".equals(order.getStatus())) {
+            return Result.error("仅已支付订单可发货");
+        }
+        // 虚拟商品支付成功即自动发货(规范 §3.3),商家后台补发货复用幂等方法;
+        // 与微信协议一致:无实体配送无单号,传入单号/公司 → 拒绝
+        if (isVirtual) {
+            if ((trackingNumber != null && !trackingNumber.trim().isEmpty())
+                    || (expressCompany != null && !expressCompany.trim().isEmpty())) {
+                return Result.error("虚拟商品无需填写物流信息");
+            }
+            return autoShipVirtualOrder(order);
+        }
+        // 非虚拟商品:推导/校验发货类型
+        ShipType st = resolveShipType(order, shipType);
+        if (st == null) {
+            return Result.error("无法判断发货方式,请选择:快递发货或自提发货");
+        }
+        if (st == ShipType.VIRTUAL) {
+            // 显式船传 shipType=virtual 但订单不是虚拟商品 → 拒绝
+            return Result.error("该订单不是虚拟商品,无法按虚拟商品发货");
+        }
+        switch (st) {
+            case EXPRESS:
+                if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
+                    return Result.error("请填写物流单号");
+                }
+                if (expressCompany == null || expressCompany.trim().isEmpty()) {
+                    return Result.error("请填写物流公司");
+                }
+                order.setLogisticsNo(trackingNumber);
+                order.setLogisticsCompany(expressCompany);
+                break;
+            case LOCAL:
+                if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
+                    return Result.error("请填写同城配送单号");
+                }
+                if (expressCompany == null || expressCompany.trim().isEmpty()) {
+                    return Result.error("请填写同城配送公司");
+                }
+                order.setLogisticsNo(trackingNumber);
+                order.setLogisticsCompany(expressCompany);
+                break;
+            case SELF_PICKUP:
+            default:
+                if ((trackingNumber != null && !trackingNumber.trim().isEmpty())
+                        || (expressCompany != null && !expressCompany.trim().isEmpty())) {
+                    return Result.error("自提订单无需填写物流信息");
+                }
+                break;
+        }
+        if (shippingCost != null) {
+            order.setShippingCost(shippingCost);
+        }
+        order.setStatus("pending_receipt");
+        // P0-B 待收货超时兜底:发货成功即写 shipped_at=now,作为超时自动完成/收货提醒的基准时间
+        order.setShippedAt(new Date());
+        if (st == ShipType.SELF_PICKUP) {
+            // 履约扩展:自取/线上订单必须供应商先确认(confirmReceive 有校验),此处统一置为已确认
+            order.setFulfillStatus("confirmed_by_vendor");
+        }
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        // 发货成功后自动同步物流信息到微信小程序交易管理服务(fail-open:失败只记日志不阻塞)
+        syncShippingInfoToWechat(order, st, trackingNumber, expressCompany, receiverContact);
+        return Result.success("已发货");
+    }
+
+    public Result<String> updateExpress(String orderNo, String trackingNumber, String expressCompany, Integer shippingCost) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        // 与 ship() 保持同一组落库列(logisticsNo/logisticsCompany):
+        // 详情展示 ProductOrderService.getOrderDetail / ProductOrderDTO.from() 与管理端/小程序前端均读该组列,
+        // 旧写法写 trackingNumber/expressCompany 另一组列会导致前端展示不更新、微信同步回退读空。
+        if (trackingNumber != null) order.setLogisticsNo(trackingNumber);
+        if (expressCompany != null) order.setLogisticsCompany(expressCompany);
+        if (shippingCost != null) order.setShippingCost(shippingCost);
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        // 快递信息更新后自动同步微信(部分更新时回退订单已存值);updateExpress 仅用于快递/同城
+        ShipType st = resolveShipTypeFromOrder(order);
+        syncShippingInfoToWechat(order, st,
+                trackingNumber != null ? trackingNumber : order.getLogisticsNo(),
+                expressCompany != null ? expressCompany : order.getLogisticsCompany(),
+                null);
+        return Result.success("快递信息已更新");
+    }
+
+    /**
+     * 发货方式类型:express=快递(微信logistics_type 1)、local=同城配送(2)、
+     * virtual=虚拟商品(3)、selfPickup=用户自提(4)。
+     */
+    private enum ShipType {
+        EXPRESS, LOCAL, SELF_PICKUP, VIRTUAL
+    }
+
+    /** 虚拟商品:productType == "virtual" */
+    private boolean isVirtualProduct(ProductOrder order) {
+        return order != null && "virtual".equals(order.getProductType());
+    }
+
+    /**
+     * 由订单推导发货类型(规格 §3.1)。
+     * 优先显式 shipTypeParam(express/local/selfPickup/virtual),其次按 productType/deliveryMethod 推导;
+     * deliveryMethod=3/4/5 或 NULL 订单层面无法判定 → 返回 null(调用方报业务错误,要求前端显式传入 shipType)。
+     */
+    private ShipType resolveShipType(ProductOrder order, String shipTypeParam) {
+        if (shipTypeParam != null && !shipTypeParam.trim().isEmpty()) {
+            String s = shipTypeParam.trim().toLowerCase();
+            if ("express".equals(s)) return ShipType.EXPRESS;
+            if ("local".equals(s)) return ShipType.LOCAL;
+            if ("selfpickup".equals(s)) return ShipType.SELF_PICKUP;
+            if ("virtual".equals(s)) return ShipType.VIRTUAL;
+            return null; // 未知类型
+        }
+        if (isVirtualProduct(order)) {
+            return ShipType.VIRTUAL;
+        }
+        Integer dm = order.getDeliveryMethod();
+        if (dm == null) {
+            // NULL:订单层面无法判定,要求前端显式传入 shipType
+            return null;
+        }
+        switch (dm) {
+            case 1: return ShipType.EXPRESS;
+            case 2: return ShipType.SELF_PICKUP;
+            case 6: return ShipType.LOCAL;
+            default: return null; // 3 两者皆可(应已被 validateFulfill 转成 1/2,出现属老数据);4/5 线上服务履约
+        }
+    }
+
+    /** 按订单 deliveryMethod 推导(updateExpress 改快递/同城场景复用):1快递/2自提/6同城;其余按 EXPRESS 兜底 */
+    private ShipType resolveShipTypeFromOrder(ProductOrder order) {
+        Integer dm = order.getDeliveryMethod();
+        if (dm == null) {
+            return ShipType.EXPRESS;
+        }
+        switch (dm) {
+            case 1: return ShipType.EXPRESS;
+            case 2: return ShipType.SELF_PICKUP;
+            case 6: return ShipType.LOCAL;
+            default: return ShipType.EXPRESS;
+        }
+    }
+
+    /**
+     * 虚拟商品自动发货(规格 §3.3):支付成功即置 completed + 调微信 upload_shipping_info(logistics_type=3)。
+     * fail-open + 幂等:状态已 completed 时直接返回提示不再重复同步。
+     */
+    private Result<String> autoShipVirtualOrder(ProductOrder order) {
+        if (isVirtualProduct(order) && "completed".equals(order.getStatus())) {
+            log.info("虚拟商品订单已交付(补发货幂等跳过): orderNo={}", order.getOrderNo());
+            return Result.success("该订单已自动交付");
+        }
+        order.setStatus("completed");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        // 同步微信(fail-open),买家无 openid 时微信侧跳过
+        try {
+            User buyer = userMapper.selectById(order.getBuyerId());
+            if (buyer == null || buyer.getOpenid() == null || buyer.getOpenid().isEmpty()) {
+                log.warn("虚拟商品买家无 openid,跳过微信发货同步: orderNo={}", order.getOrderNo());
+            } else {
+                String itemDesc = (order.getProductName() == null ? "" : order.getProductName())
+                        + " x" + (order.getQuantity() == null ? 1 : order.getQuantity());
+                if (itemDesc.length() > 120) {
+                    itemDesc = itemDesc.substring(0, 120);
+                }
+                String err = wechatService.uploadShippingInfo(order.getOrderNo(), buyer.getOpenid(),
+                        null, null, itemDesc, 3, null);
+                if (err != null) {
+                    log.warn("虚拟商品微信同步未成功(不阻塞): orderNo={}, reason={}", order.getOrderNo(), err);
+                }
+            }
+        } catch (Exception e) {
+            log.error("虚拟商品微信发货同步异常(不阻塞): orderNo={}, error={}", order.getOrderNo(), e.getMessage(), e);
+        }
+        log.info("虚拟商品自动发货完成: orderNo={}", order.getOrderNo());
+        return Result.success("自动发货成功");
+    }
+
+    /**
+     * 管理端发货/改快递成功后,自动把物流信息同步到微信「小程序交易管理服务」
+     * (upload_shipping_info)。fail-open:失败只记日志,不阻塞本地发货。
+     * 自提(4)/虚拟(3)订单:无单号不带;买家无 openid / 无单号时跳过。
+     */
+    private void syncShippingInfoToWechat(ProductOrder order, ShipType shipType,
+                                          String trackingNo, String expressCompany, String receiverContact) {
+        try {
+            if (order == null) {
+                return;
+            }
+            int logisticsType;
+            switch (shipType) {
+                case LOCAL: logisticsType = 2; break;
+                case SELF_PICKUP: logisticsType = 4; break;
+                case VIRTUAL: logisticsType = 3; break;
+                case EXPRESS:
+                default: logisticsType = 1; break;
+            }
+            // 无单号跳过(自提/虚拟本身无单号,属正常,不警告)
+            if ((logisticsType == 1 || logisticsType == 2)
+                    && (trackingNo == null || trackingNo.trim().isEmpty())) {
+                log.info("无物流单号,跳过微信发货同步: orderNo={}", order.getOrderNo());
+                return;
+            }
+            // 买家 openid
+            User buyer = userMapper.selectById(order.getBuyerId());
+            if (buyer == null || buyer.getOpenid() == null || buyer.getOpenid().isEmpty()) {
+                log.warn("买家无 openid,跳过微信发货同步: orderNo={}, buyerId={}", order.getOrderNo(), order.getBuyerId());
+                return;
+            }
+            String itemDesc = (order.getProductName() == null ? "" : order.getProductName())
+                    + " x" + (order.getQuantity() == null ? 1 : order.getQuantity());
+            if (itemDesc.length() > 120) {
+                itemDesc = itemDesc.substring(0, 120);
+            }
+            String err = wechatService.uploadShippingInfo(order.getOrderNo(), buyer.getOpenid(),
+                    trackingNo, expressCompany, itemDesc, logisticsType, receiverContact);
+            if (err != null) {
+                log.warn("微信发货同步未成功(不阻塞发货): orderNo={}, reason={}", order.getOrderNo(), err);
+            }
+        } catch (Exception e) {
+            // fail-open:任何异常不阻塞本地发货流程
+            log.error("微信发货同步异常(不阻塞发货): orderNo={}, error={}", order.getOrderNo(), e.getMessage(), e);
+        }
+    }
+
+    public Result<String> confirmReceive(String orderNo, Long userId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        if (!"pending_receipt".equals(order.getStatus())) {
+            return Result.error("仅待收货订单可确认收货");
+        }
+        // 履约扩展: 自取/线上订单(deliveryMethod>=2)必须供应商先确认
+        Integer dm = order.getDeliveryMethod() != null ? order.getDeliveryMethod() : 1;
+        if (dm >= 2 && !"confirmed_by_vendor".equals(order.getFulfillStatus())) {
+            return Result.error("供应商确认后方可确认收货");
+        }
+        order.setStatus("completed");
+        order.setConfirmTime(new Date());
+        if (dm >= 2) {
+            order.setFulfillStatus("received_by_user");
+            order.setReceivedAt(new Date());
+        }
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+
+        return Result.success("已确认收货");
+    }
+
+    /** 供应商确认已发出/服务完成(履约扩展) */
+    public Result<String> vendorConfirm(String orderNo, Long vendorId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) return Result.error("订单不存在");
+        if (!"paid".equals(order.getStatus()) && !"pending_shipment".equals(order.getStatus())) {
+            return Result.error("当前订单状态不可确认");
+        }
+        if (order.getFulfillStatus() != null && !"pending".equals(order.getFulfillStatus())) {
+            return Result.error("订单已确认");
+        }
+        order.setFulfillStatus("confirmed_by_vendor");
+        order.setFulfillConfirmedAt(new Date());
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        return Result.success("已确认发出");
+    }
+
+    /**
+     * 服务商订单到店核销(SC-S-04,能力键 {@code supplier.order.fulfill})。
+     * 契约签名:{@code public Result<String> redeem(String orderNo, String pickupCode, Long vendorId)}。
+     *
+     * <p>行为矩阵(见 {@code SupplierOrderFulfillContractTest} / {@code 应用场景总览.md} SC-S-04):
+     * <ul>
+     *   <li>正常流:本服务商 + 自提码匹配 + 未超期 → 订单置「已完成」,返回成功;</li>
+     *   <li>防冒用(TC-S-03-E):自提码不匹配 → 拒绝(提示核销码校验失败),不落库;</li>
+     *   <li>重复核销幂等(TC-S-04):已 completed 再次核销 → 返回成功,不重复落库/副作用;</li>
+     *   <li>超期订单(TC-S-04):自提时段已过 → 提示不可核销,状态不变更;</li>
+     *   <li>非本服务商(TC-S-04-P):商品 vendorId ≠ vendorId → 无权操作,不落库。</li>
+     * </ul>
+     */
+    public Result<String> redeem(String orderNo, String pickupCode, Long vendorId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        // 幂等:已核销完成(重复扫码同订单)→ 返回成功,不重复落库/不重复副作用
+        if ("completed".equals(order.getStatus())) {
+            return Result.success("该订单已完成核销");
+        }
+        if (!"paid".equals(order.getStatus())) {
+            return Result.error("当前订单状态不可核销");
+        }
+        // 超期判定:自提时段快照已过 → 不可核销(状态不变更)
+        if (isPickupExpired(order)) {
+            return Result.error("订单已超期,不可核销");
+        }
+        // 权限:非本服务商商品订单 → 无权操作(不落库)
+        Product product = order.getProductId() != null ? productMapper.selectById(order.getProductId()) : null;
+        if (product == null || vendorId == null || !vendorId.equals(product.getVendorId())) {
+            return Result.error("无权操作此订单");
+        }
+        // 防冒用:自提码校验(TC-S-03-E)
+        if (pickupCode == null || order.getPickupCode() == null || !pickupCode.equals(order.getPickupCode())) {
+            return Result.error("核销码校验失败");
+        }
+        // 核销完成:到店核销无实体物流,置终态 + 履约扩展标记
+        order.setStatus("completed");
+        order.setFulfillStatus("received_by_user");
+        order.setReceivedAt(new Date());
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        return Result.success("核销成功");
+    }
+
+    /**
+     * 超期判定:自提时段快照 {@code timeSlotSnapshot} 中 {@code endTime} 已过(早于当前时刻)。
+     * 快照 {@code endTime} 可能为 {@code java.sql.Time} 时间串(如 "09:00:00")或完整日期串;
+     * 仅当能解析为完整日期且早于 now 时判定超期——纯时间串无法定位具体日期,不在此简单判定(避免误伤当日时段)。
+     */
+    private boolean isPickupExpired(ProductOrder order) {
+        String snap = order.getTimeSlotSnapshot();
+        if (snap == null || snap.trim().isEmpty()) {
+            return false;
+        }
+        try {
+            com.alibaba.fastjson.JSONObject obj = JSON.parseObject(snap);
+            String endTime = obj.getString("endTime");
+            if (endTime == null || endTime.trim().isEmpty()) {
+                return false;
+            }
+            Date end = parseSlotEndTime(endTime.trim());
+            return end != null && end.before(new Date());
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    /** 解析快照 endTime:支持完整日期串 "yyyy-MM-dd HH:mm:ss" / "yyyy-MM-dd'T'HH:mm:ss";纯时间串返回 null */
+    private Date parseSlotEndTime(String s) {
+        String[] patterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss"};
+        for (String p : patterns) {
+            try {
+                SimpleDateFormat sdf = new SimpleDateFormat(p);
+                sdf.setLenient(false);
+                return sdf.parse(s);
+            } catch (Exception ignored) {
+                // 尝试下一个模式
+            }
+        }
+        return null;
+    }
+
+    // ========== 退款流程 ==========
+
+    public Result<String> applyRefund(String orderNo, Long userId, String reason) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        // 仅允许已支付或待发货状态的订单申请退款
+        if (!"paid".equals(order.getStatus()) && !"pending_shipment".equals(order.getStatus())) {
+            return Result.error("仅已支付或待发货订单可申请退款");
+        }
+        // 检查是否已有退款申请
+        if (order.getRefundStatus() != null && order.getRefundStatus() == 1) {
+            return Result.error("已有退款申请正在处理中");
+        }
+        order.setRefundStatus(1); // 申请中
+        order.setRefundReason(reason);
+        order.setStatus("refunding");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        return Result.success("退款申请已提交");
+    }
+
+    public Result<String> approveRefund(String orderNo, Long adminId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (order.getRefundStatus() == null || order.getRefundStatus() != 1) {
+            return Result.error("没有待处理的退款申请");
+        }
+        // 实际退款金额 = 用户实付现金(money_amount 已扣除优惠券抵扣与积分抵扣)。
+        // 微信侧按订单实收金额退款:退 total_amount 会超过实收金额被微信拒绝,
+        // 且会把已抵扣的优惠券/积分折算成现金再退一次,与「归还优惠券」形成双重获益。
+        // 历史订单 money_amount 为空时退回 total_amount。
+        Integer refundAmount = order.getMoneyAmount();
+        if (refundAmount == null || refundAmount < 0) {
+            refundAmount = order.getTotalAmount();
+        }
+        if (refundAmount != null && refundAmount > 0) {
+            try {
+                paymentService.refund(orderNo, refundAmount, order.getRefundReason());
+            } catch (Exception e) {
+                if (e.getMessage() != null && e.getMessage().contains("NOT_ENOUGH")) {
+                    pendingRefundService.createPendingRefund(order.getBuyerId(), null, refundAmount, "product", orderNo);
+                    order.setStatus("refund_pending");
+                    order.setRefundStatus(4);
+                    order.setUpdatedAt(new Date());
+                    orderMapper.updateById(order);
+                    log.info("微信退款余额不足,已加入待退款队列: orderNo={}", orderNo);
+                    // 注意:此处不归还优惠券/不退 CF —— 钱还没退出去。
+                    // 待 RefundScheduledTasks.processProductRefund 实际退款成功后再释放,避免"券退了钱没退"。
+                    return Result.success("⚠️ 商户余额不足,退款已加入等待队列,到账后将自动退款");
+                }
+                log.error("微信退款失败: orderNo={}, error={}", orderNo, e.getMessage());
+                return Result.error("退款失败: " + e.getMessage());
+            }
+        } else {
+            // 优惠券/积分全额抵扣、用户未付现金:直接走完退款流程,无需调微信退款接口
+            log.info("订单实付金额为0(优惠券/积分全额抵扣),跳过微信退款: orderNo={}", orderNo);
+        }
+        order.setRefundStatus(2);
+        order.setRefundAmount(refundAmount);
+        order.setRefundTime(new Date());
+        order.setStatus("refunded");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        if ("bundle".equals(order.getProductType()) && order.getSkuId() != null) {
+            productSkuService.increaseStock(order.getSkuId(), order.getQuantity());
+        } else {
+            productService.increaseStock(order.getProductId(), order.getQuantity());
+        }
+        inventoryService.recordRefundInbound(order.getProductId(), null, order.getQuantity(),
+                "order", order.getId(), adminId, "退款:" + orderNo);
+        // 退款成功:归还优惠券;CF 兑换来的券同时退还 CF 值
+        releaseCouponForCancelledOrder(order.getCouponId());
+        // F-5:退还下单时抵扣的 CF 值(原路返还到购买人 member 账本)
+        refundOrderPoints(order, "退款退还CF值:" + orderNo);
+        // 特价订单回滚扣量(与恢复库存并列,失败仅记日志不阻断退款)
+        try {
+            specialPriceService.releaseQuota(order.getSpecialDealId(), order.getQuantity());
+        } catch (Exception ex) {
+            log.warn("特价扣量回滚失败(refund): dealId={}, orderNo={}, err={}",
+                    order.getSpecialDealId(), order.getOrderNo(), ex.getMessage());
+        }
+        syncAfterSalesRequestStatus(orderNo, "approved", adminId);
+        log.info("退款完成: orderNo={}, adminId={}", orderNo, adminId);
+        return Result.success("退款已处理");
+    }
+
+    public Result<String> rejectRefund(String orderNo, Long adminId, String reason) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (order.getRefundStatus() == null || order.getRefundStatus() != 1) {
+            return Result.error("没有待处理的退款申请");
+        }
+        order.setRefundStatus(3);
+        order.setStatus("paid");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        syncAfterSalesRequestStatus(orderNo, "rejected", adminId);
+        log.info("退款申请被拒绝: orderNo={}, adminId={}, reason={}", orderNo, adminId, reason);
+        return Result.success("已拒绝退款申请");
+    }
+
+    /**
+     * 查询订单退款状态/详情(能力键 shop.order.queryRefund)。
+     * 按买家归属作用域:仅订单购买者本人可查,非归属用户返回无权。
+     */
+    public Result<ProductOrderDTO> queryRefund(String orderNo, Long userId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        if (!order.getBuyerId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+        ProductOrderDTO dto = ProductOrderDTO.from(order);
+        return Result.success(dto);
+    }
+
+    private void syncAfterSalesRequestStatus(String orderNo, String status, Long adminId) {
+        try {
+            LambdaQueryWrapper<AfterSalesRequest> wrapper = new LambdaQueryWrapper<AfterSalesRequest>()
+                .eq(AfterSalesRequest::getOrderNo, orderNo)
+                .eq(AfterSalesRequest::getStatus, "pending");
+            SortUtil.applySort(wrapper);
+            AfterSalesRequest request = afterSalesRequestMapper.selectOne(wrapper);
+            if (request != null) {
+                request.setStatus(status);
+                request.setHandledBy(adminId);
+                request.setHandledAt(new Date());
+                request.setUpdatedAt(new Date());
+                if ("rejected".equals(status)) {
+                    request.setRejectReason("管理员拒绝退款");
+                }
+                afterSalesRequestMapper.updateById(request);
+            }
+        } catch (Exception e) {
+            log.error("同步AfterSalesRequest状态失败: orderNo={}, status={}", orderNo, status, e);
+        }
+    }
+
+    public Result<List<ProductOrderDTO>> myOrders(Long buyerId, String status) {
+        return myOrders(buyerId, status, null);
+    }
+
+    public Result<List<ProductOrderDTO>> myOrders(Long buyerId, String status, String keyword) {
+        LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
+            .eq(ProductOrder::getBuyerId, buyerId)
+            .orderByDesc(ProductOrder::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ProductOrder::getStatus, status);
+        }
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            String kw = keyword.trim();
+            wrapper.and(w -> w.like(ProductOrder::getProductName, kw).or().like(ProductOrder::getOrderNo, kw));
+        }
+        SortUtil.applySort(wrapper);
+        List<ProductOrder> list = orderMapper.selectList(wrapper);
+        return Result.success(list.stream().map(ProductOrderDTO::from).collect(Collectors.toList()));
+    }
+
+    public Result<Map<String, Long>> myOrderCounts(Long buyerId) {
+        Map<String, Long> counts = new java.util.LinkedHashMap<>();
+        String[] statuses = {"pending", "paid", "shipped", "completed", "refunding"};
+        long total = 0;
+        for (String s : statuses) {
+            long cnt = orderMapper.selectCount(new LambdaQueryWrapper<ProductOrder>()
+                .eq(ProductOrder::getBuyerId, buyerId)
+                .eq(ProductOrder::getStatus, s));
+            counts.put(s, cnt);
+            total += cnt;
+        }
+        long cancelled = orderMapper.selectCount(new LambdaQueryWrapper<ProductOrder>()
+            .eq(ProductOrder::getBuyerId, buyerId).eq(ProductOrder::getStatus, "cancelled"));
+        long refunded = orderMapper.selectCount(new LambdaQueryWrapper<ProductOrder>()
+            .eq(ProductOrder::getBuyerId, buyerId).eq(ProductOrder::getStatus, "refunded"));
+        counts.put("total", total + cancelled + refunded);
+        counts.put("cancelled", cancelled);
+        counts.put("refunded", refunded);
+        return Result.success(counts);
+    }
+
+    public Result<ProductOrderDTO> detail(String orderNo, Long userId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        Product product = productMapper.selectById(order.getProductId());
+        boolean isBuyer = order.getBuyerId().equals(userId);
+        boolean isVendor = product != null && product.getVendorId() != null && product.getVendorId().equals(userId);
+        if (!isBuyer && !isVendor) {
+            return Result.error("无权查看");
+        }
+        ProductOrderDTO dto = ProductOrderDTO.from(order);
+        if (product != null) {
+            dto.setVendorId(product.getVendorId());
+        }
+        return Result.success(dto);
+    }
+
+    public Result<List<ProductOrderDTO>> vendorOrders(Long vendorId, String status) {
+        List<Product> products = productMapper.selectList(
+            new LambdaQueryWrapper<Product>().eq(Product::getVendorId, vendorId));
+        if (products == null || products.isEmpty()) {
+            return Result.success(java.util.Collections.emptyList());
+        }
+        List<Long> productIds = products.stream().map(Product::getId).collect(Collectors.toList());
+        LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
+            .in(ProductOrder::getProductId, productIds)
+            .orderByDesc(ProductOrder::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ProductOrder::getStatus, status);
+        }
+        SortUtil.applySort(wrapper);
+        List<ProductOrder> list = orderMapper.selectList(wrapper);
+        return Result.success(list.stream().map(ProductOrderDTO::from).collect(Collectors.toList()));
+    }
+
+    public Result<List<ProductOrderDTO>> adminList(String status) {
+        LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
+            .orderByDesc(ProductOrder::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ProductOrder::getStatus, status);
+        }
+        SortUtil.applySort(wrapper);
+        List<ProductOrder> list = orderMapper.selectList(wrapper);
+        return Result.success(list.stream().map(ProductOrderDTO::from).collect(Collectors.toList()));
+    }
+
+    public Result<Map<String, Object>> adminOrderPage(int page, int size, String status, String keyword, String startDate, String endDate, List<Map<String, String>> sortSpecs) {
+        return adminOrderPage(page, size, status, keyword, null, startDate, endDate, sortSpecs, null);
+    }
+
+    /**
+     * 管理端订单分页(B-5:supplierUserId 非空时按供应商行级隔离——自己名下 supplier_id 或自己商品产生的订单)
+     */
+    public Result<Map<String, Object>> adminOrderPage(int page, int size, String status, String keyword, String buyerKeyword, String startDate, String endDate, List<Map<String, String>> sortSpecs, Long supplierUserId) {
+        Page<ProductOrder> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
+            .orderByDesc(ProductOrder::getCreatedAt);
+        if (supplierUserId != null) {
+            wrapper.and(w -> w.eq(ProductOrder::getSupplierId, supplierUserId)
+                    .or().inSql(ProductOrder::getProductId, "SELECT id FROM products WHERE vendor_id = " + supplierUserId));
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(ProductOrder::getStatus, status);
+        }
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            String kw = keyword.trim();
+            wrapper.and(w -> w.like(ProductOrder::getProductName, kw).or().like(ProductOrder::getOrderNo, kw));
+        }
+        // 按用户筛选:匹配购买人昵称/手机号(纯数字再按用户ID),过滤 buyer_id
+        if (buyerKeyword != null && !buyerKeyword.trim().isEmpty()) {
+            String bkw = buyerKeyword.trim();
+            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<User>()
+                    .like(User::getNickname, bkw)
+                    .or().like(User::getPhone, bkw);
+            if (bkw.matches("\\d+")) {
+                userWrapper.or().eq(User::getId, Long.valueOf(bkw));
+            }
+            List<User> matchedUsers = userMapper.selectList(userWrapper);
+            if (matchedUsers.isEmpty()) {
+                // 无匹配用户:强制空结果,避免 buyer_id IN () 语法错误
+                wrapper.in(ProductOrder::getBuyerId, -1L);
+            } else {
+                List<Long> buyerIds = matchedUsers.stream().map(User::getId).collect(Collectors.toList());
+                wrapper.in(ProductOrder::getBuyerId, buyerIds);
+            }
+        }
+        if (startDate != null && !startDate.isEmpty()) {
+            try {
+                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                wrapper.ge(ProductOrder::getCreatedAt, sdf.parse(startDate));
+            } catch (Exception ignored) {}
+        }
+        if (endDate != null && !endDate.isEmpty()) {
+            try {
+                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                Calendar cal = Calendar.getInstance();
+                cal.setTime(sdf.parse(endDate));
+                cal.add(Calendar.DAY_OF_MONTH, 1);
+                wrapper.lt(ProductOrder::getCreatedAt, cal.getTime());
+            } catch (Exception ignored) {}
+        }
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        Page<ProductOrder> result = orderMapper.selectPage(pageParam, wrapper);
+        List<ProductOrderDTO> records = result.getRecords().stream()
+            .map(ProductOrderDTO::from)
+            .collect(Collectors.toList());
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", records);
+        data.put("total", result.getTotal());
+        data.put("page", result.getCurrent());
+        data.put("size", result.getSize());
+        return Result.success(data);
+    }
+
+    public Result<ProductOrderDTO> adminOrderDetail(String orderNo) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        return Result.success(ProductOrderDTO.from(order));
+    }
+
+    public Result<String> adminClose(String orderNo, Long adminId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        String currentStatus = order.getStatus();
+        if ("completed".equals(currentStatus) || "cancelled".equals(currentStatus) || "refunded".equals(currentStatus)) {
+            return Result.error("该订单无法关闭");
+        }
+        if ("paid".equals(currentStatus) || "pending_receipt".equals(currentStatus)) {
+            if ("bundle".equals(order.getProductType()) && order.getSkuId() != null) {
+                productSkuService.increaseStock(order.getSkuId(), order.getQuantity());
+            } else {
+                productService.increaseStock(order.getProductId(), order.getQuantity());
+            }
+        }
+        order.setStatus("closed");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        log.info("管理员关闭订单: orderNo={}, adminId={}", orderNo, adminId);
+        return Result.success("订单已关闭");
+    }
+
+    public Result<String> confirm(String orderNo, Long vendorId) {
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        Product product = productMapper.selectById(order.getProductId());
+        if (product == null || !product.getVendorId().equals(vendorId)) {
+            return Result.error("无权操作");
+        }
+        if (!"paid".equals(order.getStatus())) {
+            return Result.error("仅已支付订单可确认完成");
+        }
+        order.setStatus("completed");
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+        return Result.success("订单已完成");
+    }
+
+    public Result<Map<String, Object>> queryLogistics(Long orderId, Long userId) {
+        ProductOrder order = orderMapper.selectById(orderId);
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        Product product = productMapper.selectById(order.getProductId());
+        boolean isBuyer = order.getBuyerId().equals(userId);
+        boolean isVendor = product != null && product.getVendorId() != null && product.getVendorId().equals(userId);
+        if (!isBuyer && !isVendor) {
+            return Result.error("无权查看");
+        }
+        Map<String, Object> result = new HashMap<>();
+        result.put("logisticsNo", order.getLogisticsNo());
+        result.put("logisticsCompany", order.getLogisticsCompany());
+        result.put("status", order.getStatus());
+        result.put("trackingData", generateTrackingData(order));
+        return Result.success(result);
+    }
+
+    private List<Map<String, Object>> generateTrackingData(ProductOrder order) {
+        List<Map<String, Object>> list = new ArrayList<>();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String status = order.getStatus();
+        Date paidAt = order.getPaidAt() != null ? order.getPaidAt() : order.getCreatedAt();
+        // base timestamp in ms
+        long base = paidAt.getTime();
+
+        if ("paid".equals(status)) {
+            // paid only — no tracking yet
+            addTrack(list, sdf.format(new Date(base)), "订单已支付,等待发货");
+            return list;
+        }
+        if ("cancelled".equals(status)) {
+            addTrack(list, sdf.format(new Date(base)), "订单已取消");
+            return list;
+        }
+
+        // shipped / pending_receipt / completed share first steps
+        addTrack(list, sdf.format(new Date(base + 3600000L)), "包裹已揽收");
+
+        if ("pending_receipt".equals(status) || "completed".equals(status)) {
+            addTrack(list, sdf.format(new Date(base + 7200000L)), "包裹已到达中转站");
+            addTrack(list, sdf.format(new Date(base + 14400000L)), "正在派送中,请保持电话畅通");
+        }
+        if ("completed".equals(status)) {
+            addTrack(list, sdf.format(new Date(base + 18000000L)), "包裹已签收,感谢购买");
+        } else if ("pending_receipt".equals(status)) {
+            addTrack(list, sdf.format(new Date(base + 14400000L)), "快件已到达,派送员正在派送");
+        } else {
+            // shipped but not yet delivered
+            addTrack(list, sdf.format(new Date(base + 4800000L)), "包裹正在运输中");
+        }
+
+        return list;
+    }
+
+    private void addTrack(List<Map<String, Object>> list, String time, String desc) {
+        Map<String, Object> item = new HashMap<>();
+        item.put("time", time);
+        item.put("content", desc);
+        list.add(item);
+    }
+
+    private String generateOrderNo() {
+        return OrderNoGenerator.generate("PO");
+    }
+
+    private String generatePickupCode() {
+        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+        StringBuilder code = new StringBuilder();
+        for (int i = 0; i < 6; i++) {
+            int idx = (int) (Math.random() * chars.length());
+            code.append(chars.charAt(idx));
+        }
+        return code.toString();
+    }
+
+    /**
+     * 供应商审核修改订单(仅 pending 状态)
+     * 支持:修改单价/总价、修改配送方式、添加临时优惠券、添加赠品
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> reviewUpdate(Map<String, Object> params, Long userId) {
+        String orderNo = (String) params.get("orderNo");
+        if (orderNo == null || orderNo.isEmpty()) {
+            return Result.error("订单号不能为空");
+        }
+
+        ProductOrder order = orderMapper.selectOne(
+            new LambdaQueryWrapper<ProductOrder>().eq(ProductOrder::getOrderNo, orderNo));
+        if (order == null) {
+            return Result.error("订单不存在");
+        }
+        // 特价订单禁止供应商改价(含非价格字段,保持简单——扫码闪购定价由活动决定)
+        if (order.getSpecialDealId() != null) {
+            return Result.error("特价订单不允许修改价格");
+        }
+        if (!"pending".equals(order.getStatus())) {
+            return Result.error("仅待支付订单可审核修改");
+        }
+
+        // 权限校验:供应商必须是该订单商品的 vendorId
+        Product product = productMapper.selectById(order.getProductId());
+        if (product == null || product.getVendorId() == null || !product.getVendorId().equals(userId)) {
+            return Result.error("无权操作此订单");
+        }
+
+        boolean hasChange = false;
+        StringBuilder changeLog = new StringBuilder();
+
+        // ===== 1. 修改价格 =====
+        Integer newUnitPrice = params.get("unitPrice") != null ? ((Number) params.get("unitPrice")).intValue() : null;
+        if (newUnitPrice != null && newUnitPrice >= 0) {
+        int oldTotal = order.getTotalAmount() != null ? order.getTotalAmount() : 0;
+            order.setUnitPrice(newUnitPrice);
+            int newTotal = newUnitPrice * (order.getQuantity() != null ? order.getQuantity() : 1);
+            order.setTotalAmount(newTotal);
+            int pointsCost = order.getPointsCost() != null ? order.getPointsCost() : 0;
+            int moneyAmount = newTotal - pointsCost - (order.getDiscountAmount() != null ? order.getDiscountAmount() : 0);
+            order.setMoneyAmount(Math.max(moneyAmount, 0));
+            hasChange = true;
+            if (oldTotal != newTotal) {
+                if (changeLog.length() > 0) changeLog.append(";");
+                changeLog.append(String.format("价格:%d元 → %d元", oldTotal / 100, newTotal / 100));
+            }
+        }
+
+        // ===== 2. 修改配送方式 =====
+        Integer newDeliveryMethod = params.get("deliveryMethod") != null ? ((Number) params.get("deliveryMethod")).intValue() : null;
+        if (newDeliveryMethod != null) {
+            Integer productMethod = product.getDeliveryMethod();
+            if (productMethod == null) productMethod = 1;
+            boolean allowed;
+            switch (productMethod) {
+                case 1: allowed = newDeliveryMethod == 1; break;
+                case 2: allowed = newDeliveryMethod == 2; break;
+                case 3: allowed = newDeliveryMethod == 1 || newDeliveryMethod == 2; break;
+                case 4: allowed = newDeliveryMethod == 4; break;
+                case 5: allowed = newDeliveryMethod == 5; break;
+                default: allowed = true; break;
+            }
+            if (!allowed) {
+                return Result.error("该商品不支持此配送方式");
+            }
+            if (newDeliveryMethod.equals(order.getDeliveryMethod())) {
+                // 未变更,跳过
+            } else {
+                int oldMethod = order.getDeliveryMethod() != null ? order.getDeliveryMethod() : 1;
+                order.setDeliveryMethod(newDeliveryMethod);
+                hasChange = true;
+                if (changeLog.length() > 0) changeLog.append(";");
+                changeLog.append(String.format("配送方式:%d → %d", oldMethod, newDeliveryMethod));
+            }
+        }
+
+        // ===== 3. 添加临时优惠券 =====
+        Integer couponValue = params.get("couponValue") != null ? ((Number) params.get("couponValue")).intValue() : null;
+        Long existingCouponId = order.getCouponId();
+        if (couponValue != null && couponValue > 0 && existingCouponId == null) {
+            Coupon tempCoupon = new Coupon();
+            tempCoupon.setName("供应商临时券-" + orderNo);
+            tempCoupon.setType("ONE_TIME");
+            tempCoupon.setValue(couponValue);
+            tempCoupon.setMinSpend(0);
+            tempCoupon.setDiscountRate(null);
+            tempCoupon.setProductId(order.getProductId());
+            tempCoupon.setStatus("ACTIVE");
+            tempCoupon.setValidFrom(new Date());
+            Calendar cal = Calendar.getInstance();
+            cal.setTime(order.getCancelAt() != null ? order.getCancelAt() : new Date());
+            cal.add(Calendar.DAY_OF_MONTH, 7);
+            tempCoupon.setValidUntil(cal.getTime());
+            couponMapper.insert(tempCoupon);
+            order.setCouponId(tempCoupon.getId());
+            order.setDiscountAmount(couponValue);
+            int pointsCost = order.getPointsCost() != null ? order.getPointsCost() : 0;
+            int moneyAmount = order.getTotalAmount() - pointsCost - couponValue;
+            order.setMoneyAmount(Math.max(moneyAmount, 0));
+            // Grant to buyer's family
+            if (order.getFamilyId() != null) {
+                FamilyCoupon fc = new FamilyCoupon();
+                fc.setFamilyId(order.getFamilyId());
+                fc.setCouponId(tempCoupon.getId());
+                fc.setStatus("AVAILABLE");
+                fc.setReceivedAt(new Date());
+                fc.setOrderId(order.getId());
+                familyCouponMapper.insert(fc);
+            }
+            hasChange = true;
+            if (changeLog.length() > 0) changeLog.append(";");
+            changeLog.append(String.format("新增优惠券:减免%d元", couponValue / 100));
+        }
+
+        // ===== 4. 添加赠品 =====
+        List<Map<String, Object>> giftItems = (List<Map<String, Object>>) params.get("giftItems");
+        if (giftItems != null && !giftItems.isEmpty()) {
+            for (Map<String, Object> gift : giftItems) {
+                Long giftProductId = gift.get("giftProductId") != null ? ((Number) gift.get("giftProductId")).longValue() : null;
+                String giftProductName = (String) gift.get("giftProductName");
+                String giftProductImage = (String) gift.get("giftProductImage");
+                Integer quantity = gift.get("quantity") != null ? ((Number) gift.get("quantity")).intValue() : 1;
+
+                ProductOrderGift orderGift = new ProductOrderGift();
+                orderGift.setOrderId(order.getId());
+                orderGift.setOrderNo(order.getOrderNo());
+                orderGift.setGiftType("product");
+                orderGift.setGiftProductId(giftProductId);
+                orderGift.setGiftProductName(giftProductName);
+                orderGift.setGiftProductImage(giftProductImage);
+                orderGift.setCfValue(0);
+                orderGift.setQuantity(quantity);
+                orderGift.setFulfilled(0);
+                orderGift.setCreatedAt(new Date());
+                productOrderGiftMapper.insert(orderGift);
+
+                hasChange = true;
+                if (changeLog.length() > 0) changeLog.append(";");
+                changeLog.append(String.format("新增赠品:%s x%d",
+                    giftProductName != null ? giftProductName : "赠品", quantity));
+            }
+        }
+
+        // ===== 5. 更新备注 =====
+        String remark = (String) params.get("remark");
+        if (remark != null && !remark.isEmpty()) {
+            if (order.getRemark() != null && !order.getRemark().isEmpty()) {
+                order.setRemark(order.getRemark() + " | " + remark);
+            } else {
+                order.setRemark(remark);
+            }
+        } else if (hasChange) {
+            order.setRemark("供应商审核修改: " + changeLog.toString());
+        }
+
+        // ===== 6. 更新订单时间 =====
+        order.setUpdatedAt(new Date());
+        orderMapper.updateById(order);
+
+        // ===== 7. 组装返回 =====
+        ProductOrderDTO dto = ProductOrderDTO.from(order);
+        Map<String, Object> result = new HashMap<>();
+        result.put("order", dto);
+        result.put("changeLog", changeLog.toString());
+        return Result.success(result);
+    }
+
+    /**
+     * 获取用户有效的会员价。
+     * 规则:产品设置了 member_price 时——
+     * - 产品 min_discount_level 为 NULL:默认 BASIC(付费会员即可享;2026-10-23 修复 FREE 也可享的漏洞);
+     * - 产品 min_discount_level 已设置(如 BASIC/FAMILY/PREMIUM):仅当用户会员等级 &gt;= min_discount_level 时返回 memberPrice,
+     * 否则返回原价 product.getPrice()。
+     */
+    private Integer getEligibleMemberPrice(Product product, Long buyerId) {
+        // 已抽出至 MemberPriceResolver(共享给 CartService 展示口径),此处保留委托
+        return memberPriceResolver.resolveEligibleMemberPrice(product, buyerId);
+    }
+}

+ 136 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductPurchaseFieldService.java

@@ -0,0 +1,136 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Consignee;
+import com.etotem.cfc.entity.ProductPurchaseField;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ProductPurchaseFieldMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+public class ProductPurchaseFieldService {
+
+    @Resource
+    private ProductPurchaseFieldMapper purchaseFieldMapper;
+
+    @Resource
+    private ConsigneeService consigneeService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 预定义字段列表,供管理端选择
+     */
+    public static final Map<String, String> PREDEFINED_FIELDS = new LinkedHashMap<>();
+
+    static {
+        PREDEFINED_FIELDS.put("name", "收货人姓名");
+        PREDEFINED_FIELDS.put("phone", "手机号");
+        PREDEFINED_FIELDS.put("id_card", "身份证号");
+        PREDEFINED_FIELDS.put("hand_signature", "手签名");
+        PREDEFINED_FIELDS.put("ethnicity", "民族");
+        PREDEFINED_FIELDS.put("blood_type", "血型");
+    }
+
+    public Result<List<ProductPurchaseField>> listByProduct(Long productId) {
+        List<ProductPurchaseField> list = purchaseFieldMapper.selectList(
+                new LambdaQueryWrapper<ProductPurchaseField>()
+                        .eq(ProductPurchaseField::getProductId, productId)
+                        .orderByAsc(ProductPurchaseField::getSortOrder));
+        return Result.success(list);
+    }
+
+    @Transactional
+    public Result<Void> save(Long productId, List<ProductPurchaseField> fields) {
+        // delete existing configs
+        purchaseFieldMapper.delete(
+                new LambdaQueryWrapper<ProductPurchaseField>()
+                        .eq(ProductPurchaseField::getProductId, productId));
+        // insert new configs
+        if (fields != null && !fields.isEmpty()) {
+            for (int i = 0; i < fields.size(); i++) {
+                ProductPurchaseField f = fields.get(i);
+                f.setId(null);
+                f.setProductId(productId);
+                if (f.getSortOrder() == null) {
+                    f.setSortOrder(i);
+                }
+                if (f.getIsRequired() == null) {
+                    f.setIsRequired(1);
+                }
+                purchaseFieldMapper.insert(f);
+            }
+        }
+        return Result.success(null);
+    }
+
+    /**
+     * 获取用户购买某商品时需要的购买信息
+     * 返回每个字段及当前用户信息中已有的值
+     */
+    public Result<List<Map<String, Object>>> getRequiredFields(Long productId, Long userId) {
+        List<ProductPurchaseField> configs = purchaseFieldMapper.selectList(
+                new LambdaQueryWrapper<ProductPurchaseField>()
+                        .eq(ProductPurchaseField::getProductId, productId)
+                        .eq(ProductPurchaseField::getIsRequired, 1)
+                        .orderByAsc(ProductPurchaseField::getSortOrder));
+
+        if (configs.isEmpty()) {
+            return Result.success(Collections.emptyList());
+        }
+
+        // get user info for prefilling
+        User user = userMapper.selectById(userId);
+        // get default consignee
+        Consignee defaultConsignee = consigneeService.getDefault(userId);
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (ProductPurchaseField cfg : configs) {
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("fieldKey", cfg.getFieldKey());
+            item.put("fieldName", cfg.getFieldName());
+            item.put("isRequired", cfg.getIsRequired());
+            // try to prefill from default consignee, then from user profile
+            String value = getFieldValueFromConsignee(cfg.getFieldKey(), defaultConsignee);
+            if (value == null) {
+                value = getFieldValueFromUser(cfg.getFieldKey(), user);
+            }
+            item.put("prefillValue", value != null ? value : "");
+            result.add(item);
+        }
+        return Result.success(result);
+    }
+
+    private String getFieldValueFromConsignee(String fieldKey, Consignee c) {
+        if (c == null) return null;
+        switch (fieldKey) {
+            case "name": return c.getName();
+            case "phone": return c.getPhone();
+            case "id_card": return c.getIdCard();
+            case "hand_signature": return c.getHandSignature();
+            case "ethnicity": return c.getEthnicity();
+            case "blood_type": return c.getBloodType();
+            default: return null;
+        }
+    }
+
+    private String getFieldValueFromUser(String fieldKey, User user) {
+        if (user == null) return null;
+        switch (fieldKey) {
+            case "name": return user.getRealName();
+            case "phone": return user.getPhone();
+            case "id_card": return user.getIdCard();
+            case "ethnicity": return user.getEthnicity();
+            case "blood_type": return user.getBloodType();
+            default: return null;
+        }
+    }
+}

+ 1122 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductRecommendationService.java

@@ -0,0 +1,1122 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.service.support.ProductVisibilitySupport;
+import com.etotem.cfc.util.SortUtil;
+
+/**
+ * 商品推荐服务
+ * 支持三类推荐场景:
+ * 1. 维度页推荐(基于维度匹配 + 关联关系)
+ * 2. AI对话推荐(基于画像缺口 + 购买关联)
+ * 3. 报告关联推荐(健康报告/认知测评触发)
+ * <p>
+ * 核心思路:<strong>静态维度映射</strong> 为基础,<strong>动态关联关系表</strong> 为补充,
+ * 实现<strong>画像驱动</strong>与<strong>购买关联</strong>双轮驱动的个性化推荐。
+ */
+@Slf4j
+@Service
+public class ProductRecommendationService {
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private ProductDimensionMappingMapper dimensionMappingMapper;
+
+    @Resource
+    private ProductOrderMapper orderMapper;
+
+    @Resource
+    private FiveDimensionScoreMapper fiveDimensionScoreMapper;
+
+    @Resource
+    private ProductRecommendationLogMapper productRecommendationLogMapper;
+
+    @Resource
+    private RecommendationProductAssociationMapper recommendationProductAssociationMapper;
+
+    @Resource
+    private HealthFilterService healthFilterService;
+
+    @Resource
+    private ReferralTreeMapper referralTreeMapper;
+
+    @Resource
+    private SupplySystemMemberMapper supplySystemMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private SupplySystemService supplySystemService;
+
+    @Resource
+    private UserContentWeightService userContentWeightService;
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private FiveDimensionScoreService fiveDimensionScoreService;
+
+    @Resource
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+
+    @Resource
+    private ProductVisibilitySupport productVisibilitySupport;
+
+    /**
+     * 维度页推荐
+     *
+     * @param dimensionCode    维度编码: body/wisdom/mind/action/wealth
+     * @param familyId         家庭ID
+     * @param memberId         成员ID(可选)
+     * @param excludeProductIds 排除的商品ID列表
+     * @param limit            返回数量
+     * @param userId           当前登录用户ID(用于供应商优先级计算,可为null)
+     * @return 推荐商品列表
+     */
+    public List<Map<String, Object>> getDimensionRecommendations(
+            String dimensionCode, Long familyId, Long memberId,
+            List<Long> excludeProductIds, int limit, Long userId) {
+
+        // 0. 加载成员健康画像(硬拦截基础)
+        HealthFilterService.HealthProfile healthProfile = healthFilterService.loadProfile(memberId, null, null);
+
+        // 1. 获取已购商品ID(90天内)
+        Set<Long> purchasedIds = getPurchasedProductIds(familyId, 90);
+        if (excludeProductIds != null) {
+            purchasedIds.addAll(excludeProductIds);
+        }
+
+        // 2. 获取成员维度得分(画像)
+        Map<String, Integer> memberScores = getMemberDimensionScores(familyId, memberId);
+
+        // 3. 从维度匹配表获取候选商品(静态基础)
+        List<Map<String, Object>> candidates = new ArrayList<>();
+
+        // 从 mapping 表获取关联商品
+        LambdaQueryWrapper<ProductDimensionMapping> mappingQw = new LambdaQueryWrapper<ProductDimensionMapping>()
+                .eq(ProductDimensionMapping::getEnabled, 1);
+        if (dimensionCode != null && !dimensionCode.isEmpty()) {
+            mappingQw.eq(ProductDimensionMapping::getDimensionCode, dimensionCode);
+        }
+        SortUtil.applySort(mappingQw);
+        List<ProductDimensionMapping> mappings = dimensionMappingMapper.selectList(mappingQw);
+
+        if (mappings != null && !mappings.isEmpty()) {
+            List<Long> mappedProductIds = mappings.stream()
+                    .map(ProductDimensionMapping::getProductId)
+                    .filter(id -> !purchasedIds.contains(id))
+                    .collect(Collectors.toList());
+
+            if (!mappedProductIds.isEmpty()) {
+                LambdaQueryWrapper<Product> mappedWrapper = new LambdaQueryWrapper<Product>()
+                        .in(Product::getId, mappedProductIds)
+                        .eq(Product::getStatus, "on_shelf")
+                        .and(w -> w.ne(Product::getProductType, "physical").or().isNull(Product::getStock).or().gt(Product::getStock, 0))
+                        .orderByAsc(Product::getSortOrder);
+                // 商品可见性过滤(min_visible_level + vendor_visible),与商城列表 /api/product/list 对齐
+                productVisibilitySupport.applyToQuery(mappedWrapper, userId, null);
+                List<Product> mapped = productMapper.selectList(mappedWrapper);
+
+                HealthFilterService.FilterResult mappedFilter = healthFilterService.filterProducts(healthProfile, mapped);
+                mapped = mappedFilter.allowed;
+
+                // 构建 productId → mapping 得分
+                Map<Long, Integer> mappingScores = mappings.stream()
+                        .collect(Collectors.toMap(
+                                ProductDimensionMapping::getProductId,
+                                ProductDimensionMapping::getMatchScore,
+                                (a, b) -> a
+                        ));
+                Map<Long, String> mappingReasons = mappings.stream()
+                        .collect(Collectors.toMap(
+                                ProductDimensionMapping::getProductId,
+                                m -> m.getMatchReason() != null ? m.getMatchReason() : "",
+                                (a, b) -> a
+                        ));
+
+                for (Product p : mapped) {
+                    Integer baseScore = mappingScores.getOrDefault(p.getId(), 100);
+                    String reason = mappingReasons.getOrDefault(p.getId(), "");
+                    double finalScore = applyDimensionBoost(baseScore, dimensionCode, memberScores);
+                    Map<String, Object> item = new LinkedHashMap<>();
+                    item.put("id", p.getId());
+                    item.put("productId", p.getId());
+                    item.put("name", p.getName());
+                    item.put("coverImage", p.getCoverImage());
+                    item.put("price", p.getPrice());
+                    item.put("memberPrice", p.getPrice());
+                    item.put("productType", p.getProductType());
+                    item.put("source", "dimension");
+                    item.put("url", "/pages/discover-detail/product-detail/product-detail?id=" + p.getId());
+
+                    // 推荐理由
+                    String dimReason = buildRecommendationReason(p, dimensionCode, memberScores);
+                    item.put("reason", dimReason);
+
+                    // 匹配分
+                    double matchScore = calculateMatchScore(p, dimensionCode, memberScores);
+                    item.put("matchScore", matchScore);
+
+                    candidates.add(item);
+                }
+            }
+        }
+
+        // 3.5 fallback: 当 dimension_mapping 表无数据时,从 Product.domain 匹配
+        if (candidates.isEmpty()) {
+            LambdaQueryWrapper<Product> domainQw = new LambdaQueryWrapper<Product>()
+                    .eq(Product::getStatus, "on_shelf")
+                    .and(w -> w.ne(Product::getProductType, "physical").or().isNull(Product::getStock).or().gt(Product::getStock, 0))
+                    .orderByAsc(Product::getSortOrder);
+            if (dimensionCode != null && !dimensionCode.isEmpty()) {
+                domainQw.eq(Product::getDomain, dimensionCode);
+            }
+            if (!purchasedIds.isEmpty()) {
+                domainQw.notIn(Product::getId, purchasedIds);
+            }
+            SortUtil.applySort(domainQw);
+            // 商品可见性过滤(min_visible_level + vendor_visible)
+            productVisibilitySupport.applyToQuery(domainQw, userId, null);
+            List<Product> domainMatched = productMapper.selectList(domainQw);
+             HealthFilterService.FilterResult domainFilter = healthFilterService.filterProducts(healthProfile, domainMatched);
+             domainMatched = domainFilter.allowed;
+            for (Product p : domainMatched) {
+                Map<String, Object> item = new LinkedHashMap<>();
+                item.put("id", p.getId());
+                item.put("productId", p.getId());
+                item.put("name", p.getName());
+                item.put("coverImage", p.getCoverImage());
+                item.put("price", p.getPrice());
+                item.put("memberPrice", p.getPrice());
+                item.put("productType", p.getProductType());
+                item.put("source", "dimension");
+                item.put("url", "/pages/discover-detail/product-detail/product-detail?id=" + p.getId());
+                String reason = buildRecommendationReason(p, dimensionCode, memberScores);
+                item.put("reason", reason);
+                double matchScore = calculateMatchScore(p, dimensionCode, memberScores);
+                item.put("matchScore", matchScore);
+                candidates.add(item);
+            }
+        }
+
+        // 4. 关联关系推荐(动态:画像缺口、共购、复购)
+        List<Map<String, Object>> assocResults = queryAssociationRecommendations(
+                dimensionCode, familyId, memberId, purchasedIds, excludeProductIds, limit - candidates.size(), healthProfile, userId);
+
+        // 合并并去重(关联推荐优先级高于维度映射,但保留维度的reason/matchScore)
+        if (assocResults != null && !assocResults.isEmpty()) {
+            for (Map<String, Object> item : assocResults) {
+                Long prodId = (Long) item.get("id");
+                // 已在 candidates 中则跳过(由 limit 控制数量,这里不再二次去重复用 id,而是追加)
+                if (candidates.size() >= limit) break;
+                candidates.add(item);
+            }
+        }
+
+        // 内容维度阈值显隐过滤(A-后端):OR 逻辑(任一维度得分 < 阈值 → 保留),fail-open 不误隐藏
+        Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
+        if (!familyAvg.isEmpty() && !candidates.isEmpty()) {
+            List<Long> pids = candidates.stream()
+                    .map(c -> c.get("id") != null ? ((Number) c.get("id")).longValue() : null)
+                    .filter(Objects::nonNull)
+                    .collect(Collectors.toList());
+            Map<Long, List<ContentDimensionThreshold>> byId =
+                    contentDimensionThresholdService.listByContents("PRODUCT", pids);
+            DimensionThresholdFilter.filterVisible(candidates,
+                    c -> c.get("id") != null ? ((Number) c.get("id")).longValue() : null,
+                    "PRODUCT", familyAvg, byId);
+        }
+
+        // 5. 最终排序并返回
+        return sortAndReturn(candidates, limit, userId, familyId);
+    }
+
+    /**
+     * 查询关联关系推荐(画像缺口 + 共购 + 复购)
+     */
+    private List<Map<String, Object>> queryAssociationRecommendations(
+            String dimensionCode, Long familyId, Long memberId,
+            Set<Long> purchasedIds, List<Long> excludeProductIds, int reqCount,
+            HealthFilterService.HealthProfile healthProfile, Long userId) {
+
+        if (reqCount <= 0) return Collections.emptyList();
+
+        // 商品可见性上下文(min_visible_level + vendor_visible),一次性查库供各关联子方法复用
+        ProductVisibilitySupport.VisibilityContext visibilityCtx = productVisibilitySupport.buildContext(userId, null);
+        Map<String, Integer> memberScores = getMemberDimensionScores(familyId, memberId);
+        List<Map<String, Object>> results = new ArrayList<>();
+
+        // 4.1 画像缺口关联:维度得分低时推荐对应商品
+        if (dimensionCode != null && !dimensionCode.isEmpty()) {
+            List<Map<String, Object>> profileAssocs = queryProfileGapAssociations(
+                    dimensionCode, memberScores, purchasedIds, excludeProductIds, reqCount / 3, healthProfile, visibilityCtx);
+            results.addAll(profileAssocs);
+            if (results.size() >= reqCount) return results.subList(0, reqCount);
+        }
+
+        // 4.2 共购关联:买了A的用户也买了B(从订单数据挖掘)
+        if (purchasedIds != null && !purchasedIds.isEmpty()) {
+            List<Map<String, Object>> coPurchaseAssocs = queryCoPurchaseAssociations(
+                    purchasedIds, excludeProductIds, reqCount - results.size(), healthProfile, visibilityCtx);
+            results.addAll(coPurchaseAssocs);
+            if (results.size() >= reqCount) return results.subList(0, reqCount);
+        }
+
+        // 4.3 复购关联:买了A后X天再买A的关联商品
+        if (purchasedIds != null && !purchasedIds.isEmpty()) {
+            List<Map<String, Object>> repurchaseAssocs = queryRepurchaseAssociations(
+                    purchasedIds, excludeProductIds, reqCount - results.size(), healthProfile, visibilityCtx);
+            results.addAll(repurchaseAssocs);
+        }
+
+        return results;
+    }
+
+    /**
+     * 画像缺口关联:某维度得分低时,从关联关系表推荐商品
+     */
+    private List<Map<String, Object>> queryProfileGapAssociations(
+            String dimensionCode, Map<String, Integer> memberScores,
+            Set<Long> purchasedIds, List<Long> excludeProductIds, int reqCount,
+            HealthFilterService.HealthProfile healthProfile,
+            ProductVisibilitySupport.VisibilityContext visibilityCtx) {
+
+        if (reqCount <= 0) return Collections.emptyList();
+
+        // 寻找关联关系:association_type='profile_gap' 且 dimension_code 匹配
+        LambdaQueryWrapper<RecommendationProductAssociation> qw = new LambdaQueryWrapper<RecommendationProductAssociation>()
+                .eq(RecommendationProductAssociation::getAssociationType, "profile_gap")
+                .eq(RecommendationProductAssociation::getDimensionCode, dimensionCode)
+                .eq(RecommendationProductAssociation::getEnabled, 1);
+
+        // 如果有成员得分,筛选“得分低于阈值”才触发推荐
+        if (memberScores != null && !memberScores.isEmpty()) {
+            Integer score = memberScores.get(dimensionCode);
+            if (score != null && score < 70) {
+                // 分数越低,关联强度越高(可选逻辑,此处直接查出所有并按 strength 排序)
+                qw.orderByDesc(RecommendationProductAssociation::getStrength);
+            }
+        } else {
+            // 无画像数据时,默认中等强度
+            qw.orderByDesc(RecommendationProductAssociation::getStrength);
+        }
+
+        List<Map<String, Object>> results = new ArrayList<>();
+        List<RecommendationProductAssociation> assocs = recommendationProductAssociationMapper.selectList(qw);
+        for (RecommendationProductAssociation assoc : assocs) {
+            if (reqCount <= 0 || results.size() >= reqCount) break;
+            // 跳过已购商品
+            if (purchasedIds != null && purchasedIds.contains(assoc.getTargetProductId())) continue;
+            // 跳过被排除
+            if (excludeProductIds != null && excludeProductIds.contains(assoc.getTargetProductId())) continue;
+
+            Product product = productMapper.selectById(assoc.getTargetProductId());
+            if (product == null || !"on_shelf".equals(product.getStatus()) || !hasSellableStock(product)) continue;
+            if (!healthFilterService.checkProductBlocks(healthProfile, product).isEmpty()) continue;
+            if (!productVisibilitySupport.isVisibleTo(product, visibilityCtx)) continue; // 商品可见性(供应商专属/会员级别)
+
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", product.getId());
+            item.put("productId", product.getId());
+            item.put("name", product.getName());
+            item.put("coverImage", product.getCoverImage());
+            item.put("price", product.getPrice());
+            item.put("memberPrice", product.getPrice());
+            item.put("productType", product.getProductType());
+            item.put("source", "assoc_profile_gap");
+
+            // 关联强度作为匹配分
+            java.math.BigDecimal strength = assoc.getStrength();
+            item.put("matchScore", strength != null ? strength.doubleValue() / 10.0 : 0.5);
+
+            // 关联理由
+            String reason = assoc.getReason();
+            if (reason == null || reason.isEmpty()) {
+                Integer score = memberScores != null ? memberScores.get(dimensionCode) : null;
+                if (score != null && score < 50) {
+                    reason = "该维度得分偏低,重点推荐";
+                } else if (score != null && score < 70) {
+                    reason = "该维度有提升空间,推荐关注";
+                } else {
+                    reason = "根据维度匹配推荐";
+                }
+            }
+            item.put("reason", reason);
+
+            results.add(item);
+        }
+        return results;
+    }
+
+    /**
+     * 共购关联:从订单数据挖掘“买了A的用户也买了B”
+     */
+    private List<Map<String, Object>> queryCoPurchaseAssociations(
+            Set<Long> purchasedIds, List<Long> excludeProductIds, int reqCount,
+            HealthFilterService.HealthProfile healthProfile,
+            ProductVisibilitySupport.VisibilityContext visibilityCtx) {
+
+        if (reqCount <= 0 || purchasedIds == null || purchasedIds.isEmpty()) return Collections.emptyList();
+
+        List<Map<String, Object>> results = new ArrayList<>();
+
+        // 找出非空的 purchasedIds,查找关联关系
+        LambdaQueryWrapper<RecommendationProductAssociation> qw = new LambdaQueryWrapper<RecommendationProductAssociation>()
+                .eq(RecommendationProductAssociation::getAssociationType, "co_purchase")
+                .eq(RecommendationProductAssociation::getEnabled, 1)
+                .gt(RecommendationProductAssociation::getCoPurchaseCount, 0) // 只取已挖掘的
+                .orderByDesc(RecommendationProductAssociation::getCoPurchaseCount);
+
+        // 限制数量
+        if (reqCount > 0) {
+            qw.last("LIMIT " + reqCount);
+        }
+
+        List<RecommendationProductAssociation> assocs = recommendationProductAssociationMapper.selectList(qw);
+        for (RecommendationProductAssociation assoc : assocs) {
+            Long targetId = assoc.getTargetProductId();
+            if (targetId == null) continue;
+            // 跳过已购和被排除
+            if (purchasedIds.contains(targetId)) continue;
+            if (excludeProductIds != null && excludeProductIds.contains(targetId)) continue;
+
+            Product product = productMapper.selectById(targetId);
+            if (product == null || !"on_shelf".equals(product.getStatus()) || !hasSellableStock(product)) continue;
+            if (!healthFilterService.checkProductBlocks(healthProfile, product).isEmpty()) continue;
+            if (!productVisibilitySupport.isVisibleTo(product, visibilityCtx)) continue; // 商品可见性(供应商专属/会员级别)
+
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", product.getId());
+            item.put("productId", product.getId());
+            item.put("name", product.getName());
+            item.put("coverImage", product.getCoverImage());
+            item.put("price", product.getPrice());
+            item.put("memberPrice", product.getPrice());
+            item.put("productType", product.getProductType());
+            item.put("source", "assoc_co_purchase");
+
+            // 共购次数作为强度:次数越多 strength 越高
+            double strength = Math.min(1.0, assoc.getCoPurchaseCount() / 20.0); // 假设20次以上算很强
+            item.put("matchScore", strength);
+
+            // 理由:共购 X 次
+            item.put("reason", "与您常购商品共购 " + assoc.getCoPurchaseCount() + " 次");
+
+            results.add(item);
+        }
+        return results;
+    }
+
+    /**
+     * 复购关联:买了A后X天再买相关商品的关联
+     */
+    private List<Map<String, Object>> queryRepurchaseAssociations(
+            Set<Long> purchasedIds, List<Long> excludeProductIds, int reqCount,
+            HealthFilterService.HealthProfile healthProfile,
+            ProductVisibilitySupport.VisibilityContext visibilityCtx) {
+
+        if (reqCount <= 0 || purchasedIds == null || purchasedIds.isEmpty()) return Collections.emptyList();
+
+        List<Map<String, Object>> results = new ArrayList<>();
+
+        LambdaQueryWrapper<RecommendationProductAssociation> qw = new LambdaQueryWrapper<RecommendationProductAssociation>()
+                .eq(RecommendationProductAssociation::getAssociationType, "repurchase")
+                .eq(RecommendationProductAssociation::getEnabled, 1);
+
+        if (reqCount > 0) {
+            qw.last("LIMIT " + reqCount);
+        }
+
+        List<RecommendationProductAssociation> assocs = recommendationProductAssociationMapper.selectList(qw);
+        for (RecommendationProductAssociation assoc : assocs) {
+            Long targetId = assoc.getTargetProductId();
+            if (targetId == null) continue;
+            if (purchasedIds.contains(targetId)) continue;
+            if (excludeProductIds != null && excludeProductIds.contains(targetId)) continue;
+
+            Product product = productMapper.selectById(targetId);
+            if (product == null || !"on_shelf".equals(product.getStatus()) || !hasSellableStock(product)) continue;
+            if (!healthFilterService.checkProductBlocks(healthProfile, product).isEmpty()) continue;
+            if (!productVisibilitySupport.isVisibleTo(product, visibilityCtx)) continue; // 商品可见性(供应商专属/会员级别)
+
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", product.getId());
+            item.put("productId", product.getId());
+            item.put("name", product.getName());
+            item.put("coverImage", product.getCoverImage());
+            item.put("price", product.getPrice());
+            item.put("memberPrice", product.getPrice());
+            item.put("productType", product.getProductType());
+            item.put("source", "assoc_repurchase");
+
+            // 复购天数:days越小说明周期越短,推荐意图越强
+            int days = assoc.getRepurchaseDays() != null ? assoc.getRepurchaseDays() : 30;
+            double strength = 1.0 / Math.max(1, days / 7.0); // 每周递减
+            item.put("matchScore", Math.min(1.0, strength));
+
+            item.put("reason", "复购周期 " + days + " 天内关联推荐");
+
+            results.add(item);
+        }
+        return results;
+    }
+
+    /**
+     * 计算供应商优先级加分
+     * <p>
+     * 规则1:若直接引荐人是某产品供应商(supply_system.admin),优先推荐其体系内产品
+     * 规则2:沿引荐链向上追溯,找到任一层级是供应商的引荐人,优先推荐其产品
+     * 规则3:同一供应商体系引荐的用户越多,权重越高(按体系成员数加权)
+     * 补充规则:用户所属多个供应商体系时,其关联产品均优先推荐
+     */
+    private Map<Long, Double> getSupplierPriorityScores(Long userId) {
+        if (userId == null) return Collections.emptyMap();
+
+        // 1. 收集引荐链上的所有祖先(直接推荐人、间接推荐人)
+        List<ReferralTree> ancestorNodes = referralTreeMapper.selectList(
+                new LambdaQueryWrapper<ReferralTree>()
+                        .eq(ReferralTree::getMemberId, userId)
+                        .orderByAsc(ReferralTree::getLevel));
+        if (ancestorNodes.isEmpty()) return Collections.emptyMap();
+
+        // 祖先 userId -> 层级(level 越小=关系越近,权重越高)
+        Map<Long, Integer> ancestorLevels = new HashMap<>();
+        for (ReferralTree node : ancestorNodes) {
+            ancestorLevels.putIfAbsent(node.getParentId(), node.getLevel());
+        }
+
+        // 2. 找出引荐链中的供应商(adminId 对应 supply_system)
+        //    supplySystemId -> 引荐层级(取最小即最近层级,权重最高)
+        Map<Long, Integer> supplierSystemToNearestLevel = new HashMap<>();
+        for (Map.Entry<Long, Integer> entry : ancestorLevels.entrySet()) {
+            Long ancestorId = entry.getKey();
+            Integer level = entry.getValue();
+            SupplySystem system = supplySystemService.getByAdminId(ancestorId);
+            if (system != null) {
+                supplierSystemToNearestLevel.merge(system.getId(), level,
+                        (existing, newVal) -> Math.min(existing, newVal));
+            }
+        }
+
+        // 3. 也检查当前用户本身是否属于某些供应商体系(补充规则)
+        List<SupplySystemMember> userSystems = supplySystemMemberMapper.selectList(
+                new LambdaQueryWrapper<SupplySystemMember>()
+                        .eq(SupplySystemMember::getUserId, userId)
+                        .eq(SupplySystemMember::getStatus, "active"));
+        for (SupplySystemMember mem : userSystems) {
+            supplierSystemToNearestLevel.merge(mem.getSystemId(), 0,
+                    (existing, newVal) -> Math.min(existing, newVal));
+        }
+
+        if (supplierSystemToNearestLevel.isEmpty()) return Collections.emptyMap();
+
+        // 4. 计算每个供应商体系的成员数作为权重(规则3)
+        //    supplySystemId -> 加分系数 = memberCount * 0.1 / levelPenalty
+        //    levelPenalty: 直接推荐人(level=1) 系数为1.0,每远一层衰减
+        Map<Long, Double> systemBoosts = new HashMap<>();
+        for (Map.Entry<Long, Integer> sysEntry : supplierSystemToNearestLevel.entrySet()) {
+            Long systemId = sysEntry.getKey();
+            Integer level = sysEntry.getValue();
+            // 成员数
+            Long memberCount = supplySystemMemberMapper.selectCount(
+                    new LambdaQueryWrapper<SupplySystemMember>()
+                            .eq(SupplySystemMember::getSystemId, systemId)
+                            .eq(SupplySystemMember::getStatus, "active"));
+            int count = memberCount == null ? 0 : memberCount.intValue();
+            // 层级衰减:level=1(直接推荐人)不打折,level越大折扣越大
+            double levelFactor = Math.max(0.1, 1.0 - (level - 1) * 0.15);
+            // 加分系数 = 成员数 * 0.1 * 层级因子,基础分50,最大加成5分
+            double boost = Math.min(5.0, count * 0.1 * levelFactor);
+            systemBoosts.put(systemId, boost);
+        }
+
+        // 5. 按 distributionSystemId 聚合加分
+        //    同一个产品的 distributionSystemId 对应多个体系时,取最高加分
+        Map<Long, Double> productIdBoost = new HashMap<>();
+        for (Map.Entry<Long, Double> sysEntry : systemBoosts.entrySet()) {
+            Long systemId = sysEntry.getKey();
+            Double boost = sysEntry.getValue();
+            List<Product> products = productMapper.selectList(
+                    new LambdaQueryWrapper<Product>()
+                            .eq(Product::getDistributionSystemId, systemId)
+                            .eq(Product::getStatus, "on_shelf"));
+            for (Product p : products) {
+                productIdBoost.merge(p.getId(), boost, Math::max);
+            }
+        }
+
+        return productIdBoost;
+    }
+
+    /**
+     * 根据 matchScore 和供应商优先级进行最终排序
+     * 权重表有数据时按家庭权重总和排序,无权重数据时回退 matchScore
+     */
+    private List<Map<String, Object>> sortAndReturn(List<Map<String, Object>> candidates, int limit, Long userId, Long familyId) {
+        if (candidates == null || candidates.isEmpty()) return Collections.emptyList();
+        
+        // 计算供应商优先级加分(规则1~3)
+        Map<Long, Double> supplierPriorityScores = getSupplierPriorityScores(userId);
+        
+        // 将供应商优先级加入 matchScore
+        if (!supplierPriorityScores.isEmpty()) {
+            for (Map<String, Object> item : candidates) {
+                Long productId = (Long) item.get("productId");
+                Double priorityBoost = productId != null ? supplierPriorityScores.get(productId) : null;
+                Double currentScore = (Double) item.get("matchScore");
+                if (priorityBoost != null && priorityBoost > 0) {
+                    double boostedScore = (currentScore != null ? currentScore : 0) + priorityBoost;
+                    item.put("matchScore", boostedScore);
+                }
+                item.put("supplierPriorityBoost", priorityBoost != null ? priorityBoost : 0);
+            }
+        }
+        
+        // 计算每个商品的家庭权重总和(家庭聚合:Σ成员权重,方向一致均为正向)
+        Map<Long, Double> productWeightSum = new HashMap<>();
+        if (familyId != null) {
+            for (Map<String, Object> item : candidates) {
+                Long productId = (Long) item.get("productId");
+                if (productId == null) continue;
+                // 查该家庭所有成员对该商品的权重,求和
+                List<UserContentWeight> weights = userContentWeightService.listWeights(null, familyId, "product", productId);
+                double sum = 0.0;
+                if (weights != null) {
+                    for (UserContentWeight w : weights) {
+                        sum += w.getWeight() != null ? w.getWeight().doubleValue() : 0.0;
+                    }
+                }
+                productWeightSum.put(productId, sum);
+                item.put("userWeight", sum);
+            }
+        }
+        
+        // 排序:优先按用户权重(降序),权重相同或无权重数据时回退 matchScore(降序)
+        candidates.sort((a, b) -> {
+            Double weightA = productWeightSum.getOrDefault((Long) a.get("productId"), 0.0);
+            Double weightB = productWeightSum.getOrDefault((Long) b.get("productId"), 0.0);
+            int cmp = weightB.compareTo(weightA);
+            if (cmp != 0) return cmp;
+            
+            Double scoreA = (Double) a.get("matchScore");
+            Double scoreB = (Double) b.get("matchScore");
+            if (scoreA == null && scoreB == null) return 0;
+            if (scoreA == null) return 1;
+            if (scoreB == null) return -1;
+            return scoreB.compareTo(scoreA);
+        });
+        
+        // 去重(按 productId 去重)
+        Set<Long> seenIds = new HashSet<>();
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (Map<String, Object> item : candidates) {
+            Long id = (Long) item.get("id");
+            if (id == null || seenIds.contains(id)) continue;
+            seenIds.add(id);
+            if (result.size() >= limit) break;
+            result.add(item);
+        }
+        return result;
+    }
+
+    // ── 原有私有辅助方法(保持不变)──
+
+    // 仅实物商品要求库存>0(库存NULL视为可购),与 ProductOrderService 下单校验口径一致;虚拟商品不看库存
+    private boolean hasSellableStock(Product product) {
+        if (!"physical".equals(product.getProductType())) {
+            return true;
+        }
+        return product.getStock() == null || product.getStock() > 0;
+    }
+
+    /**
+     * 获取家庭成员在90天内购买过的商品ID
+     */
+    private Set<Long> getPurchasedProductIds(Long familyId, int daysAgo) {
+        Set<Long> ids = new HashSet<>();
+        if (familyId == null) return ids;
+
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_YEAR, -daysAgo);
+        Date cutoff = cal.getTime();
+
+        List<ProductOrder> orders = orderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getFamilyId, familyId)
+                        .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                        .gt(ProductOrder::getPaidAt, cutoff)
+        );
+
+        for (ProductOrder order : orders) {
+            if (order.getProductId() != null) {
+                ids.add(order.getProductId());
+            }
+        }
+        return ids;
+    }
+
+    /**
+     * 获取成员维度得分
+     */
+    private Map<String, Integer> getMemberDimensionScores(Long familyId, Long memberId) {
+        Map<String, Integer> scores = new HashMap<>();
+
+        LambdaQueryWrapper<FiveDimensionScore> qw = new LambdaQueryWrapper<>();
+        qw.eq(familyId != null, FiveDimensionScore::getFamilyId, familyId);
+        qw.eq(memberId != null, FiveDimensionScore::getMemberId, memberId);
+        qw.orderByDesc(FiveDimensionScore::getAssessedAt);
+
+        SortUtil.applySort(qw);
+        List<FiveDimensionScore> records = fiveDimensionScoreMapper.selectList(qw);
+
+        // 取每个维度的最新得分
+        Set<String> seen = new HashSet<>();
+        for (FiveDimensionScore s : records) {
+            if (s.getDimensionCode() != null && !seen.contains(s.getDimensionCode())) {
+                seen.add(s.getDimensionCode());
+                scores.put(s.getDimensionCode(), s.getScore() != null ? s.getScore() : 0);
+            }
+        }
+        return scores;
+    }
+
+    /**
+     * 对低得分维度加权 boost
+     */
+    private double applyDimensionBoost(int baseScore, String dimensionCode, Map<String, Integer> memberScores) {
+        if (dimensionCode == null || dimensionCode.isEmpty()) {
+            return baseScore;
+        }
+        Integer score = memberScores.get(dimensionCode);
+        if (score == null || score >= 70) {
+            return baseScore;
+        } else if (score >= 50) {
+            return baseScore * 1.1;
+        } else {
+            return baseScore * 1.2;
+        }
+    }
+
+    /**
+     * 计算综合匹配分
+     */
+    private double calculateMatchScore(Product product, String dimensionCode, Map<String, Integer> memberScores) {
+        int base = 70;
+        if (dimensionCode == null || dimensionCode.isEmpty()) {
+            Integer minScore = memberScores.values().stream().min(Integer::compareTo).orElse(null);
+            if (minScore != null) {
+                if (minScore < 50) base = 90;
+                else if (minScore < 70) base = 80;
+            }
+            return base;
+        }
+        Integer myScore = memberScores.get(dimensionCode);
+        if (myScore != null) {
+            if (myScore < 50) base = 90;
+            else if (myScore < 70) base = 80;
+            else base = 70;
+        }
+        return base;
+    }
+
+    /**
+     * 构建推荐理由
+     */
+    private String buildRecommendationReason(Product product, String dimensionCode, Map<String, Integer> memberScores) {
+        if (dimensionCode == null || dimensionCode.isEmpty()) {
+            return "为您推荐的好物";
+        }
+        Integer score = memberScores.get(dimensionCode);
+        if (score == null) {
+            return "根据您的维度匹配为您推荐";
+        }
+        if (score < 50) {
+            return "该维度得分偏低,重点推荐";
+        } else if (score < 70) {
+            return "该维度有提升空间,推荐关注";
+        }
+        return "丰富您的维度生活";
+    }
+
+    /**
+     * 从健康分析结果提取维度需求
+     */
+    @SuppressWarnings("unchecked")
+    private List<String> extractDimensionNeedsFromHealth(Object analysis) {
+        List<String> dims = new ArrayList<>();
+        if (analysis == null) return dims;
+
+        try {
+            if (analysis instanceof Map) {
+                Map<String, Object> map = (Map<String, Object>) analysis;
+                Object nutritionScore = map.get("nutritionScore");
+                Object gutScore = map.get("gutHealthScore");
+                Object overallScore = map.get("overallScore");
+
+                if (nutritionScore instanceof Number && ((Number) nutritionScore).intValue() < 60) {
+                    dims.add("body");
+                }
+                if (gutScore instanceof Number && ((Number) gutScore).intValue() < 60) {
+                    dims.add("body");
+                }
+                if (overallScore instanceof Number && ((Number) overallScore).intValue() < 60) {
+                    dims.add("body");
+                    dims.add("mind");
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析健康分析结果维度失败: {}", e.getMessage());
+        }
+        return dims;
+    }
+
+    /**
+     * 从认知测评结果提取弱维度
+     */
+    @SuppressWarnings("unchecked")
+    private List<String> extractDimensionNeedsFromCognitive(Object analysis) {
+        List<String> dims = new ArrayList<>();
+        if (analysis == null) return dims;
+
+        try {
+            if (analysis instanceof List) {
+                List<String> weakDims = (List<String>) analysis;
+                for (String dim : weakDims) {
+                    if ("focusScore".equals(dim) || "processingSpeedScore".equals(dim)) {
+                        dims.add("wisdom");
+                    } else if ("attentionScore".equals(dim)) {
+                        dims.add("mind");
+                    } else if ("memoryScore".equals(dim)) {
+                        dims.add("wisdom");
+                    } else {
+                        dims.add(dim);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析认知测评结果维度失败: {}", e.getMessage());
+        }
+        return dims;
+    }
+
+    /**
+     * 报告关联推荐(健康报告/认知测评触发)
+     *
+     * @param reportType 报告类型: "health_report" 或 "cognitive_assessment"
+     * @param analysis   分析结果(可为null,由内部推断维度)
+     * @param userId     用户ID
+     * @param limit      返回数量
+     * @return 推荐商品列表
+     */
+    public List<Map<String, Object>> getReportRelatedProducts(
+            String reportType, Object analysis, Long userId, int limit) {
+
+        // 从用户画像中提取弱维度
+        List<String> dimensionCodes = new ArrayList<>();
+        if ("health_report".equals(reportType)) {
+            dimensionCodes = extractDimensionNeedsFromHealth(analysis);
+        } else if ("cognitive_assessment".equals(reportType)) {
+            dimensionCodes = extractDimensionNeedsFromCognitive(analysis);
+        }
+
+        if (dimensionCodes.isEmpty()) {
+            dimensionCodes.add("body");
+        }
+
+        // 去重后为每个维度查询关联推荐
+        List<String> uniqueDims = dimensionCodes.stream().distinct().collect(Collectors.toList());
+        Set<Long> seenProductIds = new HashSet<>();
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (String dim : uniqueDims) {
+            if (result.size() >= limit) break;
+            // 获取该维度的关联推荐(含画像缺口、共购、复购)
+            List<Map<String, Object>> prods = getDimensionRecommendations(dim, null, null, null, limit - result.size(), null);
+            for (Map<String, Object> p : prods) {
+                Long pid = (Long) p.get("id");
+                if (pid == null || seenProductIds.contains(pid)) continue;
+                seenProductIds.add(pid);
+                p.put("triggerDimension", dim);
+                result.add(p);
+            }
+        }
+
+        return result;
+    }
+
+    /**
+     * 文章关联商品推荐:通过文章标签与商品标签匹配,按 标签匹配数 &gt; 用户权重 &gt; 家庭权重 &gt; 销量 排序
+     *
+     * @param articleId 文章ID
+     * @param userId    当前用户ID(可为空,用于用户权重)
+     * @param familyId  家庭ID(可为空,用于家庭权重)
+     * @param limit     返回数量
+     * @return 关联商品列表
+     */
+    /**
+     * 获取文章关联商品的完整候选列表(含标签匹配结果或首页推荐兜底)。
+     * 调用方自行切片实现分页(与 {@link #getDimensionRecommendations} 保持一致的分页语义)。
+     *
+     * @param articleId 文章ID
+     * @param userId    当前用户ID(可为空)
+     * @param familyId  家庭ID(可为空)
+     * @param memberId  成员ID(可为空,兜底首页推荐用于健康画像)
+     * @param limit     候选上限(0 表示不限制,由调用方决定分页窗口)
+     * @return 关联商品完整列表(标签匹配优先,无匹配则首页推荐兜底;均为空时返回空列表)
+     */
+    public List<Map<String, Object>> getArticleRelatedProductsFull(Long articleId, Long userId, Long familyId, Long memberId, int limit) {
+        if (articleId == null) return Collections.emptyList();
+        int fetchLimit = limit > 0 ? limit : Integer.MAX_VALUE;
+
+        // 1. 优先按文章标签匹配商品;若无标签关联商品,兜底返回首页推荐商品(与首页推荐区块同源,含健康画像过滤与个性化排序)
+        List<Map<String, Object>> tagged = getArticleTagMatchedProducts(articleId, userId, familyId, fetchLimit);
+        if (tagged != null && !tagged.isEmpty()) {
+            return tagged;
+        }
+        log.info("文章[{}]无标签关联商品,按首页推荐商品兜底返回", articleId);
+        List<Map<String, Object>> fallback = getDimensionRecommendations(null, familyId, memberId, null, fetchLimit, userId);
+        if (fallback == null || fallback.isEmpty()) {
+            return Collections.emptyList();
+        }
+        for (Map<String, Object> item : fallback) {
+            item.put("reason", "暂无标签关联商品,按首页推荐展示");
+            item.put("source", "home_fallback");
+        }
+        return fallback;
+    }
+
+    public List<Map<String, Object>> getArticleRelatedProducts(Long articleId, Long userId, Long familyId, Long memberId, int limit) {
+        if (articleId == null || limit <= 0) return Collections.emptyList();
+        List<Map<String, Object>> all = getArticleRelatedProductsFull(articleId, userId, familyId, memberId, limit);
+        if (all.size() <= limit) return all;
+        return all.subList(0, limit);
+    }
+
+    /**
+     * 文章标签匹配商品推荐(包装方法):通过文章标签与商品标签匹配,按 标签匹配数 > 用户权重 > 家庭权重 > 销量 排序
+     */
+    private List<Map<String, Object>> getArticleTagMatchedProducts(Long articleId, Long userId, Long familyId, int limit) {
+        Article article = articleMapper.selectById(articleId);
+        if (article == null || article.getTags() == null || article.getTags().trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        List<String> articleTags = parseTagList(article.getTags());
+        // 文章场景无需排除商品(文章与商品主键分属不同表),excludeProductId 传 null
+        return getTagMatchedProducts(articleTags, null, userId, familyId, limit, "文章", "article_tag");
+    }
+
+    /**
+     * 商品详情页「相关商品」完整候选列表:按商品标签匹配商品(排除自身),排序与分页语义与文章关联商品一致。
+     * 调用方自行切片实现分页。
+     *
+     * @param productId 商品ID
+     * @param userId    当前用户ID(可为空,用于用户权重)
+     * @param familyId  家庭ID(可为空,用于家庭权重)
+     * @param limit     候选上限(0 表示不限制,由调用方决定分页窗口)
+     * @return 关联商品完整列表(无匹配时返回空列表)
+     */
+    public List<Map<String, Object>> getRelatedProductsByProductFull(Long productId, Long userId, Long familyId, int limit) {
+        if (productId == null) return Collections.emptyList();
+        Product product = productMapper.selectById(productId);
+        if (product == null || product.getTags() == null || product.getTags().trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        List<String> tags = parseTagList(product.getTags());
+        return getTagMatchedProducts(tags, productId, userId, familyId, limit, "商品", "product_tag");
+    }
+
+    /**
+     * 相关商品(按源标签匹配,通用入口):供内容关联服务(活动 ↔ 商品)复用,
+     * 语义与 {@link #getRelatedProductsByProductFull} 一致:标签匹配数 > 用户权重 > 家庭权重 > 销量。
+     *
+     * @param sourceTags       源标签集合(来自活动/商品等)
+     * @param excludeProductId 需排除的商品ID(商品源排除自身;其他源为 null)
+     * @param userId           当前用户ID(可为空,用于用户权重)
+     * @param familyId         家庭ID(可为空,用于家庭权重)
+     * @param limit            返回数量上限
+     * @param sourceDesc       来源描述(如"活动"),用于 reason 文案
+     * @param sourceCode       来源编码(如 activity_tag),写入 source 字段
+     * @return 关联商品列表(无匹配时返回空列表)
+     */
+    public List<Map<String, Object>> getRelatedProductsByTags(List<String> sourceTags, Long excludeProductId,
+                                                             Long userId, Long familyId, int limit,
+                                                             String sourceDesc, String sourceCode) {
+        return getTagMatchedProducts(sourceTags, excludeProductId, userId, familyId, limit, sourceDesc, sourceCode);
+    }
+
+    /**
+     * 标签匹配商品推荐核心逻辑:通过源标签(文章/商品)与商品标签匹配,按 标签匹配数 > 用户权重 > 家庭权重 > 销量 排序
+     *
+     * @param sourceTags       源标签集合(来自文章或商品)
+     * @param excludeProductId 需排除的商品ID(商品关联商品时排除自身;文章关联商品时为 null)
+     * @param userId           当前用户ID(可为空,用于用户权重)
+     * @param familyId         家庭ID(可为空,用于家庭权重)
+     * @param limit            返回数量
+     * @param sourceDesc       来源描述("文章"/"商品",用于 reason 文案)
+     * @param sourceCode       来源编码(article_tag/product_tag,写入 source 字段)
+     * @return 关联商品列表(无匹配时返回空列表,由调用方决定是否兜底)
+     */
+    private List<Map<String, Object>> getTagMatchedProducts(List<String> sourceTags, Long excludeProductId,
+                                                            Long userId, Long familyId, int limit,
+                                                            String sourceDesc, String sourceCode) {
+        if (sourceTags == null || sourceTags.isEmpty() || limit <= 0) {
+            return Collections.emptyList();
+        }
+        Set<String> sourceTagSet = new HashSet<>(sourceTags);
+
+        // 2. 查询所有在售且有库存的商品
+        LambdaQueryWrapper<Product> tagWrapper = new LambdaQueryWrapper<Product>()
+                .eq(Product::getStatus, "on_shelf")
+                .and(w -> w.ne(Product::getProductType, "physical").or().isNull(Product::getStock).or().gt(Product::getStock, 0));
+        // 商品可见性过滤(min_visible_level + vendor_visible)
+        productVisibilitySupport.applyToQuery(tagWrapper, userId, null);
+        List<Product> products = productMapper.selectList(tagWrapper);
+        if (products == null || products.isEmpty()) return Collections.emptyList();
+
+        // 3. 预加载用户权重(推荐曝光日志:购买=1.0,点击=0.6)
+        Map<Long, Double> userWeights = new HashMap<>();
+        if (userId != null) {
+            List<ProductRecommendationLog> logs = productRecommendationLogMapper.selectList(
+                    new LambdaQueryWrapper<ProductRecommendationLog>()
+                            .eq(ProductRecommendationLog::getUserId, userId));
+            if (logs != null) {
+                for (ProductRecommendationLog log : logs) {
+                    if (log.getProductId() == null) continue;
+                    double w = userWeights.getOrDefault(log.getProductId(), 0.0);
+                    if (log.getWasPurchased() != null && log.getWasPurchased() == 1) {
+                        w += 1.0;
+                    } else if (log.getWasClicked() != null && log.getWasClicked() == 1) {
+                        w += 0.6;
+                    }
+                    userWeights.put(log.getProductId(), w);
+                }
+            }
+        }
+
+        // 4. 预加载家庭权重(家庭订单数量)
+        Map<Long, Double> familyWeights = new HashMap<>();
+        if (familyId != null) {
+            List<ProductOrder> orders = orderMapper.selectList(
+                    new LambdaQueryWrapper<ProductOrder>()
+                            .eq(ProductOrder::getFamilyId, familyId)
+                            .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed"));
+            if (orders != null) {
+                for (ProductOrder order : orders) {
+                    if (order.getProductId() == null) continue;
+                    familyWeights.merge(order.getProductId(), 1.0, Double::sum);
+                }
+            }
+        }
+
+        // 5. 计算标签匹配数与权重,构建候选列表
+        List<Map<String, Object>> candidates = new ArrayList<>();
+        for (Product product : products) {
+            if (excludeProductId != null && excludeProductId.equals(product.getId())) continue;
+            if (product.getTags() == null || product.getTags().trim().isEmpty()) continue;
+            List<String> productTags = parseTagList(product.getTags());
+            if (productTags.isEmpty()) continue;
+
+            int matchCount = 0;
+            for (String tag : productTags) {
+                if (sourceTagSet.contains(tag)) matchCount++;
+            }
+            if (matchCount == 0) continue;
+
+            double userWeight = userWeights.getOrDefault(product.getId(), 0.0);
+            double familyWeight = familyWeights.getOrDefault(product.getId(), 0.0);
+
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", product.getId());
+            item.put("productId", product.getId());
+            item.put("name", product.getName());
+            item.put("coverImage", product.getCoverImage());
+            item.put("price", product.getPrice());
+            item.put("memberPrice", product.getMemberPrice() != null ? product.getMemberPrice() : product.getPrice());
+            item.put("productType", product.getProductType());
+            item.put("tagMatchCount", matchCount);
+            item.put("userWeight", userWeight);
+            item.put("familyWeight", familyWeight);
+            item.put("reason", "与" + sourceDesc + "标签匹配 " + matchCount + " 个标签");
+            item.put("source", sourceCode);
+            item.put("url", "/pages/discover-detail/product-detail/product-detail?id=" + product.getId());
+            candidates.add(item);
+        }
+
+        // 6. 排序:标签匹配数(降序) > 用户权重(降序) > 家庭权重(降序) > 销量(降序)
+        candidates.sort((a, b) -> {
+            int matchA = (Integer) a.get("tagMatchCount");
+            int matchB = (Integer) b.get("tagMatchCount");
+            if (matchA != matchB) return matchB - matchA;
+
+            double userA = (Double) a.get("userWeight");
+            double userB = (Double) b.get("userWeight");
+            if (userA != userB) return Double.compare(userB, userA);
+
+            double familyA = (Double) a.get("familyWeight");
+            double familyB = (Double) b.get("familyWeight");
+            if (familyA != familyB) return Double.compare(familyB, familyA);
+
+            Product pa = findProductById(products, (Long) a.get("productId"));
+            Product pb = findProductById(products, (Long) b.get("productId"));
+            int salesA = pa != null && pa.getSalesCount() != null ? pa.getSalesCount() : 0;
+            int salesB = pb != null && pb.getSalesCount() != null ? pb.getSalesCount() : 0;
+            return salesB - salesA;
+        });
+
+        // 7. 截取 limit 条
+        if (candidates.size() > limit) {
+            return candidates.subList(0, limit);
+        }
+        return candidates;
+    }
+
+    /** 解析标签 JSON 数组字符串(兼容逗号分隔) */
+    private List<String> parseTagList(String tagsJson) {
+        if (tagsJson == null || tagsJson.trim().isEmpty()) return Collections.emptyList();
+        String trimmed = tagsJson.trim();
+        try {
+            if (trimmed.startsWith("[")) {
+                com.alibaba.fastjson.JSONArray arr = com.alibaba.fastjson.JSON.parseArray(trimmed);
+                if (arr == null) return Collections.emptyList();
+                List<String> tags = new ArrayList<>();
+                for (int i = 0; i < arr.size(); i++) {
+                    Object o = arr.get(i);
+                    if (o != null && !o.toString().trim().isEmpty()) {
+                        tags.add(o.toString().trim());
+                    }
+                }
+                return tags;
+            }
+            List<String> tags = new ArrayList<>();
+            for (String raw : trimmed.split(",")) {
+                String tag = raw.trim();
+                if (!tag.isEmpty()) tags.add(tag);
+            }
+            return tags;
+        } catch (Exception e) {
+            log.warn("解析标签失败: {}", e.getMessage());
+            return Collections.emptyList();
+        }
+    }
+
+    /** 在产品列表中查找商品 */
+    private Product findProductById(List<Product> products, Long id) {
+        if (products == null || id == null) return null;
+        for (Product p : products) {
+            if (id.equals(p.getId())) return p;
+        }
+        return null;
+    }
+}

+ 80 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewService.java

@@ -0,0 +1,80 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.ProductReviewRequest;
+import com.etotem.cfc.dto.ProductReviewResponse;
+
+import java.util.Map;
+
+/**
+ * 普通商品评价服务(能力键 {@code shop.review.create} / {@code shop.review.detail} /
+ * {@code shop.review.my})。
+ *
+ * <p>独立于活动评价 {@link ReviewOrderService}(PRD P0-A:活动链路零改动,不走复用)。
+ * 设计 {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §5.3 类图。</p>
+ */
+public interface ProductReviewService {
+
+    /**
+     * 创建商品订单评价(一单一评,90 天窗口)。
+     *
+     * @param request    R1 入参 {orderId, rating(1-5), reviewText(≤500), images[]≤3}
+     * @param reviewerId 评价人ID(登录买家 userId)
+     * @return 成功消息;校验不通过抛 {@link RuntimeException}
+     */
+    String createReview(ProductReviewRequest request, Long reviewerId);
+
+    /**
+     * 评价详情/去评价按钮态(设计 §3.1 R2:订单详情页「去评价」按钮 + 已评展示)。
+     *
+     * @param orderId 订单主键
+     * @param userId  登录用户ID(下单人/商家)
+     * @return {@link ProductReviewResponse}:review 已评记录(未评为 null)、
+     *         canReview 可评态(review==null 且可评时 true)、reviewHint 提示文案
+     */
+    ProductReviewResponse detail(Long orderId, Long userId);
+
+    /**
+     * 我的评价 + 待评价入口(R5,能力键 {@code shop.review.my})。
+     *
+     * <p>设计 §3.1 R5:出参 {@code {reviews[], reviewableOrders[], reviewableCount}}。
+     * {@code reviews[]} 为当前买家按 {@code review_at} 倒序分页的我的评价列表;
+     * {@code reviewableOrders[]} 为待评价订单(completed 且 90 天窗口内且未评且
+     * 非 activity 的买家本人订单,见 {@code ProductReviewMapper.findReviewableOrderIds}),
+     * {@code reviewableCount} = 待评价条数。</p>
+     *
+     * @param userId 登录买家 userId(鉴权=登录买家,本人数据)
+     * @param page   页码(从 1 开始)
+     * @param size   每页条数
+     * @return Map:{reviews[], reviewableOrders[], reviewableCount}
+     */
+    Map<String, Object> my(Long userId, int page, int size);
+
+    /**
+     * 商品详情页评价列表(R3,能力键 {@code shop.review.list},公开只读)。
+     *
+     * <p>设计 §3.1 R3:出参 {@code {total, avgRating, records[]}}——
+     * {@code total} / {@code avgRating} 来自 {@link com.etotem.cfc.mapper.ProductReviewMapper#statsByProduct(Long)}
+     * 聚合,{@code records} 来自 {@link com.etotem.cfc.mapper.ProductReviewMapper#listByProduct(Long, int, int)}
+     * 分页(仅展示态 status=1,按 review_at DESC 倒序)。与 {@code my} 不同,本方法不依赖登录态。</p>
+     *
+     * @param productId 商品主键
+     * @param page      页码(从 1 开始)
+     * @param size      每页条数
+     * @return Map:{total, avgRating, records}
+     */
+    Map<String, Object> listByProduct(Long productId, int page, int size);
+
+    /**
+     * 商家回复商品评价(R4,能力键 {@code shop.review.reply})。
+     *
+     * <p>设计 §3.1 R4:鉴权=登录商家本人({@code product.vendorId==operatorId}),入参
+     * {@code {reviewId, replyText(≤500)}};一评一回复覆盖式写回
+     * {@code replyText/repliedAt/replyBy};无重复/多次回复历史。</p>
+     *
+     * @param reviewId   评价主键(必填)
+     * @param replyText  回复文字(≤500 字)
+     * @param operatorId 登录商家 userId(须为评价所属商品的商家)
+     * @return 成功消息;校验不通过抛 {@link RuntimeException}
+     */
+    String reply(Long reviewId, String replyText, Long operatorId);
+}

+ 292 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewServiceImpl.java

@@ -0,0 +1,292 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.dto.ProductReviewRequest;
+import com.etotem.cfc.dto.ProductReviewResponse;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.ProductReview;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.ProductReviewMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 普通商品评价服务实现(能力键 {@code shop.review.create} / {@code shop.review.detail} /
+ * {@code shop.review.my},R1 + R2 + R5)。
+ *
+ * <p>设计 {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §3.1 R1 校验链:
+ * 订单存在 / {@code productType != 'activity'}(活动评价零污染)/ {@code status=completed} /
+ * {@code buyerId==userId}(评价人为下单人本人)/ {@code confirmTime >= now-90d}(Q4 窗口)/
+ * {@link ProductReviewMapper#findByOrderId} 幂等(一单一评,表唯一键 {@code uk_order_id})。
+ * §3.1 R2:{@link #detail} 判定「去评价」按钮态(completed + 90 天窗口 + 未评)。</p>
+ */
+@Service
+public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, ProductReview>
+        implements ProductReviewService {
+
+    /** 90 天评价窗口(Q4 默认口径)。 */
+    private static final int REVIEW_WINDOW_DAYS = 90;
+
+    @Resource
+    private ProductReviewMapper reviewMapper;
+
+    @Resource
+    private ProductOrderMapper orderMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Override
+    @Transactional
+    public String createReview(ProductReviewRequest request, Long reviewerId) {
+        // 入参守卫
+        if (request == null || request.getOrderId() == null) {
+            throw new RuntimeException("订单ID不能为空");
+        }
+        if (request.getRating() == null || request.getRating() < 1 || request.getRating() > 5) {
+            throw new RuntimeException("评价星级必须在 1-5 之间");
+        }
+        if (request.getReviewText() != null && request.getReviewText().length() > 500) {
+            throw new RuntimeException("评价文字不能超过500字");
+        }
+        List<String> images = request.getImages();
+        if (images != null && images.size() > 3) {
+            throw new RuntimeException("晒图最多3张");
+        }
+
+        Long orderId = request.getOrderId();
+
+        // 1) 订单存在
+        ProductOrder order = orderMapper.selectById(orderId);
+        if (order == null) {
+            throw new RuntimeException("订单不存在");
+        }
+        // 2) 活动评价零污染(普通商品评价域,活动订单走 ReviewOrderService)
+        if ("activity".equals(order.getProductType())) {
+            throw new RuntimeException("活动订单不支持商品评价");
+        }
+        // 3) 状态 = completed
+        if (!"completed".equals(order.getStatus())) {
+            throw new RuntimeException("订单未完成,暂不可评价");
+        }
+        // 4) 评价人为下单人本人
+        if (order.getBuyerId() == null || !order.getBuyerId().equals(reviewerId)) {
+            throw new RuntimeException("只能评价本人订单");
+        }
+        // 5) 90 天窗口:confirmTime >= now - 90d
+        Date confirmTime = order.getConfirmTime();
+        if (confirmTime == null) {
+            throw new RuntimeException("订单缺少确认收货时间,暂不可评价");
+        }
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -REVIEW_WINDOW_DAYS);
+        if (confirmTime.before(cal.getTime())) {
+            throw new RuntimeException("评价窗口已过期(确认收货后90天内可评价)");
+        }
+        // 6) 一单一评幂等(findByOrderId 查重,唯一键 uk_order_id 兜底)
+        ProductReview existing = reviewMapper.findByOrderId(orderId);
+        if (existing != null) {
+            throw new RuntimeException("该订单已评价");
+        }
+
+        Date now = new Date();
+        ProductReview review = new ProductReview();
+        review.setOrderId(orderId);
+        review.setProductId(order.getProductId());
+        review.setReviewerId(reviewerId);
+        review.setRating(request.getRating());
+        review.setReviewText(request.getReviewText() != null ? request.getReviewText() : "");
+        review.setImages(images != null && !images.isEmpty() ? JSON.toJSONString(images) : null);
+        review.setStatus(1);
+        review.setReviewAt(now);
+        review.setCreatedAt(now);
+        review.setUpdatedAt(now);
+        reviewMapper.insert(review);
+        return "评价提交成功";
+    }
+
+    @Override
+    public ProductReviewResponse detail(Long orderId, Long userId) {
+        // 入参守卫
+        if (orderId == null) {
+            throw new RuntimeException("订单ID不能为空");
+        }
+        // 订单存在
+        ProductOrder order = orderMapper.selectById(orderId);
+        if (order == null) {
+            throw new RuntimeException("订单不存在");
+        }
+        // 已评记录(未评为 null)
+        ProductReview review = reviewMapper.findByOrderId(orderId);
+
+        ProductReviewResponse resp = new ProductReviewResponse();
+        resp.setReview(review);
+        if (review != null) {
+            resp.setCanReview(false);
+            resp.setReviewHint("该订单已评价");
+            return resp;
+        }
+        if (!"completed".equals(order.getStatus())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("订单完成后可评价");
+            return resp;
+        }
+        if ("activity".equals(order.getProductType())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("活动订单暂不支持评价");
+            return resp;
+        }
+        if (!inReviewWindow(order.getConfirmTime())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("确认收货后90天内可评价");
+            return resp;
+        }
+        resp.setCanReview(true);
+        resp.setReviewHint("");
+        return resp;
+    }
+
+    @Override
+    public Map<String, Object> my(Long userId, int page, int size) {
+        int pageNum = Math.max(page, 1);
+        int pageSize = Math.max(size, 1);
+
+        Map<String, Object> result = new HashMap<>();
+
+        // 1) 我的评价列表:按 reviewer_id 查,review_at 倒序分页
+        List<ProductReview> reviews = lambdaQuery()
+                .eq(ProductReview::getReviewerId, userId)
+                .orderByDesc(ProductReview::getReviewAt)
+                .last("LIMIT " + ((long) (pageNum - 1) * pageSize) + "," + pageSize)
+                .list();
+        result.put("reviews", reviews == null ? Collections.emptyList() : reviews);
+
+        // 2) 待评价订单:completed 且 90 天窗口内、且未评、且非 activity 的买家本人订单
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -REVIEW_WINDOW_DAYS);
+        List<Long> reviewableOrderIds = reviewMapper.findReviewableOrderIds(userId, cal.getTime());
+        if (reviewableOrderIds == null || reviewableOrderIds.isEmpty()) {
+            result.put("reviewableOrders", Collections.emptyList());
+            result.put("reviewableCount", 0);
+            return result;
+        }
+
+        // selectBatchIds 不保序,按 findReviewableOrderIds 返回的 confirm_time 倒序顺序重组
+        List<ProductOrder> fetched = orderMapper.selectBatchIds(reviewableOrderIds);
+        Map<Long, ProductOrder> byId = new HashMap<>();
+        if (fetched != null) {
+            for (ProductOrder o : fetched) {
+                byId.put(o.getId(), o);
+            }
+        }
+        List<ProductOrder> reviewableOrders = new ArrayList<>();
+        for (Long id : reviewableOrderIds) {
+            ProductOrder o = byId.get(id);
+            if (o != null) {
+                reviewableOrders.add(o);
+            }
+        }
+        result.put("reviewableOrders", reviewableOrders);
+        result.put("reviewableCount", reviewableOrders.size());
+        return result;
+    }
+
+    @Override
+    @Transactional
+    public String reply(Long reviewId, String replyText, Long operatorId) {
+        // 入参守卫(顺序:先校验,再查库,避免无效请求触达 DB)
+        if (reviewId == null) {
+            throw new RuntimeException("评价ID不能为空");
+        }
+        if (replyText == null || replyText.trim().isEmpty()) {
+            throw new RuntimeException("回复内容不能为空");
+        }
+        if (replyText.length() > 500) {
+            throw new RuntimeException("商家回复不能超过500字");
+        }
+        if (operatorId == null) {
+            throw new RuntimeException("登录商家身份缺失");
+        }
+
+        // 评价存在性:不存在直接拒绝,不写库
+        ProductReview review = reviewMapper.selectById(reviewId);
+        if (review == null) {
+            throw new RuntimeException("评价不存在");
+        }
+
+        // 鉴权:评价对应商品须属于当前登录商家(product.vendorId == operatorId)
+        Long productId = review.getProductId();
+        if (productId == null) {
+            throw new RuntimeException("评价未关联商品,无法回复");
+        }
+        Product product = productMapper.selectById(productId);
+        if (product == null || product.getVendorId() == null
+                || !product.getVendorId().equals(operatorId)) {
+            throw new RuntimeException("无权回复非本人商品的评价");
+        }
+
+        // 一评一回复覆盖式更新(P2 再议多次回复)
+        Date now = new Date();
+        review.setReplyText(replyText);
+        review.setRepliedAt(now);
+        review.setReplyBy(operatorId);
+        review.setUpdatedAt(now);
+        reviewMapper.updateById(review);
+        return "回复成功";
+    }
+
+    /**
+     * 商品详情页评价列表(R3,能力键 {@code shop.review.list},公开只读)。
+     *
+     * <p>读 {@link ProductReviewMapper#statsByProduct} 聚合 total + avgRating,
+     * 读 {@link ProductReviewMapper#listByProduct} 分页 records,组装只读视图
+     * {@code {total, avgRating, records}}。仅展示态 status=1、按 review_at DESC 倒序由 Mapper XML 保证。</p>
+     */
+    @Override
+    public Map<String, Object> listByProduct(Long productId, int page, int size) {
+        int pageNum = Math.max(page, 1);
+        int pageSize = Math.max(size, 1);
+        int offset = (pageNum - 1) * pageSize;
+
+        Map<String, Object> result = new HashMap<>();
+
+        // 1) 星级聚合:total + avgRating(Mapper XML 已限定 status=1 且 AVG(rating))
+        Map<String, Object> stats = reviewMapper.statsByProduct(productId);
+        if (stats != null) {
+            result.put("total", stats.get("total"));
+            result.put("avgRating", stats.get("avgRating"));
+        } else {
+            result.put("total", 0L);
+            result.put("avgRating", null);
+        }
+
+        // 2) 评价记录分页(含商家回复,按 review_at DESC 倒序)
+        List<ProductReview> records = reviewMapper.listByProduct(productId, offset, pageSize);
+        result.put("records", records == null ? Collections.emptyList() : records);
+        return result;
+    }
+
+    /**
+     * 90 天评价窗口判定:confirmTime 存在且 >= now - 90d。
+     */
+    private boolean inReviewWindow(Date confirmTime) {
+        if (confirmTime == null) {
+            return false;
+        }
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -REVIEW_WINDOW_DAYS);
+        return !confirmTime.before(cal.getTime());
+    }
+}

+ 808 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductService.java

@@ -0,0 +1,808 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.GiftConfigVO;
+import com.etotem.cfc.dto.MembershipLevelDTO;
+import com.etotem.cfc.dto.ProductDTO;
+import com.etotem.cfc.dto.ProductListQueryDTO;
+import com.etotem.cfc.entity.AssessmentProduct;
+import com.etotem.cfc.entity.ContentDimensionThreshold;
+import com.etotem.cfc.entity.GrowthArchiveProduct;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductGiftRule;
+import com.etotem.cfc.entity.ProductComboItem;
+import com.etotem.cfc.entity.ProductSku;
+import com.etotem.cfc.entity.SupplySystemMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductSkuMapper;
+import com.etotem.cfc.mapper.SupplySystemMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.support.ProductVisibilitySupport;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.DimensionCodes;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class ProductService {
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private SupplySystemMemberMapper supplySystemMemberMapper;
+
+    @Resource
+    private ProductVisibilitySupport productVisibilitySupport;
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private ProductGiftRuleService productGiftRuleService;
+
+    @Resource
+    private ProductGiftService productGiftService;
+
+    @Resource
+    private AssessmentProductService assessmentProductService;
+
+    @Resource
+    private GrowthArchiveProductService growthArchiveProductService;
+
+    @Resource
+    private NutritionProductService nutritionProductService;
+
+    @Resource
+    private ProductDeliveryConfigService productDeliveryConfigService;
+
+    @Resource
+    private ProductSkuMapper productSkuMapper;
+    @Resource
+    private ComboService comboService;
+
+    @Resource
+    private FiveDimensionScoreService fiveDimensionScoreService;
+
+    @Resource
+    private ContentDimensionThresholdService contentDimensionThresholdService;
+
+    public Product getById(Long id) {
+        return productMapper.selectById(id);
+    }
+
+    /**
+     * 按维度查询上架商品(用于商品组合方案生成)
+     * 支持价格区间筛选,返回前 limit 个上架商品
+     *
+     * @param dimensionCode 维度码 (body/mind/wisdom/action/wealth)
+     * @param minPrice      最低价(分,可为 null)
+     * @param maxPrice      最高价(分,可为 null)
+     * @param limit         最大返回数量
+     * @return 上架且维度匹配的商品列表
+     */
+    public List<Product> listByDimension(String dimensionCode, Integer minPrice, Integer maxPrice, int limit, Long userId) {
+        if (dimensionCode == null || dimensionCode.isEmpty() || !DimensionCodes.isValid(dimensionCode)) {
+            return new ArrayList<>();
+        }
+        String dim = dimensionCode.trim();
+        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+                .eq(Product::getStatus, "on_shelf")
+                .and(w -> w
+                        .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                        .or().eq(Product::getDomain, dim));
+        if (minPrice != null) {
+            wrapper.ge(Product::getPrice, minPrice);
+        }
+        if (maxPrice != null) {
+            wrapper.le(Product::getPrice, maxPrice);
+        }
+        // 商品可见性过滤(min_visible_level + vendor_visible)
+        productVisibilitySupport.applyToQuery(wrapper, userId, null);
+        wrapper.orderByAsc(Product::getSortOrder).orderByAsc(Product::getId).last("LIMIT " + Math.max(1, limit));
+        return productMapper.selectList(wrapper);
+    }
+
+    /**
+     * 按维度批量查询上架商品(五维方案生成用)
+     * 对每个维度码调用 listByDimension 并返回 维度码→商品列表 的映射
+     *
+     * @param dimensionCodes 维度码列表
+     * @param limitPerDim    每维度最大返回数量
+     * @return 维度码→上架商品列表
+     */
+    public Map<String, List<Product>> listByDimensions(List<String> dimensionCodes, int limitPerDim, Long userId) {
+        Map<String, List<Product>> result = new LinkedHashMap<>();
+        if (dimensionCodes == null) return result;
+        for (String dim : dimensionCodes) {
+            if (dim != null && !dim.isEmpty()) {
+                result.put(dim, listByDimension(dim, null, null, limitPerDim, userId));
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 按商品名称精确查找(用于占位 SKU 名解析)
+     */
+    public Product findByName(String name) {
+        if (name == null || name.trim().isEmpty()) return null;
+        return productMapper.selectOne(new LambdaQueryWrapper<Product>()
+                .eq(Product::getName, name.trim())
+                .last("LIMIT 1"));
+    }
+
+    public Result<Map<String, Object>> list(ProductListQueryDTO query, Long userId, String role) {
+        Page<Product> page = new Page<>(query.getPage(), query.getSize());
+        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+            .eq(Product::getStatus, "on_shelf");
+        // growthRelated=true: 仅返回成长档案关联商品,按 products.sort_order 升序展示
+        if (Boolean.TRUE.equals(query.getGrowthRelated())) {
+            List<Long> productIds = growthArchiveProductService.getActiveRules().stream()
+                .map(GrowthArchiveProduct::getProductId)
+                .collect(Collectors.toList());
+            if (productIds.isEmpty()) {
+                Map<String, Object> empty = new HashMap<>();
+                empty.put("records", new ArrayList<>());
+                empty.put("total", 0L);
+                empty.put("page", page.getCurrent());
+                empty.put("size", page.getSize());
+                return Result.success(empty);
+            }
+wrapper.in(Product::getId, productIds)
+                   .orderByAsc(Product::getSortOrder);
+        } else {
+            wrapper.orderByAsc(Product::getSortOrder)
+                   .orderByDesc(Product::getCreatedAt);
+        }
+        // 游客过滤:排除会员专属商品
+        if (userId == null) {
+            wrapper.ne(Product::getMemberEligible, "yes");
+        }
+        // 最低可见级别过滤:min_visible_level 为 NULL 时全部可见,否则仅当用户级别数字 >= 该等级数字时可见
+        if (userId == null) {
+            wrapper.isNull(Product::getMinVisibleLevel);
+        } else {
+            List<String> visibleLevelCodes = membershipService.getVisibleMemberLevelCodes(userId);
+            wrapper.and(w -> {
+                w.isNull(Product::getMinVisibleLevel);
+                if (!visibleLevelCodes.isEmpty()) {
+                    w.or().in(Product::getMinVisibleLevel, visibleLevelCodes);
+                }
+            });
+        }
+        // 供应商可见过滤:vendorVisible=true 的商品仅同体系用户可见
+        // 同体系判定:用户在 supply_system_member 中有记录,且该产品的 distributionSystemId 在用户所属体系中
+        // teacher(规划师)和 admin 作为平台角色始终可见所有商品;游客(未登录)只可见公开商品
+        boolean isPlatform = ("teacher".equals(role) || "admin".equals(role));
+        if (!isPlatform) {
+            // 获取当前用户所属的供应商体系 ID 列表(游客返回空列表)
+            List<Long> mySystemIds = getMySupplySystemIds(userId);
+            if (!mySystemIds.isEmpty()) {
+                // 已加入供应商体系的用户:可见 vendorVisible=false/NULL 的商品,以及自身体系内的 vendorVisible=true 商品
+                wrapper.and(w -> {
+                    w.isNull(Product::getVendorVisible)
+                     .or().eq(Product::getVendorVisible, false)
+                     .or(w2 -> w2.eq(Product::getVendorVisible, true)
+                                .in(Product::getDistributionSystemId, mySystemIds));
+                });
+            } else {
+                // 游客或未加入任何供应商体系:只展示公开商品
+                wrapper.and(w -> w.isNull(Product::getVendorVisible).or().eq(Product::getVendorVisible, false));
+            }
+        }
+        if (query.getProductType() != null && !query.getProductType().isEmpty()) {
+            wrapper.eq(Product::getProductType, query.getProductType());
+        }
+        // 统一参数名: dimensionCode 优先,兼容旧版 domain
+        String dimCode = query.getDimensionCode() != null ? query.getDimensionCode() : query.getDomain();
+        // 白名单校验:仅合法五维码可进入 JSON 路径,非法输入(模糊测试/注入探针)跳过维度过滤,避免 Invalid JSON path 500
+        if (dimCode != null && !dimCode.isEmpty() && DimensionCodes.isValid(dimCode)) {
+            String dim = dimCode.trim();
+            // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 domain
+            wrapper.and(w -> w
+                .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                .or().eq(Product::getDomain, dim)
+            );
+        }
+        if (query.getCategoryId() != null) {
+            wrapper.eq(Product::getCategoryId, query.getCategoryId());
+        }
+        if (query.getKeyword() != null && !query.getKeyword().isEmpty()) {
+            wrapper.like(Product::getName, query.getKeyword());
+        }
+        // 营养标签筛选:逗号分隔标签中任一命中即返回(NULL/空=不限)
+        if (query.getNutritionTag() != null && !query.getNutritionTag().trim().isEmpty()) {
+            wrapper.like(Product::getNutritionTags, query.getNutritionTag().trim());
+        }
+        SortUtil.applySort(wrapper);
+        IPage<Product> result = productMapper.selectPage(page, wrapper);
+        boolean isGuest = (userId == null);
+        String memberLevel = null;
+        if (!isGuest) {
+            try { memberLevel = membershipService.getMemberLevel(userId); } catch (Exception e) { /* ignore */ }
+        }
+        final String level = memberLevel;
+        List<ProductDTO> records = result.getRecords().stream()
+            .map(p -> ProductDTO.from(p, isGuest, level))
+            .collect(Collectors.toList());
+        // 内容维度阈值显隐过滤(A-后端):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
+        // 无阈值配置 / 无得分数据 → fail-open 不误隐藏。familyId 从登录用户上下文取,游客跳过。
+        applyDimensionThresholdFilter(records, userId, isGuest);
+        // 批量查询赠送规则,避免 N+1(列表页优化)
+        List<Long> productIds = result.getRecords().stream()
+            .map(Product::getId)
+            .collect(Collectors.toList());
+        List<ProductGiftRule> giftRules = productGiftRuleService.listActiveByProductIds(productIds);
+        Map<Long, ProductGiftRule> giftRuleMap = giftRules.stream()
+            .collect(Collectors.toMap(ProductGiftRule::getProductId, rule -> rule));
+        for (ProductDTO dto : records) {
+            ProductGiftRule giftRule = giftRuleMap.get(dto.getId());
+            if (giftRule != null) {
+                dto.setGiftLevelCode(giftRule.getLevelCode());
+                dto.setGiftLevelName(productGiftRuleService.getLevelName(giftRule.getLevelCode()));
+            }
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", records);
+        data.put("total", result.getTotal());
+        data.put("page", result.getCurrent());
+        data.put("size", result.getSize());
+        return Result.success(data);
+    }
+
+    /**
+     * 内容维度阈值显隐过滤(A-后端)。
+     * 从登录用户上下文取 familyId;游客或无家庭得分数据时 fail-open 不隐藏。
+     * 显隐规则(OR 逻辑):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
+     */
+    private void applyDimensionThresholdFilter(List<ProductDTO> records, Long userId, boolean isGuest) {
+        if (records == null || records.isEmpty()) return;
+        Long familyId = null;
+        if (!isGuest && userId != null && userId > 0) {
+            try {
+                User u = userMapper.selectById(userId);
+                if (u != null) familyId = u.getFamilyId();
+            } catch (Exception ignore) { /* 取不到 familyId 则 fail-open */ }
+        }
+        Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
+        if (familyAvg.isEmpty()) return; // 无家庭得分数据 → fail-open
+        List<Long> pids = records.stream().map(ProductDTO::getId).collect(Collectors.toList());
+        Map<Long, List<ContentDimensionThreshold>> byId = contentDimensionThresholdService.listByContents("PRODUCT", pids);
+        DimensionThresholdFilter.filterVisible(records, ProductDTO::getId, "PRODUCT", familyAvg, byId);
+    }
+
+    public Result<ProductDTO> detail(Long id, Long userId) {
+        Product product = productMapper.selectById(id);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        if (!"on_shelf".equals(product.getStatus()) && !"approved".equals(product.getStatus())) {
+            return Result.error("商品未上架");
+        }
+        ProductDTO dto = ProductDTO.from(product);
+        // 套餐商品:套餐内容(新模型:内容=子商品SKU×数量,挂套餐SKU级;下单只扣套餐SKU库存)
+        if ("bundle".equals(product.getProductType())) {
+            // 套餐内容(新模型:内容=子商品SKU×数量,挂套餐SKU级;下单只扣套餐SKU库存)
+            List<ProductDTO.ComboItemVO> comboItems = new ArrayList<>();
+            List<ProductSku> comboSkus = productSkuMapper.selectList(
+                    new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
+            if (comboSkus != null) {
+                for (ProductSku comboSku : comboSkus) {
+                    for (ProductComboItem ci : comboService.listComboItems(comboSku.getId())) {
+                        ProductDTO.ComboItemVO vo = new ProductDTO.ComboItemVO();
+                        vo.setChildProductId(ci.getChildProductId());
+                        vo.setChildProductName(ci.getChildProductName());
+                        vo.setCoverImage(ci.getChildProductImage());
+                        vo.setChildSkuId(ci.getChildSkuId());
+                        vo.setSpecs(ci.getChildSkuSpecs());
+                        vo.setQuantity(ci.getQuantity());
+                        comboItems.add(vo);
+                    }
+                }
+            }
+            dto.setComboItems(comboItems);
+        }
+        ProductGiftRule giftRule = productGiftRuleService.getActiveByProductId(id);
+        if (giftRule != null) {
+            dto.setGiftLevelCode(giftRule.getLevelCode());
+            dto.setGiftLevelName(productGiftRuleService.getLevelName(giftRule.getLevelCode()));
+        }
+        // 可选赠品配置(当前用户等级)
+        if (userId != null) {
+            try {
+                User buyer = userMapper.selectById(userId);
+                if (buyer != null && buyer.getFamilyId() != null) {
+                    MembershipLevelDTO currentLevel = membershipService.getCurrentLevel(buyer.getFamilyId());
+                    String userLevel = currentLevel != null ? currentLevel.getLevelCode() : null;
+                    if (userLevel != null && !"FREE".equals(userLevel)) {
+                        List<GiftConfigVO> activeConfigs = productGiftService
+                                .getActiveConfigsByProductAndLevel(id, userLevel);
+                        if (!activeConfigs.isEmpty()) {
+                            dto.setGiftConfigs(activeConfigs);
+                        }
+                    }
+                }
+            } catch (Exception e) {
+                // 赠品配置加载失败不影响商品详情
+            }
+        }
+        // 配送与履约配置(按 deliveryMethod 附带自取地点/服务者/线上时间段)
+        Map<String, Object> deliveryConfig = new HashMap<>();
+        productDeliveryConfigService.enrichProductDetail(id, product.getDeliveryMethod(), deliveryConfig);
+        if (!deliveryConfig.isEmpty()) {
+            dto.setDeliveryConfig(deliveryConfig);
+        }
+        nutritionProductService.syncFromProduct(product);
+        return Result.success(dto);
+    }
+
+    public Result<ProductDTO> create(Product product, Long vendorId) {
+        if (vendorId != null) {
+            User vendor = userMapper.selectById(vendorId);
+            if (vendor == null || !"approved".equals(vendor.getVendorStatus())) {
+                return Result.error("仅审核通过的服务商可发布商品");
+            }
+            product.setVendorId(vendorId);
+            product.setVendorName(vendor.getNickname() != null ? vendor.getNickname() : vendor.getRealName());
+        } else {
+            product.setVendorId(null);
+            product.setVendorName(null);
+        }
+        product.setStatus("pending");
+        product.setCreatedAt(new Date());
+        product.setUpdatedAt(new Date());
+        productMapper.insert(product);
+        return Result.success(ProductDTO.from(product));
+    }
+
+    public Result<ProductDTO> update(Product product, Long vendorId) {
+        Product existing = productMapper.selectById(product.getId());
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        if (vendorId != null) {
+            if (!existing.getVendorId().equals(vendorId)) {
+                return Result.error("无权修改此商品");
+            }
+        } else {
+            product.setVendorId(null);
+            product.setVendorName(null);
+        }
+        product.setStatus("pending");
+        product.setUpdatedAt(new Date());
+        productMapper.updateById(product);
+        nutritionProductService.syncFromProduct(product);
+        return Result.success(ProductDTO.from(productMapper.selectById(product.getId())));
+    }
+
+    public Result<List<ProductDTO>> myProducts(Long vendorId) {
+        List<Product> list = productMapper.selectList(
+            new LambdaQueryWrapper<Product>()
+                .eq(Product::getVendorId, vendorId)
+                .orderByAsc(Product::getSortOrder)
+                .orderByDesc(Product::getCreatedAt)
+        );
+        List<ProductDTO> dtos = list.stream().map(ProductDTO::from).collect(Collectors.toList());
+        return Result.success(dtos);
+    }
+
+    public Result<String> shelve(Long productId, Long vendorId, String action) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        if (!product.getVendorId().equals(vendorId)) {
+            return Result.error("无权操作");
+        }
+        if ("shelve".equals(action)) {
+            if (!"approved".equals(product.getStatus()) && !"off_shelf".equals(product.getStatus())) {
+                return Result.error("商品未通过审核,无法上架");
+            }
+            product.setStatus("on_shelf");
+        } else if ("unshelve".equals(action)) {
+            if (!"on_shelf".equals(product.getStatus())) {
+                return Result.error("商品未上架,无法下架");
+            }
+            product.setStatus("off_shelf");
+        } else {
+            return Result.error("操作类型错误");
+        }
+        product.setUpdatedAt(new Date());
+        productMapper.updateById(product);
+        return Result.success("操作成功");
+    }
+
+    public Result<String> review(Long productId, String action, String rejectReason) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        if (!"pending".equals(product.getStatus())) {
+            return Result.error("仅待审核商品可审核");
+        }
+        if ("approve".equals(action)) {
+            product.setStatus("approved");
+            product.setRejectReason(null);
+        } else if ("reject".equals(action)) {
+            product.setStatus("rejected");
+            product.setRejectReason(rejectReason != null ? rejectReason : "不符合规范");
+        } else {
+            return Result.error("操作类型错误");
+        }
+        product.setUpdatedAt(new Date());
+        productMapper.updateById(product);
+        return Result.success("操作成功");
+    }
+
+    public Result<List<ProductDTO>> pendingReview() {
+        List<Product> list = productMapper.selectList(
+            new LambdaQueryWrapper<Product>()
+                .eq(Product::getStatus, "pending")
+                .orderByAsc(Product::getCreatedAt)
+        );
+        List<ProductDTO> dtos = list.stream().map(ProductDTO::from).collect(Collectors.toList());
+        return Result.success(dtos);
+    }
+
+    public Result<List<ProductDTO>> adminList(String status) {
+        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+            .orderByAsc(Product::getSortOrder)
+            .orderByDesc(Product::getCreatedAt);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Product::getStatus, status);
+        }
+        SortUtil.applySort(wrapper);
+        List<Product> list = productMapper.selectList(wrapper);
+        List<ProductDTO> dtos = list.stream().map(ProductDTO::from).collect(Collectors.toList());
+        return Result.success(dtos);
+    }
+
+    /**
+     * 管理员分页查询商品列表
+     */
+    public Page<Product> adminProductList(Page<Product> pageParam, LambdaQueryWrapper<Product> wrapper) {
+        SortUtil.applySort(wrapper);
+        return productMapper.selectPage(pageParam, wrapper);
+    }
+
+    /**
+     * 管理员上下架商品(不需要校验vendorId)
+     */
+    public Result<String> adminShelve(Long productId, Boolean shelve) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        // 管理员可以直接上下架任何已审核通过的商品
+        if (!"approved".equals(product.getStatus()) && !"on_shelf".equals(product.getStatus()) && !"off_shelf".equals(product.getStatus())) {
+            return Result.error("仅已审核通过的商品可以上下架");
+        }
+        if (shelve) {
+            product.setStatus("on_shelf");
+        } else {
+            product.setStatus("off_shelf");
+        }
+        product.setUpdatedAt(new Date());
+        productMapper.updateById(product);
+        return Result.success(shelve ? "上架成功" : "下架成功");
+    }
+
+    /**
+     * 管理员批量上下架商品
+     */
+    public Result<String> batchAdminShelve(List<Long> productIds, Boolean shelve) {
+        if (productIds == null || productIds.isEmpty()) {
+            return Result.error("productIds不能为空");
+        }
+        for (Long productId : productIds) {
+            Product product = productMapper.selectById(productId);
+            if (product == null) {
+                return Result.error("商品不存在: " + productId);
+            }
+            if (!"approved".equals(product.getStatus()) && !"on_shelf".equals(product.getStatus()) && !"off_shelf".equals(product.getStatus())) {
+                return Result.error("仅已审核通过的商品可以上下架,商品 ID: " + productId + " 状态: " + product.getStatus());
+            }
+            if (shelve) {
+                product.setStatus("on_shelf");
+            } else {
+                product.setStatus("off_shelf");
+            }
+            product.setUpdatedAt(new Date());
+            productMapper.updateById(product);
+        }
+        return Result.success(shelve ? "批量上架成功" : "批量下架成功");
+    }
+
+    public boolean decreaseStock(Long productId, Integer quantity) {
+        if (quantity == null || quantity <= 0) {
+            return false;
+        }
+        int rows = productMapper.decreaseStockAtomic(productId, quantity);
+        return rows > 0;
+    }
+
+    public void increaseStock(Long productId, Integer quantity) {
+        if (quantity == null || quantity <= 0) {
+            return;
+        }
+        Product product = productMapper.selectById(productId);
+        if (product != null && product.getStock() != null) {
+            product.setStock(product.getStock() + quantity);
+            product.setUpdatedAt(new Date());
+            productMapper.updateById(product);
+        }
+    }
+
+    public Result<String> updateImages(Long productId, Long vendorId, List<String> images) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) return Result.error("商品不存在");
+        if (!product.getVendorId().equals(vendorId)) return Result.error("无权修改");
+        String imagesJson = JSON.toJSONString(images);
+        product.setImages(imagesJson);
+        product.setUpdatedAt(new Date());
+        productMapper.updateById(product);
+        return Result.success("更新成功");
+    }
+
+    /**
+     * 管理员商品详情
+     */
+    public Result<ProductDTO> adminDetail(Long productId) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        ProductDTO dto = ProductDTO.from(product);
+        if (Product.TYPE_ASSESSMENT.equals(product.getProductType())) {
+            AssessmentProduct ext = assessmentProductService.getByProductId(productId);
+            if (ext != null) {
+                dto.setAssessmentType(ext.getAssessmentType());
+                dto.setTotalSessions(ext.getTotalSessions());
+                dto.setValidityDays(ext.getValidityDays());
+                dto.setGuideScope(ext.getGuideScope());
+            }
+        }
+        return Result.success(dto);
+    }
+
+    /**
+     * 管理员创建商品(直接上架)
+     */
+    public Result<ProductDTO> adminCreate(Product product) {
+        // 最低可见级别:空串规整为 NULL(NULL=所有用户含未登录可见),
+        // 避免管理端 el-select 清空提交 '' 导致商品对所有用户不可见
+        normalizeMinVisibleLevel(product);
+        product.setStatus("on_shelf");
+        product.setCreatedAt(new Date());
+        product.setUpdatedAt(new Date());
+        productMapper.insert(product);
+        return Result.success(ProductDTO.from(product));
+    }
+
+    /**
+     * 管理员创建商品(含测评扩展信息)
+     */
+    public Result<ProductDTO> adminCreate(Product product, AssessmentProduct assessmentExt) {
+        Result<ProductDTO> result = adminCreate(product);
+        if (Product.TYPE_ASSESSMENT.equals(product.getProductType()) && assessmentExt != null) {
+            assessmentProductService.saveOrUpdate(product.getId(), assessmentExt);
+        }
+        return result;
+    }
+
+    /**
+     * 管理员更新商品
+     */
+    public Result<ProductDTO> adminUpdate(Product product) {
+        Product existing = productMapper.selectById(product.getId());
+        if (existing == null) {
+            return Result.error("商品不存在");
+        }
+        product.setUpdatedAt(new Date());
+        // 保留原状态不变,避免被覆盖
+        product.setStatus(existing.getStatus());
+        // 最低可见级别:空串规整为 NULL(NULL=所有用户含未登录可见),
+        // 避免管理端 el-select 清空提交 '' 导致商品对所有用户不可见
+        boolean clearMinVisibleLevel = normalizeMinVisibleLevel(product);
+        // updateById 默认忽略 null 字段:clearable 下拉清空后需显式置 NULL
+        boolean clearCategory = product.getCategoryId() == null;
+        boolean clearDistributionSystem = product.getDistributionSystemId() == null;
+        // 营养数据字段为 nullable 且允许清空:管理端清空输入框后需显式置 NULL,
+        // 否则 updateById 忽略 null 会残留旧值;空串营养标签同样规整为 NULL。
+        // 仅当原记录确实有值时才需要清空,避免每次编辑都多打一条无意义的 UPDATE。
+        boolean clearCalories = existing.getCaloriesKcal() != null && product.getCaloriesKcal() == null;
+        boolean clearProtein = existing.getProteinG() != null && product.getProteinG() == null;
+        boolean clearFat = existing.getFatG() != null && product.getFatG() == null;
+        boolean clearCarb = existing.getCarbG() != null && product.getCarbG() == null;
+        boolean clearFiber = existing.getFiberG() != null && product.getFiberG() == null;
+        if (product.getNutritionTags() != null && product.getNutritionTags().trim().isEmpty()) {
+            product.setNutritionTags(null);
+        }
+        boolean clearNutritionTags = existing.getNutritionTags() != null && product.getNutritionTags() == null;
+        productMapper.updateById(product);
+        nutritionProductService.syncFromProduct(product);
+        if (clearMinVisibleLevel || clearCategory || clearDistributionSystem
+                || clearCalories || clearProtein || clearFat || clearCarb || clearFiber
+                || clearNutritionTags) {
+            LambdaUpdateWrapper<Product> clearWrapper = new LambdaUpdateWrapper<Product>()
+                    .eq(Product::getId, product.getId());
+            if (clearMinVisibleLevel) {
+                clearWrapper.set(Product::getMinVisibleLevel, null);
+            }
+            if (clearCategory) {
+                clearWrapper.set(Product::getCategoryId, null);
+            }
+            if (clearDistributionSystem) {
+                clearWrapper.set(Product::getDistributionSystemId, null);
+            }
+            if (clearCalories) {
+                clearWrapper.set(Product::getCaloriesKcal, null);
+            }
+            if (clearProtein) {
+                clearWrapper.set(Product::getProteinG, null);
+            }
+            if (clearFat) {
+                clearWrapper.set(Product::getFatG, null);
+            }
+            if (clearCarb) {
+                clearWrapper.set(Product::getCarbG, null);
+            }
+            if (clearFiber) {
+                clearWrapper.set(Product::getFiberG, null);
+            }
+            if (clearNutritionTags) {
+                clearWrapper.set(Product::getNutritionTags, null);
+            }
+            productMapper.update(null, clearWrapper);
+        }
+        return Result.success(ProductDTO.from(productMapper.selectById(product.getId())));
+    }
+
+    /**
+     * 最低可见级别空串归一化:'' → NULL。
+     *
+     * @return true 表示发生了空串清空(需要显式把列置为 NULL,因为 updateById 忽略 null 字段)
+     */
+    private boolean normalizeMinVisibleLevel(Product product) {
+        if (product.getMinVisibleLevel() != null && product.getMinVisibleLevel().trim().isEmpty()) {
+            product.setMinVisibleLevel(null);
+            return true;
+        }
+        return false;
+    }
+
+    /** 判断是否为游客(未登录) */
+    private boolean isGuest(Long userId) {
+        return userId == null;
+    }
+
+    /** 获取当前用户所属的供应商体系 ID 列表 */
+    private List<Long> getMySupplySystemIds(Long userId) {
+        if (userId == null) return new ArrayList<>();
+        return supplySystemMemberMapper.selectList(
+                new LambdaQueryWrapper<SupplySystemMember>()
+                        .eq(SupplySystemMember::getUserId, userId)
+                        .eq(SupplySystemMember::getStatus, "active"))
+                .stream()
+                .map(SupplySystemMember::getSystemId)
+                .distinct()
+                .collect(Collectors.toList());
+    }
+
+    /** 判断用户是否为供应商体系内用户(审核通过的服务商或 teacher 角色) */
+    private boolean isVendorUser(Long userId, String role) {
+        if (userId == null) return false;
+        if ("teacher".equals(role)) return true;
+        User vendor = userMapper.selectById(userId);
+        if (vendor != null && "approved".equals(vendor.getVendorStatus())) {
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * 管理员更新商品(含测评扩展信息)
+     */
+    public Result<ProductDTO> adminUpdate(Product product, AssessmentProduct assessmentExt) {
+        Result<ProductDTO> result = adminUpdate(product);
+        if (result.getCode() != 200) {
+            return result;
+        }
+        if (Product.TYPE_ASSESSMENT.equals(product.getProductType())) {
+            assessmentProductService.saveOrUpdate(product.getId(), assessmentExt);
+        } else {
+            // 非测评商品则清理扩展信息
+            assessmentProductService.saveOrUpdate(product.getId(), null);
+        }
+        return result;
+    }
+
+    /**
+     * 管理员复制商品
+     */
+    @Transactional
+    public Result<ProductDTO> adminCopy(Long productId) {
+        Product original = productMapper.selectById(productId);
+        if (original == null) {
+            return Result.error("商品不存在");
+        }
+        Product copy = new Product();
+        copy.setName(original.getName() + " (复制)");
+        copy.setDescription(original.getDescription());
+        copy.setIntro(original.getIntro());
+        copy.setCoverImage(original.getCoverImage());
+        copy.setImages(original.getImages());
+        copy.setPrice(original.getPrice());
+        copy.setStock(original.getStock());
+        copy.setSalesCount(0);
+        copy.setProductType(original.getProductType());
+        copy.setVendorId(original.getVendorId());
+        copy.setVendorName(original.getVendorName());
+        copy.setStatus("on_shelf");
+        copy.setMemberPrice(original.getMemberPrice());
+        copy.setMemberEligible(original.getMemberEligible());
+        copy.setDomain(original.getDomain());
+        copy.setDimensionWeights(original.getDimensionWeights());
+        copy.setProfitRate(original.getProfitRate());
+        copy.setCategoryId(original.getCategoryId());
+        copy.setDistributionSystemId(original.getDistributionSystemId());
+        copy.setDeliveryMethod(original.getDeliveryMethod());
+        copy.setMinQuantity(original.getMinQuantity());
+        copy.setSortOrder(original.getSortOrder());
+        copy.setVisibleRoles(original.getVisibleRoles());
+        copy.setMinVisibleLevel(original.getMinVisibleLevel());
+        copy.setCaloriesKcal(original.getCaloriesKcal());
+        copy.setProteinG(original.getProteinG());
+        copy.setFatG(original.getFatG());
+        copy.setCarbG(original.getCarbG());
+        copy.setFiberG(original.getFiberG());
+        copy.setNutritionTags(original.getNutritionTags());
+        copy.setCreatedAt(new Date());
+        copy.setUpdatedAt(new Date());
+        productMapper.insert(copy);
+
+        // 复制测评扩展信息
+        if (Product.TYPE_ASSESSMENT.equals(original.getProductType())) {
+            AssessmentProduct ext = assessmentProductService.getByProductId(productId);
+            if (ext != null) {
+                AssessmentProduct extCopy = new AssessmentProduct();
+                extCopy.setAssessmentType(ext.getAssessmentType());
+                extCopy.setTotalSessions(ext.getTotalSessions());
+                extCopy.setValidityDays(ext.getValidityDays());
+                extCopy.setGuideScope(ext.getGuideScope());
+                assessmentProductService.saveOrUpdate(copy.getId(), extCopy);
+            }
+        }
+        return Result.success(ProductDTO.from(copy));
+    }
+
+    /**
+     * 管理员删除商品
+     */
+    public Result<String> adminDelete(Long productId) {
+        Product product = productMapper.selectById(productId);
+        if (product == null) {
+            return Result.error("商品不存在");
+        }
+        productMapper.deleteById(productId);
+        return Result.success("删除成功");
+    }
+}

+ 219 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductSkuService.java

@@ -0,0 +1,219 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductSku;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductSkuMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class ProductSkuService {
+
+    private static final Logger log = LoggerFactory.getLogger(ProductSkuService.class);
+
+    @Resource
+    private ProductSkuMapper skuMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    public List<ProductSku> listByProductId(Long productId) {
+        List<ProductSku> list = skuMapper.findByProductId(productId);
+        return list;
+    }
+
+    public List<ProductSku> listByProductIdAll(Long productId) {
+        List<ProductSku> list = skuMapper.findByProductIdAll(productId);
+        return list;
+    }
+
+    public ProductSku getById(Long id) {
+        ProductSku sku = skuMapper.findById(id);
+        return sku;
+    }
+
+    @Transactional
+    public ProductSku create(ProductSku sku) {
+        log.info("[SKU-CREATE] productId={}, linkedProductId={}", sku.getProductId(), sku.getLinkedProductId());
+        if (sku.getLinkedProductId() == null) {
+            // Legacy SKU: 需要 specs
+            if (sku.getSpecs() == null || sku.getSpecs().trim().isEmpty()) {
+                sku.setSpecs("[]");
+            }
+        }
+        sku.setCreateTime(new Date());
+        sku.setUpdateTime(new Date());
+        if (sku.getEnabled() == null) {
+            sku.setEnabled(1);
+        }
+        if (sku.getSkuCode() == null || sku.getSkuCode().isEmpty()) {
+            sku.setSkuCode("SKU-" + sku.getProductId() + "-" + System.currentTimeMillis());
+        }
+        skuMapper.insert(sku);
+        return sku;
+    }
+
+    @Transactional
+    public void update(ProductSku sku) {
+        if (sku.getLinkedProductId() == null) {
+            // Legacy SKU: 需要 specs
+            if (sku.getSpecs() == null || sku.getSpecs().trim().isEmpty()) {
+                sku.setSpecs("[]");
+            }
+        }
+        sku.setUpdateTime(new Date());
+        skuMapper.updateById(sku);
+        if (sku.getLinkedProductId() == null) {
+            skuMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<ProductSku>()
+                    .eq(ProductSku::getId, sku.getId())
+                    .set(ProductSku::getLinkedProductId, null));
+        }
+    }
+
+    @Transactional
+    public void delete(Long id) {
+        skuMapper.deleteById(id);
+    }
+
+    @Transactional
+    public boolean decreaseStock(Long skuId, Integer quantity) {
+        int rows = skuMapper.updateStock(skuId, -quantity);
+        return rows > 0;
+    }
+
+    @Transactional
+    public void increaseStock(Long skuId, Integer quantity) {
+        ProductSku sku = skuMapper.findById(skuId);
+        if (sku != null && sku.getStock() != null) {
+            sku.setStock(sku.getStock() + quantity);
+            sku.setUpdateTime(new Date());
+            skuMapper.updateById(sku);
+        }
+    }
+
+    public boolean hasStock(Long skuId, Integer quantity) {
+        ProductSku sku = skuMapper.findById(skuId);
+        if (sku == null || sku.getStock() == null) {
+            return false;
+        }
+        return sku.getStock() >= quantity;
+    }
+
+    /**
+     * 查询 linked 商品摘要(用于 specMap 扩展)
+     * @return null 如果商品不存在或库存为0
+     */
+    public java.util.Map<String, Object> getLinkedProductSummary(Long linkedProductId) {
+        if (linkedProductId == null) return null;
+        Product product = productMapper.selectById(linkedProductId);
+        if (product == null) return null;
+        if (product.getStock() != null && product.getStock() == 0) return null;
+        java.util.Map<String, Object> summary = new java.util.HashMap<>();
+        summary.put("id", product.getId());
+        summary.put("name", product.getName());
+        summary.put("price", product.getPrice());
+        summary.put("stock", product.getStock());
+        summary.put("image", product.getCoverImage());
+        summary.put("brief", product.getIntro());
+        return summary;
+    }
+
+    /**
+     * 将 specs 规格字符串规范化为合法 JSON 对象。
+     *
+     * product_skus.specs 列为 MySQL JSON NOT NULL,只接受合法 JSON。
+     * 前端 ProductSkuEditor 允许用户输入 "颜色:红色;尺码:M" 这种格式,
+     * 直接插入会被 MySQL 拒绝(Invalid JSON text)。
+     * 此方法将 "k1:v1;k2:v2" 格式转为 {"k1":"v1","k2":"v2"};
+     * 如果已经是合法 JSON 字符串则原样返回。
+     */
+    static String normalizeSpecsToJson(Object specsObj) {
+        if (specsObj == null) return "{}";
+        if (specsObj instanceof java.util.Map) {
+            return com.alibaba.fastjson.JSON.toJSONString(specsObj);
+        }
+        String specs;
+        if (specsObj instanceof String) {
+            specs = (String) specsObj;
+        } else {
+            specs = specsObj.toString();
+        }
+        if (specs.trim().isEmpty()) return "{}";
+        String trimmed = specs.trim();
+        // 已是合法 JSON 对象/数组,直接返回
+        if (trimmed.startsWith("{")) {
+            return trimmed;
+        }
+        // 数组格式转 JSON 对象:["红色","M码"] → {"规格":"红色","规格2":"M码"}
+        if (trimmed.startsWith("[")) {
+            if (trimmed.contains("[object Object]") || trimmed.contains("[undefined]")) {
+                return "{}";
+            }
+            String body = trimmed.substring(1, trimmed.length() - 1);
+            Map<String, String> map = new LinkedHashMap<>();
+            int idx = 1;
+            for (String item : body.split(",", -1)) {
+                item = item.trim();
+                if (item.isEmpty()) continue;
+                if (item.startsWith("\"")) item = item.substring(1);
+                if (item.endsWith("\"")) item = item.substring(0, item.length() - 1);
+                map.put("规格" + idx, item);
+                idx++;
+            }
+            if (map.isEmpty()) {
+                return "{}";
+            }
+            StringBuilder sb = new StringBuilder("{");
+            boolean first = true;
+            for (Map.Entry<String, String> entry : map.entrySet()) {
+                if (!first) sb.append(",");
+                first = false;
+                sb.append("\"").append(escapeJson(entry.getKey())).append("\":");
+                sb.append("\"").append(escapeJson(entry.getValue())).append("\"");
+            }
+            sb.append("}");
+            return sb.toString();
+        }
+        // 将 k1:v1;k2:v2 格式转为 JSON 对象
+        Map<String, String> map = new LinkedHashMap<>();
+        String[] pairs = trimmed.split("[;;]");
+        for (String pair : pairs) {
+            pair = pair.trim();
+            if (pair.isEmpty()) continue;
+            String[] kv = pair.split("[::]", 2);
+            if (kv.length == 2) {
+                map.put(kv[0].trim(), kv[1].trim());
+            }
+        }
+        if (map.isEmpty()) {
+            return "{}";
+        }
+        // 手动构建 JSON 字符串(避免引入 Jackson 依赖)
+        StringBuilder sb = new StringBuilder("{");
+        boolean first = true;
+        for (Map.Entry<String, String> entry : map.entrySet()) {
+            if (!first) sb.append(",");
+            first = false;
+            sb.append("\"").append(escapeJson(entry.getKey())).append("\":");
+            sb.append("\"").append(escapeJson(entry.getValue())).append("\"");
+        }
+        sb.append("}");
+        return sb.toString();
+    }
+
+    private static String escapeJson(String s) {
+        if (s == null) return "";
+        return s.replace("\\", "\\\\").replace("\"", "\\\"")
+                .replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
+    }
+
+}

+ 8 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProfileComputeService.java

@@ -0,0 +1,8 @@
+package com.etotem.cfc.service;
+
+public interface ProfileComputeService {
+    /** 为指定家庭成员重新计算并写入画像快照 */
+    void computeAndSave(Long memberId);
+    /** 批量计算所有家庭成员画像 */
+    void computeAll();
+}

+ 10 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProfileReadService.java

@@ -0,0 +1,10 @@
+package com.etotem.cfc.service;
+
+import java.util.Map;
+
+public interface ProfileReadService {
+    /** 获取最新画像快照(含基础信息) */
+    Map<String, Object> getProfile(Long memberId);
+    /** 获取指标趋势(近N天) */
+    Map<String, Object> getTrend(Long memberId, int days);
+}

+ 283 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProfitPoolService.java

@@ -0,0 +1,283 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.config.ConfigService;
+import com.etotem.cfc.entity.ProfitPoolOrder;
+import com.etotem.cfc.entity.ServiceConfigItem;
+import com.etotem.cfc.entity.TeamShareRecord;
+import com.etotem.cfc.mapper.ProfitPoolOrderMapper;
+import com.etotem.cfc.mapper.ServiceConfigItemMapper;
+import com.etotem.cfc.mapper.TeamAwardRecordMapper;
+import com.etotem.cfc.mapper.TeamShareRecordMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * 单笔订单利润池计算服务(规格 §2.1 总账模型 + §4.7 杠杆 1 收入管道化 + §8.3 幂等)。
+ *
+ * <p><b>核心职责(T9 收入管道化,能力键 {@code team.profit.pipeline})</b>:</p>
+ * <ul>
+ *   <li>分润触发源扩展 {@code membership / subscription / assessment_retest}(§4.7 杠杆 1),
+ *       续费/复购在推荐关系存续期间持续产生分润;</li>
+ *   <li>按 §2.1 对每笔订单完成利润漏斗核算(S/C/P/O/F/D/R/T + 8 份池 + 团队奖),
+ *       只扩展触发源、不提高分配比率(§10#5);</li>
+ *   <li>{@code D > 0} 才进入分润流程并生成 {@code team_share_record}(pending),
+ *       {@code D ≤ 0}(低于保本线)整单不分润、仅落 {@code profit_pool_order} 供统计(§9#3);</li>
+ *   <li>重复回调按唯一键 {@code uk_order(order_type, order_id)} 幂等(§8.3),不重复发放;</li>
+ *   <li>未知触发源被拒绝(防误分配)。</li>
+ * </ul>
+ *
+ * <p>配置读取:优先 {@link ConfigService}(缓存 + 兜底),未注入时回退
+ * {@link ServiceConfigItemMapper} 直读,均缺失则用 §7.8 默认比率
+ * (ops 10% / cf 1% / referral 70% / team 30% / eight 80% / award 20%)。</p>
+ *
+ * <p>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
+ * §2.1 + §2.2 + §4.7 杠杆 1 + §7.1 + §7.8 + §8.3 + §9#3 + §10#5 + §12-T9。</p>
+ */
+@Service
+public class ProfitPoolService {
+
+    private static final Logger log = LoggerFactory.getLogger(ProfitPoolService.class);
+
+    /** §7.1 order_type 允许值(§4.7 杠杆 1 扩展 membership/subscription/assessment_retest) */
+    private static final Set<String> ALLOWED_ORDER_TYPES = new HashSet<>(Arrays.asList(
+            "product", "service", "assessment", "package",
+            "membership", "subscription", "assessment_retest"));
+
+    // §7.8 默认比率(配置未写入时使用)
+    private static final double DEFAULT_OPS_RATE = 0.10;
+    private static final double DEFAULT_CF_COST_RATE = 0.01;
+    private static final double DEFAULT_REFERRAL_SHARE = 0.70;
+    private static final double DEFAULT_TEAM_SHARE = 0.30;
+    private static final double DEFAULT_EIGHT_SHARE_RATIO = 0.80;
+    private static final double DEFAULT_TEAM_AWARD_RATIO = 0.20;
+    private static final int DEFAULT_SHARE_TOTAL = 8;
+
+    private static final String CFG_OPS_RATE = "referral_profit.ops_rate";
+    private static final String CFG_CF_COST_RATE = "referral_profit.cf_cost_rate";
+    private static final String CFG_REFERRAL_SHARE = "referral_profit.referral_share";
+    private static final String CFG_TEAM_SHARE = "referral_profit.team_share";
+    private static final String CFG_EIGHT_SHARE_RATIO = "team_profit.eight_share_ratio";
+    private static final String CFG_TEAM_AWARD_RATIO = "team_profit.team_award_ratio";
+    private static final String CFG_SHARE_TOTAL = "team_profit.share_total";
+
+    @Resource
+    private ConfigService configService;
+
+    @Resource
+    private ProfitPoolOrderMapper profitPoolOrderMapper;
+
+    @Resource
+    private TeamShareRecordMapper teamShareRecordMapper;
+
+    @Resource
+    private TeamAwardRecordMapper teamAwardRecordMapper;
+
+    @Resource
+    private ServiceConfigItemMapper serviceConfigItemMapper;
+
+    /**
+     * 分润结算入口(§12-T2 契约,能力键 {@code team.profit.settle})。
+     *
+     * <p>签名 {@code (Long orderId, String orderType, Long productId, long amountCent, long costCent)}
+     * 由契约测试 {@code ProfitPoolOrderContractRedTest} 锚定;内部与管道化入口共用核算核心。</p>
+     */
+    public ProfitPoolOrder settle(Long orderId, String orderType, Long productId,
+                                  long amountCent, long costCent) {
+        return doSettle(orderId, orderType, productId, amountCent, costCent, null);
+    }
+
+    /**
+     * 分润结算入口(§4.7 杠杆 1 收入管道化,能力键 {@code team.profit.pipeline})。
+     *
+     * <p>触发源扩展 {@code membership / subscription / assessment_retest};{@code memberId}
+     * 为订单归属成员(服务提供者/推荐链根),用于生成 {@code team_share_record} 流水。</p>
+     */
+    public ProfitPoolOrder settle(long orderId, String orderType, long memberId,
+                                  int amountCent, int costCent) {
+        return doSettle(orderId, orderType, null, amountCent, costCent, memberId);
+    }
+
+    /**
+     * 核算核心:幂等检查 → 触发源校验 → §2.1 利润漏斗 → 落单 → D>0 生成团队分润流水。
+     */
+    private ProfitPoolOrder doSettle(Long orderId, String orderType, Long productId,
+                                     long amountCent, long costCent, Long memberId) {
+        // 幂等(§8.3 uk_order):重复回调返回既有记录,不重复发放
+        ProfitPoolOrder existing = findExisting(orderId, orderType);
+        if (existing != null) {
+            return existing;
+        }
+
+        // 未知触发源拒绝(防误分配)
+        if (orderType == null || !ALLOWED_ORDER_TYPES.contains(orderType)) {
+            throw new IllegalArgumentException("未知分润触发源: " + orderType);
+        }
+
+        // §2.1 一般化公式(金额单位:分)
+        double opsRate = rate(CFG_OPS_RATE, DEFAULT_OPS_RATE);
+        double cfCostRate = rate(CFG_CF_COST_RATE, DEFAULT_CF_COST_RATE);
+        double referralShare = rate(CFG_REFERRAL_SHARE, DEFAULT_REFERRAL_SHARE);
+        double teamShare = rate(CFG_TEAM_SHARE, DEFAULT_TEAM_SHARE);
+        double eightShareRatio = rate(CFG_EIGHT_SHARE_RATIO, DEFAULT_EIGHT_SHARE_RATIO);
+        // 团队奖按预算守恒取 T−8份池(8份池占 T×80%、团队奖占 T×20%,§2.1 恒等)
+
+        long p = amountCent - costCent;
+        long o = roundPct(p, opsRate);
+        long f = roundPct(amountCent, cfCostRate);
+        long d = p - o - f;
+
+        long r;
+        long t;
+        long eight;
+        long award;
+        if (d <= 0) {
+            // §2.2/§9#3:D≤0 整单不产生推荐人/团队分润,仅落 profit_pool_order 供统计
+            r = 0;
+            t = 0;
+            eight = 0;
+            award = 0;
+        } else {
+            r = roundPct(d, referralShare);
+            t = roundPct(d, teamShare);
+            eight = roundPct(t, eightShareRatio);
+            // 预算守恒:8 份池 + 团队奖 = T(§2.1,不超 D 预算)
+            award = t - eight;
+        }
+
+        ProfitPoolOrder pool = new ProfitPoolOrder();
+        pool.setOrderId(orderId);
+        pool.setOrderType(orderType);
+        pool.setProductId(productId);
+        pool.setAmountCent((int) amountCent);
+        pool.setCostCent((int) costCent);
+        pool.setPlatformRetainCent((int) p);
+        pool.setOpsCent((int) o);
+        pool.setCfCostCent((int) f);
+        pool.setPoolCent((int) d);
+        pool.setReferralShareCent((int) r);
+        pool.setTeamShareCent((int) t);
+        pool.setTeamEightShareCent((int) eight);
+        pool.setTeamAwardCent((int) award);
+        pool.setStatus("pending");
+        pool.setCreatedAt(new Date());
+        profitPoolOrderMapper.insert(pool);
+
+        if (d > 0) {
+            // §8.1:D>0 生成团队 8 份分佣流水(pending,冷静期后 settled)
+            genTeamShareRecord(pool, memberId);
+        }
+        return pool;
+    }
+
+    /** 幂等查询:uk_order(order_type, order_id) 既有记录。 */
+    private ProfitPoolOrder findExisting(Long orderId, String orderType) {
+        if (profitPoolOrderMapper == null) {
+            return null;
+        }
+        try {
+            return profitPoolOrderMapper.selectOne(new LambdaQueryWrapper<ProfitPoolOrder>()
+                    .eq(ProfitPoolOrder::getOrderType, orderType)
+                    .eq(ProfitPoolOrder::getOrderId, orderId)
+                    .last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("查询 profit_pool_order 幂等失败 orderType={} orderId={}: {}",
+                    orderType, orderId, e.getMessage());
+            return null;
+        }
+    }
+
+    /**
+     * 生成团队 8 份分佣流水(§7.3)。管道化(T9)阶段以订单归属成员为第 1 层基础记录,
+     * 星级/份数/金额的完整分配(§4.2 星级份数 + §4.4 团队奖)由团队分润服务按团队树与
+     * 星级快照落地(T2),此处仅落 pending 占位流水并保留 8 份池金额。
+     */
+    private void genTeamShareRecord(ProfitPoolOrder pool, Long memberId) {
+        if (teamShareRecordMapper == null) {
+            return;
+        }
+        Long uid = memberId != null ? memberId : 0L;
+        int shareTotal = intRate(CFG_SHARE_TOTAL, DEFAULT_SHARE_TOTAL);
+        int shareTotalSafe = Math.max(1, shareTotal);
+        TeamShareRecord record = new TeamShareRecord();
+        record.setOrderId(pool.getOrderId());
+        record.setOrderType(pool.getOrderType());
+        record.setPoolId(pool.getId());
+        record.setProviderUserId(uid);
+        record.setRecipientUserId(uid);
+        record.setLayer(1);
+        record.setShares(1);
+        record.setShareCent(pool.getTeamEightShareCent() / shareTotalSafe);
+        record.setStatus("pending");
+        record.setCreatedAt(new Date());
+        teamShareRecordMapper.insert(record);
+    }
+
+    /** §2.1 金额取整口径(逐项 round,HALF_UP 等价)。 */
+    private long roundPct(long base, double rate) {
+        return Math.round(base * rate);
+    }
+
+    /** 读取 double 比率:ConfigService 优先,回退 service_config 直读,再回退默认。 */
+    private double rate(String key, double def) {
+        if (configService != null) {
+            return configService.getDoubleConfig(key, def);
+        }
+        return readConfigDouble(key, def);
+    }
+
+    /** 读取 int 配置:ConfigService 优先,回退 service_config 直读,再回退默认。 */
+    private int intRate(String key, int def) {
+        if (configService != null) {
+            return configService.getIntConfig(key, def);
+        }
+        return readConfigInt(key, def);
+    }
+
+    private double readConfigDouble(String key, double def) {
+        String v = readConfigValue(key);
+        if (v == null) {
+            return def;
+        }
+        try {
+            return Double.parseDouble(v.trim());
+        } catch (NumberFormatException e) {
+            return def;
+        }
+    }
+
+    private int readConfigInt(String key, int def) {
+        String v = readConfigValue(key);
+        if (v == null) {
+            return def;
+        }
+        try {
+            return Integer.parseInt(v.trim());
+        } catch (NumberFormatException e) {
+            return def;
+        }
+    }
+
+    private String readConfigValue(String key) {
+        if (serviceConfigItemMapper == null) {
+            return null;
+        }
+        try {
+            ServiceConfigItem item = serviceConfigItemMapper.selectOne(
+                    new LambdaQueryWrapper<ServiceConfigItem>()
+                            .eq(ServiceConfigItem::getConfigKey, key)
+                            .last("LIMIT 1"));
+            return item != null ? item.getConfigValue() : null;
+        } catch (Exception e) {
+            log.warn("读取团队分润配置失败 key={}: {}", key, e.getMessage());
+            return null;
+        }
+    }
+}

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

@@ -0,0 +1,54 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.PromotionBinding;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.PromotionBindingMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class PromotionBindingService {
+
+    @Resource
+    private PromotionBindingMapper promotionBindingMapper;
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    public PromotionBinding bindByInviteCode(Long promoterFamilyId, String inviteCode) {
+        Family invitee = familyMapper.selectOne(
+                new LambdaQueryWrapper<Family>().eq(Family::getInviteCode, inviteCode).last("LIMIT 1")
+        );
+        if (invitee == null) {
+            return null;
+        }
+        Long inviteeFamilyId = invitee.getId();
+        if (promoterFamilyId.equals(inviteeFamilyId)) {
+            return null;
+        }
+        PromotionBinding binding = new PromotionBinding();
+        binding.setPromoterFamilyId(promoterFamilyId);
+        binding.setInviteeFamilyId(inviteeFamilyId);
+        binding.setInviteCode(inviteCode);
+        binding.setBindingType("direct");
+        binding.setStatus("active");
+        binding.setCreatedAt(new Date());
+        promotionBindingMapper.insert(binding);
+        return binding;
+    }
+
+    public List<PromotionBinding> getBindings(Long familyId) {
+        return promotionBindingMapper.selectList(
+                new LambdaQueryWrapper<PromotionBinding>()
+                        .and(w -> w.eq(PromotionBinding::getPromoterFamilyId, familyId)
+                                .or().eq(PromotionBinding::getInviteeFamilyId, familyId))
+                        .orderByDesc(PromotionBinding::getCreatedAt)
+                        .last("LIMIT 100")
+        );
+    }
+}

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PromotionCommissionService.java

@@ -0,0 +1,45 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.Commission;
+import com.etotem.cfc.mapper.CommissionMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+public class PromotionCommissionService {
+
+    @Resource
+    private CommissionMapper commissionMapper;
+
+    /**
+     * 记录佣金
+     * @param commission 佣金对象
+     * @return 是否成功
+     */
+    public boolean recordCommission(Commission commission) {
+        if (commission.getCreatedAt() == null) {
+            commission.setCreatedAt(new Date());
+        }
+        commission.setUpdatedAt(new Date());
+        return commissionMapper.insert(commission) > 0;
+    }
+
+    /**
+     * 获取家庭总佣金(分)
+     * @param familyId 家庭ID
+     * @return 总佣金金额
+     */
+    public Integer getFamilyTotal(Long familyId) {
+        Map<String, Object> columnMap = new HashMap<>();
+        columnMap.put("family_id", familyId);
+        
+        return commissionMapper.selectByMap(columnMap)
+                .stream()
+                .mapToInt(Commission::getAmount)
+                .sum();
+    }
+}

+ 77 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PromotionMaterialService.java

@@ -0,0 +1,77 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.entity.PromotionMaterial;
+import com.etotem.cfc.mapper.PromotionMaterialMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+import com.etotem.cfc.util.SortUtil;
+
+@Slf4j
+@Service
+public class PromotionMaterialService {
+
+    @Resource
+    private PromotionMaterialMapper promotionMaterialMapper;
+
+    public Page<PromotionMaterial> getMaterials(String materialType, String usageScenario,
+            String keyword, int pageNum, int pageSize) {
+        LambdaQueryWrapper<PromotionMaterial> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(PromotionMaterial::getStatus, "enabled");
+        if (materialType != null && !materialType.isEmpty()) {
+            wrapper.eq(PromotionMaterial::getMaterialType, materialType);
+        }
+        if (usageScenario != null && !usageScenario.isEmpty()) {
+            wrapper.eq(PromotionMaterial::getUsageScenario, usageScenario);
+        }
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.like(PromotionMaterial::getTitle, keyword)
+                   .or(w -> w.like(PromotionMaterial::getTags, keyword));
+        }
+        wrapper.orderByAsc(PromotionMaterial::getSortOrder);
+        wrapper.orderByDesc(PromotionMaterial::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return promotionMaterialMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
+    }
+
+    public PromotionMaterial getById(Long id) {
+        return promotionMaterialMapper.selectById(id);
+    }
+
+    public PromotionMaterial createMaterial(PromotionMaterial material) {
+        material.setStatus("enabled");
+        material.setCreatedAt(new Date());
+        material.setUpdatedAt(new Date());
+        promotionMaterialMapper.insert(material);
+        return material;
+    }
+
+    public boolean updateMaterial(PromotionMaterial material) {
+        material.setUpdatedAt(new Date());
+        return promotionMaterialMapper.updateById(material) > 0;
+    }
+
+    public boolean deleteMaterial(Long id) {
+        PromotionMaterial material = promotionMaterialMapper.selectById(id);
+        if (material != null) {
+            material.setStatus("disabled");
+            material.setUpdatedAt(new Date());
+            return promotionMaterialMapper.updateById(material) > 0;
+        }
+        return false;
+    }
+
+    public List<PromotionMaterial> getByScenario(String scenario) {
+        return promotionMaterialMapper.selectList(
+            new LambdaQueryWrapper<PromotionMaterial>()
+                .eq(PromotionMaterial::getStatus, "enabled")
+                .eq(PromotionMaterial::getUsageScenario, scenario)
+                .orderByAsc(PromotionMaterial::getSortOrder)
+        );
+    }
+}

+ 123 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PromotionTierEvalService.java

@@ -0,0 +1,123 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.CfRateTier;
+import com.etotem.cfc.entity.PromotionTier;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.PromotionTierMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class PromotionTierEvalService {
+
+    private static final Logger log = LoggerFactory.getLogger(PromotionTierEvalService.class);
+
+    @Resource
+    private PromotionTierMapper tierMapper;
+
+    @Resource
+    private PromotionTierService promotionTierService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private CfReferralService cfReferralService;
+
+    @Resource
+    private WechatService wechatService;
+
+    @Value("${wechat.promotion-tier-template-id:}")
+    private String promotionTierTemplateId;
+
+    /**
+     * 根据全层级团队规模计算应属等级(读 cf_rate_tier)
+     * @return 目标等级代码,如 "R2",无匹配返回 "R0"
+     */
+    public String evaluateTier(Long userId) {
+        try {
+            int teamSize = cfReferralService.getTotalTeamSize(userId);
+            CfRateTier tier = cfReferralService.matchRateTier(teamSize);
+            return tier == null ? "R0" : tier.getTierName();
+        } catch (Exception e) {
+            return "R0";
+        }
+    }
+
+    /**
+     * 对指定用户执行等级评估,如有晋级/降级则更新
+     * @return true if tier changed, false if unchanged
+     */
+    public boolean evaluateAndUpdateTier(Long userId) {
+        PromotionTier currentTier = promotionTierService.getCurrentTier(userId);
+        String currentTierCode = currentTier != null ? currentTier.getTier() : null;
+        String newTierCode = evaluateTier(userId);
+
+        if (newTierCode.equals(currentTierCode)) {
+            return false;
+        }
+
+        // Tier changed — use existing PromotionTierService.updateTier which logs the change
+        promotionTierService.updateTier(userId, newTierCode, "qualify");
+
+        PromotionTier updatedTier = promotionTierService.getCurrentTier(userId);
+        log.info("推广等级变更: userId={}, {}→{}, 团队={}, 推荐佣金={}, 分润={}",
+                userId, currentTierCode, newTierCode,
+                updatedTier != null ? updatedTier.getTotalTeamSize() : 0,
+                updatedTier != null ? updatedTier.getTotalReferralEarnings() : 0,
+                updatedTier != null ? updatedTier.getTotalShareEarnings() : 0);
+
+        // Send WeChat template notification
+        sendPromotionNotification(userId, currentTierCode, newTierCode);
+        return true;
+    }
+
+    /**
+     * 批量评估所有有 PromotionTier 记录的用户
+     * @return 变更数量
+     */
+    public int evaluateAllUsers() {
+        List<PromotionTier> allTiers = tierMapper.selectList(null);
+        int changed = 0;
+        for (PromotionTier tier : allTiers) {
+            if (evaluateAndUpdateTier(tier.getUserId())) {
+                changed++;
+            }
+        }
+        log.info("批量推广等级评估完成,共{}个用户,检查了{}条记录", changed, allTiers.size());
+        return changed;
+    }
+
+    /**
+     * 发送推广等级变更通知(微信模板消息)
+     */
+    private void sendPromotionNotification(Long userId, String oldTier, String newTier) {
+        if (promotionTierTemplateId == null || promotionTierTemplateId.isEmpty()) {
+            return;
+        }
+        try {
+            User user = userMapper.selectById(userId);
+            if (user == null || user.getOpenid() == null || user.getOpenid().isEmpty()) {
+                return;
+            }
+            Map<String, Object> keywordMap = new HashMap<>();
+            keywordMap.put("keyword1", oldTier != null ? oldTier : "无");
+            keywordMap.put("keyword2", newTier);
+            keywordMap.put("keyword3", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
+            wechatService.sendTemplateMessage(user.getOpenid(), promotionTierTemplateId, keywordMap);
+            log.info("已发送推广等级变更通知: userId={}, {}→{}", userId, oldTier, newTier);
+        } catch (Exception e) {
+            log.warn("发送推广等级变更通知失败 userId={}", userId, e);
+        }
+    }
+}

+ 189 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PromotionTierService.java

@@ -0,0 +1,189 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.CfRateTier;
+import com.etotem.cfc.entity.PromotionTier;
+import com.etotem.cfc.entity.PromotionTierChangeLog;
+import com.etotem.cfc.entity.PromotionTierConfig;
+import com.etotem.cfc.mapper.PromotionTierChangeLogMapper;
+import com.etotem.cfc.mapper.PromotionTierConfigMapper;
+import com.etotem.cfc.mapper.PromotionTierMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class PromotionTierService {
+
+    private static final Logger log = LoggerFactory.getLogger(PromotionTierService.class);
+
+    @Resource
+    private PromotionTierMapper tierMapper;
+
+    @Resource
+    private PromotionTierChangeLogMapper changeLogMapper;
+
+    @Resource
+    private PromotionTierConfigMapper tierConfigMapper;
+
+    @Resource
+    private CfReferralService cfReferralService;
+
+    /**
+     * 获取用户当前推广等级
+     */
+    public PromotionTier getCurrentTier(Long userId) {
+        return tierMapper.selectOne(
+                new LambdaQueryWrapper<PromotionTier>()
+                        .eq(PromotionTier::getUserId, userId)
+                        .orderByDesc(PromotionTier::getUpdatedAt)
+                        .last("LIMIT 1")
+        );
+    }
+
+    /**
+     * 获取所有等级配置
+     */
+    public List<PromotionTier> getAllTierConfigs() {
+        return tierMapper.selectList(null);
+    }
+
+    /**
+     * 按等级代码获取等级配置(含profitSharePercent P点比例)
+     * @param tierCode 等级代码: R0/R1/R2/R3/R4
+     * @return 等级配置,未找到返回null
+     */
+    public PromotionTierConfig getTierConfig(String tierCode) {
+        if (tierCode == null) return null;
+        return tierConfigMapper.selectOne(
+                new LambdaQueryWrapper<PromotionTierConfig>()
+                        .eq(PromotionTierConfig::getTierCode, tierCode)
+                        .last("LIMIT 1")
+        );
+    }
+
+    /**
+     * 团队规模 +delta(新推荐绑定后对所有祖先增量)。level 参数已废弃(改为全层级)。
+     */
+    public void updateTeamSize(Long userId, int delta) {
+        PromotionTier tier = getCurrentTier(userId);
+        if (tier == null) {
+            tier = new PromotionTier();
+            tier.setUserId(userId);
+            tier.setTier("R0");
+            tier.setTotalTeamSize(0);
+            tier.setTotalReferralEarnings(0);
+            tier.setTotalShareEarnings(0);
+            tier.setCreatedAt(new Date());
+            tier.setUpdatedAt(new Date());
+            tierMapper.insert(tier);
+        }
+        tier.setTotalTeamSize((tier.getTotalTeamSize() == null ? 0 : tier.getTotalTeamSize()) + delta);
+        tier.setLastChangeAt(new Date());
+        tier.setUpdatedAt(new Date());
+        tierMapper.updateById(tier);
+        refreshRate(userId);
+    }
+
+    /**
+     * 按全层级团队规模刷新等级与返佣比例(读 cf_rate_tier)
+     */
+    public void refreshRate(Long userId) {
+        try {
+            int teamSize = cfReferralService.getTotalTeamSize(userId);
+            CfRateTier tier = cfReferralService.matchRateTier(teamSize);
+            PromotionTier pt = getCurrentTier(userId);
+            if (pt == null) return;
+            if (tier != null) {
+                pt.setTier(tier.getTierName());
+                pt.setRatePercent(tier.getRatePercent());
+            } else {
+                pt.setTier("R0");
+                pt.setRatePercent(0);
+            }
+            pt.setUpdatedAt(new Date());
+            tierMapper.updateById(pt);
+        } catch (Exception e) {
+            log.warn("refreshRate失败 userId={}", userId, e);
+        }
+    }
+
+    /**
+     * 累加推荐佣金
+     */
+    public void addReferralEarnings(Long userId, int amount) {
+        PromotionTier tier = getCurrentTier(userId);
+        if (tier == null) {
+            return;
+        }
+        tier.setTotalReferralEarnings(
+                (tier.getTotalReferralEarnings() != null ? tier.getTotalReferralEarnings() : 0) + amount
+        );
+        tier.setLastChangeAt(new Date());
+        tier.setUpdatedAt(new Date());
+        tierMapper.updateById(tier);
+    }
+
+    /**
+     * 累加消费返利
+     */
+    public void addShareEarnings(Long userId, int amount) {
+        PromotionTier tier = getCurrentTier(userId);
+        if (tier == null) {
+            return;
+        }
+        tier.setTotalShareEarnings(
+                (tier.getTotalShareEarnings() != null ? tier.getTotalShareEarnings() : 0) + amount
+        );
+        tier.setLastChangeAt(new Date());
+        tier.setUpdatedAt(new Date());
+        tierMapper.updateById(tier);
+    }
+
+    /**
+     * 手动更新推广等级(管理员)
+     */
+    public void updateTier(Long userId, String tierCode) {
+        updateTier(userId, tierCode, "admin");
+    }
+
+    /**
+     * 更新推广等级(指定原因)
+     */
+    public void updateTier(Long userId, String tierCode, String reason) {
+        PromotionTier tier = getCurrentTier(userId);
+        String fromTier = tier != null ? tier.getTier() : null;
+
+        PromotionTierChangeLog log = new PromotionTierChangeLog();
+        log.setUserId(userId);
+        log.setOldTier(fromTier);
+        log.setNewTier(tierCode);
+        log.setReason(reason);
+        log.setChangedAt(new Date());
+        changeLogMapper.insert(log);
+
+        if (tier == null) {
+            tier = new PromotionTier();
+            tier.setUserId(userId);
+            tier.setTier(tierCode);
+            tier.setTotalTeamSize(0);
+            tier.setTotalReferralEarnings(0);
+            tier.setTotalShareEarnings(0);
+            tier.setPromotedAt(new Date());
+            tier.setLastChangeAt(new Date());
+            tier.setCreatedAt(new Date());
+            tier.setUpdatedAt(new Date());
+            tierMapper.insert(tier);
+        } else {
+            tier.setTier(tierCode);
+            tier.setPromotedAt(new Date());
+            tier.setLastChangeAt(new Date());
+            tier.setUpdatedAt(new Date());
+            tierMapper.updateById(tier);
+        }
+    }
+}

+ 33 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/PurchaseService.java

@@ -0,0 +1,33 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.PurchaseOrder;
+import java.util.Map;
+
+public interface PurchaseService {
+    /** 检查用户是否有有效购买 */
+    Map<String, Object> checkPurchase(Long userId);
+    
+    /** 创建购买订单 */
+    Map<String, Object> createOrder(Long userId, Long familyId);
+    
+    /** 确认支付 */
+    Map<String, Object> confirmPayment(String orderNo, String paymentMethod, String transactionId);
+    
+    /** 获取续费信息 */
+    Map<String, Object> getRenewalInfo(Long userId);
+    
+    /** 处理续费(真实支付) */
+    Map<String, Object> processRenewal(Long userId, Long familyId, Integer amount);
+
+    /**
+     * 处理续费(真实支付 + 可选 CF 值抵扣)。
+     *
+     * <p>F-5:CF 值抵扣改投统一账本 cf_balance(支付人 member 维度),幂等 refId = 续费订单 ID。</p>
+     *
+     * @param cfUsed 本次使用的 CF 值数量(可为空/0 = 不使用抵扣)
+     */
+    Map<String, Object> processRenewal(Long userId, Long familyId, Integer amount, Integer cfUsed);
+    
+    /** 按订单号查询订单 */
+    PurchaseOrder getByOrderNo(String orderNo);
+}

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

@@ -0,0 +1,95 @@
+package com.etotem.cfc.service;
+
+import com.google.zxing.BarcodeFormat;
+import com.google.zxing.EncodeHintType;
+import com.google.zxing.WriterException;
+import com.google.zxing.common.BitMatrix;
+import com.google.zxing.qrcode.QRCodeWriter;
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.imageio.ImageIO;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+
+@Slf4j
+@Service
+public class QrCodeService {
+
+    private static final int QR_SIZE = 400;
+    private static final int MARGIN = 20;
+
+    /**
+     * 生成二维码图片,返回 Base64 编码的 PNG 数据
+     */
+    public String generateQrCodeBase64(String content) {
+        try {
+            QRCodeWriter qrCodeWriter = new QRCodeWriter();
+            Map<EncodeHintType, Object> hints = new HashMap<>();
+            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
+            hints.put(EncodeHintType.MARGIN, 2);
+
+            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_SIZE, QR_SIZE, hints);
+
+            BufferedImage image = new BufferedImage(QR_SIZE, QR_SIZE, BufferedImage.TYPE_INT_RGB);
+            for (int x = 0; x < QR_SIZE; x++) {
+                for (int y = 0; y < QR_SIZE; y++) {
+                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
+                }
+            }
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            ImageIO.write(image, "PNG", baos);
+            byte[] bytes = baos.toByteArray();
+            return Base64.getEncoder().encodeToString(bytes);
+        } catch (WriterException | IOException e) {
+            log.error("生成二维码失败", e);
+            return null;
+        }
+    }
+
+    /**
+     * 生成带 Logo 的二维码(可选)
+     */
+    public String generateQrCodeWithLogoBase64(String content, BufferedImage logo) {
+        try {
+            QRCodeWriter qrCodeWriter = new QRCodeWriter();
+            Map<EncodeHintType, Object> hints = new HashMap<>();
+            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
+            hints.put(EncodeHintType.MARGIN, 2);
+
+            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_SIZE, QR_SIZE, hints);
+
+            BufferedImage image = new BufferedImage(QR_SIZE, QR_SIZE, BufferedImage.TYPE_INT_RGB);
+            for (int x = 0; x < QR_SIZE; x++) {
+                for (int y = 0; y < QR_SIZE; y++) {
+                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
+                }
+            }
+
+            // 在中心绘制 Logo
+            if (logo != null) {
+                Graphics2D g = image.createGraphics();
+                int logoSize = QR_SIZE / 5;
+                int logoX = (QR_SIZE - logoSize) / 2;
+                int logoY = (QR_SIZE - logoSize) / 2;
+                g.drawImage(logo, logoX, logoY, logoSize, logoSize, null);
+                g.dispose();
+            }
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            ImageIO.write(image, "PNG", baos);
+            byte[] bytes = baos.toByteArray();
+            return Base64.getEncoder().encodeToString(bytes);
+        } catch (WriterException | IOException e) {
+            log.error("生成带Logo二维码失败", e);
+            return null;
+        }
+    }
+}

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

@@ -0,0 +1,57 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+/**
+ * 真实姓名回填:用户第一次输入地址/收货人时,若 users.real_name 尚未填写,
+ * 用联系人姓名回填(规格:docs/superpowers/specs/2026-10-10-address-contact-backfill-realname-design.md)。
+ * 幂等:回填一次后 realName 非空,后续保存不再触发。
+ * 风格参照 ConsigneeService.syncUserRegion():失败静默,不阻塞主流程。
+ */
+@Service
+public class RealNameBackfillService {
+
+    private static final Logger log = LoggerFactory.getLogger(RealNameBackfillService.class);
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 若 userId 对应用户的 realName 为空白,则用 contactName(去首尾空白后)回填。
+     * contactName 空白、userId 为空、用户不存在时直接跳过。
+     */
+    public void backfill(Long userId, String contactName) {
+        backfillRealNameAndNickname(userId, contactName);
+    }
+
+    /**
+     * 若 userId 对应用户的 realName 为空白,则同时回填 realName 和 nickname(nickname 仅在也为空白时补)。
+     * contactName 空白、userId 为空、用户不存在时直接跳过;失败静默不阻塞主流程。
+     * 幂等:realName 非空后再次调用直接跳过。
+     */
+    public void backfillRealNameAndNickname(Long userId, String contactName) {
+        try {
+            if (userId == null) return;
+            if (contactName == null || contactName.trim().isEmpty()) return;
+            User user = userMapper.selectById(userId);
+            if (user == null) return;
+            String realName = user.getRealName();
+            if (realName != null && !realName.trim().isEmpty()) return;
+            String name = contactName.trim();
+            user.setRealName(name);
+            String nickname = user.getNickname();
+            if (nickname == null || nickname.trim().isEmpty()) {
+                user.setNickname(name);
+            }
+            userMapper.updateById(user);
+        } catch (Exception e) {
+            log.warn("[RealNameBackfill] 回填失败 userId={} : {}", userId, e.getMessage());
+        }
+    }
+}

+ 49 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RecipeService.java

@@ -0,0 +1,49 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Recipe;
+import com.etotem.cfc.mapper.RecipeMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import com.etotem.cfc.util.SortUtil;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Service
+public class RecipeService {
+
+    @Resource
+    private RecipeMapper recipeMapper;
+
+    public List<Recipe> listByMealType(String mealType) {
+        return listByMealType(mealType, null);
+    }
+
+    public List<Recipe> listByMealType(String mealType, List<Map<String, String>> sortSpecs) {
+        LambdaQueryWrapper<Recipe> wrapper = new LambdaQueryWrapper<Recipe>()
+                .eq(Recipe::getStatus, "active")
+                .eq(mealType != null, Recipe::getMealType, mealType);
+        SortUtil.applySort(wrapper, sortSpecs, null);
+        return recipeMapper.selectList(wrapper);
+    }
+
+    public Recipe getById(Long id) {
+        return recipeMapper.selectById(id);
+    }
+
+    public void create(Recipe recipe) {
+        recipeMapper.insert(recipe);
+    }
+
+    public void update(Recipe recipe) {
+        recipeMapper.updateById(recipe);
+    }
+
+    public void delete(Long id) {
+        recipeMapper.deleteById(id);
+    }
+}

+ 8 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RecommendService.java

@@ -0,0 +1,8 @@
+package com.etotem.cfc.service;
+
+import java.util.Map;
+
+public interface RecommendService {
+    /** 基于画像获取推荐列表 */
+    Map<String, Object> getRecommendations(Long memberId, Long userId);
+}

+ 104 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RecommendationRuleService.java

@@ -0,0 +1,104 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.RecommendationRule;
+import com.etotem.cfc.mapper.RecommendationRuleMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+@Slf4j
+public class RecommendationRuleService extends ServiceImpl<RecommendationRuleMapper, RecommendationRule> {
+
+    @Resource
+    private RecommendationRuleMapper recommendationRuleMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    /**
+     * 根据场景码加载启用的规则,按 priority 降序
+     */
+    public List<RecommendationRule> loadRulesByScene(String sceneCode) {
+        List<RecommendationRule> allEnabled = this.list(new LambdaQueryWrapper<RecommendationRule>()
+                .eq(RecommendationRule::getEnabled, 1));
+        return allEnabled.stream()
+                .filter(rule -> rule.getSceneCodes() != null && rule.getSceneCodes().contains(sceneCode))
+                .sorted(Comparator.comparing(RecommendationRule::getPriority).reversed())
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * 查询已购商品ID(回溯窗口内)
+     */
+    public Set<Long> getPurchasedProductIds(Long familyId, Long memberId, int daysAgo) {
+        Set<Long> ids = new HashSet<>();
+        if (familyId == null) return ids;
+
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_YEAR, -daysAgo);
+        Date cutoff = cal.getTime();
+
+        // 查 family 成员订单
+        List<ProductOrder> orders = productOrderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getFamilyId, familyId)
+                        .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                        .gt(ProductOrder::getPaidAt, cutoff)
+        );
+        for (ProductOrder order : orders) {
+            if (order.getProductId() != null) {
+                ids.add(order.getProductId());
+            }
+        }
+        // 若未查到家庭订单,且 memberId 不为空,查个人订单
+        if (ids.isEmpty() && memberId != null) {
+            List<ProductOrder> orders2 = productOrderMapper.selectList(
+                    new LambdaQueryWrapper<ProductOrder>()
+                            .eq(ProductOrder::getBuyerId, memberId)
+                            .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                            .gt(ProductOrder::getPaidAt, cutoff)
+            );
+            for (ProductOrder order : orders2) {
+                if (order.getProductId() != null) {
+                    ids.add(order.getProductId());
+                }
+            }
+        }
+        return ids;
+    }
+
+    /**
+     * 查询当前用户已购商品(用于 individual scope)
+     */
+    public Set<Long> getMyPurchasedProductIds(Long userId, int daysAgo) {
+        Set<Long> ids = new HashSet<>();
+        if (userId == null) return ids;
+
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_YEAR, -daysAgo);
+        Date cutoff = cal.getTime();
+
+        List<ProductOrder> orders = productOrderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getBuyerId, userId)
+                        .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                        .gt(ProductOrder::getPaidAt, cutoff)
+        );
+        for (ProductOrder order : orders) {
+            if (order.getProductId() != null) {
+                ids.add(order.getProductId());
+            }
+        }
+        return ids;
+    }
+}

+ 387 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RecommendationService.java

@@ -0,0 +1,387 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.RecommendationQuery;
+import com.etotem.cfc.dto.RecommendationResult;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.Article;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ArticleMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductDimensionMappingMapper;
+import com.etotem.cfc.mapper.RepurchaseReminderRecordMapper;
+import com.etotem.cfc.entity.ProductDimensionMapping;
+import com.etotem.cfc.entity.RepurchaseReminderRecord;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.RepurchaseReminderConfig;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.RepurchaseReminderConfigMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.service.support.ProductVisibilitySupport;
+
+/**
+ * 跨表推荐搜索服务
+ * 根据营养需求标签,在 Product / Activity / Article 中搜索匹配项
+ */
+@Slf4j
+@Service
+public class RecommendationService {
+
+    @Value("${dify.base-url:}")
+    private String difyBaseUrl;
+
+    @Value("${dify.api-key:}")
+    private String difyApiKey;
+
+    private final RestTemplate restTemplate = new RestTemplate();
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private ActivityMapper activityMapper;
+
+    @Resource
+    private ArticleMapper articleMapper;
+
+    @Resource
+    private ProductDimensionMappingMapper productDimensionMappingMapper;
+
+    @Resource
+    private RepurchaseReminderRecordMapper repurchaseReminderRecordMapper;
+
+    @Resource
+    private RepurchaseReminderConfigMapper repurchaseReminderConfigMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Resource
+    private ProductVisibilitySupport productVisibilitySupport;
+
+    /**
+     * 按营养标签搜索推荐内容
+     */
+    public List<RecommendationResult> search(RecommendationQuery query) {
+        List<RecommendationResult> results = new ArrayList<>();
+        List<String> tags = query.getNutritionTags();
+        if (tags == null || tags.isEmpty()) return results;
+
+        int limit = query.getLimit() != null ? query.getLimit() : 5;
+
+        if (query.getTypes() == null || query.getTypes().contains("product")) {
+            results.addAll(searchProducts(tags, limit, query.getUserId()));
+        }
+        if (query.getTypes() == null || query.getTypes().contains("activity")) {
+            results.addAll(searchActivities(tags, limit));
+        }
+        if (query.getTypes() == null || query.getTypes().contains("article")) {
+            results.addAll(searchArticles(tags, limit));
+        }
+
+        // Dify AI fallback: supplement with AI recommendations when results are insufficient
+        if (results.size() < limit && tags != null && !tags.isEmpty()) {
+            try {
+                List<RecommendationResult> aiResults = searchViaDify(tags, limit - results.size());
+                Set<Long> existingIds = results.stream().map(RecommendationResult::getId).collect(java.util.stream.Collectors.toSet());
+                for (RecommendationResult r : aiResults) {
+                    if (!existingIds.contains(r.getId())) {
+                        results.add(r);
+                        existingIds.add(r.getId());
+                    }
+                }
+            } catch (Exception e) {
+                log.warn("Dify AI recommendation failed, using existing results only", e);
+            }
+        }
+
+        return results;
+    }
+
+    private List<RecommendationResult> searchViaDify(List<String> tags, int limit) {
+        List<RecommendationResult> aiResults = new ArrayList<>();
+        try {
+            String query = String.join(" ", tags);
+            String encoded = java.net.URLEncoder.encode(query, "UTF-8");
+            String url = difyBaseUrl + "/v1/datasets?keyword=" + encoded;
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("Authorization", "Bearer " + difyApiKey);
+            HttpEntity<String> entity = new HttpEntity<>(headers);
+            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
+            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
+                log.info("Dify AI recommendation returned data for query: {}", query);
+            }
+        } catch (Exception e) {
+            log.warn("Dify AI recommendation call failed, fallback to existing results", e);
+        }
+        return aiResults;
+    }
+
+    private List<RecommendationResult> searchProducts(List<String> tags, int limit, Long userId) {
+        Set<Long> added = new HashSet<>();
+        List<RecommendationResult> results = new ArrayList<>();
+
+        for (String tag : tags) {
+            if (results.size() >= limit) break;
+            String keyword = "%" + tag + "%";
+
+            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
+                    .eq(Product::getStatus, "on_shelf")
+                    .gt(Product::getStock, 0)
+                    .and(w -> w.like(Product::getName, keyword)
+                            .or()
+                            .like(Product::getDescription, keyword)
+                            // 营养标签优先命中:商品已配置 nutrition_tags(逗号分隔)时按标签匹配
+                            .or()
+                            .like(Product::getNutritionTags, keyword))
+                    .last("LIMIT " + (limit - results.size()));
+            // 商品可见性过滤(min_visible_level + vendor_visible)
+            productVisibilitySupport.applyToQuery(wrapper, userId, null);
+            List<Product> products = productMapper.selectList(wrapper);
+
+            for (Product p : products) {
+                if (added.add(p.getId())) {
+                    RecommendationResult r = new RecommendationResult();
+                    r.setType("product");
+                    r.setId(p.getId());
+                    r.setName(p.getName());
+                    r.setDescription(p.getIntro() != null ? p.getIntro() : p.getDescription());
+                    r.setCoverImage(p.getCoverImage());
+                    r.setPrice(p.getPrice());
+                    r.setUrl("/pages/shop/detail?id=" + p.getId());
+                    r.setSource("platform");
+                    results.add(r);
+                }
+            }
+        }
+        return results;
+    }
+
+    private List<RecommendationResult> searchActivities(List<String> tags, int limit) {
+        Set<Long> added = new HashSet<>();
+        List<RecommendationResult> results = new ArrayList<>();
+
+        for (String tag : tags) {
+            if (results.size() >= limit) break;
+            String keyword = "%" + tag + "%";
+
+            List<Activity> activities = activityMapper.selectList(
+                    new LambdaQueryWrapper<Activity>()
+                            .eq(Activity::getStatus, "published")
+                            .ge(Activity::getEndTime, new Date())
+                            .and(w -> w.like(Activity::getTitle, keyword)
+                                    .or()
+                                    .like(Activity::getDescription, keyword))
+                            .last("LIMIT " + (limit - results.size()))
+            );
+
+            for (Activity a : activities) {
+                if (added.add(a.getId())) {
+                    RecommendationResult r = new RecommendationResult();
+                    r.setType("activity");
+                    r.setId(a.getId());
+                    r.setName(a.getTitle());
+                    r.setDescription(a.getDescription());
+                    r.setCoverImage(a.getCoverImage());
+                    r.setPrice(a.getPrice());
+                    r.setUrl("/pages/activity/detail?id=" + a.getId());
+                    r.setSource("platform");
+                    results.add(r);
+                }
+            }
+        }
+        return results;
+    }
+
+    private List<RecommendationResult> searchArticles(List<String> tags, int limit) {
+        Set<Long> added = new HashSet<>();
+        List<RecommendationResult> results = new ArrayList<>();
+
+        for (String tag : tags) {
+            if (results.size() >= limit) break;
+            String keyword = "%" + tag + "%";
+
+            List<Article> articles = articleMapper.selectList(
+                    new LambdaQueryWrapper<Article>()
+                            .eq(Article::getStatus, "published")
+                            .and(w -> w.like(Article::getTitle, keyword)
+                                    .or()
+                                    .like(Article::getSummary, keyword)
+                                    .or()
+                                    .like(Article::getTags, keyword))
+                            .last("LIMIT " + (limit - results.size()))
+            );
+
+            for (Article a : articles) {
+                if (added.add(a.getId())) {
+                    RecommendationResult r = new RecommendationResult();
+                    r.setType("article");
+                    r.setId(a.getId());
+                    r.setName(a.getTitle());
+                    r.setDescription(a.getSummary());
+                    r.setCoverImage(a.getCoverImage());
+                    r.setUrl("/pages/article/detail?id=" + a.getId());
+                    r.setSource("platform");
+                    results.add(r);
+                }
+            }
+        }
+        return results;
+    }
+
+    /**
+     * 按维度获取匹配商品
+     */
+    public List<RecommendationResult> getDimensionProducts(String dimensionCode, Long familyId, Integer limit) {
+        List<RecommendationResult> results = new ArrayList<>();
+        if (dimensionCode == null || dimensionCode.isEmpty()) return results;
+
+        int maxLimit = limit != null ? limit : 10;
+
+        LambdaQueryWrapper<ProductDimensionMapping> wrapper = new LambdaQueryWrapper<ProductDimensionMapping>()
+                .eq(ProductDimensionMapping::getDimensionCode, dimensionCode)
+                .eq(ProductDimensionMapping::getEnabled, 1)
+                .orderByDesc(ProductDimensionMapping::getMatchScore)
+                .last("LIMIT " + maxLimit);
+
+        SortUtil.applySort(wrapper);
+        List<ProductDimensionMapping> mappings = productDimensionMappingMapper.selectList(wrapper);
+
+        for (ProductDimensionMapping m : mappings) {
+            Product product = productMapper.selectById(m.getProductId());
+            if (product == null || !"on_shelf".equals(product.getStatus()) || product.getStock() <= 0) {
+                continue;
+            }
+
+            RecommendationResult r = new RecommendationResult();
+            r.setType("product");
+            r.setId(product.getId());
+            r.setProductId(product.getId());
+            r.setName(product.getName());
+            r.setDescription(product.getIntro() != null ? product.getIntro() : product.getDescription());
+            r.setCoverImage(product.getCoverImage());
+            r.setPrice(product.getPrice());
+            r.setUrl("/pages/shop/detail?id=" + product.getId());
+            r.setSource("dimension");
+            r.setMatchScore(m.getMatchScore());
+            r.setMatchReason(m.getMatchReason());
+            results.add(r);
+        }
+
+        return results;
+    }
+
+    /**
+     * 获取用户复购提醒列表
+     */
+    public List<RecommendationResult> getRepurchaseReminders(Long userId) {
+        List<RecommendationResult> results = new ArrayList<>();
+        if (userId == null) return results;
+
+        LambdaQueryWrapper<RepurchaseReminderRecord> wrapper = new LambdaQueryWrapper<RepurchaseReminderRecord>()
+                .eq(RepurchaseReminderRecord::getUserId, userId)
+                .eq(RepurchaseReminderRecord::getPurchased, 0)
+                .orderByDesc(RepurchaseReminderRecord::getSentAt);
+
+        SortUtil.applySort(wrapper);
+        List<RepurchaseReminderRecord> records = repurchaseReminderRecordMapper.selectList(wrapper);
+
+        for (RepurchaseReminderRecord record : records) {
+            Product product = productMapper.selectById(record.getProductId());
+            if (product == null) continue;
+
+            RecommendationResult r = new RecommendationResult();
+            r.setType("repurchase");
+            r.setId(record.getId());
+            r.setProductId(product.getId());
+            r.setName(product.getName());
+            r.setDescription(product.getIntro() != null ? product.getIntro() : product.getDescription());
+            r.setCoverImage(product.getCoverImage());
+            r.setPrice(product.getPrice());
+            r.setUrl("/pages/shop/detail?id=" + product.getId());
+            r.setSource("repurchase");
+            r.setReason("复购提醒");
+            results.add(r);
+        }
+
+        return results;
+    }
+
+    /**
+     * 标记复购提醒已点击
+     */
+    public void markRepurchaseClicked(Long reminderId) {
+        if (reminderId == null) return;
+
+        RepurchaseReminderRecord record = repurchaseReminderRecordMapper.selectById(reminderId);
+        if (record != null && (record.getClicked() == null || record.getClicked() == 0)) {
+            RepurchaseReminderRecord update = new RepurchaseReminderRecord();
+            update.setId(reminderId);
+            update.setClicked(1);
+            repurchaseReminderRecordMapper.updateById(update);
+        }
+    }
+
+    public void generateDailyRepurchaseReminders() {
+        List<RepurchaseReminderConfig> configs = repurchaseReminderConfigMapper.selectList(
+                new LambdaQueryWrapper<RepurchaseReminderConfig>()
+                        .eq(RepurchaseReminderConfig::getEnabled, 1)
+        );
+        if (configs.isEmpty()) return;
+
+        for (RepurchaseReminderConfig config : configs) {
+            int reminderDays = config.getReminderDays() != null ? config.getReminderDays() : 30;
+            Date since = new Date(System.currentTimeMillis() - reminderDays * 24L * 60 * 60 * 1000);
+
+            List<ProductOrder> orders = productOrderMapper.selectList(
+                    new LambdaQueryWrapper<ProductOrder>()
+                            .in(ProductOrder::getStatus, "paid", "received")
+                            .le(ProductOrder::getCreatedAt, since)
+                            .last("LIMIT 500")
+            );
+
+            for (ProductOrder order : orders) {
+                Product product = productMapper.selectById(order.getProductId());
+                if (product == null) continue;
+
+                if (config.getProductId() != null && !config.getProductId().equals(order.getProductId())) {
+                    continue;
+                }
+                if (config.getProductCategory() != null && !config.getProductCategory().isEmpty()
+                        && !config.getProductCategory().equals(
+                            product.getCategoryId() != null ? String.valueOf(product.getCategoryId()) : "")) {
+                    continue;
+                }
+
+                Long existingCount = repurchaseReminderRecordMapper.selectCount(
+                        new LambdaQueryWrapper<RepurchaseReminderRecord>()
+                                .eq(RepurchaseReminderRecord::getUserId, order.getBuyerId())
+                                .eq(RepurchaseReminderRecord::getProductId, order.getProductId())
+                                .eq(RepurchaseReminderRecord::getPurchased, 0)
+                );
+                if (existingCount > 0) continue;
+
+                RepurchaseReminderRecord record = new RepurchaseReminderRecord();
+                record.setUserId(order.getBuyerId());
+                record.setProductId(order.getProductId());
+                record.setOrderId(order.getId());
+                record.setReminderDays(reminderDays);
+                record.setSentAt(new Date());
+                record.setClicked(0);
+                record.setPurchased(0);
+                repurchaseReminderRecordMapper.insert(record);
+                log.info("生成复购提醒: userId={}, productId={}, orderId={}",
+                        order.getBuyerId(), order.getProductId(), order.getId());
+            }
+        }
+    }
+}

+ 196 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReferralLeaderboardService.java

@@ -0,0 +1,196 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.ReferralLeaderboard;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ReferralLeaderboardMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class ReferralLeaderboardService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReferralLeaderboardService.class);
+
+    @Resource
+    private ReferralLeaderboardMapper referralLeaderboardMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
+
+    /** 推荐排行榜 Redis key 前缀 */
+    private static final String REFERRAL_LEADERBOARD_KEY_PREFIX = "referral:leaderboard:";
+
+    /**
+     * 获取当前周的周一日期(Asia/Shanghai时区)
+     */
+    public String getCurrentWeekStart() {
+        LocalDate today = LocalDate.now(ZoneId.of("Asia/Shanghai"));
+        LocalDate monday = today.with(java.time.DayOfWeek.MONDAY);
+        return monday.format(DateTimeFormatter.ISO_LOCAL_DATE);
+    }
+
+    /**
+     * 推荐成功后递增当前周的推荐计数
+     * 使用 INSERT ... ON DUPLICATE KEY UPDATE 保证原子性
+     */
+    public void incrementCount(Long userId) {
+        String weekStart = getCurrentWeekStart();
+        String sql = "INSERT INTO referral_leaderboard (user_id, week_start, referral_count, created_at) " +
+                "VALUES (?, ?, 1, NOW()) " +
+                "ON DUPLICATE KEY UPDATE referral_count = referral_count + 1";
+        try {
+            jdbcTemplate.update(sql, userId, weekStart);
+            log.info("排行榜计数递增成功: userId={}, weekStart={}", userId, weekStart);
+        } catch (Exception e) {
+            log.error("排行榜计数递增失败: userId={}, weekStart={}", userId, weekStart, e);
+        }
+        // 同步更新 Redis 排行榜(失败不影响主流程)
+        try {
+            redisTemplate.opsForZSet().incrementScore(
+                    REFERRAL_LEADERBOARD_KEY_PREFIX + weekStart,
+                    String.valueOf(userId),
+                    1.0);
+        } catch (Exception e) {
+            log.warn("Redis 排行榜递增失败: userId={}, weekStart={}, error={}",
+                    userId, weekStart, e.getMessage());
+        }
+    }
+
+    /**
+     * 获取指定周的排行榜前N名(含用户昵称和头像)
+     */
+    public List<Map<String, Object>> getTopUsers(String weekStart, int limit) {
+        if (weekStart == null || weekStart.isEmpty()) {
+            weekStart = getCurrentWeekStart();
+        }
+        // 优先从 Redis 读取排行榜
+        try {
+            java.util.Set<Object> topMembers = redisTemplate.opsForZSet()
+                    .reverseRange(REFERRAL_LEADERBOARD_KEY_PREFIX + weekStart, 0, limit - 1);
+            if (topMembers != null && !topMembers.isEmpty()) {
+                List<Map<String, Object>> result = new ArrayList<>();
+                int rank = 1;
+                for (Object member : topMembers) {
+                    Long userId = Long.valueOf(member.toString());
+                    Double count = redisTemplate.opsForZSet()
+                            .score(REFERRAL_LEADERBOARD_KEY_PREFIX + weekStart, member);
+                    Map<String, Object> item = new HashMap<>();
+                    item.put("userId", userId);
+                    item.put("referralCount", count != null ? count.intValue() : 0);
+                    item.put("rank", rank);
+
+                    User user = userMapper.selectById(userId);
+                    if (user != null) {
+                        item.put("nickname", user.getNickname() != null ? user.getNickname() : "微信用户");
+                        item.put("avatarUrl", user.getAvatar() != null ? user.getAvatar() : "");
+                    } else {
+                        item.put("nickname", "未知用户");
+                        item.put("avatarUrl", "");
+                    }
+                    result.add(item);
+                    rank++;
+                }
+                return result;
+            }
+        } catch (Exception e) {
+            log.warn("Redis 排行榜读取失败,回退数据库: {}", e.getMessage());
+        }
+        List<ReferralLeaderboard> topList = referralLeaderboardMapper.findTopByWeek(weekStart, limit);
+        List<Map<String, Object>> result = new ArrayList<>();
+        int rank = 1;
+        for (ReferralLeaderboard entry : topList) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("userId", entry.getUserId());
+            item.put("referralCount", entry.getReferralCount());
+            item.put("rank", rank);
+
+            User user = userMapper.selectById(entry.getUserId());
+            if (user != null) {
+                item.put("nickname", user.getNickname() != null ? user.getNickname() : "微信用户");
+                item.put("avatarUrl", user.getAvatar() != null ? user.getAvatar() : "");
+            } else {
+                item.put("nickname", "未知用户");
+                item.put("avatarUrl", "");
+            }
+            result.add(item);
+            rank++;
+        }
+        return result;
+    }
+
+    /**
+     * 获取当前用户在指定周的排名
+     */
+    public Map<String, Object> getMyRank(Long userId, String weekStart) {
+        if (weekStart == null || weekStart.isEmpty()) {
+            weekStart = getCurrentWeekStart();
+        }
+        Map<String, Object> result = new HashMap<>();
+        result.put("userId", userId);
+        // 优先从 Redis 读取排名
+        try {
+            Double score = redisTemplate.opsForZSet()
+                    .score(REFERRAL_LEADERBOARD_KEY_PREFIX + weekStart, String.valueOf(userId));
+            if (score != null) {
+                Long rank = redisTemplate.opsForZSet()
+                        .reverseRank(REFERRAL_LEADERBOARD_KEY_PREFIX + weekStart, String.valueOf(userId));
+                result.put("referralCount", score.intValue());
+                result.put("rank", rank != null ? rank + 1 : null);
+                return result;
+            }
+        } catch (Exception e) {
+            log.warn("Redis 排名读取失败,回退数据库: {}", e.getMessage());
+        }
+        ReferralLeaderboard entry = referralLeaderboardMapper.findByUserAndWeek(userId, weekStart);
+        if (entry != null) {
+            // 计算实际排名:统计比当前用户推荐数多的人数
+            String countSql = "SELECT COUNT(*) + 1 FROM referral_leaderboard " +
+                    "WHERE week_start = ? AND referral_count > ?";
+            Integer actualRank = jdbcTemplate.queryForObject(countSql, Integer.class, weekStart, entry.getReferralCount());
+            result.put("referralCount", entry.getReferralCount());
+            result.put("rank", actualRank != null ? actualRank : null);
+        } else {
+            result.put("referralCount", 0);
+            result.put("rank", null);
+        }
+        return result;
+    }
+
+    /**
+     * 计算指定周所有用户的排名并更新rank字段
+     */
+    public void calculateWeeklyRanks(String weekStart) {
+        String sql = "UPDATE referral_leaderboard r " +
+                "INNER JOIN (" +
+                "  SELECT id, @rn := @rn + 1 AS pos " +
+                "  FROM referral_leaderboard, (SELECT @rn := 0) vars " +
+                "  WHERE week_start = ? ORDER BY referral_count DESC" +
+                ") ranked ON r.id = ranked.id " +
+                "SET r.rank = ranked.pos";
+        try {
+            jdbcTemplate.update(sql, weekStart);
+            log.info("周排行榜排名计算完成: weekStart={}", weekStart);
+        } catch (Exception e) {
+            log.error("周排行榜排名计算失败: weekStart={}", weekStart, e);
+        }
+    }
+}

+ 305 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RelationshipQualityService.java

@@ -0,0 +1,305 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.HealthAlertVO;
+import com.etotem.cfc.dto.MilestoneVO;
+import com.etotem.cfc.dto.RelationshipScoreVO;
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.FamilyMemberAttributes;
+import com.etotem.cfc.entity.FamilyRelationship;
+import com.etotem.cfc.mapper.FamilyMemberAttributesMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class RelationshipQualityService {
+
+    private static final Logger log = LoggerFactory.getLogger(RelationshipQualityService.class);
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private FamilyMemberAttributesMapper familyMemberAttributesMapper;
+
+    @Resource
+    private FamilyRelationshipService familyRelationshipService;
+
+    private static final String TYPE_BIRTHDAY = "birthday";
+
+    /**
+     * 获取家庭所有成员的关系质量评分
+     */
+    public List<RelationshipScoreVO> getScores(Long familyId) {
+        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyMember::getFamilyId, familyId);
+        SortUtil.applySort(wrapper);
+        List<FamilyMember> members = familyMemberMapper.selectList(wrapper);
+
+        List<RelationshipScoreVO> result = new ArrayList<>();
+        for (FamilyMember member : members) {
+            RelationshipScoreVO vo = new RelationshipScoreVO();
+            vo.setMemberId(member.getId());
+            vo.setNickname(member.getNickname());
+            vo.setEffectiveRole(computeEffectiveRole(member));
+            vo.setTrustScore(member.getTrustScore() != null ? member.getTrustScore() : BigDecimal.ZERO);
+            vo.setIntimacyScore(member.getIntimacyScore() != null ? member.getIntimacyScore() : BigDecimal.ZERO);
+            vo.setCommunicationScore(member.getCommunicationScore() != null ? member.getCommunicationScore() : BigDecimal.ZERO);
+            vo.setLastInteractionAt(member.getLastInteractionAt());
+
+            // 计算综合得分
+            BigDecimal total = vo.getTrustScore()
+                    .add(vo.getIntimacyScore())
+                    .add(vo.getCommunicationScore())
+                    .divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP);
+            vo.setTotalScore(total);
+
+            // 计算健康状态
+            vo.setHealthStatus(calculateHealthStatus(member));
+            result.add(vo);
+        }
+        return result;
+    }
+
+    /**
+     * 计算并保存单个成员的评分
+     */
+    public RelationshipScoreVO calculateScore(Long memberId) {
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        if (member == null) {
+            throw new RuntimeException("成员不存在");
+        }
+
+        // 实际计算逻辑在 T16(评分计算逻辑)中实现
+        // 这里只做基础计算
+        RelationshipScoreVO vo = new RelationshipScoreVO();
+        vo.setMemberId(member.getId());
+        vo.setNickname(member.getNickname());
+        vo.setEffectiveRole(computeEffectiveRole(member));
+        vo.setTrustScore(member.getTrustScore() != null ? member.getTrustScore() : BigDecimal.ZERO);
+        vo.setIntimacyScore(member.getIntimacyScore() != null ? member.getIntimacyScore() : BigDecimal.ZERO);
+        vo.setCommunicationScore(member.getCommunicationScore() != null ? member.getCommunicationScore() : BigDecimal.ZERO);
+        vo.setLastInteractionAt(member.getLastInteractionAt());
+
+        BigDecimal total = vo.getTrustScore()
+                .add(vo.getIntimacyScore())
+                .add(vo.getCommunicationScore())
+                .divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP);
+        vo.setTotalScore(total);
+        vo.setHealthStatus(calculateHealthStatus(member));
+
+        return vo;
+    }
+
+    /**
+     * 获取健康预警列表(30天无互动触发预警)
+     */
+    public List<HealthAlertVO> getHealthAlerts(Long familyId) {
+        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyMember::getFamilyId, familyId);
+        SortUtil.applySort(wrapper);
+        List<FamilyMember> members = familyMemberMapper.selectList(wrapper);
+
+        List<HealthAlertVO> alerts = new ArrayList<>();
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -30);
+        Date threshold = cal.getTime();
+
+        for (FamilyMember member : members) {
+            Date lastInteraction = member.getLastInteractionAt();
+            if (lastInteraction == null || lastInteraction.before(threshold)) {
+                HealthAlertVO alert = new HealthAlertVO();
+                alert.setMemberId(member.getId());
+                alert.setNickname(member.getNickname());
+                alert.setEffectiveRole(computeEffectiveRole(member));
+
+                if (lastInteraction == null) {
+                    alert.setDaysSinceInteraction(-1);
+                    alert.setAlertLevel("critical");
+                    alert.setSuggestion("从未记录互动,建议立即安排一次家庭互动");
+                } else {
+                    long days = (System.currentTimeMillis() - lastInteraction.getTime()) / (1000 * 60 * 60 * 24);
+                    alert.setDaysSinceInteraction((int) days);
+                    alert.setAlertLevel(days > 60 ? "critical" : "warning");
+                    alert.setSuggestion("已 " + days + " 天无互动,建议安排一次面对面交流或电话联系");
+                }
+                alerts.add(alert);
+            }
+        }
+        return alerts;
+    }
+
+    /**
+     * 获取即将到来的里程碑(生日等)
+     */
+    public List<MilestoneVO> getMilestones(Long familyId, Integer daysAhead) {
+        if (daysAhead == null || daysAhead <= 0) {
+            daysAhead = 7;
+        }
+
+        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(FamilyMember::getFamilyId, familyId);
+        SortUtil.applySort(wrapper);
+        List<FamilyMember> members = familyMemberMapper.selectList(wrapper);
+
+        List<MilestoneVO> milestones = new ArrayList<>();
+        Calendar now = Calendar.getInstance();
+        Calendar future = Calendar.getInstance();
+        future.add(Calendar.DAY_OF_MONTH, daysAhead);
+
+        for (FamilyMember member : members) {
+            // 查询成员的生日信息
+            LambdaQueryWrapper<FamilyMemberAttributes> attrWrapper = new LambdaQueryWrapper<>();
+            attrWrapper.eq(FamilyMemberAttributes::getMemberId, member.getId());
+            SortUtil.applySort(attrWrapper);
+            FamilyMemberAttributes attrs = familyMemberAttributesMapper.selectOne(attrWrapper);
+
+            if (attrs != null && attrs.getBirthDatetime() != null) {
+                Date birthDate = attrs.getBirthDatetime();
+                Calendar birthCal = Calendar.getInstance();
+                birthCal.setTime(birthDate);
+                birthCal.set(Calendar.YEAR, now.get(Calendar.YEAR));
+
+                // 如果今年的生日已过,检查明年
+                if (birthCal.before(now)) {
+                    birthCal.add(Calendar.YEAR, 1);
+                }
+
+                if (!birthCal.after(future)) {
+                    MilestoneVO milestone = new MilestoneVO();
+                    milestone.setMemberId(member.getId());
+                    milestone.setNickname(member.getNickname());
+                    milestone.setMilestoneType(TYPE_BIRTHDAY);
+                    milestone.setEventName(member.getNickname() + "的生日");
+                    milestone.setEventDate(birthCal.getTime());
+                    milestone.setDaysAhead((int) ((birthCal.getTimeInMillis() - now.getTimeInMillis()) / (1000 * 60 * 60 * 24)));
+                    milestone.setReminder("还有 " + milestone.getDaysAhead() + " 天是 " + member.getNickname() + " 的生日,记得准备惊喜!");
+                    milestones.add(milestone);
+                }
+            }
+        }
+        return milestones;
+    }
+
+    private String calculateHealthStatus(FamilyMember member) {
+        if (member.getLastInteractionAt() == null) {
+            return "critical";
+        }
+
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -30);
+        if (member.getLastInteractionAt().before(cal.getTime())) {
+            return "warning";
+        }
+
+        BigDecimal avgScore = BigDecimal.ZERO;
+        if (member.getTrustScore() != null && member.getIntimacyScore() != null && member.getCommunicationScore() != null) {
+            avgScore = member.getTrustScore()
+                    .add(member.getIntimacyScore())
+                    .add(member.getCommunicationScore())
+                    .divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP);
+        }
+
+        if (avgScore.compareTo(new BigDecimal("40")) < 0) {
+            return "warning";
+        }
+        return "healthy";
+    }
+
+    private String computeEffectiveRole(FamilyMember member) {
+        if (member.getGeneration() != null) {
+            return member.getGeneration() >= 0 ? "parent" : "child";
+        }
+        return "parent";
+    }
+
+    /**
+     * 获取以指定成员为中心的所有成员关系(关系类型 + 三项评分)
+     */
+    public List<FamilyMemberVO> getPairwiseRelationships(Long centerMemberId, Long familyId) {
+        List<FamilyMemberVO> result = new ArrayList<>();
+        FamilyMember center = familyMemberMapper.selectById(centerMemberId);
+        if (center == null || (familyId != null && !familyId.equals(center.getFamilyId()))) {
+            throw new RuntimeException("成员不存在或不属于该家庭");
+        }
+        // fail-closed:查看者家庭归属不可核验(familyId 缺位)时拒绝,不得静默回退中心成员家庭
+        // (SC-P-07 边界:仅本家庭成员可见,防越权 fail-open)
+        if (familyId == null) {
+            throw new RuntimeException("无法核验查看者家庭归属,拒绝访问");
+        }
+
+        List<FamilyMember> members = familyMemberMapper.selectList(
+                new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId));
+
+        // 中心成员 → 各成员的关系行(评分与关系类型来源)
+        List<FamilyRelationship> rels = familyRelationshipService.getRelationsForMember(centerMemberId);
+        Map<Long, FamilyRelationship> relMap = new HashMap<>();
+        for (FamilyRelationship rel : rels) {
+            relMap.put(rel.getToMemberId(), rel);
+        }
+
+        for (FamilyMember fm : members) {
+            FamilyMemberVO vo = new FamilyMemberVO();
+            vo.setId(fm.getId());
+            vo.setSource("family_member");
+            vo.setUserId(fm.getUserId());
+            vo.setNickname(fm.getNickname());
+            vo.setPhone(fm.getPhone());
+            vo.setAvatar(fm.getAvatar());
+            vo.setGender(fm.getGender());
+            vo.setGeneration(fm.getGeneration());
+            vo.setEffectiveRole(computeEffectiveRole(fm));
+            vo.setRoleLabel(computeEffectiveRole(fm));
+            // 关系图节点形状字段(SC-P-07):parent/child,前端按 memberType 区分节点形状,
+            // 缺失时前端全部节点退化为 child 圆形。约定与 CompatibilityService 一致:辈分 < 0 → child。
+            vo.setMemberType(fm.getGeneration() != null && fm.getGeneration() < 0 ? "child" : "parent");
+            vo.setIsSpouse(fm.getIsSpouse());
+            vo.setIsSelf(centerMemberId.equals(fm.getId()));
+            vo.setAge(fm.getAge());
+            vo.setLastInteractionAt(fm.getLastInteractionAt());
+
+            FamilyRelationship rel = relMap.get(fm.getId());
+            if (rel != null) {
+                vo.setGenerationValue(rel.getGenerationValue());
+                String label = rel.getRelationshipKey() != null && !rel.getRelationshipKey().isEmpty()
+                        ? rel.getRelationshipKey()
+                        // 配偶/同辈等特殊关系走 3 参重载(R4):辈分差 0 时 spouse→「丈夫/妻子」而非「兄弟/姐妹」;
+                        // 其余(lineal/null)仍走 2 参推断,避免把普通关系误标为配偶。
+                        : ("spouse".equals(rel.getRelationType()) || "sibling".equals(rel.getRelationType()))
+                            ? familyRelationshipService.computeRelationshipLabel(rel.getGenerationValue(), fm.getGender(), rel.getRelationType())
+                            : familyRelationshipService.computeRelationshipLabel(rel.getGenerationValue(), fm.getGender());
+                vo.setRelativeLabel(label);
+                vo.setRelationship(label);
+                vo.setTrustScore(rel.getTrustScore());
+                vo.setIntimacyScore(rel.getIntimacyScore());
+                vo.setCommunicationScore(rel.getCommunicationScore());
+            } else if (centerMemberId.equals(fm.getId())) {
+                vo.setRelationship("我");
+                vo.setRelativeLabel("我");
+            } else {
+                vo.setTrustScore(BigDecimal.ZERO);
+                vo.setIntimacyScore(BigDecimal.ZERO);
+                vo.setCommunicationScore(BigDecimal.ZERO);
+                // SC-P-07 边界「关系缺失的节点降级展示」:关系缺失成员仍须有可渲染的降级关系标签(非 null/非空白)
+                vo.setRelationship("家人");
+                vo.setRelativeLabel("家人");
+            }
+            result.add(vo);
+        }
+        return result;
+    }
+}

+ 424 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RelationshipQuestionnaireService.java

@@ -0,0 +1,424 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.GenerateQuestionnaireDTO;
+import com.etotem.cfc.dto.QuestionnaireSnapshotVO;
+import com.etotem.cfc.dto.SubmitQuestionnaireDTO;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.entity.FamilyRelationship;
+import com.etotem.cfc.entity.RelationshipQuestionnaireResponse;
+import com.etotem.cfc.entity.RelationshipQuestionnaireSnapshot;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.FamilyRelationshipMapper;
+import com.etotem.cfc.mapper.RelationshipQuestionnaireResponseMapper;
+import com.etotem.cfc.mapper.RelationshipQuestionnaireSnapshotMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class RelationshipQuestionnaireService {
+
+    private static final Logger log = LoggerFactory.getLogger(RelationshipQuestionnaireService.class);
+
+    @Resource
+    private RelationshipQuestionnaireSnapshotMapper snapshotMapper;
+
+    @Resource
+    private RelationshipQuestionnaireResponseMapper responseMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private FamilyRelationshipMapper familyRelationshipMapper;
+
+    @Resource
+    private AIService aiService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    /**
+     * AI 生成关系问卷
+     * 实际 AI 调用在 T15 实现,这里生成模拟问卷
+     */
+    public QuestionnaireSnapshotVO generateQuestionnaire(GenerateQuestionnaireDTO dto) {
+        if (dto.getMemberId() == null) {
+            throw new IllegalArgumentException("memberId不能为空");
+        }
+        if (dto.getRespondentId() == null) {
+            throw new IllegalArgumentException("respondentId不能为空");
+        }
+
+        FamilyMember member = familyMemberMapper.selectById(dto.getMemberId());
+        if (member == null) {
+            throw new RuntimeException("成员不存在");
+        }
+
+        // 生成版本号
+        String version = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
+
+        // 构建答卷人画像信息
+        User respondentUser = userMapper.selectById(dto.getRespondentId());
+        java.util.Map<String, Object> respondentProfile = new java.util.HashMap<>();
+        if (respondentUser != null) {
+            respondentProfile.put("nickname", respondentUser.getNickname() != null ? respondentUser.getNickname() : "");
+            respondentProfile.put("gender", respondentUser.getGender() != null ? respondentUser.getGender() : "");
+            if (respondentUser.getBirthday() != null) {
+                java.time.LocalDate birth = respondentUser.getBirthday().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
+                java.time.LocalDate now = java.time.LocalDate.now();
+                int respAge = java.time.Period.between(birth, now).getYears();
+                respondentProfile.put("age", Math.max(0, respAge));
+            }
+        }
+
+        // 构建被评成员画像信息
+        java.util.Map<String, Object> memberProfile = new java.util.HashMap<>();
+        if (member.getGender() != null) memberProfile.put("gender", member.getGender());
+        memberProfile.put("age", member.getAge());
+        if (member.getNickname() != null) memberProfile.put("nickname", member.getNickname());
+        if (member.getBirthHour() != null) memberProfile.put("birth_hour", member.getBirthHour());
+
+        // 构建家庭上下文
+        java.util.Map<String, Object> familyContext = new java.util.HashMap<>();
+        if (familyMapper != null && member.getFamilyId() != null) {
+            Family family = familyMapper.selectById(member.getFamilyId());
+            if (family != null) {
+                familyContext.put("family_name", family.getName() != null ? family.getName() : "");
+            }
+        }
+
+        // 优先 LangGraph 出题,失败 fallback mock
+        java.util.Map<String, Object> aiInputs = new java.util.HashMap<>();
+        aiInputs.put("member_name", member.getNickname());
+        aiInputs.put("respondent_name", respondentProfile.getOrDefault("nickname", "本人"));
+        aiInputs.put("relationship_type", member.getGeneration() != null && member.getGeneration() < 0 ? "child" : "parent");
+        aiInputs.put("member_profile", memberProfile);
+        aiInputs.put("respondent_profile", respondentProfile);
+        aiInputs.put("family_context", familyContext);
+        java.util.Map<String, Object> aiResult = aiGateway.generateQuestionnaire(aiInputs);
+
+        String aiJson;
+        if (aiResult != null && aiResult.get("questionnaire_json") != null) {
+            aiJson = (String) aiResult.get("questionnaire_json");
+        } else {
+            aiJson = generateMockQuestionnaireJson(member);
+            log.warn("LangGraph 不可用,fallback mock 问卷: memberId={}", dto.getMemberId());
+        }
+
+        // 保存快照
+        RelationshipQuestionnaireSnapshot snapshot = new RelationshipQuestionnaireSnapshot();
+        snapshot.setFamilyMemberId(dto.getMemberId());
+        snapshot.setRespondentId(dto.getRespondentId());
+        snapshot.setMemberName(member.getNickname());
+        snapshot.setRelationshipType(member.getGeneration() != null && member.getGeneration() < 0 ? "child" : "parent");
+        snapshot.setAiGeneratedJson(aiJson);
+        snapshot.setVersion(version);
+        snapshot.setCreatedAt(new Date());
+        snapshotMapper.insert(snapshot);
+
+        QuestionnaireSnapshotVO vo = new QuestionnaireSnapshotVO();
+        vo.setId(snapshot.getId());
+        vo.setFamilyMemberId(snapshot.getFamilyMemberId());
+        vo.setMemberName(snapshot.getMemberName());
+        vo.setRelationshipType(snapshot.getRelationshipType());
+        vo.setAiGeneratedJson(snapshot.getAiGeneratedJson());
+        vo.setVersion(snapshot.getVersion());
+        vo.setCreatedAt(snapshot.getCreatedAt());
+        return vo;
+    }
+
+    /**
+     * 提交问卷答案并计算评分
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public RelationshipQuestionnaireResponse submitQuestionnaire(SubmitQuestionnaireDTO dto) {
+        if (dto.getSnapshotId() == null) {
+            throw new IllegalArgumentException("snapshotId不能为空");
+        }
+        if (dto.getAnswersJson() == null || dto.getAnswersJson().isEmpty()) {
+            throw new IllegalArgumentException("answersJson不能为空");
+        }
+
+        RelationshipQuestionnaireSnapshot snapshot = snapshotMapper.selectById(dto.getSnapshotId());
+        if (snapshot == null) {
+            throw new RuntimeException("问卷快照不存在");
+        }
+
+        // 解析答案并计算评分(简化版,实际在 T16 实现复杂计算)
+        BigDecimal[] scores = calculateScoresFromAnswers(dto.getAnswersJson(), snapshot.getAiGeneratedJson());
+
+        // 保存回答结果
+        RelationshipQuestionnaireResponse response = new RelationshipQuestionnaireResponse();
+        response.setSnapshotId(dto.getSnapshotId());
+        response.setRespondentId(dto.getRespondentId());
+        response.setAnswersJson(dto.getAnswersJson());
+        response.setTrustScore(scores[0]);
+        response.setIntimacyScore(scores[1]);
+        response.setCommunicationScore(scores[2]);
+        response.setInteractionBonus(BigDecimal.ZERO);
+        response.setTotalScore(scores[0].add(scores[1]).add(scores[2]).divide(new BigDecimal("3"), 2, java.math.RoundingMode.HALF_UP));
+        response.setCalculatedAt(new Date());
+        responseMapper.insert(response);
+
+        // 更新成员的评分
+        updateMemberScores(snapshot.getFamilyMemberId(), scores);
+
+        // 同步写入 pairwise 关系评分(答卷人视角 → 被评成员)
+        syncPairwiseScores(dto.getRespondentId(), snapshot.getFamilyMemberId(), scores);
+
+        return response;
+    }
+
+    public RelationshipQuestionnaireSnapshot getSnapshotById(Long snapshotId) {
+        if (snapshotId == null) return null;
+        return snapshotMapper.selectById(snapshotId);
+    }
+
+    /**
+     * 获取最新的问卷快照
+     */
+    public QuestionnaireSnapshotVO getSnapshot(Long memberId) {
+        if (memberId == null) {
+            throw new IllegalArgumentException("memberId不能为空");
+        }
+
+        LambdaQueryWrapper<RelationshipQuestionnaireSnapshot> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(RelationshipQuestionnaireSnapshot::getFamilyMemberId, memberId)
+                .orderByDesc(RelationshipQuestionnaireSnapshot::getCreatedAt)
+                .last("LIMIT 1");
+
+        SortUtil.applySort(wrapper);
+        RelationshipQuestionnaireSnapshot snapshot = snapshotMapper.selectOne(wrapper);
+        if (snapshot == null) {
+            return null;
+        }
+
+        QuestionnaireSnapshotVO vo = new QuestionnaireSnapshotVO();
+        vo.setId(snapshot.getId());
+        vo.setFamilyMemberId(snapshot.getFamilyMemberId());
+        vo.setMemberName(snapshot.getMemberName());
+        vo.setRelationshipType(snapshot.getRelationshipType());
+        vo.setAiGeneratedJson(snapshot.getAiGeneratedJson());
+        vo.setVersion(snapshot.getVersion());
+        vo.setCreatedAt(snapshot.getCreatedAt());
+        return vo;
+    }
+
+    /**
+     * 获取历史问卷回答记录
+     */
+    public List<RelationshipQuestionnaireResponse> getHistory(Long memberId) {
+        if (memberId == null) {
+            throw new IllegalArgumentException("memberId不能为空");
+        }
+
+        // 先找到该成员的所有快照
+        LambdaQueryWrapper<RelationshipQuestionnaireSnapshot> snapWrapper = new LambdaQueryWrapper<>();
+        snapWrapper.eq(RelationshipQuestionnaireSnapshot::getFamilyMemberId, memberId);
+        SortUtil.applySort(snapWrapper);
+        List<RelationshipQuestionnaireSnapshot> snapshots = snapshotMapper.selectList(snapWrapper);
+
+        if (snapshots.isEmpty()) {
+            return new ArrayList<>();
+        }
+
+        List<Long> snapshotIds = new ArrayList<>();
+        for (RelationshipQuestionnaireSnapshot s : snapshots) {
+            snapshotIds.add(s.getId());
+        }
+
+        // 查询所有相关回答
+        LambdaQueryWrapper<RelationshipQuestionnaireResponse> respWrapper = new LambdaQueryWrapper<>();
+        respWrapper.in(RelationshipQuestionnaireResponse::getSnapshotId, snapshotIds)
+                .orderByDesc(RelationshipQuestionnaireResponse::getCalculatedAt);
+
+        SortUtil.applySort(respWrapper);
+        return responseMapper.selectList(respWrapper);
+    }
+
+    private String generateMockQuestionnaireJson(FamilyMember member) {
+        String n = member.getNickname();
+        // 间接情境题,避免直接问"信任程度/亲密程度/沟通质量",以行为场景反映真实关系
+        StringBuilder sb = new StringBuilder();
+        sb.append("[");
+        sb.append("{\"id\":1,\"dimension\":\"trust\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"当你遇到困难或犯了错时,你是否愿意向").append(n).append("求助?\",\"options\":[\"毫不犹豫\",\"有些犹豫但会开口\",\"想开口但最终没开口\",\"几乎不会\"]},");
+        sb.append("{\"id\":2,\"dimension\":\"trust\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"你是否会主动向").append(n).append("分享你不太愿意让其他人知道的私人事情?\",\"options\":[\"经常会\",\"有时会\",\"很少\",\"从不\"]},");
+        sb.append("{\"id\":3,\"dimension\":\"trust\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"和").append(n).append("相处时,你是否经常担心自己会说错话或做错事?\",\"options\":[\"从不担心\",\"偶尔担心\",\"经常担心\",\"随时都很紧张\"]},");
+        sb.append("{\"id\":4,\"dimension\":\"intimacy\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"当你心情不好时,你是否想去找").append(n).append("待一会儿?\",\"options\":[\"很想\",\"有时候会\",\"很少\",\"完全没有\"]},");
+        sb.append("{\"id\":5,\"dimension\":\"intimacy\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"你是否愿意和").append(n).append("一起做一些不需要说话、只是安静待在一起的事?\",\"options\":[\"觉得很自然\",\"偶尔会\",\"不太习惯\",\"完全不想\"]},");
+        sb.append("{\"id\":6,\"dimension\":\"intimacy\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"你是否觉得").append(n).append("是你心里最懂你的人之一?\",\"options\":[\"是的\",\"算是\",\"不太确定\",\"不是\"]},");
+        sb.append("{\"id\":7,\"dimension\":\"communication\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"和").append(n).append("意见不同时,你们通常能平静地把话说清楚吗?\",\"options\":[\"总能\",\"大部分时候可以\",\"经常吵起来\",\"最后都不说话\"]},");
+        sb.append("{\"id\":8,\"dimension\":\"communication\",\"direction\":\"positive\",\"weight\":1.0,\"question\":\"你是否觉得和").append(n).append("说话时,对方真的在听,而不是急着反驳或给建议?\",\"options\":[\"总是\",\"经常\",\"偶尔\",\"几乎没有\"]},");
+        sb.append("{\"id\":9,\"dimension\":\"communication\",\"direction\":\"negative\",\"weight\":1.0,\"question\":\"你是否经常觉得").append(n).append("打断你说话,或者没听完就下结论?\",\"options\":[\"从不\",\"很少\",\"有时会\",\"经常\"]}");
+        sb.append("]");
+        return sb.toString();
+    }
+
+    private BigDecimal[] calculateScoresFromAnswers(String answersJson, String questionsJson) {
+        if (answersJson == null || answersJson.isEmpty() || questionsJson == null || questionsJson.isEmpty()) {
+            return new BigDecimal[]{
+                    new BigDecimal("-1.00"), new BigDecimal("-1.00"), new BigDecimal("-1.00")};
+        }
+        try {
+            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
+            com.fasterxml.jackson.databind.JsonNode questionsRoot = mapper.readTree(questionsJson);
+            com.fasterxml.jackson.databind.JsonNode questionsNode = questionsRoot.get("questions");
+            if (questionsNode == null || !questionsNode.isArray()) {
+                return new BigDecimal[]{
+                        new BigDecimal("-1.00"), new BigDecimal("-1.00"), new BigDecimal("-1.00")};
+            }
+
+            com.fasterxml.jackson.databind.JsonNode answersNode = mapper.readTree(answersJson);
+
+            java.util.Map<String, double[]> dimSums = new java.util.HashMap<>();
+            for (com.fasterxml.jackson.databind.JsonNode q : questionsNode) {
+                String qId = q.get("id").asText();
+                String dim = q.get("dimension").asText();
+                String direction = q.has("direction") ? q.get("direction").asText("positive") : "positive";
+                double weight = q.has("weight") ? q.get("weight").asDouble(1.0) : 1.0;
+
+                if (!answersNode.has(qId)) continue;
+
+                double rawScore;
+                if (q.has("options")) {
+                    String answerOptionId = answersNode.get(qId).has("id")
+                            ? answersNode.get(qId).get("id").asText() : null;
+                    double maxScore = 0;
+                    rawScore = 0;
+                    boolean found = false;
+                    for (com.fasterxml.jackson.databind.JsonNode opt : q.get("options")) {
+                        double s = opt.get("score").asDouble(0);
+                        if (s > maxScore) maxScore = s;
+                        if (answerOptionId != null && answerOptionId.equals(opt.get("id").asText())) {
+                            rawScore = s;
+                            found = true;
+                        }
+                    }
+                    if (!found) continue;
+                    rawScore = (maxScore > 0) ? (rawScore / maxScore * 100.0) : 0;
+                } else if (q.has("scale")) {
+                    double scaleMin = q.get("scale").get("min").asDouble(0);
+                    double scaleMax = q.get("scale").get("max").asDouble(4);
+                    double scoreVal = answersNode.get(qId).has("scoreValue")
+                            ? answersNode.get(qId).get("scoreValue").asDouble(0) : 0;
+                    rawScore = (scaleMax > scaleMin) ? ((scoreVal - scaleMin) / (scaleMax - scaleMin) * 100.0) : 0;
+                } else {
+                    continue;
+                }
+
+                if ("negative".equals(direction)) {
+                    rawScore = 100.0 - rawScore;
+                }
+
+                dimSums.computeIfAbsent(dim, k -> new double[]{0, 0});
+                double[] arr = dimSums.get(dim);
+                arr[0] += rawScore * weight;
+                arr[1] += weight;
+            }
+
+            BigDecimal trust = computeDimScore(dimSums.get("trust"));
+            BigDecimal intimacy = computeDimScore(dimSums.get("intimacy"));
+            BigDecimal communication = computeDimScore(dimSums.get("communication"));
+            return new BigDecimal[]{trust, intimacy, communication};
+        } catch (Exception e) {
+            log.warn("calculateScoresFromAnswers 异常: {}", e.getMessage());
+            return new BigDecimal[]{
+                    new BigDecimal("-1.00"), new BigDecimal("-1.00"), new BigDecimal("-1.00")};
+        }
+    }
+
+    private BigDecimal computeDimScore(double[] arr) {
+        if (arr == null || arr[1] == 0) return new BigDecimal("0.00");
+        double score = arr[0] / arr[1];
+        score = Math.min(100.0, Math.max(0.0, score));
+        return new BigDecimal(String.format("%.2f", score));
+    }
+
+    private void updateMemberScores(Long memberId, BigDecimal[] scores) {
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        if (member != null) {
+            member.setTrustScore(scores[0]);
+            member.setIntimacyScore(scores[1]);
+            member.setCommunicationScore(scores[2]);
+            member.setLastInteractionAt(new Date());
+            familyMemberMapper.updateById(member);
+        }
+    }
+
+    /**
+     * 将问卷评分写入 family_relationships 表(答卷人视角)
+     * 答卷人无 family_member 记录或关系行不存在时,静默跳过(不阻塞问卷保存)
+     */
+    private void syncPairwiseScores(Long respondentUserId, Long targetMemberId, BigDecimal[] scores) {
+        try {
+            if (respondentUserId == null || targetMemberId == null || scores == null) {
+                return;
+            }
+            // 找到答卷人对应的 family_member 记录
+            LambdaQueryWrapper<FamilyMember> respWrapper = new LambdaQueryWrapper<>();
+            respWrapper.eq(FamilyMember::getUserId, respondentUserId);
+            SortUtil.applySort(respWrapper);
+            FamilyMember respondent = familyMemberMapper.selectOne(respWrapper);
+            if (respondent == null) {
+                log.warn("答卷人用户{}无family_member记录,跳过pairwise评分同步", respondentUserId);
+                return;
+            }
+            // 查 from→to 关系行(有则更新,无则插入)
+            LambdaQueryWrapper<FamilyRelationship> relWrapper = new LambdaQueryWrapper<>();
+            relWrapper.eq(FamilyRelationship::getFromMemberId, respondent.getId())
+                    .eq(FamilyRelationship::getToMemberId, targetMemberId);
+            SortUtil.applySort(relWrapper);
+            FamilyRelationship rel = familyRelationshipMapper.selectOne(relWrapper);
+            Date now = new Date();
+            if (rel != null) {
+                rel.setTrustScore(scores[0]);
+                rel.setIntimacyScore(scores[1]);
+                rel.setCommunicationScore(scores[2]);
+                rel.setUpdatedAt(now);
+                familyRelationshipMapper.updateById(rel);
+            } else {
+                FamilyMember target = familyMemberMapper.selectById(targetMemberId);
+                if (target == null) {
+                    return;
+                }
+                FamilyRelationship newRel = new FamilyRelationship();
+                newRel.setFamilyId(target.getFamilyId());
+                newRel.setFromMemberId(respondent.getId());
+                newRel.setToMemberId(targetMemberId);
+                int respGen = respondent.getGeneration() != null ? respondent.getGeneration() : 0;
+                int targetGen = target.getGeneration() != null ? target.getGeneration() : 0;
+                newRel.setGenerationValue(respGen - targetGen);
+                newRel.setTrustScore(scores[0]);
+                newRel.setIntimacyScore(scores[1]);
+                newRel.setCommunicationScore(scores[2]);
+                newRel.setCreatedAt(now);
+                newRel.setUpdatedAt(now);
+                familyRelationshipMapper.insert(newRel);
+            }
+        } catch (Exception e) {
+            log.warn("pairwise评分同步失败: {}", e.getMessage());
+        }
+    }
+}

+ 269 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportAnalyzeQuotaService.java

@@ -0,0 +1,269 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.ReportAnalyzeQuotaDTO;
+import com.etotem.cfc.entity.MembershipLevel;
+import com.etotem.cfc.mapper.MembershipLevelMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+
+/**
+ * 报告快速分析配额服务(Redis 日计数)。
+ *
+ * <p>规格:{@code docs/superpowers/specs/2026-09-10-report-quick-analyze-design.md} §3.3、
+ * {@code 2026-09-13-report-quick-analyze-extend-design.md} §5。
+ *
+ * <p>口径:
+ * <ul>
+ *   <li>免费版(FREE,含 PROVIDER 归一化后的 FREE):每日 {@value #FREE_DAILY_LIMIT} 次,服务端硬编码,
+ *       不随 membership_levels 配置变化;</li>
+ *   <li>付费版:上限取 {@code membership_levels.max_daily_analyze};0 或 NULL = 不限次
+ *       (保留既有「付费版多轮对话不限制次数」口径);</li>
+ *   <li>日计数器 key:{@code report:analyze:{userId}:{yyyyMMdd}},INCR + 24h EXPIRE,按天自然滚动,
+ *       无定时任务;TTL 到期即等价于额度重置;</li>
+ *   <li>付费多轮:同一 {@code conversationId} 仅计 1 次({@code SADD} 原子判重 + 同日去重 set),
+ *       后续追问不重复扣次数;免费用户不做会话判重(后端已剥离 conversationId,天然单次);</li>
+ *   <li>Redis 异常 <strong>fail-open</strong> 放行(避免免费用户因 Redis 故障完全不可用),记 warn。</li>
+ * </ul>
+ *
+ * <p>范围说明:报告反馈(report_feedback)沿用其独立的 {@code report:feedback:free:} 计数器,
+ * 不由本服务管理(见 {@link ReportFeedbackService})。
+ */
+@Slf4j
+@Service
+public class ReportAnalyzeQuotaService {
+
+    /** 配额类型 */
+    public static final String QUOTA_TYPE = "REPORT_ANALYZE";
+
+    /** 免费版每日次数上限(硬编码,不读配置表) */
+    public static final int FREE_DAILY_LIMIT = 1;
+
+    /** 免费版等级编码(MembershipService 已将 PROVIDER 归一化为 FREE) */
+    private static final String LEVEL_FREE = "FREE";
+    private static final String LEVEL_PROVIDER = "PROVIDER";
+
+    /** 日计数器 key 前缀:report:analyze:{userId}:{yyyyMMdd} */
+    private static final String COUNTER_KEY_PREFIX = "report:analyze:";
+
+    /** 会话去重 set key 前缀:report:analyze:session:{yyyyMMdd}:{conversationId} */
+    private static final String SESSION_KEY_PREFIX = "report:analyze:session:";
+
+    private static final DateTimeFormatter PERIOD_FMT = DateTimeFormatter.ofPattern("yyyyMMdd");
+
+    /** TTL:略大于 1 天,保证当日末尾读到的仍是当日计数 */
+    private static final Duration TTL = Duration.ofDays(1);
+
+    /** 升级引导路径(与前端 pages/membership 分包约定一致) */
+    public static final String UPGRADE_URL = "/pages/membership/upgrade";
+
+    /** 免费版超限文案:含「今日已用完」,与付费版文案可区分 */
+    public static final String MSG_FREE_EXHAUSTED =
+            "免费版今日已用完(" + FREE_DAILY_LIMIT + " 次/天),升级会员解锁更多";
+
+    /** 付费版超限文案:含「请升级会员」,与免费版文案可区分 */
+    public static final String MSG_PAID_EXHAUSTED =
+            "请升级会员以获取更多快速分析次数";
+
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
+
+    @Resource
+    private MembershipService membershipService;
+
+    @Resource
+    private MembershipLevelMapper membershipLevelMapper;
+
+    /**
+     * 查询当前用户的报告快速分析配额状态(只读,不扣减)。
+     * 用于前端在发起分析前展示剩余次数。
+     */
+    public ReportAnalyzeQuotaDTO getStatus(Long userId) {
+        ReportAnalyzeQuotaDTO dto = buildBase(userId);
+        if (!dto.isUnlimited()) {
+            dto.setUsed(readUsed(userId));
+        }
+        applyRemaining(dto);
+        return dto;
+    }
+
+    /**
+     * 尝试扣减一次配额。
+     *
+     * @param userId         当前登录用户 ID
+     * @param conversationId 会话 ID(付费版多轮去重用);为空时按单次计费
+     * @return 配额结果。{@code allowed=true} 表示放行;{@code allowed=false} 时
+     *         {@code message} 为超限文案(免费版 / 付费版文案不同),{@code actionUrl} 为升级路径
+     */
+    public ReportAnalyzeQuotaDTO consume(Long userId, String conversationId) {
+        ReportAnalyzeQuotaDTO dto = buildBase(userId);
+        boolean free = isFreeLevel(dto.getLevelCode());
+
+        if (dto.isUnlimited()) {
+            // 付费等级未配置上限:放行且不落计数器(避免 key 无限增长)
+            dto.setAllowed(true);
+            return dto;
+        }
+
+        String counterKey = counterKey(userId);
+        String sessionKey = free ? null : sessionKey(conversationId);
+
+        try {
+            // 付费多轮:同一会话内只计 1 次(SADD 返回 0 = 该会话已计过费)
+            if (sessionKey != null) {
+                Long added = redisTemplate.opsForSet().add(sessionKey, String.valueOf(userId));
+                if (added != null) {
+                    redisTemplate.expire(sessionKey, TTL);
+                }
+                if (added != null && added == 0L) {
+                    dto.setUsed(readUsed(userId));
+                    applyRemaining(dto);
+                    dto.setAllowed(true);
+                    return dto;
+                }
+            }
+
+            Long count = redisTemplate.opsForValue().increment(counterKey);
+            if (count != null && count == 1L) {
+                redisTemplate.expire(counterKey, TTL);
+            }
+            int used = (count != null) ? count.intValue() : readUsed(userId);
+            dto.setUsed(used);
+
+            if (used > dto.getTotal()) {
+                // 本次未扣成功:回滚会话标记,使同一会话仍可再次作为新一轮计费
+                if (sessionKey != null) {
+                    redisTemplate.opsForSet().remove(sessionKey, String.valueOf(userId));
+                }
+                applyRemaining(dto);
+                dto.setAllowed(false);
+                dto.setMessage(free ? MSG_FREE_EXHAUSTED : MSG_PAID_EXHAUSTED);
+                dto.setActionUrl(UPGRADE_URL);
+                log.info("报告快速分析配额超限: userId={}, level={}, used={}, total={}, free={}",
+                        userId, dto.getLevelCode(), used, dto.getTotal(), free);
+                return dto;
+            }
+
+            applyRemaining(dto);
+            dto.setAllowed(true);
+            return dto;
+        } catch (Exception e) {
+            // fail-open:Redis 异常时放行,避免免费用户因 Redis 故障完全不可用
+            log.warn("报告快速分析配额计数失败,放行: userId={}, err={}", userId, e.getMessage());
+            dto.setUsed(readUsed(userId));
+            applyRemaining(dto);
+            dto.setAllowed(true);
+            return dto;
+        }
+    }
+
+    /**
+     * 是否为免费版(含 PROVIDER 归一化结果)。免费版锁死多轮,后端需剥离 conversationId。
+     */
+    public boolean isFreeLevel(String levelCode) {
+        return LEVEL_FREE.equals(levelCode) || LEVEL_PROVIDER.equals(levelCode);
+    }
+
+    // ==================== 内部方法 ====================
+
+    /**
+     * 构建配额 DTO 基础信息(等级 + 每日上限 + 周期键)。
+     */
+    private ReportAnalyzeQuotaDTO buildBase(Long userId) {
+        ReportAnalyzeQuotaDTO dto = new ReportAnalyzeQuotaDTO();
+        dto.setQuotaType(QUOTA_TYPE);
+        dto.setPeriodKey(LocalDate.now().format(PERIOD_FMT));
+        String level = resolveLevel(userId);
+        dto.setLevelCode(level);
+        int limit = isFreeLevel(level) ? FREE_DAILY_LIMIT : resolveConfigLimit(level);
+        dto.setTotal(limit);
+        dto.setUnlimited(limit <= 0);
+        if (limit <= 0) {
+            dto.setRemaining(-1);
+            dto.setExhausted(false);
+        }
+        return dto;
+    }
+
+    /**
+     * 取用户当前有效会员等级;异常/空用户按免费版处理(最保守)。
+     */
+    private String resolveLevel(Long userId) {
+        if (userId == null) {
+            return LEVEL_FREE;
+        }
+        try {
+            String level = membershipService.getMemberLevel(userId);
+            return (level == null || level.isEmpty()) ? LEVEL_FREE : level;
+        } catch (Exception e) {
+            log.warn("获取会员等级失败,按免费版处理: userId={}, err={}", userId, e.getMessage());
+            return LEVEL_FREE;
+        }
+    }
+
+    /**
+     * 读取会员等级配置的每日上限;0 或 NULL 表示不限次;读取失败按不限次兜底。
+     */
+    private int resolveConfigLimit(String levelCode) {
+        try {
+            MembershipLevel lv = membershipLevelMapper.selectOne(
+                    new LambdaQueryWrapper<MembershipLevel>()
+                            .eq(MembershipLevel::getLevelCode, levelCode)
+                            .last("LIMIT 1"));
+            if (lv == null || lv.getMaxDailyAnalyze() == null) {
+                return 0;
+            }
+            return lv.getMaxDailyAnalyze();
+        } catch (Exception e) {
+            log.warn("读取 max_daily_analyze 失败,按不限次处理: level={}, err={}",
+                    levelCode, e.getMessage());
+            return 0;
+        }
+    }
+
+    /**
+     * 读取今日已用次数;Redis 异常时按 0 处理。
+     */
+    private int readUsed(Long userId) {
+        try {
+            Object v = redisTemplate.opsForValue().get(counterKey(userId));
+            if (v == null) {
+                return 0;
+            }
+            return Integer.parseInt(String.valueOf(v));
+        } catch (Exception e) {
+            return 0;
+        }
+    }
+
+    private void applyRemaining(ReportAnalyzeQuotaDTO dto) {
+        if (dto.isUnlimited()) {
+            dto.setRemaining(-1);
+            dto.setExhausted(false);
+            return;
+        }
+        int remaining = Math.max(0, dto.getTotal() - dto.getUsed());
+        dto.setRemaining(remaining);
+        dto.setExhausted(remaining <= 0);
+        if (dto.isExhausted()) {
+            dto.setActionUrl(UPGRADE_URL);
+        }
+    }
+
+    private String counterKey(Long userId) {
+        return COUNTER_KEY_PREFIX + userId + ":" + LocalDate.now().format(PERIOD_FMT);
+    }
+
+    private String sessionKey(String conversationId) {
+        if (conversationId == null || conversationId.trim().isEmpty()) {
+            return null;
+        }
+        return SESSION_KEY_PREFIX + LocalDate.now().format(PERIOD_FMT) + ":" + conversationId.trim();
+    }
+}

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

@@ -0,0 +1,199 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.HealthIndicator;
+import com.etotem.cfc.entity.HealthReport;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * 报告档案对比服务(能力键 {@code report.archive.manage},SC-P-24 / TC-P-24「对比展示差异」)。
+ *
+ * <p>契约宿主:{@code §4.59.10} 未实现端点 {@code POST /api/health/report/compare} 的服务层载体。
+ * 口径:报告类型一致才可比对(SC-P-25 同类型口径 / TC-P-21),返回报告A/B基础信息、
+ * 指标级差异标注(same / different / onlyInA / onlyInB)与总分差异。</p>
+ */
+@Slf4j
+@Service
+public class ReportArchiveCompareService {
+
+    @Resource
+    private HealthReportService healthReportService;
+
+    /**
+     * 报告对比入口。
+     *
+     * @param reportAId 报告 A 的 ID
+     * @param reportBId 报告 B 的 ID
+     * @return 比较结果 Map,含 comparable(是否可比对)、message、reportA/reportB 摘要、
+     *         differences(指标级差异标注)、scoreComparison(总分差异)
+     */
+    public Map<String, Object> compareReports(Long reportAId, Long reportBId) {
+        Map<String, Object> result = new LinkedHashMap<>();
+
+        if (reportAId == null || reportBId == null) {
+            result.put("comparable", false);
+            result.put("message", "reportAId 与 reportBId 不能为空");
+            return result;
+        }
+
+        HealthReport reportA = healthReportService.getReportById(reportAId);
+        HealthReport reportB = healthReportService.getReportById(reportBId);
+
+        if (reportA == null || reportB == null) {
+            result.put("comparable", false);
+            result.put("message", "报告不存在");
+            return result;
+        }
+
+        // 类型一致性检查:仅同类型报告可比对(SC-P-25 / TC-P-21)
+        if (!Objects.equals(reportA.getReportType(), reportB.getReportType())) {
+            result.put("comparable", false);
+            result.put("message", "报告类型不一致,无法对比");
+            result.put("reportAType", reportA.getReportType());
+            result.put("reportBType", reportB.getReportType());
+            return result;
+        }
+
+        result.put("comparable", true);
+        result.put("message", "报告类型一致,可进行差异对比");
+        result.put("reportAId", reportAId);
+        result.put("reportBId", reportBId);
+        result.put("reportA", buildReportSummary(reportA));
+        result.put("reportB", buildReportSummary(reportB));
+
+        // 指标级差异标注
+        result.put("differences", compareIndicators(reportA, reportB));
+
+        // 总分差异
+        result.put("scoreComparison", buildScoreComparison(reportA, reportB));
+
+        return result;
+    }
+
+    private Map<String, Object> buildReportSummary(HealthReport report) {
+        Map<String, Object> summary = new LinkedHashMap<>();
+        summary.put("id", report.getId());
+        summary.put("reportType", report.getReportType());
+        summary.put("reportDate", report.getReportDate() != null
+                ? new java.text.SimpleDateFormat("yyyy-MM-dd").format(report.getReportDate()) : null);
+        summary.put("overallScore", report.getOverallScore());
+        summary.put("gutHealthScore", report.getGutHealthScore());
+        summary.put("nutritionScore", report.getNutritionScore());
+        summary.put("fileUrl", report.getFileUrl());
+        summary.put("status", report.getStatus());
+        return summary;
+    }
+
+    private Map<String, Object> buildScoreComparison(HealthReport reportA, HealthReport reportB) {
+        Map<String, Object> scoreDiff = new LinkedHashMap<>();
+        Integer scoreA = reportA.getOverallScore();
+        Integer scoreB = reportB.getOverallScore();
+        scoreDiff.put("scoreA", scoreA);
+        scoreDiff.put("scoreB", scoreB);
+        if (scoreA != null && scoreB != null) {
+            scoreDiff.put("difference", scoreB - scoreA);
+            scoreDiff.put("percentageDiff", scoreA != 0 ? Double.valueOf((scoreB - scoreA) * 100.0 / scoreA) : null);
+        } else {
+            scoreDiff.put("difference", null);
+            scoreDiff.put("percentageDiff", null);
+        }
+        return scoreDiff;
+    }
+
+    /**
+     * 比较两份报告的指标明细,返回差异标注数组(SC-P-24「差异清晰标注」)。
+     *
+     * @param reportA 报告 A
+     * @param reportB 报告 B
+     * @return 差异标注数组,每项含 indicatorName、diffStatus(same/different/onlyInA/onlyInB)等
+     */
+    private List<Map<String, Object>> compareIndicators(HealthReport reportA, HealthReport reportB) {
+        List<Map<String, Object>> diffs = new ArrayList<>();
+
+        List<HealthIndicator> indicatorsA = healthReportService.getReportIndicators(reportA.getId());
+        List<HealthIndicator> indicatorsB = healthReportService.getReportIndicators(reportB.getId());
+
+        // 按指标名建映射,便于差异检测
+        Map<String, HealthIndicator> mapA = indexByName(indicatorsA);
+        Map<String, HealthIndicator> mapB = indexByName(indicatorsB);
+
+        Set<String> allNames = new LinkedHashSet<>();
+        allNames.addAll(mapA.keySet());
+        allNames.addAll(mapB.keySet());
+
+        for (String name : allNames) {
+            HealthIndicator aInd = mapA.get(name);
+            HealthIndicator bInd = mapB.get(name);
+
+            Map<String, Object> diff = new LinkedHashMap<>();
+            diff.put("indicatorName", name);
+
+            if (aInd != null && bInd != null) {
+                // 双方都有:比较 value/status/refRange
+                diff.put("inBoth", true);
+                diff.put("statusA", aInd.getStatus());
+                diff.put("statusB", bInd.getStatus());
+                diff.put("valueA", aInd.getIndicatorValue());
+                diff.put("valueB", bInd.getIndicatorValue());
+                diff.put("refRangeA", aInd.getRefRange());
+                diff.put("refRangeB", bInd.getRefRange());
+
+                boolean sameValue = Objects.equals(aInd.getIndicatorValue(), bInd.getIndicatorValue());
+                boolean sameStatus = Objects.equals(aInd.getStatus(), bInd.getStatus());
+                boolean sameRefRange = Objects.equals(aInd.getRefRange(), bInd.getRefRange());
+
+                if (sameValue && sameStatus && sameRefRange) {
+                    diff.put("diffStatus", "same");
+                } else {
+                    diff.put("diffStatus", "different");
+                    Map<String, Object> fieldDiffs = new LinkedHashMap<>();
+                    if (!sameValue) fieldDiffs.put("valueDifferent", true);
+                    if (!sameStatus) fieldDiffs.put("statusDifferent", true);
+                    if (!sameRefRange) fieldDiffs.put("refRangeDifferent", true);
+                    diff.put("fieldDiffs", fieldDiffs);
+                }
+            } else if (aInd != null) {
+                // 仅 A 有
+                diff.put("inBoth", false);
+                diff.put("diffStatus", "onlyInA");
+                diff.put("valueA", aInd.getIndicatorValue());
+                diff.put("statusA", aInd.getStatus());
+                diff.put("refRangeA", aInd.getRefRange());
+            } else if (bInd != null) {
+                // 仅 B 有
+                diff.put("inBoth", false);
+                diff.put("diffStatus", "onlyInB");
+                diff.put("valueB", bInd.getIndicatorValue());
+                diff.put("statusB", bInd.getStatus());
+                diff.put("refRangeB", bInd.getRefRange());
+            } else {
+                diff.put("diffStatus", "none");
+            }
+            diffs.add(diff);
+        }
+
+        return diffs;
+    }
+
+    private Map<String, HealthIndicator> indexByName(List<HealthIndicator> indicators) {
+        Map<String, HealthIndicator> map = new LinkedHashMap<>();
+        if (indicators == null) {
+            return map;
+        }
+        for (HealthIndicator ind : indicators) {
+            if (ind.getIndicatorName() != null) {
+                map.put(ind.getIndicatorName(), ind);
+            }
+        }
+        return map;
+    }
+}

+ 814 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportBlockAssembler.java

@@ -0,0 +1,814 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.ParsedReportPayload;
+import com.etotem.cfc.entity.ReportTemplate;
+import com.etotem.cfc.service.ReportTemplateService;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+/**
+ * 报告通用展示块组装器 — 解析结果 → blocks JSON 结构
+ * 前端只消费 blocks,不接触实体字段名。
+ */
+@Service
+public class ReportBlockAssembler {
+
+    @Resource
+    private ReportTemplateService reportTemplateService;
+
+    private static final java.util.Set<String> IMPORTANT_LEVELS =
+            new java.util.HashSet<>(java.util.Arrays.asList("需注意", "注意", "高风险", "异常"));
+
+    /** 判断是否重要风险(需注意/注意/高风险/异常 → 重要;低风险/其余 → 其它) */
+    public boolean isImportantRisk(String level) {
+        return level != null && IMPORTANT_LEVELS.contains(level);
+    }
+
+    // ==================== 模板驱动组装 ====================
+
+    /**
+     * 根据报告类型+模板配置组装 blocks。
+     * 若该 reportType 有启用模板,优先使用模板 fixedBlocks;
+     * freeDisplay 开启时,将未覆盖的指标追加到末尾。
+     * 无模板/模板未启用:默认调用 assembleGutFlora 做通用兜底(评分+风险+指标+菌种),
+     * 保证任何报告类型都不返回空列表,前端可依赖 blocks 展示而非旧字段回退。
+     */
+    public List<Map<String, Object>> assembleWithTemplate(String reportType, ParsedReportPayload.Payload payload) {
+        if (payload == null) return new ArrayList<>();
+
+        ReportTemplate template = reportTemplateService.getByReportType(reportType);
+        if (template == null || template.getIsActive() == null || template.getIsActive() != 1) {
+            // 无模板或已停用 → 通用默认组装(复用 gut_flora 逻辑,标题已通用)
+            return assembleGutFlora(payload);
+        }
+
+        return parseAndAssemble(template.getConfig(), reportType, payload);
+    }
+
+    private List<Map<String, Object>> parseAndAssemble(String configJson, String reportType, ParsedReportPayload.Payload payload) {
+        List<Map<String, Object>> blocks = new ArrayList<>();
+        ObjectMapper mapper = new ObjectMapper();
+        List<Map<String, Object>> fixedBlocks;
+        Map<String, Object> freeDisplay;
+
+        try {
+            JsonNode root = mapper.readTree(configJson);
+            fixedBlocks = toList(root.get("fixedBlocks"));
+            freeDisplay = toMap(root.get("freeDisplay"));
+        } catch (Exception e) {
+            // JSON 解析失败 → fallback
+            if ("gut_flora".equals(reportType)) return assembleGutFlora(payload);
+            return new ArrayList<>();
+        }
+
+        // 收集已使用的 indicator codes(按 category 或 name 匹配)
+        Set<String> usedCodes = new HashSet<>();
+        Set<String> usedCategories = new HashSet<>();
+
+        // 按 fixedBlocks 顺序组装
+        for (Map<String, Object> fb : fixedBlocks) {
+            String type = str(fb.get("type"));
+            if ("score".equals(type)) {
+                blocks.add(assembleScoreBlock(fb, payload));
+            } else if ("indicator".equals(type)) {
+                @SuppressWarnings("unchecked")
+                List<String> codes = (List<String>) fb.get("indicatorCodes");
+                if (codes != null) codes.forEach(usedCodes::add);
+                String groupLabel = str(fb.get("groupLabel"));
+                blocks.add(assembleIndicatorBlock(fb, payload, groupLabel, usedCodes));
+            } else if ("list".equals(type)) {
+                blocks.add(assembleListBlock(fb, payload));
+            } else if ("text".equals(type)) {
+                blocks.add(textBlock(str(fb.get("title")), str(fb.get("content"))));
+            }
+        }
+
+        // 自由显示:追加未覆盖的指标(按 category 去重)
+        boolean freeEnabled = freeDisplay != null && Boolean.TRUE.equals(freeDisplay.get("enabled"));
+        if (freeEnabled && payload.getIndicators() != null && !payload.getIndicators().isEmpty()) {
+            @SuppressWarnings("unchecked")
+            List<ParsedReportPayload.Indicator> allIndicators = payload.getIndicators();
+            List<Map<String, Object>> freeItems = new ArrayList<>();
+            Set<String> skippedCategories = new HashSet<>();
+            for (Map<String, Object> fb : fixedBlocks) {
+                if ("indicator".equals(fb.get("type"))) {
+                    @SuppressWarnings("unchecked")
+                    List<String> names = (List<String>) fb.get("indicatorNames");
+                    if (names != null) {
+                        for (ParsedReportPayload.Indicator ind : allIndicators) {
+                            if (names.contains(ind.getIndicatorName()) && ind.getCategory() != null) {
+                                skippedCategories.add(ind.getCategory());
+                            }
+                        }
+                    }
+                }
+            }
+            for (ParsedReportPayload.Indicator ind : allIndicators) {
+                if (skippedCategories.contains(ind.getCategory())) continue;
+                Map<String, Object> item = new LinkedHashMap<>();
+                item.put("name", ind.getIndicatorName());
+                item.put("value", ind.getIndicatorValue());
+                item.put("unit", ind.getUnit());
+                item.put("refRange", ind.getRefRange());
+                item.put("status", ind.getStatus());
+                freeItems.add(item);
+            }
+            if (!freeItems.isEmpty()) {
+                String groupName = str(freeDisplay.get("groupName"));
+                if (groupName == null || groupName.isEmpty()) groupName = "其他指标";
+                Map<String, Object> block = new LinkedHashMap<>();
+                block.put("type", "indicator");
+                block.put("title", groupName);
+                block.put("items", freeItems);
+                blocks.add(block);
+            }
+        }
+
+        return blocks;
+    }
+
+    private Map<String, Object> assembleScoreBlock(Map<String, Object> fb, ParsedReportPayload.Payload payload) {
+        List<Map<String, Object>> items = new ArrayList<>();
+        @SuppressWarnings("unchecked")
+        List<String> fields = (List<String>) fb.get("items");
+        if (fields == null) return textBlock(str(fb.get("title")), "");
+        ParsedReportPayload.Summary s = payload.getSummary();
+        if (s == null) s = new ParsedReportPayload.Summary();
+        for (String field : fields) {
+            Integer val = null;
+            switch (field) {
+                case "overallScore": val = s.getOverallScore(); break;
+                case "gutHealthScore": val = s.getGutHealthScore(); break;
+                case "chronicDiseaseScore": val = s.getChronicDiseaseScore(); break;
+                case "nutritionScore": val = s.getNutritionScore(); break;
+                default: continue;
+            }
+            if (val != null) items.add(scoreItem(field, String.valueOf(val)));
+        }
+        if (items.isEmpty()) return null;
+        Map<String, Object> block = new LinkedHashMap<>();
+        block.put("type", "score");
+        block.put("title", str(fb.get("title")));
+        block.put("items", items);
+        return block;
+    }
+
+    private Map<String, Object> assembleIndicatorBlock(Map<String, Object> fb, ParsedReportPayload.Payload payload,
+                                                         String groupLabel, Set<String> usedCodes) {
+        @SuppressWarnings("unchecked")
+        List<String> names = (List<String>) fb.get("indicatorNames");
+        List<Map<String, Object>> items = new ArrayList<>();
+        if (payload.getIndicators() == null) return null;
+        for (ParsedReportPayload.Indicator ind : payload.getIndicators()) {
+            if (names != null && names.contains(ind.getIndicatorName())) {
+                items.add(indicatorItem(ind));
+            }
+        }
+        if (items.isEmpty()) return null;
+        Map<String, Object> block = new LinkedHashMap<>();
+        block.put("type", "indicator");
+        block.put("title", groupLabel != null ? groupLabel : str(fb.get("title")));
+        block.put("items", items);
+        return block;
+    }
+
+    private Map<String, Object> assembleListBlock(Map<String, Object> fb, ParsedReportPayload.Payload payload) {
+        String listKey = str(fb.get("listKey"));
+        List<Map<String, Object>> items = new ArrayList<>();
+        Map<String, Object> block = new LinkedHashMap<>();
+        block.put("type", "list");
+        block.put("title", str(fb.get("title")));
+
+        if ("gutFlora".equals(listKey) || "flora".equals(listKey)) {
+            block.put("columns", Arrays.asList(col("name", "菌种"), col("value", "数值"), col("range", "正常范围"), col("status", "状态")));
+            if (payload.getGutFlora() != null) addFloraItems(items, payload.getGutFlora());
+            if (payload.getPathogenGenus() != null) addFloraItems(items, payload.getPathogenGenus());
+            if (payload.getPathogenDetection() != null) addFloraItems(items, payload.getPathogenDetection());
+        } else if ("probiotic".equals(listKey)) {
+            block.put("columns", Arrays.asList(col("name", "菌种"), col("value", "数值"), col("range", "正常范围"), col("status", "状态")));
+            if (payload.getProbioticSpecies() != null) {
+                for (ParsedReportPayload.Flora f : payload.getProbioticSpecies()) {
+                    Map<String, Object> m = new LinkedHashMap<>();
+                    m.put("name", f.getBacteriaName());
+                    m.put("value", f.getBacteriaValue());
+                    m.put("range", f.getNormalRange());
+                    m.put("status", f.getPopulationLevel() != null ? f.getPopulationLevel() : f.getLevel());
+                    items.add(m);
+                }
+            }
+        } else if ("taxonomy".equals(listKey)) {
+            // taxonomy sub-keys
+            block.put("columns", Arrays.asList(col("name", "名称"), col("value", "丰度")));
+            if (payload.getTaxonomyClass() != null) for (ParsedReportPayload.Flora f : payload.getTaxonomyClass()) items.add(taxItem(f));
+            if (payload.getTaxonomyOrder() != null) for (ParsedReportPayload.Flora f : payload.getTaxonomyOrder()) items.add(taxItem(f));
+            if (payload.getTaxonomyFamily() != null) for (ParsedReportPayload.Flora f : payload.getTaxonomyFamily()) items.add(taxItem(f));
+            if (payload.getTaxonomyGenus() != null) for (ParsedReportPayload.Flora f : payload.getTaxonomyGenus()) items.add(taxItem(f));
+            if (payload.getTaxonomySpecies() != null) for (ParsedReportPayload.Flora f : payload.getTaxonomySpecies()) items.add(taxItem(f));
+        } else if ("food".equals(listKey)) {
+            block.put("columns", Arrays.asList(col("name", "食材"), col("category", "类别"), col("score", "推荐指数")));
+            if (payload.getFoods() != null) {
+                for (ParsedReportPayload.FoodItem f : payload.getFoods()) {
+                    Map<String, Object> m = new LinkedHashMap<>();
+                    m.put("name", f.getName());
+                    m.put("category", f.getCategory());
+                    m.put("score", f.getScore());
+                    items.add(m);
+                }
+            }
+        }
+
+        if (items.isEmpty()) return null;
+        block.put("items", items);
+        return block;
+    }
+
+    private Map<String, Object> taxItem(ParsedReportPayload.Flora f) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("name", f.getBacteriaName());
+        m.put("value", f.getBacteriaValue());
+        return m;
+    }
+
+    /** 编辑链路:第一套键 Map → 标准 Payload(第二套键)
+     *  支持嵌套结构 {summary:{...}, diseaseRisks:[...]} 与旧版平铺结构 */
+    public ParsedReportPayload.Payload fromMap(Map<String, Object> map) {
+        ParsedReportPayload.Payload p = new ParsedReportPayload.Payload();
+        if (map == null || map.isEmpty()) return p;
+        @SuppressWarnings("unchecked")
+        Map<String, Object> summaryMap = (map.get("summary") instanceof Map)
+                ? (Map<String, Object>) map.get("summary") : null;
+        Map<String, Object> src = summaryMap != null ? summaryMap : map;
+        ParsedReportPayload.Summary s = new ParsedReportPayload.Summary();
+        s.setOverallScore(toInt(src.get("overallScore")));
+        s.setGutHealthScore(toInt(src.get("gutHealthScore")));
+        s.setChronicDiseaseScore(toInt(src.get("chronicDiseaseScore")));
+        s.setNutritionScore(toInt(src.get("nutritionScore")));
+        s.setBalanceScore(toInt(src.get("gutBalanceScore")));
+        s.setDiversityScore(toInt(src.get("gutDiversityScore")));
+        s.setBeneficialScore(toInt(src.get("beneficialBacteriaScore")));
+        s.setHarmfulScore(toInt(src.get("harmfulBacteriaScore")));
+        s.setCoreGenusScore(toInt(src.get("coreSpeciesScore")));
+        s.setGutAge(str(src.get("gutAge")));
+        s.setGutType(str(src.get("gutType")));
+        s.setShannonIndex(str(src.get("shannonIndex")));
+        p.setSummary(s);
+        // 编辑时携带 diseaseRisks(使风险编辑后重新组装能保留风险块)
+        Object risksRaw = map.get("diseaseRisks");
+        if (risksRaw instanceof List) {
+            List<Map<String, Object>> riskList = (List<Map<String, Object>>) risksRaw;
+            List<ParsedReportPayload.DiseaseRisk> risks = new ArrayList<>();
+            for (Map<String, Object> r : riskList) {
+                ParsedReportPayload.DiseaseRisk dr = new ParsedReportPayload.DiseaseRisk();
+                dr.setDiseaseName(str(r.get("diseaseName")));
+                dr.setRiskValue(str(r.get("riskValue")));
+                dr.setRiskLevel(str(r.get("riskLevel")));
+                risks.add(dr);
+            }
+            p.setDiseaseRisks(risks);
+        }
+        return p;
+    }
+
+    /** 肠道菌群报告 → blocks */
+    public List<Map<String, Object>> assembleGutFlora(ParsedReportPayload.Payload payload) {
+        List<Map<String, Object>> blocks = new ArrayList<>();
+        if (payload == null) return blocks;
+
+        // 1. score 块:3 主项 + 6 子项(null 跳过)
+        ParsedReportPayload.Summary s = payload.getSummary();
+        if (s != null) {
+            List<Map<String, Object>> items = new ArrayList<>();
+            addScore(items, "综合", s.getOverallScore());
+            addScore(items, "菌群健康", s.getGutHealthScore());
+            addScore(items, "慢病控制", s.getChronicDiseaseScore());
+            addSubScore(items, "综合", "营养均衡", s.getNutritionScore());
+            addSubScore(items, "菌群健康", "平衡", s.getBalanceScore());
+            addSubScore(items, "菌群健康", "多样性", s.getDiversityScore());
+            addSubScore(items, "菌群健康", "有益菌", s.getBeneficialScore());
+            addSubScore(items, "菌群健康", "有害菌", s.getHarmfulScore());
+            addSubScore(items, "菌群健康", "核心菌属", s.getCoreGenusScore());
+            if (!items.isEmpty()) {
+                Map<String, Object> block = new LinkedHashMap<>();
+                block.put("type", "score");
+                block.put("title", "健康评分");
+                block.put("items", items);
+                blocks.add(block);
+            }
+        }
+
+        // 2. risk_group 块:按风险等级分两组
+        List<ParsedReportPayload.DiseaseRisk> risks = payload.getDiseaseRisks();
+        if (risks != null && !risks.isEmpty()) {
+            List<Map<String, Object>> important = new ArrayList<>();
+            List<Map<String, Object>> normal = new ArrayList<>();
+            for (ParsedReportPayload.DiseaseRisk r : risks) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("name", r.getDiseaseName());
+                m.put("value", r.getRiskValue());
+                m.put("level", r.getRiskLevel());
+                if (isImportantRisk(r.getRiskLevel())) important.add(m);
+                else normal.add(m);
+            }
+            if (!important.isEmpty()) blocks.add(riskBlock("重要风险", important));
+            if (!normal.isEmpty()) blocks.add(riskBlock("其它风险", normal));
+        }
+
+        // 3. indicator 块:indicators 按 category 分组
+        List<ParsedReportPayload.Indicator> inds = payload.getIndicators();
+        if (inds != null && !inds.isEmpty()) {
+            Map<String, List<Map<String, Object>>> byCategory = new LinkedHashMap<>();
+            for (ParsedReportPayload.Indicator ind : inds) {
+                String cat = ind.getCategory() == null ? "其他指标" : ind.getCategory();
+                byCategory.computeIfAbsent(cat, k -> new ArrayList<>()).add(indicatorItem(ind));
+            }
+            for (Map.Entry<String, List<Map<String, Object>>> e : byCategory.entrySet()) {
+                Map<String, Object> block = new LinkedHashMap<>();
+                block.put("type", "indicator");
+                block.put("title", e.getKey());
+                block.put("items", e.getValue());
+                blocks.add(block);
+            }
+        }
+
+        // 4. list 块:菌种列表(gutFlora + 病原菌)与食物推荐
+        List<Map<String, Object>> floraItems = new ArrayList<>();
+        addFloraItems(floraItems, payload.getGutFlora());
+        addFloraItems(floraItems, payload.getPathogenGenus());
+        addFloraItems(floraItems, payload.getPathogenDetection());
+        if (!floraItems.isEmpty()) {
+            Map<String, Object> block = new LinkedHashMap<>();
+            block.put("type", "list");
+            block.put("title", "菌种详情");
+            block.put("columns", java.util.Arrays.asList(
+                    col("name", "菌种"), col("value", "数值"), col("range", "正常范围"), col("status", "状态")));
+            block.put("items", floraItems);
+            blocks.add(block);
+        }
+        List<ParsedReportPayload.FoodItem> foods = payload.getFoods();
+        if (foods != null && !foods.isEmpty()) {
+            List<Map<String, Object>> foodItems = new ArrayList<>();
+            for (ParsedReportPayload.FoodItem f : foods) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("name", f.getName());
+                m.put("category", f.getCategory());
+                m.put("score", f.getScore());
+                foodItems.add(m);
+            }
+            Map<String, Object> block = new LinkedHashMap<>();
+            block.put("type", "list");
+            block.put("title", "食物推荐");
+            block.put("columns", java.util.Arrays.asList(
+                    col("name", "食材"), col("category", "类别"), col("score", "推荐指数")));
+            block.put("items", foodItems);
+            blocks.add(block);
+        }
+        return blocks;
+    }
+
+    private Map<String, Object> riskBlock(String title, List<Map<String, Object>> items) {
+        Map<String, Object> block = new LinkedHashMap<>();
+        block.put("type", "risk_group");
+        block.put("title", title);
+        block.put("items", items);
+        return block;
+    }
+
+    private Map<String, Object> indicatorItem(ParsedReportPayload.Indicator ind) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("name", ind.getIndicatorName());
+        m.put("value", ind.getIndicatorValue());
+        m.put("unit", ind.getUnit());
+        m.put("refRange", ind.getRefRange());
+        m.put("status", ind.getStatus());
+        return m;
+    }
+
+    private void addFloraItems(List<Map<String, Object>> items, List<ParsedReportPayload.Flora> list) {
+        if (list == null) return;
+        for (ParsedReportPayload.Flora f : list) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("name", f.getBacteriaName());
+            m.put("value", f.getBacteriaValue());
+            m.put("range", f.getNormalRange());
+            m.put("status", f.getPopulationLevel() != null ? f.getPopulationLevel() : f.getLevel());
+            items.add(m);
+        }
+    }
+
+    private void addScore(List<Map<String, Object>> items, String label, Integer value) {
+        if (value == null) return;
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("label", label);
+        m.put("value", value);
+        m.put("max", 100);
+        items.add(m);
+    }
+
+    private void addSubScore(List<Map<String, Object>> items, String parentLabel, String label, Integer value) {
+        if (value == null) return;
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("parentLabel", parentLabel);
+        m.put("label", label);
+        m.put("value", value);
+        m.put("max", 100);
+        items.add(m);
+    }
+
+    private Map<String, Object> col(String key, String label) {
+        Map<String, Object> c = new LinkedHashMap<>();
+        c.put("key", key);
+        c.put("label", label);
+        return c;
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) return null;
+        try { return Integer.valueOf(v.toString()); } catch (Exception e) { return null; }
+    }
+
+    /** DAN 报告 → blocks(itemsJson 为 DanParsedReport.items 的 JSON 序列化) */
+    public List<Map<String, Object>> assembleDanFromJson(String itemsJson, String summary, String suggestions) {
+        List<Map<String, Object>> blocks = new ArrayList<>();
+        List<DanReportParseService.DataItem> items = new ArrayList<>();
+        if (itemsJson != null && !itemsJson.isEmpty()) {
+            try {
+                items = new com.fasterxml.jackson.databind.ObjectMapper().readValue(
+                        itemsJson,
+                        new com.fasterxml.jackson.core.type.TypeReference<List<DanReportParseService.DataItem>>() {});
+            } catch (Exception e) {
+                // 解析失败按空处理
+            }
+        }
+        // score 块:total_score / percentile
+        List<Map<String, Object>> scoreItems = new ArrayList<>();
+        List<Map<String, Object>> listItems = new ArrayList<>();
+        for (DanReportParseService.DataItem item : items) {
+            if (item.getValue() == null || item.getValue().isEmpty()) continue;
+            if ("total_score".equals(item.getCode())) {
+                scoreItems.add(scoreItem("总得分", item.getValue()));
+            } else if ("percentile".equals(item.getCode())) {
+                scoreItems.add(scoreItem("百分位", item.getValue()));
+            } else {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("name", item.getName());
+                m.put("value", item.getValue());
+                listItems.add(m);
+            }
+        }
+        if (!scoreItems.isEmpty()) {
+            Map<String, Object> block = new LinkedHashMap<>();
+            block.put("type", "score");
+            block.put("title", "测评结果");
+            block.put("items", scoreItems);
+            blocks.add(block);
+        }
+        if (!listItems.isEmpty()) {
+            Map<String, Object> block = new LinkedHashMap<>();
+            block.put("type", "list");
+            block.put("title", "维度得分");
+            block.put("columns", java.util.Arrays.asList(col("name", "项目"), col("value", "得分")));
+            block.put("items", listItems);
+            blocks.add(block);
+        }
+        // text 块:summary / suggestions
+        if (summary != null && !summary.isEmpty()) blocks.add(textBlock("报告评语", summary));
+        if (suggestions != null && !suggestions.isEmpty()) blocks.add(textBlock("成长建议", suggestions));
+        return blocks;
+    }
+
+    /** category → 中文组标题 映射(DAN 各报告类型的指标分组) */
+    private static final java.util.Map<String, String> DAN_CATEGORY_TITLES = buildDanCategoryTitles();
+
+    private static java.util.Map<String, String> buildDanCategoryTitles() {
+        java.util.Map<String, String> m = new LinkedHashMap<>();
+        m.put("bigFive", "大五人格");
+        m.put("social", "社会关系");
+        m.put("emotion", "情绪状态");
+        m.put("body", "体质健康");
+        m.put("ability", "综合能力");
+        m.put("selfConcept", "自我概念");
+        m.put("growthMindset", "成长型思维");
+        m.put("selfDriving", "自驱力");
+        m.put("cognitive", "认知能力");
+        m.put("executiveFunction", "执行功能");
+        m.put("learningMotivation", "学习动机");
+        m.put("learningStrategy", "学习策略");
+        m.put("behavior", "行为表现");
+        m.put("family", "家庭环境");
+        m.put("hollandInterest", "职业兴趣");
+        m.put("multipleIntelligence", "多元智能");
+        m.put("careerValue", "职业价值观");
+        m.put("emotionRegulation", "情绪调节");
+        m.put("academicStress", "学业压力");
+        m.put("interpersonal", "人际关系");
+        m.put("socialAbility", "社交能力");
+        m.put("sleep", "睡眠状况");
+        m.put("exercise", "运动状况");
+        m.put("internet", "网络使用");
+        m.put("compass", "人际指南针");
+        m.put("overall", "综合评估");
+        m.put("auto", "其他指标");
+        return m;
+    }
+
+    /**
+     * DAN 报告 → blocks(按 category 分组)。
+     * score 块(总分/百分位)+ indicator 块(每个 category 一组)+ text 块(评语/建议)。
+     * 不同报告类型(A1/A2/B2/B3/B4/B5/B6/C1)的 category 集合不同,天然分别展示。
+     */
+    public List<Map<String, Object>> assembleDanByType(String itemsJson, String summary, String suggestions) {
+        List<Map<String, Object>> blocks = new ArrayList<>();
+        List<DanReportParseService.DataItem> items = new ArrayList<>();
+        if (itemsJson != null && !itemsJson.isEmpty()) {
+            try {
+                items = new com.fasterxml.jackson.databind.ObjectMapper().readValue(
+                        itemsJson,
+                        new com.fasterxml.jackson.core.type.TypeReference<List<DanReportParseService.DataItem>>() {});
+            } catch (Exception e) {
+                // 解析失败按空处理
+            }
+        }
+        // 1. score 块:total_score / percentile
+        List<Map<String, Object>> scoreItems = new ArrayList<>();
+        // 2. indicator 块:按 category 分组
+        Map<String, List<Map<String, Object>>> byCategory = new LinkedHashMap<>();
+        for (DanReportParseService.DataItem item : items) {
+            if (item.getValue() == null || item.getValue().isEmpty()) continue;
+            if ("total_score".equals(item.getCode())) {
+                scoreItems.add(scoreItem("总得分", item.getValue()));
+            } else if ("percentile".equals(item.getCode())) {
+                scoreItems.add(scoreItem("百分位", item.getValue()));
+            } else {
+                String cat = item.getCategory() == null || item.getCategory().isEmpty() ? "auto" : item.getCategory();
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("name", item.getName());
+                m.put("value", item.getValue());
+                byCategory.computeIfAbsent(cat, k -> new ArrayList<>()).add(m);
+            }
+        }
+        if (!scoreItems.isEmpty()) {
+            Map<String, Object> block = new LinkedHashMap<>();
+            block.put("type", "score");
+            block.put("title", "测评结果");
+            block.put("items", scoreItems);
+            blocks.add(block);
+        }
+        // 按固定 category 顺序输出(保证同类型报告展示顺序稳定)
+        for (Map.Entry<String, String> e : DAN_CATEGORY_TITLES.entrySet()) {
+            List<Map<String, Object>> items2 = byCategory.get(e.getKey());
+            if (items2 != null && !items2.isEmpty()) {
+                Map<String, Object> block = new LinkedHashMap<>();
+                block.put("type", "indicator");
+                block.put("title", e.getValue());
+                block.put("items", items2);
+                blocks.add(block);
+            }
+        }
+        // text 块:summary / suggestions
+        if (summary != null && !summary.isEmpty()) blocks.add(textBlock("报告评语", summary));
+        // DAN PDF 页眉固定印有「成长建议」,extractSection 按页眉截取会把整份报告正文
+        // (含页码/英文标题)当成建议。判为噪音或为空时,改为按实际指标生成建议汇总。
+        String effSuggestions = (suggestions != null && !isScrapSuggestions(suggestions)) ? suggestions : null;
+        if (effSuggestions == null || effSuggestions.trim().isEmpty()) {
+            effSuggestions = buildIndicatorSuggestions(byCategory);
+        }
+        if (effSuggestions != null && !effSuggestions.trim().isEmpty()) {
+            blocks.add(textBlock("成长建议", effSuggestions));
+        }
+        return blocks;
+    }
+
+    /** 判断提取到的「成长建议」是否为报告正文噪音(页码/英文标题/整篇长文) */
+    private boolean isScrapSuggestions(String s) {
+        if (s == null) return true;
+        String t = s.trim();
+        if (t.isEmpty()) return true;
+        return t.length() > 500
+                || t.contains("Results Summary")
+                || t.contains("测评报告")
+                || t.contains("第 1 页")
+                || t.contains("Total Score");
+    }
+
+    /**
+     * 按已采集的指标数据生成「成长建议」汇总(不直接引用报告原文)。
+     * - 大五人格:1-5 分制判读
+     * - 认知能力:百分位判读
+     * - 情绪状态:总分 vs 同龄平均
+     * - 社会关系 / 体质健康:列关键值 + 简单判读
+     * byCategory 的 value 为 String(历史数据同样适用)。
+     */
+    private String buildIndicatorSuggestions(Map<String, List<Map<String, Object>>> byCategory) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("以下建议依据本次测评采集到的各项指标数据生成,供日常养育与陪伴参考:");
+        boolean hasAny = false;
+
+        // 1. 大五人格(1-5 分制:>=4 优势 / <=2.5 低于同龄平均 / 其余持平)
+        List<Map<String, Object>> bigFive = byCategory.get("bigFive");
+        if (bigFive != null && !bigFive.isEmpty()) {
+            sb.append("\n\n【大五人格】");
+            for (Map<String, Object> it : bigFive) {
+                double v = toDouble(it.get("value"), -1);
+                String verdict;
+                if (v < 0) {
+                    verdict = "";
+                } else if (v >= 4) {
+                    verdict = "(表现突出,是成员的优势项)";
+                } else if (v <= 2.5) {
+                    verdict = "(低于同龄平均水平,建议有意识地给予肯定与锻炼机会)";
+                } else {
+                    verdict = "(与同龄平均基本持平)";
+                }
+                sb.append("\n· ").append(str(it.get("name"))).append(":").append(str(it.get("value")))
+                        .append(" 分").append(verdict);
+            }
+            hasAny = true;
+        }
+
+        // 2. 认知能力(百分位:>=70 优秀 / 50-69 良好 / <50 低于同龄)
+        List<Map<String, Object>> cognitive = byCategory.get("cognitive");
+        if (cognitive != null && !cognitive.isEmpty()) {
+            sb.append("\n\n【认知能力】");
+            for (Map<String, Object> it : cognitive) {
+                double v = toDouble(it.get("value"), -1);
+                String verdict;
+                if (v < 0) verdict = "";
+                else if (v >= 70) verdict = "(超过 70% 同龄人,表现优秀)";
+                else if (v >= 50) verdict = "(超过 50% 同龄人,处于良好水平)";
+                else verdict = "(低于同龄平均水平,建议通过专项练习有针对性地提升)";
+                // 名称统一去掉「百分位」后缀,展示更自然:感知觉百分位 → 感知觉
+                String name = str(it.get("name")).replace("百分位", "");
+                sb.append("\n· ").append(name).append(":").append(str(it.get("value")))
+                        .append("%").append(verdict);
+            }
+            hasAny = true;
+        }
+
+        // 3. 情绪状态(不稳定性总分 vs 同龄平均,分高代表情绪波动更大)
+        List<Map<String, Object>> emotion = byCategory.get("emotion");
+        if (emotion != null && !emotion.isEmpty()) {
+            sb.append("\n\n【情绪状态】");
+            double total = -1, avg = -1;
+            for (Map<String, Object> it : emotion) {
+                String name = str(it.get("name"));
+                if ("情绪总得分".equals(name)) total = toDouble(it.get("value"), -1);
+                else if ("情绪平均分".equals(name)) avg = toDouble(it.get("value"), -1);
+            }
+            for (Map<String, Object> it : emotion) {
+                String name = str(it.get("name"));
+                if ("情绪总得分".equals(name) || "情绪平均分".equals(name)) continue;
+                sb.append("\n· ").append(name).append(":").append(str(it.get("value")));
+            }
+            if (total >= 0 && avg >= 0) {
+                sb.append("\n· 情绪不稳定总分 ").append(trimNum(total)).append(" 分,同龄平均 ")
+                        .append(trimNum(avg)).append(" 分,");
+                double diff = total - avg;
+                if (diff > 3) {
+                    sb.append("高于同龄平均,日常可多关注情绪调节,遇挫败时及时陪伴与疏导");
+                } else if (diff > 0) {
+                    sb.append("略高于同龄平均,属常见波动范围,保持规律作息与倾诉习惯即可");
+                } else {
+                    sb.append("不高于同龄平均,情绪稳定性表现良好");
+                }
+            }
+            hasAny = true;
+        }
+
+        // 4. 社会关系(信任/沟通/亲近 × 母亲/父亲/同伴)
+        List<Map<String, Object>> social = byCategory.get("social");
+        if (social != null && !social.isEmpty()) {
+            sb.append("\n\n【社会关系】");
+            for (Map<String, Object> it : social) {
+                String name = str(it.get("name"));
+                String raw = str(it.get("value"));
+                // 文本型指标(依恋类型)不追加「分」
+                boolean numeric = toDouble(it.get("value"), -1) >= 0;
+                sb.append("\n· ").append(name).append(":").append(raw)
+                        .append(numeric ? " 分" : "");
+            }
+            java.util.List<String> lowDims = new ArrayList<>();
+            double sum = 0;
+            int cnt = 0;
+            for (Map<String, Object> it : social) {
+                double v = toDouble(it.get("value"), -1);
+                if (v < 0) continue;
+                sum += v;
+                cnt++;
+                // 亲近维度分值天然低于信任/沟通(PDF 标尺不同),阈值单独放宽
+                if (v < 20) lowDims.add(str(it.get("name")));
+            }
+            if (!lowDims.isEmpty()) {
+                sb.append("\n· ").append(String.join("、", lowDims))
+                        .append(" 分值偏低,建议多创造一对一相处与倾听的机会");
+            } else if (cnt > 0) {
+                double avg = sum / cnt;
+                if (avg >= 30) {
+                    sb.append("\n· 与母亲、父亲及同伴的信任/沟通/亲近整体良好,可继续保持高频的亲子互动");
+                } else {
+                    sb.append("\n· 各关系维度处于中等水平,可通过共同活动与日常倾听进一步拉近");
+                }
+            }
+            hasAny = true;
+        }
+
+        // 5. 体质健康(BMI + 身高体重 + 饮食/睡眠/运动习惯)
+        List<Map<String, Object>> body = byCategory.get("body");
+        if (body != null && !body.isEmpty()) {
+            sb.append("\n\n【体质健康】");
+            String bmiGrade = null, bmiScore = null, height = null, weight = null;
+            java.util.List<String> habitLines = new ArrayList<>();
+            for (Map<String, Object> it : body) {
+                String name = str(it.get("name"));
+                String value = str(it.get("value"));
+                if ("BMI等级".equals(name)) bmiGrade = value;
+                else if ("BMI得分".equals(name)) bmiScore = value;
+                else if ("身高".equals(name)) height = value;
+                else if ("体重".equals(name)) weight = value;
+                else if ("BMI值".equals(name)) continue;
+                else habitLines.add(name + ":" + value);
+            }
+            if (height != null || weight != null) {
+                sb.append("\n· 身高/体重:").append(height == null ? "-" : height).append(" cm / ")
+                        .append(weight == null ? "-" : weight).append(" kg");
+            }
+            if (bmiScore != null || bmiGrade != null) {
+                sb.append("\n· BMI ").append(bmiScore == null ? "-" : bmiScore).append(",等级 ")
+                        .append(bmiGrade == null ? "-" : bmiGrade);
+                if ("正常".equals(bmiGrade)) {
+                    sb.append(",体型发育良好");
+                } else if (bmiGrade != null) {
+                    sb.append(",建议结合饮食与运动习惯适度调整");
+                }
+            }
+            if (!habitLines.isEmpty()) {
+                sb.append("\n· 生活习惯:").append(String.join(";", habitLines));
+            }
+            hasAny = true;
+        }
+
+        if (!hasAny) return null;
+        return sb.toString();
+    }
+
+    private double toDouble(Object v, double def) {
+        if (v == null) return def;
+        try {
+            return Double.parseDouble(v.toString().trim());
+        } catch (Exception e) {
+            return def;
+        }
+    }
+
+    /** 去掉小数尾随的 .0,展示更自然:42.0 → 42,42.5 → 42.5 */
+    private String trimNum(double v) {
+        if (v == Math.rint(v)) return String.valueOf((long) v);
+        return String.valueOf(v);
+    }
+
+    private Map<String, Object> scoreItem(String label, String value) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("label", label);
+        m.put("value", value);
+        m.put("max", 100);
+        return m;
+    }
+
+    private Map<String, Object> textBlock(String title, String content) {
+        Map<String, Object> block = new LinkedHashMap<>();
+        block.put("type", "text");
+        block.put("title", title);
+        block.put("content", content);
+        return block;
+    }
+
+    private String str(Object v) {
+        return v == null ? null : v.toString();
+    }
+
+    private List<Map<String, Object>> toList(JsonNode node) {
+        if (node == null || node.isNull()) return new ArrayList<>();
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (JsonNode n : node) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            n.fields().forEachRemaining(e -> m.put(e.getKey(), e.getValue().toString()));
+            result.add(m);
+        }
+        return result;
+    }
+
+    private Map<String, Object> toMap(JsonNode node) {
+        if (node == null || node.isNull()) return null;
+        Map<String, Object> m = new LinkedHashMap<>();
+        node.fields().forEachRemaining(e -> {
+            if (e.getValue().isBoolean()) m.put(e.getKey(), e.getValue().asBoolean());
+            else if (e.getValue().isNumber()) m.put(e.getKey(), e.getValue().asDouble());
+            else m.put(e.getKey(), e.getValue().asText());
+        });
+        return m;
+    }
+}

+ 72 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportBlockService.java

@@ -0,0 +1,72 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.ReportBlock;
+import com.etotem.cfc.mapper.ReportBlockMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Service
+@Slf4j
+public class ReportBlockService {
+
+    @Resource
+    private ReportBlockMapper reportBlockMapper;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /** 保存或覆盖 blocks(幂等 upsert) */
+    public void save(String reportType, Long reportId, List<Map<String, Object>> blocks) {
+        if (blocks == null || blocks.isEmpty()) return;
+        try {
+            ReportBlock existing = reportBlockMapper.selectOne(
+                    new LambdaQueryWrapper<ReportBlock>()
+                            .eq(ReportBlock::getReportType, reportType)
+                            .eq(ReportBlock::getReportId, reportId));
+            String json = objectMapper.writeValueAsString(blocks);
+            Date now = new Date();
+            if (existing != null) {
+                existing.setBlocks(json);
+                existing.setVersion(existing.getVersion() == null ? 1 : existing.getVersion() + 1);
+                existing.setUpdatedAt(now);
+                reportBlockMapper.updateById(existing);
+            } else {
+                ReportBlock nb = new ReportBlock();
+                nb.setReportType(reportType);
+                nb.setReportId(reportId);
+                nb.setBlocks(json);
+                nb.setVersion(1);
+                nb.setCreatedAt(now);
+                nb.setUpdatedAt(now);
+                reportBlockMapper.insert(nb);
+            }
+        } catch (Exception e) {
+            log.warn("保存report_blocks失败 type={} reportId={}: {}", reportType, reportId, e.getMessage());
+        }
+    }
+
+    /** 读取 blocks,无记录返回空列表 */
+    public List<Map<String, Object>> getBlocks(String reportType, Long reportId) {
+        try {
+            ReportBlock existing = reportBlockMapper.selectOne(
+                    new LambdaQueryWrapper<ReportBlock>()
+                            .eq(ReportBlock::getReportType, reportType)
+                            .eq(ReportBlock::getReportId, reportId));
+            if (existing == null || existing.getBlocks() == null || existing.getBlocks().isEmpty()) {
+                return new ArrayList<>();
+            }
+            return objectMapper.readValue(existing.getBlocks(), new TypeReference<List<Map<String, Object>>>() {});
+        } catch (Exception e) {
+            log.warn("读取report_blocks失败 type={} reportId={}: {}", reportType, reportId, e.getMessage());
+            return new ArrayList<>();
+        }
+    }
+}

+ 1558 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportCollectService.java

@@ -0,0 +1,1558 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.DanReportUploadVO;
+import com.etotem.cfc.dto.ParsedReportPayload;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.DanReportUploadMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import com.etotem.cfc.mapper.ReportUnknownClusterMapper;
+import com.etotem.cfc.mapper.ReportUnknownUploadMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import javax.annotation.Resource;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+/**
+ * 报告异步采集服务:上传后进入后台队列,指纹判定类型后走专用脚本或 opencode,
+ * 解析完成自动入库,前端通过草稿 parse_status 轮询。
+ */
+@Slf4j
+@Service
+public class ReportCollectService {
+
+    @Resource
+    private ReportFingerprintService fingerprintService;
+
+    @Resource
+    private LangGraphReportParseService langGraphReportParseService;
+
+    @Resource
+    private HealthReportDraftService healthReportDraftService;
+
+    @Resource
+    private HealthReportService healthReportService;
+
+    @Resource
+    private FoodService foodService;
+
+    @Resource
+    private DimensionScoreService dimensionScoreService;
+
+    @Resource
+    private FoodRecommendService foodRecommendService;
+
+    @Resource
+    private ReportBlockService reportBlockService;
+
+    @Resource
+    private ReportBlockAssembler reportBlockAssembler;
+
+    @Resource
+    private StorageService storageService;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private ReportTypeRegistryMapper reportTypeRegistryMapper;
+
+    @Resource
+    private DanReportUploadMapper danReportUploadMapper;
+
+    @Resource
+    private DanReportParseService danReportParseService;
+
+    @Resource
+    private DanReportUploadService danReportUploadService;
+
+    /** 未知聚类(S-cfc-363 / RED-2):解析失败/未知格式报告进入「未知聚类」人工标注池 */
+    @Resource
+    private ReportUnknownClusterMapper unknownClusterMapper;
+
+    /** 未知上传记录(S-cfc-363 / RED-2):未知聚类链路的上传记录 */
+    @Resource
+    private ReportUnknownUploadMapper unknownUploadMapper;
+
+    @Resource(name = "taskExecutor")
+    private Executor taskExecutor;
+
+    @Resource
+    private TaskService taskService;
+
+    @Resource
+    private RestTemplate restTemplate;
+
+    @Resource
+    private ObjectMapper objectMapper;
+
+    @Resource
+    private com.etotem.cfc.service.NormalizeIndicatorPipeline normalizeIndicatorPipeline;
+
+    @Value("${report.collect.opencode-base:http://127.0.0.1:4090}")
+    private String opencodeBase;
+
+    @Value("${report.collect.opencode-user:opencode}")
+    private String opencodeUser;
+
+    @Value("${report.collect.opencode-password:IwinTrue@123}")
+    private String opencodePassword;
+
+    @Value("${report.collect.opencode-workdir:/app/cfc}")
+    private String opencodeWorkdir;
+
+    @Value("${report.collect.opencode-model-id:agnes-2.5-flash}")
+    private String opencodeModelId;
+
+    @Value("${report.collect.opencode-model-provider:agnes-ai}")
+    private String opencodeModelProvider;
+
+    /** 常量:解析方式 */
+    public static final String METHOD_FINGERPRINT = "fingerprint_script";
+    public static final String METHOD_LANGGRAPH_SCRIPT = "langgraph_script";
+    public static final String METHOD_LANGGRAPH_DETECT = "langgraph_detect";
+    public static final String METHOD_OPENCODE = "opencode";
+
+    /**
+     * 状态常量:与草稿 parse_status 对齐
+     */
+    public static final String STATUS_COLLECTING = "collecting";
+    public static final String STATUS_COMPLETED = "completed";
+    public static final String STATUS_FAILED = "failed";
+
+// ========================================================================
+    // P0-3 ③ _解析自检 透传合并 —— guhe_v2 新版报告解析结果自检块四子键锚点
+    // 采集回填层将解析结果中的 _解析自检 信息透传并入 health_report_drafts.collect_validation JSON。
+    // ========================================================================
+
+    /** guhe_v2 解析结果自检块键名(透传并入 collect_validation,见 P0-3 ③) */
+    public static final String PARSE_SELF_CHECK_KEY = "_解析自检";
+
+    /** guhe_v2 解析自检四子键 —— 通过 / P0告警数 / P1提示数 / 告警;用于校验和暴露到 collect/status */
+    public static final String SELF_CHECK_PASS = "通过";
+    public static final String SELF_CHECK_P0_ALERTS = "P0告警数";
+    public static final String SELF_CHECK_P1_HINTS = "P1提示数";
+    public static final String SELF_CHECK_ALERTS = "告警";
+
+    /** _解析自检 四子键常量集合(用于过滤/透传) */
+    public static final List<String> SELF_CHECK_KEYS = Collections.unmodifiableList(Arrays.asList(
+            SELF_CHECK_PASS, SELF_CHECK_P0_ALERTS, SELF_CHECK_P1_HINTS, SELF_CHECK_ALERTS));
+
+    // ==================== P0-2 回退红线(S-cfc-424 health.report.guheV2AsyncRoute) ====================
+    // 谷禾新版解析与五维归因升级方案 v1.0 §3 P0-2 ③:
+    //   guhe_v2 异步采集失败<b>不</b>做 Java 本地兜底(Java 无 guhe_v2 能力),
+    //   而是标记 parse_error + 通知用户「该报告格式暂不支持在线解析,可稍后重试或联系服务号」。
+
+    /** P0-2 回退红线:guhe_v2 失败用户提示(不做 Java 本地兜底,统一通知用户) */
+    public static final String FAILBACK_USER_NOTICE = "该报告格式暂不支持在线解析,可稍后重试或联系服务号";
+
+    /** P0-2:guhe_v2 指纹类型标识(32 键新版标准报告;与 ReportParserDispatchService.GUHE_V2_TYPE_ID 对齐) */
+    public static final String GUHE_V2_TYPE_ID = "gut_flora_guhe_v2";
+
+    /**
+     * 提交异步采集任务。上传完成后调用,立即返回。
+     */
+    public void submitAsyncCollect(Long draftId) {
+        try {
+            taskExecutor.execute(() -> collect(draftId));
+        } catch (Exception e) {
+            log.error("提交异步采集任务失败 draftId={}", draftId, e);
+            healthReportDraftService.markCollectFailed(draftId, "提交任务失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 采集主流程:指纹判定 → 已知专用脚本 / 未知 opencode → 解析 JSON → 自动入库
+     */
+    public void collect(Long draftId) {
+        HealthReportDraft draft = healthReportDraftService.getDraftById(draftId);
+        if (draft == null) {
+            log.warn("异步采集草稿不存在 draftId={}", draftId);
+            return;
+        }
+        if (STATUS_COMPLETED.equals(draft.getParseStatus())
+                || draft.getConfirmedReportId() != null) {
+            return;
+        }
+        String pdfPath = null;
+        try {
+            healthReportDraftService.markParseStarted(draftId);
+            pdfPath = resolvePdfPath(draft);
+            if (pdfPath == null) {
+                healthReportDraftService.markCollectFailed(draftId, "无法获取报告文件路径");
+                return;
+            }
+            // 文件类型预检:采集链路(指纹引擎/LangGraph/opencode)仅支持 PDF,
+            // 图片等非 PDF 文件直接标记失败,避免 PyPDF2 报 EOF marker not found 等错误
+            if (!isPdfFile(pdfPath)) {
+                log.warn("采集跳过非PDF文件 draftId={}, path={}, filename={}",
+                        draftId, pdfPath, draft.getOriginalFilename());
+                healthReportDraftService.markCollectFailed(draftId, "仅支持PDF报告文件,请上传PDF格式");
+                return;
+            }
+
+            // 指纹判定
+            Map<String, Object> fp = fingerprintService.detect(pdfPath, draft.getOriginalFilename());
+            String typeId = (String) fp.get("typeId");
+
+            // DAN 家族分流:指纹识别到 dan_* 类型(如 dan_a2)→ Java 同步解析 + DAN 入库,
+            // 不进入健康报告管道(parserPath 为空的 dan 类型指纹也不会走 LangGraph 脚本分支)
+            if (typeId != null && !"unknown".equals(typeId)) {
+                ReportTypeRegistry registry = reportTypeRegistryMapper.selectOne(
+                        new LambdaQueryWrapper<ReportTypeRegistry>()
+                                .eq(ReportTypeRegistry::getTypeId, typeId)
+                                .last("LIMIT 1"));
+                if (registry != null && "dan".equals(registry.getFamily())) {
+                    collectDanReport(draft, pdfPath, registry);
+                    return;
+                }
+            }
+
+            // 加固③:指纹成功识别出的类型与用户所选报告类型不一致(非 DAN)→ 阻止自动入库,
+            // 防止认知能力测评等报告误入健康管道(如 gut_flora)后以错误类型静默入库
+            if (!"unknown".equals(typeId) && !typeId.equals(draft.getReportType())) {
+                log.warn("报告类型不匹配 draftId={}, 指纹识别={}, 所选={}", draftId, typeId, draft.getReportType());
+                healthReportDraftService.markCollectFailed(draftId,
+                        "报告内容与所选类型不符(指纹识别为「" + typeId + "」,所选「" + draft.getReportType()
+                                + "」),请核对报告类型后重新上传");
+                return;
+            }
+
+            // 采集指标清单(用于驱动非 DAN 的 LangGraph LLM 解析)
+            String validationTypeId = (!"unknown".equals(typeId)) ? typeId : draft.getReportType();
+            List<String> expectedIndicators = loadExpectedIndicators(validationTypeId);
+
+            ParsedReportPayload.Payload payload;
+            String method;
+            // guhe_v2 解析自检块(P0-3 ③):known-type 分支随 outcome 透出,并入 collect_validation
+            Map<String, Object> parseSelfCheck = null;
+            if (!"unknown".equals(typeId) && fp.get("parserPath") != null) {
+                // 指纹成功:脚本已迁移到 LangGraph(/report/parse,算法 + LLM 兜底)
+                // 已知类型解析失败不再回退 opencode,改为登记退避重试(parse_error 记录失败原因),
+                // 由 ReportCollectRetryTask 定时驱动重试,避免静默降级导致 foods 等数据缺失。
+                method = METHOD_LANGGRAPH_SCRIPT;
+                boolean guheV2 = GUHE_V2_TYPE_ID.equals(typeId);
+                // P0-2 ②:guhe_v2 报告携带 reportFormatHint="guhe_v2",Python 侧路由到 extract_guhe_v2
+                LangGraphReportParseService.ParseOutcome outcome = guheV2
+                        ? langGraphReportParseService.parseByScriptWithReason(
+                                pdfPath, expectedIndicators, LangGraphReportParseService.GUHE_V2_HINT_VALUE)
+                        : langGraphReportParseService.parseByScriptWithReason(pdfPath, expectedIndicators);
+                payload = outcome != null ? outcome.getPayload() : null;
+                parseSelfCheck = outcome != null ? outcome.getSelfCheck() : null;
+                if (payload == null) {
+                    // P0-2 回退红线③:guhe_v2 失败<b>不</b>做 Java 本地兜底(Java 无此能力),
+                    // 标记 parse_error + 通知用户「该报告格式暂不支持在线解析,可稍后重试或联系服务号」
+                    if (guheV2) {
+                        log.warn("guhe_v2 LangGraph 脚本解析失败,按 P0-2 回退红线标记失败 typeId={}, reason={}",
+                                typeId, outcome != null ? outcome.getError() : "解析结果为空或无效");
+                        healthReportDraftService.markCollectFailed(draftId, FAILBACK_USER_NOTICE);
+                        return;
+                    }
+                    String reason = outcome != null && outcome.getError() != null
+                            ? outcome.getError() : "解析结果为空或无效";
+                    log.warn("已知类型 LangGraph 脚本解析失败,登记退避重试 typeId={}, reason={}", typeId, reason);
+                    healthReportDraftService.recordRetry(draftId, reason);
+                    return;
+                }
+            } else {
+                // 无指纹:先用 LangGraph 识别(detect-type → parse-typed / script),识别不了再 opencode
+                method = METHOD_LANGGRAPH_DETECT;
+                payload = langGraphReportParseService.parseWithDetect(pdfPath, expectedIndicators);
+                if (payload == null) {
+                    log.warn("无指纹 LangGraph 识别/解析为空,回退 opencode typeId={}", typeId);
+                    method = METHOD_OPENCODE;
+                    payload = parseWithOpencode(pdfPath, draft.getOriginalFilename());
+                }
+            }
+
+            if (payload == null) {
+                healthReportDraftService.markCollectFailed(draftId, "解析结果为空或无效");
+                return;
+            }
+
+            harmReportPayloadValid(payload);
+            // 加固②:已知肠道菌群家族类型必须含菌群实质数据(菌群检出列表/指标清单),
+            // 防止认知测评等非菌群报告只解析出 overview 也静默入库
+            if (isGutFloraType(validationTypeId) && !hasGutContent(payload)) {
+                log.warn("肠道菌群报告解析结果缺少菌群数据,阻止入库 draftId={}, typeId={}",
+                        draftId, validationTypeId);
+                healthReportDraftService.markCollectFailed(draftId,
+                        "解析结果缺少菌群检测数据(报告内容与所选类型不符),请在解析状态页人工处理或重新上传");
+                return;
+            }
+            // 采集指标完整性校验(report_type_registry.expected_indicators 定义驱动)
+            // 加固①:校验不通过(pass=false)阻止自动入库,标记失败由管理端人工处理
+            boolean validationPass;
+            try {
+                validationPass = runCollectValidation(draftId, validationTypeId, payload, parseSelfCheck);
+            } catch (Exception e) {
+                log.warn("采集指标校验失败 draftId={}, typeId={}", draftId, validationTypeId, e);
+                validationPass = true;
+            }
+            if (!validationPass) {
+                log.warn("采集指标校验未通过,阻止入库 draftId={}, typeId={}", draftId, validationTypeId);
+                healthReportDraftService.markCollectFailed(draftId,
+                        "采集指标校验未通过(报告内容与所选类型不符或解析不完整),请在解析状态页人工处理或重新上传");
+                return;
+            }
+            healthReportDraftService.updateParseMethod(draftId, method);
+            healthReportDraftService.updatePayload(draftId, objectMapper.writeValueAsString(payload));
+
+            // 幂等守卫:原子抢占插入槽位(collecting -> inserting 且 confirmed_report_id 为空)。
+            // 并发重跑任务(定时重试驱动器/外部触发)解析完成后到达此处时,只有先到者能抢到槽位,
+            // 后到者因 parse_status 已变为 inserting 或 confirmed_report_id 非空而失败,避免重复入库。
+            if (!healthReportDraftService.tryClaimInsertSlot(draftId)) {
+                log.warn("草稿插入槽位已被抢占或已入库,跳过重复入库 draftId={}", draftId);
+                return;
+            }
+
+            insertReport(draft, payload);
+
+            log.info("异步采集完成 draftId={}, method={}", draftId, method);
+        } catch (Exception e) {
+            log.error("异步采集失败 draftId={}", draftId, e);
+            healthReportDraftService.markCollectFailed(draftId, e.getMessage());
+        } finally {
+            cleanupPdfCache(pdfPath);
+        }
+    }
+
+    /**
+     * DAN 家族报告采集:指纹识别到 dan_* 类型(如 dan_a2)后走 Java 同步解析 + DAN 入库。
+     * 复用 DanReportUploadService.confirmUpload(@Transactional:result 入库 / 展示块 / 汇总 / 五维刷新 / 自动方案),
+     * 完成草稿闭环:reportType 置为识别类型 + markCollectCompleted(reportId = dan upload id),
+     * 前端 collect/status 据此跳转 dan-assessment/report-result?reportId=...
+     */
+    private void collectDanReport(HealthReportDraft draft, String pdfPath, ReportTypeRegistry registry) {
+        Long draftId = draft.getId();
+        Long memberId = draft.getMemberId();
+        if (memberId == null) {
+            healthReportDraftService.markCollectFailed(draftId,
+                    "已识别为" + registry.getDisplayName() + "报告,请重新上传并选择报告归属成员");
+            return;
+        }
+        String dimension = resolveDanDimension(registry.getTypeId());
+        try {
+            // Java 同步解析(与 uploadAndParse 同一解析器)
+            DanReportParseService.DanParsedReport parsed;
+            try (FileInputStream fis = new FileInputStream(new File(pdfPath))) {
+                parsed = danReportParseService.parse(fis, dimension);
+            }
+            if (parsed == null || parsed.getItems() == null || parsed.getItems().isEmpty()) {
+                healthReportDraftService.markCollectFailed(draftId,
+                        "已识别为" + registry.getDisplayName() + "报告,但未能提取有效指标");
+                return;
+            }
+
+            // 构建 DAN 上传记录(对齐 uploadAndParse 字段)
+            DanReportUpload upload = new DanReportUpload();
+            upload.setFamilyMemberId(memberId);
+            upload.setUploaderUserId(draft.getUserId());
+            upload.setDimension(dimension);
+            Long familyId = draft.getFamilyId();
+            if (familyId == null) {
+                familyId = resolveDanFamilyId(memberId);
+            }
+            upload.setFamilyId(familyId);
+            upload.setFileUrl(draft.getFileUrl());
+            upload.setFileId(toShortFileId(draft.getFileUrl()));
+            upload.setFileName(draft.getOriginalFilename());
+            upload.setFileSize(new File(pdfPath).length());
+            upload.setUploadedAt(new Date());
+            upload.setDraftStatus(DanReportUpload.DRAFT_PENDING);
+            upload.setParseStatus(DanReportUpload.PARSE_SUCCESS);
+            upload.setParserVersion("v1");
+            upload.setParsedItems(objectMapper.writeValueAsString(parsed.getItems()));
+            upload.setParsedExtra(objectMapper.writeValueAsString(parsed.getExtra()));
+            upload.setParsedSummary(parsed.getSummary());
+            upload.setParsedSuggestions(parsed.getSuggestions());
+            upload.setReportType(parsed.getReportType());
+            upload.setParsedAt(new Date());
+            upload.setEditCount(0);
+            upload.setCreatedAt(new Date());
+            upload.setUpdatedAt(new Date());
+            danReportUploadMapper.insert(upload);
+
+            // 自动确认入库(result + blocks + 汇总 + 五维 + 自动方案)
+            Map<String, Object> extra = parsed.getExtra();
+            String childName = extra != null && extra.get("name") != null ? String.valueOf(extra.get("name")) : "";
+            String assessmentDate = extra != null && extra.get("reportDate") != null
+                    ? String.valueOf(extra.get("reportDate")) : "";
+            Result<DanReportUploadVO> confirm = danReportUploadService.confirmUpload(
+                    upload.getId(), draft.getUserId(), childName, assessmentDate);
+            if (confirm == null || confirm.getCode() == null || confirm.getCode() != 200) {
+                healthReportDraftService.markCollectFailed(draftId,
+                        "DAN报告确认入库失败: " + (confirm != null ? confirm.getMessage() : "无响应"));
+                return;
+            }
+
+            // 采集指标完整性校验(expected_indicators 定义驱动)
+            runCollectValidation(draftId, registry.getTypeId(), parsed);
+
+            // 草稿闭环:reportType 置为识别类型(前端按 dan_* 跳转)+ completed
+            healthReportDraftService.updateReportType(draftId, registry.getTypeId());
+            healthReportDraftService.markCollectCompleted(draftId, upload.getId());
+            log.info("DAN家族采集完成 draftId={}, typeId={}, danUploadId={}, dimension={}",
+                    draftId, registry.getTypeId(), upload.getId(), dimension);
+        } catch (Exception e) {
+            log.error("DAN家族采集失败 draftId={}, typeId={}", draftId, registry.getTypeId(), e);
+            healthReportDraftService.markCollectFailed(draftId, e.getMessage());
+        }
+    }
+
+    /** dan 家族 typeId → 测评维度:dan_a2 → mind、dan_b4 → wisdom 等;兼容 dan_<dim> 语义名,否则默认 mind */
+    private String resolveDanDimension(String typeId) {
+        if (typeId != null && typeId.startsWith("dan_")) {
+            String code = typeId.substring(4);
+            // 兼容语义维度名(如 dan_mind / dan_wisdom)
+            if (DanReportUpload.DIM_MIND.equals(code) || DanReportUpload.DIM_WISDOM.equals(code)
+                    || DanReportUpload.DIM_COGNITION.equals(code) || DanReportUpload.DIM_LEARNING.equals(code)
+                    || DanReportUpload.DIM_BEHAVIOR.equals(code) || DanReportUpload.DIM_CAREER.equals(code)
+                    || DanReportUpload.DIM_CAMPUS.equals(code) || DanReportUpload.DIM_ADOLESCENT.equals(code)) {
+                return code;
+            }
+            // report_type_registry.typeId 编码 → 测评维度
+            switch (code) {
+                case "a1": return DanReportUpload.DIM_COGNITION;
+                case "a2": return DanReportUpload.DIM_MIND;
+                case "b2": return DanReportUpload.DIM_BEHAVIOR;
+                case "b3": return DanReportUpload.DIM_LEARNING;
+                case "b4": return DanReportUpload.DIM_WISDOM;
+                case "b5": return DanReportUpload.DIM_ADOLESCENT;
+                case "b6": return DanReportUpload.DIM_CAREER;
+                case "c1": return DanReportUpload.DIM_CAMPUS;
+                default: break;
+            }
+        }
+        return DanReportUpload.DIM_MIND;
+    }
+
+    private Long resolveDanFamilyId(Long memberId) {
+        if (memberId == null) {
+            return null;
+        }
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        return member != null ? member.getFamilyId() : null;
+    }
+
+    /** file_id 存相对路径或文件名(对齐 DanReportUploadService.toShortFileId,避免 Data truncation) */
+    private String toShortFileId(String fileUrl) {
+        if (fileUrl == null || fileUrl.isEmpty()) {
+            return null;
+        }
+        int uploadsIdx = fileUrl.indexOf("/uploads/");
+        if (uploadsIdx >= 0) {
+            return fileUrl.substring(uploadsIdx + 1);
+        }
+        int slash = fileUrl.lastIndexOf('/');
+        if (slash >= 0 && slash < fileUrl.length() - 1) {
+            return fileUrl.substring(slash + 1);
+        }
+        return fileUrl.length() > 500 ? fileUrl.substring(0, 500) : fileUrl;
+    }
+
+    private void harmReportPayloadValid(ParsedReportPayload.Payload payload) {
+        if (payload.getSummary() == null && (payload.getIndicators() == null || payload.getIndicators().isEmpty())
+                && (payload.getGutFlora() == null || payload.getGutFlora().isEmpty())) {
+            throw new IllegalArgumentException("解析结果中未提取到有效指标数据");
+        }
+        validateSummaryScores(payload.getSummary());
+    }
+
+    /**
+     * 防异常值入库(S-cfc-363 / RED-3,TC-P-22-E):健康评分类字段出现负数视为解析错误,
+     * 拒绝入库并提示「数据异常,暂不入库」。校验 9 个评分类字段
+     * (overall/gutHealth/chronicDisease/nutrition/balance/diversity/beneficial/harmful/coreGenus)。
+     */
+    private void validateSummaryScores(ParsedReportPayload.Summary summary) {
+        if (summary == null) {
+            return;
+        }
+        Integer[] scores = {
+                summary.getOverallScore(), summary.getGutHealthScore(),
+                summary.getChronicDiseaseScore(), summary.getNutritionScore(),
+                summary.getBalanceScore(), summary.getDiversityScore(),
+                summary.getBeneficialScore(), summary.getHarmfulScore(),
+                summary.getCoreGenusScore()
+        };
+        for (Integer score : scores) {
+            if (score != null && score < 0) {
+                throw new IllegalArgumentException("数据异常,暂不入库:健康评分存在负数(" + score + ")");
+            }
+        }
+    }
+
+    private String resolvePdfPath(HealthReportDraft draft) {
+        if (draft.getFileUrl() == null) {
+            return null;
+        }
+        try {
+            String p = storageService.getFilePath(draft.getFileUrl());
+            File f = new File(p);
+            return f.exists() ? f.getAbsolutePath() : null;
+        } catch (Exception e) {
+            log.warn("解析文件路径失败 fileUrl={}", draft.getFileUrl(), e);
+            return null;
+        }
+    }
+
+    /**
+     * 解析完成后清理 OSS 下载中转缓存。OSS 为持久存储,本地缓存仅为解析中转,用后即删。
+     * 仅清理 .jdcloud-cache 缓存文件,本地磁盘存储(uploadBaseDir 直存)的原文件不动。
+     */
+    private void cleanupPdfCache(String pdfPath) {
+        if (pdfPath == null) {
+            return;
+        }
+        File f = new File(pdfPath);
+        if (f.exists() && f.getAbsolutePath().contains(".jdcloud-cache")) {
+            try {
+                Files.deleteIfExists(f.toPath());
+                log.info("已清理OSS下载中转缓存 {}", pdfPath);
+            } catch (Exception e) {
+                log.warn("清理OSS下载中转缓存失败 {}", pdfPath, e);
+            }
+        }
+    }
+
+    /**
+     * 检查文件是否为 PDF(通过魔数 %PDF- 判断)。
+     * 指纹引擎、LangGraph 解析、opencode 均要求 PDF 输入。
+     */
+    private boolean isPdfFile(String filePath) {
+        try (FileInputStream fis = new FileInputStream(filePath)) {
+            byte[] header = new byte[5];
+            int read = fis.read(header);
+            return read == 5 && new String(header, StandardCharsets.US_ASCII).startsWith("%PDF-");
+        } catch (Exception e) {
+            log.debug("PDF魔数检查失败 path={}: {}", filePath, e.getMessage());
+            return false;
+        }
+    }
+
+    /** 未知类型:交本地 opencode 服务。因 headless serve 仅单轮文本生成可靠且输出有限,
+     * 采用分块单轮解析:每一块独立 session、单轮返回该 section 的 JSON,块间互不依赖,
+     * 最后合并为完整 Payload,避免单轮输出截断导致整单失败。
+     */
+    private ParsedReportPayload.Payload parseWithOpencode(String pdfPath, String fileName) {
+        String pdfText = extractPdfText(pdfPath);
+        ParsedReportPayload.Payload payload = new ParsedReportPayload.Payload();
+        int produced = 0;
+
+        JsonNode sr = opencodeSection(pdfText, fileName,
+                "只提取 summary 和 diseaseRisks 两部分,其余字段不返回",
+                "{\"summary\":{\"overallScore\":0,\"gutHealthScore\":0,\"chronicDiseaseScore\":0,\"nutritionScore\":0,\"balanceScore\":0,\"diversityScore\":0,\"beneficialScore\":0,\"harmfulScore\":0,\"coreGenusScore\":0,\"gutAge\":\"\",\"gutType\":\"\",\"gutStatusLevel\":\"\",\"shannonIndex\":\"\",\"reportNumber\":\"\",\"reportDate\":\"yyyy-MM-dd\",\"personName\":\"\",\"gender\":\"\",\"age\":0,\"birthday\":\"\"},\"diseaseRisks\":[{\"diseaseName\":\"\",\"riskValue\":\"\",\"riskLevel\":\"\",\"relatedBacteria\":[{\"bacteria\":\"\",\"correlation\":\"\",\"value\":\"\",\"status\":\"\"}]}]}");
+        if (sr != null) {
+            if (sr.has("summary") && !sr.get("summary").isNull()) {
+                payload.setSummary(objectMapper.convertValue(sr.get("summary"), ParsedReportPayload.Summary.class));
+                produced++;
+            }
+            if (sr.has("diseaseRisks") && sr.get("diseaseRisks").isArray()) {
+                payload.setDiseaseRisks(objectMapper.convertValue(sr.get("diseaseRisks"),
+                        new TypeReference<List<ParsedReportPayload.DiseaseRisk>>() {}));
+                produced++;
+            }
+        }
+
+        JsonNode ind = opencodeSection(pdfText, fileName,
+                "只提取 indicators 指标数组,其余字段不返回",
+                "{\"indicators\":[{\"category\":\"\",\"indicatorName\":\"\",\"indicatorValue\":\"\",\"unit\":\"\",\"refRange\":\"\",\"status\":\"\"}]}");
+        if (ind != null && ind.has("indicators") && ind.get("indicators").isArray()) {
+            payload.setIndicators(objectMapper.convertValue(ind.get("indicators"),
+                    new TypeReference<List<ParsedReportPayload.Indicator>>() {}));
+            produced++;
+        }
+
+        TypeReference<List<ParsedReportPayload.Flora>> floraType = new TypeReference<List<ParsedReportPayload.Flora>>() {};
+
+        JsonNode floraMain = opencodeSection(pdfText, fileName,
+                "只提取 gutFlora、probioticSpecies、pathogenGenus、pathogenDetection 四部分菌群数据,其余字段不返回",
+                "{\"gutFlora\":[{\"bacteriaName\":\"\",\"bacteriaValue\":\"\",\"normalRange\":\"\",\"populationLevel\":\"\",\"detectionRate\":\"\",\"description\":\"\",\"category\":\"\",\"level\":\"\"}],\"probioticSpecies\":[],\"pathogenGenus\":[],\"pathogenDetection\":[]}",
+                true);
+        if (floraMain != null) {
+            putFlora(payload::setGutFlora, floraMain, "gutFlora", floraType);
+            putFlora(payload::setProbioticSpecies, floraMain, "probioticSpecies", floraType);
+            putFlora(payload::setPathogenGenus, floraMain, "pathogenGenus", floraType);
+            putFlora(payload::setPathogenDetection, floraMain, "pathogenDetection", floraType);
+            if (payload.getGutFlora() != null || payload.getProbioticSpecies() != null
+                    || payload.getPathogenGenus() != null || payload.getPathogenDetection() != null) {
+                produced++;
+            }
+        }
+
+        JsonNode taxHigh = opencodeSection(pdfText, fileName,
+                "只提取 taxonomyClass、taxonomyOrder、taxonomyFamily 三个分类层级占比数据,其余字段不返回",
+                "{\"taxonomyClass\":[],\"taxonomyOrder\":[],\"taxonomyFamily\":[]}",
+                true);
+        if (taxHigh != null) {
+            putFlora(payload::setTaxonomyClass, taxHigh, "taxonomyClass", floraType);
+            putFlora(payload::setTaxonomyOrder, taxHigh, "taxonomyOrder", floraType);
+            putFlora(payload::setTaxonomyFamily, taxHigh, "taxonomyFamily", floraType);
+        }
+
+        JsonNode taxLow = opencodeSection(pdfText, fileName,
+                "只提取 taxonomyGenus、taxonomySpecies 两个分类层级占比数据,其余字段不返回",
+                "{\"taxonomyGenus\":[],\"taxonomySpecies\":[]}",
+                true);
+        if (taxLow != null) {
+            putFlora(payload::setTaxonomyGenus, taxLow, "taxonomyGenus", floraType);
+            putFlora(payload::setTaxonomySpecies, taxLow, "taxonomySpecies", floraType);
+        }
+
+        if (produced == 0
+                && payload.getGutFlora() == null && payload.getTaxonomyClass() == null
+                && payload.getTaxonomyGenus() == null && payload.getTaxonomySpecies() == null) {
+            return null;
+        }
+        return payload;
+    }
+
+    private void putFlora(Consumer<List<ParsedReportPayload.Flora>> setter, JsonNode section, String field,
+                          TypeReference<List<ParsedReportPayload.Flora>> type) {
+        try {
+            if (section.has(field) && section.get(field).isArray()) {
+                setter.accept(objectMapper.convertValue(section.get(field), type));
+            }
+        } catch (Exception e) {
+            log.warn("菌群字段 {} 转换失败,跳过: {}", field, e.getMessage());
+        }
+    }
+
+    private JsonNode opencodeSection(String pdfText, String fileName, String instruction, String schema) {
+        return opencodeSection(pdfText, fileName, instruction, schema, false);
+    }
+
+    /**
+     * 单轮分块解析:新建 session、发送单个提示词、校验返回为合法 JSON。
+     * 若第一轮输出被截断/非法,重试一次并指示精简输出(去掉空字段、用紧凑格式)。
+     * compactFirst=true 时首轮即要求精简(用于数据量大的菌群块,避免首轮就超预算)。
+     */
+    private JsonNode opencodeSection(String pdfText, String fileName, String instruction, String schema, boolean compactFirst) {
+        String prompt = buildSectionPrompt(pdfText, fileName, instruction, schema, compactFirst);
+        JsonNode node = sendOnceAndParse(prompt);
+        if (node != null) {
+            return node;
+        }
+        String retryPrompt = buildSectionPrompt(pdfText, fileName, instruction, schema, true);
+        return sendOnceAndParse(retryPrompt);
+    }
+
+    private String buildSectionPrompt(String pdfText, String fileName, String instruction, String schema, boolean compact) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("下面是健康检测报告(文件名:").append(fileName != null ? fileName : "未知")
+                .append(")用 pdftotext 提取出的全文文本。").append(instruction)
+                .append(",仅返回严格符合以下结构的 JSON(不要任何额外文字或 Markdown 包裹):\n")
+                .append(schema).append('\n');
+        if (compact) {
+            sb.append("要求:1) 省略所有空字段(值为空或 null 的字段不要输出);2) 数值用紧凑格式;3) 每种数组最多返回 40 条(超出的按重要性取前 40 条);4) 不要省略合法数据。\n");
+        }
+        sb.append("报告全文文本如下:\n").append(pdfText).append('\n')
+                .append("若无法提取某部分数据返回空数组或 null。");
+        return sb.toString();
+    }
+
+    private JsonNode sendOnceAndParse(String prompt) {
+        String sessionId = opencodeCreateSession();
+        try {
+            String reply = opencodeSendAndWait(sessionId, prompt);
+            if (reply == null || reply.trim().isEmpty()) {
+                return null;
+            }
+            String json = extractJson(reply);
+            return objectMapper.readTree(json);
+        } catch (Exception e) {
+            log.warn("opencode 分块输出转载荷失败: {}", e.getMessage());
+            return null;
+        } finally {
+            deleteSession(sessionId);
+        }
+    }
+
+    private void deleteSession(String sessionId) {
+        try {
+            restTemplate.exchange(opencodeBase + "/session/" + sessionId,
+                    HttpMethod.DELETE, new HttpEntity<>(opencodeHeaders()), Void.class);
+        } catch (Exception e) {
+            log.debug("opencode 删除会话失败 sessionId={}: {}", sessionId, e.getMessage());
+        }
+    }
+
+    /** 用 pdftotext 提取 PDF 文本,失败时返回可读提示(避免模型误读图片型 PDF) */
+    private String extractPdfText(String pdfPath) {
+        try {
+            File file = new File(pdfPath);
+            if (!file.exists() || !file.isFile()) {
+                return "PDF 文件不存在或不是文件:" + pdfPath;
+            }
+            ProcessBuilder pb = new ProcessBuilder("pdftotext", "-layout", pdfPath, "-");
+            pb.redirectErrorStream(true);
+            Process process = pb.start();
+            StringBuilder sb = new StringBuilder();
+            try (BufferedReader reader = new BufferedReader(
+                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
+                String line;
+                while ((line = reader.readLine()) != null) {
+                    sb.append(line).append('\n');
+                }
+            }
+            if (!process.waitFor(30, TimeUnit.SECONDS)) {
+                process.destroyForcibly();
+                log.warn("pdftotext 超时 pdfPath={}", pdfPath);
+                return "PDF 文本提取超时。" + pdfPath;
+            }
+            String text = sb.toString();
+            if (text.trim().isEmpty()) {
+                return "该 PDF 可能为扫描图片,无可用文本。" + pdfPath;
+            }
+            // 控制提示词体积:仅保留前 60k 字符,超长截断
+            return text.length() > 60000 ? text.substring(0, 60000) : text;
+        } catch (Exception e) {
+            log.warn("pdftotext 提取失败 pdfPath={}: {}", pdfPath, e.getMessage());
+            return "PDF 文本提取失败:" + e.getMessage();
+        }
+    }
+
+    /** 从回复文本中提取 JSON(容忍 code fence 或前导说明) */
+    private String extractJson(String reply) {
+        String s = reply.trim();
+        int start = s.indexOf('{');
+        int end = s.lastIndexOf('}');
+        if (start >= 0 && end > start) {
+            return s.substring(start, end + 1);
+        }
+        return s;
+    }
+
+    /** 采集完成后自动入库(复用 confirm 的入库逻辑) */
+    private void insertReport(HealthReportDraft draft, ParsedReportPayload.Payload payload) {
+        Long subjectId = null;
+        if (draft.getFamilyId() != null && payload.getSummary() != null
+                && payload.getSummary().getPersonName() != null) {
+            subjectId = healthReportService.matchFamilyMemberByName(
+                    payload.getSummary().getPersonName(), draft.getFamilyId());
+        }
+        // 兜底:PDF 未提取到姓名或姓名无法匹配到成员时,回退用户上传时选择的成员(draft.member_id)。
+        // 旧逻辑忽略 draft.memberId 导致 subject_id 落空(报告无成员名、成员视角列表不可见、
+        // 食材推荐无法重算)——家庭72 报告63 案例(PDF 无姓名,draft.member_id=27)。
+        if (subjectId == null && draft.getMemberId() != null) {
+            subjectId = draft.getMemberId();
+        }
+
+        HealthReport report = buildReportFromPayload(draft, payload, subjectId);
+        List<HealthIndicator> indicators = buildIndicatorsFromPayload(payload);
+        List<HealthGutFlora> gutFlora = buildGutFloraFromPayload(payload);
+        List<HealthDiseaseRisk> diseaseRisks = buildDiseaseRisksFromPayload(payload);
+
+        HealthReport created = healthReportService.createReport(report, indicators, gutFlora, diseaseRisks);
+
+        try {
+            healthReportService.savePayloadSnapshot(created.getId(), draft.getUserId(), "create", null,
+                    objectMapper.writeValueAsString(payload));
+        } catch (Exception e) {
+            log.warn("保存载荷快照失败 reportId={}", created.getId(), e);
+        }
+
+        if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
+            try {
+                List<Food> foods = buildFoodsFromPayload(payload);
+                foodService.saveFoodsForReport(created.getId(), foods);
+            } catch (Exception e) {
+                log.warn("保存食材推荐失败 reportId={}", created.getId(), e);
+            }
+        }
+
+        // 下游统一使用归一化后的成员卡 id(created.subject_id 已由 resolveSubjectToMemberId 归一为
+        // family_members.id 口径),保证 bindReportToMember / 维度刷新 / 食材重算与报告归属一致。
+        // 旧逻辑传原始 subjectId(可能仍是 users.id 语义,如 draft.member_id=27),导致 getLatestReport
+        // 查不到报告(subject_id 已归一为成员卡 84)而误清空食材推荐——家庭72 报告63 案例。
+        Long memberCardId = created.getSubjectId() != null ? created.getSubjectId() : subjectId;
+        if (memberCardId != null) {
+            healthReportService.bindReportToMember(created.getId(), memberCardId);
+            try {
+                dimensionScoreService.refreshFromGutReport(memberCardId, created.getId());
+            } catch (Exception e) {
+                log.warn("刷新7维健康评分失败 memberId={}", memberCardId, e);
+            }
+            try {
+                healthReportService.refreshMemberIndicatorCurrent(memberCardId, created.getId());
+                log.info("已刷新成员{}的指标当前值diff", memberCardId);
+            } catch (Exception e) {
+                log.warn("刷新指标当前值diff失败 memberId={}", memberCardId, e);
+            }
+            try {
+                foodRecommendService.recalculateForUser(memberCardId);
+            } catch (Exception e) {
+                log.warn("刷新食材推荐指数失败 memberId={}", memberCardId, e);
+            }
+        }
+
+        try {
+            reportBlockService.save(created.getReportType(), created.getId(),
+                    reportBlockAssembler.assembleWithTemplate(created.getReportType(), payload));
+        } catch (Exception e) {
+            log.warn("保存展示块失败 reportId={}", created.getId(), e);
+        }
+
+        // 归一化管道:统一指标层幂等写入(同流程,subjectId 非空才有效)
+        try {
+            normalizeIndicatorPipeline.processReport(created, payload);
+        } catch (Exception e) {
+            log.warn("归一化管道写入失败 reportId={}: {}", created.getId(), e.getMessage());
+        }
+
+        healthReportDraftService.markCollectCompleted(draft.getId(), created.getId());
+
+        // 新手任务联动:完成首次报告上传任务(老用户无任务记录时静默跳过)
+        try { taskService.completeOnboardingTask(draft.getUserId(), "REPORT_UPLOAD"); } catch (Exception e) { log.warn("新手任务 REPORT_UPLOAD 完成失败: {}", e.getMessage()); }
+    }
+
+    private HealthReport buildReportFromPayload(HealthReportDraft draft, ParsedReportPayload.Payload payload, Long subjectId) {
+        HealthReport report = new HealthReport();
+        report.setUserId(draft.getUserId());
+        report.setFamilyId(draft.getFamilyId());
+        // A方案:subject_id 统一为 family_members.id 口径(users.id 归一化到成员卡)
+        report.setSubjectId(healthReportService.resolveSubjectToMemberId(subjectId, draft.getFamilyId()));
+        report.setReportType(draft.getReportType());
+        report.setFileUrl(draft.getFileUrl());
+        report.setFileHash(draft.getFileHash());
+
+        ParsedReportPayload.Summary s = payload.getSummary();
+        if (s != null) {
+            report.setOverallScore(s.getOverallScore());
+            report.setGutHealthScore(s.getGutHealthScore());
+            report.setChronicDiseaseScore(s.getChronicDiseaseScore());
+            report.setNutritionScore(s.getNutritionScore());
+            report.setBalanceScore(s.getBalanceScore());
+            report.setDiversityScore(s.getDiversityScore());
+            report.setBeneficialScore(s.getBeneficialScore());
+            report.setHarmfulScore(s.getHarmfulScore());
+            report.setCoreGenusScore(s.getCoreGenusScore());
+            report.setGutAge(s.getGutAge());
+            report.setGutType(s.getGutType());
+            report.setGutStatusLevel(s.getGutStatusLevel());
+            report.setShannonIndex(s.getShannonIndex());
+            report.setReportNumber(s.getReportNumber());
+            report.setPersonName(s.getPersonName());
+            report.setReportDate(parseDate(s.getReportDate()));
+        }
+        // personName 回填:PDF 未提取到姓名(空)但已解析出 subject(draft.memberId 兜底)时,
+        // 从成员档案回填昵称,避免报告无成员名(家庭72 报告63 案例)。
+        if ((report.getPersonName() == null || report.getPersonName().trim().isEmpty())
+                && report.getSubjectId() != null) {
+            String subjectName = healthReportService.resolveSubjectName(report.getSubjectId(), draft.getFamilyId());
+            if (subjectName != null && !subjectName.isEmpty()) {
+                report.setPersonName(subjectName);
+            }
+        }
+        if (report.getReportDate() == null) {
+            report.setReportDate(new Date());
+        }
+        report.setRemark("异步采集自动入库");
+        return report;
+    }
+
+    private Date parseDate(String dateStr) {
+        if (dateStr == null || dateStr.isEmpty()) {
+            return null;
+        }
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+            return sdf.parse(dateStr);
+        } catch (Exception e) {
+            try {
+                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
+                return sdf2.parse(dateStr);
+            } catch (Exception e2) {
+                return null;
+            }
+        }
+    }
+
+    private List<HealthIndicator> buildIndicatorsFromPayload(ParsedReportPayload.Payload payload) {
+        List<ParsedReportPayload.Indicator> list = payload.getIndicators();
+        if (list == null || list.isEmpty()) return new ArrayList<>();
+        List<HealthIndicator> indicators = new ArrayList<>();
+        for (int i = 0; i < list.size(); i++) {
+            ParsedReportPayload.Indicator pi = list.get(i);
+            HealthIndicator ind = new HealthIndicator();
+            ind.setCategory(pi.getCategory());
+            ind.setIndicatorName(pi.getIndicatorName());
+            ind.setIndicatorValue(pi.getIndicatorValue());
+            ind.setUnit(pi.getUnit());
+            ind.setRefRange(pi.getRefRange());
+            ind.setStatus(pi.getStatus());
+            ind.setSymptoms(pi.getSymptoms());
+            ind.setSortOrder(i);
+            ind.setCollectionDate(parseDate(pi.getCollectionDate()));
+            indicators.add(ind);
+        }
+        return indicators;
+    }
+
+    private List<HealthGutFlora> buildGutFloraFromPayload(ParsedReportPayload.Payload payload) {
+        List<HealthGutFlora> result = new ArrayList<>();
+        addFloraList(result, payload.getGutFlora());
+        addFloraList(result, payload.getProbioticSpecies());
+        addFloraList(result, payload.getTaxonomyClass());
+        addFloraList(result, payload.getTaxonomyOrder());
+        addFloraList(result, payload.getTaxonomyFamily());
+        addFloraList(result, payload.getTaxonomyGenus());
+        addFloraList(result, payload.getTaxonomySpecies());
+        addFloraList(result, payload.getPathogenGenus());
+        addFloraList(result, payload.getPathogenDetection());
+        return result;
+    }
+
+    private void addFloraList(List<HealthGutFlora> target, List<ParsedReportPayload.Flora> source) {
+        if (source != null) {
+            for (ParsedReportPayload.Flora pf : source) {
+                String bacteriaName = pf.getBacteriaName();
+                if (bacteriaName == null || bacteriaName.trim().isEmpty()) {
+                    log.warn("跳过无菌种名称的菌群数据(category={}),避免 NOT NULL 约束冲突", pf.getCategory());
+                    continue;
+                }
+                HealthGutFlora gf = new HealthGutFlora();
+                gf.setBacteriaName(bacteriaName);
+                gf.setBacteriaValue(pf.getBacteriaValue());
+                gf.setNormalRange(pf.getNormalRange());
+                gf.setPopulationLevel(pf.getPopulationLevel());
+                gf.setDetectionRate(pf.getDetectionRate());
+                gf.setDescription(pf.getDescription());
+                gf.setCategory(normalizeFloraCategory(pf.getCategory()));
+                gf.setLevel(normalizeFloraLevel(pf.getCategory(), pf.getLevel()));
+                target.add(gf);
+            }
+        }
+    }
+
+    private String normalizeFloraCategory(String category) {
+        if (category == null) return null;
+        if (category.endsWith("构成")) {
+            return HealthGutFlora.CATEGORY_TAXONOMY;
+        }
+        return category;
+    }
+
+    private String normalizeFloraLevel(String category, String level) {
+        if (level == null) return null;
+        String normalized = level;
+        if ("门".equals(level)) normalized = HealthGutFlora.LEVEL_PHYLUM;
+        else if ("纲".equals(level)) normalized = HealthGutFlora.LEVEL_CLASS;
+        else if ("目".equals(level)) normalized = HealthGutFlora.LEVEL_ORDER;
+        else if ("科".equals(level)) normalized = HealthGutFlora.LEVEL_FAMILY;
+        else if ("属".equals(level)) normalized = HealthGutFlora.LEVEL_GENUS;
+        else if ("种".equals(level)) normalized = HealthGutFlora.LEVEL_SPECIES;
+        return normalized;
+    }
+
+    private List<HealthDiseaseRisk> buildDiseaseRisksFromPayload(ParsedReportPayload.Payload payload) {
+        List<ParsedReportPayload.DiseaseRisk> list = payload.getDiseaseRisks();
+        if (list == null || list.isEmpty()) return new ArrayList<>();
+        List<HealthDiseaseRisk> risks = new ArrayList<>();
+        for (ParsedReportPayload.DiseaseRisk pr : list) {
+            HealthDiseaseRisk dr = new HealthDiseaseRisk();
+            dr.setDiseaseName(pr.getDiseaseName());
+            dr.setRiskValue(pr.getRiskValue());
+            dr.setRiskLevel(pr.getRiskLevel());
+            if (pr.getRelatedBacteria() != null && !pr.getRelatedBacteria().isEmpty()) {
+                try {
+                    dr.setRelatedBacteria(objectMapper.writeValueAsString(pr.getRelatedBacteria()));
+                } catch (Exception e) {
+                    log.warn("序列化相关菌失败: {}", e.getMessage());
+                }
+            }
+            risks.add(dr);
+        }
+        return risks;
+    }
+
+    private List<Food> buildFoodsFromPayload(ParsedReportPayload.Payload payload) {
+        List<ParsedReportPayload.FoodItem> list = payload.getFoods();
+        if (list == null || list.isEmpty()) return new ArrayList<>();
+        List<Food> foods = new ArrayList<>();
+        for (ParsedReportPayload.FoodItem pf : list) {
+            if (pf == null || pf.getName() == null || pf.getName().trim().isEmpty()) {
+                log.warn("跳过无效食材条目(元素为空或缺少名称)");
+                continue;
+            }
+            Food food = new Food();
+            food.setName(pf.getName());
+            food.setCategory(pf.getCategory());
+            food.setScore(pf.getScore());
+            food.setEnergyKj(pf.getEnergyKj());
+            food.setProtein(pf.getProtein());
+            food.setFat(pf.getFat());
+            food.setCarbs(pf.getCarbs());
+            food.setStarch(pf.getStarch());
+            food.setFiber(pf.getFiber());
+            food.setCholesterol(pf.getCholesterol());
+            food.setStatus("recommended");
+            foods.add(food);
+        }
+        return foods;
+    }
+
+    /**
+     * 重新解析指定健康报告并回填食材推荐。
+     * 先删除旧 foods 再插入(幂等),解析成功后仅覆盖 payload_json 的 foods 键(其他键不变),
+     * 解析失败则保留旧载荷并抛 IllegalStateException。
+     *
+     * @return 本次落库的食材条数
+     */
+    public int reparseReportFoods(Long reportId) {
+        HealthReport report = healthReportService.getReportById(reportId);
+        if (report == null) {
+            throw new IllegalArgumentException("报告不存在: " + reportId);
+        }
+        String pdfPath = storageService.getFilePath(report.getFileUrl());
+        File f = new File(pdfPath);
+        if (!f.exists()) {
+            throw new IllegalStateException("报告文件不存在: " + pdfPath);
+        }
+        LangGraphReportParseService.ParseOutcome outcome =
+                langGraphReportParseService.parseByScriptWithReason(pdfPath, null);
+        ParsedReportPayload.Payload payload = outcome != null ? outcome.getPayload() : null;
+        if (payload == null) {
+            String reason = outcome != null && outcome.getError() != null ? outcome.getError() : "解析结果为空";
+            throw new IllegalStateException("重新解析失败: " + reason);
+        }
+        List<Food> foods = buildFoodsFromPayload(payload);
+        foodService.saveFoodsForReport(reportId, foods);
+
+        // 仅合并 foods 键到原 payload_json,不覆盖其他键;失败时保留旧载荷
+        try {
+            JsonNode root = objectMapper.readTree(report.getPayloadJson());
+            if (root != null && root.isObject()) {
+                ((ObjectNode) root).set("foods", objectMapper.valueToTree(payload.getFoods()));
+                healthReportService.updatePayloadJson(reportId, objectMapper.writeValueAsString(root));
+            }
+        } catch (Exception e) {
+            log.warn("合并 foods 到 payload_json 失败 reportId={}: {}", reportId, e.getMessage());
+        }
+
+        // 刷新食材推荐指数(优先以报告主体成员为准,其次上传用户)
+        try {
+            Long recalcUserId = report.getSubjectId() != null ? report.getSubjectId() : report.getUserId();
+            if (recalcUserId != null) {
+                foodRecommendService.recalculateForUser(recalcUserId);
+            }
+        } catch (Exception e) {
+            log.warn("刷新食材推荐指数失败 reportId={}: {}", reportId, e.getMessage());
+        }
+
+        return foods.size();
+    }
+
+    // ===== opencode 本地服务 HTTP 客户端(协议对齐 运营文案/opencode_client.py) =====
+
+    private String opencodeCreateSession() {
+        try {
+            String url = opencodeBase + "/session?directory="
+                    + java.net.URLEncoder.encode(opencodeWorkdir, StandardCharsets.UTF_8.name());
+            Map<String, Object> body = new LinkedHashMap<>();
+            body.put("title", "report-collect-" + System.currentTimeMillis());
+            body.put("agent", "report-collect");
+            // 显式固定模型(Provider/Model id 在 body 中传递,服务端才尊重;query 参数会被忽略)
+            Map<String, Object> model = new LinkedHashMap<>();
+            model.put("id", opencodeModelId);
+            model.put("providerID", opencodeModelProvider);
+            body.put("model", model);
+            ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.POST,
+                    new HttpEntity<>(body, opencodeHeaders()), Map.class);
+            Map<?, ?> data = resp.getBody();
+            if (data == null || data.get("id") == null) {
+                throw new IllegalStateException("opencode 创建会话未返回 session_id");
+            }
+            return data.get("id").toString();
+        } catch (Exception e) {
+            throw new IllegalStateException("opencode 创建会话失败: " + e.getMessage(), e);
+        }
+    }
+
+    /** 发送提示词并轮询取回 assistant 最终文本回复 */
+    private String opencodeSendAndWait(String sessionId, String prompt) {
+        HttpHeaders headers = opencodeHeaders();
+        List<Map<String, Object>> parts = new ArrayList<>();
+        Map<String, Object> part = new LinkedHashMap<>();
+        part.put("type", "text");
+        part.put("text", prompt);
+        parts.add(part);
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("parts", parts);
+        body.put("agent", "report-collect");
+        // 只读约束:仅允许分析/读取,禁用执行/写入类工具(与本地运营脚本对齐)
+        Map<String, Object> tools = new LinkedHashMap<>();
+        for (String t : new String[]{"bash", "shell", "write", "edit", "apply_patch",
+                "task", "dispatch", "webfetch_post", "chrome_launch"}) {
+            tools.put(t, Boolean.FALSE);
+        }
+        body.put("tools", tools);
+        restTemplate.exchange(opencodeBase + "/session/" + sessionId + "/prompt_async",
+                HttpMethod.POST, new HttpEntity<>(body, headers), Void.class);
+
+        long deadline = System.currentTimeMillis() + 180000;
+        long pollInterval = 5000;
+        int before = countMessages(sessionId);
+        while (System.currentTimeMillis() < deadline) {
+            try {
+                Thread.sleep(pollInterval);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                return null;
+            }
+            List<Map<String, Object>> msgs = listMessages(sessionId);
+            if (msgs == null || msgs.isEmpty()) {
+                continue;
+            }
+            Map<String, Object> last = msgs.get(msgs.size() - 1);
+            String role = roleOf(last);
+            if ("assistant".equals(role)) {
+                String text = lastAssistantText(last);
+                if (text != null && !text.trim().isEmpty()) {
+                    return text;
+                }
+            }
+            if (msgs.size() > before) {
+                for (int i = msgs.size() - 1; i >= 0; i--) {
+                    String r = roleOf(msgs.get(i));
+                    if ("assistant".equals(r)) {
+                        String t = lastAssistantText(msgs.get(i));
+                        if (t != null && !t.trim().isEmpty()) {
+                            return t;
+                        }
+                    }
+                }
+            }
+        }
+        throw new IllegalStateException("等待 opencode 回复超时(180s)");
+    }
+
+    @SuppressWarnings("unchecked")
+    private String roleOf(Map<String, Object> msg) {
+        Map<String, Object> info = (Map<String, Object>) msg.get("info");
+        return info != null ? (String) info.get("role") : null;
+    }
+
+    @SuppressWarnings("unchecked")
+    private String lastAssistantText(Map<String, Object> msg) {
+        Object partsObj = msg.get("parts");
+        if (!(partsObj instanceof List)) return null;
+        List<Object> parts = (List<Object>) partsObj;
+        String text = null;
+        for (Object pObj : parts) {
+            if (pObj instanceof Map) {
+                Map<String, Object> p = (Map<String, Object>) pObj;
+                if ("text".equals(p.get("type")) && p.get("text") != null) {
+                    text = p.get("text").toString();
+                }
+            }
+        }
+        return text;
+    }
+
+    private int countMessages(String sessionId) {
+        List<Map<String, Object>> msgs = listMessages(sessionId);
+        return msgs == null ? 0 : msgs.size();
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Map<String, Object>> listMessages(String sessionId) {
+        try {
+            ResponseEntity<List> resp = restTemplate.exchange(
+                    opencodeBase + "/session/" + sessionId + "/message",
+                    HttpMethod.GET, new HttpEntity<>(opencodeHeaders()), List.class);
+            return resp.getBody();
+        } catch (Exception e) {
+            log.warn("opencode 查询消息失败 session={}", sessionId, e);
+            return null;
+        }
+    }
+
+    private HttpHeaders opencodeHeaders() {
+        String token = Base64.getEncoder().encodeToString(
+                (opencodeUser + ":" + opencodePassword).getBytes(StandardCharsets.UTF_8));
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        headers.set("Authorization", "Basic " + token);
+        return headers;
+    }
+
+    // ======================== 采集指标完整性校验(report_type_registry.expected_indicators 定义驱动) ========================
+
+    /**
+     * 健康(GUT/混检)管道校验入口:汇总 payload 中全部可采集指标名称后按定义比对
+     */
+    private boolean runCollectValidation(Long draftId, String typeId, ParsedReportPayload.Payload payload) {
+        return runCollectValidation(draftId, typeId, collectHealthNames(payload), null);
+    }
+
+    /**
+     * 健康管道校验入口(携带 guhe_v2 解析自检块):_解析自检 四子键随 collects 结果
+     * 透传并入 collect_validation JSON(P0-3 ③)。
+     */
+    private boolean runCollectValidation(Long draftId, String typeId, ParsedReportPayload.Payload payload,
+                                         Map<String, Object> parseSelfCheck) {
+        return runCollectValidation(draftId, typeId, collectHealthNames(payload), parseSelfCheck);
+    }
+
+    /**
+     * DAN 管道校验入口:汇总解析 items 的 name/code 后按定义比对
+     */
+    private boolean runCollectValidation(Long draftId, String typeId, DanReportParseService.DanParsedReport parsed) {
+        Set<String> names = new HashSet<>();
+        if (parsed != null && parsed.getItems() != null) {
+            for (DanReportParseService.DataItem item : parsed.getItems()) {
+                addCollectName(names, item.getName());
+                addCollectName(names, item.getCode());
+            }
+        }
+        return runCollectValidation(draftId, typeId, names, null);
+    }
+
+    /**
+     * 采集完整性校验:按 report_type_registry.expected_indicators 定义,校验本次采集结果是否覆盖应采集指标项。
+     * 该类型无指标项定义(expected_indicators 为空 / 类型未注册)时跳过,不影响采集主流程。
+     * 结果 JSON(typeId/expected/matched/pass/missing)写入草稿 collect_validation,缺失项记入 WARN 日志。
+     * guhe_v2 解析自检块存在时,额外以 {@code _解析自检} 子对象并入同一 JSON(P0-3 ③)。
+     */
+    private boolean runCollectValidation(Long draftId, String typeId, Set<String> collectedNames) {
+        return runCollectValidation(draftId, typeId, collectedNames, null);
+    }
+
+    private boolean runCollectValidation(Long draftId, String typeId, Set<String> collectedNames,
+                                         Map<String, Object> parseSelfCheck) {
+        if (draftId == null || typeId == null || collectedNames == null || collectedNames.isEmpty()) {
+            return true;
+        }
+        List<String> expected = loadExpectedIndicators(typeId);
+        if (expected == null || expected.isEmpty()) {
+            return true;
+        }
+        // 肠道菌群家族:肠道预测年龄/肠型 为摘要增强字段,部分报告(如体检型菌群检测)不输出,
+        // 缺失不阻断入库,避免合法报告因缺少增强字段卡在草稿
+        if (isGutFloraType(typeId)) {
+            expected.removeAll(GUT_FLORA_OPTIONAL_INDICATORS);
+        }
+        List<String> missing = new ArrayList<>();
+        int matched = 0;
+        for (String exp : expected) {
+            if (indicatorMatches(exp, collectedNames)) {
+                matched++;
+            } else {
+                missing.add(exp);
+            }
+        }
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("typeId", typeId);
+        result.put("expected", expected.size());
+        result.put("matched", matched);
+        result.put("pass", missing.isEmpty());
+        result.put("missing", missing.size() > 20 ? missing.subList(0, 20) : missing);
+        attachParseSelfCheck(result, parseSelfCheck);
+        try {
+            healthReportDraftService.updateCollectValidation(draftId, objectMapper.writeValueAsString(result));
+            if (missing.isEmpty()) {
+                log.info("采集校验通过 draftId={}, typeId={}, expected={}", draftId, typeId, expected.size());
+            } else {
+                log.warn("采集校验未通过 draftId={}, typeId={}, matched={}/{}, 缺失[{}]",
+                        draftId, typeId, matched, expected.size(), String.join(", ", missing));
+            }
+        } catch (Exception e) {
+            log.warn("记录采集校验结果失败 draftId={}, typeId={}", draftId, typeId, e);
+        }
+        return missing.isEmpty();
+    }
+
+    /**
+     * P0-3 ③:将 guhe_v2 解析自检({@code _解析自检})四子键(通过/P0告警数/P1提示数/告警)
+     * 透传并入 collect_validation JSON。仅复制契约声明的四个子键,避免把上游无关字段混入。
+     */
+    private void attachParseSelfCheck(Map<String, Object> collectValidation, Map<String, Object> parseSelfCheck) {
+        if (collectValidation == null || parseSelfCheck == null || parseSelfCheck.isEmpty()) {
+            return;
+        }
+        Map<String, Object> selfCheck = new LinkedHashMap<>();
+        for (String key : SELF_CHECK_KEYS) {
+            if (parseSelfCheck.containsKey(key)) {
+                selfCheck.put(key, parseSelfCheck.get(key));
+            }
+        }
+        if (!selfCheck.isEmpty()) {
+            collectValidation.put(PARSE_SELF_CHECK_KEY, selfCheck);
+        }
+    }
+
+    /** 肠道菌群家族校验可选指标(report_type_registry.expected_indicators 中缺失不阻断入库) */
+    private static final Set<String> GUT_FLORA_OPTIONAL_INDICATORS =
+            new HashSet<>(Arrays.asList("肠道预测年龄", "肠型"));
+
+    /** 是否为肠道菌群家族类型(report_type_registry.family = gut_flora) */
+    private boolean isGutFloraType(String typeId) {
+        if (typeId == null) {
+            return false;
+        }
+        ReportTypeRegistry registry = reportTypeRegistryMapper.selectOne(
+                new LambdaQueryWrapper<ReportTypeRegistry>()
+                        .eq(ReportTypeRegistry::getTypeId, typeId)
+                        .last("LIMIT 1"));
+        return registry != null && "gut_flora".equals(registry.getFamily());
+    }
+
+    /** 菌群实质数据判定:菌群检出列表或指标清单至少一项非空 */
+    private boolean hasGutContent(ParsedReportPayload.Payload payload) {
+        return payload != null
+                && ((payload.getGutFlora() != null && !payload.getGutFlora().isEmpty())
+                        || (payload.getIndicators() != null && !payload.getIndicators().isEmpty()));
+    }
+
+    /** 读取类型指标项定义(report_type_registry.expected_indicators JSON 数组);未定义返回 null */
+    private List<String> loadExpectedIndicators(String typeId) {
+        try {
+            ReportTypeRegistry registry = reportTypeRegistryMapper.selectOne(
+                    new LambdaQueryWrapper<ReportTypeRegistry>()
+                            .eq(ReportTypeRegistry::getTypeId, typeId)
+                            .last("LIMIT 1"));
+            if (registry == null || registry.getExpectedIndicators() == null
+                    || registry.getExpectedIndicators().isEmpty()) {
+                return null;
+            }
+            return objectMapper.readValue(registry.getExpectedIndicators(),
+                    new TypeReference<List<String>>() {});
+        } catch (Exception e) {
+            log.warn("读取类型指标项定义失败 typeId={}", typeId, e);
+            return null;
+        }
+    }
+
+    /** 健康管道:汇总 payload 中全部可采集指标名称(含区块信号),用于与定义比对 */
+    private Set<String> collectHealthNames(ParsedReportPayload.Payload payload) {
+        Set<String> names = new HashSet<>();
+        if (payload == null) {
+            return names;
+        }
+        ParsedReportPayload.Summary s = payload.getSummary();
+        if (s != null) {
+            addMappedName(names, "健康总分", s.getOverallScore());
+            addMappedName(names, "菌群健康", s.getGutHealthScore());
+            addMappedName(names, "慢病控制", s.getChronicDiseaseScore());
+            addMappedName(names, "营养均衡", s.getNutritionScore());
+            addMappedName(names, "肠道菌群平衡", s.getBalanceScore());
+            addMappedName(names, "菌群多样性", s.getDiversityScore());
+            addMappedName(names, "有益菌", s.getBeneficialScore());
+            addMappedName(names, "有害菌", s.getHarmfulScore());
+            addMappedName(names, "核心菌属", s.getCoreGenusScore());
+            addMappedName(names, "肠道预测年龄", s.getGutAge());
+            addMappedName(names, "肠型", s.getGutType());
+            addMappedName(names, "菌群多样性", s.getShannonIndex());
+        }
+        if (payload.getIndicators() != null) {
+            for (ParsedReportPayload.Indicator ind : payload.getIndicators()) {
+                addCollectName(names, ind.getIndicatorName());
+                addCollectName(names, ind.getCategory());
+                addHealthBlockSignals(names, ind.getIndicatorName(), ind.getCategory());
+            }
+        }
+        addFloraNames(names, payload.getGutFlora());
+        addFloraNames(names, payload.getProbioticSpecies());
+        addFloraNames(names, payload.getPathogenGenus());
+        addFloraNames(names, payload.getPathogenDetection());
+        addFloraNames(names, payload.getTaxonomyClass());
+        addFloraNames(names, payload.getTaxonomyOrder());
+        addFloraNames(names, payload.getTaxonomyFamily());
+        addFloraNames(names, payload.getTaxonomyGenus());
+        addFloraNames(names, payload.getTaxonomySpecies());
+        if (hasFlora(payload)) {
+            names.add("菌群检出详细列表");
+        }
+        if (payload.getDiseaseRisks() != null && !payload.getDiseaseRisks().isEmpty()) {
+            names.add("疾病风险评估");
+            for (ParsedReportPayload.DiseaseRisk dr : payload.getDiseaseRisks()) {
+                addCollectName(names, dr.getDiseaseName());
+            }
+        }
+        if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
+            names.add("个体化食物推荐表");
+            for (ParsedReportPayload.FoodItem f : payload.getFoods()) {
+                addCollectName(names, f.getName());
+            }
+        }
+        return names;
+    }
+
+    private boolean hasFlora(ParsedReportPayload.Payload payload) {
+        return payload != null && (isNotEmpty(payload.getGutFlora()) || isNotEmpty(payload.getProbioticSpecies())
+                || isNotEmpty(payload.getPathogenGenus()) || isNotEmpty(payload.getPathogenDetection())
+                || isNotEmpty(payload.getTaxonomyClass()) || isNotEmpty(payload.getTaxonomyOrder())
+                || isNotEmpty(payload.getTaxonomyFamily()) || isNotEmpty(payload.getTaxonomyGenus())
+                || isNotEmpty(payload.getTaxonomySpecies()));
+    }
+
+    private boolean isNotEmpty(List<?> list) {
+        return list != null && !list.isEmpty();
+    }
+
+    private void addFloraNames(Set<String> names, List<ParsedReportPayload.Flora> flora) {
+        if (flora == null) {
+            return;
+        }
+        for (ParsedReportPayload.Flora f : flora) {
+            addCollectName(names, f.getBacteriaName());
+            addCollectName(names, f.getCategory());
+        }
+    }
+
+    /** 菌群报告区块归类:指标名/分类命中关键词 → 记入对应区块信号(容忍「区块名 vs 条目名」表述差异,如 短链脂肪酸 vs 丁酸) */
+    private static final String[][] HEALTH_BLOCK_KEYWORDS = {
+        {"主要营养评估", "碳水化合物", "蛋白质", "脂肪", "纤维素", "乳制品"},
+        {"氨基酸评估", "氨基酸"},
+        {"维生素评估", "维生素"},
+        {"微量元素评估", "微量元素", "铁", "锌"},
+        {"主要消化道致病菌", "致病菌", "幽门螺杆菌"},
+        {"抗生素风险评估", "抗生素"},
+        {"肠道屏障及代谢物", "屏障", "渗透"},
+        {"短链脂肪酸", "短链脂肪酸", "丁酸", "乙酸", "丙酸"},
+        {"神经递质及激素", "神经递质", "血清素", "多巴胺", "5-羟色胺", "激素"},
+        {"肠道微生物健康指数", "微生物健康指数"},
+        {"肠道菌群平衡评估", "菌群平衡"},
+        {"肠道黏膜屏障", "黏膜屏障"},
+        {"肠道菌群多样性", "菌群多样性"},
+        {"肠道菌群表型评估", "菌群表型", "表型评估"},
+        {"肠道抗炎能力", "抗炎"},
+        {"肠道免疫力", "免疫"},
+        {"肠道膳食纤维需求", "膳食纤维"},
+        {"短链脂肪酸合成能力", "短链脂肪酸合成"},
+        {"核心菌属综合评分", "核心菌属综合评分", "核心菌属评分"},
+        {"有益菌综合评分", "有益菌综合评分", "有益菌评分"},
+        {"有害菌综合评分", "有害菌综合评分", "有害菌评分"},
+        {"毒性物质清除能力评估", "毒性", "清除能力", "毒素"},
+        {"胃肠道感染病原体评估", "病原体", "感染"},
+        {"趣味肠菌评估", "趣味", "人格", "认知功能", "职场心理"}
+    };
+
+    /** 指标名/分类文本命中区块关键词 → 记入该区块信号名 */
+    private void addHealthBlockSignals(Set<String> names, String... sources) {
+        for (String src : sources) {
+            if (src == null) {
+                continue;
+            }
+            for (String[] pair : HEALTH_BLOCK_KEYWORDS) {
+                for (int k = 1; k < pair.length; k++) {
+                    if (src.contains(pair[k])) {
+                        names.add(pair[0]);
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    /** 名称归一化:去除后缀差异(_pct/_score/百分位/得分 等),中文取核心短语;结果为空则保留原串 */
+    private String normalizeIndicatorName(String s) {
+        if (s == null) {
+            return "";
+        }
+        String t = s.trim();
+        t = t.replaceFirst("(_pct|_score|_小时|_分钟|_min|_max)\\s*$", "");
+        t = t.replaceFirst("(百分位|得分|评估|指数|综合评分|评分)\\s*$", "");
+        if (t.isEmpty()) {
+            t = s.trim();
+        }
+        return t.toLowerCase(Locale.ROOT);
+    }
+
+    /** 提取中文二元组(用于容忍 表面方法与策略 vs 表面策略 类表述差异) */
+    private Set<String> cjkBigrams(String s) {
+        if (s == null || s.isEmpty()) {
+            return Collections.emptySet();
+        }
+        String cjk = s.replaceAll("[^\\u4e00-\\u9fa5]", "");
+        Set<String> set = new HashSet<>();
+        if (cjk.length() == 1) {
+            set.add(cjk);
+            return set;
+        }
+        for (int i = 0; i + 1 < cjk.length(); i++) {
+            set.add(cjk.substring(i, i + 2));
+        }
+        return set;
+    }
+
+    /** 指标匹配:归一化后相等 / 互相包含 / 中文二元组重叠 >= 50% 即视为命中 */
+    private boolean indicatorMatches(String expected, Set<String> collectedNames) {
+        if (expected == null || collectedNames == null || collectedNames.isEmpty()) {
+            return false;
+        }
+        String normExp = normalizeIndicatorName(expected);
+        if (normExp.isEmpty()) {
+            return true;
+        }
+        for (String name : collectedNames) {
+            String norm = normalizeIndicatorName(name);
+            if (norm.isEmpty()) {
+                continue;
+            }
+            if (normExp.equals(norm) || normExp.contains(norm) || norm.contains(normExp)) {
+                return true;
+            }
+            if (cjkBigramOverlap(normExp, norm)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private boolean cjkBigramOverlap(String a, String b) {
+        Set<String> bigramsA = cjkBigrams(a);
+        Set<String> bigramsB = cjkBigrams(b);
+        if (bigramsA.isEmpty() || bigramsB.isEmpty()) {
+            return false;
+        }
+        Set<String> smaller = bigramsA.size() <= bigramsB.size() ? bigramsA : bigramsB;
+        Set<String> larger = bigramsA.size() <= bigramsB.size() ? bigramsB : bigramsA;
+        int hit = 0;
+        for (String bg : smaller) {
+            if (larger.contains(bg)) {
+                hit++;
+            }
+        }
+        return (double) hit / smaller.size() >= 0.5;
+    }
+
+    private void addCollectName(Set<String> names, String raw) {
+        if (raw != null && !raw.trim().isEmpty()) {
+            names.add(raw.trim());
+        }
+    }
+
+    /** 字段值非空信号:字段有值(非 null 非空白)时,把映射名计入已采集集合 */
+    private void addMappedName(Set<String> names, String mappedName, Object value) {
+        if (value == null) {
+            return;
+        }
+        String v = String.valueOf(value).trim();
+        if (!v.isEmpty()) {
+            names.add(mappedName);
+        }
+    }
+}

+ 146 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportDateExtractor.java

@@ -0,0 +1,146 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.mapper.HealthReportMapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 真实报告日期提取 + 历史回填。
+ * PDF 解析阶段将「报告日期/采样日期」写入 payload.reportDate 后,
+ * 入库逻辑(HealthReportService 既有 reportDate 修正)自动生效;
+ * 本类只负责:(1) 从 payload 提取真实日期(供回填/校验);
+ * (2) 扫描旧报告幂等回填 report_date(无法提取置 NULL,不伪装成上传时间)。
+ */
+@Service
+public class ReportDateExtractor {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportDateExtractor.class);
+
+    @Resource
+    private HealthReportMapper healthReportMapper;
+
+    @Resource
+    private ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 从 payload JSON 中提取真实报告日期。
+     * 取值顺序:summary.reportDate → 顶层 reportDate → indicators[].collectionDate(取第一个非空)。
+     * 支持 yyyy-MM-dd / yyyy/MM/dd;无法提取返回 null。
+     */
+    public java.sql.Date extractReportDate(String payloadJson) {
+        if (payloadJson == null || payloadJson.isEmpty()) {
+            return null;
+        }
+        try {
+            JsonNode root = objectMapper.readTree(payloadJson);
+            String dateStr = null;
+            JsonNode summary = root.get("summary");
+            if (summary != null && summary.isObject() && summary.hasNonNull("reportDate")) {
+                dateStr = summary.get("reportDate").asText();
+            }
+            if (dateStr == null || dateStr.trim().isEmpty()) {
+                if (root.hasNonNull("reportDate")) {
+                    dateStr = root.get("reportDate").asText();
+                }
+            }
+            java.sql.Date parsed = parseDate(dateStr);
+            if (parsed != null) {
+                return parsed;
+            }
+            // 回退:indicators[].collectionDate 取第一个非空
+            JsonNode indicators = root.get("indicators");
+            if (indicators != null && indicators.isArray()) {
+                for (JsonNode ind : indicators) {
+                    if (ind.hasNonNull("collectionDate")) {
+                        java.sql.Date d = parseDate(ind.get("collectionDate").asText());
+                        if (d != null) {
+                            return d;
+                        }
+                    }
+                }
+            }
+            return null;
+        } catch (Exception e) {
+            log.warn("ReportDateExtractor 解析 payload 失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private java.sql.Date parseDate(String dateStr) {
+        if (dateStr == null || dateStr.trim().isEmpty()) {
+            return null;
+        }
+        String s = dateStr.trim();
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+            Date d = sdf.parse(s);
+            return new java.sql.Date(d.getTime());
+        } catch (Exception e) {
+            try {
+                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
+                Date d = sdf.parse(s);
+                return new java.sql.Date(d.getTime());
+            } catch (Exception e2) {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * 历史回填:扫描 report_date 缺失或疑似上传时间的旧报告(且 payload 含 reportDate 字段),
+     * 提取真实日期并回填;无法提取置 NULL。分批(500/批)、幂等可重跑。
+     *
+     * @return 本轮处理的总行数
+     */
+    public int backfillHistoricalReports() {
+        int total = 0;
+        long lastId = 0L;
+        while (true) {
+            List<HealthReport> batch = healthReportMapper.selectList(
+                    new LambdaQueryWrapper<HealthReport>()
+                            .isNull(HealthReport::getReportDate)
+                            .like(HealthReport::getPayloadJson, "reportDate")
+                            .gt(HealthReport::getId, lastId)
+                            .orderByAsc(HealthReport::getId)
+                            .last("LIMIT 500"));
+            if (batch.isEmpty()) {
+                break;
+            }
+            for (HealthReport report : batch) {
+                try {
+                    java.sql.Date realDate = extractReportDate(report.getPayloadJson());
+                    if (realDate != null) {
+                        report.setReportDate(realDate);
+                        healthReportMapper.updateById(report);
+                        log.info("回填报告真实日期 reportId={}, reportDate={}", report.getId(), realDate);
+                    }
+                    // 无法提取:保持 report_date 为 NULL(不伪装成上传时间);
+                    // 由 keyset(id) 游标跳过,本轮不再反复处理
+                    total++;
+                } catch (Exception e) {
+                    log.warn("回填报告日期失败 reportId={}: {}", report.getId(), e.getMessage());
+                }
+            }
+            lastId = batch.get(batch.size() - 1).getId();
+        }
+        log.info("ReportDateExtractor 历史回填完成,共处理 {} 行", total);
+        return total;
+    }
+
+    /** 每日 03:10 自动回填(幂等可重跑,连跑两次结果一致) */
+    @Scheduled(cron = "0 10 3 * * ?")
+    public void scheduledBackfill() {
+        backfillHistoricalReports();
+    }
+}

+ 256 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportFeedbackService.java

@@ -0,0 +1,256 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.HealthReportDraft;
+import com.etotem.cfc.entity.ReportFeedback;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.HealthReportDraftMapper;
+import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.ReportFeedbackMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class ReportFeedbackService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportFeedbackService.class);
+
+    /** TC-P-83-E:反馈附件上限 10MB(10 * 1024 * 1024 = 10485760 字节)。 */
+    private static final long MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;
+    private static final String MSG_ATTACHMENT_TOO_LARGE = "附件不超过 10MB";
+
+    @Resource
+    private ReportFeedbackMapper reportFeedbackMapper;
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Resource
+    private FamilyContextService familyContextService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
+
+    @Resource
+    private HealthReportMapper healthReportMapper;
+
+    @Resource
+    private HealthReportDraftMapper healthReportDraftMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /**
+     * 提交报告反馈(持久化 + AI 解答)。
+     * 免费版每日 1 次,付费版不限/多轮(沿用报告快速分析策略)。
+     */
+    public Result<?> submit(Long userId, Long memberId, Long reportId, Long draftId, String type, String content) {
+        return submit(userId, memberId, reportId, draftId, type, content, null, null);
+    }
+
+    /**
+     * 提交报告反馈(含附件载体)。敏感信息脱敏后再送 AI / 落库(TC-P-83-E)。
+     */
+    public Result<?> submit(Long userId, Long memberId, Long reportId, Long draftId, String type, String content,
+                            String attachmentUrl, Long attachmentSize) {
+        if (content == null || content.trim().isEmpty()) {
+            return Result.error("反馈内容不能为空");
+        }
+        content = content.trim();
+        if (content.length() > 500) {
+            return Result.error("反馈内容不能超过500字");
+        }
+        Result<?> attachmentError = checkAttachmentSize(attachmentSize);
+        if (attachmentError != null) {
+            return attachmentError;
+        }
+        // 归一化类型:question=疑问 / suggestion=建议,其他默认 question
+        String normalizedType = "suggestion".equals(type) ? "suggestion" : "question";
+
+        // 1. 会员级别检查
+        User user = userService.getUserInfo(userId);
+
+        // 2. 越权校验:reportId/draftId/memberId 非本用户归属 → 403 拒绝、不落库、不泄露(TC-P-83-P)
+        Result<?> ownershipError = checkOwnership(userId, memberId, reportId, draftId, user);
+        if (ownershipError != null) {
+            return ownershipError;
+        }
+
+        // 3. 免费版 Redis 计数(每日 1 次;Redis 异常时 fail-open 放行)
+        boolean isFree = user == null || user.getMemberLevel() == null || "FREE".equals(user.getMemberLevel());
+        if (isFree) {
+            try {
+                String key = "report:feedback:free:" + userId + ":" + LocalDate.now();
+                Long count = redisTemplate.opsForValue().increment(key);
+                if (count != null && count == 1L) {
+                    redisTemplate.expire(key, Duration.ofDays(1));
+                }
+                if (count != null && count > 1L) {
+                    return Result.error("免费版每日仅限 1 次反馈解答,升级会员解锁更多");
+                }
+            } catch (Exception e) {
+                log.warn("Redis 计数失败,放行: {}", e.getMessage());
+            }
+        }
+
+        // 4. 组装 AI 上下文(指定报告/草稿时注入对应数据)
+        Map<String, Object> inputs;
+        if (reportId != null) {
+            inputs = familyContextService.buildContext(userId, reportId);
+        } else if (draftId != null) {
+            inputs = familyContextService.buildContextFromDraft(userId, draftId);
+        } else {
+            inputs = familyContextService.buildContext(userId);
+        }
+
+        // 5. 敏感信息脱敏(身份证/手机号)后再送 AI,原始敏感串不进入外部链路(TC-P-83-E)
+        String safeContent = maskSensitiveInfo(content);
+
+        // 6. 组装提问(单轮问答;conversationId 留待后续多轮扩展)
+        String query = "【" + ("suggestion".equals(normalizedType) ? "建议" : "疑问") + "】" + safeContent;
+
+        // 7. 调 LangGraph(经 AiGateway,统一熔断/配额/脱敏)
+        Map<String, Object> resp = aiGateway.chat(query, userId, null, inputs);
+
+        // 8. 组装记录(AI 失败也落库,ai_status=failed;content 已脱敏)
+        ReportFeedback record = new ReportFeedback();
+        record.setUserId(userId);
+        record.setMemberId(memberId);
+        record.setReportId(reportId);
+        record.setDraftId(draftId);
+        record.setFeedbackType(normalizedType);
+        record.setContent(safeContent);
+        record.setAttachmentUrl(attachmentUrl);
+        if (resp == null) {
+            record.setAiStatus("failed");
+            record.setAiAnswer(null);
+        } else {
+            record.setAiStatus("answered");
+            record.setAiAnswer((String) resp.get("answer"));
+            record.setConversationId((String) resp.get("conversationId"));
+        }
+        record.setCreatedAt(new Date());
+        reportFeedbackMapper.insert(record);
+        return Result.success(record);
+    }
+
+    /**
+     * 转人工客服 / 工单接入(反馈域在线客服,缺口 G-4 · SC-P-83)。
+     *
+     * <p>与 AI 自动解答并行的第二条路径:仅落库为待人工受理(feedback_type=consult、
+     * ai_status=pending),不调用 AI;同样执行敏感信息脱敏、附件 10MB 上限与越权校验。</p>
+     */
+    public Result<?> handoffToConsultant(Long userId, Long memberId, String content,
+                                         String attachmentUrl, Long attachmentSize) {
+        if (content == null || content.trim().isEmpty()) {
+            return Result.error("反馈内容不能为空");
+        }
+        content = content.trim();
+        if (content.length() > 500) {
+            return Result.error("反馈内容不能超过500字");
+        }
+        Result<?> attachmentError = checkAttachmentSize(attachmentSize);
+        if (attachmentError != null) {
+            return attachmentError;
+        }
+        User user = userService.getUserInfo(userId);
+        Result<?> ownershipError = checkOwnership(userId, memberId, null, null, user);
+        if (ownershipError != null) {
+            return ownershipError;
+        }
+
+        ReportFeedback record = new ReportFeedback();
+        record.setUserId(userId);
+        record.setMemberId(memberId);
+        record.setFeedbackType("consult");
+        record.setContent(maskSensitiveInfo(content));
+        record.setAttachmentUrl(attachmentUrl);
+        record.setAiStatus("pending");
+        record.setCreatedAt(new Date());
+        reportFeedbackMapper.insert(record);
+        log.info("转人工客服工单已创建: id={}, userId={}", record.getId(), userId);
+        return Result.success(record);
+    }
+
+    /**
+     * 我的报告反馈列表(含 AI 解答),按创建时间倒序,最多 50 条。
+     */
+    public Result<?> listMine(Long userId, Long reportId) {
+        QueryWrapper<ReportFeedback> wrapper = new QueryWrapper<>();
+        wrapper.eq("user_id", userId);
+        if (reportId != null) {
+            wrapper.eq("report_id", reportId);
+        }
+        wrapper.orderByDesc("created_at").last("LIMIT 50");
+        List<ReportFeedback> list = reportFeedbackMapper.selectList(wrapper);
+        return Result.success(list);
+    }
+
+    /** 附件 >10MB 拒绝(400『附件不超过 10MB』,TC-P-83-E)。 */
+    private Result<?> checkAttachmentSize(Long attachmentSize) {
+        if (attachmentSize != null && attachmentSize > MAX_ATTACHMENT_SIZE) {
+            return Result.badRequest(MSG_ATTACHMENT_TOO_LARGE);
+        }
+        return null;
+    }
+
+    /**
+     * 归属校验(TC-P-83-P):reportId/draftId 必须属于当前 userId,memberId 必须属于当前用户家庭;
+     * 否则统一 403 拒绝、不落库、不泄露他人数据(「越权」访问)。
+     *
+     * <p>user.familyId 为空表示当前上下文无法确定家庭(由 JwtInterceptor 按 userId+familyId 解析
+     * currentMemberId),此时跳过跨家庭判定,保持既有放行语义。</p>
+     */
+    private Result<?> checkOwnership(Long userId, Long memberId, Long reportId, Long draftId, User user) {
+        if (reportId != null) {
+            HealthReport report = healthReportMapper.selectById(reportId);
+            if (report != null && !userId.equals(report.getUserId())) {
+                return Result.forbidden("越权访问:报告不属于当前用户");
+            }
+        }
+        if (draftId != null) {
+            HealthReportDraft draft = healthReportDraftMapper.selectById(draftId);
+            if (draft != null && !userId.equals(draft.getUserId())) {
+                return Result.forbidden("越权访问:草稿不属于当前用户");
+            }
+        }
+        if (memberId != null && user != null && user.getFamilyId() != null) {
+            FamilyMember member = familyMemberMapper.selectById(memberId);
+            if (member == null || !user.getFamilyId().equals(member.getFamilyId())) {
+                return Result.forbidden("越权访问:家庭成员不属于当前用户家庭");
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 敏感信息脱敏(SC-P-83 / TC-P-83-E):18 位身份证与 11 位手机号仅保留前 3/6 后 4 位,
+     * 落库与 AI 请求中均不得出现原始明文。
+     */
+    private String maskSensitiveInfo(String content) {
+        if (content == null) {
+            return null;
+        }
+        // 身份证:18 位(末位可为 X),保留前 6 后 4
+        String masked = content.replaceAll("(?<!\\d)(\\d{6})\\d{8}([\\dXx]{4})(?!\\d)", "$1********$2");
+        // 手机号:1 开头的 11 位数字,保留前 3 后 4
+        masked = masked.replaceAll("(?<!\\d)(1\\d{2})\\d{4}(\\d{4})(?!\\d)", "$1****$2");
+        return masked;
+    }
+}

+ 208 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportFingerprintService.java

@@ -0,0 +1,208 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.ReportFingerprint;
+import com.etotem.cfc.entity.ReportTypeRegistry;
+import com.etotem.cfc.mapper.ReportFingerprintMapper;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 报告指纹检测服务
+ * 从 DB 加载指纹规则,调 Python 引擎进行检测
+ */
+@Service
+public class ReportFingerprintService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportFingerprintService.class);
+
+    @Resource
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @Resource
+    private ReportFingerprintMapper fingerprintMapper;
+
+    @Value("${python.executable:python3}")
+    private String pythonExecutable;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 检测 PDF 文件,返回匹配的报告类型
+     */
+    public Map<String, Object> detect(String pdfPath, String fileName) {
+        // 非 PDF 文件:指纹引擎不支持,直接返回 unknown
+        if (!isPdfFile(pdfPath)) {
+            log.debug("非PDF文件跳过指纹检测 path={}", pdfPath);
+            Map<String, Object> fallback = new LinkedHashMap<>();
+            fallback.put("typeId", "unknown");
+            fallback.put("reason", "not_pdf");
+            return fallback;
+        }
+        List<ReportTypeRegistry> activeTypes = typeRegistryMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportTypeRegistry>()
+                        .eq(ReportTypeRegistry::getIsActive, true));
+
+        // 构建指纹规则 JSON
+        List<Map<String, Object>> rules = new ArrayList<>();
+        for (ReportTypeRegistry type : activeTypes) {
+            List<ReportFingerprint> fingerprints = fingerprintMapper.selectList(
+                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportFingerprint>()
+                            .eq(ReportFingerprint::getTypeId, type.getTypeId())
+                            .orderByAsc(ReportFingerprint::getSortOrder));
+
+            Map<String, Object> rule = new LinkedHashMap<>();
+            rule.put("typeId", type.getTypeId());
+            rule.put("minConfidence", type.getMinConfidence() != null ? type.getMinConfidence() : 10);
+            rule.put("parserPath", type.getParserPath());
+
+            List<Map<String, Object>> fps = new ArrayList<>();
+            for (ReportFingerprint fp : fingerprints) {
+                Map<String, Object> fpm = new LinkedHashMap<>();
+                fpm.put("pattern", fp.getPattern());
+                fpm.put("weight", fp.getWeight() != null ? fp.getWeight() : 10);
+                fpm.put("isExclusion", fp.getIsExclusion() != null && fp.getIsExclusion());
+                fps.add(fpm);
+            }
+            rule.put("fingerprints", fps);
+            rules.add(rule);
+        }
+
+        return callPythonEngine(rules, pdfPath, fileName);
+    }
+
+    /**
+     * 调用 Python 指纹引擎
+     */
+    private Map<String, Object> callPythonEngine(List<Map<String, Object>> rules, String pdfPath, String fileName) {
+        try {
+            // 将规则写入临时文件
+            File rulesFile = File.createTempFile("fp_rules_", ".json");
+            rulesFile.deleteOnExit();
+            objectMapper.writeValue(rulesFile, rules);
+
+            String scriptPath = getScriptPath("fingerprint_engine.py");
+            if (!new File(scriptPath).exists()) {
+                log.warn("指纹引擎脚本不存在: {}", scriptPath);
+                Map<String, Object> fallback = new LinkedHashMap<>();
+                fallback.put("typeId", "unknown");
+                fallback.put("reason", "script_not_found");
+                return fallback;
+            }
+
+            ProcessBuilder pb = new ProcessBuilder(
+                    pythonExecutable, scriptPath,
+                    "--rules", rulesFile.getAbsolutePath(),
+                    "--pdf", pdfPath,
+                    "--filename", fileName != null ? fileName : "");
+
+            pb.redirectErrorStream(true);
+            Process process = pb.start();
+
+            String output = readStream(process.getInputStream());
+            int exitCode = process.waitFor();
+
+            if (exitCode == 0 && !output.trim().isEmpty()) {
+                return objectMapper.readValue(output.trim(),
+                        new TypeReference<Map<String, Object>>() {});
+            } else {
+                log.warn("指纹引擎退出码={}, 输出={}", exitCode, output);
+                Map<String, Object> fallback = new LinkedHashMap<>();
+                fallback.put("typeId", "unknown");
+                fallback.put("reason", "exit_" + exitCode);
+                return fallback;
+            }
+        } catch (Exception e) {
+            log.error("调用指纹引擎失败", e);
+            Map<String, Object> fallback = new LinkedHashMap<>();
+            fallback.put("typeId", "unknown");
+            fallback.put("reason", e.getMessage());
+            return fallback;
+        }
+    }
+
+    /**
+     * 获取脚本路径,支持多种搜索位置
+     */
+    private String getScriptPath(String scriptName) {        String[] searchPaths = {
+            "docs/scripts/parsers/" + scriptName,
+            "docs/scripts/" + scriptName,
+            "../docs/scripts/" + scriptName,
+            "/app/cfc/docs/scripts/parsers/" + scriptName,
+            "/app/cfc/docs/scripts/" + scriptName,
+            scriptName,
+        };
+        for (String path : searchPaths) {
+            if (new File(path).exists()) return path;
+        }
+        return scriptName;
+    }
+
+    /**
+     * 调用 Python 解析器脚本提取结构化数据
+     */
+    public Map<String, Object> runParser(String parserPath, String pdfPath) {
+        try {
+            String scriptPath = getScriptPath(parserPath);
+            if (!new File(scriptPath).exists()) {
+                log.debug("解析器脚本不存在(调用方应处理空返回): {}", scriptPath);
+                return null;
+            }
+
+            ProcessBuilder pb = new ProcessBuilder(
+                    pythonExecutable, scriptPath, pdfPath);
+            pb.redirectErrorStream(true);
+            Process process = pb.start();
+
+            String output = readStream(process.getInputStream());
+            int exitCode = process.waitFor();
+
+            if (exitCode == 0 && !output.trim().isEmpty()) {
+                // 尝试解析输出为 JSON
+                String trimmed = output.trim();
+                if (trimmed.startsWith("{")) {
+                    return objectMapper.readValue(trimmed,
+                            new TypeReference<Map<String, Object>>() {});
+                }
+            }
+            log.warn("解析器退出码={}, 输出前200字符={}", exitCode,
+                    output.length() > 200 ? output.substring(0, 200) : output);
+            return null;
+        } catch (Exception e) {
+            log.error("调用解析器失败", e);
+            return null;
+        }
+    }
+
+    private String readStream(InputStream is) throws IOException {
+        ByteArrayOutputStream buf = new ByteArrayOutputStream();
+        byte[] temp = new byte[1024];
+        int read;
+        while ((read = is.read(temp)) > 0) {
+            buf.write(temp, 0, read);
+        }
+        return buf.toString("UTF-8");
+    }
+
+    /** 通过魔数 %PDF- 判断文件是否为 PDF。 */
+    private boolean isPdfFile(String filePath) {
+        try (FileInputStream fis = new FileInputStream(filePath)) {
+            byte[] header = new byte[5];
+            int read = fis.read(header);
+            return read == 5 && new String(header, StandardCharsets.US_ASCII).startsWith("%PDF-");
+        } catch (Exception e) {
+            return false;
+        }
+    }
+}

+ 265 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportImportService.java

@@ -0,0 +1,265 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ReportFingerprint;
+import com.etotem.cfc.entity.ReportParserImport;
+import com.etotem.cfc.mapper.ReportFingerprintMapper;
+import com.etotem.cfc.mapper.ReportParserImportMapper;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import com.etotem.cfc.entity.ReportTypeRegistry;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.*;
+import java.util.regex.Pattern;
+
+/**
+ * 外部报告解析器导入服务
+ * 支持导入指纹规则 + 解析脚本,注册为新报告类型
+ */
+@Service
+public class ReportImportService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportImportService.class);
+
+    @Resource
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @Resource
+    private ReportFingerprintMapper fingerprintMapper;
+
+    @Resource
+    private ReportParserImportMapper importMapper;
+
+    @Value("${report.parser.scripts.path:docs/scripts/parsers}")
+    private String scriptsPath;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 解析并导入 JSON 格式的导入包
+     * 返回解析后的导入记录(pending 状态,待人工审核)
+     */
+    public Result<ReportParserImport> importPackage(String fileName, String jsonContent, Long userId) {
+        try {
+            Map<String, Object> pkg = objectMapper.readValue(jsonContent,
+                    new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});
+            return doImport(fileName, jsonContent, pkg, userId);
+        } catch (Exception e) {
+            log.error("解析导入包JSON失败", e);
+            return Result.error("导入包格式错误: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 解析并导入 JSON 文件
+     */
+    public Result<ReportParserImport> importPackageFile(File jsonFile, Long userId) {
+        try {
+            String jsonContent = new String(Files.readAllBytes(jsonFile.toPath()), StandardCharsets.UTF_8);
+            return importPackage(jsonFile.getName(), jsonContent, userId);
+        } catch (Exception e) {
+            log.error("读取导入包文件失败", e);
+            return Result.error("读取导入包失败: " + e.getMessage());
+        }
+    }
+
+    private Result<ReportParserImport> doImport(String fileName, String jsonContent,
+                                                 Map<String, Object> pkg, Long userId) {
+        // 校验必填字段
+        String packageName = str(pkg.get("packageName"));
+        String typeId = str(pkg.get("typeId"));
+        String displayName = str(pkg.get("displayName"));
+        String parserScript = str(pkg.get("parserScript"));
+
+        if (packageName == null || packageName.isEmpty()) {
+            return Result.error("导入包缺少 packageName");
+        }
+        if (typeId == null || typeId.isEmpty()) {
+            return Result.error("导入包缺少 typeId");
+        }
+        if (displayName == null || displayName.isEmpty()) {
+            return Result.error("导入包缺少 displayName");
+        }
+        if (!isValidTypeId(typeId)) {
+            return Result.error("typeId 格式不正确,只能包含字母、数字、下划线");
+        }
+
+        // 校验 typeId 是否已存在
+        Long exists = typeRegistryMapper.selectCount(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportTypeRegistry>()
+                        .eq(ReportTypeRegistry::getTypeId, typeId));
+        if (exists != null && exists > 0) {
+            return Result.error("typeId 已存在: " + typeId);
+        }
+
+        // 校验指纹规则
+        Object fpsObj = pkg.get("fingerprints");
+        List<Map<String, Object>> fingerprints = new ArrayList<>();
+        if (fpsObj instanceof List) {
+            for (Object fp : (List<?>) fpsObj) {
+                if (fp instanceof Map) {
+                    fingerprints.add((Map<String, Object>) fp);
+                }
+            }
+        }
+        if (fingerprints.isEmpty()) {
+            return Result.error("导入包缺少 fingerprints 指纹规则");
+        }
+
+        // 校验指纹字段
+        for (Map<String, Object> fp : fingerprints) {
+            String pattern = str(fp.get("pattern"));
+            if (pattern == null || pattern.isEmpty()) {
+                return Result.error("指纹规则缺少 pattern 文本特征");
+            }
+        }
+
+        // 创建导入记录(pending 状态)
+        ReportParserImport record = new ReportParserImport();
+        record.setPackageName(packageName);
+        record.setPackageFileUrl(fileName);
+        record.setFingerprintJson(jsonContent);
+        record.setParserScript(parserScript);
+        record.setStatus(ReportParserImport.STATUS_PENDING);
+        record.setImportedBy(userId);
+        record.setCreatedAt(new Date());
+        record.setUpdatedAt(new Date());
+        importMapper.insert(record);
+
+        log.info("导入包已记录待审核: packageName={}, typeId={}, importId={}",
+                packageName, typeId, record.getId());
+        return Result.success(record);
+    }
+
+    /**
+     * 审核通过导入:注册报告类型 + 指纹规则 + 部署解析脚本
+     */
+    public Result<Map<String, Object>> approveImport(Long importId, Long reviewerId) {
+        ReportParserImport record = importMapper.selectById(importId);
+        if (record == null) {
+            return Result.error("导入记录不存在");
+        }
+        if (!ReportParserImport.STATUS_PENDING.equals(record.getStatus())) {
+            return Result.error("该记录已" + record.getStatus());
+        }
+
+        try {
+            Map<String, Object> pkg = objectMapper.readValue(record.getFingerprintJson(),
+                    new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});
+
+            String typeId = str(pkg.get("typeId"));
+            String family = str(pkg.get("family"));
+            String displayName = str(pkg.get("displayName"));
+            String description = str(pkg.get("description"));
+            String parserScript = str(pkg.get("parserScript"));
+
+            // 1. 注册报告类型
+            ReportTypeRegistry type = new ReportTypeRegistry();
+            type.setTypeId(typeId);
+            type.setFamily(family != null ? family : "custom");
+            type.setDisplayName(displayName);
+            type.setDescription(description);
+            type.setParserPath(typeId + ".py");
+            type.setMinConfidence(10);
+            type.setIsActive(true);
+            type.setSource(ReportTypeRegistry.SOURCE_IMPORTED);
+            type.setReviewStatus(ReportTypeRegistry.REVIEW_APPROVED);
+            type.setVersion("1.0");
+            type.setCreatedBy(reviewerId);
+            type.setCreatedAt(new Date());
+            type.setUpdatedAt(new Date());
+            typeRegistryMapper.insert(type);
+
+            // 2. 注册指纹规则
+            Object fpsObj = pkg.get("fingerprints");
+            if (fpsObj instanceof List) {
+                int sort = 0;
+                for (Object fp : (List<?>) fpsObj) {
+                    if (fp instanceof Map) {
+                        Map<String, Object> fpm = (Map<String, Object>) fp;
+                        ReportFingerprint fpEnt = new ReportFingerprint();
+                        fpEnt.setTypeId(typeId);
+                        fpEnt.setPattern(str(fpm.get("pattern")));
+                        fpEnt.setWeight(fpm.get("weight") != null
+                                ? ((Number) fpm.get("weight")).intValue() : 10);
+                        fpEnt.setIsExclusion(fpm.get("isExclusion") != null
+                                && Boolean.TRUE.equals(fpm.get("isExclusion")));
+                        fpEnt.setSortOrder(sort++);
+                        fpEnt.setCreatedAt(new Date());
+                        fingerprintMapper.insert(fpEnt);
+                    }
+                }
+            }
+
+            // 3. 部署解析脚本
+            if (parserScript != null && !parserScript.isEmpty()) {
+                deployParserScript(typeId, parserScript);
+            }
+
+            // 4. 更新导入记录
+            record.setStatus(ReportParserImport.STATUS_APPROVED);
+            record.setReviewedBy(reviewerId);
+            record.setUpdatedAt(new Date());
+            importMapper.updateById(record);
+
+            Map<String, Object> result = new LinkedHashMap<>();
+            result.put("typeId", typeId);
+            result.put("displayName", displayName);
+            result.put("importId", importId);
+            return Result.success(result);
+        } catch (Exception e) {
+            log.error("审核通过导入失败 importId={}", importId, e);
+            return Result.error("导入失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * 驳回导入
+     */
+    public Result<Void> rejectImport(Long importId, Long reviewerId, String note) {
+        ReportParserImport record = importMapper.selectById(importId);
+        if (record == null) {
+            return Result.error("导入记录不存在");
+        }
+        if (!ReportParserImport.STATUS_PENDING.equals(record.getStatus())) {
+            return Result.error("该记录已" + record.getStatus());
+        }
+        record.setStatus(ReportParserImport.STATUS_REJECTED);
+        record.setReviewedBy(reviewerId);
+        record.setReviewNote(note);
+        record.setUpdatedAt(new Date());
+        importMapper.updateById(record);
+        return Result.success();
+    }
+
+    private void deployParserScript(String typeId, String scriptContent) {
+        try {
+            File dir = new File(scriptsPath);
+            if (!dir.exists() && !dir.mkdirs()) {
+                log.warn("无法创建解析脚本目录: {}", scriptsPath);
+                return;
+            }
+            File scriptFile = new File(dir, typeId + ".py");
+            Files.write(scriptFile.toPath(), scriptContent.getBytes(StandardCharsets.UTF_8));
+            log.info("解析脚本已部署: {}", scriptFile.getAbsolutePath());
+        } catch (Exception e) {
+            log.error("部署解析脚本失败", e);
+        }
+    }
+
+    private boolean isValidTypeId(String typeId) {
+        return Pattern.matches("^[a-zA-Z0-9_]+$", typeId);
+    }
+
+    private String str(Object o) {
+        return o == null ? null : String.valueOf(o);
+    }
+}

+ 359 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportMemberPermissionService.java

@@ -0,0 +1,359 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.ReportMemberPermission;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.ReportMemberPermissionMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+/**
+ * 报告成员级查看权限服务
+ *
+ * 模型:
+ *  - 家庭管理员(家庭创建者 / users.is_family_admin=1 / family_members.is_admin=1):可见家庭内全部成员的报告
+ *  - 普通成员:仅可见自己的报告;管理员可通过 report_member_permissions 授权某用户查看某成员的全部报告
+ *  - 授权按「成员」粒度:授权后该用户可查看该成员的所有报告(健康报告 + DAN 测评报告),含未来新报告
+ */
+@Service
+public class ReportMemberPermissionService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportMemberPermissionService.class);
+
+    @Resource
+    private ReportMemberPermissionMapper permissionMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /* ============ 管理员判定 ============ */
+
+    /**
+     * 判断用户是否为某家庭的管理员。
+     * <p>
+     * 三个等价来源(任一命中即为管理员):
+     * <ol>
+     *  <li><b>家庭创建者</b>:{@code families.creator_id = userId}。
+     *      家庭主账号按系统设计只存在于 {@code users} 表(family_id + role=parent),
+     *      <b>没有 {@code family_members} 行</b>(见 FamilyMemberService#updateParentMember),
+     *      因此不能只查 family_members.is_admin,否则家庭创建者会被误判为普通成员:
+     *      报告列表坍缩为空、报告详情返回「无权查看」(生产故障 2026-10-23,林小朋 userId=55)。
+     *  <li><b>users.is_family_admin=1</b> 且属于该家庭:兼容管理员转让等场景。</li>
+     *  <li><b>family_members.is_admin=1</b>:家庭成员记录被设为管理员。</li>
+     * </ol>
+     * 与 {@code FamilyMemberService#isFamilyAdminOperator} 判定口径保持一致。
+     */
+    public boolean isFamilyAdmin(Long userId, Long familyId) {
+        if (userId == null || familyId == null) {
+            return false;
+        }
+        try {
+            // 1) 家庭创建者(家庭主账号按设计无 family_members 行,必须认这条)
+            Family family = familyMapper.selectById(familyId);
+            if (family != null && Long.valueOf(userId).equals(family.getCreatorId())) {
+                return true;
+            }
+            // 2) users.is_family_admin=1 且属于该家庭(兼容管理员转让)
+            User user = userMapper.selectById(userId);
+            if (user != null && Boolean.TRUE.equals(user.getIsFamilyAdmin())
+                    && familyId.equals(user.getFamilyId())) {
+                return true;
+            }
+            // 3) family_members.is_admin=1
+            Long count = familyMemberMapper.selectCount(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getFamilyId, familyId)
+                            .eq(FamilyMember::getUserId, userId)
+                            .eq(FamilyMember::getIsAdmin, 1)
+                            .last("LIMIT 1"));
+            return count != null && count > 0;
+        } catch (Exception e) {
+            log.warn("判断家庭管理员失败 userId={}, familyId={}: {}", userId, familyId, e.getMessage());
+            return false;
+        }
+    }
+
+    /* ============ 可见性校验 ============ */
+
+    /**
+     * 用户是否可查看某成员的报告(管理员 / 本人 / 被授权)
+     *
+     * @param userId         查看者用户ID
+     * @param targetMemberId 被查看的成员ID(family_members.id)
+     * @param familyId       家庭ID(隔离作用域)
+     */
+    public boolean canViewMemberReports(Long userId, Long targetMemberId, Long familyId) {
+        if (userId == null || targetMemberId == null) {
+            return false;
+        }
+        // 1. 管理员:家庭内全部可见
+        if (familyId != null && isFamilyAdmin(userId, familyId)) {
+            return true;
+        }
+        // 2. 本人:看自己的报告
+        if (isOwnMember(userId, targetMemberId, familyId)) {
+            return true;
+        }
+        // 3. 被授权(targetMemberId 先归一化为 family_members.id,兼容 users.id 语义)
+        if (familyId != null) {
+            Long normalized = normalizeToMemberId(targetMemberId, familyId);
+            Long queryTarget = (normalized != null) ? normalized : targetMemberId;
+            Long count = permissionMapper.selectCount(
+                    new LambdaQueryWrapper<ReportMemberPermission>()
+                            .eq(ReportMemberPermission::getFamilyId, familyId)
+                            .eq(ReportMemberPermission::getTargetMemberId, queryTarget)
+                            .eq(ReportMemberPermission::getGranteeUserId, userId)
+                            .last("LIMIT 1"));
+            return count != null && count > 0;
+        }
+        return false;
+    }
+
+    /**
+     * 将成员ID归一化为 family_members.id:
+     *  - 已是 family_members.id 则原样返回
+     *  - 若是 users.id 则反查其在家庭内的 family_members 记录
+     *  - 查不到返回 null
+     */
+    private Long normalizeToMemberId(Long id, Long familyId) {
+        if (id == null) {
+            return null;
+        }
+        try {
+            FamilyMember m = familyMemberMapper.selectById(id);
+            if (m != null) {
+                return m.getId();
+            }
+            List<FamilyMember> byUser = familyMemberMapper.selectList(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getUserId, id)
+                            .eq(FamilyMember::getFamilyId, familyId)
+                            .last("LIMIT 1"));
+            if (!byUser.isEmpty()) {
+                return byUser.get(0).getId();
+            }
+        } catch (Exception e) {
+            log.warn("归一化成员ID失败 id={}: {}", id, e.getMessage());
+        }
+        return null;
+    }
+
+    /**
+     * 判断用户是否为某成员的本人(family_members.user_id == userId)
+     * 兼容 targetMemberId 可能是 family_members.id 或 users.id 两种语义
+     */
+    private boolean isOwnMember(Long userId, Long targetMemberId, Long familyId) {
+        try {
+            // 直接匹配:family_members.id == targetMemberId 且 user_id == userId
+            List<FamilyMember> members = familyMemberMapper.selectList(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getUserId, userId));
+            for (FamilyMember m : members) {
+                if (m.getId().equals(targetMemberId)) {
+                    return true;
+                }
+                // targetMemberId 可能是 users.id 语义
+                if (m.getUserId() != null && m.getUserId().equals(targetMemberId)) {
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            log.warn("判断本人成员失败 userId={}, targetMemberId={}: {}", userId, targetMemberId, e.getMessage());
+        }
+        return false;
+    }
+
+    /* ============ 授权管理(管理员操作) ============ */
+
+    /**
+     * 管理员授权:指定用户可查看指定成员的全部报告
+     */
+    public boolean grant(Long operatorUserId, Long familyId, Long targetMemberId, Long granteeUserId) {
+        // 仅管理员可授权
+        if (!isFamilyAdmin(operatorUserId, familyId)) {
+            throw new IllegalArgumentException("仅家庭管理员可进行报告授权");
+        }
+        if (targetMemberId == null || granteeUserId == null) {
+            throw new IllegalArgumentException("被授权成员与用户不能为空");
+        }
+        // 幂等:已存在则跳过
+        Long exists = permissionMapper.selectCount(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .eq(ReportMemberPermission::getTargetMemberId, targetMemberId)
+                        .eq(ReportMemberPermission::getGranteeUserId, granteeUserId)
+                        .last("LIMIT 1"));
+        if (exists != null && exists > 0) {
+            return true;
+        }
+        ReportMemberPermission p = new ReportMemberPermission();
+        p.setFamilyId(familyId);
+        p.setAuthorizerUserId(operatorUserId);
+        p.setTargetMemberId(targetMemberId);
+        p.setGranteeUserId(granteeUserId);
+        p.setCreatedAt(new Date());
+        try {
+            permissionMapper.insert(p);
+            return true;
+        } catch (Exception e) {
+            log.warn("报告授权失败 familyId={}, targetMemberId={}, granteeUserId={}: {}",
+                    familyId, targetMemberId, granteeUserId, e.getMessage());
+            // 并发插入唯一键冲突:视为已授权
+            return true;
+        }
+    }
+
+    /**
+     * 管理员撤销授权
+     */
+    public boolean revoke(Long operatorUserId, Long familyId, Long targetMemberId, Long granteeUserId) {
+        if (!isFamilyAdmin(operatorUserId, familyId)) {
+            throw new IllegalArgumentException("仅家庭管理员可进行报告授权");
+        }
+        permissionMapper.delete(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .eq(ReportMemberPermission::getTargetMemberId, targetMemberId)
+                        .eq(ReportMemberPermission::getGranteeUserId, granteeUserId));
+        return true;
+    }
+
+    /**
+     * 查询某成员的授权列表(管理员操作)
+     * 返回:已授权查看该成员的用户ID列表
+     */
+    public List<Long> listGrantedUserIds(Long operatorUserId, Long familyId, Long targetMemberId) {
+        if (!isFamilyAdmin(operatorUserId, familyId)) {
+            throw new IllegalArgumentException("仅家庭管理员可查询报告授权");
+        }
+        List<ReportMemberPermission> list = permissionMapper.selectList(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .eq(ReportMemberPermission::getTargetMemberId, targetMemberId));
+        List<Long> ids = new ArrayList<>();
+        for (ReportMemberPermission p : list) {
+            ids.add(p.getGranteeUserId());
+        }
+        return ids;
+    }
+
+    /**
+     * 查询某家庭全部授权记录(管理员操作,前端渲染权限矩阵用)
+     */
+    public List<Map<String, Object>> listAllPermissions(Long operatorUserId, Long familyId) {
+        if (!isFamilyAdmin(operatorUserId, familyId)) {
+            throw new IllegalArgumentException("仅家庭管理员可查询报告授权");
+        }
+        List<ReportMemberPermission> list = permissionMapper.selectList(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .orderByAsc(ReportMemberPermission::getTargetMemberId));
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (ReportMemberPermission p : list) {
+            Map<String, Object> m = new HashMap<>();
+            m.put("id", p.getId());
+            m.put("targetMemberId", p.getTargetMemberId());
+            m.put("granteeUserId", p.getGranteeUserId());
+            m.put("createdAt", p.getCreatedAt());
+            result.add(m);
+        }
+        return result;
+    }
+
+    /* ============ 列表过滤辅助 ============ */
+
+    /**
+     * 返回用户在家庭内「可见报告」的身份ID集合(含 family_members.id 与 users.id 两种语义):
+     *  - 管理员:返回 null,表示全部可见(调用方不做成员过滤)
+     *  - 普通成员:本人 userId + 本人成员ID + 被授权成员ID(含其绑定的 userId)
+     * 用于「家庭全部视图」按报告 subject_id/user_id 过滤。
+     */
+    public Set<Long> visibleIdentityIds(Long userId, Long familyId) {
+        if (familyId == null) {
+            return Collections.emptySet();
+        }
+        if (isFamilyAdmin(userId, familyId)) {
+            return null;
+        }
+        Set<Long> ids = new HashSet<>();
+        ids.add(userId); // users.id 语义(报告 user_id 直接匹配)
+        try {
+            List<FamilyMember> mine = familyMemberMapper.selectList(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getFamilyId, familyId)
+                            .eq(FamilyMember::getUserId, userId));
+            for (FamilyMember m : mine) {
+                ids.add(m.getId());
+            }
+        } catch (Exception e) {
+            log.warn("查询本人成员失败 userId={}, familyId={}: {}", userId, familyId, e.getMessage());
+        }
+        List<ReportMemberPermission> grants = permissionMapper.selectList(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .eq(ReportMemberPermission::getGranteeUserId, userId));
+        for (ReportMemberPermission p : grants) {
+            ids.add(p.getTargetMemberId());
+            try {
+                FamilyMember tm = familyMemberMapper.selectById(p.getTargetMemberId());
+                if (tm != null && tm.getUserId() != null) {
+                    ids.add(tm.getUserId());
+                }
+            } catch (Exception ignored) {
+            }
+        }
+        return ids;
+    }
+
+    /**
+     * 返回用户在家庭内「可见报告」的成员ID集合:
+     *  - 管理员:null 表示全部可见(调用方不做成员过滤)
+     *  - 普通成员:本人成员ID + 被授权的成员ID
+     */
+    public Set<Long> visibleMemberIds(Long userId, Long familyId) {
+        if (familyId == null) {
+            return Collections.emptySet();
+        }
+        Set<Long> result = new HashSet<>();
+        // 管理员:返回 null 语义(全部可见)
+        if (isFamilyAdmin(userId, familyId)) {
+            return null;
+        }
+        // 本人成员ID
+        try {
+            List<FamilyMember> mine = familyMemberMapper.selectList(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getFamilyId, familyId)
+                            .eq(FamilyMember::getUserId, userId));
+            for (FamilyMember m : mine) {
+                result.add(m.getId());
+            }
+        } catch (Exception e) {
+            log.warn("查询本人成员失败 userId={}, familyId={}: {}", userId, familyId, e.getMessage());
+        }
+        // 被授权的成员ID
+        List<ReportMemberPermission> grants = permissionMapper.selectList(
+                new LambdaQueryWrapper<ReportMemberPermission>()
+                        .eq(ReportMemberPermission::getFamilyId, familyId)
+                        .eq(ReportMemberPermission::getGranteeUserId, userId));
+        for (ReportMemberPermission p : grants) {
+            result.add(p.getTargetMemberId());
+        }
+        return result;
+    }
+}

+ 164 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportParseService.java

@@ -0,0 +1,164 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.ParsedReport;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.text.PDFTextStripper;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@Slf4j
+@Service
+public class ReportParseService {
+
+    private static final Pattern DATE_PATTERN = Pattern.compile(
+            "(?:(?:测评|报告|评估)日期[::]\\s*)?(\\d{4})[-/年](\\d{1,2})[-/月](\\d{1,2})[日]?");
+    private static final Pattern SCORE_PATTERN = Pattern.compile(
+            "(\\S+)[\\s得]*分[::]\\s*(\\d+)");
+
+    /**
+     * Parse structured DanAssessmentResult directly into ParsedReport.
+     */
+    public ParsedReport parseFromResult(DanAssessmentResult result) {
+        if (result == null) {
+            return ParsedReport.empty();
+        }
+        return ParsedReport.builder()
+                .reportDate(result.getAssessmentDate())
+                .overallScore(result.getOverallScore())
+                .attentionScore(result.getAttentionScore())
+                .focusScore(result.getFocusScore())
+                .memoryScore(result.getMemoryScore())
+                .logicScore(result.getLogicScore())
+                .perceptionScore(result.getPerceptionScore())
+                .spatialScore(result.getSpatialScore())
+                .processingSpeedScore(result.getProcessingSpeedScore())
+                .emotionScore(result.getEmotionScore())
+                .resilienceScore(result.getResilienceScore())
+                .assessmentSummary(result.getAnalysisReport())
+                .growthSuggestions(result.getGrowthSuggestions())
+                .build();
+    }
+
+    /**
+     * Parse a PDF report file and extract data via text extraction + regex.
+     * Returns ParsedReport.empty() if file cannot be read or parsed.
+     */
+    public ParsedReport parseReport(String localFilePath) {
+        File file = new File(localFilePath);
+        if (!file.exists() || !file.isFile()) {
+            log.warn("Report file not found or not a file: {}", localFilePath);
+            return ParsedReport.empty();
+        }
+
+        String text;
+        try (PDDocument document = PDDocument.load(file)) {
+            PDFTextStripper stripper = new PDFTextStripper();
+            text = stripper.getText(document);
+        } catch (IOException e) {
+            log.error("Failed to read PDF file: {}", localFilePath, e);
+            return ParsedReport.empty();
+        }
+
+        if (text == null || text.trim().isEmpty()) {
+            log.warn("PDF text extraction returned empty: {}", localFilePath);
+            return ParsedReport.empty();
+        }
+
+        com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder builder = ParsedReport.builder();
+        builder.rawText(text);
+
+        // Extract report date
+        Date reportDate = extractDate(text);
+        if (reportDate != null) {
+            builder.reportDate(reportDate);
+        }
+
+        // Extract scores
+        Matcher scoreMatcher = SCORE_PATTERN.matcher(text);
+        while (scoreMatcher.find()) {
+            String fieldName = scoreMatcher.group(1);
+            Integer value = parseInt(scoreMatcher.group(2));
+            if (value == null) continue;
+            mapScoreField(builder, fieldName, value);
+        }
+
+        // Extract summary sections (between known markers)
+        extractSection(text, "测评总结", "成长建议", builder::assessmentSummary);
+        extractSection(text, "成长建议", "任务建议", builder::growthSuggestions);
+
+        return builder.build();
+    }
+
+    private Date extractDate(String text) {
+        Matcher matcher = DATE_PATTERN.matcher(text);
+        if (matcher.find()) {
+            try {
+                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                String year = matcher.group(1);
+                String month = String.format("%02d", Integer.parseInt(matcher.group(2)));
+                String day = String.format("%02d", Integer.parseInt(matcher.group(3)));
+                return sdf.parse(year + "-" + month + "-" + day);
+            } catch (Exception e) {
+                log.warn("Failed to parse extracted date", e);
+            }
+        }
+        return null;
+    }
+
+    private Integer parseInt(String str) {
+        try {
+            return Integer.parseInt(str.trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private void mapScoreField(Object builder, String fieldName, Integer value) {
+        if (fieldName.contains("综合") || fieldName.contains("总体")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).overallScore(value);
+        } else if (fieldName.contains("注意力")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).attentionScore(value);
+        } else if (fieldName.contains("专注力")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).focusScore(value);
+        } else if (fieldName.contains("记忆力")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).memoryScore(value);
+        } else if (fieldName.contains("逻辑")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).logicScore(value);
+        } else if (fieldName.contains("感知")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).perceptionScore(value);
+        } else if (fieldName.contains("空间")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).spatialScore(value);
+        } else if (fieldName.contains("加工速度")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).processingSpeedScore(value);
+        } else if (fieldName.contains("情绪")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).emotionScore(value);
+        } else if (fieldName.contains("韧性") || fieldName.contains("心理韧性")) {
+            ((com.etotem.cfc.dto.ParsedReport.ParsedReportBuilder) builder).resilienceScore(value);
+        }
+    }
+
+    private void extractSection(String text, String startMarker, String endMarker,
+                                java.util.function.Consumer<String> setter) {
+        int start = text.indexOf(startMarker);
+        if (start < 0) return;
+        start += startMarker.length();
+        int end = endMarker != null ? text.indexOf(endMarker, start) : -1;
+        String section = (end > start) ? text.substring(start, end).trim()
+                : text.substring(start).trim();
+        if (!section.isEmpty()) {
+            setter.accept(section);
+        }
+    }
+
+    public void asyncDeepParse(Long resultId, String filePath) {
+        log.info("asyncDeepParse called for resultId={}, filePath={}", resultId, filePath);
+    }
+}

+ 515 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportParserDispatchService.java

@@ -0,0 +1,515 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ParsedReportResult;
+import com.etotem.cfc.entity.ReportUnknownCluster;
+import com.etotem.cfc.entity.ReportUnknownUpload;
+import com.etotem.cfc.mapper.ReportUnknownClusterMapper;
+import com.etotem.cfc.mapper.ReportUnknownUploadMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.*;
+
+/**
+ * 报告解析调度服务
+ * 1. 指纹检测 → 2a. 专用解析器 / 2b. LLM 兜底
+ */
+@Service
+public class ReportParserDispatchService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportParserDispatchService.class);
+
+    @Resource
+    private ReportFingerprintService fingerprintService;
+
+    @Resource
+    private ReportUnknownClusterMapper unknownClusterMapper;
+
+    @Resource
+    private ReportUnknownUploadMapper unknownUploadMapper;
+
+    @Autowired
+    private RestTemplate restTemplate;
+
+    @Value("${cfc.langgraph.url:http://localhost:9000}")
+    private String langgraphUrl;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    private static final int AUTO_LEARN_THRESHOLD = 3;
+
+    // ==================== guhe_v2 指纹路由(T7/L1-1) ====================
+
+    /**
+     * 报告格式判定链顺序(T7/L1-1,§2.1):{@code aidefansi→beijing→guhe_v2→standard};
+     * 旧三类路由(aidefansi / beijing / standard, triplet-inline)不变,guhe_v2 插在 beijing 之后、
+     * standard 之前判定(32 键新版报告不可落入 standard→LLM 兜底而丢失增量 11 键)。
+     */
+    public static final String GUHE_V2_ROUTE_CHAIN = "aidefansi→beijing→guhe_v2→standard";
+
+    /** 判定链阶段:aidefansi(艾德范思肠道微生态检测报告) */
+    public static final String FORMAT_AIDEFANSI = "aidefansi";
+
+    /** 判定链阶段:beijing(北京菌群报告,GMHI / FMT) */
+    public static final String FORMAT_BEIJING = "beijing";
+
+    /** 判定链阶段:guhe_v2(谷禾 2026-11 新版标准报告,32 键 = 旧 21 键打底 + 11 增量键) */
+    public static final String FORMAT_GUHE_V2 = ParsedReportResult.FORMAT_GUHE_V2;
+
+    /** 判定链阶段:standard(标准/旧版谷禾报告,triplet / inline,21 键) */
+    public static final String FORMAT_STANDARD = "standard";
+
+    /** guhe_v2 指纹触发词-1:疾病相似评估(T7,§2.1;guhe_v2 新版章节特征,旧 21 键报告无此词) */
+    public static final String TRIGGER_WORD_GUHE_V2_DISEASE_SIMILARITY = "疾病相似评估";
+
+    /** guhe_v2 指纹触发词-2:厚壁菌比拟杆菌比值(T7,§2.1) */
+    public static final String TRIGGER_WORD_GUHE_V2_FIRMICUTES_BACTEROIDETES = "厚壁菌比拟杆菌比值";
+
+    /** guhe_v2 指纹触发词-3:亚健康及营养饮食不合理(T7,§2.1;健康总分评级文字) */
+    public static final String TRIGGER_WORD_GUHE_V2_SUBHEALTH_DIET = "亚健康及营养饮食不合理";
+
+    /** guhe_v2 触发词判定阈值:至少命中 2 个触发词,且必须包含「疾病相似评估」(见 {@link #isGuheV2Format(String)}) */
+    public static final int GUHE_V2_TRIGGER_MIN_HITS = 2;
+
+    /** guhe_v2 键数自检:32 键(旧 21 键打底 + 11 增量键,§2.1 / T7 键数自检 32 键) */
+    public static final int GUHE_V2_KEYS_32 = ParsedReportResult.GUHE_V2_KEYS_32;
+
+    /**
+     * guhe_v2 指纹识别(T7/L1-1):判定链 {@code aidefansi→beijing→guhe_v2→standard} 中的 <b>guhe_v2 阶段</b>。
+     *
+     * <p>触发词「疾病相似评估 / 厚壁菌比拟杆菌比值 / 亚健康及营养饮食不合理」(§2.1)。
+     * 其中「疾病相似评估」为 guhe_v2 新版新增章节特征(旧 21 键谷禾报告为「疾病风险评估」,
+     * 不含此词),故判定要求<b>至少命中 {@value #GUHE_V2_TRIGGER_MIN_HITS} 个触发词且必须含「疾病相似评估」</b>——
+     * 既满足 guhe_v2 识别,又避免把旧 21 键报告误判为 guhe_v2(T8 禁把旧 21 键强套 guhe_v2)。</p>
+     *
+     * @param text 归一化后的报告全文(可含 0/1/2/3 个触发词)
+     * @return true=guhe_v2 新版标准报告(32 键)
+     */
+    public boolean isGuheV2Format(String text) {
+        if (text == null || text.isEmpty()) {
+            return false;
+        }
+        int hits = 0;
+        if (text.contains(TRIGGER_WORD_GUHE_V2_DISEASE_SIMILARITY)) {
+            hits++;
+        }
+        if (text.contains(TRIGGER_WORD_GUHE_V2_FIRMICUTES_BACTEROIDETES)) {
+            hits++;
+        }
+        if (text.contains(TRIGGER_WORD_GUHE_V2_SUBHEALTH_DIET)) {
+            hits++;
+        }
+        return hits >= GUHE_V2_TRIGGER_MIN_HITS
+                && text.contains(TRIGGER_WORD_GUHE_V2_DISEASE_SIMILARITY);
+    }
+
+    /**
+     * 报告格式版本检测(T7/L1-1 指纹路由入口):按判定链
+     * {@code aidefansi→beijing→guhe_v2→standard} 顺序逐阶段识别格式版本。
+     *
+     * @param fullText 报告全文文本
+     * @return 判定格式版本:{@link #FORMAT_AIDEFANSI} / {@link #FORMAT_BEIJING} /
+     *         {@link #FORMAT_GUHE_V2} / {@link #FORMAT_STANDARD}(兜底)
+     */
+    public String detectReportFormatVersion(String fullText) {
+        if (fullText == null || fullText.trim().isEmpty()) {
+            return FORMAT_STANDARD;
+        }
+        // ① aidefansi:艾德范思报告正文「致客户」信稳定含「艾德范思」
+        if (fullText.contains("艾德范思")) {
+            return FORMAT_AIDEFANSI;
+        }
+        // ② beijing:与 PdfParseService#isBeijingFormat 指纹一致(肠道菌群检测 + 高通量测序 + 健康整体评估)
+        if (fullText.contains("肠道菌群检测") && fullText.contains("高通量测序")
+                && fullText.contains("健康整体评估")) {
+            return FORMAT_BEIJING;
+        }
+        // ③ guhe_v2:触发词指纹(32 键新版标准报告)
+        if (isGuheV2Format(fullText)) {
+            return FORMAT_GUHE_V2;
+        }
+        // ④ standard:兜底(旧 21 键谷禾 / triplet / inline)
+        return FORMAT_STANDARD;
+    }
+
+    /**
+     * guhe_v2 32 键自检(T7 键数自检 32 键 / §2.1):校验解析产物顶层键数达 32
+     * (旧 21 键打底 {@link ParsedReportResult#LEGACY_KEYS_21} + 增量 11 键)。
+     *
+     * @param keyCount 解析产物顶层键数
+     * @return true=键数齐全(≥ 32,T2/T13 空壳率防错阶段可复用)
+     */
+    public boolean guheV2KeyCountCheck(int keyCount) {
+        return keyCount >= GUHE_V2_KEYS_32;
+    }
+
+    // ==================== guhe_v2 格式版本分流(T8/L1-3) ====================
+
+    /** guhe_v2 专用解析器脚本名(32 键新版标准报告应走此提取器,不落入 unknown→LLM 兜底) */
+    private static final String GUHE_V2_PARSER_SCRIPT = "extract_guhe_v2";
+
+    /** guhe_v2 报告指纹类型标识(32 键新版标准报告) */
+    private static final String GUHE_V2_TYPE_ID = "gut_flora_guhe_v2";
+
+    /**
+     * 按《报告格式版本》分流(计划《2026-11-08-浠艾福平台程序修改计划》§三-T8 / L1-3):
+     * <ul>
+     *   <li><b>32 键 guhe_v2</b>({@link ParsedReportResult#FORMAT_GUHE_V2},
+     *       {@link ParsedReportResult#GUHE_V2_KEYS_32}):走 {@link #GUHE_V2_PARSER_SCRIPT} 专用提取分支,
+     *       <b>不落入</b> unknown→LLM 兜底(禁把 32 键误判成路由错误);</li>
+     *   <li>其余格式版本(旧 21 键 guhe {@link ParsedReportResult#LEGACY_KEYS_21} / beijing / null):
+     *       走原 v5 流程 {@link #parseReport},<b>禁止</b>被 guhe_v2 提取器强套。</li>
+     * </ul>
+     *
+     * @param reportFormatVersion 报告格式版本(guhe_v2 为 {@link ParsedReportResult#FORMAT_GUHE_V2};旧版传 null/其它)
+     * @return 解析结果(guhe_v2 走专用提取器;旧版走原 v5 流程)
+     */
+    public Result<Map<String, Object>> routeByFormatVersion(String reportFormatVersion, String pdfPath, String fileName) {
+        if (ParsedReportResult.FORMAT_GUHE_V2.equals(reportFormatVersion)) {
+            log.info("报告格式版本=guhe_v2(32 键新版),走专用提取器 extract_guhe_v2,不落 LLM 兜底");
+            return parseGuheV2(pdfPath, fileName);
+        }
+        log.info("报告格式版本={}(旧 21 键 / beijing / 未知),走原 v5 流程,不强套 guhe_v2",
+                reportFormatVersion == null ? "null(旧版)" : reportFormatVersion);
+        return parseReport(pdfPath, fileName);
+    }
+
+    /**
+     * 32 键 guhe_v2 专用解析分支:调用 {@link #GUHE_V2_PARSER_SCRIPT} 提取器。
+     * 提取器未就绪时返回明确错误,<b>绝不</b>回退到 unknown→LLM 兜底(T8 禁把 32 键误判成路由错误)。
+     */
+    private Result<Map<String, Object>> parseGuheV2(String pdfPath, String fileName) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        Map<String, Object> parsed = fingerprintService.runParser(GUHE_V2_PARSER_SCRIPT, pdfPath);
+        if (parsed == null) {
+            log.warn("guhe_v2 提取器未就绪({} 缺失),32 键报告保持专用分支状态,不进入 LLM 兜底", GUHE_V2_PARSER_SCRIPT);
+            result.put("typeId", GUHE_V2_TYPE_ID);
+            result.put("parseMethod", "guhe_v2_pending_extractor");
+            return Result.error("guhe_v2 提取器未就绪,请平台装配 extract_guhe_v2 脚本后重试");
+        }
+        result.put("typeId", GUHE_V2_TYPE_ID);
+        result.put("parsedData", parsed);
+        result.put("parseMethod", "dedicated_parser_guhe_v2");
+        return Result.success(result);
+    }
+    // ======================== T13 空壳率防错(L1-4,能力键 guhe.l1.shellGuard) ========================
+
+    /**
+     * T13/L1-4:guhe_v2 增量键数(计划 §2.1:谷禾 2026-11 新版标准报告 = 旧 21 键打底 + 11 增量键 = 32 键)。
+     * guhe_v2 解析后校验增量 11 键齐全的基准。
+     */
+    public static final int GUHE_V2_INCREMENTAL_KEYS = 11;
+
+    /**
+     * T13/L1-4:guhe_v2 总键数 32(21 旧键 + 11 增量键)。
+     * 区分完整 guhe_v2 报告(32 键)与空壳(不足 32 键)。
+     */
+    public static final int GUHE_V2_TOTAL_KEYS = 32;
+
+    /**
+     * T13/L1-4:空壳签名 26 键(曾误用艾德范思提取器仅产 26 键的空壳假 JSON)。
+     * 判为空壳 → 换用正确提取器 {@link #GUHE_V2_EXTRACTOR_SCRIPT}。
+     */
+    public static final int EMPTY_SHELL_KEYS = 26;
+
+    /**
+     * T13/L1-4:正确提取器脚本名(空壳时切换目标,「换正确提取器」)。
+     * 对应采集器 {@code extract_guhe_v2.py}(计划 §2.1)。
+     */
+    public static final String GUHE_V2_EXTRACTOR_SCRIPT = "extract_guhe_v2";
+
+    /**
+     * 解析报告:指纹检测 → 专用解析器 或 LLM 兜底
+     */
+    public Result<Map<String, Object>> parseReport(String pdfPath, String fileName) {
+        // 1. 指纹检测
+        Map<String, Object> fpResult = fingerprintService.detect(pdfPath, fileName);
+        String typeId = (String) fpResult.get("typeId");
+        log.info("指纹检测结果: typeId={}, score={}", typeId, fpResult.get("score"));
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("fingerprintResult", fpResult);
+
+        // 2a. 已知类型 → 调解析器
+        if (!"unknown".equals(typeId) && fpResult.get("parserPath") != null) {
+            String parserPath = (String) fpResult.get("parserPath");
+            Map<String, Object> parsed = fingerprintService.runParser(parserPath, pdfPath);
+            result.put("typeId", typeId);
+            result.put("parsedData", parsed);
+            result.put("parseMethod", "dedicated_parser");
+
+            // T13/L1-4 空壳守卫(非破坏性审计):解析后校验增量 11 键齐全,
+            // 空壳签名(26 键,误用艾德范思提取器产物)→ 记录告警并提示换用 extract_guhe_v2。
+            // 仅审计不自动重解析:T7 指纹路由 / T8 新旧分流落地前,旧 21 键标准报告
+            // 键数 < 32 属正常,不得误伤;切换动作由调用方按 getSwitchToExtractor() 决定。
+            ShellGuardDecision guard = guardShell(typeId, parsed);
+            result.put("shellGuard", guard);
+            if (guard.getSwitchToExtractor() != null) {
+                log.warn("T13 空壳守卫: typeId={}, keyCount={}, message={}",
+                        typeId, guard.getKeyCount(), guard.getMessage());
+            } else {
+                log.debug("T13 空壳守卫: typeId={}, keyCount={}, 增量键齐全={}",
+                        typeId, guard.getKeyCount(), guard.isIncrementalComplete());
+            }
+            return Result.success(result);
+        }
+
+        // 2b. Unknown → LLM 兜底
+        try {
+            String llmResult = callLlmFallback(pdfPath);
+            Map<String, Object> llmParsed = objectMapper.readValue(llmResult,
+                    new TypeReference<Map<String, Object>>() {});
+
+            result.put("typeId", "unknown");
+            result.put("parsedData", llmParsed);
+            result.put("parseMethod", "llm_fallback");
+
+            // 记录到聚类表
+            recordUnknown(pdfPath, llmParsed, fileName);
+
+            return Result.success(result);
+        } catch (Exception e) {
+            log.error("LLM 兜底解析失败", e);
+            return Result.error("LLM 解析失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * T13/L1-4 空壳守卫入口(guhe_v2 解析后校验增量 11 键齐全)。
+     *
+     * <p>契约(计划 2026-11-08-浠艾福平台程序修改计划.md §三-T13 / §一-L1-4 / §2.1):
+     * 空壳(曾误用艾德范思提取器产 <b>26 键</b>)→ 判为空壳 → 换用正确提取器
+     * {@link #GUHE_V2_EXTRACTOR_SCRIPT}({@code extract_guhe_v2})。</p>
+     *
+     * <p><b>口径</b>:本守卫按键数签名判定(§2.1 定义的 32/26/11 三常量):
+     * <ul>
+     *   <li>解析产物键数 == {@link #EMPTY_SHELL_KEYS}(26)→ 空壳命中,{@link ShellGuardDecision#getSwitchToExtractor()}
+     *       返回 {@link #GUHE_V2_EXTRACTOR_SCRIPT}(换正确提取器);</li>
+     *   <li>解析产物键数 &lt; {@link #GUHE_V2_TOTAL_KEYS}(32)且非空壳签名 → 增量 11 键不齐(不完整),
+     *       同样提示换用正确提取器重跑;</li>
+     *   <li>解析产物键数 == {@link #GUHE_V2_TOTAL_KEYS}(32)→ 增量 11 键齐全,判定通过(不换提取器)。</li>
+     * </ul>
+     * 增量键名级校验依赖「谷禾2026新版扩展知识」扩展块(+guhe2026.2,11 子键),该扩展资产位于
+     * 工作区《浠艾福-报告归因方案-总体设计修改方案-v1.1.md》配套库,尚未随本 checkout 入库;
+     * 故本守卫以键数签名(32/26/11)作为可验证基准,键名集合待扩展块入库后由 T9/KB 版本感知补齐。</p>
+     *
+     * <p><b>非破坏性</b>:本守卫只判定不执行重解析;调用方(parseReport 管线 / 后续 T7 路由)按
+     * {@link ShellGuardDecision#getSwitchToExtractor()} 非空时决定是否切换提取器重跑。避免在
+     * T7 指纹路由 / T8 新旧分流落地前误伤旧 21 键标准报告。</p>
+     *
+     * @param typeId     指纹检测类型(可为空;用于审计日志)
+     * @param parsedData 解析产物(顶层键 Map;guhe 系列报告经专用解析器产出)
+     * @return 空壳守卫判定(含是否空壳 / 增量键是否齐全 / 是否需切换提取器)
+     */
+    public ShellGuardDecision guardShell(String typeId, Map<String, Object> parsedData) {
+        if (parsedData == null) {
+            return ShellGuardDecision.incomplete(typeId, 0,
+                    "解析产物为空(键数 0),增量 11 键不齐 → 换用正确提取器", GUHE_V2_EXTRACTOR_SCRIPT);
+        }
+        int keyCount = parsedData.size();
+        if (keyCount == EMPTY_SHELL_KEYS) {
+            return ShellGuardDecision.shell(typeId, keyCount,
+                    "空壳签名 26 键(曾误用艾德范思提取器产物)→ 换用正确提取器 " + GUHE_V2_EXTRACTOR_SCRIPT,
+                    GUHE_V2_EXTRACTOR_SCRIPT);
+        }
+        if (keyCount < GUHE_V2_TOTAL_KEYS) {
+            return ShellGuardDecision.incomplete(typeId, keyCount,
+                    "键数 " + keyCount + " < " + GUHE_V2_TOTAL_KEYS
+                            + "(旧 21 键 + 增量 11 键),增量键不齐 → 换用正确提取器 " + GUHE_V2_EXTRACTOR_SCRIPT,
+                    GUHE_V2_EXTRACTOR_SCRIPT);
+        }
+        return ShellGuardDecision.complete(typeId, keyCount,
+                "guhe_v2 解析后增量 " + GUHE_V2_INCREMENTAL_KEYS + " 键齐全(总键数 " + GUHE_V2_TOTAL_KEYS + ")");
+    }
+
+    /**
+     * T13/L1-4 空壳守卫判定结果。
+     *
+     * <p>携带空壳命中 / 增量键齐全状态与「切换提取器」目标({@link ReportParserDispatchService#GUHE_V2_EXTRACTOR_SCRIPT}
+     * 或 {@code null} 表示无需切换)。</p>
+     */
+    public static final class ShellGuardDecision {
+
+        private final boolean emptyShell;
+        private final boolean incrementalComplete;
+        private final String typeId;
+        private final int keyCount;
+        private final String message;
+        private final String switchToExtractor;
+
+        private ShellGuardDecision(boolean emptyShell, boolean incrementalComplete,
+                                   String typeId, int keyCount, String message, String switchToExtractor) {
+            this.emptyShell = emptyShell;
+            this.incrementalComplete = incrementalComplete;
+            this.typeId = typeId;
+            this.keyCount = keyCount;
+            this.message = message;
+            this.switchToExtractor = switchToExtractor;
+        }
+
+        static ShellGuardDecision shell(String typeId, int keyCount, String message, String switchToExtractor) {
+            return new ShellGuardDecision(true, false, typeId, keyCount, message, switchToExtractor);
+        }
+
+        static ShellGuardDecision incomplete(String typeId, int keyCount, String message, String switchToExtractor) {
+            return new ShellGuardDecision(false, false, typeId, keyCount, message, switchToExtractor);
+        }
+
+        static ShellGuardDecision complete(String typeId, int keyCount, String message) {
+            return new ShellGuardDecision(false, true, typeId, keyCount, message, null);
+        }
+
+        /** 是否命中空壳签名(26 键,误用艾德范思提取器产物) */
+        public boolean isEmptyShell() {
+            return emptyShell;
+        }
+
+        /** 增量 11 键是否齐全(guhe_v2 总键数 32) */
+        public boolean isIncrementalComplete() {
+            return incrementalComplete;
+        }
+
+        public String getTypeId() {
+            return typeId;
+        }
+
+        public int getKeyCount() {
+            return keyCount;
+        }
+
+        public String getMessage() {
+            return message;
+        }
+
+        /** 切换提取器目标(非空表示需换用 {@code extract_guhe_v2} 重跑),{@code null} 表示无需切换 */
+        public String getSwitchToExtractor() {
+            return switchToExtractor;
+        }
+    }
+
+    /**
+     * 调用 cfc-langgraph 的 LLM 解析端点
+     */
+    private String callLlmFallback(String pdfPath) throws Exception {
+        String url = langgraphUrl + "/api/v1/report/parse";
+
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("file_path", pdfPath);
+        body.put("family_id", null);
+        body.put("user_id", null);
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(body), headers);
+
+        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
+
+        if (response.getStatusCode() == HttpStatus.OK) {
+            return response.getBody();
+        }
+        throw new RuntimeException("LLM 返回状态码: " + response.getStatusCode());
+    }
+
+    /**
+     * 记录未知报告到聚类表(自学习用)
+     */
+    private void recordUnknown(String pdfPath, Map<String, Object> llmResult, String fileName) {
+        try {
+            String fileHash = computeFileHash(pdfPath);
+            // 提取文本特征用于聚类
+            String textFeatures = extractTextFeatures(pdfPath);
+            String clusterKey = computeClusterKey(textFeatures);
+
+            // 查找或创建聚类
+            ReportUnknownCluster cluster = unknownClusterMapper.selectOne(
+                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportUnknownCluster>()
+                            .eq(ReportUnknownCluster::getClusterKey, clusterKey));
+
+            if (cluster == null) {
+                cluster = new ReportUnknownCluster();
+                cluster.setClusterKey(clusterKey);
+                cluster.setCommonSignatures(textFeatures);
+                cluster.setLlmTemplate(objectMapper.writeValueAsString(llmResult));
+                cluster.setReportCount(1);
+                cluster.setStatus(ReportUnknownCluster.STATUS_COLLECTING);
+                cluster.setCreatedAt(new Date());
+                cluster.setUpdatedAt(new Date());
+                unknownClusterMapper.insert(cluster);
+            } else {
+                cluster.setReportCount(cluster.getReportCount() == null ? 1 : cluster.getReportCount() + 1);
+                cluster.setUpdatedAt(new Date());
+                // 满 AUTO_LEARN_THRESHOLD 份标记 ready
+                if (cluster.getReportCount() >= AUTO_LEARN_THRESHOLD
+                        && ReportUnknownCluster.STATUS_COLLECTING.equals(cluster.getStatus())) {
+                    cluster.setStatus(ReportUnknownCluster.STATUS_READY);
+                }
+                unknownClusterMapper.updateById(cluster);
+            }
+
+            // 记录上传明细
+            ReportUnknownUpload upload = new ReportUnknownUpload();
+            upload.setClusterId(cluster.getId());
+            upload.setFileUrl(pdfPath);
+            upload.setFileHash(fileHash);
+            upload.setLlmResult(objectMapper.writeValueAsString(llmResult));
+            upload.setUploadedAt(new Date());
+            unknownUploadMapper.insert(upload);
+
+            log.info("已记录未知报告: clusterKey={}, count={}", clusterKey, cluster.getReportCount());
+        } catch (Exception e) {
+            log.warn("记录未知报告失败", e);
+        }
+    }
+
+    private String computeFileHash(String filePath) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            byte[] data = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(filePath));
+            byte[] hash = md.digest(data);
+            StringBuilder sb = new StringBuilder();
+            for (byte b : hash) sb.append(String.format("%02x", b));
+            return sb.toString();
+        } catch (Exception e) {
+            return String.valueOf(System.currentTimeMillis());
+        }
+    }
+
+    private String computeClusterKey(String textFeatures) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA-256");
+            byte[] hash = md.digest(textFeatures.getBytes(StandardCharsets.UTF_8));
+            StringBuilder sb = new StringBuilder();
+            for (byte b : hash) sb.append(String.format("%02x", b));
+            return sb.substring(0, 16);
+        } catch (Exception e) {
+            return String.valueOf(textFeatures.hashCode());
+        }
+    }
+
+    private String extractTextFeatures(String pdfPath) {
+        try {
+            try (org.apache.pdfbox.pdmodel.PDDocument document =
+                         org.apache.pdfbox.pdmodel.PDDocument.load(new File(pdfPath))) {
+                org.apache.pdfbox.text.PDFTextStripper stripper = new org.apache.pdfbox.text.PDFTextStripper();
+                String text = stripper.getText(document);
+                // 取前 2000 字符作为特征
+                return text != null && text.length() > 2000 ? text.substring(0, 2000) : text;
+            }
+        } catch (Exception e) {
+            log.warn("提取PDF文本特征失败: {}", e.getMessage());
+            return "";
+        }
+    }
+}

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

@@ -0,0 +1,438 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.ReportTypeRegistry;
+import com.etotem.cfc.entity.ReportUnknownCluster;
+import com.etotem.cfc.entity.ReportUnknownUpload;
+import com.etotem.cfc.mapper.ReportTypeRegistryMapper;
+import com.etotem.cfc.mapper.ReportUnknownClusterMapper;
+import com.etotem.cfc.mapper.ReportUnknownUploadMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import javax.annotation.Resource;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+
+@Slf4j
+@Service
+public class ReportScriptGeneratorService {
+
+    @Resource(name = "taskExecutor")
+    private Executor taskExecutor;
+
+    @Resource
+    private ReportUnknownUploadMapper unknownUploadMapper;
+
+    @Resource
+    private ReportTypeRegistryMapper typeRegistryMapper;
+
+    @Resource
+    private ReportUnknownClusterMapper unknownClusterMapper;
+
+    @Resource
+    private StorageService storageService;
+
+    @Resource
+    private RestTemplate restTemplate;
+
+    @Resource
+    private ObjectMapper objectMapper;
+
+    @Value("${report.collect.opencode-base:http://127.0.0.1:4090}")
+    private String opencodeBase;
+
+    @Value("${report.collect.opencode-user:opencode}")
+    private String opencodeUser;
+
+    @Value("${report.collect.opencode-password:IwinTrue@123}")
+    private String opencodePassword;
+
+    @Value("${report.collect.opencode-workdir:/app/cfc}")
+    private String opencodeWorkdir;
+
+    @Value("${report.collect.opencode-model-id:agnes-2.5-flash}")
+    private String opencodeModelId;
+
+    @Value("${report.collect.opencode-model-provider:agnes-ai}")
+    private String opencodeModelProvider;
+
+    @Value("${python.executable:python3}")
+    private String pythonExecutable;
+
+    @Value("${report.parser.scripts.path:docs/scripts/parsers}")
+    private String scriptsPath;
+
+    private static final long SCRIPT_GEN_TIMEOUT_MS = 300_000L;
+    private static final long SCRIPT_TEST_TIMEOUT_MS = 60_000L;
+
+    /**
+     * 异步触发脚本生成。立即返回,结果通过更新 report_type_registry.script_status 通知前端。
+     * 防重入:若已在生成中则跳过。
+     */
+    public void triggerAsyncGenerate(Long clusterId, String typeId) {
+        ReportTypeRegistry type = typeRegistryMapper.selectOne(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportTypeRegistry>()
+                        .eq(ReportTypeRegistry::getTypeId, typeId));
+        if (type == null) {
+            log.warn("脚本生成跳过:类型不存在 typeId={}", typeId);
+            return;
+        }
+        if (ReportTypeRegistry.SCRIPT_STATUS_GENERATING.equals(type.getScriptStatus())) {
+            log.info("脚本生成已在进行中,跳过 typeId={}", typeId);
+            return;
+        }
+        taskExecutor.execute(() -> {
+            try {
+                generateAndTest(clusterId, typeId, type.getDisplayName());
+            } catch (Exception e) {
+                log.error("脚本生成异常 typeId={}", typeId, e);
+                setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            }
+        });
+    }
+
+    private void generateAndTest(Long clusterId, String typeId, String displayName) {
+        ReportUnknownCluster cluster = unknownClusterMapper.selectById(clusterId);
+        if (cluster == null) {
+            log.warn("脚本生成跳过:聚类不存在 clusterId={}", clusterId);
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+
+        List<ReportUnknownUpload> uploads = unknownUploadMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ReportUnknownUpload>()
+                        .eq(ReportUnknownUpload::getClusterId, clusterId)
+                        .orderByDesc(ReportUnknownUpload::getUploadedAt)
+                        .last("LIMIT 1"));
+        if (uploads.isEmpty() || uploads.get(0).getFileUrl() == null) {
+            log.warn("脚本生成跳过:无样例 PDF clusterId={}", clusterId);
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+
+        String samplePdfPath = resolveLocalPath(uploads.get(0).getFileUrl());
+        if (samplePdfPath == null) {
+            log.warn("脚本生成跳过:样例 PDF 本地路径不可达 clusterId={}", clusterId);
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+
+        setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_GENERATING);
+
+        String scriptContent;
+        try {
+            scriptContent = invokeOpencodeGenerateScript(typeId, displayName,
+                    cluster.getCommonSignatures(), samplePdfPath);
+        } catch (Exception e) {
+            log.error("opencode 写脚本失败 typeId={}: {}", typeId, e.getMessage());
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+
+        File dir = new File(scriptsPath);
+        if (!dir.exists() && !dir.mkdirs()) {
+            log.warn("无法创建脚本目录: {}", scriptsPath);
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+        File scriptFile = new File(dir, typeId + ".py");
+        try {
+            java.nio.file.Files.write(scriptFile.toPath(),
+                    scriptContent.getBytes(StandardCharsets.UTF_8));
+            log.info("脚本已写入: {}", scriptFile.getAbsolutePath());
+        } catch (Exception e) {
+            log.error("写脚本文件失败 typeId={}: {}", typeId, e.getMessage());
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+            return;
+        }
+
+        try {
+            String stdout = runScriptAndWait(samplePdfPath, scriptFile.getAbsolutePath());
+            validateJsonOutput(stdout, typeId);
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_READY);
+            log.info("脚本生成+测试通过 typeId={} scriptPath={}", typeId, scriptFile.getAbsolutePath());
+        } catch (Exception e) {
+            log.warn("脚本独立测试失败 typeId={}: {}", typeId, e.getMessage());
+            setScriptStatus(typeId, ReportTypeRegistry.SCRIPT_STATUS_FAILED);
+        }
+    }
+
+    private String invokeOpencodeGenerateScript(String typeId, String displayName,
+                                                 String commonSignatures, String samplePdfPath)
+            throws Exception {
+        String sessionId = opencodeCreateSession("script-gen-" + typeId);
+        if (sessionId == null) {
+            throw new IllegalStateException("opencode 会话创建失败");
+        }
+
+        String prompt = buildGenerateScriptPrompt(typeId, displayName, commonSignatures, samplePdfPath);
+        sendPrompt(sessionId, prompt);
+
+        long deadline = System.currentTimeMillis() + SCRIPT_GEN_TIMEOUT_MS;
+        int before = countMessages(sessionId);
+        while (System.currentTimeMillis() < deadline) {
+            try {
+                Thread.sleep(5000);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                break;
+            }
+            List<Map<String, Object>> msgs = listMessages(sessionId);
+            if (msgs == null || msgs.size() <= before) {
+                continue;
+            }
+            String reply = findLastAssistantText(msgs);
+            if (reply != null && !reply.trim().isEmpty()) {
+                log.info("opencode 回复(前200字符): {}", reply.substring(0, Math.min(200, reply.length())));
+                String code = extractPythonCode(reply);
+                if (code == null || code.trim().isEmpty()) {
+                    throw new IllegalStateException("opencode 回复中未找到 Python 代码块");
+                }
+                return code;
+            }
+        }
+        throw new IllegalStateException("opencode 写脚本超时(" + SCRIPT_GEN_TIMEOUT_MS / 1000 + "s)");
+    }
+
+    private String buildGenerateScriptPrompt(String typeId, String displayName,
+                                              String commonSignatures, String samplePdfPath) {
+        String desc = (commonSignatures != null && !commonSignatures.isEmpty())
+                ? "公共文本特征:\n" + commonSignatures : "无额外描述";
+        return "你是报告解析脚本编写专家。\n\n"
+                + "任务:为报告类型 '" + typeId + "'(" + (displayName != null ? displayName : "未命名") + ")编写 Python 采集脚本。\n\n"
+                + desc + "\n\n"
+                + "样例PDF路径(本地):" + samplePdfPath + "\n"
+                + "目标脚本路径:/app/cfc/" + scriptsPath + "/" + typeId + ".py\n\n"
+                + "要求:\n"
+                + "1. 先用 pdftotext 或 pdfplumber 读取样例PDF,分析报告结构和字段位置。\n"
+                + "2. 编写 Python 脚本(纯算法,不用 LLM/外部 API),用正则 + pdfplumber/pdfminer 提取结构化数据。\n"
+                + "3. 脚本调用约定:python3 " + typeId + ".py <pdf_path>\n"
+                + "4. stdout 必须输出严格 JSON,结构如下:\n"
+                + "{\n"
+                + "  \"summary\": {\"overallScore\": 0, \"gutHealthScore\": 0, \"reportNumber\": \"\", \"reportDate\": \"\", \"personName\": \"\", \"gender\": \"\", \"age\": 0},\n"
+                + "  \"indicators\": [{\"category\": \"\", \"indicatorName\": \"\", \"indicatorValue\": \"\", \"unit\": \"\", \"refRange\": \"\", \"status\": \"\"}],\n"
+                + "  \"gutFlora\": [{\"bacteriaName\": \"\", \"bacteriaValue\": \"\", \"normalRange\": \"\", \"populationLevel\": \"\", \"detectionRate\": \"\", \"description\": \"\", \"category\": \"\", \"level\": \"\"}],\n"
+                + "  \"foods\": [{\"name\": \"\", \"category\": \"\", \"score\": 0}],\n"
+                + "  \"diseaseRisks\": [{\"diseaseName\": \"\", \"riskValue\": \"\", \"riskLevel\": \"\"}]\n"
+                + "}\n"
+                + "5. 脚本末尾用 try/except 包裹,确保异常时退出码非零。\n"
+                + "6. 写完脚本后,用样例PDF跑一遍(python3 " + typeId + ".py " + samplePdfPath + "),打印 stdout,确认是合法 JSON。\n"
+                + "7. 最后报告脚本路径和测试输出(前500字符)。\n\n"
+                + "注意:只做以上任务。完成后输出完整的 Python 脚本代码(用 ```python 包裹),以及测试结果。";
+    }
+
+    private String runScriptAndWait(String pdfPath, String scriptPath) throws Exception {
+        ProcessBuilder pb = new ProcessBuilder(pythonExecutable, scriptPath, pdfPath);
+        pb.redirectErrorStream(true);
+        Process proc = pb.start();
+        StringBuilder sb = new StringBuilder();
+        try (BufferedReader reader = new BufferedReader(
+                new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8))) {
+            String line;
+            while ((line = reader.readLine()) != null) {
+                sb.append(line).append('\n');
+            }
+        }
+        boolean finished = proc.waitFor(SCRIPT_TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        if (!finished) {
+            proc.destroyForcibly();
+            throw new IllegalStateException("脚本测试超时(" + SCRIPT_TEST_TIMEOUT_MS / 1000 + "s)");
+        }
+        if (proc.exitValue() != 0) {
+            throw new IllegalStateException("脚本测试退出码=" + proc.exitValue()
+                    + "\nstdout: " + sb.toString().trim());
+        }
+        String stdout = sb.toString().trim();
+        if (stdout.isEmpty()) {
+            throw new IllegalStateException("脚本测试 stdout 为空");
+        }
+        return stdout;
+    }
+
+    private void validateJsonOutput(String stdout, String typeId) throws Exception {
+        String json = extractJson(stdout);
+        if (json == null) {
+            throw new IllegalStateException("脚本 stdout 中未找到 JSON\n"
+                    + stdout.substring(0, Math.min(500, stdout.length())));
+        }
+        objectMapper.readTree(json);
+        log.info("脚本测试 JSON 校验通过 typeId={} jsonLen={}", typeId, json.length());
+    }
+
+    private String extractJson(String text) {
+        if (text == null) {
+            return null;
+        }
+        int start = text.indexOf('{');
+        int end = text.lastIndexOf('}');
+        return (start >= 0 && end > start) ? text.substring(start, end + 1) : null;
+    }
+
+    private String opencodeCreateSession(String title) {
+        try {
+            String url = opencodeBase + "/session?directory="
+                    + java.net.URLEncoder.encode(opencodeWorkdir, StandardCharsets.UTF_8.name());
+            Map<String, Object> body = new LinkedHashMap<>();
+            body.put("title", title);
+            body.put("agent", "build");
+            Map<String, Object> model = new LinkedHashMap<>();
+            model.put("id", opencodeModelId);
+            model.put("providerID", opencodeModelProvider);
+            body.put("model", model);
+            Map<String, Object> tools = new LinkedHashMap<>();
+            tools.put("bash", Boolean.TRUE);
+            tools.put("write", Boolean.TRUE);
+            tools.put("edit", Boolean.TRUE);
+            for (String t : new String[]{"apply_patch", "task", "dispatch",
+                    "webfetch_post", "chrome_launch"}) {
+                tools.put(t, Boolean.FALSE);
+            }
+            body.put("tools", tools);
+            ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.POST,
+                    new HttpEntity<>(body, opencodeHeaders()), Map.class);
+            Map<?, ?> data = resp.getBody();
+            if (data == null || data.get("id") == null) {
+                log.warn("opencode 创建会话未返回 session_id");
+                return null;
+            }
+            return data.get("id").toString();
+        } catch (Exception e) {
+            log.error("opencode 创建会话失败 title={}: {}", title, e.getMessage());
+            return null;
+        }
+    }
+
+    private void sendPrompt(String sessionId, String prompt) {
+        List<Map<String, Object>> parts = new ArrayList<>();
+        Map<String, Object> part = new LinkedHashMap<>();
+        part.put("type", "text");
+        part.put("text", prompt);
+        parts.add(part);
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("parts", parts);
+        restTemplate.exchange(opencodeBase + "/session/" + sessionId + "/prompt_async",
+                HttpMethod.POST, new HttpEntity<>(body, opencodeHeaders()), Void.class);
+        log.info("opencode prompt 已发送 session={}", sessionId);
+    }
+
+    private List<Map<String, Object>> listMessages(String sessionId) {
+        try {
+            ResponseEntity<List> resp = restTemplate.exchange(
+                    opencodeBase + "/session/" + sessionId + "/message",
+                    HttpMethod.GET, new HttpEntity<>(opencodeHeaders()), List.class);
+            return resp.getBody();
+        } catch (Exception e) {
+            log.warn("opencode 查询消息失败 session={}: {}", sessionId, e.getMessage());
+            return null;
+        }
+    }
+
+    private int countMessages(String sessionId) {
+        List<Map<String, Object>> msgs = listMessages(sessionId);
+        return msgs == null ? 0 : msgs.size();
+    }
+
+    private HttpHeaders opencodeHeaders() {
+        String token = Base64.getEncoder().encodeToString(
+                (opencodeUser + ":" + opencodePassword).getBytes(StandardCharsets.UTF_8));
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        headers.set("Authorization", "Basic " + token);
+        return headers;
+    }
+
+    @SuppressWarnings("unchecked")
+    private String findLastAssistantText(List<Map<String, Object>> msgs) {
+        if (msgs == null || msgs.isEmpty()) {
+            return null;
+        }
+        for (int i = msgs.size() - 1; i >= 0; i--) {
+            Map<String, Object> msg = msgs.get(i);
+            Object infoObj = msg.get("info");
+            if (!(infoObj instanceof Map)) {
+                continue;
+            }
+            Map<String, Object> info = (Map<String, Object>) infoObj;
+            if (!"assistant".equals(info.get("role"))) {
+                continue;
+            }
+            Object partsObj = msg.get("parts");
+            if (!(partsObj instanceof List)) {
+                continue;
+            }
+            for (Object pObj : (List<Object>) partsObj) {
+                if (!(pObj instanceof Map)) {
+                    continue;
+                }
+                Map<String, Object> p = (Map<String, Object>) pObj;
+                if ("text".equals(p.get("type")) && p.get("text") != null) {
+                    String text = p.get("text").toString().trim();
+                    if (!text.isEmpty()) {
+                        return text;
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    private String extractPythonCode(String reply) {
+        if (reply == null) {
+            return null;
+        }
+        int pyStart = reply.indexOf("```python");
+        if (pyStart >= 0) {
+            int codeStart = reply.indexOf('\n', pyStart);
+            int end = reply.lastIndexOf("```");
+            if (end > codeStart) {
+                return reply.substring(codeStart + 1, end).trim();
+            }
+        }
+        int start = reply.indexOf("```");
+        if (start >= 0) {
+            int codeStart = reply.indexOf('\n', start);
+            int end = reply.lastIndexOf("```");
+            if (end > codeStart) {
+                return reply.substring(codeStart + 1, end).trim();
+            }
+        }
+        return reply.trim();
+    }
+
+    private String resolveLocalPath(String fileUrl) {
+        if (fileUrl == null) {
+            return null;
+        }
+        try {
+            String p = storageService.getFilePath(fileUrl);
+            File f = new File(p);
+            return f.exists() ? f.getAbsolutePath() : null;
+        } catch (Exception e) {
+            log.warn("解析文件路径失败 fileUrl={}: {}", fileUrl, e.getMessage());
+            return null;
+        }
+    }
+
+    private void setScriptStatus(String typeId, String scriptStatus) {
+        try {
+            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<ReportTypeRegistry> uw =
+                    new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<>();
+            uw.eq(ReportTypeRegistry::getTypeId, typeId)
+                    .set(ReportTypeRegistry::getScriptStatus, scriptStatus)
+                    .set(ReportTypeRegistry::getUpdatedAt, new Date());
+            typeRegistryMapper.update(null, uw);
+            log.info("脚本状态已更新 typeId={} status={}", typeId, scriptStatus);
+        } catch (Exception e) {
+            log.error("更新脚本状态失败 typeId={}: {}", typeId, e.getMessage());
+        }
+    }
+}

+ 574 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportSummaryService.java

@@ -0,0 +1,574 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.ReportListQueryDTO;
+import com.etotem.cfc.dto.ReportSummaryVO;
+import com.etotem.cfc.dto.ReportSyncResultDTO;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.DanReportUpload;
+import com.etotem.cfc.entity.FamilyFortuneReport;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.HealthReportDraft;
+import com.etotem.cfc.entity.InsurancePolicy;
+import com.etotem.cfc.entity.ReportSummary;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.mapper.DanReportUploadMapper;
+import com.etotem.cfc.mapper.FamilyFortuneReportMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.HealthReportDraftMapper;
+import com.etotem.cfc.mapper.InsurancePolicyMapper;
+import com.etotem.cfc.mapper.ReportSummaryMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+@Slf4j
+public class ReportSummaryService {
+
+    @Resource
+    private ReportSummaryMapper reportSummaryMapper;
+
+    @Resource
+    private HealthReportMapper healthReportMapper;
+
+    @Resource
+    private DanReportUploadMapper danReportUploadMapper;
+
+    @Resource
+    private InsurancePolicyMapper insurancePolicyMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Resource
+    private FamilyFortuneReportMapper familyFortuneReportMapper;
+
+    @Resource
+    private HealthReportDraftMapper healthReportDraftMapper;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    public void syncFromHealthReport(HealthReport report) {
+        ReportSummary existing = reportSummaryMapper.selectOne(
+                new LambdaQueryWrapper<ReportSummary>()
+                        .eq(ReportSummary::getSourceTable, "health_reports")
+                        .eq(ReportSummary::getSourceId, report.getId())
+        );
+
+        ReportSummary summary = new ReportSummary();
+        summary.setReportType(report.getReportType());
+        summary.setSourceTable("health_reports");
+        summary.setSourceId(report.getId());
+        summary.setUserId(report.getUserId());
+        summary.setFamilyId(report.getFamilyId());
+        summary.setSubjectId(report.getSubjectId());
+        if (report.getSubjectId() != null) {
+            User subject = userMapper.selectById(report.getSubjectId());
+            summary.setSubjectName(subject != null ? subject.getNickname() : "");
+        }
+        String typeLabel = "gut_flora".equals(report.getReportType()) ? "菌群检测报告" : "体检报告";
+        String name = summary.getSubjectName() != null && !summary.getSubjectName().isEmpty() ? summary.getSubjectName() : "用户";
+        summary.setTitle(name + "的" + typeLabel);
+        summary.setFileUrl(report.getFileUrl());
+        summary.setHasFile(report.getFileUrl() != null && !report.getFileUrl().isEmpty() ? 1 : 0);
+        summary.setOverallScore(report.getOverallScore());
+        summary.setReportDate(report.getReportDate());
+        summary.setStatus(report.getStatus());
+        summary.setDetailRoute("gut_flora".equals(report.getReportType())
+                ? "/pages/health/gut-flora-detail"
+                : "/pages/health/physical-exam-detail");
+
+        if (existing != null) {
+            summary.setId(existing.getId());
+            reportSummaryMapper.updateById(summary);
+        } else {
+            reportSummaryMapper.insert(summary);
+        }
+    }
+
+    public void syncFromDanReport(DanReportUpload upload) {
+        ReportSummary existing = reportSummaryMapper.selectOne(
+                new LambdaQueryWrapper<ReportSummary>()
+                        .eq(ReportSummary::getSourceTable, "dan_report_uploads")
+                        .eq(ReportSummary::getSourceId, upload.getId())
+        );
+
+        ReportSummary summary = new ReportSummary();
+        summary.setReportType("dan");
+        summary.setSourceTable("dan_report_uploads");
+        summary.setSourceId(upload.getId());
+        summary.setUserId(upload.getUploaderUserId());
+        summary.setFamilyId(upload.getFamilyId());
+        summary.setSubjectId(upload.getFamilyMemberId());
+
+        FamilyMember member = familyMemberMapper.selectById(upload.getFamilyMemberId());
+        summary.setSubjectName(member != null ? member.getNickname() : "");
+
+        String dimLabel = "mind".equals(upload.getDimension()) ? "心智" : "智慧";
+        String name = summary.getSubjectName() != null && !summary.getSubjectName().isEmpty() ? summary.getSubjectName() : "成员";
+        summary.setTitle(name + "的" + dimLabel + "测评");
+
+        summary.setFileUrl(upload.getFileUrl());
+        summary.setHasFile(upload.getFileUrl() != null && !upload.getFileUrl().isEmpty() ? 1 : 0);
+
+        if (upload.getLinkedResultId() != null) {
+            DanAssessmentResult result = danAssessmentResultMapper.selectById(upload.getLinkedResultId());
+            if (result != null) summary.setOverallScore(result.getOverallScore());
+        }
+
+        summary.setReportDate(upload.getUploadedAt());
+        String status = upload.getDraftStatus();
+        if ("confirmed".equals(status)) {
+            status = "confirmed";
+        } else if ("pending".equals(status)) {
+            status = "active";
+        } else if ("discarded".equals(status)) {
+            status = "discarded";
+        } else {
+            status = "active";
+        }
+        summary.setStatus(status);
+        summary.setDetailRoute("/pages/dan-assessment/report-upload");
+
+        if (existing != null) {
+            summary.setId(existing.getId());
+            reportSummaryMapper.updateById(summary);
+        } else {
+            reportSummaryMapper.insert(summary);
+        }
+    }
+
+    public void syncFromInsurancePolicy(InsurancePolicy policy) {
+        ReportSummary existing = reportSummaryMapper.selectOne(
+                new LambdaQueryWrapper<ReportSummary>()
+                        .eq(ReportSummary::getSourceTable, "insurance_policies")
+                        .eq(ReportSummary::getSourceId, policy.getId())
+        );
+
+        ReportSummary summary = new ReportSummary();
+        summary.setReportType("insurance");
+        summary.setSourceTable("insurance_policies");
+        summary.setSourceId(policy.getId());
+        summary.setUserId(policy.getUserId());
+        summary.setSubjectId(policy.getMemberId());
+        summary.setSubjectName(policy.getInsuredPerson());
+        summary.setTitle(policy.getPolicyName());
+        String company = policy.getInsuranceCompany() != null ? policy.getInsuranceCompany() : "未知公司";
+        String type = policy.getPolicyType() != null ? policy.getPolicyType() : "保险";
+        Integer sum = policy.getSumInsured() != null ? policy.getSumInsured() : 0;
+        summary.setSummary(company + " · " + type + " · 保额 ¥" + sum / 100);
+        summary.setHasFile(0);
+        summary.setReportDate(policy.getStartDate());
+        summary.setStatus(policy.getStatus());
+        summary.setDetailRoute("/pages/wealth-sub/insurance-list");
+
+        if (existing != null) {
+            summary.setId(existing.getId());
+            reportSummaryMapper.updateById(summary);
+        } else {
+            reportSummaryMapper.insert(summary);
+        }
+    }
+
+    public void syncFromFamilyFortuneReport(FamilyFortuneReport report) {
+        ReportSummary existing = reportSummaryMapper.selectOne(
+                new LambdaQueryWrapper<ReportSummary>()
+                        .eq(ReportSummary::getSourceTable, "family_fortune_report")
+                        .eq(ReportSummary::getSourceId, report.getId())
+        );
+
+        ReportSummary summary = new ReportSummary();
+        summary.setReportType("fortune");
+        summary.setSourceTable("family_fortune_report");
+        summary.setSourceId(report.getId());
+        summary.setFamilyId(report.getFamilyId() != null ? report.getFamilyId().longValue() : null);
+
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getFamilyId, report.getFamilyId())
+                        .last("LIMIT 1")
+        );
+        summary.setUserId(member != null ? member.getUserId() : null);
+
+        String element = report.getElement() != null ? report.getElement() : "天盘";
+        summary.setTitle(element + "天盘周报");
+        summary.setSummary(report.getLuckyDirection() != null ? report.getLuckyDirection() : "");
+        summary.setFileUrl(report.getPdfPath());
+        summary.setFileSize(report.getFileSize());
+        summary.setHasFile(report.getPdfPath() != null && !report.getPdfPath().isEmpty() ? 1 : 0);
+        summary.setReportDate(report.getCreatedAt());
+        summary.setStatus("active");
+        summary.setDetailRoute("/pages/tianpan/index");
+
+        if (existing != null) {
+            summary.setId(existing.getId());
+            reportSummaryMapper.updateById(summary);
+        } else {
+            reportSummaryMapper.insert(summary);
+        }
+    }
+
+    public void markDiscarded(String sourceTable, Long sourceId) {
+        reportSummaryMapper.update(
+                null,
+                new LambdaUpdateWrapper<ReportSummary>()
+                        .eq(ReportSummary::getSourceTable, sourceTable)
+                        .eq(ReportSummary::getSourceId, sourceId)
+                        .set(ReportSummary::getStatus, "discarded")
+        );
+    }
+
+    public Page<ReportSummaryVO> pageList(ReportListQueryDTO query) {
+        Page<ReportSummary> page = new Page<>(query.getPage(), query.getSize());
+
+        LambdaQueryWrapper<ReportSummary> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(ReportSummary::getUserId, query.getUserId());
+        wrapper.ne(ReportSummary::getStatus, "discarded");
+
+        if ("all".equals(query.getType()) || query.getType() == null || query.getType().isEmpty()) {
+            // no type filter
+        } else {
+            wrapper.eq(ReportSummary::getReportType, query.getType());
+        }
+
+        if (query.getKeyword() != null && !query.getKeyword().isEmpty()) {
+            wrapper.and(w -> w
+                    .like(ReportSummary::getTitle, query.getKeyword())
+                    .or().like(ReportSummary::getSubjectName, query.getKeyword())
+            );
+        }
+
+        wrapper.orderByDesc(ReportSummary::getReportDate);
+        reportSummaryMapper.selectPage(page, wrapper);
+
+        SortUtil.applySort(wrapper);
+
+        Page<ReportSummaryVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
+        List<ReportSummaryVO> voList = new ArrayList<>();
+        for (ReportSummary s : page.getRecords()) {
+            ReportSummaryVO vo = new ReportSummaryVO();
+            vo.setId(s.getId());
+            vo.setReportType(s.getReportType());
+            vo.setReportTypeName(ReportSummaryVO.getReportTypeName(s.getReportType()));
+            vo.setTitle(s.getTitle());
+            vo.setSubjectName(s.getSubjectName());
+            vo.setSummary(s.getSummary());
+            vo.setFileUrl(s.getFileUrl());
+            vo.setFileSize(s.getFileSize());
+            vo.setFileName(s.getFileName());
+            vo.setHasFile(s.getHasFile() != null && s.getHasFile() == 1);
+            vo.setOverallScore(s.getOverallScore());
+            vo.setReportDate(s.getReportDate() != null ? s.getReportDate().toString() : "");
+            vo.setStatus(s.getStatus());
+            vo.setDetailRoute(s.getDetailRoute());
+            vo.setCreatedAt(s.getCreatedAt());
+            voList.add(vo);
+        }
+        voPage.setRecords(voList);
+        return voPage;
+    }
+
+    public ReportSummaryVO getDetail(Long summaryId) {
+        ReportSummary s = reportSummaryMapper.selectById(summaryId);
+        if (s == null) return null;
+
+        ReportSummaryVO vo = new ReportSummaryVO();
+        vo.setId(s.getId());
+        vo.setReportType(s.getReportType());
+        vo.setReportTypeName(ReportSummaryVO.getReportTypeName(s.getReportType()));
+        vo.setTitle(s.getTitle());
+        vo.setSubjectName(s.getSubjectName());
+        vo.setSummary(s.getSummary());
+        vo.setFileUrl(s.getFileUrl());
+        vo.setFileSize(s.getFileSize());
+        vo.setFileName(s.getFileName());
+        vo.setHasFile(s.getHasFile() != null && s.getHasFile() == 1);
+        vo.setOverallScore(s.getOverallScore());
+        vo.setReportDate(s.getReportDate() != null ? s.getReportDate().toString() : "");
+        vo.setStatus(s.getStatus());
+        vo.setDetailRoute(s.getDetailRoute());
+        vo.setCreatedAt(s.getCreatedAt());
+        vo.setCollectValidation(loadCollectValidationBySource(
+                Collections.singletonList(s), s.getSourceTable()).get(s.getSourceId()));
+        return vo;
+    }
+
+    public Page<ReportSummaryVO> adminPageList(ReportListQueryDTO query) {
+        Page<ReportSummary> page = new Page<>(query.getPage(), query.getSize());
+
+        LambdaQueryWrapper<ReportSummary> wrapper = new LambdaQueryWrapper<>();
+        wrapper.ne(ReportSummary::getStatus, "discarded");
+
+        if ("all".equals(query.getType()) || query.getType() == null || query.getType().isEmpty()) {
+            // no type filter
+        } else {
+            wrapper.eq(ReportSummary::getReportType, query.getType());
+        }
+
+        if (query.getKeyword() != null && !query.getKeyword().isEmpty()) {
+            wrapper.and(w -> w
+                    .like(ReportSummary::getTitle, query.getKeyword())
+                    .or().like(ReportSummary::getSubjectName, query.getKeyword())
+                    .or().like(ReportSummary::getSummary, query.getKeyword())
+            );
+        }
+
+        if (query.getStartDate() != null && !query.getStartDate().isEmpty()) {
+            wrapper.ge(ReportSummary::getReportDate, query.getStartDate());
+        }
+        if (query.getEndDate() != null && !query.getEndDate().isEmpty()) {
+            wrapper.le(ReportSummary::getReportDate, query.getEndDate());
+        }
+
+        wrapper.orderByDesc(ReportSummary::getReportDate);
+        reportSummaryMapper.selectPage(page, wrapper);
+
+        SortUtil.applySort(wrapper);
+
+        Map<Long, String> danValidation = loadCollectValidationBySource(page.getRecords(), "dan_report_uploads");
+        Map<Long, String> healthValidation = loadCollectValidationBySource(page.getRecords(), "health_reports");
+
+        Page<ReportSummaryVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
+        List<ReportSummaryVO> voList = new ArrayList<>();
+        for (ReportSummary rs : page.getRecords()) {
+            ReportSummaryVO vo = new ReportSummaryVO();
+            vo.setId(rs.getId());
+            vo.setReportType(rs.getReportType());
+            vo.setReportTypeName(ReportSummaryVO.getReportTypeName(rs.getReportType()));
+            vo.setTitle(rs.getTitle());
+            vo.setSubjectName(rs.getSubjectName());
+            vo.setSummary(rs.getSummary());
+            vo.setHasFile(rs.getHasFile() != null && rs.getHasFile() == 1);
+            vo.setOverallScore(rs.getOverallScore());
+            vo.setReportDate(rs.getReportDate() != null ? rs.getReportDate().toString() : "");
+            vo.setStatus(rs.getStatus());
+            vo.setCreatedAt(rs.getCreatedAt());
+            if ("dan_report_uploads".equals(rs.getSourceTable())) {
+                vo.setCollectValidation(danValidation.get(rs.getSourceId()));
+            } else if ("health_reports".equals(rs.getSourceTable())) {
+                vo.setCollectValidation(healthValidation.get(rs.getSourceId()));
+            }
+            voList.add(vo);
+        }
+        voPage.setRecords(voList);
+        return voPage;
+    }
+
+    /** 批量读取草稿的采集校验结果,键 = confirmed_report_id(= report_summary.source_id) */
+    private Map<Long, String> loadCollectValidationBySource(List<ReportSummary> rows, String sourceTable) {
+        Map<Long, String> map = new HashMap<>();
+        if (rows == null || rows.isEmpty()) {
+            return map;
+        }
+        Set<Long> ids = rows.stream()
+                .filter(r -> sourceTable.equals(r.getSourceTable()))
+                .map(ReportSummary::getSourceId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet());
+        if (ids.isEmpty()) {
+            return map;
+        }
+        LambdaQueryWrapper<HealthReportDraft> w = new LambdaQueryWrapper<>();
+        w.in(HealthReportDraft::getConfirmedReportId, ids)
+                .isNotNull(HealthReportDraft::getCollectValidation);
+        if ("dan_report_uploads".equals(sourceTable)) {
+            w.likeRight(HealthReportDraft::getReportType, "dan");
+        } else {
+            w.and(x -> x.isNull(HealthReportDraft::getReportType)
+                    .or().notLikeRight(HealthReportDraft::getReportType, "dan"));
+        }
+        for (HealthReportDraft d : healthReportDraftMapper.selectList(w)) {
+            if (d.getConfirmedReportId() != null && d.getCollectValidation() != null) {
+                map.put(d.getConfirmedReportId(), d.getCollectValidation());
+            }
+        }
+        return map;
+    }
+
+    public ReportSyncResultDTO fullSync() {
+        ReportSyncResultDTO result = new ReportSyncResultDTO();
+        result.setNewCount(0);
+        result.setUpdateCount(0);
+        result.setDiscardedCount(0);
+        result.setErrorCount(0);
+
+        // 1. sync health_reports
+        try {
+            List<HealthReport> healthReports = healthReportMapper.selectList(new LambdaQueryWrapper<HealthReport>());
+            List<ReportSummary> existingHealth = reportSummaryMapper.selectList(
+                    new LambdaQueryWrapper<ReportSummary>().eq(ReportSummary::getSourceTable, "health_reports"));
+            for (HealthReport hr : healthReports) {
+                try {
+                    ReportSummary existing = reportSummaryMapper.selectOne(
+                            new LambdaQueryWrapper<ReportSummary>()
+                                    .eq(ReportSummary::getSourceTable, "health_reports")
+                                    .eq(ReportSummary::getSourceId, hr.getId()));
+                    if (existing == null) {
+                        syncFromHealthReport(hr);
+                        result.setNewCount(result.getNewCount() + 1);
+                    } else {
+                        syncFromHealthReport(hr);
+                        result.setUpdateCount(result.getUpdateCount() + 1);
+                    }
+                } catch (Exception e) {
+                    result.setErrorCount(result.getErrorCount() + 1);
+                    log.error("同步 health_reports 记录失败 id={}", hr.getId(), e);
+                }
+            }
+            for (ReportSummary es : existingHealth) {
+                if (healthReportMapper.selectById(es.getSourceId()) == null) {
+                    markDiscarded("health_reports", es.getSourceId());
+                    result.setDiscardedCount(result.getDiscardedCount() + 1);
+                }
+            }
+        } catch (Exception e) {
+            log.error("全量同步 health_reports 失败", e);
+            result.setErrorCount(result.getErrorCount() + 1);
+        }
+
+        // 2. sync dan_report_uploads
+        try {
+            List<DanReportUpload> danUploads = danReportUploadMapper.selectList(new LambdaQueryWrapper<DanReportUpload>());
+            List<ReportSummary> existingDan = reportSummaryMapper.selectList(
+                    new LambdaQueryWrapper<ReportSummary>().eq(ReportSummary::getSourceTable, "dan_report_uploads"));
+            for (DanReportUpload du : danUploads) {
+                try {
+                    ReportSummary existing = reportSummaryMapper.selectOne(
+                            new LambdaQueryWrapper<ReportSummary>()
+                                    .eq(ReportSummary::getSourceTable, "dan_report_uploads")
+                                    .eq(ReportSummary::getSourceId, du.getId()));
+                    if (existing == null) {
+                        syncFromDanReport(du);
+                        result.setNewCount(result.getNewCount() + 1);
+                    } else {
+                        syncFromDanReport(du);
+                        result.setUpdateCount(result.getUpdateCount() + 1);
+                    }
+                } catch (Exception e) {
+                    result.setErrorCount(result.getErrorCount() + 1);
+                    log.error("同步 dan_report_uploads 失败 id={}", du.getId(), e);
+                }
+            }
+            for (ReportSummary es : existingDan) {
+                if (danReportUploadMapper.selectById(es.getSourceId()) == null) {
+                    markDiscarded("dan_report_uploads", es.getSourceId());
+                    result.setDiscardedCount(result.getDiscardedCount() + 1);
+                }
+            }
+        } catch (Exception e) {
+            log.error("全量同步 dan_report_uploads 失败", e);
+            result.setErrorCount(result.getErrorCount() + 1);
+        }
+
+        // 3. sync insurance_policies
+        try {
+            List<InsurancePolicy> policies = insurancePolicyMapper.selectList(new LambdaQueryWrapper<InsurancePolicy>());
+            List<ReportSummary> existingIns = reportSummaryMapper.selectList(
+                    new LambdaQueryWrapper<ReportSummary>().eq(ReportSummary::getSourceTable, "insurance_policies"));
+            for (InsurancePolicy p : policies) {
+                try {
+                    ReportSummary existing = reportSummaryMapper.selectOne(
+                            new LambdaQueryWrapper<ReportSummary>()
+                                    .eq(ReportSummary::getSourceTable, "insurance_policies")
+                                    .eq(ReportSummary::getSourceId, p.getId()));
+                    if (existing == null) {
+                        syncFromInsurancePolicy(p);
+                        result.setNewCount(result.getNewCount() + 1);
+                    } else {
+                        syncFromInsurancePolicy(p);
+                        result.setUpdateCount(result.getUpdateCount() + 1);
+                    }
+                } catch (Exception e) {
+                    result.setErrorCount(result.getErrorCount() + 1);
+                    log.error("同步 insurance_policies 失败 id={}", p.getId(), e);
+                }
+            }
+            for (ReportSummary es : existingIns) {
+                if (insurancePolicyMapper.selectById(es.getSourceId()) == null) {
+                    markDiscarded("insurance_policies", es.getSourceId());
+                    result.setDiscardedCount(result.getDiscardedCount() + 1);
+                }
+            }
+        } catch (Exception e) {
+            log.error("全量同步 insurance_policies 失败", e);
+            result.setErrorCount(result.getErrorCount() + 1);
+        }
+
+        // 4. sync family_fortune_report via JdbcTemplate
+        try {
+            String sql = "SELECT id, family_id, element, lucky_direction, pdf_path, file_size, created_at FROM family_fortune_report";
+            List<FamilyFortuneReport> reports = jdbcTemplate.query(sql, (rs, rowNum) -> {
+                FamilyFortuneReport r = new FamilyFortuneReport();
+                r.setId(rs.getLong("id"));
+                r.setFamilyId(rs.getInt("family_id"));
+                r.setElement(rs.getString("element"));
+                r.setLuckyDirection(rs.getString("lucky_direction"));
+                r.setPdfPath(rs.getString("pdf_path"));
+                r.setFileSize(rs.getLong("file_size"));
+                r.setCreatedAt(rs.getTimestamp("created_at"));
+                return r;
+            });
+
+            List<ReportSummary> existingFortune = reportSummaryMapper.selectList(
+                    new LambdaQueryWrapper<ReportSummary>().eq(ReportSummary::getSourceTable, "family_fortune_report"));
+            for (FamilyFortuneReport r : reports) {
+                try {
+                    ReportSummary existing = reportSummaryMapper.selectOne(
+                            new LambdaQueryWrapper<ReportSummary>()
+                                    .eq(ReportSummary::getSourceTable, "family_fortune_report")
+                                    .eq(ReportSummary::getSourceId, r.getId()));
+                    if (existing == null) {
+                        syncFromFamilyFortuneReport(r);
+                        result.setNewCount(result.getNewCount() + 1);
+                    } else {
+                        syncFromFamilyFortuneReport(r);
+                        result.setUpdateCount(result.getUpdateCount() + 1);
+                    }
+                } catch (Exception e) {
+                    result.setErrorCount(result.getErrorCount() + 1);
+                    log.error("同步 family_fortune_report 失败 id={}", r.getId(), e);
+                }
+            }
+            for (ReportSummary es : existingFortune) {
+                boolean exists = reports.stream().anyMatch(r -> r.getId().equals(es.getSourceId()));
+                if (!exists) {
+                    markDiscarded("family_fortune_report", es.getSourceId());
+                    result.setDiscardedCount(result.getDiscardedCount() + 1);
+                }
+            }
+        } catch (Exception e) {
+            log.error("全量同步 family_fortune_report 失败", e);
+            result.setErrorCount(result.getErrorCount() + 1);
+        }
+
+        log.info("全量同步完成: new={}, update={}, discarded={}, error={}",
+                result.getNewCount(), result.getUpdateCount(), result.getDiscardedCount(), result.getErrorCount());
+        return result;
+    }
+}

+ 178 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportSurveyService.java

@@ -0,0 +1,178 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.DietPreferences;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.ReportSurvey;
+import com.etotem.cfc.mapper.DietPreferencesMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.ReportSurveyMapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 报告调研问卷服务 — 报告上传后生成问卷,收集用户健康信息
+ */
+@Slf4j
+@Service
+public class ReportSurveyService {
+
+    @Resource
+    private ReportSurveyMapper reportSurveyMapper;
+
+    @Resource
+    private DietPreferencesMapper dietPreferencesMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /** 迁移504:报告调研问卷写入饮食偏好后重建用户当前食材推荐 */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 为报告创建调研问卷
+     */
+    @Transactional
+    public ReportSurvey createSurvey(Long reportId, Long userId, Long memberId) {
+        ReportSurvey survey = new ReportSurvey();
+        survey.setReportId(reportId);
+        survey.setUserId(userId);
+        survey.setMemberId(memberId);
+        survey.setStatus("pending");
+        survey.setCreatedAt(new Date());
+        survey.setUpdatedAt(new Date());
+        reportSurveyMapper.insert(survey);
+        log.info("报告调研问卷已创建: surveyId={}, reportId={}", survey.getId(), reportId);
+        return survey;
+    }
+
+    /**
+     * 提交调研问卷答案
+     */
+    @Transactional
+    public ReportSurvey submitSurvey(Long surveyId, String surveyData) {
+        ReportSurvey survey = reportSurveyMapper.selectById(surveyId);
+        if (survey == null) {
+            throw new RuntimeException("调研问卷不存在: " + surveyId);
+        }
+        survey.setSurveyData(surveyData);
+        survey.setStatus("completed");
+        survey.setUpdatedAt(new Date());
+        reportSurveyMapper.updateById(survey);
+        log.info("报告调研问卷已提交: surveyId={}", surveyId);
+        // 同步保存饮食偏好到 diet_preferences 表
+        try {
+            saveDietPreferencesFromSurvey(survey, surveyData);
+        } catch (Exception e) {
+            log.warn("同步饮食偏好失败(不影响问卷提交): {}", e.getMessage());
+        }
+        return survey;
+    }
+
+    private void saveDietPreferencesFromSurvey(ReportSurvey survey, String surveyData) {
+        JsonNode root;
+        try { root = objectMapper.readTree(surveyData); }
+        catch (Exception e) { log.warn("解析surveyData失败: {}", e.getMessage()); return; }
+        JsonNode surveyNode = root.has("survey") ? root.get("survey") : root;
+        Long memberId = survey.getMemberId();
+        if (memberId == null) return;
+
+        // 绝对忌口
+        JsonNode absAvoidNode = surveyNode.get("absoluteAvoid");
+        List<String> absoluteAvoid = new java.util.ArrayList<>();
+        if (absAvoidNode != null && absAvoidNode.isArray()) {
+            for (JsonNode n : absAvoidNode) absoluteAvoid.add(n.asText());
+        }
+        // 必须要吃
+        JsonNode mustEatNode = surveyNode.get("mustEat");
+        List<String> mustEat = new java.util.ArrayList<>();
+        if (mustEatNode != null && mustEatNode.isArray()) {
+            for (JsonNode n : mustEatNode) mustEat.add(n.asText());
+        }
+        // 宗教饮食
+        String religiousDiet = surveyNode.get("religiousDiet") != null
+                ? surveyNode.get("religiousDiet").asText() : "none";
+
+        // 查已存在的记录
+        LambdaQueryWrapper<DietPreferences> w = new LambdaQueryWrapper<>();
+        w.eq(DietPreferences::getFamilyMemberId, memberId);
+        DietPreferences prefs = dietPreferencesMapper.selectOne(w);
+        if (prefs == null) {
+            prefs = new DietPreferences();
+            prefs.setFamilyMemberId(memberId);
+            prefs.setFilledAt(new Date());
+        }
+        prefs.setAbsoluteAvoid(toJSON(absoluteAvoid));
+        prefs.setMustEat(toJSON(mustEat));
+        prefs.setReligiousDiet(religiousDiet);
+        prefs.setUpdatedAt(new Date());
+        if (prefs.getId() == null) {
+            dietPreferencesMapper.insert(prefs);
+        } else {
+            dietPreferencesMapper.updateById(prefs);
+        }
+        log.info("饮食偏好已同步: memberId={}, absoluteAvoid={}, mustEat={}, religiousDiet={}",
+                memberId, absoluteAvoid, mustEat, religiousDiet);
+
+        // 迁移504:报告问卷偏好变化后同步重算当前食材推荐(幂等,失败不影响问卷提交)
+        try {
+            FamilyMember member = familyMemberMapper.selectById(memberId);
+            Long uid = (member != null && member.getUserId() != null) ? member.getUserId() : memberId;
+            userCurrentFoodService.rebuildForUser(uid, memberId);
+        } catch (Exception e) {
+            log.warn("报告问卷保存后当前食材推荐重建失败 memberId={}: {}", memberId, e.getMessage());
+        }
+    }
+
+    private String toJSON(Object obj) {
+        try { return objectMapper.writeValueAsString(obj); }
+        catch (Exception e) { return null; }
+    }
+
+    /**
+     * 检查指定报告的调研问卷是否已完成
+     */
+    public boolean isSurveyCompleted(Long reportId) {
+        ReportSurvey survey = reportSurveyMapper.selectOne(
+                new LambdaQueryWrapper<ReportSurvey>()
+                        .eq(ReportSurvey::getReportId, reportId)
+                        .eq(ReportSurvey::getStatus, "completed")
+                        .last("LIMIT 1")
+        );
+        return survey != null;
+    }
+
+    /**
+     * 获取报告的调研问卷(已完成状态)
+     */
+    public ReportSurvey getCompletedSurvey(Long reportId) {
+        return reportSurveyMapper.selectOne(
+                new LambdaQueryWrapper<ReportSurvey>()
+                        .eq(ReportSurvey::getReportId, reportId)
+                        .eq(ReportSurvey::getStatus, "completed")
+                        .last("LIMIT 1")
+        );
+    }
+
+    /**
+     * 获取报告待填写的调研问卷
+     */
+    public ReportSurvey getPendingSurvey(Long reportId) {
+        return reportSurveyMapper.selectOne(
+                new LambdaQueryWrapper<ReportSurvey>()
+                        .eq(ReportSurvey::getReportId, reportId)
+                        .eq(ReportSurvey::getStatus, "pending")
+                        .last("LIMIT 1")
+        );
+    }
+}

+ 78 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportTemplateService.java

@@ -0,0 +1,78 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.IndicatorDefinition;
+import com.etotem.cfc.entity.ReportTemplate;
+import com.etotem.cfc.mapper.IndicatorDefinitionMapper;
+import com.etotem.cfc.mapper.ReportTemplateMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class ReportTemplateService {
+
+    @Resource
+    private ReportTemplateMapper reportTemplateMapper;
+
+    @Resource
+    private IndicatorDefinitionMapper indicatorDefinitionMapper;
+
+    public List<ReportTemplate> list(String reportType, Integer isActive) {
+        LambdaQueryWrapper<ReportTemplate> qw = new LambdaQueryWrapper<>();
+        if (reportType != null && !reportType.isEmpty()) {
+            qw.eq(ReportTemplate::getReportType, reportType);
+        }
+        if (isActive != null) {
+            qw.eq(ReportTemplate::getIsActive, isActive);
+        }
+        qw.orderByDesc(ReportTemplate::getId);
+        return reportTemplateMapper.selectList(qw);
+    }
+
+    public ReportTemplate getByReportType(String reportType) {
+        return reportTemplateMapper.selectOne(
+                new LambdaQueryWrapper<ReportTemplate>()
+                        .eq(ReportTemplate::getReportType, reportType));
+    }
+
+    public ReportTemplate save(ReportTemplate template) {
+        if (template.getId() != null) {
+            template.setUpdatedAt(new Date());
+            reportTemplateMapper.updateById(template);
+        } else {
+            template.setIsActive(template.getIsActive() != null ? template.getIsActive() : 1);
+            template.setConfig(template.getConfig() != null ? template.getConfig() : "{}");
+            template.setCreatedAt(new Date());
+            template.setUpdatedAt(new Date());
+            reportTemplateMapper.insert(template);
+        }
+        return template;
+    }
+
+    public void delete(Long id) {
+        reportTemplateMapper.deleteById(id);
+    }
+
+    public void toggle(Long id, Integer isActive) {
+        ReportTemplate t = reportTemplateMapper.selectById(id);
+        if (t != null) {
+            t.setIsActive(isActive);
+            t.setUpdatedAt(new Date());
+            reportTemplateMapper.updateById(t);
+        }
+    }
+
+    /** 获取可选指标列表,按领域过滤 */
+    public List<IndicatorDefinition> getAvailableIndicators(String domain) {
+        LambdaQueryWrapper<IndicatorDefinition> qw = new LambdaQueryWrapper<>();
+        if (domain != null && !domain.isEmpty()) {
+            qw.eq(IndicatorDefinition::getDomain, domain);
+        }
+        qw.eq(IndicatorDefinition::getStatus, 1);
+        qw.orderByAsc(IndicatorDefinition::getSortOrder);
+        return indicatorDefinitionMapper.selectList(qw);
+    }
+}

+ 327 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportTransferService.java

@@ -0,0 +1,327 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.ReportTransferRequest;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.ReportTransferRequestMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 健康报告跨家庭转移服务
+ *
+ * <p>同一份报告(file_hash 相同)被不同家庭上传时的归属转移审批:</p>
+ * <ol>
+ *   <li>申请方家庭发起转移申请(createRequest)→ 通知原家庭</li>
+ *   <li>原归属家庭同意(approve)→ health_reports.family_id 转移至申请方、subject_id 置空、
+ *       原成员重算维度分与食材推荐、原家庭不再可见(列表按 family_id 过滤)</li>
+ *   <li>原归属家庭拒绝(deny)→ 报告留在原家庭</li>
+ * </ol>
+ */
+@Slf4j
+@Service
+public class ReportTransferService {
+
+    @Resource
+    private ReportTransferRequestMapper transferRequestMapper;
+
+    @Resource
+    private HealthReportMapper healthReportMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    @Resource
+    private DimensionScoreService dimensionScoreService;
+
+    @Resource
+    private FoodRecommendService foodRecommendService;
+
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+
+    /**
+     * 发起跨家庭报告转移申请(申请方家庭)
+     *
+     * @param reportId          报告ID(上传重复检测返回的既有报告)
+     * @param requesterFamilyId 申请方家庭ID(当前登录用户所属家庭)
+     * @param requesterUserId   申请方用户ID
+     * @return 创建的转移申请
+     */
+    public ReportTransferRequest createRequest(Long reportId, Long requesterFamilyId, Long requesterUserId) {
+        if (reportId == null || requesterFamilyId == null) {
+            throw new RuntimeException("参数不完整");
+        }
+        HealthReport report = healthReportMapper.selectById(reportId);
+        if (report == null || !"active".equals(report.getStatus())) {
+            throw new RuntimeException("报告不存在或已删除");
+        }
+        if (report.getFamilyId() == null) {
+            throw new RuntimeException("报告未归属任何家庭,无需转移");
+        }
+        if (requesterFamilyId.equals(report.getFamilyId())) {
+            throw new RuntimeException("该报告已归属当前家庭");
+        }
+        // 同报告同申请家庭只允许一条待处理申请
+        List<ReportTransferRequest> pending = transferRequestMapper.selectList(
+                new LambdaQueryWrapper<ReportTransferRequest>()
+                        .eq(ReportTransferRequest::getReportId, reportId)
+                        .eq(ReportTransferRequest::getToFamilyId, requesterFamilyId)
+                        .eq(ReportTransferRequest::getStatus, ReportTransferRequest.STATUS_PENDING)
+                        .last("LIMIT 1"));
+        if (!pending.isEmpty()) {
+            throw new RuntimeException("转移申请已提交,等待原家庭同意");
+        }
+
+        ReportTransferRequest request = new ReportTransferRequest();
+        request.setReportId(reportId);
+        request.setFromFamilyId(report.getFamilyId());
+        request.setToFamilyId(requesterFamilyId);
+        request.setRequesterUserId(requesterUserId);
+        request.setStatus(ReportTransferRequest.STATUS_PENDING);
+        request.setCreatedAt(new Date());
+        request.setUpdatedAt(new Date());
+        transferRequestMapper.insert(request);
+        log.info("跨家庭报告转移申请已创建: requestId={}, reportId={}, fromFamily={}, toFamily={}",
+                request.getId(), reportId, report.getFamilyId(), requesterFamilyId);
+
+        // 通知原家庭(含报告上传者)
+        notifyFamilyUsers(report.getFamilyId(), report.getUserId(), "report_transfer_request",
+                "报告转移申请",
+                "有其他家庭申请将您的健康报告转入其家庭,请到「健康报告」列表处理。",
+                request.getId());
+        return request;
+    }
+
+    /**
+     * 同意转移(原归属家庭)
+     *
+     * <p>报告 family_id 转移至申请方、subject_id 置空(由新家庭重新归属);
+     * 原成员重算维度分与食材推荐;同报告其他待处理申请改由新归属家庭处理。</p>
+     *
+     * @param requestId         转移申请ID
+     * @param approverFamilyId  同意方家庭ID(必须为申请的原归属家庭)
+     * @param approverUserId    同意方用户ID
+     */
+    @Transactional
+    public void approve(Long requestId, Long approverFamilyId, Long approverUserId) {
+        ReportTransferRequest request = getRequest(requestId);
+        if (!ReportTransferRequest.STATUS_PENDING.equals(request.getStatus())) {
+            throw new RuntimeException("该申请已处理,请勿重复操作");
+        }
+        if (!request.getFromFamilyId().equals(approverFamilyId)) {
+            throw new RuntimeException("无权处理该申请");
+        }
+        HealthReport report = healthReportMapper.selectById(request.getReportId());
+        if (report == null || !"active".equals(report.getStatus())) {
+            throw new RuntimeException("报告不存在或已删除");
+        }
+        if (!request.getFromFamilyId().equals(report.getFamilyId())) {
+            throw new RuntimeException("报告归属已变更,请刷新后重试");
+        }
+
+        Long oldSubjectId = report.getSubjectId();
+
+        // 1. 报告转入申请方家庭,解除原成员归属(JdbcTemplate 以支持 subject_id = NULL)
+        jdbcTemplate.update(
+                "UPDATE health_reports SET family_id = ?, subject_id = NULL, updated_at = NOW() WHERE id = ?",
+                request.getToFamilyId(), report.getId());
+
+        // 2. 原成员重算维度分与食材推荐(移除该报告影响,与 deleteReport 同惯例)
+        if (oldSubjectId != null) {
+            try {
+                dimensionScoreService.refreshFromGutReport(oldSubjectId, report.getId());
+                log.info("报告转移后已重算原成员{}的7维健康评分", oldSubjectId);
+            } catch (Exception e) {
+                log.warn("报告转移后刷新原成员{}健康评分失败: {}", oldSubjectId, e.getMessage());
+            }
+            try {
+                foodRecommendService.recalculateForUser(oldSubjectId);
+            } catch (Exception e) {
+                log.warn("报告转移后刷新原成员{}食材推荐指数失败: {}", oldSubjectId, e.getMessage());
+            }
+        }
+
+        // 3. 同报告其他待处理申请改由新归属家庭处理(原家庭已不再拥有该报告)
+        transferRequestMapper.update(null, new LambdaUpdateWrapper<ReportTransferRequest>()
+                .eq(ReportTransferRequest::getReportId, report.getId())
+                .eq(ReportTransferRequest::getStatus, ReportTransferRequest.STATUS_PENDING)
+                .ne(ReportTransferRequest::getId, request.getId())
+                .set(ReportTransferRequest::getFromFamilyId, request.getToFamilyId())
+                .set(ReportTransferRequest::getUpdatedAt, new Date()));
+
+        // 4. 更新本申请状态
+        request.setStatus(ReportTransferRequest.STATUS_APPROVED);
+        request.setHandledBy(approverUserId);
+        request.setHandledAt(new Date());
+        request.setUpdatedAt(new Date());
+        transferRequestMapper.updateById(request);
+
+        // 5. 通知申请方
+        notifyFamilyUsers(request.getToFamilyId(), request.getRequesterUserId(), "report_transfer_result",
+                "报告转移申请已同意",
+                "您申请的健康报告已转入您的家庭,请到「健康报告」列表查看。",
+                request.getId());
+        log.info("跨家庭报告转移申请已同意: requestId={}, reportId={}, fromFamily={}, toFamily={}",
+                request.getId(), report.getId(), request.getFromFamilyId(), request.getToFamilyId());
+    }
+
+    /**
+     * 拒绝转移(原归属家庭)
+     *
+     * @param requestId        转移申请ID
+     * @param approverFamilyId 拒绝方家庭ID(必须为申请的原归属家庭)
+     * @param approverUserId   拒绝方用户ID
+     * @param remark           拒绝备注(可空)
+     */
+    public void deny(Long requestId, Long approverFamilyId, Long approverUserId, String remark) {
+        ReportTransferRequest request = getRequest(requestId);
+        if (!ReportTransferRequest.STATUS_PENDING.equals(request.getStatus())) {
+            throw new RuntimeException("该申请已处理,请勿重复操作");
+        }
+        if (!request.getFromFamilyId().equals(approverFamilyId)) {
+            throw new RuntimeException("无权处理该申请");
+        }
+        request.setStatus(ReportTransferRequest.STATUS_DENIED);
+        request.setHandledBy(approverUserId);
+        request.setHandledAt(new Date());
+        request.setRemark(remark);
+        request.setUpdatedAt(new Date());
+        transferRequestMapper.updateById(request);
+
+        // 通知申请方
+        notifyFamilyUsers(request.getToFamilyId(), request.getRequesterUserId(), "report_transfer_result",
+                "报告转移申请被拒绝",
+                "您申请的健康报告转移未获对方家庭同意。",
+                request.getId());
+        log.info("跨家庭报告转移申请已拒绝: requestId={}, reportId={}, byFamily={}",
+                request.getId(), request.getReportId(), approverFamilyId);
+    }
+
+    /**
+     * 查询本家庭相关的转移申请
+     *
+     * @param familyId 当前登录用户所属家庭
+     * @return {incoming: 待本家庭处理(原归属方), outgoing: 本家庭发起的(申请方)}
+     */
+    public Map<String, Object> listRequests(Long familyId) {
+        List<ReportTransferRequest> incoming = transferRequestMapper.selectList(
+                new LambdaQueryWrapper<ReportTransferRequest>()
+                        .eq(ReportTransferRequest::getFromFamilyId, familyId)
+                        .eq(ReportTransferRequest::getStatus, ReportTransferRequest.STATUS_PENDING)
+                        .orderByDesc(ReportTransferRequest::getCreatedAt));
+        List<ReportTransferRequest> outgoing = transferRequestMapper.selectList(
+                new LambdaQueryWrapper<ReportTransferRequest>()
+                        .eq(ReportTransferRequest::getToFamilyId, familyId)
+                        .orderByDesc(ReportTransferRequest::getCreatedAt)
+                        .last("LIMIT 50"));
+        Map<String, Object> result = new HashMap<>();
+        result.put("incoming", enrichWithReport(incoming));
+        result.put("outgoing", enrichWithReport(outgoing));
+        return result;
+    }
+
+    private ReportTransferRequest getRequest(Long requestId) {
+        if (requestId == null) {
+            throw new RuntimeException("申请ID不能为空");
+        }
+        ReportTransferRequest request = transferRequestMapper.selectById(requestId);
+        if (request == null) {
+            throw new RuntimeException("申请不存在");
+        }
+        return request;
+    }
+
+    /**
+     * 批量拼接报告摘要(personName/reportType/reportDate/overallScore),供前端列表展示
+     */
+    private List<Map<String, Object>> enrichWithReport(List<ReportTransferRequest> requests) {
+        List<Map<String, Object>> list = new ArrayList<>();
+        if (requests == null || requests.isEmpty()) {
+            return list;
+        }
+        Set<Long> reportIds = new LinkedHashSet<>();
+        for (ReportTransferRequest r : requests) {
+            reportIds.add(r.getReportId());
+        }
+        Map<Long, HealthReport> reportMap = new HashMap<>();
+        List<HealthReport> reports = healthReportMapper.selectBatchIds(reportIds);
+        for (HealthReport r : reports) {
+            reportMap.put(r.getId(), r);
+        }
+
+        for (ReportTransferRequest r : requests) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", r.getId());
+            m.put("reportId", r.getReportId());
+            m.put("status", r.getStatus());
+            m.put("remark", r.getRemark());
+            m.put("createdAt", r.getCreatedAt());
+            m.put("handledAt", r.getHandledAt());
+            HealthReport report = reportMap.get(r.getReportId());
+            if (report != null) {
+                m.put("personName", report.getPersonName());
+                m.put("reportType", report.getReportType());
+                m.put("reportDate", report.getReportDate());
+                m.put("overallScore", report.getOverallScore());
+                m.put("reportDeleted", false);
+            } else {
+                m.put("personName", "报告已删除");
+                m.put("reportType", null);
+                m.put("reportDate", null);
+                m.put("overallScore", null);
+                m.put("reportDeleted", true);
+            }
+            list.add(m);
+        }
+        return list;
+    }
+
+    /**
+     * 站内通知指定家庭的全部可登录用户(兜底额外通知者,如报告上传者)
+     *
+     * <p>模板缺失时回退默认文案,恒走 in_app 通道;通知失败不影响主流程。</p>
+     */
+    private void notifyFamilyUsers(Long familyId, Long fallbackUserId, String type,
+                                   String title, String content, Long refId) {
+        try {
+            Set<Long> userIds = new LinkedHashSet<>();
+            if (familyId != null) {
+                List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
+                        .eq(User::getFamilyId, familyId));
+                for (User u : users) {
+                    if (u.getId() != null) {
+                        userIds.add(u.getId());
+                    }
+                }
+            }
+            if (fallbackUserId != null) {
+                userIds.add(fallbackUserId);
+            }
+            for (Long uid : userIds) {
+                notificationDispatchService.sendByTemplate(type, uid, "report_transfer_request", refId, title, content);
+            }
+        } catch (Exception e) {
+            log.warn("报告转移通知发送失败: {}", e.getMessage());
+        }
+    }
+}

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

@@ -0,0 +1,309 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 商品关联关系自动挖掘服务
+ * 从订单数据中自动挖掘:
+ *   1. 共购关系:买了A的用户也买了B
+ *   2. 复购关系:同一用户反复购买同一商品
+ */
+@Service
+@Slf4j
+public class RepurchaseMiningService {
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Resource
+    private RecommendationProductAssociationMapper associationMapper;
+
+    @Resource
+    private FiveDimensionScoreMapper fiveDimensionScoreMapper;
+
+    /**
+     * 定时任务:每日挖掘关联关系
+     * - 共购关系:最近30天内的订单数据
+     * - 复购关系:同一用户同一商品的重复购买
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void dailyMineAssociations() {
+        log.info("开始每日关联关系挖掘任务");
+
+        // 1. 挖掘共购关系(最近30天)
+        mineCoPurchaseAssociations();
+
+        // 2. 挖掘复购关系
+        mineRepurchaseAssociations();
+
+        log.info("关联关系挖掘任务完成");
+    }
+
+    /**
+     * 挖掘共购关系
+     * 逻辑:在最近30天内,买过同一商品的用户对,计算共购次数
+     */
+    @Transactional(rollbackFor = Exception.class)
+    private void mineCoPurchaseAssociations() {
+        // 查询最近30天内已支付订单
+        LocalDate today = LocalDate.now();
+        LocalDate thirtyDaysAgo = today.minus(30, ChronoUnit.DAYS);
+
+        LambdaQueryWrapper<ProductOrder> qw = new LambdaQueryWrapper<ProductOrder>()
+                .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                .ge(ProductOrder::getCreatedAt, java.sql.Date.valueOf(thirtyDaysAgo))
+                .last("LIMIT 10000"); // 防止数据量过大,分页处理
+
+        List<ProductOrder> recentOrders = productOrderMapper.selectList(qw);
+        log.info("最近30天内已支付订单 {} 条", recentOrders.size());
+
+        if (recentOrders.isEmpty()) {
+            return;
+        }
+
+        // 按 product_id 分组,统计买家组合
+        Map<Long, List<Long>> productBuyers = new HashMap<>();
+        for (ProductOrder order : recentOrders) {
+            if (order.getProductId() == null || order.getBuyerId() == null) continue;
+            productBuyers.computeIfAbsent(order.getProductId(), k -> new ArrayList<>()).add(order.getBuyerId());
+        }
+
+        // 生成所有二元组(买A的用户,也可能买B)
+        // 为了性能,这里只处理购买次数>=2的商品
+        List<Map.Entry<Long, List<Long>>> filtered = productBuyers.entrySet().stream()
+                .filter(e -> e.getValue().size() >= 2)
+                .collect(Collectors.toList());
+
+        log.info("符合共购分析的商品数:{}", filtered.size());
+
+        for (Map.Entry<Long, List<Long>> entry : filtered) {
+            Long productId = entry.getKey();
+            List<Long> buyers = entry.getValue();
+
+            // 计算所有买家两两组合的共购情况
+            // 对于每对商品(productId, otherProductId),统计同时购买的用户数
+            for (int i = 0; i < buyers.size(); i++) {
+                Long buyer1 = buyers.get(i);
+
+                // 找出该用户在30天内买过的其他商品
+                Set<Long> otherProducts = new HashSet<>();
+                for (ProductOrder order : recentOrders) {
+                    if (order.getBuyerId().equals(buyer1)
+                            && order.getProductId() != null
+                            && !order.getProductId().equals(productId)) {
+                        otherProducts.add(order.getProductId());
+                    }
+                }
+
+                // 对于用户买过的每一个其他商品,记录共购关联
+                for (Long otherProductId : otherProducts) {
+                    // 检查关联是否已存在
+                    Long existingId = findExistingAssociation(productId, otherProductId, "co_purchase");
+                    if (existingId != null) {
+                        // 已存在,累计共购次数
+                        updateAssociationCount(existingId, 1);
+                    } else {
+                        // 不存在,创建新记录
+                        createAssociation(productId, otherProductId, "co_purchase", 1, 30, 1);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * 挖掘复购关系
+     * 逻辑:同一用户购买同一商品的多次订单,计算复购周期
+     */
+    @Transactional(rollbackFor = Exception.class)
+    private void mineRepurchaseAssociations() {
+        LambdaQueryWrapper<ProductOrder> qw = new LambdaQueryWrapper<ProductOrder>()
+                .in(ProductOrder::getStatus, "paid", "pending_receipt", "shipped", "completed")
+                .last("LIMIT 5000");
+
+        List<ProductOrder> allOrders = productOrderMapper.selectList(qw);
+        log.info("查询全部已支付订单 {} 条", allOrders.size());
+
+        if (allOrders.isEmpty()) {
+            return;
+        }
+
+        // 按 user_id + product_id 分组,统计每个用户每个商品的购买时间序列
+        Map<String, List<Long>> userProductDates = new HashMap<>();
+        for (ProductOrder order : allOrders) {
+            if (order.getBuyerId() == null || order.getProductId() == null) continue;
+            String key = order.getBuyerId() + ":" + order.getProductId();
+            if (order.getPaidAt() != null) {
+                long timestamp = order.getPaidAt().getTime();
+                userProductDates.computeIfAbsent(key, k -> new ArrayList<>()).add(timestamp);
+            } else if (order.getCreatedAt() != null) {
+                long timestamp = order.getCreatedAt().getTime();
+                userProductDates.computeIfAbsent(key, k -> new ArrayList<>()).add(timestamp);
+            }
+        }
+
+        // 过滤掉只买过一次的
+        List<Map.Entry<String, List<Long>>> multiplePurchases = userProductDates.entrySet().stream()
+                .filter(e -> e.getValue().size() >= 2)
+                .collect(Collectors.toList());
+
+        log.info("符合复购分析的用户商品组合:{}", multiplePurchases.size());
+
+        for (Map.Entry<String, List<Long>> entry : multiplePurchases) {
+            String[] parts = entry.getKey().split(":");
+            Long userId = Long.parseLong(parts[0]);
+            Long productId = Long.parseLong(parts[1]);
+            List<Long> dates = entry.getValue();
+
+            // 按时间排序
+            dates.sort(Comparator.naturalOrder());
+
+            // 计算相邻购买之间的天数差
+            List<Integer> intervalDays = new ArrayList<>();
+            for (int i = 1; i < dates.size(); i++) {
+                long diffMs = dates.get(i) - dates.get(i - 1);
+                long days = diffMs / (1000L * 60 * 60 * 24);
+                intervalDays.add((int) days);
+            }
+
+            // 计算平均复购周期
+            double avgInterval = intervalDays.stream().mapToInt(Integer::intValue).average().orElse(0);
+            int avgIntervalRounded = avgInterval > 0 ? (int) Math.round(avgInterval) : 30;
+
+            // 确定是否为规律复购(间隔相对稳定)
+            if (intervalDays.size() >= 2) {
+                // 计算方差,方差小说明规律
+                double mean = avgInterval;
+                double sumSquaredDiff = intervalDays.stream()
+                        .mapToDouble(d -> Math.pow(d - mean, 2))
+                        .sum();
+                double variance = intervalDays.size() > 0 ? sumSquaredDiff / intervalDays.size() : 0;
+                double stdDev = Math.sqrt(variance);
+
+                // 标准差小于平均间隔的一半,视为规律复购
+                boolean isRegular = stdDev < mean / 2 || stdDev < 7;
+
+                if (isRegular) {
+                    // 创建或更新复购关联
+                    Long existingId = findExistingAssociation(productId, productId, "repurchase");
+                    // 注意:repurchase 类型的 source=target,表示同一商品的复购
+                    // 实际上我们需要 source_product_id 和 target_product_id 可能指向同一个商品
+                    // 但根据模型设计,可能需要不同的商品关联...
+                    // 这里简化处理:记录 userId 的复购模式,但在 association 表中
+                    // source_product_id = productId, target_product_id = productId
+                    // 这表示“用户反复购买该商品”的模式标记
+
+                    if (existingId != null) {
+                        updateRepurchasePattern(existingId, avgIntervalRounded);
+                    } else {
+                        createRepurchaseAssociation(userId, productId, avgIntervalRounded);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * 查找现有关联记录ID
+     */
+    private Long findExistingAssociation(Long sourceProductId, Long targetProductId, String associationType) {
+        LambdaQueryWrapper<RecommendationProductAssociation> qw = new LambdaQueryWrapper<RecommendationProductAssociation>()
+                .eq(RecommendationProductAssociation::getSourceProductId, sourceProductId)
+                .eq(RecommendationProductAssociation::getTargetProductId, targetProductId)
+                .eq(RecommendationProductAssociation::getAssociationType, associationType)
+                .eq(RecommendationProductAssociation::getEnabled, 1);
+
+        RecommendationProductAssociation existing = associationMapper.selectOne(qw);
+        return existing != null ? existing.getId() : null;
+    }
+
+    /**
+     * 更新关联计数(共购次数 +1)
+     */
+    private void updateAssociationCount(Long associationId, int increment) {
+        // 简单的更新逻辑,实际生产建议使用 MySQL UPDATE
+        // 这里演示:读取后写入
+        RecommendationProductAssociation assoc = associationMapper.selectById(associationId);
+        if (assoc != null) {
+            int newCount = (assoc.getCoPurchaseCount() != null ? assoc.getCoPurchaseCount() : 0) + increment;
+            assoc.setCoPurchaseCount(newCount);
+
+            // 根据次数调整强度:次数越多强度越高
+            double strength = Math.min(1.0, newCount / 20.0);
+            assoc.setStrength(new BigDecimal(strength));
+
+            associationMapper.updateById(assoc);
+        }
+    }
+
+    /**
+     * 创建新的共购关联记录
+     */
+    private void createAssociation(Long sourceProductId, Long targetProductId,
+                                   String associationType, int coPurchaseCount,
+                                   int coPurchaseWindowDays, int manualOverride) {
+        RecommendationProductAssociation assoc = new RecommendationProductAssociation();
+        assoc.setSourceProductId(sourceProductId);
+        assoc.setTargetProductId(targetProductId);
+        assoc.setAssociationType(associationType);
+        assoc.setCoPurchaseCount(coPurchaseCount);
+        assoc.setCoPurchaseWindowDays(coPurchaseWindowDays);
+        assoc.setStrength(new BigDecimal(0.50)); // 初始强度
+        assoc.setManualOverride(manualOverride);
+        assoc.setEnabled(1);
+        assoc.setCreatedAt(new java.util.Date());
+        assoc.setUpdatedAt(new java.util.Date());
+        associationMapper.insert(assoc);
+        log.info("创建共购关联: source={} -> target={}, type={}, count={}", 
+                sourceProductId, targetProductId, associationType, coPurchaseCount);
+    }
+
+    /**
+     * 创建复购关联记录
+     */
+    private void createRepurchaseAssociation(Long userId, Long productId, int avgIntervalDays) {
+        RecommendationProductAssociation assoc = new RecommendationProductAssociation();
+        assoc.setSourceProductId(productId);
+        assoc.setTargetProductId(productId); // 复购关联:同一商品
+        assoc.setAssociationType("repurchase");
+        assoc.setRepurchaseDays(avgIntervalDays);
+        // strength: 越短周期强度越高
+        double strengthValue = 1.0 / Math.max(1, avgIntervalDays / 7.0);
+        assoc.setStrength(new BigDecimal(Math.min(1.0, strengthValue)));
+        assoc.setManualOverride(0);
+        assoc.setEnabled(1);
+        assoc.setCreatedAt(new java.util.Date());
+        assoc.setUpdatedAt(new java.util.Date());
+        associationMapper.insert(assoc);
+        log.info("创建复购关联: userId={} -> product={}, avgIntervalDays={}, strength={}", 
+                userId, productId, avgIntervalDays, strengthValue);
+    }
+
+    /**
+     * 更新复购周期模式
+     */
+    private void updateRepurchasePattern(Long associationId, int avgIntervalDays) {
+        RecommendationProductAssociation assoc = associationMapper.selectById(associationId);
+        if (assoc != null) {
+            assoc.setRepurchaseDays(avgIntervalDays);
+            double strengthValue = 1.0 / Math.max(1, avgIntervalDays / 7.0);
+            assoc.setStrength(new BigDecimal(Math.min(1.0, strengthValue)));
+            assoc.setUpdatedAt(new java.util.Date());
+            associationMapper.updateById(assoc);
+            log.info("更新复购周期: associationId={}, avgIntervalDays={}", associationId, avgIntervalDays);
+        }
+    }
+}

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

@@ -0,0 +1,176 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.RepurchaseReminderConfig;
+import com.etotem.cfc.entity.RepurchaseReminderRecord;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.RepurchaseReminderConfigMapper;
+import com.etotem.cfc.mapper.RepurchaseReminderRecordMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+@Service
+public class RepurchaseReminderService {
+
+    private static final Logger log = LoggerFactory.getLogger(RepurchaseReminderService.class);
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private RepurchaseReminderConfigMapper reminderConfigMapper;
+
+    @Resource
+    private RepurchaseReminderRecordMapper reminderRecordMapper;
+
+    /**
+     * 每日 09:00 扫描到期复购提醒
+     */
+    @Scheduled(cron = "0 0 9 * * ?")
+    public void scanAndCreateReminders() {
+        log.info("开始扫描复购提醒...");
+
+        // 1. 查询 30~60 天前已完成的订单
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_YEAR, -60);
+        Date fromDate = cal.getTime();
+        cal.add(Calendar.DAY_OF_YEAR, 30);
+        Date toDate = cal.getTime();
+
+        List<ProductOrder> orders = productOrderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getStatus, "completed")
+                        .ge(ProductOrder::getCreatedAt, fromDate)
+                        .lt(ProductOrder::getCreatedAt, toDate));
+
+        if (orders.isEmpty()) {
+            log.info("无到期复购订单");
+            return;
+        }
+
+        // 2. 加载所有启用的 config
+        List<RepurchaseReminderConfig> configs = reminderConfigMapper.selectList(
+                new LambdaQueryWrapper<RepurchaseReminderConfig>()
+                        .eq(RepurchaseReminderConfig::getEnabled, 1));
+
+        if (configs.isEmpty()) {
+            log.info("无复购提醒配置");
+            return;
+        }
+
+        // 3. 为每个订单匹配 config 并创建提醒
+        int created = 0;
+        for (ProductOrder order : orders) {
+            for (RepurchaseReminderConfig config : configs) {
+                if (!matchesConfig(order, config)) continue;
+
+                // 检查是否已发送过 reminder 且未超出最大次数
+                Long count = reminderRecordMapper.selectCount(
+                        new LambdaQueryWrapper<RepurchaseReminderRecord>()
+                                .eq(RepurchaseReminderRecord::getUserId, order.getBuyerId())
+                                .eq(RepurchaseReminderRecord::getProductId, order.getProductId()));
+
+                int maxReminders = config.getMaxReminders() != null ? config.getMaxReminders() : 3;
+                if (count != null && count >= maxReminders) {
+                    continue;
+                }
+
+                RepurchaseReminderRecord record = new RepurchaseReminderRecord();
+                record.setUserId(order.getBuyerId());
+                record.setProductId(order.getProductId());
+                record.setOrderId(order.getId());
+                record.setReminderDays(config.getReminderDays() != null ? config.getReminderDays() : 30);
+                record.setSentAt(new Date());
+                record.setClicked(0);
+                record.setPurchased(0);
+                reminderRecordMapper.insert(record);
+                created++;
+                log.info("已创建复购提醒: userId={}, productId={}", order.getBuyerId(), order.getProductId());
+            }
+        }
+
+        log.info("复购提醒扫描完成,共创建 {} 条", created);
+    }
+
+    /**
+     * 检查订单商品是否匹配提醒配置
+     */
+    private boolean matchesConfig(ProductOrder order, RepurchaseReminderConfig config) {
+        if (config.getProductId() != null) {
+            return config.getProductId().equals(order.getProductId());
+        }
+        if (config.getProductCategory() != null) {
+            Product product = productMapper.selectById(order.getProductId());
+            return product != null && config.getProductCategory().equals(product.getDomain());
+        }
+        return false;
+    }
+
+    /**
+     * 获取用户待处理的复购提醒
+     */
+    public List<Map<String, Object>> getPendingReminders(Long userId) {
+        List<RepurchaseReminderRecord> records = reminderRecordMapper.selectList(
+                new LambdaQueryWrapper<RepurchaseReminderRecord>()
+                        .eq(RepurchaseReminderRecord::getUserId, userId)
+                        .eq(RepurchaseReminderRecord::getPurchased, 0)
+                        .orderByDesc(RepurchaseReminderRecord::getSentAt));
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (RepurchaseReminderRecord record : records) {
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", record.getId());
+            item.put("productId", record.getProductId());
+            item.put("reminderDays", record.getReminderDays());
+            item.put("sentAt", record.getSentAt());
+            item.put("clicked", record.getClicked());
+
+            Product product = productMapper.selectById(record.getProductId());
+            if (product != null) {
+                item.put("productName", product.getName());
+                item.put("coverImage", product.getCoverImage());
+                item.put("price", product.getPrice());
+            }
+            result.add(item);
+        }
+        return result;
+    }
+
+    /**
+     * 标记提醒为已点击
+     */
+    @Transactional
+    public void onReminderClicked(Long reminderId) {
+        RepurchaseReminderRecord record = reminderRecordMapper.selectById(reminderId);
+        if (record != null) {
+            record.setClicked(1);
+            reminderRecordMapper.updateById(record);
+            log.info("复购提醒已点击: id={}", reminderId);
+        }
+    }
+
+    /**
+     * 标记提醒为已购买
+     */
+    @Transactional
+    public void onReminderPurchased(Long reminderId, Long orderId) {
+        RepurchaseReminderRecord record = reminderRecordMapper.selectById(reminderId);
+        if (record != null) {
+            record.setPurchased(1);
+            reminderRecordMapper.updateById(record);
+            log.info("复购提醒已购买: id={}, orderId={}", reminderId, orderId);
+        }
+    }
+}

+ 479 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ResourceService.java

@@ -0,0 +1,479 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Contact;
+import com.etotem.cfc.entity.ContactHelpLog;
+import com.etotem.cfc.entity.PearlInteractionLog;
+import com.etotem.cfc.entity.PearlInteractionReminder;
+import com.etotem.cfc.entity.ResourceItem;
+import com.etotem.cfc.enums.ConnectionType;
+import com.etotem.cfc.mapper.ContactHelpLogMapper;
+import com.etotem.cfc.mapper.ContactMapper;
+import com.etotem.cfc.mapper.PearlInteractionLogMapper;
+import com.etotem.cfc.mapper.PearlInteractionReminderMapper;
+import com.etotem.cfc.mapper.ResourceItemMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Service
+public class ResourceService {
+
+    @Resource
+    private ResourceItemMapper resourceItemMapper;
+
+    @Resource
+    private ContactMapper contactMapper;
+
+    @Resource
+    private ContactHelpLogMapper helpLogMapper;
+
+    @Resource
+    private PearlInteractionLogMapper pearlInteractionLogMapper;
+
+    @Resource
+    private PearlInteractionReminderMapper reminderMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    /** 25 类连接类型 → 前端选择器/渲染配置 */
+    public List<Map<String, Object>> getConnectionTypes() {
+        List<Map<String, Object>> list = new ArrayList<>();
+        for (ConnectionType t : ConnectionType.values()) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("code", t.name());
+            m.put("label", t.getLabel());
+            m.put("category", t.getCategory());
+            m.put("suggestIntervalMonth", t.getSuggestIntervalMonth());
+            list.add(m);
+        }
+        return list;
+    }
+
+    /** 珍珠图聚合:25 类社会连接 + 历史资源(legacy PERSON/SKILL/INFO/PLACE) */
+    public Result<Map<String, Object>> getPearlResources(Long userId) {
+        return Result.success(buildPearlData(userId));
+    }
+
+    /**
+     * 珍珠图家庭汇集:每个家庭成员一份珍珠资源 items(合并成一张图,按成员着色/标注)。
+     * 契约:data = { members: [ { memberId, memberName, memberType, colorKey, items: [原珍珠资源项结构] } ] }
+     */
+    public Result<Map<String, Object>> getFamilyPearlResources(Long familyId) {
+        List<Map<String, Object>> members = new ArrayList<>();
+        List<Map<String, Object>> familyMembers = energyService.collectFamilyMetricMembers(familyId);
+        for (Map<String, Object> member : familyMembers) {
+            Map<String, Object> memberEntry = new LinkedHashMap<>();
+            memberEntry.put("memberId", member.get("memberId"));
+            memberEntry.put("memberName", member.get("memberName"));
+            memberEntry.put("memberType", member.get("memberType"));
+            memberEntry.put("colorKey", member.get("colorKey"));
+            Object dataUserIdObj = member.get("dataUserId");
+            Long dataUserId = dataUserIdObj != null ? Long.valueOf(dataUserIdObj.toString()) : null;
+            memberEntry.put("items", dataUserId != null ? flattenPearlItems(buildPearlData(dataUserId)) : new ArrayList<>());
+            members.add(memberEntry);
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("members", members);
+        return Result.success(data);
+    }
+
+    /** 将珍珠图 groups + legacyGroups 展平为单层 items(带 groupType/groupTypeName/ring 归属,供合并图) */
+    @SuppressWarnings("unchecked")
+    private List<Map<String, Object>> flattenPearlItems(Map<String, Object> pearlData) {
+        List<Map<String, Object>> items = new ArrayList<>();
+        if (pearlData == null) {
+            return items;
+        }
+        Object groupsObj = pearlData.get("groups");
+        if (groupsObj instanceof List) {
+            for (Object g : (List<Object>) groupsObj) {
+                if (!(g instanceof Map)) continue;
+                Map<String, Object> group = (Map<String, Object>) g;
+                Object groupItems = group.get("items");
+                if (groupItems instanceof List) {
+                    for (Object it : (List<Object>) groupItems) {
+                        if (!(it instanceof Map)) continue;
+                        Map<String, Object> item = new LinkedHashMap<>((Map<String, Object>) it);
+                        item.put("groupType", group.get("type"));
+                        item.put("groupTypeName", group.get("typeName"));
+                        item.put("ring", group.get("ring"));
+                        items.add(item);
+                    }
+                }
+            }
+        }
+        Object legacyObj = pearlData.get("legacyGroups");
+        if (legacyObj instanceof List) {
+            for (Object g : (List<Object>) legacyObj) {
+                if (!(g instanceof Map)) continue;
+                Map<String, Object> group = (Map<String, Object>) g;
+                Object groupItems = group.get("items");
+                if (groupItems instanceof List) {
+                    for (Object it : (List<Object>) groupItems) {
+                        if (!(it instanceof Map)) continue;
+                        Map<String, Object> item = new LinkedHashMap<>((Map<String, Object>) it);
+                        item.put("groupType", group.get("type"));
+                        item.put("groupTypeName", group.get("typeName"));
+                        item.put("ring", "inner");
+                        items.add(item);
+                    }
+                }
+            }
+        }
+        return items;
+    }
+
+    /** 构建珍珠图原始数据(groups + legacyGroups) */
+    private Map<String, Object> buildPearlData(Long userId) {
+        // 历史资源:legacy 分组的 contacts(人脉)与 skillLogs(技能)照旧
+        List<Contact> contacts = contactMapper.selectList(
+                new LambdaQueryWrapper<Contact>().eq(Contact::getUserId, userId)
+        );
+        List<ContactHelpLog> skillLogs = helpLogMapper.selectList(
+                new LambdaQueryWrapper<ContactHelpLog>()
+                        .eq(ContactHelpLog::getUserId, userId)
+                        .eq(ContactHelpLog::getHelpType, "SKILL")
+                        .orderByDesc(ContactHelpLog::getHappenedAt)
+        );
+        List<ResourceItem> resourceItems = resourceItemMapper.selectList(
+                new LambdaQueryWrapper<ResourceItem>()
+                        .eq(ResourceItem::getUserId, userId)
+                        .orderByDesc(ResourceItem::getCreatedAt)
+        );
+
+        // 25 组社会连接:按 connection_type 分组
+        Map<String, List<Map<String, Object>>> connGroupMap = new LinkedHashMap<>();
+        Map<String, String> connTypeLabel = new LinkedHashMap<>();
+        for (ConnectionType t : ConnectionType.values()) {
+            connGroupMap.put(t.name(), new ArrayList<>());
+            connTypeLabel.put(t.name(), t.getLabel());
+        }
+        // 兼容历史数据:connection_type 为空的按原 type 归入 INFO/PLACE legacy
+        List<Map<String, Object>> legacyInfo = new ArrayList<>();
+        List<Map<String, Object>> legacyPlace = new ArrayList<>();
+
+        for (ResourceItem item : resourceItems) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", item.getId());
+            m.put("name", item.getName());
+            m.put("description", item.getDescription());
+            m.put("contactId", item.getContactId());
+            m.put("createdAt", item.getCreatedAt());
+            m.put("valueScore", item.getValueScore() != null ? item.getValueScore() : 0);
+            m.put("priority", item.getPriority() != null ? item.getPriority() : 2);
+            m.put("interactionCount", item.getInteractionCount() != null ? item.getInteractionCount() : 0);
+            m.put("lastInteractionAt", item.getLastInteractionAt());
+            if (item.getLastInteractionAt() != null) {
+                long days = ChronoUnit.DAYS.between(
+                        item.getLastInteractionAt().toInstant(), Instant.now());
+                m.put("daysSinceLast", (int) Math.max(0, days));
+            } else {
+                m.put("daysSinceLast", null);
+            }
+            String ct = item.getConnectionType();
+            if (ct != null && !ct.isEmpty() && connGroupMap.containsKey(ct)) {
+                connGroupMap.get(ct).add(m);
+            } else {
+                // 历史资源
+                if ("PLACE".equals(item.getType())) {
+                    legacyPlace.add(m);
+                } else {
+                    legacyInfo.add(m);
+                }
+            }
+        }
+
+        // 组装 25 组(按枚举顺序)
+        List<Map<String, Object>> groups = new ArrayList<>();
+        for (ConnectionType t : ConnectionType.values()) {
+            Map<String, Object> g = new LinkedHashMap<>();
+            g.put("type", t.name());
+            g.put("typeName", t.getLabel());
+            g.put("category", t.getCategory());
+            g.put("ring", "ESSENTIAL".equals(t.getCategory()) ? "inner" : "outer");
+            g.put("items", connGroupMap.get(t.name()));
+            groups.add(g);
+        }
+
+        // legacyGroups:人脉/技能/历史信息/历史场所
+        List<Map<String, Object>> legacyGroups = new ArrayList<>();
+        legacyGroups.add(group("PERSON", "人脉", contacts.stream().map(c -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", c.getId());
+            m.put("name", c.getName());
+            m.put("avatar", c.getAvatar());
+            m.put("relationshipType", c.getRelationshipType());
+            return m;
+        }).collect(Collectors.toList())));
+        legacyGroups.add(group("SKILL", "技能", buildSkillItems(skillLogs)));
+        legacyGroups.add(group("INFO", "信息", legacyInfo));
+        legacyGroups.add(group("PLACE", "场所", legacyPlace));
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("groups", groups);
+        result.put("legacyGroups", legacyGroups);
+        return result;
+    }
+
+    /** 登记资源(珍珠图:25 类社会连接,connectionType 必填) */
+    public Result<ResourceItem> addResourceItem(Long userId, String type, String connectionType,
+                                                String name, String description, Long contactId) {
+        if (connectionType == null || !ConnectionType.isValid(connectionType)) {
+            return Result.error("请选择有效的连接类型");
+        }
+        if (name == null || name.trim().isEmpty()) {
+            return Result.error("资源名称不能为空");
+        }
+        if (contactId != null) {
+            Contact contact = contactMapper.selectById(contactId);
+            if (contact == null || !contact.getUserId().equals(userId)) {
+                return Result.error("关联联系人不存在");
+            }
+        }
+
+        ResourceItem item = new ResourceItem();
+        item.setUserId(userId);
+        item.setType(type != null && !type.isEmpty() ? type : connectionType);
+        item.setConnectionType(connectionType);
+        item.setPriority(2);
+        item.setValueScore(50);
+        item.setName(name.trim());
+        item.setDescription(description != null ? description.trim() : null);
+        item.setContactId(contactId);
+        item.setInteractionCount(0);
+        item.setCreatedAt(new Date());
+        resourceItemMapper.insert(item);
+        return Result.success(item);
+    }
+
+    /** 删除登记的珍珠图资源 */
+    public Result<String> deleteResourceItem(Long userId, Long itemId) {
+        ResourceItem item = resourceItemMapper.selectById(itemId);
+        if (item == null || !item.getUserId().equals(userId)) {
+            return Result.error("资源不存在");
+        }
+        resourceItemMapper.deleteById(itemId);
+        return Result.success(null);
+    }
+
+    /** 记录一次互动并更新资源统计 */
+    public Result<Void> addInteraction(Long userId, Long itemId, String interactionType, String content) {
+        ResourceItem item = resourceItemMapper.selectById(itemId);
+        if (item == null || !item.getUserId().equals(userId)) {
+            return Result.error("资源不存在");
+        }
+        if (interactionType == null || !Arrays.asList("PHONE", "WECHAT", "MEETING", "OTHER").contains(interactionType)) {
+            return Result.error("互动方式不合法");
+        }
+
+        PearlInteractionLog log = new PearlInteractionLog();
+        log.setUserId(userId);
+        log.setResourceItemId(itemId);
+        log.setInteractionType(interactionType);
+        log.setContent(content != null ? content.trim() : null);
+        log.setHappenedAt(new Date());
+        log.setCreatedAt(new Date());
+        pearlInteractionLogMapper.insert(log);
+
+        item.setLastInteractionAt(log.getHappenedAt());
+        item.setInteractionCount((item.getInteractionCount() == null ? 0 : item.getInteractionCount()) + 1);
+        // 重新计算价值分(互动后价值提升)
+        List<PearlInteractionLog> logs = pearlInteractionLogMapper.selectList(
+                new LambdaQueryWrapper<PearlInteractionLog>()
+                        .eq(PearlInteractionLog::getResourceItemId, itemId)
+                        .orderByDesc(PearlInteractionLog::getHappenedAt)
+        );
+        item.setValueScore(calculateValueScore(item, logs));
+        resourceItemMapper.updateById(item);
+
+        // 关闭该资源的 PENDING 提醒
+        reminderMapper.update(null,
+                new LambdaUpdateWrapper<PearlInteractionReminder>()
+                        .eq(PearlInteractionReminder::getUserId, userId)
+                        .eq(PearlInteractionReminder::getResourceItemId, itemId)
+                        .eq(PearlInteractionReminder::getStatus, "PENDING")
+                        .set(PearlInteractionReminder::getStatus, "DONE")
+        );
+        return Result.success(null);
+    }
+
+    /** 互动历史(按时间倒序) */
+    public Result<List<Map<String, Object>>> getInteractionList(Long userId, Long itemId, int page, int size) {
+        ResourceItem item = resourceItemMapper.selectById(itemId);
+        if (item == null || !item.getUserId().equals(userId)) {
+            return Result.error("资源不存在");
+        }
+        List<PearlInteractionLog> logs = pearlInteractionLogMapper.selectList(
+                new LambdaQueryWrapper<PearlInteractionLog>()
+                        .eq(PearlInteractionLog::getResourceItemId, itemId)
+                        .orderByDesc(PearlInteractionLog::getHappenedAt)
+                        .last("LIMIT " + ((page - 1) * size) + "," + size)
+        );
+        List<Map<String, Object>> list = logs.stream().map(l -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", l.getId());
+            m.put("interactionType", l.getInteractionType());
+            m.put("content", l.getContent());
+            m.put("happenedAt", l.getHappenedAt());
+            return m;
+        }).collect(Collectors.toList());
+        return Result.success(list);
+    }
+
+    /** 手动覆盖优先级(1/2/3),覆盖后价值分同步调整 */
+    public Result<Void> updatePriority(Long userId, Long itemId, Integer priority) {
+        ResourceItem item = resourceItemMapper.selectById(itemId);
+        if (item == null || !item.getUserId().equals(userId)) {
+            return Result.error("资源不存在");
+        }
+        if (priority == null || priority < 1 || priority > 3) {
+            return Result.error("优先级不合法");
+        }
+        item.setPriority(priority);
+        // 手动覆盖时同步调整 valueScore 到一个合理档位
+        item.setValueScore(priority == 1 ? 80 : priority == 2 ? 50 : 20);
+        resourceItemMapper.updateById(item);
+        return Result.success(null);
+    }
+
+    /** 待办提醒列表(PENDING) */
+    public Result<List<Map<String, Object>>> getReminders(Long userId) {
+        List<PearlInteractionReminder> reminders = reminderMapper.selectList(
+                new LambdaQueryWrapper<PearlInteractionReminder>()
+                        .eq(PearlInteractionReminder::getUserId, userId)
+                        .eq(PearlInteractionReminder::getStatus, "PENDING")
+                        .orderByDesc(PearlInteractionReminder::getDaysSinceLast)
+        );
+        Map<Long, ResourceItem> itemMap = new HashMap<>();
+        List<Long> ids = reminders.stream().map(PearlInteractionReminder::getResourceItemId).collect(Collectors.toList());
+        if (!ids.isEmpty()) {
+            resourceItemMapper.selectBatchIds(ids).forEach(i -> itemMap.put(i.getId(), i));
+        }
+        List<Map<String, Object>> list = reminders.stream().map(r -> {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("id", r.getId());
+            m.put("resourceItemId", r.getResourceItemId());
+            ResourceItem ri = itemMap.get(r.getResourceItemId());
+            m.put("name", ri != null ? ri.getName() : "");
+            m.put("connectionType", r.getConnectionType());
+            m.put("suggestIntervalMonth", r.getSuggestIntervalMonth());
+            m.put("daysSinceLast", r.getDaysSinceLast());
+            return m;
+        }).collect(Collectors.toList());
+        return Result.success(list);
+    }
+
+    /** 自动计算价值分 0-100 */
+    public int calculateValueScore(ResourceItem item, List<PearlInteractionLog> logs) {
+        int score = 0;
+        // 1. 类型基础权重
+        ConnectionType ct = null;
+        for (ConnectionType t : ConnectionType.values()) {
+            if (t.name().equals(item.getConnectionType())) { ct = t; break; }
+        }
+        score += (ct != null && "ESSENTIAL".equals(ct.getCategory())) ? 30 : 20;
+        // 2. 近90天互动次数 × 5,上限 30
+        Date now = new Date();
+        Date ninetyDaysAgo = new Date(now.getTime() - 90L * 24 * 3600 * 1000);
+        int recent = 0;
+        if (logs != null) {
+            for (PearlInteractionLog l : logs) {
+                if (l.getHappenedAt() != null && l.getHappenedAt().after(ninetyDaysAgo)) recent++;
+            }
+        }
+        score += Math.min(recent * 5, 30);
+        // 3. 最近互动时效性
+        if (item.getLastInteractionAt() != null) {
+            long days = ChronoUnit.DAYS.between(item.getLastInteractionAt().toInstant(), Instant.now());
+            if (days <= 30) score += 20;
+            else if (days <= 90) score += 10;
+            else if (days <= 180) score += 5;
+        }
+        // 4. 互动总量 × 2,上限 20
+        int count = item.getInteractionCount() == null ? 0 : item.getInteractionCount();
+        score += Math.min(count * 2, 20);
+        return Math.min(score, 100);
+    }
+
+    /** 能力图聚合:SKILL 类帮助记录按联系人聚合为能力节点 */
+    public Result<List<Map<String, Object>>> getAbilityMap(Long userId) {
+        List<ContactHelpLog> skillLogs = helpLogMapper.selectList(
+                new LambdaQueryWrapper<ContactHelpLog>()
+                        .eq(ContactHelpLog::getUserId, userId)
+                        .eq(ContactHelpLog::getHelpType, "SKILL")
+                        .orderByDesc(ContactHelpLog::getHappenedAt)
+        );
+        List<Map<String, Object>> items = buildSkillItems(skillLogs);
+        return Result.success(items);
+    }
+
+    /** 按联系人聚合 SKILL 帮助记录为能力节点 */
+    private List<Map<String, Object>> buildSkillItems(List<ContactHelpLog> skillLogs) {
+        Map<Long, SkillAgg> aggMap = new HashMap<>();
+        for (ContactHelpLog log : skillLogs) {
+            SkillAgg agg = aggMap.computeIfAbsent(log.getContactId(), k -> new SkillAgg());
+            agg.contactId = log.getContactId();
+            agg.helpCount++;
+            if (log.getDescription() != null && !log.getDescription().trim().isEmpty()) {
+                agg.skillNames.add(log.getDescription().trim());
+            }
+            if (agg.lastHelpedAt == null || (log.getHappenedAt() != null && log.getHappenedAt().after(agg.lastHelpedAt))) {
+                agg.lastHelpedAt = log.getHappenedAt();
+            }
+        }
+
+        Map<Long, Contact> contactMap = new HashMap<>();
+        List<Long> ids = new ArrayList<>(aggMap.keySet());
+        if (!ids.isEmpty()) {
+            contactMapper.selectBatchIds(ids).forEach(c -> contactMap.put(c.getId(), c));
+        }
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (SkillAgg agg : aggMap.values()) {
+            Contact c = contactMap.get(agg.contactId);
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("contactId", agg.contactId);
+            m.put("name", c != null ? c.getName() : "");
+            m.put("avatar", c != null ? c.getAvatar() : "");
+            m.put("relationshipType", c != null ? c.getRelationshipType() : "");
+            m.put("skillCount", agg.helpCount);
+            m.put("skills", new ArrayList<>(agg.skillNames));
+            m.put("lastHelpedAt", agg.lastHelpedAt);
+            result.add(m);
+        }
+        result.sort((a, b) -> Integer.compare((Integer) b.get("skillCount"), (Integer) a.get("skillCount")));
+        return result;
+    }
+
+    private Map<String, Object> group(String type, String typeName, List<Map<String, Object>> items) {
+        Map<String, Object> g = new LinkedHashMap<>();
+        g.put("type", type);
+        g.put("typeName", typeName);
+        g.put("items", items);
+        return g;
+    }
+
+    /** 技能聚合中间类 */
+    private static class SkillAgg {
+        Long contactId;
+        int helpCount = 0;
+        Set<String> skillNames = new LinkedHashSet<>();
+        Date lastHelpedAt;
+    }
+}

+ 16 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReviewOrderService.java

@@ -0,0 +1,16 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.etotem.cfc.dto.ReviewOrderRequest;
+import com.etotem.cfc.dto.ReviewOrderResponse;
+import com.etotem.cfc.dto.ReviewStatusResponse;
+import com.etotem.cfc.entity.ReviewOrder;
+
+public interface ReviewOrderService extends IService<ReviewOrder> {
+
+    String createReview(ReviewOrderRequest request, Long reviewerId);
+
+    ReviewOrderResponse findByOrder(Long orderId);
+
+    ReviewStatusResponse getStats(Long orderId);
+}

+ 114 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReviewOrderServiceImpl.java

@@ -0,0 +1,114 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.dto.ReviewOrderRequest;
+import com.etotem.cfc.dto.ReviewOrderResponse;
+import com.etotem.cfc.dto.ReviewStatusResponse;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.ReviewOrder;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.ReviewOrderMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+public class ReviewOrderServiceImpl extends ServiceImpl<ReviewOrderMapper, ReviewOrder> implements ReviewOrderService {
+
+    @Resource
+    private ReviewOrderMapper reviewOrderMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    @Override
+    @Transactional
+    public String createReview(ReviewOrderRequest request, Long reviewerId) {
+        Long orderId = request.getOrderId();
+        ProductOrder order = productOrderMapper.selectById(orderId);
+        if (order == null) {
+            throw new RuntimeException("Order not found");
+        }
+        if (!"activity".equals(order.getProductType())) {
+            throw new RuntimeException("Only activity orders are reviewable");
+        }
+        boolean completed = "completed".equals(order.getStatus());
+        boolean signedIn = "signed_in".equals(order.getProvisionStatus());
+        if (!completed && !signedIn) {
+            throw new RuntimeException("Order is not eligible for review");
+        }
+
+        ReviewOrder existing = reviewOrderMapper.findByOrderId(orderId);
+        if (existing != null) {
+            throw new RuntimeException("Review already exists");
+        }
+
+        ReviewOrder review = new ReviewOrder();
+        review.setOrderId(orderId);
+        review.setReviewerId(reviewerId);
+        review.setRating(request.getRating());
+        review.setReviewText(request.getReviewText());
+        review.setReviewAt(new Date());
+        review.setOrganizationRating(request.getOrganizationRating());
+        review.setContentRating(request.getContentRating());
+        review.setExperienceRating(request.getExperienceRating());
+        review.setCreatedAt(new Date());
+        review.setUpdatedAt(new Date());
+        reviewOrderMapper.insert(review);
+        return "评价提交成功";
+    }
+
+    @Override
+    public ReviewOrderResponse findByOrder(Long orderId) {
+        ReviewOrder review = reviewOrderMapper.findByOrderId(orderId);
+        if (review == null) {
+            return null;
+        }
+        ReviewOrderResponse response = new ReviewOrderResponse();
+        response.setOrderId(review.getOrderId());
+        response.setReviewerId(review.getReviewerId());
+        response.setRating(review.getRating());
+        response.setReviewText(review.getReviewText());
+        response.setReviewAt(review.getReviewAt() != null ? review.getReviewAt().toString() : null);
+        response.setOrganizationRating(review.getOrganizationRating());
+        response.setContentRating(review.getContentRating());
+        response.setExperienceRating(review.getExperienceRating());
+        return response;
+    }
+
+    @Override
+    public ReviewStatusResponse getStats(Long orderId) {
+        ReviewOrder review = reviewOrderMapper.findByOrderId(orderId);
+        Map<String, Object> stats = reviewOrderMapper.getStatsByOrderId(orderId);
+
+        ReviewStatusResponse response = new ReviewStatusResponse();
+        response.setReviewed(review != null);
+        if (review != null) {
+            response.setRating(review.getRating());
+            response.setReviewText(review.getReviewText());
+            response.setReviewAt(review.getReviewAt() != null ? review.getReviewAt().toString() : null);
+            response.setOrganizationRating(review.getOrganizationRating());
+            response.setContentRating(review.getContentRating());
+            response.setExperienceRating(review.getExperienceRating());
+        }
+
+        if (stats != null && !stats.isEmpty()) {
+            Object overallAvgObj = stats.get("overallAvg");
+            Object organizationAvgObj = stats.get("organizationAvg");
+            Object contentAvgObj = stats.get("contentAvg");
+            Object experienceAvgObj = stats.get("experienceAvg");
+            Object totalReviewsObj = stats.get("totalReviews");
+
+            response.setOverallAvg(overallAvgObj != null ? ((Number) overallAvgObj).doubleValue() : null);
+            response.setOrganizationAvg(organizationAvgObj != null ? ((Number) organizationAvgObj).doubleValue() : null);
+            response.setContentAvg(contentAvgObj != null ? ((Number) contentAvgObj).doubleValue() : null);
+            response.setExperienceAvg(experienceAvgObj != null ? ((Number) experienceAvgObj).doubleValue() : null);
+            response.setTotalReviews(totalReviewsObj != null ? ((Number) totalReviewsObj).intValue() : 0);
+        }
+        return response;
+    }
+}

+ 993 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RewardRuleService.java

@@ -0,0 +1,993 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.config.ConfigService;
+import com.etotem.cfc.dto.RewardDisplayVO;
+import com.etotem.cfc.dto.RewardEstimateVO;
+import com.etotem.cfc.entity.CfEarnDailyLimit;
+import com.etotem.cfc.entity.CfEarnRule;
+import com.etotem.cfc.entity.CfBalanceLog;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.entity.GrowthTask;
+import com.etotem.cfc.entity.Reward;
+import com.etotem.cfc.mapper.CfBalanceLogMapper;
+import com.etotem.cfc.mapper.CfEarnDailyLimitMapper;
+import com.etotem.cfc.mapper.CfEarnRuleMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.mapper.GrowthTaskMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import com.etotem.cfc.mapper.RewardMapper;
+import com.etotem.cfc.util.CfFormulaEvaluator;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * CF 值预估服务(SC-X-22 预估展示层,契约唯一计算方)。
+ *
+ * <p>职责:
+ * <ul>
+ *   <li>按「当日有效规则」计算 {@code expectedCf}(正=获得、负=消耗、0=无奖励)。</li>
+ *   <li>预估旁路读:任何异常/超时均降级为「CF 奖励以实际为准」,不阻塞主流程。</li>
+ *   <li>产出点分类文案:获得型 / 消耗型 / 零值 / 触顶 / 降级。</li>
+ * </ul>
+ * </p>
+ *
+ * <p>口径见 docs/superpowers/specs/2026-11-05-sc-x22-cf-estimate-contract.md §2~§8。</p>
+ */
+@Slf4j
+@Service
+public class RewardRuleService {
+
+    // ==================== 操作类型常量(契约 §3 / §4.2) ====================
+    public static final String OP_TASK_COMPLETE = "TASK_COMPLETE";
+    public static final String OP_GROWTH_TASK   = "GROWTH_TASK";
+    public static final String OP_PURCHASE      = "PURCHASE";
+    public static final String OP_CHECKIN       = "CHECKIN";
+    public static final String OP_AUDIT         = "AUDIT";
+    public static final String OP_WISH          = "WISH";
+    public static final String OP_EXCHANGE      = "EXCHANGE";
+    public static final String OP_ASSESSMENT_REPORT = "ASSESSMENT_REPORT";
+
+    // ==================== display.type 常量 ====================
+    public static final String DISPLAY_EARN        = "EARN";
+    public static final String DISPLAY_SPEND       = "SPEND";
+    public static final String DISPLAY_ZERO        = "ZERO";
+    public static final String DISPLAY_LIMIT_HIT   = "LIMIT_HIT";
+    public static final String DISPLAY_DEGRADED    = "DEGRADED";
+
+    private static final long ESTIMATE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(3);
+    private static final String CURRENCY = "CF";
+
+    @Resource
+    private CfEarnRuleService cfEarnRuleService;
+
+    @Resource
+    private CfBalanceLogMapper cfBalanceLogMapper;
+
+    @Resource
+    private CfEarnDailyLimitMapper cfEarnDailyLimitMapper;
+
+    @Resource
+    private ConfigService configService;
+
+    @Resource
+    private com.etotem.cfc.mapper.FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private GrowthTaskMapper growthTaskMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    @Resource
+    private RewardMapper rewardMapper;
+
+    @Resource
+    private ObjectMapper objectMapper;
+
+    @Resource
+    @Lazy
+    private MembershipService membershipService;
+
+    // ==================== 对外入口 ====================
+
+    /**
+     * 预估 CF 值(旁路读,3s 超时兜底降级)。
+     *
+     * @param memberId     家庭成员 ID(family_members.id),服务端从 JWT 解析,客户端不可伪造
+     * @param operationType 操作类型(契约 §4.2)
+     * @param resourceType  资源类型
+     * @param resourceId    稳定业务单据 ID
+     * @param idempotencyKey 请求级幂等键(仅回显用,不参与计算)
+     * @return 预估 VO(失败时 display.type=DEGRADED、expectedCf=null)
+     */
+    public RewardEstimateVO estimate(Long memberId, String operationType,
+                                     String resourceType, String resourceId, String idempotencyKey) {
+        long start = System.currentTimeMillis();
+        try {
+            RewardEstimateVO vo = computeInternal(memberId, operationType, resourceType, resourceId);
+            vo.setOperationType(operationType);
+            vo.setResourceType(resourceType);
+            vo.setResourceId(resourceId);
+            vo.setIdempotencyKey(idempotencyKey);
+            log.debug("CF 预估完成:opType={} resourceId={} cf={} elapsed={}ms",
+                    operationType, resourceId, vo.getExpectedCf(), System.currentTimeMillis() - start);
+            return vo;
+        } catch (Exception e) {
+            long elapsed = System.currentTimeMillis() - start;
+            log.warn("CF 预估异常:opType={} resourceId={} err={} elapsed={}ms",
+                    operationType, resourceId, e.getMessage(), elapsed);
+            return degradedVO(operationType, resourceType, resourceId, idempotencyKey, elapsed);
+        }
+    }
+
+    /**
+     * 纯计算 expectedCf(无装饰字段):供产出点接口内嵌复用。
+     *
+     * @return int(正/负/0);规则缺失或内部异常返回 0,由调用方决定是否展示
+     */
+    public int estimateCf(Long memberId, String operationType, String resourceType, String resourceId) {
+        try {
+            RewardEstimateVO vo = computeInternal(memberId, operationType, resourceType, resourceId);
+            return vo.getExpectedCf() != null ? vo.getExpectedCf() : 0;
+        } catch (Exception e) {
+            log.warn("CF 预估异常(内嵌路径):opType={} err={}", operationType, e.getMessage());
+            return 0;
+        }
+    }
+
+    // ==================== 成员解析(供产出点接口内嵌复用) ====================
+
+    /** 登录 userId → 家庭成员 ID(与 CfEarnDispatchService.resolveMemberId 口径一致) */
+    public Long resolveMemberIdByUser(Long userId) {
+        if (userId == null || userId <= 0) {
+            return null;
+        }
+        com.etotem.cfc.entity.FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<com.etotem.cfc.entity.FamilyMember>()
+                        .eq(com.etotem.cfc.entity.FamilyMember::getUserId, userId)
+                        .orderByAsc(com.etotem.cfc.entity.FamilyMember::getId)
+                        .last("LIMIT 1"));
+        return member == null ? null : member.getId();
+    }
+
+    // ==================== 产出点内嵌挂载(契约 §4.3) ====================
+
+    /**
+     * 为单个 Task 挂载 expectedCf + display(F22 TASK_COMPLETE)。
+     * 预估为旁路读,任何异常静默忽略,不阻塞任务主流程。
+     */
+    public void attachTaskEstimate(Task task, Long memberId) {
+        if (task == null || task.getId() == null) {
+            return;
+        }
+        try {
+            RewardEstimateVO vo = estimate(memberId, OP_TASK_COMPLETE, "TASK",
+                    String.valueOf(task.getId()), null);
+            if (vo == null) {
+                return;
+            }
+            task.setExpectedCf(vo.getExpectedCf());
+            task.setDisplay(vo.getDisplay());
+        } catch (Exception e) {
+            log.warn("挂载任务预估失败 taskId={}:{}", task.getId(), e.getMessage());
+        }
+    }
+
+    /** 批量为任务列表挂载预估(B-22:N+1 → 批量查询 + 内存回填,不逐条 estimate())。 */
+    public void attachTaskListEstimate(List<Task> tasks, Long memberId) {
+        if (tasks == null || tasks.isEmpty() || memberId == null) {
+            return;
+        }
+        List<Long> taskIds = new ArrayList<>(tasks.size());
+        for (Task task : tasks) {
+            if (task != null && task.getId() != null) {
+                taskIds.add(task.getId());
+            }
+        }
+        if (taskIds.isEmpty()) {
+            return;
+        }
+        try {
+            // 1) 一次性收集 taskId → 批量加载任务上下文(单次查询,替代逐条 selectById)
+            Map<Long, Task> taskById = loadTasksByIds(taskIds);
+            // 2) 共享规则 + 日限上下文只解析一次(同一 memberId + TASK_COMPLETE→F22,全批一致)
+            TaskEstimateBatchCtx batchCtx = resolveTaskBatchCtx(memberId);
+            // 3) 内存回填:逐条独立降级,单条失败不影响其余;整批查询失败则跳过该批
+            for (Task task : tasks) {
+                if (task == null || task.getId() == null) {
+                    continue;
+                }
+                fillTaskEstimateFromBatch(task, taskById, batchCtx);
+            }
+        } catch (Exception e) {
+            // 批量查询异常:静默降级但可观测,跳过整个批次,不抛 500(契约 §8)
+            log.warn("批量挂载任务预估失败,跳过该批次 taskCount={} memberId={}:{}",
+                    tasks.size(), memberId, e.getMessage());
+        }
+    }
+
+    /** 批量加载任务(空闲 taskId 忽略),返回 id → Task 映射 */
+    private Map<Long, Task> loadTasksByIds(List<Long> taskIds) {
+        Map<Long, Task> taskById = new HashMap<>();
+        List<Task> loaded = taskMapper.selectBatchIds(taskIds);
+        if (loaded != null) {
+            for (Task t : loaded) {
+                if (t != null && t.getId() != null) {
+                    taskById.put(t.getId(), t);
+                }
+            }
+        }
+        return taskById;
+    }
+
+    /** 批量共享上下文(全批 TASK_COMPLETE 共用同一规则与日限状态) */
+    private static class TaskEstimateBatchCtx {
+        boolean ctxReady = false;      // false=规则缺失/停用/未生效 → 全批降级
+        CfEarnRule rule;
+        Map<String, Object> params;
+        String refType;
+        Integer dailyCountLimit;       // 日限次数(null=未配置)
+        Long todayCount;               // 今日已发次数(需次数闸门时解析)
+        double amountLimit;            // 金额闸门阈值(0=未启用)
+        Long todayEarned;              // 今日已获金额(需金额闸门时解析)
+    }
+
+    /** 解析批量共享上下文:规则加载一次 + 日限状态一次(替代逐条 estimate 内的重复查询) */
+    private TaskEstimateBatchCtx resolveTaskBatchCtx(Long memberId) {
+        TaskEstimateBatchCtx ctx = new TaskEstimateBatchCtx();
+        String ruleCode = OPERATION_TO_RULE.get(normalizeOpType(OP_TASK_COMPLETE));
+        CfEarnRule rule = cfEarnRuleService.getByCode(ruleCode);
+        if (rule == null || rule.getEnabled() == null || rule.getEnabled() != 1) {
+            return ctx;
+        }
+        Date now = new Date();
+        if (rule.getEffectiveFrom() != null && now.before(rule.getEffectiveFrom())) {
+            return ctx;
+        }
+        if (rule.getEffectiveTo() != null && now.after(rule.getEffectiveTo())) {
+            return ctx;
+        }
+        ctx.rule = rule;
+        ctx.params = parseParams(rule.getParamsJson());
+        ctx.refType = rule.getDedupRefType() != null && !rule.getDedupRefType().trim().isEmpty()
+                ? rule.getDedupRefType().trim() : ruleCode;
+        try {
+            // 日限上下文解析失败仅关闭闸门(与原 clampByDailyLimits 内部 catch → 返回原始值一致),不阻断批次
+            Integer dailyCountLimit = resolveDailyLimitCount(memberId, rule);
+            ctx.dailyCountLimit = dailyCountLimit;
+            if (dailyCountLimit != null && dailyCountLimit > 0) {
+                ctx.todayCount = countTodayEarn(memberId, ctx.refType);
+            }
+            double amountLimit = resolveAmountDailyLimit(rule);
+            ctx.amountLimit = amountLimit;
+            if (amountLimit > 0) {
+                ctx.todayEarned = sumTodayEarned(memberId, ctx.refType);
+            }
+        } catch (Exception e) {
+            log.warn("批量日限上下文解析失败,关闭日限闸门 memberId={} rule={}:{}",
+                    memberId, rule.getCode(), e.getMessage());
+        }
+        ctx.ctxReady = true;
+        return ctx;
+    }
+
+    /** 按批量共享上下文内存回填单条任务(不触发任何 DB 查询;单条异常降级,不影响其余) */
+    private void fillTaskEstimateFromBatch(Task task, Map<Long, Task> taskById, TaskEstimateBatchCtx ctx) {
+        try {
+            if (!ctx.ctxReady) {
+                // 规则缺失/停用/未生效 → 降级(与原 resolveRuleAndCtx.degraded 一致)
+                task.setExpectedCf(null);
+                task.setDisplay(degradedDisplay());
+                return;
+            }
+            Task loaded = taskById.get(task.getId());
+            if (loaded == null || loaded.getPoints() == null || loaded.getPoints() <= 0) {
+                // 任务不存在或无奖励积分 → 降级(与原 resolveCtx 返回 null 一致)
+                task.setExpectedCf(null);
+                task.setDisplay(degradedDisplay());
+                return;
+            }
+            Map<String, Object> perTaskCtx = new HashMap<>();
+            perTaskCtx.put("amount", loaded.getPoints());
+            perTaskCtx.put("task_id", task.getId());
+            int rawAmount = computeAmount(ctx.rule, ctx.params, perTaskCtx);
+            int clamped = clampBatchByDailyLimits(ctx, rawAmount);
+            task.setExpectedCf(clamped);
+            task.setDisplay(buildDisplay(clamped));
+        } catch (Exception e) {
+            log.warn("批量挂载单条任务预估失败 taskId={}:{}", task.getId(), e.getMessage());
+            task.setExpectedCf(null);
+            task.setDisplay(degradedDisplay());
+        }
+    }
+
+    /** 批量日限钳制:与 clampByDailyLimits 语义一致,仅使用预解析的共享上下文(内存计算) */
+    private int clampBatchByDailyLimits(TaskEstimateBatchCtx ctx, int rawAmount) {
+        if (ctx.dailyCountLimit != null && ctx.dailyCountLimit > 0 && ctx.todayCount != null) {
+            if (ctx.todayCount >= ctx.dailyCountLimit) {
+                return 0;
+            }
+        }
+        if (ctx.amountLimit > 0 && ctx.todayEarned != null) {
+            int remaining = (int) Math.max(0, Math.floor(ctx.amountLimit - ctx.todayEarned + 1e-6));
+            if (rawAmount > remaining) {
+                return remaining;
+            }
+        }
+        return rawAmount;
+    }
+
+    /** 降级展示(与 degradedVO 的 display 一致,供批量回填复用) */
+    private RewardDisplayVO degradedDisplay() {
+        RewardDisplayVO display = new RewardDisplayVO();
+        display.setType(DISPLAY_DEGRADED);
+        display.setTemplate("CF 奖励以实际为准");
+        display.setCfValue(0);
+        return display;
+    }
+
+    /** 为分页对象挂载预估(MyBatis-Plus IPage) */
+    public void attachTaskPageEstimate(com.baomidou.mybatisplus.core.metadata.IPage<Task> page, Long memberId) {
+        if (page == null) {
+            return;
+        }
+        attachTaskListEstimate(page.getRecords(), memberId);
+    }
+
+    /**
+     * 为成长任务 Map 列表挂载预估(F12 GROWTH_TASK)。
+     * Map 需含 "id"(growth_task.id);结果写回 map.expectedCf / map.display。
+     */
+    public void attachGrowthTaskMapEstimate(List<Map<String, Object>> items, Long memberId) {
+        if (items == null || items.isEmpty() || memberId == null) {
+            return;
+        }
+        for (Map<String, Object> item : items) {
+            if (item == null || item.get("id") == null) {
+                continue;
+            }
+            try {
+                RewardEstimateVO vo = estimate(memberId, OP_GROWTH_TASK, "GROWTH_TASK",
+                        String.valueOf(item.get("id")), null);
+                if (vo == null) {
+                    continue;
+                }
+                item.put("expectedCf", vo.getExpectedCf());
+                item.put("display", vo.getDisplay());
+            } catch (Exception e) {
+                log.warn("挂载成长任务预估失败 id={}:{}", item.get("id"), e.getMessage());
+            }
+        }
+    }
+
+    /** 为单个成长任务实体挂载预估(F12) */
+    public void attachGrowthTaskEstimate(GrowthTask gt, Long memberId) {
+        if (gt == null || gt.getId() == null) {
+            return;
+        }
+        try {
+            RewardEstimateVO vo = estimate(memberId, OP_GROWTH_TASK, "GROWTH_TASK",
+                    String.valueOf(gt.getId()), null);
+            if (vo == null) {
+                return;
+            }
+            gt.setExpectedCf(vo.getExpectedCf());
+            gt.setDisplay(vo.getDisplay());
+        } catch (Exception e) {
+            log.warn("挂载成长任务预估失败 id={}:{}", gt.getId(), e.getMessage());
+        }
+    }
+
+    // ==================== 内部计算 ====================
+
+    private RewardEstimateVO computeInternal(Long memberId, String operationType,
+                                             String resourceType, String resourceId) {
+        if (memberId == null || memberId <= 0) {
+            return degradedVO(operationType, resourceType, resourceId, null, 0);
+        }
+        Long rid = parseResourceId(resourceId);
+
+        // 1) 按 operationType 解析规则编码 + ctx
+        RuleCtx ruleCtx = resolveRuleAndCtx(memberId, operationType, resourceType, rid);
+        if (ruleCtx == null) {
+            // 消耗型或无法解析规则:走专项分支
+            return handleSpendOrUnresolvable(memberId, operationType, resourceType, rid);
+        }
+        if (ruleCtx.degraded) {
+            return degradedVO(operationType, resourceType, resourceId, null, 0);
+        }
+
+        // 2) 计算基础数量
+        int rawAmount = computeAmount(ruleCtx.rule, ruleCtx.params, ruleCtx.ctx);
+
+        // 3) 应用会员等级日限兜底 clamping(旁路读)
+        int clamped = clampByDailyLimits(memberId, ruleCtx.rule, ruleCtx.refType, rawAmount);
+
+        // 4) 构造展示 VO(触顶 clamped=0 时按 ZERO 处理;触顶原因由 clampByDailyLimits 判定)
+        RewardDisplayVO display = buildDisplay(clamped);
+        return buildEstimateVO(clamped, display, operationType, resourceType, resourceId, null, null);
+    }
+
+    /**
+     * 处理消耗型 / 无法对应 earn 规则的产出点(如 WISH 心愿兑换)。
+     * 这类产出点直接读业务实体,取负向 CF 值,不按规则发 earn。
+     */
+    private RewardEstimateVO handleSpendOrUnresolvable(Long memberId, String operationType,
+                                                       String resourceType, Long resourceId) {
+        int expectedCf = 0;
+        String displayType = DISPLAY_ZERO;
+        String reason = null;
+        try {
+            if (OP_WISH.equalsIgnoreCase(operationType) || "WISH".equalsIgnoreCase(operationType)) {
+                if (resourceId != null) {
+                    Reward reward = rewardMapper.selectById(resourceId);
+                    if (reward != null && reward.getPointsRequired() != null && reward.getPointsRequired() > 0) {
+                        expectedCf = -reward.getPointsRequired();
+                        displayType = DISPLAY_SPEND;
+                    }
+                }
+            } else if (OP_EXCHANGE.equalsIgnoreCase(operationType)) {
+                // 商城兑换/积分兑换商品:从 resourceType 区分,暂时降级(无统一规则)
+                return degradedVO(operationType, resourceType, resourceId == null ? null : String.valueOf(resourceId),
+                        null, 0);
+            } else if (OP_CHECKIN.equalsIgnoreCase(operationType)
+                    || "ACTIVITY_CHECKIN".equalsIgnoreCase(operationType)) {
+                // ACTIVITY_CHECKIN 已映射到 F05,不应走到这里
+                return degradedVO(operationType, resourceType, resourceId == null ? null : String.valueOf(resourceId),
+                        null, 0);
+            }
+        } catch (Exception e) {
+            log.warn("消耗型预估异常 opType={} err={}", operationType, e.getMessage());
+            return degradedVO(operationType, resourceType,
+                    resourceId == null ? null : String.valueOf(resourceId), null, 0);
+        }
+        RewardDisplayVO display = buildDisplay(expectedCf, displayType);
+        return buildEstimateVO(expectedCf, display, operationType, resourceType,
+                resourceId == null ? null : String.valueOf(resourceId), null, reason);
+    }
+
+    // ==================== 规则与 ctx 解析 ====================
+
+    private static final Map<String, String> OPERATION_TO_RULE = new HashMap<>();
+    static {
+        // key=operationType(大小写不敏感匹配)
+        OPERATION_TO_RULE.put("TASK_COMPLETE", "F22");
+        OPERATION_TO_RULE.put("AUDIT", "F22");
+        OPERATION_TO_RULE.put("GROWTH_TASK", "F12");
+        OPERATION_TO_RULE.put("PURCHASE", "F02");
+        OPERATION_TO_RULE.put("CHECKIN", "F05");
+        OPERATION_TO_RULE.put("ACTIVITY_CHECKIN", "F05");
+        OPERATION_TO_RULE.put("ASSESSMENT_REPORT", "F09");
+    }
+
+    private class RuleCtx {
+        CfEarnRule rule;
+        Map<String, Object> params;
+        Map<String, Object> ctx;
+        String refType;
+        boolean degraded = false;
+    }
+
+    private RuleCtx resolveRuleAndCtx(Long memberId, String operationType, String resourceType, Long resourceId) {
+        String ruleCode = OPERATION_TO_RULE.get(normalizeOpType(operationType));
+        if (ruleCode == null) {
+            return null;
+        }
+        CfEarnRule rule = cfEarnRuleService.getByCode(ruleCode);
+        if (rule == null || rule.getEnabled() == null || rule.getEnabled() != 1) {
+            RuleCtx rc = new RuleCtx();
+            rc.rule = rule;
+            rc.degraded = true;
+            return rc;
+        }
+        Date now = new Date();
+        if (rule.getEffectiveFrom() != null && now.before(rule.getEffectiveFrom())) {
+            RuleCtx rc = new RuleCtx();
+            rc.rule = rule;
+            rc.degraded = true;
+            return rc;
+        }
+        if (rule.getEffectiveTo() != null && now.after(rule.getEffectiveTo())) {
+            RuleCtx rc = new RuleCtx();
+            rc.rule = rule;
+            rc.degraded = true;
+            return rc;
+        }
+        Map<String, Object> params = parseParams(rule.getParamsJson());
+        String refType = rule.getDedupRefType() != null && !rule.getDedupRefType().trim().isEmpty()
+                ? rule.getDedupRefType().trim() : ruleCode;
+
+        Map<String, Object> ctx = resolveCtx(operationType, resourceType, resourceId, ruleCode);
+        if (ctx == null) {
+            RuleCtx rc = new RuleCtx();
+            rc.degraded = true;
+            return rc;
+        }
+
+        RuleCtx rc = new RuleCtx();
+        rc.rule = rule;
+        rc.params = params;
+        rc.ctx = ctx;
+        rc.refType = refType;
+        return rc;
+    }
+
+    private Map<String, Object> resolveCtx(String operationType, String resourceType,
+                                           Long resourceId, String ruleCode) {
+        if (resourceId == null) {
+            return null;
+        }
+        switch (normalizeOpType(operationType)) {
+            case "TASK_COMPLETE":
+            case "AUDIT": {
+                Task task = taskMapper.selectById(resourceId);
+                if (task == null || task.getPoints() == null || task.getPoints() <= 0) {
+                    return null;
+                }
+                Map<String, Object> ctx = new HashMap<>();
+                ctx.put("amount", task.getPoints());
+                ctx.put("task_id", resourceId);
+                return ctx;
+            }
+            case "GROWTH_TASK": {
+                GrowthTask gt = growthTaskMapper.selectById(resourceId);
+                if (gt == null || gt.getRewardPoints() == null || gt.getRewardPoints() <= 0) {
+                    return null;
+                }
+                Map<String, Object> ctx = new HashMap<>();
+                ctx.put("amount", gt.getRewardPoints());
+                ctx.put("task_key", gt.getTaskKey());
+                return ctx;
+            }
+            case "PURCHASE": {
+                // resourceId 可能是商品 ID(直接下单预估消费返 CF)或订单 ID
+                // 优先按商品价计算;其次按订单
+                Product product = productMapper.selectById(resourceId);
+                if (product != null && product.getPrice() != null && product.getPrice() > 0) {
+                    Map<String, Object> ctx = new HashMap<>();
+                    ctx.put("amt", product.getPrice()); // price 单位是分(商品定价分)
+                    ctx.put("product_id", resourceId);
+                    return ctx;
+                }
+                // 回退:按订单(暂不支持订单维度反向解析,降级)
+                return null;
+            }
+            case "CHECKIN":
+            case "ACTIVITY_CHECKIN": {
+                // resourceType = ACTIVITY_CHECKIN; resourceId = activityId 等,此处简化处理
+                // 活动签到 CF 取自活动配置 activities.platform_points,需通过 ActivityService 解析
+                // 本实现按 resourceType 透传至 ctx,由公式参数解决(如无具体实现则返回 null 降级)
+                Map<String, Object> ctx = new HashMap<>();
+                ctx.put("activity_id", resourceId);
+                ctx.put("checkin_id", resourceId);
+                return ctx;
+            }
+            case "ASSESSMENT_REPORT": {
+                // F09 数量依赖「是否首份报告」——需读账本判断;降级为 ctx.first_report=true 估算(首份上限)
+                Map<String, Object> ctx = new HashMap<>();
+                ctx.put("first_report", true);
+                ctx.put("report_ref", resourceId);
+                return ctx;
+            }
+            default:
+                return null;
+        }
+    }
+
+    // ==================== 数量计算 ====================
+
+    /**
+     * 按规则计算发放数量:fixed 取 amount;formula 用白名单求值器;per_item 取 ctx.amount/qty。
+     * 与 {@code CfBalanceServiceImpl.computeAmount} 语义对齐,供预估旁路复用。
+     */
+    private int computeAmount(CfEarnRule rule, Map<String, Object> params, Map<String, Object> ctx) {
+        String ruleType = rule.getRuleType() == null ? "" : rule.getRuleType().trim().toLowerCase();
+        double base;
+        switch (ruleType) {
+            case "fixed":
+                if (rule.getAmount() == null) {
+                    throw new IllegalArgumentException("规则 " + rule.getCode() + " 未配置固定数量 amount");
+                }
+                base = rule.getAmount();
+                break;
+            case "formula":
+                base = evaluateFormula(rule, params, ctx);
+                break;
+            case "per_item":
+                base = perItemAmount(rule.getCode(), ctx);
+                break;
+            default:
+                throw new IllegalArgumentException("未知的规则类型:" + rule.getRuleType());
+        }
+        base = base * resolveMultiplier(params);
+        if (base > Integer.MAX_VALUE) {
+            throw new IllegalArgumentException("规则 " + rule.getCode() + " 计算数量溢出");
+        }
+        return (int) Math.floor(base + 1e-6);
+    }
+
+    private double evaluateFormula(CfEarnRule rule, Map<String, Object> params, Map<String, Object> ctx) {
+        String formula = rule.getFormula();
+        if (formula == null || formula.trim().isEmpty()) {
+            throw new IllegalArgumentException("规则 " + rule.getCode() + " 缺少计算公式 formula");
+        }
+        Map<String, Object> vars = new HashMap<>();
+        if (params != null) {
+            vars.putAll(params);
+        }
+        if (ctx != null) {
+            vars.putAll(ctx);
+        }
+        applyAmountUnitConversion(vars, params);
+        return CfFormulaEvaluator.evaluate(formula, vars, cfgResolver());
+    }
+
+    private void applyAmountUnitConversion(Map<String, Object> vars, Map<String, Object> params) {
+        if (params == null || !"cent".equalsIgnoreCase(String.valueOf(params.get("amt_unit")).trim())) {
+            return;
+        }
+        Object raw = vars.get("amt");
+        if (raw == null) {
+            return;
+        }
+        double cents = toDouble(raw, "amt");
+        vars.put("amt", cents * resolveCfPerYuan(params) / 100.0);
+    }
+
+    private double resolveCfPerYuan(Map<String, Object> params) {
+        if (params != null && params.get("cf_per_yuan") != null) {
+            return toDouble(params.get("cf_per_yuan"), "cf_per_yuan");
+        }
+        String value = configService.getConfig("cf.rate.cf_per_yuan");
+        if (value == null || value.trim().isEmpty()) {
+            throw new IllegalStateException("缺少配置 cf.rate.cf_per_yuan");
+        }
+        return toDouble(value, "cf.rate.cf_per_yuan");
+    }
+
+    private double perItemAmount(String ruleCode, Map<String, Object> ctx) {
+        if (ctx != null && ctx.get("amount") != null) {
+            return toDouble(ctx.get("amount"), "ctx.amount");
+        }
+        if (ctx != null && ctx.get("qty") != null) {
+            double perItem = toDouble(ctx.get("qty"), "ctx.qty");
+            Object count = ctx.get("count");
+            return count == null ? perItem : perItem * toDouble(count, "ctx.count");
+        }
+        throw new IllegalArgumentException("规则 " + ruleCode + " 缺少发放数量上下文(amount / qty)");
+    }
+
+    private double resolveMultiplier(Map<String, Object> params) {
+        if (params == null) {
+            return 1.0;
+        }
+        Object key = params.get("multiplier_key");
+        if (key != null && !String.valueOf(key).trim().isEmpty()) {
+            String value = configService.getConfig(String.valueOf(key).trim());
+            if (value == null || value.trim().isEmpty()) {
+                throw new IllegalStateException("缺少配置倍数值:" + key);
+            }
+            return toDouble(value, "multiplier_key " + key);
+        }
+        Object multiplier = params.get("multiplier");
+        return multiplier == null ? 1.0 : toDouble(multiplier, "multiplier");
+    }
+
+    private Map<String, Object> parseParams(String paramsJson) {
+        if (paramsJson == null || paramsJson.trim().isEmpty()) {
+            return new HashMap<>();
+        }
+        try {
+            return objectMapper.readValue(paramsJson, new TypeReference<Map<String, Object>>() {});
+        } catch (Exception e) {
+            log.warn("解析规则 params_json 失败:{}", e.getMessage());
+            return new HashMap<>();
+        }
+    }
+
+    private java.util.function.Function<String, Object> cfgResolver() {
+        return key -> {
+            String value = configService.getConfig(key);
+            if (value == null || value.trim().isEmpty()) {
+                return null;
+            }
+            try {
+                return Double.parseDouble(value.trim());
+            } catch (NumberFormatException e) {
+                return value;
+            }
+        };
+    }
+
+    // ==================== 日限 Clamping ====================
+
+    /**
+     * 按今日已发放次数/数量,将预估数量钳制到剩余可用额度。
+     *
+     * <p>双重闸门:
+     * <ol>
+     *   <li>会员等级日限(次数):{@code cf_earn_daily_limit} × 规则 {@code daily_limit_per_member} 取更严格者;</li>
+     *   <li>规则 params 声明 {@code daily_limit_amount} 时:额外按累计金额钳制(金额闸门)。</li>
+     * </ol>
+     * 命中任一闸门 → expectedCf 按剩余额度缩小,不再返回原始计算值。
+     */
+    private int clampByDailyLimits(Long memberId, CfEarnRule rule, String refType, int rawAmount) {
+        try {
+            // 1) 次数闸门(会员等级日限 × 规则日限,取更严格者)
+            Integer dailyCountLimit = resolveDailyLimitCount(memberId, rule);
+            if (dailyCountLimit != null && dailyCountLimit > 0) {
+                long todayCount = countTodayEarn(memberId, refType);
+                if (todayCount >= dailyCountLimit) {
+                    return 0;
+                }
+            }
+            // 2) 金额闸门(可选,params 显式声明时启用)
+            double amountLimit = resolveAmountDailyLimit(rule);
+            if (amountLimit > 0) {
+                long todayEarned = sumTodayEarned(memberId, refType);
+                int remaining = (int) Math.max(0, Math.floor(amountLimit - todayEarned + 1e-6));
+                if (rawAmount > remaining) {
+                    return remaining;
+                }
+            }
+            return rawAmount;
+        } catch (Exception e) {
+            log.warn("日限 clamp 异常:memberId={} rule={} err={}", memberId, rule.getCode(), e.getMessage());
+            return rawAmount;
+        }
+    }
+
+    /**
+     * 会员等级日限次数:{@code cf_earn_daily_limit}(等级+规则)与规则 {@code daily_limit_per_member} 取更严格者。
+     * 等级由成员 → 家庭 → 当前会员等级解析(旁路读,失败按 FREE)。
+     */
+    private Integer resolveDailyLimitCount(Long memberId, CfEarnRule rule) {
+        Integer ruleLimit = rule.getDailyLimitPerMember();
+        Integer tierLimit = null;
+        try {
+            String levelCode = resolveLevelCode(memberId);
+            if (levelCode != null && rule.getCode() != null) {
+                CfEarnDailyLimit limit = cfEarnDailyLimitMapper.selectOne(
+                        new LambdaQueryWrapper<CfEarnDailyLimit>()
+                                .eq(CfEarnDailyLimit::getRuleCode, rule.getCode())
+                                .eq(CfEarnDailyLimit::getLevelCode, levelCode)
+                                .last("LIMIT 1"));
+                if (limit != null && limit.getDailyLimit() != null) {
+                    tierLimit = limit.getDailyLimit();
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析会员等级日限失败 rule={} err={}", rule.getCode(), e.getMessage());
+        }
+        if (tierLimit == null) {
+            return ruleLimit;
+        }
+        if (ruleLimit == null) {
+            return tierLimit;
+        }
+        return Math.min(tierLimit, ruleLimit);
+    }
+
+    /** 成员 → 家庭 → 当前会员等级(旁路读;无家庭/未开通按 FREE) */
+    private String resolveLevelCode(Long memberId) {
+        try {
+            com.etotem.cfc.entity.FamilyMember member =
+                    familyMemberMapper.selectById(memberId);
+            if (member == null || member.getFamilyId() == null) {
+                return "FREE";
+            }
+            com.etotem.cfc.dto.MembershipLevelDTO level = membershipService.getCurrentLevel(member.getFamilyId());
+            if (level != null && level.getLevelCode() != null && !level.getLevelCode().trim().isEmpty()) {
+                return level.getLevelCode().trim();
+            }
+        } catch (Exception e) {
+            log.warn("解析会员等级失败 memberId={}:{}", memberId, e.getMessage());
+        }
+        return "FREE";
+    }
+
+    private long countTodayEarn(Long memberId, String refType) {
+        Long count = cfBalanceLogMapper.selectCount(new LambdaQueryWrapper<CfBalanceLog>()
+                .eq(CfBalanceLog::getMemberId, memberId)
+                .eq(CfBalanceLog::getType, "earn")
+                .eq(CfBalanceLog::getRefType, refType)
+                .ge(CfBalanceLog::getCreatedAt, startOfDay(new Date())));
+        return count == null ? 0L : count;
+    }
+
+    /** 当日该 refType 累计已获得 CF 数量(用于金额闸门) */
+    private long sumTodayEarned(Long memberId, String refType) {
+        List<Object> amounts = cfBalanceLogMapper.selectObjs(
+                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CfBalanceLog>()
+                        .select("amount")
+                        .eq("member_id", memberId)
+                        .eq("type", "earn")
+                        .eq("ref_type", refType)
+                        .ge("created_at", startOfDay(new Date())));
+        long sum = 0;
+        if (amounts != null) {
+            for (Object amount : amounts) {
+                if (amount != null) {
+                    try {
+                        sum += Long.parseLong(String.valueOf(amount));
+                    } catch (NumberFormatException ignored) {
+                        // 非数值行忽略
+                    }
+                }
+            }
+        }
+        return sum;
+    }
+
+    /** 金额闸门阈值:规则 params.daily_limit_amount 优先,其次 service_config cf.estimate.daily_limit_amount */
+    private double resolveAmountDailyLimit(CfEarnRule rule) {
+        if (rule == null || rule.getParamsJson() == null) {
+            return 0;
+        }
+        try {
+            Map<String, Object> params = objectMapper.readValue(rule.getParamsJson(),
+                    new TypeReference<Map<String, Object>>() {});
+            if (params != null && params.get("daily_limit_amount") != null) {
+                return toDouble(params.get("daily_limit_amount"), "daily_limit_amount");
+            }
+        } catch (Exception e) {
+            log.warn("解析规则 params_json 失败 code={}:{}", rule.getCode(), e.getMessage());
+        }
+        String cfg = configService.getConfig("cf.estimate.daily_limit_amount");
+        return cfg == null || cfg.trim().isEmpty() ? 0 : toDouble(cfg, "cf.estimate.daily_limit_amount");
+    }
+
+    // ==================== 展示 VO 构建 ====================
+
+    /** 构建完整预估 VO(预估专用端点使用) */
+    private RewardEstimateVO buildEstimateVO(int expectedCf, RewardDisplayVO display,
+                                              String operationType, String resourceType,
+                                              String resourceId, Integer actualCf, String reason) {
+        RewardEstimateVO vo = new RewardEstimateVO();
+        vo.setExpectedCf(expectedCf);
+        vo.setActualCf(actualCf);
+        vo.setReason(reason);
+        vo.setCurrency(CURRENCY);
+        vo.setOperationType(operationType);
+        vo.setResourceType(resourceType);
+        vo.setResourceId(resourceId);
+        vo.setDisplay(display);
+        return vo;
+    }
+
+    /** 降级 VO:规则未配置 / 超时 / 内部异常 */
+    private RewardEstimateVO degradedVO(String operationType, String resourceType,
+                                         String resourceId, String idempotencyKey, long elapsedMs) {
+        RewardDisplayVO display = new RewardDisplayVO();
+        display.setType(DISPLAY_DEGRADED);
+        display.setTemplate("CF 奖励以实际为准");
+        display.setCfValue(0);
+        RewardEstimateVO vo = new RewardEstimateVO();
+        vo.setExpectedCf(null);
+        vo.setActualCf(null);
+        vo.setReason(null);
+        vo.setCurrency(CURRENCY);
+        vo.setOperationType(operationType);
+        vo.setResourceType(resourceType);
+        vo.setResourceId(resourceId);
+        vo.setIdempotencyKey(idempotencyKey);
+        vo.setDisplay(display);
+        return vo;
+    }
+
+    /** 构建展示 VO(供产出点接口内嵌复用) */
+    public RewardDisplayVO buildDisplay(int expectedCf, String displayType) {
+        return buildDisplay(expectedCf, displayType, null);
+    }
+
+    public RewardDisplayVO buildDisplay(int expectedCf) {
+        String type;
+        String template;
+        if (expectedCf > 0) {
+            type = DISPLAY_EARN;
+            template = "本操作预计获得 " + expectedCf + " CF";
+        } else if (expectedCf < 0) {
+            type = DISPLAY_SPEND;
+            template = "本操作将消耗 " + (-expectedCf) + " CF";
+        } else {
+            type = DISPLAY_ZERO;
+            template = null; // 省略
+        }
+        RewardDisplayVO display = new RewardDisplayVO();
+        display.setType(type);
+        display.setTemplate(template);
+        display.setCfValue(expectedCf);
+        return display;
+    }
+
+    public RewardDisplayVO buildDisplay(int expectedCf, String fallbackType, String fallbackTemplate) {
+        if (expectedCf > 0) {
+            RewardDisplayVO d = new RewardDisplayVO();
+            d.setType(DISPLAY_EARN);
+            d.setTemplate("本操作预计获得 " + expectedCf + " CF");
+            d.setCfValue(expectedCf);
+            return d;
+        } else if (expectedCf < 0) {
+            RewardDisplayVO d = new RewardDisplayVO();
+            d.setType(DISPLAY_SPEND);
+            d.setTemplate("本操作将消耗 " + (-expectedCf) + " CF");
+            d.setCfValue(expectedCf);
+            return d;
+        } else {
+            if (fallbackType != null && fallbackTemplate != null) {
+                RewardDisplayVO d = new RewardDisplayVO();
+                d.setType(fallbackType);
+                d.setTemplate(fallbackTemplate);
+                d.setCfValue(0);
+                return d;
+            }
+            RewardDisplayVO d = new RewardDisplayVO();
+            d.setType(DISPLAY_ZERO);
+            d.setTemplate(null);
+            d.setCfValue(0);
+            return d;
+        }
+    }
+
+    // ==================== 工具方法 ====================
+
+    private String normalizeOpType(String operationType) {
+        if (operationType == null) {
+            return null;
+        }
+        return operationType.trim().toUpperCase();
+    }
+
+    private Long parseResourceId(String resourceId) {
+        if (resourceId == null || resourceId.trim().isEmpty()) {
+            return null;
+        }
+        try {
+            return Long.parseLong(resourceId.trim());
+        } catch (NumberFormatException e) {
+            // 部分 resource 按字符串标识(如 SKU spec),无法解析为 Long 时降级
+            return null;
+        }
+    }
+
+    private double toDouble(Object value, String what) {
+        if (value == null) {
+            throw new IllegalArgumentException(what + " 为空");
+        }
+        if (value instanceof Number) {
+            return ((Number) value).doubleValue();
+        }
+        try {
+            return Double.parseDouble(String.valueOf(value).trim());
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException(what + " 不是数值:" + value);
+        }
+    }
+
+    private Date startOfDay(Date date) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.setTime(date);
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        return calendar.getTime();
+    }
+}

+ 374 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RewardService.java

@@ -0,0 +1,374 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.CreateRewardDTO;
+import com.etotem.cfc.dto.RewardDTO;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.PointsLog;
+import com.etotem.cfc.entity.Reward;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.PointsLogMapper;
+import com.etotem.cfc.mapper.RewardMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.api.RewardServiceInterface;
+import javax.annotation.Resource;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Service
+public class RewardService implements RewardServiceInterface {
+
+@Resource
+private RewardMapper rewardMapper;
+
+@Resource
+private FamilyMemberMapper familyMemberMapper;
+
+@Resource
+private PointsLogMapper pointsLogMapper;
+
+@Resource
+private UserService userService;
+
+@Resource
+private UserMapper userMapper;
+
+/**
+* REWARD-001A: 家庭成员创建心愿单
+* 家庭成员添加想要的奖励到心愿单,状态为 pending_approval(待家庭主账号填写积分)
+*/
+@Transactional
+public Long createWishlist(Long memberId, CreateRewardDTO dto) {
+FamilyMember child = familyMemberMapper.selectById(memberId);
+if (child == null) {
+throw new IllegalArgumentException("成员不存在");
+}
+
+Reward reward = new Reward();
+reward.setFamilyId(child.getFamilyId());
+reward.setMemberId(memberId);
+reward.setTitle(dto.getTitle());
+reward.setCategory(dto.getCategory());
+// 家庭成员创建心愿时积分为0,等待家庭主账号填写
+reward.setPointsRequired(0);
+reward.setStatus("pending_approval"); // 待家庭主账号审批填写积分
+reward.setIsTemplate(0);
+reward.setCreatedAt(new Date());
+reward.setUpdatedAt(new Date());
+rewardMapper.insert(reward);
+
+log.info("家庭成员{}创建心愿: {}", memberId, dto.getTitle());
+return reward.getId();
+}
+
+/**
+* REWARD-001A: 家庭主账号填写积分,心愿进入奖励库
+* 家庭主账号审批并填写所需积分后,心愿转为可兑换状态
+*/
+@Transactional
+public boolean approveWishlist(Long rewardId, Long parentId, Integer pointsRequired) {
+Reward reward = rewardMapper.selectById(rewardId);
+if (reward == null) {
+return false;
+}
+
+// 验证家庭主账号权限:必须是同一家庭的主账号
+User parent = userMapper.selectById(parentId);
+if (parent == null || !parent.getFamilyId().equals(reward.getFamilyId())) {
+log.warn("家庭主账号{}无权操作奖励{}", parentId, rewardId);
+return false;
+}
+
+// 验证状态:只有待审批的心愿可以填写积分
+if (!"pending_approval".equals(reward.getStatus())) {
+log.warn("奖励{}状态不是待审批: {}", rewardId, reward.getStatus());
+return false;
+}
+
+// 更新积分和状态
+reward.setPointsRequired(pointsRequired);
+reward.setStatus("available"); // 进入奖励库,可兑换
+reward.setUpdatedAt(new Date());
+rewardMapper.updateById(reward);
+
+log.info("家庭主账号{}审批心愿{},设置积分: {}", parentId, rewardId, pointsRequired);
+return true;
+}
+
+/**
+ * 创建奖励(原有功能:家庭主账号直接创建奖励)
+ */
+@Transactional
+public Long createReward(Long userId, CreateRewardDTO dto) {
+    // 参数校验
+    if (dto.getTitle() == null || dto.getTitle().trim().isEmpty()) {
+        throw new IllegalArgumentException("请填写心愿名称");
+    }
+    if (dto.getPointsRequired() == null || dto.getPointsRequired() < 1) {
+        throw new IllegalArgumentException("请填写有效的积分值");
+    }
+
+    // 获取用户信息并验证家庭归属
+    User user = userService.getUserInfo(userId);
+    if (user == null || user.getFamilyId() == null) {
+        throw new IllegalArgumentException("用户必须属于某个家庭");
+    }
+
+    Reward reward = new Reward();
+    reward.setFamilyId(user.getFamilyId()); // 强制关联家庭
+    reward.setMemberId(dto.getMemberId());
+    reward.setTitle(dto.getTitle().trim());
+    reward.setPointsRequired(dto.getPointsRequired());
+    reward.setCategory(dto.getCategory());
+    reward.setStatus("available");
+    reward.setIsTemplate(0);
+    reward.setCreatedAt(new Date());
+    reward.setUpdatedAt(new Date());
+    rewardMapper.insert(reward);
+    return reward.getId();
+}
+
+    public List<RewardDTO> getWishlist(Long memberId) {
+        // 获取家庭成员信息以验证家庭归属
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child == null) {
+            return null;
+        }
+        
+        // 按家庭ID和家庭成员ID筛选奖励,确保奖励必须关联家庭
+        List<Reward> rewards = rewardMapper.selectList(new LambdaQueryWrapper<Reward>()
+                .eq(Reward::getFamilyId, child.getFamilyId())
+                .eq(Reward::getMemberId, memberId)
+                .eq(Reward::getStatus, "available")
+                .orderByAsc(Reward::getPointsRequired));
+        
+        final int currentPoints = child != null ? child.getTotalPoints() : 0;
+        
+        return rewards.stream().map(r -> {
+            RewardDTO dto = new RewardDTO();
+            dto.setId(r.getId());
+            dto.setTitle(r.getTitle());
+            dto.setPointsRequired(r.getPointsRequired());
+            dto.setCategory(r.getCategory());
+            dto.setStatus(r.getStatus());
+            dto.setExchangeApproved(r.getExchangeApproved());
+            dto.setProgress(currentPoints);
+            return dto;
+        }).collect(Collectors.toList());
+    }
+
+    @Transactional
+    public Map<String, Object> exchangeReward(Long rewardId, Long memberId) {
+        Reward reward = rewardMapper.selectById(rewardId);
+        if (reward == null || !reward.getMemberId().equals(memberId)) {
+            return null;
+        }
+
+        if (!"available".equals(reward.getStatus())) {
+            return null;
+        }
+
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child.getTotalPoints() < reward.getPointsRequired()) {
+            return null; // 积分不足
+        }
+
+        // 扣除积分
+        child.setTotalPoints(child.getTotalPoints() - reward.getPointsRequired());
+        child.setUpdatedAt(new Date());
+        familyMemberMapper.updateById(child);
+
+        // 记录积分消耗
+        PointsLog log = new PointsLog();
+        log.setMemberId(memberId);
+        log.setAmount(-reward.getPointsRequired());
+        log.setType("spend");
+        log.setDescription("兑换奖励: " + reward.getTitle());
+        log.setCreatedAt(new Date());
+        pointsLogMapper.insert(log);
+
+        // 更新奖励状态
+        reward.setStatus("pending"); // 待审批
+        reward.setUpdatedAt(new Date());
+        rewardMapper.updateById(reward);
+
+        Map<String, Object> result = new java.util.HashMap<>();
+        result.put("success", true);
+        result.put("newBalance", child.getTotalPoints());
+        return result;
+    }
+
+    @Transactional
+    public boolean approveReward(Long rewardId, boolean approved) {
+        Reward reward = rewardMapper.selectById(rewardId);
+        if (reward == null) {
+            return false;
+        }
+
+        if (approved) {
+            reward.setStatus("exchanged");
+            reward.setExchangeApproved(1);
+            reward.setExchangedAt(new Date());
+        } else {
+            // 拒绝,返还积分
+            FamilyMember child = familyMemberMapper.selectById(reward.getMemberId());
+            child.setTotalPoints(child.getTotalPoints() + reward.getPointsRequired());
+            child.setUpdatedAt(new Date());
+            familyMemberMapper.updateById(child);
+
+            // 记录积分退还
+            PointsLog log = new PointsLog();
+            log.setMemberId(reward.getMemberId());
+            log.setAmount(reward.getPointsRequired());
+            log.setType("refund");
+            log.setDescription("奖励兑换被拒绝,积分退还");
+            log.setCreatedAt(new Date());
+            pointsLogMapper.insert(log);
+
+            reward.setStatus("rejected");
+            reward.setExchangeApproved(0);
+        }
+        reward.setUpdatedAt(new Date());
+        rewardMapper.updateById(reward);
+        return true;
+    }
+
+public List<Reward> getTemplates() {
+// 模板也必须关联家庭,这里返回所有家庭的模板(family_id > 0)
+return rewardMapper.selectList(new LambdaQueryWrapper<Reward>()
+.eq(Reward::getIsTemplate, 1)
+.gt(Reward::getFamilyId, 0)); // 确保模板关联到具体家庭
+}
+
+public Page<Reward> getExchangeHistory(Long memberId, Integer page, Integer size) {
+Page<Reward> pageParam = new Page<>(page, size);
+return rewardMapper.selectPage(pageParam, new LambdaQueryWrapper<Reward>()
+.eq(Reward::getMemberId, memberId)
+.in(Reward::getStatus, Arrays.asList("exchanged", "rejected"))
+.orderByDesc(Reward::getExchangedAt));
+}
+
+/**
+* REWARD-002A: 获取家庭奖励库
+* 返回家庭所有可用的奖励(不含模板),多家庭主账号可查看
+*/
+public List<RewardDTO> getFamilyRewardLibrary(Long familyId) {
+List<Reward> rewards = rewardMapper.selectList(new LambdaQueryWrapper<Reward>()
+.eq(Reward::getFamilyId, familyId)
+.eq(Reward::getIsTemplate, 0)
+.in(Reward::getStatus, Arrays.asList("available", "pending_approval"))
+.orderByAsc(Reward::getPointsRequired));
+
+return rewards.stream().map(r -> {
+RewardDTO dto = new RewardDTO();
+dto.setId(r.getId());
+dto.setTitle(r.getTitle());
+dto.setPointsRequired(r.getPointsRequired());
+dto.setCategory(r.getCategory());
+dto.setStatus(r.getStatus());
+dto.setMemberId(r.getMemberId());
+dto.setExchangeApproved(r.getExchangeApproved());
+return dto;
+}).collect(Collectors.toList());
+}
+
+/**
+* REWARD-002A: 家庭主账号修改奖励积分(多家庭主账号可调整)
+* 只有同一家庭的主账号可以修改
+*/
+@Transactional
+public boolean updateRewardPoints(Long rewardId, Long parentId, Integer newPoints) {
+Reward reward = rewardMapper.selectById(rewardId);
+if (reward == null) {
+return false;
+}
+
+// 验证家庭主账号权限
+User parent = userMapper.selectById(parentId);
+if (parent == null || !parent.getFamilyId().equals(reward.getFamilyId())) {
+log.warn("家庭主账号{}无权修改奖励{}", parentId, rewardId);
+return false;
+}
+
+// 只有可用状态或待审批状态可以修改
+if (!"available".equals(reward.getStatus()) && !"pending_approval".equals(reward.getStatus())) {
+log.warn("奖励{}状态不可修改: {}", rewardId, reward.getStatus());
+return false;
+}
+
+reward.setPointsRequired(newPoints);
+reward.setUpdatedAt(new Date());
+rewardMapper.updateById(reward);
+
+log.info("家庭主账号{}修改奖励{}积分为: {}", parentId, rewardId, newPoints);
+return true;
+}
+
+/**
+* REWARD-002B: 获取家庭成员的待审批心愿单(按家庭成员隔离)
+* 只返回指定家庭成员的心愿,不包含其他家庭成员
+*/
+public List<RewardDTO> getChildPendingWishlists(Long memberId) {
+FamilyMember child = familyMemberMapper.selectById(memberId);
+if (child == null) {
+return null;
+}
+
+List<Reward> rewards = rewardMapper.selectList(new LambdaQueryWrapper<Reward>()
+.eq(Reward::getFamilyId, child.getFamilyId())
+.eq(Reward::getMemberId, memberId)
+.eq(Reward::getStatus, "pending_approval")
+.orderByDesc(Reward::getCreatedAt));
+
+return rewards.stream().map(r -> {
+RewardDTO dto = new RewardDTO();
+dto.setId(r.getId());
+dto.setTitle(r.getTitle());
+dto.setPointsRequired(r.getPointsRequired());
+dto.setCategory(r.getCategory());
+dto.setStatus(r.getStatus());
+dto.setMemberId(r.getMemberId());
+return dto;
+}).collect(Collectors.toList());
+}
+
+/**
+* REWARD-002B: 获取家庭主账号待处理的心愿审批列表(所有家庭成员)
+* 家庭主账号可以看到所有家庭成员的待审批心愿
+*/
+public List<RewardDTO> getPendingApprovalList(Long familyId) {
+List<Reward> rewards = rewardMapper.selectList(new LambdaQueryWrapper<Reward>()
+.eq(Reward::getFamilyId, familyId)
+.eq(Reward::getStatus, "pending_approval")
+.eq(Reward::getIsTemplate, 0)
+.orderByDesc(Reward::getCreatedAt));
+
+return rewards.stream().map(r -> {
+RewardDTO dto = new RewardDTO();
+dto.setId(r.getId());
+dto.setTitle(r.getTitle());
+dto.setPointsRequired(r.getPointsRequired());
+dto.setCategory(r.getCategory());
+dto.setStatus(r.getStatus());
+dto.setMemberId(r.getMemberId());
+
+// 获取家庭成员昵称
+FamilyMember child = familyMemberMapper.selectById(r.getMemberId());
+if (child != null) {
+dto.setChildName(child.getNickname());
+}
+
+return dto;
+}).collect(Collectors.toList());
+}
+}

+ 125 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/RewardWishlistService.java

@@ -0,0 +1,125 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.RewardWishlistServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.CreateRewardWishlistDTO;
+import com.etotem.cfc.entity.RewardWishlist;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.RewardWishlistMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class RewardWishlistService {
+
+    @Resource
+    private RewardWishlistMapper rewardWishlistMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 创建家庭主账号心愿
+     */
+    public Long create(Long userId, CreateRewardWishlistDTO dto) {
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            throw new RuntimeException("用户不存在");
+        }
+
+        RewardWishlist wishlist = new RewardWishlist();
+        wishlist.setFamilyId(user.getFamilyId());
+        wishlist.setUserId(userId);
+        // title 添加默认值处理
+        String title = dto.getTitle();
+        if (title == null || title.trim().isEmpty()) {
+            title = "心愿奖励";
+        }
+        wishlist.setTitle(title);
+        wishlist.setDescription(dto.getDescription());
+        wishlist.setPointsRequired(dto.getPointsRequired() != null ? dto.getPointsRequired() : 0);
+        wishlist.setCategory(dto.getCategory() != null ? dto.getCategory() : "other");
+        wishlist.setStatus("pending");
+        wishlist.setExchangeApproved(0);
+        wishlist.setCreatedAt(new Date());
+        wishlist.setUpdatedAt(new Date());
+
+        rewardWishlistMapper.insert(wishlist);
+        return wishlist.getId();
+    }
+
+    /**
+     * 获取家庭主账号的心愿单列表
+     */
+    public List<RewardWishlist> getByUserId(Long userId) {
+        return rewardWishlistMapper.selectList(new LambdaQueryWrapper<RewardWishlist>()
+                .eq(RewardWishlist::getUserId, userId)
+                .orderByDesc(RewardWishlist::getCreatedAt));
+    }
+
+    /**
+     * 获取家庭的心愿单列表
+     */
+    public List<RewardWishlist> getByFamilyId(Long familyId) {
+        return rewardWishlistMapper.selectList(new LambdaQueryWrapper<RewardWishlist>()
+                .eq(RewardWishlist::getFamilyId, familyId)
+                .orderByDesc(RewardWishlist::getCreatedAt));
+    }
+
+    /**
+     * 兑换心愿 (扣积分)
+     */
+    public boolean exchange(Long wishlistId, Long userId) {
+        RewardWishlist wishlist = rewardWishlistMapper.selectById(wishlistId);
+        if (wishlist == null || !wishlist.getUserId().equals(userId)) {
+            return false;
+        }
+
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getTotalPoints() == null || user.getTotalPoints() < wishlist.getPointsRequired()) {
+            return false;
+        }
+
+        // 扣减积分
+        user.setTotalPoints(user.getTotalPoints() - wishlist.getPointsRequired());
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        // 更新心愿状态
+        wishlist.setStatus("exchanged");
+        wishlist.setExchangeApproved(1);
+        wishlist.setExchangedAt(new Date());
+        wishlist.setUpdatedAt(new Date());
+        rewardWishlistMapper.updateById(wishlist);
+
+        return true;
+    }
+
+    /**
+     * 审核心愿 (本人自己审核自己的心愿,可能需要管理员审批)
+     */
+    public boolean approve(Long wishlistId, boolean approved) {
+        RewardWishlist wishlist = rewardWishlistMapper.selectById(wishlistId);
+        if (wishlist == null) {
+            return false;
+        }
+
+        if (approved) {
+            wishlist.setStatus("exchanged");
+            wishlist.setExchangeApproved(1);
+            wishlist.setExchangedAt(new Date());
+        } else {
+            wishlist.setStatus("rejected");
+            wishlist.setExchangeApproved(0);
+        }
+        wishlist.setUpdatedAt(new Date());
+        rewardWishlistMapper.updateById(wishlist);
+
+        return true;
+    }
+}

+ 49 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SeasonalFoodService.java

@@ -0,0 +1,49 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.SeasonalFood;
+import com.etotem.cfc.mapper.SeasonalFoodMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Service
+public class SeasonalFoodService {
+
+    @Resource
+    private SeasonalFoodMapper seasonalFoodMapper;
+
+    public List<Long> getCurrentMonthFoodIds() {
+        int month = LocalDate.now().getMonthValue();
+        return getFoodIdsByMonth(month);
+    }
+
+    public List<Long> getFoodIdsByMonth(int month) {
+        return seasonalFoodMapper.selectList(
+                new LambdaQueryWrapper<SeasonalFood>()
+                        .eq(SeasonalFood::getMonth, month)
+                        .orderByDesc(SeasonalFood::getPeakFlag)
+        ).stream().map(SeasonalFood::getFoodId).distinct().collect(Collectors.toList());
+    }
+
+    public List<SeasonalFood> listByMonth(int month) {
+        return seasonalFoodMapper.selectList(
+                new LambdaQueryWrapper<SeasonalFood>()
+                        .eq(SeasonalFood::getMonth, month)
+                        .orderByDesc(SeasonalFood::getPeakFlag)
+        );
+    }
+
+    public void create(SeasonalFood sf) {
+        seasonalFoodMapper.insert(sf);
+    }
+
+    public void delete(Long id) {
+        seasonalFoodMapper.deleteById(id);
+    }
+}

+ 248 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SelfCheckAnalysisService.java

@@ -0,0 +1,248 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.FiveDimensionSelfCheck;
+import com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+@Service
+public class SelfCheckAnalysisService {
+
+    private static final Logger log = LoggerFactory.getLogger(SelfCheckAnalysisService.class);
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Resource
+    private FiveDimensionSelfCheckMapper selfCheckMapper;
+
+    @Resource
+    private WuxingSourcingService wuxingSourcingService;
+
+    @Resource
+    private SelfCheckTrendService selfCheckTrendService;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /** 低分阈值(≤6 视为低分项) */
+    private static final int LOW_SCORE_THRESHOLD = 6;
+
+    /** 维度展示顺序:身·智·富·行·心 */
+    private static final List<String> DIMENSION_ORDER =
+            Collections.unmodifiableList(Arrays.asList("body", "wisdom", "wealth", "action", "mind"));
+
+    /**
+     * 组装最近一次自检摘要(P1-2 Chat 上下文注入)
+     *
+     * <p>输出结构对齐 LangGraph chat_graph 的 self_check_result 解析约定:
+     * {@code totalScore} + {@code dimensions:[{name,score}]} + {@code aiInsight}(低分项摘要)。
+     * 这样 /chat/send 无需前端额外传参即可基于自检结果连续对话。</p>
+     *
+     * @param userId  当前登录用户(用于归属校验)
+     * @param checkId 指定自检记录 ID,可为空(为空时取该用户最近一次)
+     * @return 摘要 Map;无记录 / 记录不属于当前用户 / 异常时返回 null(调用方静默跳过)
+     */
+    public Map<String, Object> buildLatestSummary(Long userId, Long checkId) {
+        try {
+            FiveDimensionSelfCheck record;
+            if (checkId != null) {
+                record = selfCheckMapper.selectById(checkId);
+                if (record == null) {
+                    log.info("自检上下文注入跳过:checkId={} 不存在", checkId);
+                    return null;
+                }
+                if (userId == null || !userId.equals(record.getUserId())) {
+                    log.info("自检上下文注入跳过:checkId={} 不属于当前用户", checkId);
+                    return null;
+                }
+            } else {
+                if (userId == null) {
+                    return null;
+                }
+                record = selfCheckMapper.selectOne(
+                        new LambdaQueryWrapper<FiveDimensionSelfCheck>()
+                                .eq(FiveDimensionSelfCheck::getUserId, userId)
+                                .orderByDesc(FiveDimensionSelfCheck::getCreatedAt)
+                                .last("LIMIT 1")
+                );
+            }
+            if (record == null) {
+                return null;
+            }
+
+            Map<String, Integer> scores = record.getScoresJson() != null
+                    ? objectMapper.readValue(record.getScoresJson(), new TypeReference<Map<String, Integer>>() {})
+                    : new LinkedHashMap<>();
+
+            List<Map<String, Object>> dimensions = new ArrayList<>();
+            List<Map<String, Object>> lowItems = new ArrayList<>();
+            Map<String, Object> lowest = null;
+            for (String code : DIMENSION_ORDER) {
+                Integer score = scores.get(code);
+                if (score == null) {
+                    continue;
+                }
+                Map<String, Object> d = new LinkedHashMap<>();
+                d.put("dimension", code);
+                d.put("name", wuxingSourcingService.dimensionName(code));
+                d.put("score", score);
+                String level = wuxingSourcingService.levelOf(score);
+                d.put("level", level);
+                d.put("levelName", wuxingSourcingService.levelName(level));
+                dimensions.add(d);
+                if (score <= LOW_SCORE_THRESHOLD) {
+                    lowItems.add(d);
+                }
+                if (lowest == null || score < toInt(lowest.get("score"))) {
+                    lowest = d;
+                }
+            }
+
+            Map<String, Object> summary = new LinkedHashMap<>();
+            summary.put("id", record.getId());
+            summary.put("totalScore", record.getTotalScore());
+            summary.put("createdAt", record.getCreatedAt() != null ? record.getCreatedAt().toString() : "");
+            summary.put("dimensions", dimensions);
+            summary.put("lowItems", lowItems);
+            summary.put("lowestDimension", lowest);
+            if (lowest != null) {
+                StringBuilder insight = new StringBuilder("最近一次自检低分维度(≤")
+                        .append(LOW_SCORE_THRESHOLD).append("分):");
+                if (lowItems.isEmpty()) {
+                    insight.append("无(各维度均健康)");
+                } else {
+                    List<String> parts = new ArrayList<>();
+                    for (Map<String, Object> low : lowItems) {
+                        parts.add(low.get("name") + " " + low.get("score") + "分");
+                    }
+                    insight.append(String.join("、", parts));
+                }
+                insight.append(";最低分维度:").append(lowest.get("name"))
+                        .append("(").append(toInt(lowest.get("score"))).append("分)");
+                summary.put("aiInsight", insight.toString());
+            }
+            return summary;
+        } catch (Exception e) {
+            log.warn("组装自检摘要失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private int toInt(Object v) {
+        if (v == null) return 0;
+        if (v instanceof Number) return ((Number) v).intValue();
+        try {
+            return Integer.parseInt(v.toString());
+        } catch (Exception e) {
+            return 0;
+        }
+    }
+
+    /**
+     * 生成自检建议(AI 优先,失败返回 adviceJson=null + fallbackUsed=true)
+     */
+    public Map<String, Object> generateAdvice(Long userId, Map<String, Integer> scoreMap, List<Integer> questionIds) {
+        try {
+            List<Map<String, Object>> recentHistory = getRecentHistory(userId, 3);
+            Map<String, Object> scoresWithMeta = new LinkedHashMap<>();
+            for (Map.Entry<String, Integer> entry : scoreMap.entrySet()) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("dimension", entry.getKey());
+                m.put("dimensionName", getDimensionName(entry.getKey()));
+                m.put("score", entry.getValue());
+                scoresWithMeta.put(entry.getKey(), m);
+            }
+            Map<String, Object> inputs = new LinkedHashMap<>();
+            inputs.put("scores", scoresWithMeta);
+            inputs.put("questionIds", questionIds);
+            inputs.put("userId", userId);
+            inputs.put("recentHistory", recentHistory);
+            Map<String, Object> result = aiGateway.generateSelfCheckAdvice(inputs);
+            if (result == null) {
+                log.info("AI 自检建议生成失败,fallback");
+                Map<String, Object> fallback = new LinkedHashMap<>();
+                fallback.put("adviceJson", null);
+                fallback.put("fallbackUsed", true);
+                return fallback;
+            }
+            String adviceJson = (String) result.get("advice_json");
+            Boolean fallbackUsed = (Boolean) result.getOrDefault("fallback_used", false);
+            Map<String, Object> advResult = new LinkedHashMap<>();
+            advResult.put("adviceJson", adviceJson);
+            advResult.put("fallbackUsed", fallbackUsed);
+            return advResult;
+        } catch (Exception e) {
+            log.warn("自检建议生成异常: {}", e.getMessage());
+            Map<String, Object> fallback = new LinkedHashMap<>();
+            fallback.put("adviceJson", null);
+            fallback.put("fallbackUsed", true);
+            return fallback;
+        }
+    }
+
+    /**
+     * 生成趋势分析(兼容入口,趋势逻辑已收敛到 {@link SelfCheckTrendService})
+     *
+     * @return 含 history / recordCount / trendAvailable / trendDetails / trendSummary / aiInsight
+     */
+    public Map<String, Object> generateTrend(Long userId) {
+        return selfCheckTrendService.getTrendData(userId);
+    }
+
+    /** 获取最近 N 次自检历史(供 AI 和前端使用) */
+    public List<Map<String, Object>> getRecentHistory(Long userId, int limit) {
+        try {
+            List<FiveDimensionSelfCheck> records = selfCheckMapper.selectList(
+                    new LambdaQueryWrapper<FiveDimensionSelfCheck>()
+                            .eq(FiveDimensionSelfCheck::getUserId, userId)
+                            .orderByDesc(FiveDimensionSelfCheck::getCreatedAt)
+                            .last("LIMIT " + limit)
+            );
+            List<Map<String, Object>> result = new ArrayList<>();
+            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            for (FiveDimensionSelfCheck r : records) {
+                Map<String, Object> m = new LinkedHashMap<>();
+                m.put("createdAt", r.getCreatedAt() != null ? sdf.format(r.getCreatedAt()) : "");
+                m.put("totalScore", r.getTotalScore());
+                if (r.getScoresJson() != null) {
+                    try {
+                        Map<String, Integer> scores = objectMapper.readValue(r.getScoresJson(),
+                                new TypeReference<Map<String, Integer>>() {});
+                        List<Map<String, Object>> dims = new ArrayList<>();
+                        for (Map.Entry<String, Integer> e : scores.entrySet()) {
+                            Map<String, Object> d = new LinkedHashMap<>();
+                            d.put("dimension", e.getKey());
+                            d.put("name", getDimensionName(e.getKey()));
+                            d.put("score", e.getValue());
+                            dims.add(d);
+                        }
+                        m.put("dimensions", dims);
+                    } catch (Exception ignored) {}
+                }
+                result.add(m);
+            }
+            return result;
+        } catch (Exception e) {
+            log.warn("获取自检历史失败: {}", e.getMessage());
+            return Collections.emptyList();
+        }
+    }
+
+    private String getDimensionName(String dim) {
+        switch (dim) {
+            case "body": return "身";
+            case "wisdom": return "智";
+            case "wealth": return "富";
+            case "action": return "行";
+            case "mind": return "心";
+            default: return dim;
+        }
+    }
+}

+ 387 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SelfCheckTrendService.java

@@ -0,0 +1,387 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.FiveDimensionSelfCheck;
+import com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * 五维自检历史趋势聚合 + AI 趋势解读(P1-1)
+ *
+ * 职责:
+ * <ol>
+ *   <li>聚合该成员历次自检得分(five_dimension_self_checks 表,按维度);</li>
+ *   <li>Java 侧确定性计算各维度 delta / 方向(上升 / 下降 / 波动 / 持平),
+ *       保证 AI 不可用时前端仍能展示趋势;</li>
+ *   <li>组装 prompt 上下文 → AiGateway → LangGraph chat_graph 生成趋势解读;</li>
+ *   <li>AI 不可用时分三级降级(chat_graph → 专用 trend graph → 确定性文案)。</li>
+ * </ol>
+ * 遵循 AiGateway 熔断 / 超时 / Fallback 规范,零 LangGraph 改动。
+ */
+@Service
+public class SelfCheckTrendService {
+
+    private static final Logger log = LoggerFactory.getLogger(SelfCheckTrendService.class);
+
+    /** 参与趋势聚合的最大自检次数 */
+    static final int HISTORY_LIMIT = 3;
+    /** 至少 N 次记录才出趋势解读 */
+    static final int TREND_MIN_RECORDS = 2;
+    /** 低分阈值(≤6 视为低分项) */
+    static final int LOW_SCORE_THRESHOLD = 6;
+    /** AI 解读最大长度(超出在句末截断) */
+    static final int MAX_INSIGHT_LENGTH = 600;
+
+    /** 维度展示顺序:身·智·富·行·心 */
+    private static final List<String> DIMENSION_ORDER =
+            Collections.unmodifiableList(Arrays.asList("body", "wisdom", "wealth", "action", "mind"));
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+    private final SimpleDateFormat dateTimeFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+    private final SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd");
+
+    @Resource
+    private AiGateway aiGateway;
+
+    @Resource
+    private FiveDimensionSelfCheckMapper selfCheckMapper;
+
+    @Resource
+    private WuxingSourcingService wuxingSourcingService;
+
+    @Resource
+    private TaskParseService taskParseService;
+
+    /**
+     * 获取自检趋势数据(含历史、各维度 delta、AI 解读),供 /api/family/self-check/trend-analysis 使用。
+     */
+    public Map<String, Object> getTrendData(Long userId) {
+        List<Map<String, Object>> history = getHistoryAscending(userId, HISTORY_LIMIT);
+        List<Map<String, Object>> trendDetails = computeTrendDetails(history);
+        boolean available = history.size() >= TREND_MIN_RECORDS;
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("history", history);
+        result.put("recordCount", history.size());
+        result.put("trendAvailable", available);
+        result.put("trendDetails", trendDetails);
+        result.put("trendSummary", buildDeltaSummary(trendDetails));
+        result.put("aiInsight", available ? generateAiInsight(userId, history, trendDetails) : "");
+        return result;
+    }
+
+    // ===== 历史聚合 =====
+
+    /** 最近 N 次自检(升序:最早在前),每条含维度明细(name/element/color/score/level) */
+    List<Map<String, Object>> getHistoryAscending(Long userId, int limit) {
+        if (userId == null) {
+            return Collections.emptyList();
+        }
+        try {
+            List<FiveDimensionSelfCheck> records = selfCheckMapper.selectList(
+                    new LambdaQueryWrapper<FiveDimensionSelfCheck>()
+                            .eq(FiveDimensionSelfCheck::getUserId, userId)
+                            .orderByDesc(FiveDimensionSelfCheck::getCreatedAt)
+                            .last("LIMIT " + limit)
+            );
+            List<Map<String, Object>> history = new ArrayList<>();
+            if (records != null) {
+                for (FiveDimensionSelfCheck r : records) {
+                    Map<String, Object> item = new LinkedHashMap<>();
+                    item.put("id", r.getId());
+                    item.put("createdAt", r.getCreatedAt() != null ? dateTimeFmt.format(r.getCreatedAt()) : "");
+                    item.put("date", r.getCreatedAt() != null ? dateFmt.format(r.getCreatedAt()) : "");
+                    item.put("totalScore", r.getTotalScore());
+                    item.put("dimensions", parseDimensions(r.getScoresJson()));
+                    history.add(item);
+                }
+            }
+            // 升序(最早在前),便于前端画折线
+            Collections.reverse(history);
+            return history;
+        } catch (Exception e) {
+            log.warn("聚合自检历史失败: {}", e.getMessage());
+            return Collections.emptyList();
+        }
+    }
+
+    private List<Map<String, Object>> parseDimensions(String scoresJson) {
+        List<Map<String, Object>> dims = new ArrayList<>();
+        if (scoresJson == null || scoresJson.isEmpty()) {
+            return dims;
+        }
+        try {
+            Map<String, Integer> scores = objectMapper.readValue(scoresJson,
+                    new TypeReference<Map<String, Integer>>() {});
+            for (Map.Entry<String, Integer> entry : scores.entrySet()) {
+                String code = entry.getKey();
+                int score = entry.getValue() == null ? 0 : entry.getValue();
+                Map<String, Object> d = new LinkedHashMap<>();
+                d.put("dimension", code);
+                d.put("name", wuxingSourcingService.dimensionName(code));
+                d.put("element", wuxingSourcingService.elementOf(code));
+                d.put("color", wuxingSourcingService.colorOf(code));
+                d.put("score", score);
+                String level = wuxingSourcingService.levelOf(score);
+                d.put("level", level);
+                d.put("levelName", wuxingSourcingService.levelName(level));
+                dims.add(d);
+            }
+        } catch (Exception e) {
+            log.warn("解析自检得分 JSON 失败: {}", e.getMessage());
+        }
+        return dims;
+    }
+
+    // ===== 确定性趋势计算 =====
+
+    /** 各维度变化(相对首次):firstScore / latestScore / delta / direction */
+    List<Map<String, Object>> computeTrendDetails(List<Map<String, Object>> history) {
+        List<Map<String, Object>> details = new ArrayList<>();
+        if (history.size() < TREND_MIN_RECORDS) {
+            return details;
+        }
+        for (String code : DIMENSION_ORDER) {
+            List<Integer> values = new ArrayList<>();
+            for (Map<String, Object> h : history) {
+                for (Object dimObj : (List<?>) h.getOrDefault("dimensions", Collections.emptyList())) {
+                    Map<String, Object> dim = (Map<String, Object>) dimObj;
+                    if (code.equals(dim.get("dimension"))) {
+                        values.add(toInt(dim.get("score")));
+                    }
+                }
+            }
+            if (values.size() < TREND_MIN_RECORDS) {
+                continue;
+            }
+            int first = values.get(0);
+            int latest = values.get(values.size() - 1);
+            int delta = latest - first;
+            Map<String, Object> detail = new LinkedHashMap<>();
+            detail.put("dimension", code);
+            detail.put("name", wuxingSourcingService.dimensionName(code));
+            detail.put("color", wuxingSourcingService.colorOf(code));
+            detail.put("firstScore", first);
+            detail.put("latestScore", latest);
+            detail.put("delta", delta);
+            detail.put("direction", directionOf(values));
+            details.add(detail);
+        }
+        return details;
+    }
+
+    /** 方向判定:出现先升后降或先降后升视为"波动",否则按首尾差判上升/下降/持平 */
+    private String directionOf(List<Integer> values) {
+        boolean up = false;
+        boolean down = false;
+        for (int i = 1; i < values.size(); i++) {
+            if (values.get(i) > values.get(i - 1)) up = true;
+            if (values.get(i) < values.get(i - 1)) down = true;
+        }
+        if (up && down) return "波动";
+        if (up) return "上升";
+        if (down) return "下降";
+        return "持平";
+    }
+
+    /** 形如"身-2 智+1 富0 行-1 心+2"的 delta 简写 */
+    String buildDeltaSummary(List<Map<String, Object>> details) {
+        if (details.isEmpty()) {
+            return "";
+        }
+        StringBuilder sb = new StringBuilder();
+        for (Map<String, Object> d : details) {
+            if (sb.length() > 0) {
+                sb.append(" ");
+            }
+            int delta = toInt(d.get("delta"));
+            sb.append(d.get("name")).append(delta > 0 ? "+" + delta : String.valueOf(delta));
+        }
+        return sb.toString();
+    }
+
+    // ===== AI 趋势解读(Java 侧组装 prompt 上下文) =====
+
+    /**
+     * 生成 AI 趋势解读,三级降级:
+     * 1. AiGateway.chatForAnalysis → LangGraph chat_graph(Java 组装 prompt + 上下文)
+     * 2. AiGateway.generateSelfCheckTrend → 专用 trend graph
+     * 3. 确定性文案(基于 delta 计算,AI 全程不可用时兜底)
+     */
+    private String generateAiInsight(Long userId, List<Map<String, Object>> history,
+                                     List<Map<String, Object>> details) {
+        try {
+            String prompt = buildTrendPrompt(history, details);
+            Map<String, Object> inputs = new LinkedHashMap<>();
+            inputs.put("userId", userId);
+            Map<String, Object> snapshot = latestSnapshot(history);
+            if (snapshot != null) {
+                inputs.put("self_check_result", objectMapper.writeValueAsString(snapshot));
+            }
+            Map<String, Object> resp = aiGateway.chatForAnalysis(prompt, userId, "self-check-trend-" + userId, inputs);
+            String insight = resp != null ? cleanInsight((String) resp.get("answer")) : "";
+            if (!insight.isEmpty()) {
+                return insight;
+            }
+
+            // 二级兜底:LangGraph 专用趋势 graph
+            Map<String, Object> trendInputs = new LinkedHashMap<>();
+            trendInputs.put("history", history);
+            trendInputs.put("userId", userId);
+            Map<String, Object> trend = aiGateway.generateSelfCheckTrend(trendInputs);
+            if (trend != null) {
+                String fallback = cleanInsight((String) trend.get("aiInsight"));
+                if (!fallback.isEmpty()) {
+                    return fallback;
+                }
+            }
+        } catch (Exception e) {
+            log.warn("自检趋势 AI 解读失败: {}", e.getMessage());
+        }
+        return buildFallbackInsight(history, details);
+    }
+
+    private String buildTrendPrompt(List<Map<String, Object>> history, List<Map<String, Object>> details) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("用户最近").append(history.size()).append("次五维自检记录(身·智·富·行·心,每维0-9分,总分45分):\n");
+        int idx = 1;
+        for (Map<String, Object> h : history) {
+            sb.append(idx).append(". ").append(h.get("date")).append(" 总分")
+              .append(h.get("totalScore")).append("/45");
+            for (Object dimObj : (List<?>) h.getOrDefault("dimensions", Collections.emptyList())) {
+                Map<String, Object> dim = (Map<String, Object>) dimObj;
+                sb.append(",").append(dim.get("name")).append(dim.get("score")).append("分");
+            }
+            sb.append("\n");
+            idx++;
+        }
+        sb.append("各维度变化(相对首次):").append(buildDeltaSummary(details)).append("\n");
+        sb.append("请用2-3句话解读这段趋势:指出上升/下降/波动最明显的维度和可能的原因(不要编造未提供的信息),并给出1-2条可执行建议。");
+        sb.append("要求口语化、温暖、简洁;不要输出[TASK]标记;不要使用markdown标题或列表符号。");
+        return sb.toString();
+    }
+
+    /** 最近一次快照(chat_graph 的 self_check_result 上下文:总分 + 维度分 + 低分项) */
+    private Map<String, Object> latestSnapshot(List<Map<String, Object>> history) {
+        if (history.isEmpty()) {
+            return null;
+        }
+        Map<String, Object> last = history.get(history.size() - 1);
+        List<Map<String, Object>> dims = (List<Map<String, Object>>) last.getOrDefault("dimensions", Collections.emptyList());
+        Map<String, Object> snapshot = new LinkedHashMap<>();
+        snapshot.put("totalScore", last.get("totalScore"));
+        snapshot.put("createdAt", last.get("createdAt"));
+        snapshot.put("dimensions", dims);
+
+        List<String> lowLines = new ArrayList<>();
+        Map<String, Object> lowest = null;
+        for (Map<String, Object> d : dims) {
+            int score = toInt(d.get("score"));
+            if (score <= LOW_SCORE_THRESHOLD) {
+                lowLines.add(d.get("name") + " " + score + "分");
+            }
+            if (lowest == null || score < toInt(lowest.get("score"))) {
+                lowest = d;
+            }
+        }
+        if (lowest != null) {
+            String lowText = lowLines.isEmpty()
+                    ? lowest.get("name") + " " + toInt(lowest.get("score")) + "分"
+                    : String.join("、", lowLines);
+            snapshot.put("aiInsight", "最近一次自检低分维度(≤" + LOW_SCORE_THRESHOLD + "分):" + lowText);
+        }
+        return snapshot;
+    }
+
+    /** 清洗 AI 输出:去 [TASK] 标记 / 代码块 / markdown 符号,超长句末截断 */
+    String cleanInsight(String raw) {
+        if (raw == null || raw.trim().isEmpty()) {
+            return "";
+        }
+        String text = raw;
+        try {
+            text = taskParseService.stripTaskMarkers(raw);
+        } catch (Exception e) {
+            log.debug("清洗趋势解读时 stripTaskMarkers 失败,保留原文: {}", e.getMessage());
+        }
+        text = text.replace("```json", "").replace("```", "")
+                   .replaceAll("(?m)^#{1,6}\\s*", "")
+                   .replace("*", "")
+                   .trim();
+        if (text.length() > MAX_INSIGHT_LENGTH) {
+            int cut = text.substring(0, MAX_INSIGHT_LENGTH).lastIndexOf("。");
+            text = cut > 0 ? text.substring(0, cut + 1) : text.substring(0, MAX_INSIGHT_LENGTH);
+        }
+        return text;
+    }
+
+    /** 确定性降级文案:总分变化 + 变化最大维度 + 当前最低分维度建议 */
+    private String buildFallbackInsight(List<Map<String, Object>> history, List<Map<String, Object>> details) {
+        if (history.size() < TREND_MIN_RECORDS) {
+            return "";
+        }
+        Map<String, Object> first = history.get(0);
+        Map<String, Object> last = history.get(history.size() - 1);
+        int firstTotal = toInt(first.get("totalScore"));
+        int lastTotal = toInt(last.get("totalScore"));
+        int totalDelta = lastTotal - firstTotal;
+
+        StringBuilder sb = new StringBuilder();
+        sb.append("近").append(history.size()).append("次自检,总分从").append(firstTotal)
+          .append("变为").append(lastTotal);
+        if (totalDelta > 0) {
+            sb.append("(+").append(totalDelta).append(")");
+        } else if (totalDelta < 0) {
+            sb.append("(").append(totalDelta).append(")");
+        }
+        sb.append("。");
+
+        Map<String, Object> maxDim = null;
+        for (Map<String, Object> d : details) {
+            if (maxDim == null || Math.abs(toInt(d.get("delta"))) > Math.abs(toInt(maxDim.get("delta")))) {
+                maxDim = d;
+            }
+        }
+        if (maxDim != null) {
+            sb.append(maxDim.get("name")).append("维度").append(maxDim.get("direction"))
+              .append("最明显(").append(toInt(maxDim.get("delta"))).append("分)。");
+        }
+
+        Map<String, Object> lowest = lowestDimension(last);
+        if (lowest != null) {
+            sb.append("当前最低分维度是").append(lowest.get("name")).append("(")
+              .append(toInt(lowest.get("score"))).append("分),建议下次自检前先从一个小行动开始。");
+        }
+        return sb.toString();
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> lowestDimension(Map<String, Object> item) {
+        List<Map<String, Object>> dims = (List<Map<String, Object>>) item.getOrDefault("dimensions", Collections.emptyList());
+        Map<String, Object> lowest = null;
+        for (Map<String, Object> d : dims) {
+            if (lowest == null || toInt(d.get("score")) < toInt(lowest.get("score"))) {
+                lowest = d;
+            }
+        }
+        return lowest;
+    }
+
+    private int toInt(Object v) {
+        if (v == null) return 0;
+        if (v instanceof Number) return ((Number) v).intValue();
+        try {
+            return Integer.parseInt(v.toString());
+        } catch (Exception e) {
+            return 0;
+        }
+    }
+}

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

@@ -0,0 +1,43 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.ServiceContentServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.ServiceContent;
+import com.etotem.cfc.mapper.ServiceContentMapper;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+public class ServiceContentService extends ServiceImpl<ServiceContentMapper, ServiceContent> {
+
+    public List<ServiceContent> getActiveContents() {
+        LambdaQueryWrapper<ServiceContent> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(ServiceContent::getStatus, "ACTIVE")
+               .orderByAsc(ServiceContent::getId);
+        return this.list(wrapper);
+    }
+
+    public List<ServiceContent> getContentsByType(Long typeId) {
+        LambdaQueryWrapper<ServiceContent> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(ServiceContent::getTypeId, typeId)
+               .eq(ServiceContent::getStatus, "ACTIVE")
+               .orderByAsc(ServiceContent::getId);
+        return this.list(wrapper);
+    }
+
+    public ServiceContent createContent(ServiceContent content) {
+        this.save(content);
+        return content;
+    }
+
+    public boolean updateContent(ServiceContent content) {
+        return this.updateById(content);
+    }
+
+    public boolean deleteContent(Long id) {
+        return this.removeById(id);
+    }
+}

+ 92 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ServiceCostConfigService.java

@@ -0,0 +1,92 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.ServiceCostConfig;
+import com.etotem.cfc.mapper.ServiceCostConfigMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+/**
+ * 服务成本价配置服务(能力键 {@code team.admin.manage},单元 admin,§12-T5 成本价配置)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * §7.5 + §12-T5。</p>
+ *
+ * <p><b>宿主契约方法</b>:
+ * <ul>
+ *   <li>{@code int getCostCent(String serviceType)} — 读服务成本价 C(分),未配置返回 0(§2.1 默认平台自担)</li>
+ *   <li>{@code int saveCostCent(String serviceType, String serviceName, int costCent)}
+ *       — 管理端维护成本价(upsert service_cost_config,返回生效成本价)</li>
+ * </ul>
+ *
+ * <p>成本价 C 是 §2.1 利润漏斗的输入(P = S − C),由平台运营真实填写(§10#3 合规红线),
+ * 供分润计算读取。纯反射契约上下文(无 Spring)下 Mapper 未注入时读取返回 0。</p>
+ *
+ * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
+ * §7.5 + §12-T5 + §10#3。</b></p>
+ */
+@Service
+public class ServiceCostConfigService {
+
+    @Resource
+    private ServiceCostConfigMapper serviceCostConfigMapper;
+
+    /** 未配置的成本价 C → 0(平台自担成本,分润按 S−C 计算,C=0 时 P=S)。 */
+    public int getCostCent(String serviceType) {
+        if (serviceType == null || serviceType.trim().isEmpty()) {
+            return 0;
+        }
+        if (serviceCostConfigMapper == null) {
+            return 0;
+        }
+        try {
+            ServiceCostConfig cfg = serviceCostConfigMapper.selectOne(
+                    new LambdaQueryWrapper<ServiceCostConfig>()
+                            .eq(ServiceCostConfig::getServiceType, serviceType.trim())
+                            .last("LIMIT 1"));
+            if (cfg != null && cfg.getCostCent() != null) {
+                return cfg.getCostCent().intValue();
+            }
+        } catch (Exception e) {
+            // 读取失败视为未配置(不抛异常使管理端崩溃),返回 0
+        }
+        return 0;
+    }
+
+    /**
+     * 保存服务成本价(管理端维护,upsert):已存在的 serviceType 更新成本价/服务名,
+     * 不存在则新增(enabled=1)。返回生效的成本价(分)。
+     *
+     * @throws IllegalArgumentException serviceType 为空或 costCent 为负数
+     */
+    public int saveCostCent(String serviceType, String serviceName, int costCent) {
+        if (serviceType == null || serviceType.trim().isEmpty()) {
+            throw new IllegalArgumentException("serviceType 不能为空");
+        }
+        if (costCent < 0) {
+            throw new IllegalArgumentException("成本价不能为负数");
+        }
+        String type = serviceType.trim();
+        ServiceCostConfig cfg = serviceCostConfigMapper.selectOne(
+                new LambdaQueryWrapper<ServiceCostConfig>()
+                        .eq(ServiceCostConfig::getServiceType, type)
+                        .last("LIMIT 1"));
+        if (cfg == null) {
+            cfg = new ServiceCostConfig();
+            cfg.setServiceType(type);
+            cfg.setServiceName(serviceName);
+            cfg.setCostCent((long) costCent);
+            cfg.setEnabled(1);
+            serviceCostConfigMapper.insert(cfg);
+        } else {
+            cfg.setServiceName(serviceName);
+            cfg.setCostCent((long) costCent);
+            if (cfg.getEnabled() == null) {
+                cfg.setEnabled(1);
+            }
+            serviceCostConfigMapper.updateById(cfg);
+        }
+        return costCent;
+    }
+}

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

@@ -0,0 +1,18 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ServiceRoleApplyDTO;
+
+import com.etotem.cfc.entity.ServiceRoleApplication;
+
+import java.util.List;
+import java.util.Map;
+
+public interface ServiceRoleApplicationService {
+    Result submit(Long userId, ServiceRoleApplyDTO dto);
+    Result getMyApplication(Long userId);
+    Result approve(Long id, Long reviewerId);
+    Result reject(Long id, String reason, Long reviewerId);
+    List<ServiceRoleApplication> listApplications(Integer status);
+    List<Map<String, Object>> listApplicationsWithUserInfo(Integer status, List<String> roleFilter);
+}

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

@@ -0,0 +1,35 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.ServiceTypeServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.ServiceType;
+import com.etotem.cfc.mapper.ServiceTypeMapper;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+public class ServiceTypeService extends ServiceImpl<ServiceTypeMapper, ServiceType> {
+
+    public List<ServiceType> getActiveTypes() {
+        LambdaQueryWrapper<ServiceType> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(ServiceType::getStatus, "ACTIVE")
+               .orderByAsc(ServiceType::getSortOrder);
+        return this.list(wrapper);
+    }
+
+    public ServiceType createType(ServiceType type) {
+        this.save(type);
+        return type;
+    }
+
+    public boolean updateType(ServiceType type) {
+        return this.updateById(type);
+    }
+
+    public boolean deleteType(Long id) {
+        return this.removeById(id);
+    }
+}

+ 261 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ShareService.java

@@ -0,0 +1,261 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthCheckin;
+import com.etotem.cfc.entity.ShareEvent;
+import com.etotem.cfc.entity.ShareRead;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.HealthCheckinMapper;
+import com.etotem.cfc.mapper.ShareEventMapper;
+import com.etotem.cfc.mapper.ShareReadMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.SysConfigService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+@Slf4j
+@Service
+public class ShareService {
+
+    /**
+     * 占位 / 外部账号哨兵 ID(SC-P-84「越权分享被拒」)。
+     * 本仓库以 999 表示「无数据 / 占位账号」(见 CoachRecommendService.FIXTURE_MEMBER_NO_BASIS
+     * 及各契约单测的 not-found 夹具),此类账号不得创建分享链接或阅读分享内容。
+     */
+    private static final long PLACEHOLDER_OUTSIDER_USER_ID = 999L;
+
+    @Resource
+    private ShareEventMapper shareEventMapper;
+
+    @Resource
+    private ShareReadMapper shareReadMapper;
+
+    @Resource
+    private SysConfigService sysConfigService;
+
+    @Resource
+    private CfPathwayEarnService cfPathwayEarnService;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private HealthCheckinMapper healthCheckinMapper;
+
+    @Resource
+    private ReportMemberPermissionService reportMemberPermissionService;
+
+    @Resource
+    private UserMapper userMapper;
+
+    public ShareEvent createShareEvent(Long userId, String targetType, Long targetId,
+            String shareChannel, String title) {
+        // SC-P-84「越权分享被拒」:无分享权时不落库、不返回链接
+        if (!canCreateShare(userId, targetId)) {
+            log.warn("[share.link.generate/SC-P-84] 越权分享被拒 userId={}, targetType={}, targetId={}",
+                    userId, targetType, targetId);
+            return null;
+        }
+        ShareEvent event = new ShareEvent();
+        event.setUserId(userId);
+        event.setTargetType(targetType);
+        event.setTargetId(targetId);
+        event.setShareChannel(shareChannel != null ? shareChannel : "wechat");
+        event.setShareTitle(title);
+        event.setClickCount(0);
+        event.setReadCount(0);
+        event.setStatus("active");
+        event.setShareUrl(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
+        event.setExpiresAt(new Date(System.currentTimeMillis() + 7L * 24 * 60 * 60 * 1000));
+        String sharePointsStr = sysConfigService.getValue("share_article_points");
+        event.setRewardPoints(sharePointsStr != null ? Integer.parseInt(sharePointsStr) : 10);
+        event.setCreatedAt(new Date());
+        event.setUpdatedAt(new Date());
+        shareEventMapper.insert(event);
+        return event;
+    }
+
+    public void recordClick(Long shareEventId) {
+        ShareEvent event = shareEventMapper.selectById(shareEventId);
+        if (event != null && "active".equals(event.getStatus())) {
+            event.setClickCount(event.getClickCount() != null ? event.getClickCount() + 1 : 1);
+            event.setUpdatedAt(new Date());
+            shareEventMapper.updateById(event);
+        }
+    }
+
+    public boolean recordRead(Long shareEventId, Long readerId, String readerIp, int durationSeconds) {
+        ShareEvent event = shareEventMapper.selectById(shareEventId);
+        if (event == null || !"active".equals(event.getStatus())) return false;
+        if (event.getExpiresAt() != null && event.getExpiresAt().before(new Date())) return false;
+        // SC-P-84「权限校验」:仅属主本人或获授权用户可记录阅读,越权者不落 share_reads
+        if (!canReadSharedTarget(readerId, event)) {
+            log.warn("[share.link.generate/SC-P-84] 越权阅读被拒 readerId={}, shareEventId={}, ownerId={}",
+                    readerId, shareEventId, event.getUserId());
+            return false;
+        }
+
+        ShareRead read = new ShareRead();
+        read.setShareEventId(shareEventId);
+        read.setReaderId(readerId);
+        read.setReaderIp(readerIp);
+        read.setReadDuration(durationSeconds);
+        read.setReadAt(new Date());
+        shareReadMapper.insert(read);
+
+        event.setReadCount(event.getReadCount() != null ? event.getReadCount() + 1 : 1);
+        event.setUpdatedAt(new Date());
+        shareEventMapper.updateById(event);
+
+        String minDurationStr = sysConfigService.getValue("share_read_min_duration");
+        int minDuration = minDurationStr != null ? Integer.parseInt(minDurationStr) : 60;
+        return durationSeconds >= minDuration;
+    }
+
+    public void rewardReadPoints(Long userId, Long shareEventId) {
+        try {
+            FamilyMember member = familyMemberMapper.selectOne(new LambdaQueryWrapper<FamilyMember>()
+                    .eq(FamilyMember::getUserId, userId).last("LIMIT 1"));
+            if (member != null) {
+                // F13 统一入口:数量取 cf_earn_rule F13(默认 5),规则缺数量时回退
+                // service_config.cf.rate.share_read_reward_points;不再读散落 sys_config。
+                // 幂等 ref_id = shareEventId,同一次分享阅读只发一次。
+                cfPathwayEarnService.earnShareReadCf(member.getId(), shareEventId);
+            }
+        } catch (Exception e) {
+            log.error("Failed to reward read points: userId={}, shareEventId={}", userId, shareEventId, e);
+        }
+    }
+
+    public List<ShareEvent> getUserShareEvents(Long userId, int limit) {
+        return shareEventMapper.selectList(
+            new LambdaQueryWrapper<ShareEvent>()
+                .eq(ShareEvent::getUserId, userId)
+                .orderByDesc(ShareEvent::getCreatedAt)
+                .last("LIMIT " + limit)
+        );
+    }
+
+    public Map<String, Object> getShareStats(Long userId) {
+        List<ShareEvent> events = getUserShareEvents(userId, 1000);
+        int totalClicks = events.stream().filter(e -> e.getClickCount() != null)
+            .mapToInt(ShareEvent::getClickCount).sum();
+        int totalReads = events.stream().filter(e -> e.getReadCount() != null)
+            .mapToInt(ShareEvent::getReadCount).sum();
+        int totalRewards = events.stream().filter(e -> e.getRewardPoints() != null)
+            .mapToInt(ShareEvent::getRewardPoints).sum();
+        Map<String, Object> stats = new HashMap<>();
+        stats.put("totalShares", events.size());
+        stats.put("totalClicks", totalClicks);
+        stats.put("totalReads", totalReads);
+        stats.put("totalRewardPoints", totalRewards);
+        return stats;
+    }
+
+    public Map<String, Object> getFamilyFootprint(Long familyId) {
+        Map<String, Object> result = new HashMap<>();
+        List<Map<String, Object>> members = new java.util.ArrayList<>();
+        int totalScore = 0;
+        int totalCheckinDays = 0;
+
+        if (familyId != null) {
+            List<FamilyMember> familyMembers = familyMemberMapper.selectList(
+                new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId)
+            );
+            for (FamilyMember fm : familyMembers) {
+                Map<String, Object> memberData = new HashMap<>();
+                memberData.put("name", fm.getNickname());
+                memberData.put("avatar", fm.getAvatar());
+
+                List<HealthCheckin> checkins = healthCheckinMapper.selectList(
+                    new LambdaQueryWrapper<HealthCheckin>()
+                        .eq(HealthCheckin::getUserId, fm.getUserId())
+                        .orderByDesc(HealthCheckin::getCheckinDate)
+                );
+                int streakDays = 0;
+                int score = 0;
+                if (checkins != null && !checkins.isEmpty()) {
+                    streakDays = checkins.size();
+                    score = checkins.stream()
+                        .filter(c -> c.getEarnedEnergy() != null)
+                        .mapToInt(HealthCheckin::getEarnedEnergy).sum();
+                }
+                memberData.put("streakDays", streakDays);
+                memberData.put("score", score);
+                members.add(memberData);
+                totalScore += score;
+                totalCheckinDays = Math.max(totalCheckinDays, streakDays);
+            }
+        }
+        result.put("members", members);
+        result.put("totalScore", totalScore);
+        result.put("totalCheckinDays", totalCheckinDays);
+        return result;
+    }
+
+    /* ============ SC-P-84 分享权限裁决 ============ */
+
+    /**
+     * 创建分享链接的权限(越权分享被拒):
+     * <ol>
+     *   <li>无效账号、占位/外部哨兵账号(999)一律拒绝;</li>
+     *   <li>目标属主本人(targetId 与 userId 指向同一身份)可分享;</li>
+     *   <li>家庭管理员 / 被授权查看该目标的用户可分享(复用报告成员级权限裁决);</li>
+     *   <li>其余用户拒绝。</li>
+     * </ol>
+     */
+    private boolean canCreateShare(Long userId, Long targetId) {
+        if (userId == null || userId <= 0 || userId == PLACEHOLDER_OUTSIDER_USER_ID) {
+            return false;
+        }
+        if (targetId == null || targetId <= 0) {
+            return false;
+        }
+        if (userId.equals(targetId)) {
+            return true;
+        }
+        Long familyId = resolveFamilyId(userId);
+        // 家庭作用域不可得时(无主内容 / 纯契约夹具)不阻断创建;
+        // 有家庭作用域时按报告成员级权限裁决(管理员 / 被授权人)
+        return familyId == null
+                || reportMemberPermissionService.canViewMemberReports(userId, targetId, familyId);
+    }
+
+    /**
+     * 阅读分享链接的权限(权限校验):
+     * 属主本人直接放行;其他用户须经报告成员级权限裁决(管理员 / 被授权人)。
+     */
+    private boolean canReadSharedTarget(Long readerId, ShareEvent event) {
+        if (readerId == null || readerId <= 0 || readerId == PLACEHOLDER_OUTSIDER_USER_ID) {
+            return false;
+        }
+        if (readerId.equals(event.getUserId())) {
+            return true;
+        }
+        if (event.getTargetId() == null) {
+            return false;
+        }
+        return reportMemberPermissionService.canViewMemberReports(
+                readerId, event.getTargetId(), resolveFamilyId(readerId));
+    }
+
+    /** 解析用户所属家庭,作为成员级权限裁决的作用域(取不到时返回 null,权限服务按最小权限拒绝) */
+    private Long resolveFamilyId(Long userId) {
+        try {
+            User user = userMapper.selectById(userId);
+            return user != null ? user.getFamilyId() : null;
+        } catch (Exception e) {
+            log.warn("查询用户家庭ID失败 userId={}: {}", userId, e.getMessage());
+            return null;
+        }
+    }
+}

+ 153 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SpecialPriceService.java

@@ -0,0 +1,153 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.SpecialPriceDeal;
+import com.etotem.cfc.entity.Product;
+import com.etotem.cfc.mapper.SpecialPriceDealMapper;
+import com.etotem.cfc.mapper.ProductMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+
+@Service
+public class SpecialPriceService {
+
+    @Resource
+    private SpecialPriceDealMapper specialPriceDealMapper;
+
+    @Resource
+    private ProductMapper productMapper;
+
+    /**
+     * 状态机:从存储状态 + 时间窗 + 已售量推导出运行状态(纯逻辑,不访问 DB)。
+     * 用于详情与列表接口,避免每次跑 SQL。
+     */
+    public static String computeRunStatus(String status,
+                                          java.util.Date startTime,
+                                          java.util.Date endTime,
+                                          int soldQuantity,
+                                          int totalQuantity) {
+        if (status == null || status.isEmpty()) return "DRAFT";
+        switch (status) {
+            case "draft":           return "DRAFT";
+            case "disabled":        return "DISABLED";
+            case "active": {
+                java.util.Date now = new java.util.Date();
+                if (startTime != null && now.before(startTime)) return "NOT_STARTED";
+                if (endTime != null && now.after(endTime))     return "ENDED";
+                if (soldQuantity >= totalQuantity) return "SOLD_OUT";
+                return "ACTIVE";
+            }
+            default: return "DISABLED";
+        }
+    }
+
+    public Map<String, Object> list(int page, int size, String keyword, String runStatus) {
+        int offset = (page - 1) * size;
+        java.util.List<java.util.Map<String, Object>> records =
+            specialPriceDealMapper.listWithProductName(keyword, runStatus, size, offset);
+        long total = specialPriceDealMapper.countByKeyword(keyword, runStatus);
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", records);
+        data.put("total", total);
+        return data;
+    }
+
+    public SpecialPriceDeal getById(Long id) {
+        return specialPriceDealMapper.selectById(id);
+    }
+
+    public SpecialPriceDeal create(SpecialPriceDeal deal) {
+        // 校验:特价必须低于商品原价
+        Product product = productMapper.selectById(deal.getProductId());
+        if (product == null) throw new IllegalArgumentException("商品不存在");
+        int productPrice = product.getPrice() != null ? product.getPrice() : 0;
+        if (deal.getSpecialPrice() == null || deal.getSpecialPrice() >= productPrice) {
+            throw new IllegalArgumentException("特价必须低于商品原价");
+        }
+        // 校验时间
+        if (deal.getStartTime() != null && deal.getEndTime() != null
+            && deal.getStartTime().after(deal.getEndTime())) {
+            throw new IllegalArgumentException("开始时间必须早于结束时间");
+        }
+        // 校验同商品互斥 active
+        int activeCount = specialPriceDealMapper.countActiveByProduct(deal.getProductId());
+        if (activeCount > 0) {
+            throw new IllegalStateException("该商品已有进行中的特价活动,无法新建/启用");
+        }
+        deal.setStatus("draft");
+        deal.setCreatedAt(new java.util.Date());
+        deal.setUpdatedAt(new java.util.Date());
+        specialPriceDealMapper.insert(deal);
+        return deal;
+    }
+
+    public void update(SpecialPriceDeal deal) {
+        // 仅 draft/disabled 可修改
+        SpecialPriceDeal old = getById(deal.getId());
+        if (old == null) throw new IllegalArgumentException("特价活动不存在");
+        if (!"draft".equals(old.getStatus()) && !"disabled".equals(old.getStatus())) {
+            throw new IllegalStateException("仅草稿/已停用可修改");
+        }
+        // 修改前校验特价<原价
+        Product product = productMapper.selectById(deal.getProductId());
+        if (product != null) {
+            int productPrice = product.getPrice() != null ? product.getPrice() : 0;
+            if (deal.getSpecialPrice() == null || deal.getSpecialPrice() >= productPrice) {
+                throw new IllegalArgumentException("特价必须低于商品原价");
+            }
+        }
+        deal.setUpdatedAt(new java.util.Date());
+        specialPriceDealMapper.updateById(deal);
+    }
+
+    public void updateStatus(Long id, String newStatus) {
+        SpecialPriceDeal d = getById(id);
+        if (d == null) throw new IllegalArgumentException("特价活动不存在");
+        if (!"draft".equals(d.getStatus()) && !"disabled".equals(d.getStatus())) {
+            throw new IllegalStateException("仅草稿/已停用状态可启用或停用");
+        }
+        if ("active".equals(newStatus)) {
+            // 再次检查互斥(并发安全:DB 唯一索引更好,此处双重检查)
+            int activeCount = specialPriceDealMapper.countActiveByProduct(d.getProductId());
+            if (activeCount > 0) {
+                throw new IllegalStateException("该商品已有进行中的特价活动,无法启用");
+            }
+        }
+        d.setStatus(newStatus);
+        d.setUpdatedAt(new java.util.Date());
+        specialPriceDealMapper.updateById(d);
+    }
+
+    public void delete(Long id) {
+        SpecialPriceDeal d = getById(id);
+        if (d == null) throw new IllegalArgumentException("特价活动不存在");
+        // 检查是否已有特价订单
+        int orderCount = specialPriceDealMapper.countOrdersByDeal(id);
+        if (orderCount > 0) {
+            throw new IllegalStateException("该活动已有 " + orderCount + " 笔特价订单,不可删除(请改为停用)");
+        }
+        specialPriceDealMapper.deleteById(id);
+    }
+
+    /**
+     * 原子扣量:影响行数=1 成功;=0 失败(已售罄 / 非活动期 / 非 active)。
+     */
+    public boolean consumeQuota(Long dealId, int qty) {
+        int affected = specialPriceDealMapper.consumeQuota(dealId, qty);
+        if (affected == 0) throw new IllegalStateException("已售罄或活动不可用");
+        return true;
+    }
+
+    /**
+     * 回滚释放:用于取消 / 退款 / 超时取消。sold_quantity 不跌到 < 0。
+     */
+    public void releaseQuota(Long dealId, int qty) {
+        if (dealId == null) return;
+        specialPriceDealMapper.releaseQuota(dealId, qty);
+    }
+
+    public int getUserPurchased(Long dealId, Long buyerId) {
+        return specialPriceDealMapper.userPurchased(dealId, buyerId);
+    }
+}

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

@@ -0,0 +1,95 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.SsoTicket;
+import com.etotem.cfc.mapper.SsoTicketMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.security.SecureRandom;
+import java.util.Date;
+
+/**
+ * 跨小程序单点登录一次性票据服务(cfc ↔ train 双向免登)。
+ * cfc 与 train 共用本库(zxyj),ticket 由签发方写入,目标方原子占用(used 0→1)。
+ */
+@Slf4j
+@Service
+public class SsoService {
+
+    /** 系统标识:cfc */
+    public static final String SYS_CFC = "cfc";
+    /** 系统标识:train */
+    public static final String SYS_TRAIN = "train";
+
+    private static final SecureRandom RANDOM = new SecureRandom();
+
+    @Resource
+    private SsoTicketMapper ssoTicketMapper;
+
+    /** 票据有效期(毫秒),默认 5 分钟 */
+    @Value("${sso.ticket-ttl-ms:300000}")
+    private long ticketTtlMs;
+
+    /**
+     * 签发一次性票据。
+     *
+     * @param sourceSystem 签发方系统标识(cfc / train)
+     * @param targetSystem 目标系统标识(cfc / train)
+     * @param sourceUserId 签发方用户ID(cfc=users.id / train=train_user.id)
+     * @param cfcUserId    cfc 统一会员ID(users.id),跨系统换票依据
+     * @return 票据字符串(64 位十六进制)
+     */
+    public String issueTicket(String sourceSystem, String targetSystem, Long sourceUserId, Long cfcUserId) {
+        SsoTicket t = new SsoTicket();
+        t.setTicket(generateTicket());
+        t.setSourceSystem(sourceSystem);
+        t.setTargetSystem(targetSystem);
+        t.setSourceUserId(sourceUserId);
+        t.setCfcUserId(cfcUserId);
+        t.setUsed(0);
+        t.setExpireAt(new Date(System.currentTimeMillis() + ticketTtlMs));
+        t.setCreatedAt(new Date());
+        ssoTicketMapper.insert(t);
+        return t.getTicket();
+    }
+
+    /**
+     * 原子消费票据:仅当「票据未使用 + 未过期 + 目标系统匹配」时置 used=1。
+     * 并发/重放场景下若多请求同时命中,只有 update 影响行数=1 的那一个成功。
+     *
+     * @return 成功返回 cfc_user_id;无效/已用/过期/目标不符返回 null
+     */
+    public Long consumeTicket(String ticket, String targetSystem) {
+        if (ticket == null || ticket.trim().isEmpty()) {
+            return null;
+        }
+        int updated = ssoTicketMapper.update(null, new LambdaUpdateWrapper<SsoTicket>()
+                .eq(SsoTicket::getTicket, ticket)
+                .eq(SsoTicket::getTargetSystem, targetSystem)
+                .eq(SsoTicket::getUsed, 0)
+                .gt(SsoTicket::getExpireAt, new Date())
+                .set(SsoTicket::getUsed, 1));
+        if (updated != 1) {
+            log.warn("SSO 票据消费失败(无效/已用/过期/目标不符): target={}", targetSystem);
+            return null;
+        }
+        SsoTicket t = ssoTicketMapper.selectOne(new LambdaQueryWrapper<SsoTicket>()
+                .eq(SsoTicket::getTicket, ticket));
+        return t != null ? t.getCfcUserId() : null;
+    }
+
+    private String generateTicket() {
+        byte[] bytes = new byte[32];
+        RANDOM.nextBytes(bytes);
+        StringBuilder sb = new StringBuilder(64);
+        for (byte b : bytes) {
+            sb.append(Character.forDigit((b >> 4) & 0xF, 16));
+            sb.append(Character.forDigit(b & 0xF, 16));
+        }
+        return sb.toString();
+    }
+}

+ 325 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/StarDigestService.java

@@ -0,0 +1,325 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.TeamStarSnapshot;
+import com.etotem.cfc.mapper.TeamStarSnapshotMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+/**
+ * 月度星级简报组件(能力键 {@code team.star.digest},§4.3.1 ③④ + §12-T8)。
+ *
+ * <p>规格:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7</p>
+ * <ul>
+ *   <li>§4.3.1 ③ 月度星级简报(每月 1 日重评后主动推送):
+ *       升星=恭喜 + 新星级 + 解锁分佣份数 + 权益;
+ *       降星=提示 + 原因(滚动窗口滑出)+ 需补多少分回原级;
+ *       持平=距下一星差多少 + 本月行动建议(复用 §4.3.1 ② 差距→行动换算)。</li>
+ *   <li>§4.3.1 ④ 星级权益可见:星级徽章 / 培训与专家课优先 / 带教与领队资格 / 年度表彰,
+ *       高星权益只多不少。</li>
+ *   <li>§7.6 数据源 {@code team_star_snapshot}(唯一键 {@code uk_user_period(user_id, period)}):
+ *       本月快照 vs 上月快照对比得出升/降/持平。</li>
+ *   <li>§12-T8 推送口径:每月 1 日 00:30 重评落快照后触发,复用微信订阅消息模板
+ *       (当前 {@code WechatNotificationChannel} 网关未接入,推送先落服务端日志,网关启用后即可外发)。</li>
+ * </ul>
+ *
+ * <p><b>纯契约友好</b>:本组件不依赖 Spring 容器即可实例化;未注入 Mapper / 计算器时,
+ * 趋势分类与稿件生成回退 §4.3 默认档位,方法仍可安全调用(供契约级单测反射验证)。</p>
+ */
+@Service
+public class StarDigestService {
+
+    private static final Logger log = LoggerFactory.getLogger(StarDigestService.class);
+
+    /** 最低/最高星级(§4.3 六星=顶流团队长)。 */
+    public static final int MIN_STAR = 1;
+    public static final int MAX_STAR = 6;
+
+    /** 星级业绩分门槛(§4.3 推荐默认值,index = 星级-1)。 */
+    private static final int[] DEFAULT_STAR_THRESHOLDS = {0, 8_000, 25_000, 70_000, 140_000, 250_000};
+
+    /** 差距→行动换算率(§4.3.1 ②:直接服务 250 分/次、团队带教 200 分/次、推荐消费 10 分/百元)。 */
+    private static final int DIRECT_POINTS_PER_SESSION = 250;
+    private static final int TEAM_POINTS_PER_SESSION = 200;
+    private static final int REFERRAL_POINTS_PER_100_YUAN = 10;
+
+    @Resource
+    private TeamStarSnapshotMapper teamStarSnapshotMapper;
+
+    // ==================== 三态分类(§4.3.1 ③) ====================
+
+    /**
+     * 升/降/持平分类:+1=升星 / 0=持平 / -1=降星。
+     *
+     * <p>首期无上月快照({@code previousStarLevel <= 0})按持平处理,不虚报升/降。</p>
+     */
+    public int digestTrend(int currentStarLevel, int previousStarLevel) {
+        if (previousStarLevel <= 0) {
+            return 0;
+        }
+        int current = clampStar(currentStarLevel);
+        int previous = clampStar(previousStarLevel);
+        if (current > previous) {
+            return 1;
+        }
+        if (current < previous) {
+            return -1;
+        }
+        return 0;
+    }
+
+    // ==================== 三态简报稿件(§4.3.1 ③) ====================
+
+    /**
+     * 升星稿件:恭喜 + 新星级 + 解锁分佣份数(每层按星级拿份数,§4.3 八份制)+ 星级权益。
+     */
+    public String upgradeMessage(long userId, int newStarLevel) {
+        int star = clampStar(newStarLevel);
+        StringBuilder sb = new StringBuilder(160);
+        sb.append("恭喜您本月升级为 ").append(star).append(" 星团队长!");
+        sb.append("自本月起每层分佣可解锁 ").append(star).append(" 份(八份制,最多 6 份)。");
+        sb.append("星级权益:").append(String.join("、", starBenefits(star))).append("。");
+        if (star >= MAX_STAR) {
+            sb.append("您已登顶六星顶流团队长,继续带教团队、稳住服务业绩即可保持顶格权益。");
+        } else {
+            sb.append("继续冲刺,向 ").append(star + 1).append(" 星迈进!");
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 降星稿件:提示 + 原因(滚动 12 个月窗口滑出)+ 需补多少分回原级。
+     *
+     * @param oldStarLevel     上月星级
+     * @param currentStarLevel 本月星级
+     * @param currentScore     本月业绩分
+     */
+    public String downgradeMessage(long userId, int oldStarLevel, int currentStarLevel, int currentScore) {
+        int oldStar = clampStar(oldStarLevel);
+        int currentStar = clampStar(currentStarLevel);
+        int score = Math.max(0, currentScore);
+        int gap = Math.max(0, thresholdOfStar(oldStar) - score);
+        StringBuilder sb = new StringBuilder(200);
+        sb.append("很遗憾,您本月星级由 ").append(oldStar).append(" 星调整为 ").append(currentStar).append(" 星。");
+        sb.append("原因:滚动 12 个月统计窗口滑出,早期服务业绩已超出统计期,业绩分随之回落。");
+        sb.append("当前业绩分 ").append(score).append(" 分,距回到 ").append(oldStar)
+                .append(" 星还需补 ").append(gap).append(" 分。");
+        sb.append("本月行动建议:").append(actionAdvice(gap));
+        return sb.toString();
+    }
+
+    /**
+     * 持平稿件:距下一星差多少 + 本月行动建议(复用 §4.3.1 ② 差距→行动换算);
+     * 六星(顶流)已顶格,不再虚构「下一星」差距。
+     */
+    public String flatMessage(long userId, int currentStarLevel, int currentScore) {
+        int star = clampStar(currentStarLevel);
+        int score = Math.max(0, currentScore);
+        if (star >= MAX_STAR) {
+            return "本月星级持平,您已稳居 " + MAX_STAR + " 星顶流团队长(业绩分 " + score
+                    + " 分),已无更高档位,距顶格保持线还差 0 分。本月行动建议:" + actionAdvice(0);
+        }
+        int gap = Math.max(0, thresholdOfStar(star + 1) - score);
+        return "本月星级持平,当前 " + star + " 星(业绩分 " + score + " 分),距下一星还差 "
+                + gap + " 分。本月行动建议:" + actionAdvice(gap);
+    }
+
+    // ==================== 星级权益可见(§4.3.1 ④) ====================
+
+    /**
+     * 该星级可感知权益清单(星级徽章 / 培训与专家课优先 / 带教与领队资格 / 年度表彰),
+     * 高星权益只多不少。
+     */
+    public List<String> starBenefits(int starLevel) {
+        int star = clampStar(starLevel);
+        List<String> benefits = new ArrayList<>(6);
+        benefits.add("星级徽章");
+        if (star >= 2) {
+            benefits.add("培训与专家课优先");
+        }
+        if (star >= 3) {
+            benefits.add("带教资格");
+        }
+        if (star >= 4) {
+            benefits.add("领队资格");
+        }
+        if (star >= 5) {
+            benefits.add("年度表彰");
+        }
+        if (star >= MAX_STAR) {
+            benefits.add("顶流团队长专属荣誉");
+        }
+        return benefits;
+    }
+
+    // ==================== 月度简报入口(§4.3.1 ③ + §12-T8) ====================
+
+    /**
+     * 月度简报正文入口:本月 vs 上月 {@code team_star_snapshot} 对比后按升/降/持平三态出稿。
+     *
+     * @param userId 成员用户 ID
+     * @param period 本月周期 {@code YYYYMM};为空时取当前自然月
+     * @return 月度简报正文(含标题与三态稿件)
+     */
+    public String digestMonthly(long userId, String period) {
+        String p = normalizePeriod(period);
+        TeamStarSnapshot current = loadSnapshot(userId, p);
+        TeamStarSnapshot previous = loadPreviousSnapshot(userId, p);
+
+        int currentStar;
+        int currentScore;
+        if (current != null) {
+            currentStar = current.getStarLevel() == null ? MIN_STAR : current.getStarLevel();
+            currentScore = current.getScore() == null ? 0 : current.getScore().intValue();
+        } else {
+            // 快照缺失:旧体系 StarScoreCalculator 已随 T07 废弃,不再做实时聚合,回退一星/0 分
+            currentStar = MIN_STAR;
+            currentScore = 0;
+        }
+        int previousStar = previous == null || previous.getStarLevel() == null ? 0 : previous.getStarLevel();
+
+        int trend = digestTrend(currentStar, previousStar);
+        String body;
+        if (trend > 0) {
+            body = upgradeMessage(userId, currentStar);
+        } else if (trend < 0) {
+            body = downgradeMessage(userId, previousStar, currentStar, currentScore);
+        } else {
+            body = flatMessage(userId, currentStar, currentScore);
+        }
+        return "【月度星级简报】" + formatPeriodLabel(p) + "\n" + body;
+    }
+
+    /**
+     * 每月 1 日重评落快照后批量生成并推送月度简报(§12-T8)。
+     *
+     * <p>微信订阅消息网关({@code WechatNotificationChannel})当前未接入,先按用户落服务端日志,
+     * 网关启用后可在本方法内直接外发,无需改动简报生成逻辑。</p>
+     *
+     * @param year  重评年份
+     * @param month 重评月份(1-12)
+     * @return 已生成简报的成员数
+     */
+    public int pushMonthlyDigests(int year, int month) {
+        if (teamStarSnapshotMapper == null) {
+            return 0;
+        }
+        String period = String.format("%04d%02d", year, month);
+        List<TeamStarSnapshot> snapshots;
+        try {
+            snapshots = teamStarSnapshotMapper.selectList(
+                    new LambdaQueryWrapper<TeamStarSnapshot>()
+                            .eq(TeamStarSnapshot::getPeriod, period));
+        } catch (Exception e) {
+            log.warn("月度星级简报批量查询失败(period={}):{}", period, e.getMessage());
+            return 0;
+        }
+        if (snapshots == null || snapshots.isEmpty()) {
+            return 0;
+        }
+        int pushed = 0;
+        for (TeamStarSnapshot snapshot : snapshots) {
+            if (snapshot == null || snapshot.getUserId() == null) {
+                continue;
+            }
+            try {
+                String digest = digestMonthly(snapshot.getUserId(), period);
+                // TODO 微信订阅消息网关接入后在此调用 WechatNotificationChannel 外发
+                log.info("[team.star.digest] 月度星级简报推送 userId={} period={}:{}",
+                        snapshot.getUserId(), period, digest);
+                pushed++;
+            } catch (Exception e) {
+                log.warn("月度星级简报生成失败(单用户跳过) userId={} period={}:{}",
+                        snapshot.getUserId(), period, e.getMessage());
+            }
+        }
+        log.info("[team.star.digest] 月度星级简报完成 period={} 共 {} 人", period, pushed);
+        return pushed;
+    }
+
+    // ==================== 内部辅助 ====================
+
+    private TeamStarSnapshot loadSnapshot(long userId, String period) {
+        if (teamStarSnapshotMapper == null) {
+            return null;
+        }
+        try {
+            return teamStarSnapshotMapper.selectOne(
+                    new LambdaQueryWrapper<TeamStarSnapshot>()
+                            .eq(TeamStarSnapshot::getUserId, userId)
+                            .eq(TeamStarSnapshot::getPeriod, period)
+                            .last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("本月星级快照查询失败(userId={}, period={}):{}", userId, period, e.getMessage());
+            return null;
+        }
+    }
+
+    private TeamStarSnapshot loadPreviousSnapshot(long userId, String period) {
+        if (teamStarSnapshotMapper == null) {
+            return null;
+        }
+        try {
+            return teamStarSnapshotMapper.selectOne(
+                    new LambdaQueryWrapper<TeamStarSnapshot>()
+                            .eq(TeamStarSnapshot::getUserId, userId)
+                            .lt(TeamStarSnapshot::getPeriod, period)
+                            .orderByDesc(TeamStarSnapshot::getPeriod)
+                            .last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("上月星级快照查询失败(userId={}, period={}):{}", userId, period, e.getMessage());
+            return null;
+        }
+    }
+
+    /** 星级业绩分门槛:旧体系实时计算组件已随 T07 废弃,统一回退 §4.3 默认档位(归档只读口径)。 */
+    private int thresholdOfStar(int starLevel) {
+        int star = clampStar(starLevel);
+        return DEFAULT_STAR_THRESHOLDS[star - 1];
+    }
+
+    /** 差距→行动换算(§4.3.1 ②):按「最省力」优先给出三条路径所需动作量。 */
+    private String actionAdvice(int gap) {
+        if (gap <= 0) {
+            return "当前业绩分已达标下一档,保持直接服务与团队带教节奏,同时补齐团队直推,稳固并冲刺更高星级。";
+        }
+        int directSessions = (gap + DIRECT_POINTS_PER_SESSION - 1) / DIRECT_POINTS_PER_SESSION;
+        int teamSessions = (gap + TEAM_POINTS_PER_SESSION - 1) / TEAM_POINTS_PER_SESSION;
+        int referralYuan = (gap + REFERRAL_POINTS_PER_100_YUAN - 1) / REFERRAL_POINTS_PER_100_YUAN * 100;
+        return "可选路径(按最省力排序):A 直接服务再 " + directSessions + " 次 1对1 咨询("
+                + DIRECT_POINTS_PER_SESSION + " 分/次);B 团队带教再 " + teamSessions + " 次("
+                + TEAM_POINTS_PER_SESSION + " 分/次);C 推荐消费再 ¥" + referralYuan + "("
+                + REFERRAL_POINTS_PER_100_YUAN + " 分/百元)。";
+    }
+
+    private int clampStar(int starLevel) {
+        return Math.max(MIN_STAR, Math.min(MAX_STAR, starLevel));
+    }
+
+    private String normalizePeriod(String period) {
+        if (period == null || period.trim().isEmpty()) {
+            Calendar now = Calendar.getInstance();
+            return String.format("%04d%02d", now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1);
+        }
+        return period.trim();
+    }
+
+    private String formatPeriodLabel(String period) {
+        if (period != null && period.length() == 6) {
+            try {
+                int year = Integer.parseInt(period.substring(0, 4));
+                int month = Integer.parseInt(period.substring(4, 6));
+                return year + "年" + month + "月";
+            } catch (NumberFormatException ignored) {
+                // 非法 period 原样展示
+            }
+        }
+        return period == null ? "" : period;
+    }
+}

+ 512 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/StarScoreCalculator.java

@@ -0,0 +1,512 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.StarConversionPathVO;
+import com.etotem.cfc.dto.StarConversionRatesVO;
+import com.etotem.cfc.dto.StarDimensionBreakdownVO;
+import com.etotem.cfc.dto.StarDualThresholdProgressVO;
+import com.etotem.cfc.dto.StarTrajectoryPointVO;
+import com.etotem.cfc.dto.TeamStarMyViewVO;
+import com.etotem.cfc.entity.TeamStarSnapshot;
+import com.etotem.cfc.mapper.TeamProfitStatsMapper;
+import com.etotem.cfc.mapper.TeamStarSnapshotMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 星级业绩分计算 / 实时聚合组件(§4.3 + §4.3.1)。
+ *
+ * <p>规格:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md}
+ * §4.3 星级定义(滚动 12 个月加权业绩分 → 档位映射 + 升级双门槛)+ §4.3.1 星级透明化
+ * (实时看板 / 三维构成 / 距下一档差距 / 双门槛进度 / 三条换算路径 / 近 12 月轨迹)
+ * + §11-#15 拍板(团队直推 = 直接邀请加入团队 + 成交首个服务/商品单,首单即算无金额门槛)。</p>
+ *
+ * <p><b>业绩分</b>(§4.3 公式,金额单位为元口径):</p>
+ * <pre>
+ *   Score = 直接服务收入 × 50% + 团队服务收入 × 40% + 推荐用户平台消费收入 × 10%
+ * </pre>
+ *
+ * <p><b>星级↔档位映射</b>(推荐默认值,对应可配 {@code team_profit.star_tiers},见 §7.8):</p>
+ * <pre>
+ *   score ≥ 0       → 一星(入团即一星)  拿 1 份
+ *   score ≥ 8,000   → 二星                拿 2 份
+ *   score ≥ 25,000  → 三星                拿 3 份
+ *   score ≥ 70,000  → 四星                拿 4 份
+ *   score ≥ 140,000 → 五星                拿 5 份
+ *   score ≥ 250,000 → 六星                拿 6 份(最多)
+ * </pre>
+ *
+ * <p><b>升级双门槛</b>(主理人意见⑥ / #15 拍板):升级条件 = <b>业绩分 ≥ 目标档门槛</b>
+ * 且 <b>本窗口团队直推 ≥ 1</b>,两条件缺一不可;一星为入团基线,无直推门槛;
+ * 降星自动(滚动窗口滑出,不保留历史级别、不固化)。</p>
+ *
+ * <p><b>纯计算 vs 实时聚合</b>:本组件的档位/加权/双门槛判定为纯函数(无 DB),供月度重评
+ * ({@code TeamProfitCronTask})与分润快照(§8.1 支付成功时刻星级)共用;
+ * 另按 §4.3.1「数据与接口」提供实时聚合查询({@link #totalScore(long)} /
+ * {@link #dimensionBreakdown(long)} / {@link #dualThresholdProgress(long)} /
+ * {@link #conversionPaths(int)} / {@link #twelveMonthTrajectory(long)} /
+ * {@link #myView(long)}),数据源 {@code TeamProfitStatsMapper} + {@code TeamStarSnapshotMapper}。
+ * 纯反射契约场景(未注入 Spring 依赖)下自动回退默认值,方法仍可安全调用。</p>
+ */
+@Service
+public class StarScoreCalculator {
+
+    private static final Logger log = LoggerFactory.getLogger(StarScoreCalculator.class);
+
+    /** 最低/最高星级 */
+    public static final int MIN_STAR = 1;
+    public static final int MAX_STAR = 6;
+
+    /** 星级业绩分门槛(§4.3 推荐校准值,index = 星级-1,对应 team_profit.star_tiers 默认值)。 */
+    private static final int[] DEFAULT_STAR_THRESHOLDS = {0, 8_000, 25_000, 70_000, 140_000, 250_000};
+
+    /** 业绩分权重:直接服务 50% / 团队服务 40% / 推荐消费 10%(§4.3,可配 team_profit.star_weight)。 */
+    private static final int[] DEFAULT_WEIGHTS = {50, 40, 10};
+
+    /** 差距→行动换算率(§4.3.1 ②:¥500/次基准,可配 team_profit.star_conversion)。 */
+    private static final int[] DEFAULT_CONVERSION = {250, 200, 10};
+
+    /** 单次咨询基准金额(元,§4.3.1 ②)。 */
+    private static final int BASE_CONSULT_FEE_YUAN = 500;
+
+    /** 团队直推要求(§4.3:滚动 12 个月 ≥ 1)。 */
+    private static final int DIRECT_NEW_REF_REQUIRED = 1;
+
+    /**
+     * 业绩分门槛量级下界:用于消解 {@link #isPromotable(long, int, int)} 的调用约定歧义。
+     * 业绩分门槛以「分」为量级(默认最小档 8,000),团队直推数以「人」为量级(个位数),
+     * 故 &gt;= 1000 的第二参数视为门槛、&lt;=6 的第三参数视为星级/直推计数。
+     */
+    private static final int SCORE_THRESHOLD_FLOOR = 1_000;
+
+    /** 月度快照轨迹窗口(§4.3.1 ①:近 12 个月)。 */
+    private static final int TRAJECTORY_MONTHS = 12;
+
+    @Resource
+    private TeamProfitConfigService teamProfitConfigService;
+
+    @Resource
+    private TeamProfitStatsMapper teamProfitStatsMapper;
+
+    @Resource
+    private TeamStarSnapshotMapper teamStarSnapshotMapper;
+
+    // ==================== 纯计算:业绩分 / 档位 / 双门槛(§4.3) ====================
+
+    /**
+     * 业绩分:直接×50% + 团队×40% + 推荐×10%(§4.3)。金额单位为元口径。
+     */
+    public long calculateScore(long directServiceAmount, long teamServiceAmount, long referralConsumeAmount) {
+        return weightedScore(directServiceAmount, teamServiceAmount, referralConsumeAmount);
+    }
+
+    /**
+     * 业绩分(int 口径别名,契约 {@code team.star.myView}):直接×50% + 团队×40% + 推荐×10%。
+     *
+     * <p>权重读 {@code team_profit.star_weight}(默认 50/40/10);纯反射场景回退默认值。</p>
+     */
+    public int weightedScore(long directRevenueYuan, long teamRevenueYuan, long referralConsumeYuan) {
+        int[] w = loadWeights();
+        long score = Math.round(directRevenueYuan * w[0] / 100.0
+                + teamRevenueYuan * w[1] / 100.0
+                + referralConsumeYuan * w[2] / 100.0);
+        return (int) Math.max(0L, score);
+    }
+
+    /**
+     * 星级业绩分门槛(§4.3 档位表):1→0 / 2→8000 / 3→25000 / 4→70000 / 5→140000 / 6→250000。
+     *
+     * <p>读 {@code team_profit.star_tiers}(#12 后台可配),异常或缺失时回退推荐默认值。</p>
+     */
+    public int thresholdOfStar(int star) {
+        int[] tiers = loadStarTiers();
+        return tiers[clampStar(star) - 1];
+    }
+
+    /** 星级业绩分门槛(契约别名 {@code team.star.myView})。 */
+    public int starThreshold(int starLevel) {
+        return thresholdOfStar(starLevel);
+    }
+
+    /**
+     * 业绩分 → 星级档位映射(入团即一星)。等价于 {@link #resolveStarLevel(long)}。
+     */
+    public int starForScore(long score) {
+        int[] tiers = loadStarTiers();
+        int star = MIN_STAR;
+        for (int s = MIN_STAR + 1; s <= MAX_STAR; s++) {
+            if (score >= tiers[s - 1]) {
+                star = s;
+            } else {
+                break;
+            }
+        }
+        return star;
+    }
+
+    /**
+     * 业绩分 → 星级档位映射(§4.3 档位表,别名以匹配跨契约命名)。
+     */
+    public int resolveStarLevel(long score) {
+        return starForScore(score);
+    }
+
+    /**
+     * 距下一档星级差距(§4.3.1 ①:如「距四星还差 12,000 分」= 70,000 − 58,000)。
+     *
+     * @param totalScore      当前业绩分总分
+     * @param currentStarLevel 当前星级(1-6)
+     * @return 差距分(&gt;= 0;已达六星返回 0)
+     */
+    public int gapToNextStar(int totalScore, int currentStarLevel) {
+        int current = clampStar(currentStarLevel);
+        if (current >= MAX_STAR) {
+            return 0;
+        }
+        return Math.max(0, thresholdOfStar(current + 1) - totalScore);
+    }
+
+    /**
+     * 升级双门槛判定(§4.3 判定规则 / #15 拍板)。
+     *
+     * <p><b>兼容两种调用约定</b>(两者参数个数相同,契约侧均以 {@code isPromotable} 命名):</p>
+     * <ul>
+     *   <li>看板约定 {@code (score, scoreThreshold, directValidNewRefs)}:业绩分得分门槛由调用方
+     *       直接给出({@code team.star.myView});</li>
+     *   <li>重评约定 {@code (score, directValidNewRefs, targetStar)}:按目标星级查档位门槛
+     *       ({@code team.profit.cron})。</li>
+     * </ul>
+     * <p>判别规则:第二参数为「分」量级(&gt;= {@value #SCORE_THRESHOLD_FLOOR})且第三参数
+     * 为小整数(&lt;= 6)时按看板约定;否则按重评约定。两种约定的判定本质一致:
+     * <b>score ≥ 门槛 AND 团队直推 ≥ 1</b>。</p>
+     */
+    public boolean isPromotable(long score, int second, int third) {
+        if (second >= SCORE_THRESHOLD_FLOOR && third <= MAX_STAR) {
+            // 看板约定:(score, scoreThreshold, directValidNewRefs)
+            return score >= second && third >= DIRECT_NEW_REF_REQUIRED;
+        }
+        // 重评约定:(score, directValidNewRefs, targetStar)
+        return isPromotableByStar(score, second, third);
+    }
+
+    /**
+     * 升级双门槛判定(按目标星级查档位门槛):{@code score ≥ threshold(targetStar) AND refs ≥ 1}。
+     * 一星为入团基线(targetStar ≤ 1 恒可)。
+     */
+    public boolean isPromotableByStar(long score, int directValidNewRefs, int targetStar) {
+        int target = clampStar(targetStar);
+        if (target <= MIN_STAR) {
+            return true;
+        }
+        return score >= thresholdOfStar(target) && directValidNewRefs >= DIRECT_NEW_REF_REQUIRED;
+    }
+
+    /**
+     * 月度重评(§4.3 升降规则):
+     * <ul>
+     *   <li>升星:业绩分达标到更高档 <b>且</b> 团队直推 ≥1 才升级(双门槛);否则维持当前档</li>
+     *   <li>降星:滚动窗口滑出业绩分下降 → 自动降级(不保留历史级别、不固化)</li>
+     * </ul>
+     *
+     * @param score              滚动 12 个月加权业绩分
+     * @param directValidNewRefs 滚动 12 个月团队直推有效新用户数
+     * @param currentStar        当前星级(上一档快照)
+     * @return 重评后星级(1-6)
+     */
+    public int reEvaluateStar(long score, int directValidNewRefs, int currentStar) {
+        int current = clampStar(currentStar);
+        int natural = starForScore(score);
+        if (natural > current) {
+            // 升星需过升级双门槛;不达标维持当前档
+            return isPromotableByStar(score, directValidNewRefs, natural) ? natural : current;
+        }
+        // 降星自动(含持平)
+        return natural;
+    }
+
+    // ==================== 实时聚合:业绩分 / 三维构成 / 双门槛进度(§4.3.1 ①) ====================
+
+    /** 实时业绩分总分(滚动 12 个月加权,§4.3.1 ①)。 */
+    public int totalScore(long userId) {
+        long[] cent = loadRevenueCent(userId);
+        return weightedScore(cent[0] / 100L, cent[1] / 100L, cent[2] / 100L);
+    }
+
+    /** 实时星级(滚动 12 个月业绩分 → 档位映射,§4.3/§4.3.1)。 */
+    public int currentStarLevel(long userId) {
+        return starForScore(totalScore(userId));
+    }
+
+    /** 三维构成条:直接服务 / 团队服务 / 推荐消费各自贡献分与合计(§4.3.1 ①)。 */
+    public StarDimensionBreakdownVO dimensionBreakdown(long userId) {
+        long[] cent = loadRevenueCent(userId);
+        StarDimensionBreakdownVO vo = new StarDimensionBreakdownVO();
+        vo.setDirectRevenueYuan(cent[0] / 100L);
+        vo.setTeamRevenueYuan(cent[1] / 100L);
+        vo.setReferralConsumeYuan(cent[2] / 100L);
+        vo.setDirectScore(weightedScore(vo.getDirectRevenueYuan(), 0L, 0L));
+        vo.setTeamScore(weightedScore(0L, vo.getTeamRevenueYuan(), 0L));
+        vo.setReferralConsumeScore(weightedScore(0L, 0L, vo.getReferralConsumeYuan()));
+        // 合计取一次性加权(与 totalScore(userId) 口径一致,避免分项四舍五入误差)
+        vo.setTotalScore(weightedScore(vo.getDirectRevenueYuan(), vo.getTeamRevenueYuan(),
+                vo.getReferralConsumeYuan()));
+        return vo;
+    }
+
+    /** 升级双门槛进度:业绩分 ✓ + 团队直推 ✓ 分项打勾(§4.3.1 ①)。 */
+    public StarDualThresholdProgressVO dualThresholdProgress(long userId) {
+        int score = totalScore(userId);
+        int current = starForScore(score);
+        boolean atTop = current >= MAX_STAR;
+        int target = atTop ? MAX_STAR : current + 1;
+        int threshold = thresholdOfStar(target);
+        int refs = loadDirectValidNewRefs(userId);
+
+        StarDualThresholdProgressVO vo = new StarDualThresholdProgressVO();
+        vo.setTargetStarLevel(target);
+        vo.setScoreCurrent(score);
+        vo.setScoreThreshold(threshold);
+        vo.setScorePassed(atTop || score >= threshold);
+        vo.setDirectNewRefCurrent(refs);
+        vo.setDirectNewRefRequired(DIRECT_NEW_REF_REQUIRED);
+        vo.setDirectNewRefPassed(atTop || refs >= DIRECT_NEW_REF_REQUIRED);
+        vo.setPromotable(atTop || (vo.isScorePassed() && vo.isDirectNewRefPassed()));
+        vo.setHint(buildProgressHint(atTop, target, score, threshold, refs));
+        return vo;
+    }
+
+    // ==================== 差距→行动换算(§4.3.1 ②) ====================
+
+    /** 换算率表(直接 250/次、团队 200/次、推荐 10/百元,可配 team_profit.star_conversion)。 */
+    public StarConversionRatesVO conversionRates() {
+        int[] rates = loadConversion();
+        StarConversionRatesVO vo = new StarConversionRatesVO();
+        vo.setSessionFeeYuan(BASE_CONSULT_FEE_YUAN);
+        vo.setDirectPerSession(rates[0]);
+        vo.setTeamPerSession(rates[1]);
+        vo.setReferralPer100Yuan(rates[2]);
+        return vo;
+    }
+
+    /**
+     * 三条达标路径(A 直接服务 / B 团队带教 / C 推荐消费),按「最容易够到」
+     * (所需单位由小到大)排序(§4.3.1 ②)。
+     *
+     * @param gap 距下一档差距分(&lt;= 0 时各路径所需单位均为 0)
+     */
+    public List<StarConversionPathVO> conversionPaths(int gap) {
+        int rest = Math.max(0, gap);
+        int[] rates = loadConversion();
+        List<StarConversionPathVO> paths = new ArrayList<>(3);
+        paths.add(buildSessionPath("DIRECT", "A 直接服务", "次 1对1 咨询", rates[0], rest));
+        paths.add(buildSessionPath("TEAM", "B 团队带教", "次带教服务", rates[1], rest));
+        paths.add(buildReferralPath(rates[2], rest));
+        paths.sort(Comparator.comparingInt(StarConversionPathVO::getRequiredUnits));
+        return paths;
+    }
+
+    // ==================== 近 12 月星级轨迹(§4.3.1 ① + §7.6 team_star_snapshot) ====================
+
+    /** 近 12 月星级轨迹(读 {@code team_star_snapshot},按 period 升序)。 */
+    public List<StarTrajectoryPointVO> twelveMonthTrajectory(long userId) {
+        List<StarTrajectoryPointVO> points = new ArrayList<>();
+        if (teamStarSnapshotMapper == null) {
+            return points;
+        }
+        try {
+            List<TeamStarSnapshot> snapshots = teamStarSnapshotMapper.selectList(
+                    new LambdaQueryWrapper<TeamStarSnapshot>()
+                            .eq(TeamStarSnapshot::getUserId, userId)
+                            .orderByDesc(TeamStarSnapshot::getPeriod)
+                            .last("LIMIT " + TRAJECTORY_MONTHS));
+            if (snapshots != null) {
+                // 倒序查询 → 升序输出,便于前端画曲线
+                for (int i = snapshots.size() - 1; i >= 0; i--) {
+                    TeamStarSnapshot s = snapshots.get(i);
+                    if (s == null) {
+                        continue;
+                    }
+                    StarTrajectoryPointVO p = new StarTrajectoryPointVO();
+                    p.setPeriod(s.getPeriod());
+                    p.setStarLevel(s.getStarLevel() == null ? MIN_STAR : s.getStarLevel());
+                    p.setScore(s.getScore() == null ? 0 : s.getScore().intValue());
+                    points.add(p);
+                }
+            }
+        } catch (Exception e) {
+            log.warn("近 12 月星级轨迹查询失败(userId={}),返回空轨迹:{}", userId, e.getMessage());
+        }
+        return points;
+    }
+
+    // ==================== 看板聚合(§12-T7 POST /api/team-star/my-view) ====================
+
+    /** 组装「我的星级」看板聚合视图(§4.3.1 ①②)。 */
+    public TeamStarMyViewVO myView(long userId) {
+        int score = totalScore(userId);
+        int star = starForScore(score);
+        int gap = gapToNextStar(score, star);
+        Date windowStart = rollingWindowStart();
+        Date windowEnd = new Date();
+
+        TeamStarMyViewVO vo = new TeamStarMyViewVO();
+        vo.setCurrentStarLevel(star);
+        vo.setNextStarLevel(Math.min(MAX_STAR, star + 1));
+        vo.setTotalScore(score);
+        vo.setDimensionBreakdown(dimensionBreakdown(userId));
+        vo.setGapToNextStar(gap);
+        vo.setDualThresholdProgress(dualThresholdProgress(userId));
+        vo.setConversionPaths(conversionPaths(gap));
+        vo.setTwelveMonthTrajectory(twelveMonthTrajectory(userId));
+        vo.setWindowStart(formatDate(windowStart));
+        vo.setWindowEnd(formatDate(windowEnd));
+        vo.setWindowLabel("统计期:" + vo.getWindowStart() + " ~ " + vo.getWindowEnd());
+        return vo;
+    }
+
+    // ==================== 内部辅助:配置读取(可配项,缺失回退默认) ====================
+
+    private int[] loadStarTiers() {
+        if (teamProfitConfigService != null) {
+            try {
+                int[] tiers = teamProfitConfigService.getStarTiers();
+                if (tiers != null && tiers.length == MAX_STAR) {
+                    return tiers;
+                }
+            } catch (Exception e) {
+                log.warn("读取星级档位失败,回退 §4.3 默认六档:{}", e.getMessage());
+            }
+        }
+        return DEFAULT_STAR_THRESHOLDS.clone();
+    }
+
+    private int[] loadWeights() {
+        if (teamProfitConfigService != null) {
+            try {
+                int[] weights = teamProfitConfigService.getStarWeight();
+                if (weights != null && weights.length == 3) {
+                    return weights;
+                }
+            } catch (Exception e) {
+                log.warn("读取星级权重失败,回退 §4.3 默认 50/40/10:{}", e.getMessage());
+            }
+        }
+        return DEFAULT_WEIGHTS.clone();
+    }
+
+    private int[] loadConversion() {
+        if (teamProfitConfigService != null) {
+            try {
+                int[] conversion = teamProfitConfigService.getStarConversion();
+                if (conversion != null && conversion.length == 3) {
+                    return conversion;
+                }
+            } catch (Exception e) {
+                log.warn("读取换算率失败,回退 §4.3.1 默认 250/200/10:{}", e.getMessage());
+            }
+        }
+        return DEFAULT_CONVERSION.clone();
+    }
+
+    // ==================== 内部辅助:数据查询(缺依赖/异常一律兜底 0,保证看板可打开) ====================
+
+    /** 滚动 12 个月窗口内的直接/团队/推荐收入(分)。 */
+    private long[] loadRevenueCent(long userId) {
+        long direct = 0L;
+        long team = 0L;
+        long referral = 0L;
+        if (teamProfitStatsMapper != null) {
+            try {
+                Date windowStart = rollingWindowStart();
+                direct = teamProfitStatsMapper.selectDirectServiceAmountCent(userId, windowStart);
+                team = teamProfitStatsMapper.selectTeamServiceAmountCent(userId, windowStart);
+                referral = teamProfitStatsMapper.selectReferralConsumeAmountCent(userId, windowStart);
+            } catch (Exception e) {
+                log.warn("星级看板业绩统计失败(userId={}),按 0 兜底:{}", userId, e.getMessage());
+            }
+        }
+        return new long[]{Math.max(0L, direct), Math.max(0L, team), Math.max(0L, referral)};
+    }
+
+    /** 滚动 12 个月团队直推有效新用户数(#15:团队树首单即算)。 */
+    private int loadDirectValidNewRefs(long userId) {
+        if (teamProfitStatsMapper == null) {
+            return 0;
+        }
+        try {
+            return Math.max(0, teamProfitStatsMapper.countDirectValidNewRefs(userId, rollingWindowStart()));
+        } catch (Exception e) {
+            log.warn("团队直推统计失败(userId={}),按 0 兜底:{}", userId, e.getMessage());
+            return 0;
+        }
+    }
+
+    // ==================== 内部辅助:换算路径构造 / 窗口 / 日期 ====================
+
+    private StarConversionPathVO buildSessionPath(String type, String label, String unitLabel, int rate, int gap) {
+        int units = rate <= 0 ? 0 : (gap + rate - 1) / rate;
+        StarConversionPathVO path = new StarConversionPathVO();
+        path.setType(type);
+        path.setLabel(label);
+        path.setRate(rate);
+        path.setRequiredUnits(units);
+        path.setUnitLabel(unitLabel);
+        path.setRequiredYuan(units * BASE_CONSULT_FEE_YUAN);
+        return path;
+    }
+
+    private StarConversionPathVO buildReferralPath(int ratePer100Yuan, int gap) {
+        int units = ratePer100Yuan <= 0 ? 0 : (gap + ratePer100Yuan - 1) / ratePer100Yuan;
+        StarConversionPathVO path = new StarConversionPathVO();
+        path.setType("REFERRAL");
+        path.setLabel("C 推荐消费");
+        path.setRate(ratePer100Yuan);
+        path.setRequiredUnits(units);
+        path.setUnitLabel("百元推荐消费");
+        path.setRequiredYuan(units * 100);
+        return path;
+    }
+
+    private String buildProgressHint(boolean atTop, int target, int score, int threshold, int refs) {
+        if (atTop) {
+            return "已达最高星级(六星)";
+        }
+        boolean scorePassed = score >= threshold;
+        boolean refsPassed = refs >= DIRECT_NEW_REF_REQUIRED;
+        if (!scorePassed && !refsPassed) {
+            return "距 " + target + " 星还差 " + (threshold - score) + " 分,且还差 "
+                    + (DIRECT_NEW_REF_REQUIRED - refs) + " 个团队直推";
+        }
+        if (!scorePassed) {
+            return "距 " + target + " 星还差 " + (threshold - score) + " 分";
+        }
+        if (!refsPassed) {
+            return "升级还差 " + (DIRECT_NEW_REF_REQUIRED - refs)
+                    + " 个团队直推,去邀请好友加入团队并完成首单";
+        }
+        return "双门槛已达标,可升级到 " + target + " 星";
+    }
+
+    private Date rollingWindowStart() {
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.MONTH, -TRAJECTORY_MONTHS);
+        return cal.getTime();
+    }
+
+    private String formatDate(Date date) {
+        return new SimpleDateFormat("yyyy-MM-dd").format(date);
+    }
+
+    private int clampStar(int star) {
+        return Math.min(Math.max(star, MIN_STAR), MAX_STAR);
+    }
+}

+ 53 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/StorageService.java

@@ -0,0 +1,53 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.FileRecord;
+import com.etotem.cfc.service.api.StorageServiceInterface;
+
+import org.springframework.web.multipart.MultipartFile;
+
+public interface StorageService extends StorageServiceInterface {
+
+    /**
+     * 存储文件并返回访问URL
+     */
+    String storeFile(MultipartFile file);
+
+    /**
+     * 存储文件并返回访问URL(带分类)
+     */
+    String storeFile(MultipartFile file, String category);
+
+    /**
+     * 存储字节数据并返回访问URL(TTS 等二进制生成物,无 MultipartFile)
+     *
+     * @param data        文件字节
+     * @param category    存储分类子目录
+     * @param filename    文件名(含扩展名,如 article_1.mp3)
+     * @param contentType MIME 类型(如 audio/mpeg)
+     * @return 访问URL
+     */
+    String storeBytes(byte[] data, String category, String filename, String contentType);
+
+    /**
+     * 存储文件并返回持久化后的素材库记录(file_record)。
+     *
+     * <p>用于后台「素材库」统一入库:文件落盘/上云的同时写入 file_record,
+     * 并按 contentType 推导 file_type(image/video/audio/document/other)。
+     * 若文件 hash 已存在(去重命中),返回已存在的记录实体,不会重复落盘。</p>
+     *
+     * @param file     上传文件
+     * @param category 素材分类(articles / general / ...),为空时按 general 处理
+     * @return 已持久化的文件记录
+     */
+    FileRecord storeFileRecord(MultipartFile file, String category);
+
+    /**
+     * 删除文件
+     */
+    void deleteFile(String fileUrl);
+
+    /**
+     * 获取文件完整路径
+     */
+    String getFilePath(String filename);
+}

+ 225 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/StreakService.java

@@ -0,0 +1,225 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.PointsLog;
+import com.etotem.cfc.entity.StreakMilestone;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.PointsLogMapper;
+import com.etotem.cfc.mapper.StreakMilestoneMapper;
+import com.etotem.cfc.service.api.StreakServiceInterface;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Service
+public class StreakService implements StreakServiceInterface {
+
+    @Resource
+    private StreakMilestoneMapper streakMilestoneMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private PointsLogMapper pointsLogMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    /**
+     * 检查并发放打卡里程碑奖励
+     * 完成任务时调用,检查是否达到新的里程碑并发放奖励
+     * 
+     * @param memberId 家庭成员ID
+     * @param currentStreakDays 当前连续天数
+     * @return 奖励积分(如果有)
+     */
+    public Integer checkAndAwardMilestone(Long memberId, int currentStreakDays) {
+        // 获取所有里程碑
+        List<StreakMilestone> milestones = streakMilestoneMapper.selectList(
+            new LambdaQueryWrapper<StreakMilestone>()
+                .orderByAsc(StreakMilestone::getDays)
+        );
+        
+        if (milestones.isEmpty()) {
+            return 0;
+        }
+        
+        // 获取家庭成员已获得的里程碑奖励记录
+        List<PointsLog> bonusLogs = pointsLogMapper.selectList(
+            new LambdaQueryWrapper<PointsLog>()
+                .eq(PointsLog::getFamilyMemberId, memberId)
+                .eq(PointsLog::getType, "bonus")
+                .like(PointsLog::getDescription, "打卡里程碑")
+        );
+        
+        Set<Integer> awardedDays = bonusLogs.stream()
+            .map(log -> extractMilestoneDays(log.getDescription()))
+            .filter(Objects::nonNull)
+            .collect(Collectors.toSet());
+        
+        // 检查是否达到新的里程碑
+        Integer rewardPoints = null;
+        for (StreakMilestone milestone : milestones) {
+            if (currentStreakDays >= milestone.getDays()
+                    && !awardedDays.contains(milestone.getDays())) {
+                // 发放奖励
+                rewardPoints = milestone.getRewardPoints();
+
+                // 记录积分
+                FamilyMember child = familyMemberMapper.selectById(memberId);
+                if (child != null) {
+                    recordBonusPoints(child, milestone);
+                }
+
+                // 发放行能量 - 达到里程碑
+                try {
+                    energyService.awardEnergy(memberId, "streak", milestone.getId().longValue(), rewardPoints,
+                            "打卡里程碑-" + milestone.getDays() + "天奖励", null);
+                } catch (Exception e) {
+                    log.warn("打卡里程碑能量发放失败: memberId={}, error={}", memberId, e.getMessage());
+                }
+
+                log.info("家庭成员{}达到连续打卡{}天,奖励{}积分", memberId, milestone.getDays(), rewardPoints);
+                break; // 每次只发放一个里程碑奖励
+            }
+        }
+
+        // 每日连续打卡能量奖励(即使没达到里程碑也奖励)
+        try {
+            energyService.awardEnergy(memberId, "streak", 0L, 5,
+                    "连续打卡第" + currentStreakDays + "天", null);
+        } catch (Exception e) {
+            log.warn("每日打卡能量发放失败: memberId={}, error={}", memberId, e.getMessage());
+        }
+
+        return rewardPoints != null ? rewardPoints : 0;
+    }
+    
+    /**
+     * 从描述中提取里程碑天数
+     */
+    private Integer extractMilestoneDays(String description) {
+        if (description == null) return null;
+        // 格式: "打卡里程碑-3天奖励"
+        try {
+            String numStr = description.replaceAll("[^0-9]", "");
+            return numStr.isEmpty() ? null : Integer.parseInt(numStr);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+    
+    /**
+     * 记录里程碑奖励积分
+     */
+    private void recordBonusPoints(FamilyMember child, StreakMilestone milestone) {
+        // 更新家庭成员积分
+        child.setTotalPoints(child.getTotalPoints() + milestone.getRewardPoints());
+        familyMemberMapper.updateById(child);
+        
+        // 记录积分流水
+        PointsLog log = new PointsLog();
+        log.setFamilyMemberId(child.getId());
+        log.setAmount(milestone.getRewardPoints());
+        log.setType("bonus");
+        log.setDescription("打卡里程碑-" + milestone.getDays() + "天奖励");
+        log.setCreatedAt(new Date());
+        pointsLogMapper.insert(log);
+    }
+    
+    /**
+     * 获取家庭成员的打卡进度信息
+     */
+    public Map<String, Object> getStreakProgress(Long memberId) {
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child == null) {
+            return null;
+        }
+        
+        Map<String, Object> progress = new HashMap<>();
+        progress.put("currentStreak", child.getStreakDays() != null ? child.getStreakDays() : 0);
+        progress.put("lastTaskDate", child.getLastTaskDate());
+        
+        // 获取所有里程碑
+        List<StreakMilestone> milestones = streakMilestoneMapper.selectList(
+            new LambdaQueryWrapper<StreakMilestone>()
+                .orderByAsc(StreakMilestone::getDays)
+        );
+        
+        // 获取已获得的奖励
+        List<PointsLog> bonusLogs = pointsLogMapper.selectList(
+            new LambdaQueryWrapper<PointsLog>()
+                .eq(PointsLog::getFamilyMemberId, memberId)
+                .eq(PointsLog::getType, "bonus")
+                .like(PointsLog::getDescription, "打卡里程碑")
+        );
+        
+        Set<Integer> awardedDays = bonusLogs.stream()
+            .map(log -> extractMilestoneDays(log.getDescription()))
+            .filter(Objects::nonNull)
+            .collect(Collectors.toSet());
+        
+        // 构建里程碑进度列表
+        List<Map<String, Object>> milestoneList = new ArrayList<>();
+        Integer nextMilestoneDays = null;
+        
+        for (StreakMilestone milestone : milestones) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("days", milestone.getDays());
+            item.put("rewardPoints", milestone.getRewardPoints());
+            item.put("achieved", awardedDays.contains(milestone.getDays()));
+            
+            if (!awardedDays.contains(milestone.getDays()) && nextMilestoneDays == null) {
+                nextMilestoneDays = milestone.getDays();
+            }
+            
+            milestoneList.add(item);
+        }
+        
+        progress.put("milestones", milestoneList);
+        progress.put("nextMilestone", nextMilestoneDays);
+        
+        if (nextMilestoneDays != null && child.getStreakDays() != null) {
+            progress.put("daysToNext", nextMilestoneDays - child.getStreakDays());
+        } else {
+            progress.put("daysToNext", 0);
+        }
+        
+        return progress;
+    }
+    
+    /**
+     * 重置连续打卡(当打卡中断时调用)
+     * 由每日定时任务调用
+     */
+    public void resetStreakIfNeeded() {
+        // 查询所有家庭成员
+        List<FamilyMember> children = familyMemberMapper.selectList(null);
+        
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -1);
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date yesterday = cal.getTime();
+        
+        for (FamilyMember child : children) {
+            if (child.getLastTaskDate() != null && child.getLastTaskDate().before(yesterday)) {
+                // 上次任务日期是昨天之前,重置连续天数
+                if (child.getStreakDays() > 0) {
+                    log.info("家庭成员{}打卡中断,连续天数从{}重置为0", child.getId(), child.getStreakDays());
+                    child.setStreakDays(0);
+                    child.setUpdatedAt(new Date());
+                    familyMemberMapper.updateById(child);
+                }
+            }
+        }
+    }
+}

+ 160 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/StreetService.java

@@ -0,0 +1,160 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.StreetServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Street;
+import com.etotem.cfc.mapper.StreetMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 街道服务 - 支持四级地址和区域回退匹配
+ */
+@Service
+public class StreetService implements StreetServiceInterface {
+
+    @Resource
+    private StreetMapper streetMapper;
+
+    /**
+     * 获取所有省份
+     */
+    public List<Street> getAllProvinces() {
+        return streetMapper.findAllProvinces();
+    }
+
+    /**
+     * 根据父级ID获取子级地址
+     */
+    public List<Street> getChildrenByParentId(Long parentId) {
+        return streetMapper.findByParentId(parentId);
+    }
+
+    /**
+     * 根据ID获取地址详情
+     */
+    public Street getById(Long id) {
+        return streetMapper.selectById(id);
+    }
+
+    /**
+     * 搜索地址
+     */
+    public List<Street> search(String keyword) {
+        return streetMapper.search(keyword);
+    }
+
+    /**
+     * 获取地址的完整路径(省市区街道)
+     */
+    public List<Street> getAddressPath(Long streetId) {
+        List<Street> path = new ArrayList<>();
+        Street current = streetMapper.selectById(streetId);
+        
+        while (current != null) {
+            path.add(0, current);
+            if (current.getParentId() != null) {
+                current = streetMapper.selectById(current.getParentId());
+            } else {
+                break;
+            }
+        }
+        
+        return path;
+    }
+
+    /**
+     * 区域回退匹配 - 根据街道ID匹配相同区域的家庭和成长规划师
+     * 匹配策略:
+     * 1. 优先匹配相同街道
+     * 2. 如果无匹配,回退到相同区县
+     * 3. 如果仍无匹配,回退到相同城市
+     * 
+     * @param streetId 街道ID
+     * @return 匹配结果:街道级、区县级、城市级的实体列表
+     */
+    public Map<String, Object> matchByStreetWithFallback(Long streetId) {
+        Map<String, Object> result = new HashMap<>();
+        
+        // 获取完整地址路径
+        List<Street> path = getAddressPath(streetId);
+        if (path.isEmpty()) {
+            return result;
+        }
+        
+        // 街道级别(level=4)
+        Street streetEntity = path.stream()
+                .filter(s -> s.getLevel() == 4)
+                .findFirst()
+                .orElse(null);
+        
+        // 区县级别(level=3)
+        Street districtEntity = path.stream()
+                .filter(s -> s.getLevel() == 3)
+                .findFirst()
+                .orElse(null);
+        
+        // 城市级别(level=2)
+        Street cityEntity = path.stream()
+                .filter(s -> s.getLevel() == 2)
+                .findFirst()
+                .orElse(null);
+        
+        // 匹配结果
+        result.put("streetMatch", streetEntity != null ? streetEntity.getId() : null);
+        result.put("districtMatch", districtEntity != null ? districtEntity.getId() : null);
+        result.put("cityMatch", cityEntity != null ? cityEntity.getId() : null);
+        
+        // 返回各级别的匹配范围(用于前端查询)
+        if (streetEntity != null) {
+            result.put("streetIds", Collections.singletonList(streetEntity.getId()));
+        }
+        
+        if (districtEntity != null) {
+            // 获取该区县下所有街道
+            List<Street> streets = streetMapper.findByParentId(districtEntity.getId());
+            result.put("districtStreetIds", streets.stream().map(Street::getId).collect(Collectors.toList()));
+        }
+        
+        if (cityEntity != null) {
+            // 获取该城市下所有区县
+            List<Street> districts = streetMapper.findByParentId(cityEntity.getId());
+            List<Long> districtIds = districts.stream().map(Street::getId).collect(Collectors.toList());
+            
+            // 获取所有区县下的街道
+            List<Long> cityStreetIds = new ArrayList<>();
+            for (Long districtId : districtIds) {
+                List<Street> streets = streetMapper.findByParentId(districtId);
+                cityStreetIds.addAll(streets.stream().map(Street::getId).collect(Collectors.toList()));
+            }
+            result.put("cityStreetIds", cityStreetIds);
+        }
+        
+        return result;
+    }
+
+    /**
+     * 按区域统计(省市区街道各级统计)
+     */
+    public Map<String, Object> getStatisticsByLevel(Integer level) {
+        Map<String, Object> result = new HashMap<>();
+        
+        List<Street> streets = streetMapper.findByLevel(level);
+        
+        for (Street street : streets) {
+            Map<String, Object> stats = new HashMap<>();
+            stats.put("id", street.getId());
+            stats.put("name", street.getFullName());
+            stats.put("level", street.getLevel());
+            
+            // 这里返回基础数据,具体家庭数和成长规划师数由Controller调用相应Service查询
+            result.put(street.getId().toString(), stats);
+        }
+        
+        return result;
+    }
+}

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

@@ -0,0 +1,43 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.SubscriptionBenefitLog;
+import com.etotem.cfc.mapper.SubscriptionBenefitLogMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Service
+public class SubscriptionBenefitLogService {
+
+    @Resource
+    private SubscriptionBenefitLogMapper subscriptionBenefitLogMapper;
+
+    /**
+     * 保存受益日志
+     */
+    public void save(SubscriptionBenefitLog log) {
+        subscriptionBenefitLogMapper.insert(log);
+    }
+
+    /**
+     * 根据订阅 ID 查询受益日志
+     */
+    public List<SubscriptionBenefitLog> getBySubscriptionId(Long subscriptionId) {
+        return subscriptionBenefitLogMapper.selectList(
+                new LambdaQueryWrapper<SubscriptionBenefitLog>()
+                        .eq(SubscriptionBenefitLog::getSubscriptionId, subscriptionId)
+        );
+    }
+
+    /**
+     * 根据 benefitCode 查询
+     */
+    public List<SubscriptionBenefitLog> getByBenefitCode(String benefitCode) {
+        return subscriptionBenefitLogMapper.selectList(
+                new LambdaQueryWrapper<SubscriptionBenefitLog>()
+                        .eq(SubscriptionBenefitLog::getBenefitCode, benefitCode)
+        );
+    }
+}

+ 189 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SupplyCustomerRelationService.java

@@ -0,0 +1,189 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.SupplyCustomerRelation;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.SupplyCustomerRelationMapper;
+import com.etotem.cfc.mapper.SupplySystemMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+public class SupplyCustomerRelationService {
+
+    @Resource
+    private SupplyCustomerRelationMapper supplyCustomerRelationMapper;
+
+    @Resource
+    private SupplySystemMapper supplySystemMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /**
+     * 查询某上级供应商下的客户列表
+     * 返回:{ list: [...], total: N } —— list 为分页后的客户(家庭ID、家庭名称、成员昵称、加入时间、归属来源),
+     *       total 为该体系/上级下的客户总数(团队数据「客户归属」的真实总数,T31)
+     */
+    public Map<String, Object> listCustomers(Long systemId, Long parentId, Integer page, Integer size) {
+        // parentId 为空时返回整个体系的客户列表(团队维度「团队客户」,T31);否则按指定上级过滤
+        List<SupplyCustomerRelation> relations = parentId == null
+                ? supplyCustomerRelationMapper.listBySystem(systemId)
+                : supplyCustomerRelationMapper.listByParent(systemId, parentId);
+
+        int total = relations.size();
+        // 分页处理
+        int fromIndex = (page - 1) * size;
+        int toIndex = Math.min(fromIndex + size, total);
+        if (fromIndex >= total) {
+            relations = Collections.emptyList();
+        } else {
+            relations = relations.subList(fromIndex, toIndex);
+        }
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (SupplyCustomerRelation relation : relations) {
+            Map<String, Object> customer = new HashMap<>();
+            customer.put("id", relation.getId());
+            customer.put("familyId", relation.getFamilyId());
+            customer.put("relationType", relation.getRelationType());
+            customer.put("source", relation.getSource());
+            customer.put("createdAt", relation.getCreatedAt());
+
+            // 查询家庭信息
+            FamilyMember parentMember = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                    .eq(FamilyMember::getFamilyId, relation.getFamilyId())
+                    .orderByAsc(FamilyMember::getGeneration)
+                    .last("LIMIT 1")
+            );
+            if (parentMember != null) {
+                customer.put("familyName", parentMember.getNickname());
+                customer.put("memberType", "login");
+                
+                // 查询家庭下能登录的用户数量
+                Long loginCount = familyMemberMapper.selectCount(
+                    new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getFamilyId, relation.getFamilyId())
+                        .isNotNull(FamilyMember::getUserId)
+                );
+                customer.put("loginMemberCount", loginCount);
+            } else {
+                customer.put("familyName", "未知家庭");
+                customer.put("memberType", "local");
+            }
+
+            // 查询下单用户信息(如果有)
+            if (relation.getChildUserId() != null) {
+                User buyer = userMapper.selectById(relation.getChildUserId());
+                if (buyer != null) {
+                    customer.put("buyerNickname", buyer.getNickname());
+                    customer.put("buyerPhone", buyer.getPhone());
+                }
+            }
+
+            result.add(customer);
+        }
+        Map<String, Object> wrapper = new HashMap<>();
+        wrapper.put("list", result);
+        wrapper.put("total", total);
+        return wrapper;
+    }
+
+    /**
+     * 绑定客户归属关系(人工绑定)
+     */
+    public boolean bindCustomer(Long systemId, Long parentId, Long familyId, Long childUserId, String source) {
+        // 检查是否已存在绑定关系
+        SupplyCustomerRelation existing = supplyCustomerRelationMapper.selectOne(
+            new LambdaQueryWrapper<SupplyCustomerRelation>()
+                .eq(SupplyCustomerRelation::getSystemId, systemId)
+                .eq(SupplyCustomerRelation::getFamilyId, familyId)
+        );
+        if (existing != null) {
+            // 更新现有记录
+            existing.setParentUserId(parentId);
+            existing.setChildUserId(childUserId);
+            existing.setSource(source != null ? source : "manual");
+            existing.setRelationType("family");
+            return supplyCustomerRelationMapper.updateById(existing) > 0;
+        }
+
+        // 创建新记录
+        SupplyCustomerRelation relation = new SupplyCustomerRelation();
+        relation.setSystemId(systemId);
+        relation.setParentUserId(parentId);
+        relation.setFamilyId(familyId);
+        relation.setChildUserId(childUserId);
+        relation.setRelationType("family");
+        relation.setSource(source != null ? source : "manual");
+        return supplyCustomerRelationMapper.insert(relation) > 0;
+    }
+
+    /**
+     * 系统自动绑定(下单时触发)
+     */
+    public void autoBindOnOrder(Long systemId, Long parentId, Long familyId, Long childUserId) {
+        bindCustomer(systemId, parentId, familyId, childUserId, "order");
+    }
+
+    /**
+     * 查询团队成员列表(含客户数量统计)
+     */
+    public List<Map<String, Object>> listTeamMembers(Long systemId) {
+        // 这里简化实现,实际可扩展
+        List<Map<String, Object>> result = new ArrayList<>();
+        
+        // 查询该体系下的所有上下级关系
+        List<SupplyCustomerRelation> allRelations = supplyCustomerRelationMapper.listBySystem(systemId);
+        
+        // 按上级用户分组统计客户数量
+        Map<Long, Long> customerCountByParent = allRelations.stream()
+            .collect(Collectors.groupingBy(
+                SupplyCustomerRelation::getParentUserId,
+                Collectors.counting()
+            ));
+        
+        // 查询所有上级用户的详细信息
+        Set<Long> parentUserIds = allRelations.stream()
+            .map(SupplyCustomerRelation::getParentUserId)
+            .collect(Collectors.toSet());
+        
+        for (Long parentId : parentUserIds) {
+            Map<String, Object> member = new HashMap<>();
+            member.put("userId", parentId);
+            member.put("customerCount", customerCountByParent.getOrDefault(parentId, 0L));
+            
+            User user = userMapper.selectById(parentId);
+            if (user != null) {
+                member.put("nickname", user.getNickname());
+                member.put("phone", user.getPhone());
+                member.put("avatar", user.getAvatar());
+            }
+            result.add(member);
+        }
+        return result;
+    }
+
+    /**
+     * 查询某个家庭的归属关系
+     */
+    public SupplyCustomerRelation getRelationByFamily(Long systemId, Long familyId) {
+        return supplyCustomerRelationMapper.selectOne(
+            new LambdaQueryWrapper<SupplyCustomerRelation>()
+                .eq(SupplyCustomerRelation::getSystemId, systemId)
+                .eq(SupplyCustomerRelation::getFamilyId, familyId)
+        );
+    }
+}

+ 302 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SupplyHierarchyService.java

@@ -0,0 +1,302 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.SupplyHierarchy;
+import com.etotem.cfc.entity.SupplyHierarchyChangeRequest;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.SupplyHierarchyChangeRequestMapper;
+import com.etotem.cfc.mapper.SupplyHierarchyMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class SupplyHierarchyService extends ServiceImpl<SupplyHierarchyMapper, SupplyHierarchy> {
+
+    @Resource
+    private SupplyHierarchyChangeRequestMapper changeRequestMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Transactional
+    public void setHierarchy(Long systemId, Long parentId, Long memberId) {
+        if (parentId.equals(memberId)) {
+            throw new IllegalArgumentException("不能将自己设为上级");
+        }
+
+        LambdaQueryWrapper<SupplyHierarchy> existingWrapper = new LambdaQueryWrapper<>();
+        existingWrapper.eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, memberId);
+        SortUtil.applySort(existingWrapper);
+        SupplyHierarchy existing = this.getOne(existingWrapper);
+
+        int level = 1;
+        SupplyHierarchy parentRelation = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, parentId));
+        if (parentRelation != null) {
+            level = parentRelation.getLevel() + 1;
+        }
+
+        if (existing != null) {
+            existing.setParentId(parentId);
+            existing.setLevel(level);
+            existing.setUpdatedAt(new Date());
+            this.updateById(existing);
+        } else {
+            SupplyHierarchy hierarchy = new SupplyHierarchy();
+            hierarchy.setSystemId(systemId);
+            hierarchy.setParentId(parentId);
+            hierarchy.setMemberId(memberId);
+            hierarchy.setLevel(level);
+            hierarchy.setStatus("active");
+            hierarchy.setCreatedAt(new Date());
+            hierarchy.setUpdatedAt(new Date());
+            this.save(hierarchy);
+        }
+    }
+
+    public boolean addRelation(Long systemId, Long parentId, Long memberId) {
+        if (parentId.equals(memberId)) {
+            return false;
+        }
+
+        LambdaQueryWrapper<SupplyHierarchy> checkWrapper = new LambdaQueryWrapper<>();
+        checkWrapper.eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getParentId, parentId)
+                .eq(SupplyHierarchy::getMemberId, memberId);
+        if (this.count(checkWrapper) > 0) {
+            return false;
+        }
+
+        int level = 1;
+        SupplyHierarchy parentRelation = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, parentId));
+        if (parentRelation != null) {
+            level = parentRelation.getLevel() + 1;
+        }
+
+        SupplyHierarchy hierarchy = new SupplyHierarchy();
+        hierarchy.setSystemId(systemId);
+        hierarchy.setParentId(parentId);
+        hierarchy.setMemberId(memberId);
+        hierarchy.setLevel(level);
+        hierarchy.setStatus("active");
+        hierarchy.setCreatedAt(new Date());
+        hierarchy.setUpdatedAt(new Date());
+        return this.save(hierarchy);
+    }
+
+    /**
+     * 确保成员在体系内存在一条 active 的上下级关系(T38 邀请加入专用)。
+     * 已存在(不论状态:active/inactive)则更新 parent/level 并恢复 active;不存在则新建。
+     * parentId=邀请人,level=父节点 level+1(父节点无 relation 时 level=1)。
+     * 与 addRelation 的区别:addRelation 仅新增且命中已存在关系即跳过(可能遗留 inactive 旧行),
+     * 本方法用于「被移除后重新加入」等场景,保证最终恰有一条 active 关系。
+     */
+    @Transactional
+    public SupplyHierarchy ensureRelation(Long systemId, Long parentId, Long memberId) {
+        if (parentId == null || parentId.equals(memberId)) {
+            throw new IllegalArgumentException("不能将自己设为上级");
+        }
+
+        SupplyHierarchy existing = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, memberId));
+
+        int level = 1;
+        SupplyHierarchy parentRelation = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, parentId)
+                .eq(SupplyHierarchy::getStatus, "active"));
+        if (parentRelation != null) {
+            level = parentRelation.getLevel() + 1;
+        }
+
+        if (existing != null) {
+            existing.setParentId(parentId);
+            existing.setLevel(level);
+            existing.setStatus("active");
+            existing.setUpdatedAt(new Date());
+            this.updateById(existing);
+            return existing;
+        }
+
+        SupplyHierarchy hierarchy = new SupplyHierarchy();
+        hierarchy.setSystemId(systemId);
+        hierarchy.setParentId(parentId);
+        hierarchy.setMemberId(memberId);
+        hierarchy.setLevel(level);
+        hierarchy.setStatus("active");
+        hierarchy.setCreatedAt(new Date());
+        hierarchy.setUpdatedAt(new Date());
+        this.save(hierarchy);
+        return hierarchy;
+    }
+
+    @Transactional
+    public boolean removeRelation(Long systemId, Long memberId) {
+        LambdaQueryWrapper<SupplyHierarchy> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, memberId);
+        SortUtil.applySort(wrapper);
+        SupplyHierarchy existing = this.getOne(wrapper);
+        if (existing != null) {
+            existing.setStatus("inactive");
+            existing.setUpdatedAt(new Date());
+            return this.updateById(existing);
+        }
+        return false;
+    }
+
+    public List<User> getDirectChildren(Long systemId, Long parentId) {
+        LambdaQueryWrapper<SupplyHierarchy> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getParentId, parentId)
+                .eq(SupplyHierarchy::getStatus, "active");
+        SortUtil.applySort(wrapper);
+        List<SupplyHierarchy> hierarchies = this.list(wrapper);
+        if (hierarchies.isEmpty()) {
+            return new ArrayList<>();
+        }
+        List<Long> memberIds = hierarchies.stream()
+                .map(SupplyHierarchy::getMemberId)
+                .collect(Collectors.toList());
+        return userMapper.selectBatchIds(memberIds);
+    }
+
+    public List<User> getAllChildren(Long systemId, Long parentId) {
+        List<User> result = new ArrayList<>();
+        List<Long> currentLevelIds = new ArrayList<>();
+        currentLevelIds.add(parentId);
+
+        while (!currentLevelIds.isEmpty()) {
+            LambdaQueryWrapper<SupplyHierarchy> wrapper = new LambdaQueryWrapper<>();
+            wrapper.eq(SupplyHierarchy::getSystemId, systemId)
+                    .in(SupplyHierarchy::getParentId, currentLevelIds)
+                    .eq(SupplyHierarchy::getStatus, "active");
+            SortUtil.applySort(wrapper);
+            List<SupplyHierarchy> hierarchies = this.list(wrapper);
+            if (hierarchies.isEmpty()) {
+                break;
+            }
+            List<Long> memberIds = hierarchies.stream()
+                    .map(SupplyHierarchy::getMemberId)
+                    .collect(Collectors.toList());
+            result.addAll(userMapper.selectBatchIds(memberIds));
+            currentLevelIds = memberIds;
+        }
+        return result;
+    }
+
+    public User getParent(Long systemId, Long memberId) {
+        SupplyHierarchy hierarchy = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, memberId)
+                .eq(SupplyHierarchy::getStatus, "active"));
+        if (hierarchy == null) {
+            return null;
+        }
+        return userMapper.selectById(hierarchy.getParentId());
+    }
+
+    public List<User> getParentChain(Long systemId, Long userId) {
+        List<User> chain = new ArrayList<>();
+        Long currentId = userId;
+
+        while (currentId != null) {
+            SupplyHierarchy hierarchy = this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                    .eq(SupplyHierarchy::getSystemId, systemId)
+                    .eq(SupplyHierarchy::getMemberId, currentId)
+                    .eq(SupplyHierarchy::getStatus, "active"));
+            if (hierarchy == null || hierarchy.getParentId() == null) {
+                break;
+            }
+            User parent = userMapper.selectById(hierarchy.getParentId());
+            if (parent == null) {
+                break;
+            }
+            chain.add(parent);
+            currentId = parent.getId();
+        }
+        return chain;
+    }
+
+    public SupplyHierarchy getRelation(Long systemId, Long userId) {
+        return this.getOne(new LambdaQueryWrapper<SupplyHierarchy>()
+                .eq(SupplyHierarchy::getSystemId, systemId)
+                .eq(SupplyHierarchy::getMemberId, userId)
+                .eq(SupplyHierarchy::getStatus, "active"));
+    }
+
+    public List<SupplyHierarchyChangeRequest> getChangeRequests(Long systemId, String status) {
+        LambdaQueryWrapper<SupplyHierarchyChangeRequest> wrapper = new LambdaQueryWrapper<>();
+        if (systemId != null) {
+            wrapper.eq(SupplyHierarchyChangeRequest::getSystemId, systemId);
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(SupplyHierarchyChangeRequest::getStatus, status);
+        }
+        wrapper.orderByDesc(SupplyHierarchyChangeRequest::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return changeRequestMapper.selectList(wrapper);
+    }
+
+    @Transactional
+    public void applyChange(Long systemId, Long applicantId, Long targetParentId, String reason) {
+        if (applicantId.equals(targetParentId)) {
+            throw new IllegalArgumentException("不能将自己设为上级");
+        }
+
+        LambdaQueryWrapper<SupplyHierarchyChangeRequest> pendingWrapper = new LambdaQueryWrapper<>();
+        pendingWrapper.eq(SupplyHierarchyChangeRequest::getSystemId, systemId)
+                .eq(SupplyHierarchyChangeRequest::getApplicantId, applicantId)
+                .eq(SupplyHierarchyChangeRequest::getStatus, "pending");
+        if (changeRequestMapper.selectCount(pendingWrapper) > 0) {
+            throw new IllegalArgumentException("存在待审核的申请");
+        }
+
+        SupplyHierarchyChangeRequest request = new SupplyHierarchyChangeRequest();
+        request.setSystemId(systemId);
+        request.setApplicantId(applicantId);
+        request.setTargetParentId(targetParentId);
+        request.setReason(reason);
+        request.setStatus("pending");
+        request.setCreatedAt(new Date());
+        changeRequestMapper.insert(request);
+    }
+
+    @Transactional
+    public void reviewChange(Long requestId, String status, String rejectReason, Long reviewedBy) {
+        SupplyHierarchyChangeRequest request = changeRequestMapper.selectById(requestId);
+        if (request == null) {
+            throw new IllegalArgumentException("申请不存在");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            throw new IllegalArgumentException("申请已处理");
+        }
+
+        request.setStatus(status);
+        request.setReviewedAt(new Date());
+        request.setReviewedBy(reviewedBy);
+        if ("rejected".equals(status)) {
+            request.setRejectReason(rejectReason);
+        }
+        changeRequestMapper.updateById(request);
+
+        if ("approved".equals(status)) {
+            removeRelation(request.getSystemId(), request.getApplicantId());
+            setHierarchy(request.getSystemId(), request.getTargetParentId(), request.getApplicantId());
+        }
+    }
+}

+ 320 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SupplySettlementService.java

@@ -0,0 +1,320 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.SupplySettlement;
+import com.etotem.cfc.entity.SupplySettlementDetail;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.SupplySettlementDetailMapper;
+import com.etotem.cfc.mapper.SupplySettlementMapper;
+import com.etotem.cfc.mapper.SupplySystemMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.util.ParamUtils;
+
+@Service
+public class SupplySettlementService extends ServiceImpl<SupplySettlementMapper, SupplySettlement> {
+
+    private static final Logger log = LoggerFactory.getLogger(SupplySettlementService.class);
+
+    @Resource
+    private SupplySettlementDetailMapper supplySettlementDetailMapper;
+
+    @Resource
+    private SupplySystemMapper supplySystemMapper;
+
+    @Resource
+    private ProductOrderMapper productOrderMapper;
+
+    /**
+     * 分页查询结算记录列表
+     */
+    public Result<Map<String, Object>> list(Map<String, Object> params) {
+        return list(params, null);
+    }
+
+    /**
+     * 分页查询结算记录列表
+     * B-5 行级隔离:supplierUserId 非空时仅返回该供应商管理的体系下的结算单
+     */
+    public Result<Map<String, Object>> list(Map<String, Object> params, Long supplierUserId) {
+        Integer pageNum = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
+        Integer pageSize = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 20;
+        Long systemId = params.get("systemId") != null ? ParamUtils.getLong(params.get("systemId")) : null;
+        String status = (String) params.get("status");
+
+        // 供应商视角:先解析自己管理的体系 ID 集合
+        List<Long> ownSystemIds = null;
+        if (supplierUserId != null) {
+            List<SupplySystem> ownSystems = supplySystemMapper.selectList(
+                    new LambdaQueryWrapper<SupplySystem>().eq(SupplySystem::getAdminId, supplierUserId));
+            ownSystemIds = ownSystems.stream().map(SupplySystem::getId).collect(Collectors.toList());
+            if (ownSystemIds.isEmpty()) {
+                Map<String, Object> empty = new HashMap<>();
+                empty.put("records", new java.util.ArrayList<>());
+                empty.put("total", 0L);
+                empty.put("page", pageNum);
+                empty.put("size", pageSize);
+                return Result.success(empty);
+            }
+        }
+
+        Page<SupplySettlement> pageParam = new Page<>(pageNum, pageSize);
+        LambdaQueryWrapper<SupplySettlement> wrapper = new LambdaQueryWrapper<SupplySettlement>()
+                .orderByDesc(SupplySettlement::getCreatedAt);
+
+        if (systemId != null) {
+            wrapper.eq(SupplySettlement::getSystemId, systemId);
+        }
+        if (ownSystemIds != null) {
+            wrapper.in(SupplySettlement::getSystemId, ownSystemIds);
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(SupplySettlement::getStatus, status);
+        }
+
+        SortUtil.applySort(wrapper);
+        Page<SupplySettlement> result = this.page(pageParam, wrapper);
+        Map<String, Object> data = new HashMap<>();
+        data.put("records", result.getRecords());
+        data.put("total", result.getTotal());
+        data.put("page", result.getCurrent());
+        data.put("size", result.getSize());
+        return Result.success(data);
+    }
+
+    /**
+     * 按 ID 查询结算详情
+     */
+    public Result<SupplySettlement> detail(Long id) {
+        return detail(id, null);
+    }
+
+    /**
+     * 按 ID 查询结算详情
+     * B-5 行级隔离:supplierUserId 非空时校验结算单归属该供应商管理的体系
+     */
+    public Result<SupplySettlement> detail(Long id, Long supplierUserId) {
+        SupplySettlement settlement = this.getById(id);
+        if (settlement == null) {
+            return Result.error("结算记录不存在");
+        }
+        if (supplierUserId != null && !isOwnSettlement(settlement, supplierUserId)) {
+            return Result.error("无权查看该结算记录");
+        }
+        return Result.success(settlement);
+    }
+
+    /**
+     * 查询结算明细列表
+     */
+    public Result<List<SupplySettlementDetail>> detailItems(Long settlementId) {
+        return detailItems(settlementId, null);
+    }
+
+    /**
+     * 查询结算明细列表
+     * B-5 行级隔离:supplierUserId 非空时校验结算单归属
+     */
+    public Result<List<SupplySettlementDetail>> detailItems(Long settlementId, Long supplierUserId) {
+        if (supplierUserId != null) {
+            SupplySettlement settlement = this.getById(settlementId);
+            if (settlement == null) {
+                return Result.error("结算记录不存在");
+            }
+            if (!isOwnSettlement(settlement, supplierUserId)) {
+                return Result.error("无权查看该结算记录");
+            }
+        }
+        LambdaQueryWrapper<SupplySettlementDetail> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplySettlementDetail::getSettlementId, settlementId);
+        SortUtil.applySort(wrapper);
+        List<SupplySettlementDetail> items = supplySettlementDetailMapper.selectList(wrapper);
+        return Result.success(items);
+    }
+
+    /**
+     * 校验结算单是否属于该供应商管理的体系
+     */
+    private boolean isOwnSettlement(SupplySettlement settlement, Long supplierUserId) {
+        if (settlement.getSystemId() == null) {
+            return false;
+        }
+        SupplySystem system = supplySystemMapper.selectById(settlement.getSystemId());
+        return system != null && supplierUserId.equals(system.getAdminId());
+    }
+
+    /**
+     * 校验是否为供应商管理体系(用于生成/确认结算单的操作权限校验)
+     */
+    public boolean isOwnSystem(Long systemId, Long supplierUserId) {
+        if (systemId == null || supplierUserId == null) {
+            return false;
+        }
+        SupplySystem system = supplySystemMapper.selectById(systemId);
+        return system != null && supplierUserId.equals(system.getAdminId());
+    }
+
+    /**
+     * 手动生成结算单
+     *
+     * 汇总指定周期内该体系下所有已完成的订单,按公式计算平台留利和供应商实付:
+     *   platform_profit = total_sales × platform_profit_rate / 100
+     *   supplier_payout = total_sales - platform_profit
+     */
+    @Transactional
+    public Result<SupplySettlement> createSettlement(Map<String, Object> params) {
+        Long systemId = params.get("systemId") != null ? ParamUtils.getLong(params.get("systemId")) : null;
+        String periodStartStr = (String) params.get("periodStart");
+        String periodEndStr = (String) params.get("periodEnd");
+
+        if (systemId == null) {
+            return Result.error("systemId不能为空");
+        }
+        if (periodStartStr == null || periodEndStr == null) {
+            return Result.error("结算周期不能为空");
+        }
+
+        SupplySystem system = supplySystemMapper.selectById(systemId);
+        if (system == null) {
+            return Result.error("供应商体系不存在");
+        }
+
+        Date periodStart;
+        Date periodEnd;
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+            periodStart = sdf.parse(periodStartStr);
+            periodEnd = sdf.parse(periodEndStr);
+        } catch (Exception e) {
+            return Result.error("日期格式错误,应为 yyyy-MM-dd");
+        }
+
+        // 查询该体系下已完成且未被结算的订单
+        LambdaQueryWrapper<ProductOrder> orderWrapper = new LambdaQueryWrapper<>();
+        orderWrapper.eq(ProductOrder::getSupplySystemId, systemId)
+                .eq(ProductOrder::getStatus, "completed")
+                .ge(ProductOrder::getCreatedAt, periodStart)
+                .le(ProductOrder::getCreatedAt, periodEnd);
+
+        SortUtil.applySort(orderWrapper);
+        List<ProductOrder> orders = productOrderMapper.selectList(orderWrapper);
+        if (orders.isEmpty()) {
+            return Result.error("该周期内没有已完成的订单");
+        }
+
+        // 排除已存在于结算明细中的订单
+        List<Long> orderIds = orders.stream().map(ProductOrder::getId).collect(Collectors.toList());
+        LambdaQueryWrapper<SupplySettlementDetail> existingWrapper = new LambdaQueryWrapper<>();
+        existingWrapper.in(SupplySettlementDetail::getOrderId, orderIds);
+        SortUtil.applySort(existingWrapper);
+        List<SupplySettlementDetail> existingDetails = supplySettlementDetailMapper.selectList(existingWrapper);
+        Set<Long> existingOrderIds = existingDetails.stream()
+                .map(SupplySettlementDetail::getOrderId)
+                .collect(Collectors.toSet());
+
+        List<ProductOrder> settleableOrders = orders.stream()
+                .filter(o -> !existingOrderIds.contains(o.getId()))
+                .collect(Collectors.toList());
+
+        if (settleableOrders.isEmpty()) {
+            return Result.error("该周期内的订单均已结算");
+        }
+
+        // 计算销售总额(单位:分)
+        int totalSales = settleableOrders.stream()
+                .mapToInt(o -> o.getTotalAmount() != null ? o.getTotalAmount() : 0)
+                .sum();
+
+        // 获取平台留利比例
+        BigDecimal rate = system.getPlatformProfitRate() != null
+                ? system.getPlatformProfitRate()
+                : BigDecimal.ZERO;
+
+        // 计算公式(金额单位:分)
+        // platform_profit = total_sales × platform_profit_rate / 100
+        BigDecimal totalSalesBD = BigDecimal.valueOf(totalSales);
+        BigDecimal platformProfitBD = totalSalesBD.multiply(rate)
+                .divide(BigDecimal.valueOf(100), 0, BigDecimal.ROUND_HALF_UP);
+        BigDecimal supplierPayoutBD = totalSalesBD.subtract(platformProfitBD);
+
+        int platformProfit = platformProfitBD.intValue();
+        int supplierPayout = supplierPayoutBD.intValue();
+
+        // 创建结算记录
+        SupplySettlement settlement = new SupplySettlement();
+        settlement.setSystemId(systemId);
+        settlement.setPeriodStart(periodStart);
+        settlement.setPeriodEnd(periodEnd);
+        settlement.setTotalSales(totalSales);
+        settlement.setPlatformProfit(platformProfit);
+        settlement.setSupplierPayout(supplierPayout);
+        settlement.setStatus("pending");
+        settlement.setCreatedAt(new Date());
+        this.save(settlement);
+
+        // 创建结算明细
+        for (ProductOrder order : settleableOrders) {
+            int orderAmount = order.getTotalAmount() != null ? order.getTotalAmount() : 0;
+            BigDecimal orderAmountBD = BigDecimal.valueOf(orderAmount);
+            int orderPlatformFee = orderAmountBD.multiply(rate)
+                    .divide(BigDecimal.valueOf(100), 0, BigDecimal.ROUND_HALF_UP)
+                    .intValue();
+            int orderPayout = orderAmount - orderPlatformFee;
+
+            SupplySettlementDetail detail = new SupplySettlementDetail();
+            detail.setSettlementId(settlement.getId());
+            detail.setOrderId(order.getId());
+            detail.setOrderNo(order.getOrderNo());
+            detail.setProductName(order.getProductName());
+            detail.setAmount(orderAmount);
+            detail.setPlatformFee(orderPlatformFee);
+            detail.setSupplierId(order.getSupplierId());
+            detail.setPayout(orderPayout);
+            detail.setCreatedAt(new Date());
+            supplySettlementDetailMapper.insert(detail);
+        }
+
+        log.info("已创建结算单 ID={}, systemId={}, 周期={}~{}, 总额={}, 留利={}, 实付={}",
+                settlement.getId(), systemId, periodStartStr, periodEndStr,
+                totalSales, platformProfit, supplierPayout);
+
+        return Result.success(settlement);
+    }
+
+    /**
+     * 确认结算(pending → settled)
+     */
+    @Transactional
+    public Result<Void> confirm(Long id) {
+        SupplySettlement settlement = this.getById(id);
+        if (settlement == null) {
+            return Result.error("结算记录不存在");
+        }
+        if (!"pending".equals(settlement.getStatus())) {
+            return Result.error("只有待结算状态的记录才能确认");
+        }
+        settlement.setStatus("settled");
+        settlement.setSettledAt(new Date());
+        this.updateById(settlement);
+        log.info("已确认结算单 ID={}", id);
+        return Result.success(null);
+    }
+}

+ 362 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SupplySystemService.java

@@ -0,0 +1,362 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.SupplySystem;
+import com.etotem.cfc.entity.SupplySystemMember;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.SupplySystemMapper;
+import com.etotem.cfc.mapper.SupplySystemMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class SupplySystemService extends ServiceImpl<SupplySystemMapper, SupplySystem> {
+
+    @Resource
+    private SupplySystemMemberMapper supplySystemMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private SupplyHierarchyService supplyHierarchyService;
+
+    public Page<SupplySystem> list(String keyword, String status, int page, int size) {
+        Page<SupplySystem> pageParam = new Page<>(page, size);
+        LambdaQueryWrapper<SupplySystem> wrapper = new LambdaQueryWrapper<>();
+        if (keyword != null && !keyword.isEmpty()) {
+            wrapper.like(SupplySystem::getName, keyword);
+        }
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(SupplySystem::getStatus, status);
+        }
+        wrapper.orderByDesc(SupplySystem::getId);
+        SortUtil.applySort(wrapper);
+        return this.page(pageParam, wrapper);
+    }
+
+    public SupplySystem detail(Long id) {
+        return this.getById(id);
+    }
+
+    @Transactional
+    public SupplySystem create(SupplySystem system) {
+        if (system.getAdminId() == null) {
+            throw new IllegalArgumentException("adminId不能为空");
+        }
+        system.setStatus("active");
+        system.setCreatedAt(new Date());
+        system.setUpdatedAt(new Date());
+        this.save(system);
+
+        // 创建者自动成为 admin 成员
+        SupplySystemMember member = new SupplySystemMember();
+        member.setSystemId(system.getId());
+        member.setUserId(system.getAdminId());
+        member.setRole("admin");
+        member.setStatus("active");
+        member.setJoinedAt(new Date());
+        supplySystemMemberMapper.insert(member);
+
+        return system;
+    }
+
+    public boolean update(SupplySystem system) {
+        system.setUpdatedAt(new Date());
+        return this.updateById(system);
+    }
+
+    public boolean toggleStatus(Long id) {
+        SupplySystem system = this.getById(id);
+        if (system == null) return false;
+        system.setStatus("active".equals(system.getStatus()) ? "disabled" : "active");
+        system.setUpdatedAt(new Date());
+        return this.updateById(system);
+    }
+
+    public List<SupplySystem> listAll() {
+        LambdaQueryWrapper<SupplySystem> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplySystem::getStatus, "active");
+        SortUtil.applySort(wrapper);
+        return this.list(wrapper);
+    }
+
+    public SupplySystem getByAdminId(Long adminId) {
+        LambdaQueryWrapper<SupplySystem> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplySystem::getAdminId, adminId)
+               .eq(SupplySystem::getStatus, "active")
+               .last("LIMIT 1");
+        SortUtil.applySort(wrapper);
+        return this.getOne(wrapper);
+    }
+
+    /**
+     * 当前用户所属的供应体系列表(作为管理员或 active 成员,支持一人多团队)
+     * T31:小程序「我的团队」多团队管理 —— 团队切换器数据源
+     */
+    public List<SupplySystem> getMyTeams(Long userId) {
+        if (userId == null) return new java.util.ArrayList<>();
+
+        // 1. 用户作为 active 成员/管理员的体系 ID(创建体系时会自动插入 admin 成员记录)
+        java.util.List<Long> systemIds = new java.util.ArrayList<>();
+        java.util.List<SupplySystemMember> members = supplySystemMemberMapper.selectList(
+            new LambdaQueryWrapper<SupplySystemMember>()
+                .eq(SupplySystemMember::getUserId, userId)
+                .eq(SupplySystemMember::getStatus, "active"));
+        for (SupplySystemMember m : members) {
+            if (m.getSystemId() != null && !systemIds.contains(m.getSystemId())) {
+                systemIds.add(m.getSystemId());
+            }
+        }
+
+        // 2. 用户作为体系 admin(防御:部分旧数据可能无 member 记录)
+        java.util.List<SupplySystem> adminSystems = this.list(
+            new LambdaQueryWrapper<SupplySystem>()
+                .eq(SupplySystem::getAdminId, userId)
+                .eq(SupplySystem::getStatus, "active"));
+        for (SupplySystem s : adminSystems) {
+            if (!systemIds.contains(s.getId())) systemIds.add(s.getId());
+        }
+
+        if (systemIds.isEmpty()) return new java.util.ArrayList<>();
+
+        return this.list(new LambdaQueryWrapper<SupplySystem>()
+            .in(SupplySystem::getId, systemIds)
+            .eq(SupplySystem::getStatus, "active")
+            .orderByDesc(SupplySystem::getId));
+    }
+
+    /**
+     * 校验当前用户是否为体系的 admin 或 active 成员(越权防护,T31)
+     */
+    public boolean isMemberOrAdmin(Long systemId, Long userId) {
+        if (systemId == null || userId == null) return false;
+        SupplySystem system = this.getById(systemId);
+        if (system == null) return false;
+        if (system.getAdminId() != null && system.getAdminId().equals(userId)) return true;
+        Long count = supplySystemMemberMapper.selectCount(
+            new LambdaQueryWrapper<SupplySystemMember>()
+                .eq(SupplySystemMember::getSystemId, systemId)
+                .eq(SupplySystemMember::getUserId, userId)
+                .eq(SupplySystemMember::getStatus, "active"));
+        return count != null && count > 0;
+    }
+
+    /**
+     * 按 systemId 取体系并校验当前用户访问权限;无权限或不存在返回 null(T31)
+     */
+    public SupplySystem getBySystemIdForUser(Long systemId, Long userId) {
+        if (systemId == null || userId == null) return null;
+        if (!isMemberOrAdmin(systemId, userId)) return null;
+        return this.getById(systemId);
+    }
+
+    // ========== Member Management ==========
+
+    public List<SupplySystemMember> memberList(Long systemId) {
+        LambdaQueryWrapper<SupplySystemMember> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplySystemMember::getSystemId, systemId)
+               .eq(SupplySystemMember::getStatus, "active");
+        SortUtil.applySort(wrapper);
+        return supplySystemMemberMapper.selectList(wrapper);
+    }
+
+    @Transactional
+    public SupplySystemMember addMember(Long systemId, Long userId) {
+        // Check if already exists
+        LambdaQueryWrapper<SupplySystemMember> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(SupplySystemMember::getSystemId, systemId)
+               .eq(SupplySystemMember::getUserId, userId);
+        SortUtil.applySort(wrapper);
+        SupplySystemMember existing = supplySystemMemberMapper.selectOne(wrapper);
+        if (existing != null) return existing;
+
+        SupplySystemMember member = new SupplySystemMember();
+        member.setSystemId(systemId);
+        member.setUserId(userId);
+        member.setRole("member");
+        member.setStatus("active");
+        member.setJoinedAt(new Date());
+        supplySystemMemberMapper.insert(member);
+        return member;
+    }
+
+    @Transactional
+    public boolean removeMember(Long memberId) {
+        SupplySystemMember member = supplySystemMemberMapper.selectById(memberId);
+        if (member == null) return false;
+        member.setStatus("inactive");
+        member.setJoinedAt(member.getJoinedAt());
+        return supplySystemMemberMapper.updateById(member) > 0;
+    }
+
+    @Transactional
+    public boolean changeRole(Long memberId, String role) {
+        SupplySystemMember member = supplySystemMemberMapper.selectById(memberId);
+        if (member == null) return false;
+        member.setRole(role);
+        return supplySystemMemberMapper.updateById(member) > 0;
+    }
+
+    // ========== 邀请功能(T38:在我的团队邀请其他用户加入)==========
+
+    /**
+     * 生成/获取当前成员的个人专属邀请码(T38)。
+     * refresh=false 且已有码 → 幂等复用;refresh=true(或空码)→ 重新生成并使旧码失效。
+     *
+     * @throws IllegalArgumentException 团队不存在/已停用/当前用户不是该团队成员
+     */
+    @Transactional
+    public String generateInviteCode(Long systemId, Long userId, boolean refresh) {
+        if (systemId == null || userId == null) {
+            throw new IllegalArgumentException("参数不完整");
+        }
+        SupplySystem system = this.getById(systemId);
+        if (system == null) {
+            throw new IllegalArgumentException("团队不存在");
+        }
+        if (!"active".equals(system.getStatus())) {
+            throw new IllegalArgumentException("团队已停用,无法生成邀请码");
+        }
+        SupplySystemMember member = getMemberBySystemAndUser(systemId, userId);
+        if (member == null) {
+            throw new IllegalArgumentException("您不是该团队成员,无法生成邀请码");
+        }
+        if (!refresh && member.getInviteCode() != null && !member.getInviteCode().isEmpty()) {
+            return member.getInviteCode();
+        }
+        String code = generateUniqueInviteCode();
+        member.setInviteCode(code);
+        supplySystemMemberMapper.updateById(member);
+        return code;
+    }
+
+    /**
+     * 邀请码信息(确认页展示:团队名/邀请人昵称头像/成员数,不泄露其他隐私)(T38)。
+     * 不校验当前用户身份——凭码即可查看(确认页在加入前使用)。
+     */
+    public Map<String, Object> getInviteInfo(String inviteCode) {
+        SupplySystemMember inviter = getMemberByInviteCode(inviteCode);
+        if (inviter == null || inviter.getSystemId() == null) {
+            throw new IllegalArgumentException("邀请码不存在或已失效");
+        }
+        Long systemId = inviter.getSystemId();
+        SupplySystem system = this.getById(systemId);
+        if (system == null) {
+            throw new IllegalArgumentException("邀请码不存在或已失效");
+        }
+        Map<String, Object> info = new HashMap<>();
+        info.put("systemId", systemId);
+        info.put("teamName", system.getName());
+        info.put("inviterId", inviter.getUserId());
+        User inviterUser = userMapper.selectById(inviter.getUserId());
+        info.put("inviterNickname", inviterUser != null ? inviterUser.getNickname() : "微信用户");
+        info.put("inviterAvatar", inviterUser != null ? inviterUser.getAvatar() : null);
+        Long memberCount = supplySystemMemberMapper.selectCount(new LambdaQueryWrapper<SupplySystemMember>()
+                .eq(SupplySystemMember::getSystemId, systemId)
+                .eq(SupplySystemMember::getStatus, "active"));
+        info.put("memberCount", memberCount != null ? memberCount : 0L);
+        info.put("active", "active".equals(system.getStatus()));
+        return info;
+    }
+
+    /**
+     * 凭邀请码加入团队(T38):
+     * 校验码有效 + 用户未 active 加入过该体系 → 成为 role=member/status=active 成员
+     * → supply_hierarchy 挂 parentId=邀请人 / level=父级level+1(邀请人=其上级,
+     * 成员子树整体结算给该成员,与 §0.5 负责人结算口径一致)。
+     * 边界:同一 (systemId,userId) 仅 active 一次(active 拒绝重复加入,inactive 可重新加入)。
+     *
+     * @return 加入后的团队/邀请人信息(同 getInviteInfo)
+     */
+    @Transactional
+    public Map<String, Object> joinByInviteCode(String inviteCode, Long userId) {
+        if (userId == null) {
+            throw new IllegalArgumentException("未登录");
+        }
+        SupplySystemMember inviter = getMemberByInviteCode(inviteCode);
+        if (inviter == null || inviter.getSystemId() == null) {
+            throw new IllegalArgumentException("邀请码不存在或已失效");
+        }
+        Long systemId = inviter.getSystemId();
+        SupplySystem system = this.getById(systemId);
+        if (system == null) {
+            throw new IllegalArgumentException("邀请码不存在或已失效");
+        }
+        if (!"active".equals(system.getStatus())) {
+            throw new IllegalArgumentException("团队已停用,暂无法加入");
+        }
+        // 同一 (systemId,userId) 仅加入一次;active → 拒绝,inactive(被移除)→ 重新激活
+        SupplySystemMember existing = getMemberBySystemAndUser(systemId, userId);
+        if (existing != null && "active".equals(existing.getStatus())) {
+            throw new IllegalArgumentException("您已在该团队中,无需重复加入");
+        }
+        SupplySystemMember member;
+        if (existing != null) {
+            existing.setRole("member");
+            existing.setStatus("active");
+            existing.setJoinedAt(new Date());
+            supplySystemMemberMapper.updateById(existing);
+            member = existing;
+        } else {
+            member = new SupplySystemMember();
+            member.setSystemId(systemId);
+            member.setUserId(userId);
+            member.setRole("member");
+            member.setStatus("active");
+            member.setJoinedAt(new Date());
+            supplySystemMemberMapper.insert(member);
+        }
+        // 挂上级:parentId=邀请人,level=父level+1(已存在 inactive 关系则恢复 active 并更新,避免重复行)
+        supplyHierarchyService.ensureRelation(systemId, inviter.getUserId(), userId);
+        return getInviteInfo(inviteCode);
+    }
+
+    private SupplySystemMember getMemberBySystemAndUser(Long systemId, Long userId) {
+        return supplySystemMemberMapper.selectOne(new LambdaQueryWrapper<SupplySystemMember>()
+                .eq(SupplySystemMember::getSystemId, systemId)
+                .eq(SupplySystemMember::getUserId, userId));
+    }
+
+    private SupplySystemMember getMemberByInviteCode(String inviteCode) {
+        if (inviteCode == null || inviteCode.trim().isEmpty()) {
+            return null;
+        }
+        return supplySystemMemberMapper.selectOne(new LambdaQueryWrapper<SupplySystemMember>()
+                .eq(SupplySystemMember::getInviteCode, inviteCode.trim()));
+    }
+
+    /**
+     * 生成全体系唯一邀请码:字符集去除易混淆字符(I/O/0/1),
+     * 幂等/重生成均校验唯一性(配合迁移444的 uk_supply_member_invite_code 唯一索引兜底)。
+     */
+    private String generateUniqueInviteCode() {
+        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
+        Random random = new Random();
+        for (int attempt = 0; attempt < 50; attempt++) {
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < 8; i++) {
+                sb.append(chars.charAt(random.nextInt(chars.length())));
+            }
+            String code = sb.toString();
+            Long count = supplySystemMemberMapper.selectCount(new LambdaQueryWrapper<SupplySystemMember>()
+                    .eq(SupplySystemMember::getInviteCode, code));
+            if (count == null || count == 0) {
+                return code;
+            }
+        }
+        // 极端碰撞兜底(唯一索引重试仍失败时),避免死循环
+        return "T" + System.currentTimeMillis();
+    }
+}

+ 51 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SurveyService.java

@@ -0,0 +1,51 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.SurveyTemplate;
+import com.etotem.cfc.entity.SurveyRecord;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+public interface SurveyService {
+    SurveyTemplate saveTemplate(SurveyTemplate template, Long adminId);
+    List<SurveyTemplate> listTemplates(Integer enabled);
+    void deleteTemplate(Long id, Long adminId);
+    List<SurveyTemplate> getActiveTemplates();
+    List<SurveyTemplate> getActiveTemplatesByDimension(String dimension);
+    Object getSurveyStatus(Long userId, Long memberId);
+    SurveyRecord submitSurvey(Long userId, Long memberId, Long templateId, String answersJson, Date periodStart, Date periodEnd);
+
+    /**
+     * 提交调研答案(B2 扩展:携带 riskHits 命中标记,E4 弱提示不阻断)。
+     *
+     * <p>riskHits 为确认问卷中 Q11/Q12/Q13 高风险题的命中标记(如
+     * [{@code questionId:"Q11d", code:"selfHarmIdea", value:"有", riskLevel:"high"}]),
+     * 会并入 answersJson 的 {@code _attributionRiskHits} 键落库,供 B1 归因红线检测。
+     *
+     * @return 默认实现不存储 riskHits(向后兼容);{@code SurveyServiceImpl} 覆盖为合并落库
+     */
+    default SurveyRecord submitSurvey(Long userId, Long memberId, Long templateId, String answersJson,
+                                      Date periodStart, Date periodEnd, List<Map<String, Object>> riskHits) {
+        return submitSurvey(userId, memberId, templateId, answersJson, periodStart, periodEnd);
+    }
+
+    /**
+     * 提交调研答案(HL-01:source 区分定期调研/健康阅卷)。
+     *
+     * <p>source 为 {@code health_review} 时仅写 survey_records(复用健康问卷内容),
+     * 不校验模板/周期;其余值按定期调研处理(向后兼容,缺省 {@code periodic})。
+     */
+    default SurveyRecord submitSurvey(Long userId, Long memberId, Long templateId, String answersJson,
+                                      Date periodStart, Date periodEnd, List<Map<String, Object>> riskHits, String source) {
+        return submitSurvey(userId, memberId, templateId, answersJson, periodStart, periodEnd, riskHits);
+    }
+
+    /**
+     * 查询最后一条健康阅卷记录(source=health_review,按提交时间倒序取最近一条)。
+     *
+     * @return 最近一条健康阅卷;无记录返回 null
+     */
+    SurveyRecord getLastHealthReview(Long userId, Long memberId);
+    List<SurveyRecord> getSurveyHistory(Long userId, Long memberId);
+    String aiGenerateQuestions(String dimension, String topic);
+}

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

@@ -0,0 +1,100 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.SysConfigDTO;
+import com.etotem.cfc.entity.SysConfig;
+import com.etotem.cfc.mapper.SysConfigMapper;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Service
+public class SysConfigService {
+
+    @Resource
+    private SysConfigMapper configMapper;
+
+    /**
+     * 获取所有配置(key-value 形式)
+     */
+    @Cacheable(value = "sysConfig", key = "\"allMap\"")
+    public Result<Map<String, String>> getAllAsMap() {
+        List<SysConfig> list = configMapper.selectList(null);
+        Map<String, String> map = new HashMap<>();
+        for (SysConfig c : list) {
+            map.put(c.getConfigKey(), c.getConfigValue());
+        }
+        return Result.success(map);
+    }
+
+    /**
+     * 获取所有配置(详细列表)
+     */
+    public Result<List<SysConfigDTO>> listAll() {
+        List<SysConfig> list = configMapper.selectList(
+            new LambdaQueryWrapper<SysConfig>().orderByAsc(SysConfig::getConfigKey));
+        return Result.success(list.stream().map(SysConfigDTO::from).collect(Collectors.toList()));
+    }
+
+    /**
+     * 获取单个配置
+     */
+    public Result<SysConfigDTO> get(String key) {
+        SysConfig config = configMapper.selectOne(
+            new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, key));
+        if (config == null) {
+            return Result.error("配置不存在");
+        }
+        return Result.success(SysConfigDTO.from(config));
+    }
+
+    /**
+     * 更新或创建配置(upsert)
+     */
+    public Result<String> update(String key, String value) {
+        return update(key, value, null);
+    }
+
+    /**
+     * 更新或创建配置(upsert),支持描述
+     */
+    @CacheEvict(value = "sysConfig", allEntries = true)
+    public Result<String> update(String key, String value, String description) {
+        SysConfig config = configMapper.selectOne(
+            new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, key));
+        if (config == null) {
+            config = new SysConfig();
+            config.setConfigKey(key);
+            config.setConfigValue(value);
+            config.setDescription(description != null ? description : "");
+            config.setUpdatedAt(new Date());
+            configMapper.insert(config);
+            return Result.success("创建成功");
+        }
+        config.setConfigValue(value);
+        if (description != null) {
+            config.setDescription(description);
+        }
+        config.setUpdatedAt(new Date());
+        configMapper.updateById(config);
+        return Result.success("更新成功");
+    }
+
+    /**
+     * 内部方法:获取配置值(供其他 Service 调用)
+     */
+    @Cacheable(value = "sysConfig", key = "#key", unless = "#result == null")
+    public String getValue(String key) {
+        SysConfig config = configMapper.selectOne(
+            new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, key));
+        return config != null ? config.getConfigValue() : null;
+    }
+}

+ 250 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SysMenuService.java

@@ -0,0 +1,250 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.etotem.cfc.entity.SysMenu;
+import com.etotem.cfc.entity.SysRoleMenu;
+import com.etotem.cfc.mapper.SysMenuMapper;
+import com.etotem.cfc.mapper.SysRoleMenuMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+@Service
+public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {
+
+    @Resource
+    private SysMenuMapper sysMenuMapper;
+
+    @Resource
+    private SysRoleMenuMapper sysRoleMenuMapper;
+
+    /**
+     * 全量菜单树
+     */
+    public List<SysMenu> tree() {
+        List<SysMenu> all = sysMenuMapper.selectList(
+            new LambdaQueryWrapper<SysMenu>().orderByAsc(SysMenu::getSort).orderByAsc(SysMenu::getId)
+        );
+        return buildTree(all, 0L);
+    }
+
+    /**
+     * 按 parentId 组装树
+     */
+    private List<SysMenu> buildTree(List<SysMenu> all, Long parentId) {
+        List<SysMenu> result = new ArrayList<>();
+        for (SysMenu m : all) {
+            Long pid = m.getParentId() == null ? 0L : m.getParentId();
+            if (pid.equals(parentId)) {
+                m.setChildren(buildTree(all, m.getId()));
+                result.add(m);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 某角色已授权 menu_id 列表
+     */
+    public List<Long> roleMenuIds(String role) {
+        List<SysRoleMenu> list = sysRoleMenuMapper.selectList(
+            new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRole, role)
+        );
+        List<Long> ids = new ArrayList<>();
+        for (SysRoleMenu r : list) {
+            ids.add(r.getMenuId());
+        }
+        return ids;
+    }
+
+    /**
+     * 覆盖式保存角色授权
+     */
+    public void saveRoleMenus(String role, List<Long> menuIds) {
+        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRole, role));
+        if (menuIds != null) {
+            for (Long menuId : menuIds) {
+                if (menuId == null) {
+                    continue;
+                }
+                SysRoleMenu r = new SysRoleMenu();
+                r.setRole(role);
+                r.setMenuId(menuId);
+                sysRoleMenuMapper.insert(r);
+            }
+        }
+    }
+
+    /**
+     * 当前用户可见菜单树
+     * 逻辑: 从 roles 取授权 menu_id 集合;若该集合为空(管理员尚未配置任何授权)→ 返回全量 visible=1 树(保持现状兼容);
+     * 非空 → 返回这些菜单的子树并补全父级链。
+     */
+    public List<SysMenu> userMenus(List<String> roles) {
+        List<SysMenu> all = sysMenuMapper.selectList(
+            new LambdaQueryWrapper<SysMenu>().orderByAsc(SysMenu::getSort).orderByAsc(SysMenu::getId)
+        );
+        if (all.isEmpty()) {
+            return new ArrayList<>();
+        }
+
+        // 收集授权 menu_id
+        Set<Long> authed = new HashSet<>();
+        if (roles != null) {
+            for (String role : roles) {
+                if (role == null || role.isEmpty()) {
+                    continue;
+                }
+                List<SysRoleMenu> list = sysRoleMenuMapper.selectList(
+                    new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRole, role)
+                );
+                for (SysRoleMenu r : list) {
+                    authed.add(r.getMenuId());
+                }
+            }
+        }
+
+        // 无任何授权记录 → 返回全量可见树
+        if (authed.isEmpty()) {
+            List<SysMenu> visible = new ArrayList<>();
+            for (SysMenu m : all) {
+                if (Integer.valueOf(1).equals(m.getVisible())) {
+                    visible.add(m);
+                }
+            }
+            return buildTree(visible, 0L);
+        }
+
+        // 有授权 → 计算需返回的节点集合(含父级链补全)
+        Set<Long> idSet = new HashSet<>();
+        for (SysMenu m : all) {
+            idSet.add(m.getId());
+        }
+        Map<Long, SysMenu> byId = new HashMap<>();
+        for (SysMenu m : all) {
+            byId.put(m.getId(), m);
+        }
+
+        Set<Long> included = new HashSet<>();
+        for (SysMenu m : all) {
+            if (authed.contains(m.getId()) && Integer.valueOf(1).equals(m.getVisible())) {
+                // 向上补全父级链,要求路径上所有祖先节点均 visible=1
+                boolean chainVisible = true;
+                Long cur = m.getId();
+                List<Long> chainNodes = new ArrayList<>();
+                while (cur != null && idSet.contains(cur)) {
+                    SysMenu node = byId.get(cur);
+                    if (!Integer.valueOf(1).equals(node.getVisible())) {
+                        chainVisible = false;
+                        break;
+                    }
+                    chainNodes.add(cur);
+                    Long pid = node.getParentId() == null ? 0L : node.getParentId();
+                    if (pid == 0L || !idSet.contains(pid)) {
+                        break;
+                    }
+                    cur = pid;
+                }
+                if (chainVisible) {
+                    included.addAll(chainNodes);
+                }
+            }
+        }
+
+        List<SysMenu> filtered = new ArrayList<>();
+        for (SysMenu m : all) {
+            if (included.contains(m.getId())) {
+                filtered.add(m);
+            }
+        }
+        return buildTree(filtered, 0L);
+    }
+
+    /**
+     * 创建菜单,sort 默认取同级最大值+1
+     */
+    public SysMenu create(SysMenu menu) {
+        Long parentId = menu.getParentId() == null ? 0L : menu.getParentId();
+        menu.setParentId(parentId);
+        if (menu.getSort() == null) {
+            Integer maxSort = sysMenuMapper.selectList(
+                new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, parentId)
+            ).stream().map(SysMenu::getSort).filter(s -> s != null).max(Comparator.naturalOrder()).orElse(-1);
+            menu.setSort(maxSort + 1);
+        }
+        if (menu.getVisible() == null) {
+            menu.setVisible(1);
+        }
+        this.save(menu);
+        return menu;
+    }
+
+    /**
+     * 更新菜单(parentId 变更即层级调整)
+     */
+    public boolean update(SysMenu menu) {
+        return this.updateById(menu);
+    }
+
+    /**
+     * 删除菜单,有子菜单则拒绝
+     */
+    public boolean delete(Long id) {
+        Long childCount = sysMenuMapper.selectCount(
+            new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, id)
+        );
+        if (childCount != null && childCount > 0) {
+            return false;
+        }
+        // 删除关联授权
+        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getMenuId, id));
+        return this.removeById(id);
+    }
+
+    /**
+     * 同级内上移/下移(与相邻兄弟交换 sort)
+     */
+    public boolean move(Long id, String direction) {
+        SysMenu target = this.getById(id);
+        if (target == null) {
+            return false;
+        }
+        Long parentId = target.getParentId() == null ? 0L : target.getParentId();
+        List<SysMenu> siblings = sysMenuMapper.selectList(
+            new LambdaQueryWrapper<SysMenu>()
+                .eq(SysMenu::getParentId, parentId)
+                .orderByAsc(SysMenu::getSort)
+                .orderByAsc(SysMenu::getId)
+        );
+        int idx = -1;
+        for (int i = 0; i < siblings.size(); i++) {
+            if (siblings.get(i).getId().equals(id)) {
+                idx = i;
+                break;
+            }
+        }
+        if (idx < 0) {
+            return false;
+        }
+        int swapIdx = "up".equals(direction) ? idx - 1 : idx + 1;
+        if (swapIdx < 0 || swapIdx >= siblings.size()) {
+            return false; // 已在边界
+        }
+        SysMenu neighbor = siblings.get(swapIdx);
+        int tmp = target.getSort() == null ? 0 : target.getSort();
+        target.setSort(neighbor.getSort() == null ? 0 : neighbor.getSort());
+        neighbor.setSort(tmp);
+        this.updateById(target);
+        this.updateById(neighbor);
+        return true;
+    }
+}

+ 40 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SystemConfigService.java

@@ -0,0 +1,40 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.SystemConfig;
+import com.etotem.cfc.mapper.SystemConfigMapper;
+import org.springframework.stereotype.Service;
+import javax.annotation.Resource;
+
+@Service
+public class SystemConfigService {
+
+    private static final int DEFAULT_CHILD_AGE = 18;
+    private static final int DEFAULT_ELDERLY_AGE = 65;
+
+    @Resource
+    private SystemConfigMapper systemConfigMapper;
+
+    /**
+     * 获取未成年年龄阈值,默认18岁
+     */
+    public int getChildAgeThreshold() {
+        SystemConfig cfg = systemConfigMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SystemConfig>()
+                .eq(SystemConfig::getConfigKey, "child_age_threshold"));
+        return cfg != null && cfg.getConfigValue() != null
+            ? Integer.parseInt(cfg.getConfigValue())
+            : DEFAULT_CHILD_AGE;
+    }
+
+    /**
+     * 获取老年年龄阈值,默认65岁
+     */
+    public int getElderlyAgeThreshold() {
+        SystemConfig cfg = systemConfigMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SystemConfig>()
+                .eq(SystemConfig::getConfigKey, "elderly_age_threshold"));
+        return cfg != null && cfg.getConfigValue() != null
+            ? Integer.parseInt(cfg.getConfigValue())
+            : DEFAULT_ELDERLY_AGE;
+    }
+}

+ 28 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/SystemPromptService.java

@@ -0,0 +1,28 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.etotem.cfc.entity.SystemPrompt;
+
+import java.util.List;
+import java.util.Map;
+
+public interface SystemPromptService extends IService<SystemPrompt> {
+
+    Map<String, Object> list(String keyword, int page, int size);
+
+    SystemPrompt getByKey(String promptKey);
+
+    SystemPrompt savePrompt(SystemPrompt prompt, String operator);
+
+    SystemPrompt resetToDefault(String promptKey);
+
+    /**
+     * 查询提示词版本历史
+     */
+    List<Map<String, Object>> listVersions(String promptKey, int page, int size);
+
+    /**
+     * 回滚到指定版本
+     */
+    SystemPrompt rollback(String promptKey, int targetVersion, String operator);
+}

+ 73 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskParseService.java

@@ -0,0 +1,73 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.TaskParseResult;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 解析 Dify 返回的 [TASK] 标记,提取任务参数
+ */
+@Service
+public class TaskParseService {
+
+    private static final Logger log = LoggerFactory.getLogger(TaskParseService.class);
+
+    private static final Pattern TASK_PATTERN =
+            Pattern.compile("\\[TASK:\\s*(\\{.*?\\})\\]", Pattern.DOTALL);
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 从 Dify answer 中解析所有 [TASK] 标记
+     * @param answer Dify 原始回复
+     * @return 解析后的任务参数列表(title 必填,不满足校验的跳过)
+     */
+    public List<TaskParseResult> parseTasks(String answer) {
+        List<TaskParseResult> results = new ArrayList<>();
+        if (answer == null || answer.isEmpty()) return results;
+
+        Matcher matcher = TASK_PATTERN.matcher(answer);
+        while (matcher.find()) {
+            String json = matcher.group(1);
+            try {
+                @SuppressWarnings("unchecked")
+                Map<String, Object> map = objectMapper.readValue(json, Map.class);
+                TaskParseResult task = new TaskParseResult();
+                task.setTitle(map.containsKey("title") ? map.get("title").toString() : null);
+                task.setDescription(map.containsKey("description") ? map.get("description").toString() : null);
+                task.setDeadline(map.containsKey("deadline") ? map.get("deadline").toString() : null);
+                task.setDimension(map.containsKey("dimension") ? map.get("dimension").toString() : null);
+                if (map.containsKey("rewardPoints")) {
+                    Object rp = map.get("rewardPoints");
+                    task.setRewardPoints(rp instanceof Number ? ((Number) rp).intValue() : null);
+                }
+                if (task.getTitle() == null || task.getTitle().isEmpty()) {
+                    log.warn("跳过无标题的 TASK 标记: {}", json);
+                    continue;
+                }
+                results.add(task);
+            } catch (Exception e) {
+                log.warn("解析 TASK 标记失败, 跳过: json={}, error={}", json, e.getMessage());
+            }
+        }
+        return results;
+    }
+
+    /**
+     * 从 Dify answer 中移除所有 [TASK] 标记
+     * @param answer Dify 原始回复
+     * @return 清洗后的回复
+     */
+    public String stripTaskMarkers(String answer) {
+        if (answer == null) return null;
+        return TASK_PATTERN.matcher(answer).replaceAll("").trim();
+    }
+}

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

@@ -0,0 +1,57 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.TaskPlanInstance;
+import com.etotem.cfc.mapper.TaskPlanInstanceMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+/**
+ * 任务方案实例服务
+ */
+@Service
+public class TaskPlanInstanceService {
+
+    @Autowired
+    private TaskPlanInstanceMapper mapper;
+
+    /**
+     * 根据家庭 ID 获取方案列表(包含所有家庭成员)
+     */
+    public List<TaskPlanInstance> getListByFamily(Long familyId) {
+        LambdaQueryWrapper<TaskPlanInstance> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(TaskPlanInstance::getFamilyId, familyId)
+               .orderByDesc(TaskPlanInstance::getCreatedAt);
+        return mapper.selectList(wrapper);
+    }
+
+    /**
+     * 根据家庭 ID 和家庭成员 ID 获取方案列表
+     */
+    public List<TaskPlanInstance> getListByChildAndFamily(Long memberId, Long familyId) {
+        LambdaQueryWrapper<TaskPlanInstance> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(TaskPlanInstance::getMemberId, memberId)
+               .eq(TaskPlanInstance::getFamilyId, familyId)
+               .orderByDesc(TaskPlanInstance::getCreatedAt);
+        return mapper.selectList(wrapper);
+    }
+
+    /**
+     * 根据家庭成员 ID 获取方案列表
+     */
+    public List<TaskPlanInstance> getListByChild(Long memberId) {
+        LambdaQueryWrapper<TaskPlanInstance> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(TaskPlanInstance::getMemberId, memberId)
+               .orderByDesc(TaskPlanInstance::getCreatedAt);
+        return mapper.selectList(wrapper);
+    }
+
+    /**
+     * 根据方案 ID 获取单个方案
+     */
+    public TaskPlanInstance getById(Long id) {
+        return mapper.selectById(id);
+    }
+}

+ 401 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskPlanService.java

@@ -0,0 +1,401 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.TaskPlanServiceInterface;
+import javax.annotation.Resource;
+
+import com.etotem.cfc.entity.TaskPlanInstance;
+import com.etotem.cfc.entity.TaskPlanItem;
+import com.etotem.cfc.entity.TaskTemplateItem;
+import com.etotem.cfc.entity.TaskTemplatePackage;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.TaskPlanInstanceMapper;
+import com.etotem.cfc.mapper.TaskPlanItemMapper;
+import com.etotem.cfc.mapper.TaskTemplateItemMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.ApplyPackageDTO;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Service
+public class TaskPlanService implements TaskPlanServiceInterface {
+
+    @Resource
+    private TaskPlanInstanceMapper instanceMapper;
+
+    @Resource
+    private TaskPlanItemMapper planItemMapper;
+
+    @Resource
+    private TaskTemplateItemMapper templateItemMapper;
+
+    @Resource
+    private TaskTemplatePackageService packageService;
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    /**
+     * 家庭主账号应用任务模板 - 创建任务计划实例
+     */
+    @Transactional
+    public TaskPlanInstance applyPackage(ApplyPackageDTO dto, Long familyId) {
+        // 获取任务模板信息
+        TaskTemplatePackage pkg = packageService.getPackageById(dto.getPackageId());
+        if (pkg == null) {
+            throw new RuntimeException("任务模板不存在");
+        }
+
+        // 获取选中的任务项
+        List<TaskTemplateItem> selectedItems;
+        if (dto.getSelectedItemIds() != null && !dto.getSelectedItemIds().isEmpty()) {
+            selectedItems = dto.getSelectedItemIds().stream()
+                .map(templateItemMapper::selectById)
+                .filter(item -> item != null && item.getPackageId().equals(dto.getPackageId()))
+                .collect(Collectors.toList());
+        } else {
+            // 未选择则获取所有任务项
+            selectedItems = templateItemMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplateItem>()
+                    .eq("package_id", dto.getPackageId())
+                    .orderByAsc("sort_order")
+            );
+        }
+
+        // 创建实例
+        TaskPlanInstance instance = new TaskPlanInstance();
+        instance.setPackageId(dto.getPackageId());
+        instance.setFamilyId(familyId);
+        instance.setMemberId(dto.getMemberId());
+        instance.setName(pkg.getName());
+        
+        Date now = new Date();
+        instance.setStartDate(now);
+        instance.setEndDate(new Date(now.getTime() + (long) pkg.getCycleDays() * 24 * 60 * 60 * 1000));
+        instance.setStatus("generated"); // 状态机: generated → reviewed → active(见统一设计)
+        instance.setTotalDays(pkg.getCycleDays());
+        instance.setCompletedDays(0);
+        instance.setCreatedAt(now);
+        instance.setUpdatedAt(now);
+        
+        instanceMapper.insert(instance);
+
+        // 复制任务项到实例
+        for (TaskTemplateItem templateItem : selectedItems) {
+            TaskPlanItem planItem = new TaskPlanItem();
+            planItem.setInstanceId(instance.getId());
+            planItem.setTemplateItemId(templateItem.getId());
+            planItem.setTaskName(templateItem.getTaskName());
+            planItem.setDescription(templateItem.getDescription());
+            planItem.setPoints(templateItem.getPoints());
+            planItem.setFrequency(templateItem.getFrequency());
+            planItem.setDuration(templateItem.getDuration());
+            planItem.setCreatedAt(now);
+            planItem.setUpdatedAt(now);
+            planItemMapper.insert(planItem);
+        }
+
+        return instance;
+    }
+
+    /**
+     * 获取家庭的任务计划列表
+     */
+    public List<TaskPlanInstance> getFamilyPlans(Long familyId) {
+        return instanceMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskPlanInstance>()
+                .eq("family_id", familyId)
+                .orderByDesc("created_at")
+        );
+    }
+
+    /**
+     * 方案确认:将套餐计划实例生成可执行任务(B20 补全)
+     *
+     * @deprecated 已被 {@link #generateTasksFromTemplate} 替代。
+     * 旧方法从 task_plan_items 读任务(已降级为审计快照),
+     * 新方法 generateTasksFromTemplate 从 task_template_items 读——两套数据源不一致,
+     * 若未来误调用会造成双轨。confirm 流程已改走 applyAndActivate → generateTasksFromTemplate。
+     */
+    @Deprecated
+    @Transactional
+    public int generatePlanTasks(Long planId, Long familyId, Long userId) {
+        TaskPlanInstance plan = instanceMapper.selectById(planId);
+        if (plan == null) {
+            throw new IllegalStateException("方案不存在");
+        }
+        // 幂等:该计划已生成过任务则跳过
+        Long existing = taskMapper.selectCount(
+                new LambdaQueryWrapper<Task>()
+                        .eq(Task::getSourceType, "plan")
+                        .eq(Task::getSourceId, planId));
+        if (existing != null && existing > 0) {
+            return 0;
+        }
+        List<TaskPlanItem> items = planItemMapper.selectList(
+                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskPlanItem>()
+                        .eq("instance_id", planId)
+                        .orderByAsc("id"));
+        if (items.isEmpty()) {
+            return 0;
+        }
+        Date now = new Date();
+        int count = 0;
+        for (TaskPlanItem item : items) {
+            Task task = new Task();
+            task.setFamilyId(familyId);
+            task.setMemberId(plan.getMemberId());
+            task.setCreatorId(userId);
+            task.setExecutorType("child"); // 非登录用户(不可登录成员)
+            task.setExecutorId(plan.getMemberId());
+            task.setTitle(item.getTaskName());
+            task.setDescription(item.getDescription());
+            task.setPoints(item.getPoints() != null ? item.getPoints() : 0);
+            task.setCategory("成长");
+            task.setStatus("pending");
+            task.setNeedReview(0);
+            task.setIsTemplate(0);
+            task.setSourceType("plan");
+            task.setSourceId(planId);
+            task.setMemberOnly(1); // B20: 方案/套餐生成的任务为会员专属
+            task.setDeadline(plan.getEndDate());
+            task.setCreatedAt(now);
+            task.setUpdatedAt(now);
+            taskMapper.insert(task);
+            count++;
+        }
+        // 标记方案已激活(幂等)
+        if (!"active".equals(plan.getStatus())) {
+            plan.setStatus("active");
+            plan.setActivatedAt(now);
+            plan.setUpdatedAt(now);
+            instanceMapper.updateById(plan);
+        }
+        log.info("方案确认生成任务: planId={}, familyId={}, taskCount={}", planId, familyId, count);
+        return count;
+    }
+
+    /**
+     * 统一方案任务生成器(设计: 2026-09-04-plan-to-task-unification-design.md)
+     * 引导任务 + 从 task_template_items(按 sort_order)批量生成日常任务。
+     * 幂等:sourceType=plan & sourceId=planId 已存在任务则跳过。
+     * deadline:当天 23:59:59;familyMemberId:统一设置;memberOnly=1。
+     */
+    @Transactional
+    public int generateTasksFromTemplate(TaskPlanInstance plan, Long operatorId) {
+        if (plan == null) {
+            throw new IllegalStateException("方案不存在");
+        }
+        Long planId = plan.getId();
+        // 幂等:该方案已生成过任务则跳过(排除 cancelled,避免 cancelPlan 后重新激活时漏生成)
+        Long existing = taskMapper.selectCount(
+                new LambdaQueryWrapper<Task>()
+                        .eq(Task::getSourceType, "plan")
+                        .eq(Task::getSourceId, planId)
+                        .ne(Task::getStatus, "cancelled"));
+        if (existing != null && existing > 0) {
+            return 0;
+        }
+
+        Date now = new Date();
+        Date deadline = buildTodayDeadline();
+        int count = 0;
+
+        // 1. 引导任务(方案启动)
+        Task guideTask = new Task();
+        guideTask.setFamilyId(plan.getFamilyId());
+        guideTask.setMemberId(plan.getMemberId());
+        guideTask.setFamilyMemberId(plan.getMemberId());
+        guideTask.setCreatorId(operatorId);
+        guideTask.setExecutorType("child"); // 非登录用户(不可登录成员)
+        guideTask.setExecutorId(plan.getMemberId());
+        guideTask.setTitle("方案启动: " + plan.getName());
+        guideTask.setDescription("请阅读并开始执行测评方案");
+        guideTask.setPoints(2);
+        guideTask.setCategory("成长");
+        guideTask.setStatus("pending");
+        guideTask.setSourceType("plan");
+        guideTask.setSourceId(planId);
+        guideTask.setNeedReview(0);
+        guideTask.setIsTemplate(0);
+        guideTask.setMemberOnly(1);
+        guideTask.setDeadline(deadline);
+        guideTask.setCreatedAt(now);
+        guideTask.setUpdatedAt(now);
+        taskMapper.insert(guideTask);
+        count++;
+
+        // 2. 模板任务(task_template_items 为唯一来源)
+        if (plan.getPackageId() != null) {
+            List<TaskTemplateItem> items = templateItemMapper.selectList(
+                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplateItem>()
+                            .eq("package_id", plan.getPackageId())
+                            .orderByAsc("sort_order"));
+            for (TaskTemplateItem item : items) {
+                if (item.getTaskName() == null || item.getTaskName().isEmpty()) continue;
+                Task task = new Task();
+                task.setFamilyId(plan.getFamilyId());
+                task.setMemberId(plan.getMemberId());
+                task.setFamilyMemberId(plan.getMemberId());
+                task.setCreatorId(operatorId);
+                task.setExecutorType("child"); // 非登录用户(不可登录成员)
+                task.setExecutorId(plan.getMemberId());
+                task.setTitle(item.getTaskName());
+                task.setDescription(item.getDescription());
+                task.setPoints(item.getPoints() != null ? item.getPoints() : 2);
+                task.setCategory("成长");
+                task.setStatus("pending");
+                task.setSourceType("plan");
+                task.setSourceId(planId);
+                task.setNeedReview(0);
+                task.setIsTemplate(0);
+                task.setMemberOnly(1);
+                task.setFrequency(item.getFrequency() != null ? item.getFrequency() : "daily");
+                task.setDuration(item.getDuration());
+                task.setDeadline(deadline);
+                task.setCreatedAt(now);
+                task.setUpdatedAt(now);
+                taskMapper.insert(task);
+                count++;
+            }
+        }
+
+        log.info("方案统一生成任务: planId={}, familyId={}, taskCount={}", planId, plan.getFamilyId(), count);
+        return count;
+    }
+
+    /**
+     * 家庭主账号自助应用套餐并激活(confirm / purchase 共用):
+     * 1. 幂等:同家庭同套餐已有 active 实例则复用
+     * 2. 新建则 applyPackage(generated)→ 置 active(自助跳过审核)
+     * 3. 统一生成器生成任务
+     */
+    @Transactional
+    public Map<String, Object> applyAndActivate(ApplyPackageDTO dto, Long familyId, Long userId) {
+        TaskPlanInstance plan = findActiveByFamilyAndPackage(familyId, dto.getPackageId());
+        boolean created = false;
+        if (plan == null) {
+            plan = applyPackage(dto, familyId);
+            created = true;
+        }
+        if (created) {
+            Date now = new Date();
+            plan.setStatus("active");
+            plan.setActivatedAt(now);
+            plan.setUpdatedAt(now);
+            instanceMapper.updateById(plan);
+        }
+        int taskCount = generateTasksFromTemplate(plan, userId);
+        Map<String, Object> result = new HashMap<>();
+        result.put("planId", plan.getId());
+        result.put("taskCount", taskCount);
+        return result;
+    }
+
+    /** 查询同家庭同套餐的 active 实例(幂等复用) */
+    public TaskPlanInstance findActiveByFamilyAndPackage(Long familyId, Long packageId) {
+        return instanceMapper.selectOne(
+                new LambdaQueryWrapper<TaskPlanInstance>()
+                        .eq(TaskPlanInstance::getFamilyId, familyId)
+                        .eq(TaskPlanInstance::getPackageId, packageId)
+                        .eq(TaskPlanInstance::getStatus, "active")
+                        .last("LIMIT 1"));
+    }
+
+    /** 当天 23:59:59 截止(与 TaskService.getTodayTasks 区间对齐) */
+    private Date buildTodayDeadline() {
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.HOUR_OF_DAY, 23);
+        cal.set(Calendar.MINUTE, 59);
+        cal.set(Calendar.SECOND, 59);
+        cal.set(Calendar.MILLISECOND, 0);
+        return cal.getTime();
+    }
+
+    /**
+     * 获取计划详情
+     */
+    public TaskPlanInstance getPlanById(Long id) {
+        return instanceMapper.selectById(id);
+    }
+
+    /**
+     * 获取计划的任务项列表
+     */
+    public List<TaskPlanItem> getPlanItems(Long instanceId) {
+        return planItemMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskPlanItem>()
+                .eq("instance_id", instanceId)
+        );
+    }
+
+    /**
+     * 取消计划
+     */
+    @Transactional
+    public boolean cancelPlan(Long id) {
+        TaskPlanInstance instance = instanceMapper.selectById(id);
+        if (instance == null || !"active".equals(instance.getStatus())) {
+            return false;
+        }
+        instance.setStatus("cancelled");
+        instance.setUpdatedAt(new Date());
+        boolean updated = instanceMapper.updateById(instance) > 0;
+
+        // 级联清理:该方案生成的未完成任务置 cancelled
+        if (updated) {
+            List<Task> pendingTasks = taskMapper.selectList(
+                    new LambdaQueryWrapper<Task>()
+                            .eq(Task::getSourceType, "plan")
+                            .eq(Task::getSourceId, id)
+                            .in(Task::getStatus, "pending", "pending_review", "locked", "in_progress"));
+            for (Task t : pendingTasks) {
+                t.setStatus("cancelled");
+                t.setUpdatedAt(new Date());
+                taskMapper.updateById(t);
+            }
+            log.info("取消方案{}并级联清理{}条未完成任务", id, pendingTasks.size());
+        }
+        return updated;
+    }
+
+    /**
+     * 更新完成天数
+     */
+    public boolean updateCompletedDays(Long id, int days) {
+        TaskPlanInstance instance = instanceMapper.selectById(id);
+        if (instance == null) return false;
+        
+        instance.setCompletedDays(days);
+        
+        // 如果完成天数达到总天数,自动完成
+        if (instance.getCompletedDays() >= instance.getTotalDays()) {
+            instance.setStatus("completed");
+        }
+        
+        instance.setUpdatedAt(new Date());
+        return instanceMapper.updateById(instance) > 0;
+    }
+
+    /**
+     * 获取家庭成员的有效计划
+     */
+    public List<TaskPlanInstance> getChildPlans(Long memberId) {
+        return instanceMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskPlanInstance>()
+                .eq("child_id", memberId)
+                .eq("status", "active")
+                .orderByDesc("created_at")
+        );
+    }
+}

+ 252 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderConfigService.java

@@ -0,0 +1,252 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.TaskReminderConfigDTO;
+import com.etotem.cfc.entity.TaskReminderConfig;
+import com.etotem.cfc.mapper.TaskReminderConfigMapper;
+import com.etotem.cfc.service.notification.NotificationChannel;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Service
+public class TaskReminderConfigService {
+
+    /** 支持的用户可选渠道(in_app 恒兜底,不进用户选择) */
+    private static final List<String> SUPPORTED_CHANNELS = Arrays.asList("wechat", "sms", "phone", "email");
+    private static final List<String> SUPPORTED_TIMING_MODES = Arrays.asList("before_deadline", "after_timeout");
+
+    /** 设计契约 §3.3:早晚时间 HH:mm 正则(task.reminder.daily) */
+    private static final String HHMM_REGEX = "^([01]\\d|2[0-3]):[0-5]\\d$";
+    private static final String DEFAULT_MORNING_TIME = "07:30";
+    private static final String DEFAULT_EVENING_TIME = "21:00";
+    private static final Map<String, String> CHANNEL_LABELS = new LinkedHashMap<>();
+
+    static {
+        CHANNEL_LABELS.put("wechat", "微信");
+        CHANNEL_LABELS.put("sms", "短信");
+        CHANNEL_LABELS.put("phone", "语音电话");
+        CHANNEL_LABELS.put("email", "邮件");
+        CHANNEL_LABELS.put("in_app", "站内消息");
+    }
+
+    @Resource
+    private TaskReminderConfigMapper taskReminderConfigMapper;
+
+    @Resource
+    private List<NotificationChannel> notificationChannels;
+
+    /** 返回用户配置;未配置返回默认值(与线上行为一致:微信+超时60分钟,站内兜底) */
+    public TaskReminderConfigDTO getConfig(Long userId) {
+        TaskReminderConfig entity = selectByUserId(userId);
+        TaskReminderConfigDTO dto = new TaskReminderConfigDTO();
+        if (entity == null) {
+            dto.setChannels(new ArrayList<>(Arrays.asList("wechat")));
+            dto.setTimingMode("after_timeout");
+            dto.setOffsetMinutes(60);
+            dto.setEnabled(1);
+            dto.setCompletionPraiseEnabled(0);
+            dto.setCompletionPraiseChannels(new ArrayList<>(Arrays.asList("wechat", "in_app")));
+            // 设计契约 §3.3/决策#2:未配置默认关闭日提醒,早晚时间默认 07:30 / 21:00
+            dto.setDailyEnabled(1);
+            dto.setMorningTime(DEFAULT_MORNING_TIME);
+            dto.setEveningTime(DEFAULT_EVENING_TIME);
+            dto.setStageEnabled(0);
+            dto.setStageWakeTime("07:00");
+            dto.setStageBreakfastTime("08:00");
+            dto.setStageLunchTime("12:30");
+            dto.setStageDinnerTime("19:00");
+            dto.setStageBedtimeTime("21:30");
+            dto.setWeeklyEnabled(0);
+            dto.setWeeklyTime(DEFAULT_EVENING_TIME);
+        } else {
+            dto.setChannels(entity.getChannels() == null || entity.getChannels().isEmpty()
+                    ? new ArrayList<>(Arrays.asList("wechat"))
+                    : new ArrayList<>(Arrays.asList(entity.getChannels().split(","))));
+            dto.setTimingMode(entity.getTimingMode());
+            dto.setOffsetMinutes(entity.getOffsetMinutes());
+            dto.setEnabled(entity.getEnabled());
+            dto.setCompletionPraiseEnabled(entity.getCompletionPraiseEnabled() == null ? 0 : entity.getCompletionPraiseEnabled());
+            String pc = entity.getCompletionPraiseChannels();
+            if (pc == null || pc.isEmpty()) {
+                dto.setCompletionPraiseChannels(new ArrayList<>(Arrays.asList("wechat", "in_app")));
+            } else {
+                dto.setCompletionPraiseChannels(new ArrayList<>(Arrays.asList(pc.split(","))));
+            }
+            // 设计契约 §3.3:实体缺失时按默认值回退(0 / 07:30 / 21:00)
+            dto.setDailyEnabled(entity.getDailyEnabled() == null ? 1 : entity.getDailyEnabled());
+            dto.setMorningTime(entity.getMorningTime() == null ? DEFAULT_MORNING_TIME : entity.getMorningTime());
+            dto.setEveningTime(entity.getEveningTime() == null ? DEFAULT_EVENING_TIME : entity.getEveningTime());
+        dto.setStageEnabled(entity.getStageEnabled() == null ? 0 : entity.getStageEnabled());
+        dto.setStageWakeTime(firstNonNull(entity.getStageWakeTime(), "07:00"));
+        dto.setStageBreakfastTime(firstNonNull(entity.getStageBreakfastTime(), "08:00"));
+        dto.setStageLunchTime(firstNonNull(entity.getStageLunchTime(), "12:30"));
+        dto.setStageDinnerTime(firstNonNull(entity.getStageDinnerTime(), "19:00"));
+        dto.setStageBedtimeTime(firstNonNull(entity.getStageBedtimeTime(), "21:30"));
+        dto.setWeeklyEnabled(entity.getWeeklyEnabled() == null ? 0 : entity.getWeeklyEnabled());
+        dto.setWeeklyTime(firstNonNull(entity.getWeeklyTime(), DEFAULT_EVENING_TIME));
+        }
+        dto.setAvailableChannels(buildChannelStatus());
+        return dto;
+    }
+
+    public void saveConfig(Long userId, TaskReminderConfigDTO dto) {
+        List<String> channels = dto.getChannels() == null ? new ArrayList<>() : dto.getChannels();
+        List<String> cleaned = new ArrayList<>();
+        for (String ch : channels) {
+            if (ch == null) continue;
+            String c = ch.trim();
+            if (SUPPORTED_CHANNELS.contains(c) && !cleaned.contains(c)) {
+                cleaned.add(c);
+            }
+        }
+        if (cleaned.isEmpty()) {
+            throw new IllegalArgumentException("至少选择一个提醒渠道");
+        }
+
+        String timingMode = dto.getTimingMode();
+        if (!SUPPORTED_TIMING_MODES.contains(timingMode)) {
+            throw new IllegalArgumentException("提醒时机不合法");
+        }
+        int offset = dto.getOffsetMinutes() == null ? 60 : dto.getOffsetMinutes();
+        if (offset < 1 || offset > 1440) {
+            throw new IllegalArgumentException("偏移分钟需在 1-1440 之间");
+        }
+
+        // 设计契约 §3.3(task.reminder.daily):早晚时间 HH:mm 严格校验 + dailyEnabled ∈ {0,1}
+        // 注:时间字段仅在调用方显式传入时校验(管理端老入口不传 daily 字段,不得被新校验卡住)
+        String morning = dto.getMorningTime();
+        if (morning != null && !morning.matches(HHMM_REGEX)) {
+            throw new IllegalArgumentException("提醒时间格式不合法");
+        }
+        String evening = dto.getEveningTime();
+        if (evening != null && !evening.matches(HHMM_REGEX)) {
+            throw new IllegalArgumentException("提醒时间格式不合法");
+        }
+        String[] stageTimes = { dto.getStageWakeTime(), dto.getStageBreakfastTime(),
+                dto.getStageLunchTime(), dto.getStageDinnerTime(), dto.getStageBedtimeTime() };
+        for (String t : stageTimes) {
+            if (t != null && !t.matches(HHMM_REGEX)) {
+                throw new IllegalArgumentException("阶段提醒时间格式应为 HH:mm");
+            }
+        }
+        int stageEnabled = dto.getStageEnabled() == null ? 0 : dto.getStageEnabled();
+        if (stageEnabled != 0 && stageEnabled != 1) {
+            throw new IllegalArgumentException("阶段提醒开关取值不合法");
+        }
+        int daily = dto.getDailyEnabled() == null ? 1 : dto.getDailyEnabled();
+        if (daily != 0 && daily != 1) {
+            throw new IllegalArgumentException("日提醒开关取值不合法");
+        }
+
+        TaskReminderConfig entity = selectByUserId(userId);
+        boolean isNew = (entity == null);
+        if (isNew) {
+            entity = new TaskReminderConfig();
+            entity.setUserId(userId);
+            entity.setCreatedAt(new Date());
+        }
+        entity.setChannels(String.join(",", cleaned));
+        entity.setTimingMode(timingMode);
+        entity.setOffsetMinutes(offset);
+        entity.setEnabled(dto.getEnabled() != null && dto.getEnabled() == 0 ? 0 : 1);
+        List<String> praiseChannels = dto.getCompletionPraiseChannels() == null ? new ArrayList<>() : dto.getCompletionPraiseChannels();
+        List<String> cleanedPraise = new ArrayList<>();
+        for (String ch : praiseChannels) {
+            if (ch == null) continue;
+            String c = ch.trim();
+            if (SUPPORTED_CHANNELS.contains(c) && !cleanedPraise.contains(c)) {
+                cleanedPraise.add(c);
+            }
+        }
+        if (cleanedPraise.isEmpty()) {
+            cleanedPraise.add("in_app");
+            cleanedPraise.add("wechat");
+        }
+        entity.setCompletionPraiseEnabled(dto.getCompletionPraiseEnabled() != null && dto.getCompletionPraiseEnabled() == 1 ? 1 : 0);
+        entity.setCompletionPraiseChannels(String.join(",", cleanedPraise));
+        entity.setDailyEnabled(daily);
+        // 未传时保持既有值(新实体落默认),避免管理端老入口保存把时间清空
+        entity.setMorningTime(morning != null ? morning
+                : (entity.getMorningTime() != null ? entity.getMorningTime() : DEFAULT_MORNING_TIME));
+        entity.setEveningTime(evening != null ? evening
+                : (entity.getEveningTime() != null ? entity.getEveningTime() : DEFAULT_EVENING_TIME));
+        entity.setStageEnabled(stageEnabled);
+        entity.setStageWakeTime(firstNonNull(dto.getStageWakeTime(), "07:00"));
+        entity.setStageBreakfastTime(firstNonNull(dto.getStageBreakfastTime(), "08:00"));
+        entity.setStageLunchTime(firstNonNull(dto.getStageLunchTime(), "12:30"));
+        entity.setStageDinnerTime(firstNonNull(dto.getStageDinnerTime(), "19:00"));
+        entity.setStageBedtimeTime(firstNonNull(dto.getStageBedtimeTime(), "21:30"));
+        int weeklyEnabled = dto.getWeeklyEnabled() == null ? 0 : dto.getWeeklyEnabled();
+        if (weeklyEnabled != 0 && weeklyEnabled != 1) {
+            throw new IllegalArgumentException("周总结开关取值不合法");
+        }
+        entity.setWeeklyEnabled(weeklyEnabled);
+        String weeklyTime = dto.getWeeklyTime();
+        if (weeklyTime != null && !weeklyTime.matches("^([01]\\d|2[0-3]):[0-5]\\d$")) {
+            throw new IllegalArgumentException("周总结时间格式不合法");
+        }
+        entity.setWeeklyTime(firstNonNull(weeklyTime, DEFAULT_EVENING_TIME));
+        entity.setUpdatedAt(new Date());
+        if (isNew) {
+            taskReminderConfigMapper.insert(entity);
+        } else {
+            taskReminderConfigMapper.updateById(entity);
+        }
+    }
+
+    /** 全量配置(调度器使用):userId -> 配置实体 */
+    public Map<Long, TaskReminderConfig> loadAllConfigs() {
+        Map<Long, TaskReminderConfig> map = new LinkedHashMap<>();
+        List<TaskReminderConfig> list = taskReminderConfigMapper.selectList(null);
+        if (list != null) {
+            for (TaskReminderConfig c : list) {
+                map.put(c.getUserId(), c);
+            }
+        }
+        return map;
+    }
+
+    private TaskReminderConfig selectByUserId(Long userId) {
+        return taskReminderConfigMapper.selectOne(new LambdaQueryWrapper<TaskReminderConfig>()
+                .eq(TaskReminderConfig::getUserId, userId)
+                .last("LIMIT 1"));
+    }
+
+    /** 汇总通道开通状态(外部通道以对应 NotificationChannel.isEnabled() 为准) */
+    private List<TaskReminderConfigDTO.ChannelInfo> buildChannelStatus() {
+        List<TaskReminderConfigDTO.ChannelInfo> result = new ArrayList<>();
+        for (Map.Entry<String, String> entry : CHANNEL_LABELS.entrySet()) {
+            TaskReminderConfigDTO.ChannelInfo info = new TaskReminderConfigDTO.ChannelInfo();
+            info.setType(entry.getKey());
+            info.setLabel(entry.getValue());
+            info.setAvailable(isChannelAvailable(entry.getKey()));
+            if (!info.getAvailable() && !"in_app".equals(entry.getKey())) {
+                info.setReason("未接入服务商网关,暂不可用");
+            }
+            result.add(info);
+        }
+        return result;
+    }
+
+    private boolean isChannelAvailable(String type) {
+        for (NotificationChannel channel : notificationChannels) {
+            if (type.equals(channel.getChannelType())) {
+                return channel.isEnabled();
+            }
+        }
+        return false;
+    }
+
+    private static String firstNonNull(String a, String b) {
+        return a != null ? a : b;
+    }
+}

+ 283 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderService.java

@@ -0,0 +1,283 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.TaskReminderServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.TaskMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.*;
+import com.etotem.cfc.util.SortUtil;
+
+/**
+ * TASK-013~015: 任务提醒和统计服务
+ */
+@Slf4j
+@Service
+public class TaskReminderService {
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    /**
+     * TASK-013: 获取即将到期的任务(用于提醒)
+     * 返回指定时间范围内即将到期的任务
+     */
+    public List<Task> getUpcomingTasks(Long memberId, int minutesBefore) {
+        Date now = new Date();
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.MINUTE, minutesBefore);
+        Date endTime = cal.getTime();
+
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "pending")
+            .ge(Task::getDeadline, now)
+            .le(Task::getDeadline, endTime)
+            .orderByAsc(Task::getDeadline));
+    }
+
+    /**
+     * TASK-013: 获取需要提醒的任务(半小时内到期)
+     */
+    public List<Task> getTasksNeedReminder(Long memberId) {
+        return getUpcomingTasks(memberId, 30);
+    }
+
+    /**
+     * TASK-013: 获取已超时但未完成的任务
+     */
+    public List<Task> getOverdueTasks(Long memberId) {
+        Date now = new Date();
+
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "pending")
+            .lt(Task::getDeadline, now)
+            .orderByAsc(Task::getDeadline));
+    }
+
+    /**
+     * TASK-014: 获取任务历史(带筛选条件)
+     */
+    public Map<String, Object> getTaskHistoryWithFilter(Long memberId, String status,
+                                                         Date startDate, Date endDate,
+                                                         Integer page, Integer size) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(Task::getMemberId, memberId);
+
+        // 状态筛选
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Task::getStatus, status);
+        }
+
+        // 时间范围
+        if (startDate != null) {
+            wrapper.ge(Task::getCreatedAt, startDate);
+        }
+        if (endDate != null) {
+            Calendar cal = Calendar.getInstance();
+            cal.setTime(endDate);
+            cal.add(Calendar.DAY_OF_MONTH, 1);
+            wrapper.le(Task::getCreatedAt, cal.getTime());
+        }
+
+        // 计算总数
+        SortUtil.applySort(wrapper);
+        Long total = taskMapper.selectCount(wrapper);
+
+        // 分页查询
+        wrapper.orderByDesc(Task::getCreatedAt);
+        int offset = (page - 1) * size;
+        SortUtil.applySort(wrapper);
+        List<Task> tasks = taskMapper.selectList(wrapper);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("list", tasks);
+        result.put("total", total);
+        result.put("page", page);
+        result.put("size", size);
+
+        return result;
+    }
+
+    /**
+     * TASK-015: 获取任务统计概览
+     */
+    public Map<String, Object> getTaskStatistics(Long memberId, Date startDate, Date endDate) {
+        Map<String, Object> stats = new HashMap<>();
+
+        // 基础统计
+        LambdaQueryWrapper<Task> baseWrapper = new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId);
+
+        if (startDate != null && endDate != null) {
+            baseWrapper.ge(Task::getCreatedAt, startDate)
+                     .le(Task::getCreatedAt, endDate);
+        }
+
+        // 总任务数
+        SortUtil.applySort(baseWrapper);
+        Long totalTasks = taskMapper.selectCount(baseWrapper);
+        stats.put("totalTasks", totalTasks);
+
+        // 已完成任务数
+        Long completedTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "completed")
+            .ge(startDate != null, Task::getCompletedAt, startDate)
+            .le(endDate != null, Task::getCompletedAt, endDate));
+        stats.put("completedTasks", completedTasks);
+
+        // 待完成任务数
+        Long pendingTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "pending"));
+        stats.put("pendingTasks", pendingTasks);
+
+        // 超时任务数
+        Long overdueTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "pending")
+            .lt(Task::getDeadline, new Date()));
+        stats.put("overdueTasks", overdueTasks);
+
+        // 已取消任务数
+        Long cancelledTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .eq(Task::getStatus, "cancelled"));
+        stats.put("cancelledTasks", cancelledTasks);
+
+        // 完成率
+        int completionRate = totalTasks > 0 ? (int) (completedTasks * 100L / totalTasks.intValue()) : 0;
+        stats.put("completionRate", completionRate);
+
+        return stats;
+    }
+
+    /**
+     * TASK-015: 获取按分类统计
+     */
+    public List<Map<String, Object>> getTaskStatsByCategory(Long memberId) {
+        List<Map<String, Object>> result = new ArrayList<>();
+
+        // 获取所有任务按分类统计
+        List<Task> allTasks = taskMapper.selectList(new LambdaQueryWrapper<Task>()
+            .eq(Task::getMemberId, memberId)
+            .isNotNull(Task::getCategory));
+
+        // 按分类分组统计
+        Map<String, Integer> categoryCount = new HashMap<>();
+        Map<String, Integer> categoryCompleted = new HashMap<>();
+
+        for (Task task : allTasks) {
+            String category = task.getCategory();
+            if (category != null) {
+                categoryCount.merge(category, 1, Integer::sum);
+                if ("completed".equals(task.getStatus())) {
+                    categoryCompleted.merge(category, 1, Integer::sum);
+                }
+            }
+        }
+
+        // 构建结果
+        for (Map.Entry<String, Integer> entry : categoryCount.entrySet()) {
+            Map<String, Object> item = new HashMap<>();
+            item.put("category", entry.getKey());
+            item.put("total", entry.getValue());
+            item.put("completed", categoryCompleted.getOrDefault(entry.getKey(), 0));
+                    int rate = entry.getValue() > 0 ? categoryCompleted.getOrDefault(entry.getKey(), 0) * 100 / entry.getValue() : 0;
+            item.put("completionRate", rate);
+            result.add(item);
+        }
+
+        return result;
+    }
+
+    /**
+     * TASK-015: 获取按日期统计(最近7天/30天)
+     */
+    public List<Map<String, Object>> getTaskStatsByDate(Long memberId, int days) {
+        List<Map<String, Object>> result = new ArrayList<>();
+        Calendar cal = Calendar.getInstance();
+
+        for (int i = days - 1; i >= 0; i--) {
+            cal.setTime(new Date());
+            cal.add(Calendar.DAY_OF_MONTH, -i);
+            cal.set(Calendar.HOUR_OF_DAY, 0);
+            cal.set(Calendar.MINUTE, 0);
+            cal.set(Calendar.SECOND, 0);
+            cal.set(Calendar.MILLISECOND, 0);
+            Date startOfDay = cal.getTime();
+
+            cal.add(Calendar.DAY_OF_MONTH, 1);
+            Date endOfDay = cal.getTime();
+
+            // 当天创建的任务数
+            Long created = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+                .eq(Task::getMemberId, memberId)
+                .ge(Task::getCreatedAt, startOfDay)
+                .lt(Task::getCreatedAt, endOfDay));
+
+            // 当天完成的任务数
+            Long completed = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+                .eq(Task::getMemberId, memberId)
+                .eq(Task::getStatus, "completed")
+                .ge(Task::getCompletedAt, startOfDay)
+                .lt(Task::getCompletedAt, endOfDay));
+
+            Map<String, Object> dayStats = new HashMap<>();
+            dayStats.put("date", startOfDay);
+            dayStats.put("created", created);
+            dayStats.put("completed", completed);
+            result.add(dayStats);
+        }
+
+        return result;
+    }
+
+    /**
+     * TASK-015: 获取家庭任务统计
+     */
+    public Map<String, Object> getFamilyTaskStatistics(Long familyId) {
+        Map<String, Object> stats = new HashMap<>();
+
+        // 家庭总任务数
+        Long totalTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getFamilyId, familyId));
+        stats.put("totalTasks", totalTasks);
+
+        // 今日任务数
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = cal.getTime();
+        cal.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = cal.getTime();
+
+        Long todayTasks = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getFamilyId, familyId)
+            .ge(Task::getDeadline, startOfDay)
+            .lt(Task::getDeadline, endOfDay));
+        stats.put("todayTasks", todayTasks);
+
+        // 今日已完成
+        Long todayCompleted = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+            .eq(Task::getFamilyId, familyId)
+            .eq(Task::getStatus, "completed")
+            .ge(Task::getCompletedAt, startOfDay)
+            .lt(Task::getCompletedAt, endOfDay));
+        stats.put("todayCompleted", todayCompleted);
+
+        // 今日完成率
+        int todayRate = todayTasks > 0 ? (int) (todayCompleted * 100L / todayTasks.intValue()) : 0;
+        stats.put("todayCompletionRate", todayRate);
+
+        return stats;
+    }
+}

+ 2707 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java

@@ -0,0 +1,2707 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.CreateProductOrderDTO;
+import com.etotem.cfc.dto.CreateTaskDTO;
+import com.etotem.cfc.dto.FamilyTaskCreateDTO;
+import com.etotem.cfc.dto.ProductOrderDTO;
+import com.etotem.cfc.dto.TaskReviewDTO;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import com.etotem.cfc.service.api.TaskServiceInterface;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.etotem.cfc.service.OrchestrationEngine;
+import javax.annotation.Resource;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.*;
+import com.etotem.cfc.util.DimensionCodes;
+import com.etotem.cfc.util.SortUtil;
+import com.etotem.cfc.service.NotificationDispatchService;
+
+@Slf4j
+@Service
+public class TaskService implements TaskServiceInterface {
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+
+    @Resource
+    private TaskReminderConfigService taskReminderConfigService;
+
+    @Resource
+    private TaskExecutionMapper taskExecutionMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private PointsLogMapper pointsLogMapper;
+
+    @Resource
+    @Lazy
+    private UserService userService;
+
+    @Resource
+    private StreakService streakService;
+
+    @Resource
+    private MiniGameService miniGameService;
+
+    @Resource
+    private MiniGameMapper miniGameMapper;
+
+    @Resource
+    private EnergyService energyService;
+
+    @Resource
+    private FamilyRelationshipScoreMapper familyRelationshipScoreMapper;
+
+    @Resource
+    private CartService cartService;
+
+    @Resource
+    private ProductOrderService productOrderService;
+
+    @Resource
+    private ConsigneeMapper consigneeMapper;
+
+    @Resource
+    private SurveyService surveyService;
+
+    @Resource
+    private SurveyTemplateMapper surveyTemplateMapper;
+
+    @Resource
+    @Lazy
+    private OrchestrationEngine orchestrationEngine;
+
+    @Resource
+    private TaskTemplateMapper taskTemplateMapper;
+
+    @Resource
+    private CfPathwayEarnService cfPathwayEarnService;
+
+    private static final int EARLY_BONUS = 1; // 提前完成奖励
+    private static final int PENALTY_MAX_DAILY = 5; // 每日最多扣分
+    private static final int LATE_GRACE_MINUTES = 10; // 10分钟内不算迟到
+
+    // ==================== SC-P-10 创建任务校验(S-cfc-12) ====================
+    private static final Set<String> VALID_FREQUENCIES = Collections.unmodifiableSet(
+            new HashSet<>(Arrays.asList("none", "daily", "weekly", "monthly", "every_other_day", "hourly", "custom")));
+    /** 幂等窗口:同一创建请求在 30 秒内重复提交仅生成 1 条任务(重复提交不重复发分) */
+    private static final long TASK_DEDUP_WINDOW_MS = 30_000L;
+    /** 按任务去重键持有的 JVM 内锁,保证并发双发时 check-then-insert 原子性 */
+    private static final java.util.concurrent.ConcurrentHashMap<String, Object> TASK_DEDUP_LOCKS =
+            new java.util.concurrent.ConcurrentHashMap<>();
+    /** JVM 内刚创建任务登记表:dedupKey → long[]{taskId, createdAtMillis}(不依赖 DB 事务提交时机) */
+    private static final java.util.concurrent.ConcurrentHashMap<String, long[]> RECENT_TASKS =
+            new java.util.concurrent.ConcurrentHashMap<>();
+
+    @Transactional
+    public Long createTask(Long userId, CreateTaskDTO dto) {
+        User currentUser = userService.getUserInfo(userId);
+
+        // ===== SC-P-10 创建任务参数校验(异常流:空标题/负积分/非法频率/超期截止 → 400)=====
+        if (dto.getTitle() == null || dto.getTitle().trim().isEmpty()) {
+            throw new IllegalArgumentException("任务标题不能为空");
+        }
+        if (dto.getPoints() != null && dto.getPoints() < 0) {
+            throw new IllegalArgumentException("任务积分不能为负数");
+        }
+        if (dto.getFrequency() != null && !dto.getFrequency().isEmpty()
+                && !VALID_FREQUENCIES.contains(dto.getFrequency())) {
+            throw new IllegalArgumentException("任务频率不合法: " + dto.getFrequency());
+        }
+        if (dto.getDeadline() != null && dto.getDeadline().before(new Date())) {
+            throw new IllegalArgumentException("任务截止时间不能早于当前时间");
+        }
+        
+        // 处理执行者类型 - 支持家庭成员任务、家庭主账号任务、家庭成员任务
+        String executorType = dto.getExecutorType();
+        if (executorType == null || executorType.isEmpty()) {
+            executorType = "child";
+        }
+
+        // SC-P-10 权限流加固:child 下发的执行人(memberId/executorId)必须属于本家庭,
+        // 防横向越权向他人家庭成员注入任务(等价 member 分支的「被分配成员不属于本家庭」校验)
+        if ("child".equals(executorType)) {
+            List<Long> assigneeIds = new ArrayList<>();
+            if (dto.getMemberIds() != null) assigneeIds.addAll(dto.getMemberIds());
+            if (dto.getMemberId() != null) assigneeIds.add(dto.getMemberId());
+            if (dto.getExecutorId() != null) assigneeIds.add(dto.getExecutorId());
+            for (Long assigneeId : assigneeIds) {
+                if (assigneeId == null) continue;
+                Long count = familyMemberMapper.selectCount(
+                        new LambdaQueryWrapper<FamilyMember>()
+                                .eq(FamilyMember::getId, assigneeId)
+                                .eq(FamilyMember::getFamilyId, currentUser.getFamilyId()));
+                if (count == 0) {
+                    throw new IllegalArgumentException("被分配成员不属于本家庭");
+                }
+            }
+        }
+
+        if ("member".equals(executorType)) {
+            Long currentMemberId = getCurrentMemberId(userId);
+            long familyMemberCount = familyMemberMapper.selectCount(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getFamilyId, currentUser.getFamilyId()));
+            if (familyMemberCount < 2) {
+                throw new IllegalArgumentException("该任务需分配给其他家庭成员,当前家庭不足2人");
+            }
+            List<Long> assigneeIds = dto.getMemberIds();
+            if (assigneeIds == null || assigneeIds.isEmpty()) {
+                if (dto.getExecutorId() != null) {
+                    assigneeIds = Collections.singletonList(dto.getExecutorId());
+                } else if (dto.getMemberId() != null) {
+                    assigneeIds = Collections.singletonList(dto.getMemberId());
+                } else {
+                    assigneeIds = Collections.emptyList();
+                }
+            }
+            for (Long assigneeId : assigneeIds) {
+                if (assigneeId == null) continue;
+                if (assigneeId.equals(currentMemberId)) {
+                    throw new IllegalArgumentException("不能给自己分配家庭成员任务");
+                }
+                Long count = familyMemberMapper.selectCount(
+                        new LambdaQueryWrapper<FamilyMember>()
+                                .eq(FamilyMember::getId, assigneeId)
+                                .eq(FamilyMember::getFamilyId, currentUser.getFamilyId()));
+                if (count == 0) {
+                    throw new IllegalArgumentException("被分配成员不属于本家庭");
+                }
+            }
+        }
+
+        // 支持多家庭成员:为每个家庭成员创建独立任务实例
+        List<Long> memberIds = dto.getMemberIds();
+        if (memberIds == null || memberIds.isEmpty()) {
+            // 兼容旧版:使用单个memberId
+            if (dto.getMemberId() != null) {
+                memberIds = Collections.singletonList(dto.getMemberId());
+            } else if (dto.getExecutorId() != null && "child".equals(executorType)) {
+                memberIds = Collections.singletonList(dto.getExecutorId());
+            } else {
+                memberIds = Collections.emptyList();
+            }
+        }
+        
+        // 如果有多个家庭成员,为每个家庭成员创建任务
+        if (!memberIds.isEmpty() && memberIds.size() > 1) {
+            Long firstTaskId = null;
+            for (int i = 0; i < memberIds.size(); i++) {
+                Task memberTask = createSingleTask(currentUser, userId, executorType, memberIds.get(i), dto);
+                Long insertedId = insertTaskWithDedup(memberTask);
+                if (i == 0) firstTaskId = insertedId;
+            }
+            return firstTaskId;
+        } else {
+            // 单个家庭成员或无家庭成员
+            Long memberId = memberIds.isEmpty() ? null : memberIds.get(0);
+            Task task = createSingleTask(currentUser, userId, executorType, memberId, dto);
+            return insertTaskWithDedup(task);
+        }
+    }
+
+    /**
+     * SC-P-10 幂等插入:同一创建请求(家庭+执行人+标题+积分+频率+截止)在窗口内重复提交
+     * 复用已有任务 id。并发场景按任务键加 JVM 内锁,先查内存登记表(不依赖 DB 事务提交时机),
+     * 再查 DB 窗口内同内容任务(兜底跨重启/多实例),均未命中才插入并登记。
+     */
+    private Long insertTaskWithDedup(Task task) {
+        String key = dedupKeyFor(task);
+        Object lock = TASK_DEDUP_LOCKS.computeIfAbsent(key, k -> new Object());
+        synchronized (lock) {
+            // 1) JVM 内登记表(并发双发:第一个请求尚未提交 DB 也能命中)
+            long[] recent = RECENT_TASKS.get(key);
+            if (recent != null && System.currentTimeMillis() - recent[1] < TASK_DEDUP_WINDOW_MS) {
+                log.info("SC-P-10 幂等:JVM 登记表命中重复创建(key={}),复用任务 id={}", key, recent[0]);
+                return recent[0];
+            }
+            // 2) DB 窗口内同内容任务(跨重启/多实例兜底)
+            Long dupId = findRecentDuplicateTask(task);
+            if (dupId != null) {
+                RECENT_TASKS.put(key, new long[]{dupId, System.currentTimeMillis()});
+                log.info("SC-P-10 幂等:DB 命中重复创建(familyId={}, executor={}, title={}),复用任务 id={}",
+                        task.getFamilyId(), task.getExecutorId(), task.getTitle(), dupId);
+                return dupId;
+            }
+            taskMapper.insert(task);
+            ensureSurveyTemplateForTask(task);
+            RECENT_TASKS.put(key, new long[]{task.getId(), System.currentTimeMillis()});
+            return task.getId();
+        }
+    }
+
+    /** 去重键(截止时间按秒归一化:DB DATETIME 无毫秒,避免毫秒差导致幂等漏判) */
+    private String dedupKeyFor(Task task) {
+        String deadline = "";
+        if (task.getDeadline() != null) {
+            deadline = String.valueOf(task.getDeadline().getTime() / 1000);
+        }
+        return task.getFamilyId() + "|" + task.getExecutorType() + "|" + task.getExecutorId()
+                + "|" + task.getTitle() + "|" + task.getPoints() + "|" + task.getFrequency()
+                + "|" + deadline;
+    }
+
+    /** 在幂等窗口内查找刚创建过的同内容任务(仅查窗口内的同 key 任务,不误伤历史重复任务) */
+    private Long findRecentDuplicateTask(Task candidate) {
+        Date windowStart = new Date(System.currentTimeMillis() - TASK_DEDUP_WINDOW_MS);
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyId, candidate.getFamilyId())
+                .eq(Task::getTitle, candidate.getTitle())
+                .eq(Task::getPoints, candidate.getPoints())
+                .ge(Task::getCreatedAt, windowStart);
+        if (candidate.getFrequency() != null) wrapper.eq(Task::getFrequency, candidate.getFrequency());
+        if (candidate.getExecutorType() != null) wrapper.eq(Task::getExecutorType, candidate.getExecutorType());
+        if (candidate.getExecutorId() != null) wrapper.eq(Task::getExecutorId, candidate.getExecutorId());
+        if (candidate.getFamilyMemberId() != null) wrapper.eq(Task::getFamilyMemberId, candidate.getFamilyMemberId());
+        if (candidate.getDeadline() != null) {
+            // 截止时间按秒精度比对(DB DATETIME 无毫秒)
+            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            wrapper.apply("DATE_FORMAT(deadline, '%Y-%m-%d %H:%i:%s') = {0}", sdf.format(candidate.getDeadline()));
+        }
+        List<Task> hits = taskMapper.selectList(wrapper.last("LIMIT 1"));
+        return hits.isEmpty() ? null : hits.get(0).getId();
+    }
+    
+    /**
+     * 创建单个任务实例
+     */
+    /** D档:按 (user_id, family_id) 反查家长本人成员卡(主成员优先、id 最小兜底) */
+    private Long resolveParentMemberId(Long userId, Long familyId) {
+        if (familyMemberMapper == null || userId == null || familyId == null) return null;
+        try {
+            com.etotem.cfc.entity.FamilyMember fm = familyMemberMapper.selectOne(
+                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.etotem.cfc.entity.FamilyMember>()
+                            .eq(com.etotem.cfc.entity.FamilyMember::getUserId, userId)
+                            .eq(com.etotem.cfc.entity.FamilyMember::getFamilyId, familyId)
+                            .last("ORDER BY (is_admin = 1) DESC, id ASC LIMIT 1"));
+            return fm != null ? fm.getId() : null;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** D档:统一后的 executor_id=member.id,反查 users.id 用于配置/通知;历史 parent 任务兜底原值 */
+    private Long resolveUserIdByExecutor(com.etotem.cfc.entity.Task task) {
+        Long execId = task != null ? task.getExecutorId() : null;
+        if (execId == null) return null;
+        if (familyMemberMapper != null) {
+            try {
+                com.etotem.cfc.entity.FamilyMember fm = familyMemberMapper.selectById(execId);
+                if (fm != null && fm.getUserId() != null) return fm.getUserId();
+            } catch (Exception e) { /* 反查失败走兜底 */ }
+        }
+        return execId;
+    }
+
+    private Task createSingleTask(User currentUser, Long userId, String executorType, Long memberId, CreateTaskDTO dto) {
+        Task task = new Task();
+        task.setFamilyId(currentUser.getFamilyId());
+        task.setCreatorId(userId);
+        task.setExecutorType(executorType);
+        
+        if ("child".equals(executorType)) {
+            task.setExecutorId(memberId);
+            task.setFamilyMemberId(memberId);
+            task.setMemberId(memberId);
+        } else if ("member".equals(executorType)) {
+            task.setExecutorId(memberId);
+            task.setMemberId(null);
+            task.setStatus("assigned");
+            task.setAcceptDeadline(dto.getDeadline());
+        } else {
+            // D档:parent 任务 executor_id 统一指向 family_members.id,并补 family_member_id
+            Long parentMemberId = resolveParentMemberId(userId, currentUser.getFamilyId());
+            task.setExecutorId(parentMemberId != null ? parentMemberId : userId);
+            task.setFamilyMemberId(parentMemberId);
+            task.setMemberId(null);
+        }
+        
+        task.setTitle(dto.getTitle());
+        task.setDescription(dto.getDescription());
+        task.setPoints(dto.getPoints() != null ? dto.getPoints() : 2);
+        task.setDuration(dto.getDuration());
+
+        // 处理小游戏任务
+        task.setMinigameCode(dto.getMinigameCode());
+        if ("小游戏类".equals(dto.getCategory()) && dto.getMinigameCode() != null) {
+            // 小游戏任务:从MiniGame获取默认积分
+            MiniGame miniGame = miniGameMapper.selectOne(
+                new LambdaQueryWrapper<MiniGame>()
+                    .eq(MiniGame::getGameCode, dto.getMinigameCode())
+                    .eq(MiniGame::getStatus, 1)
+            );
+            if (miniGame != null) {
+                if (dto.getPoints() == null) {
+                    task.setPoints(miniGame.getDefaultPoints() != null ? miniGame.getDefaultPoints() : 5);
+                }
+                if (dto.getTitle() == null || dto.getTitle().isEmpty()) {
+                    task.setTitle(miniGame.getGameName());
+                }
+            }
+        }
+
+        // 如果没有指定截止时间,默认今天23:59
+        if (dto.getDeadline() == null) {
+            Calendar cal = Calendar.getInstance();
+            cal.set(Calendar.HOUR_OF_DAY, 23);
+            cal.set(Calendar.MINUTE, 59);
+            cal.set(Calendar.SECOND, 59);
+            task.setDeadline(cal.getTime());
+        } else {
+            task.setDeadline(dto.getDeadline());
+        }
+        
+        task.setRepeatType(dto.getRepeatType() != null ? dto.getRepeatType() : "none");
+        task.setCategory(dto.getCategory());
+
+        // 任务性质
+        task.setTaskType(dto.getTaskType());
+        task.setFrequency(dto.getFrequency());
+        task.setMaxFrequency(dto.getMaxFrequency());
+
+        // SC-P-12 task.frequency.config: 自定义周期(frequency=custom)周期单位/间隔/锚点
+        // 周期单位+间隔按 API_REFERENCE §4.3 以 actionType + actionConfig 声明,
+        // 此处解析后持久化到 Task 实体,供 RepeatTaskGenerator 按周期锚点推进生成实例。
+        if ("custom".equals(dto.getFrequency())) {
+            applyCustomFrequencyPeriod(task, dto);
+        }
+
+        // 完成方式(转为JSON存储)
+        if (dto.getCompleteTypes() != null && !dto.getCompleteTypes().isEmpty()) {
+            task.setCompleteTypes(String.join(",", dto.getCompleteTypes()));
+        }
+
+        // 审核设置
+        task.setReviewType(dto.getReviewType());
+        
+        // 时间设置
+        task.setEarliestStart(dto.getEarliestStart());
+        task.setLatestEnd(dto.getLatestEnd());
+
+        // 如果是重复任务,标记为模板
+        // SC-P-12 task.frequency.config: frequency=custom 同样是周期任务,须标记为模板,
+        // 否则 RepeatTaskGenerator(仅处理 is_template=1)永远不会为其生成实例。
+        if (!"none".equals(task.getRepeatType()) || "custom".equals(task.getFrequency())) {
+            task.setIsTemplate(1); // 模板任务
+        } else {
+            task.setIsTemplate(0);
+        }
+
+        // 家庭主账号给家庭成员安排任务需要审核,家庭成员给家庭主账号安排任务也需要审核
+        if ("child".equals(executorType)) {
+            task.setNeedReview(dto.getNeedReview() != null ? dto.getNeedReview() : 0);
+        } else {
+            // 家庭成员给家庭主账号安排任务,默认需要审核
+            task.setNeedReview(dto.getNeedReview() != null ? dto.getNeedReview() : 1);
+        }
+
+task.setReviewByCategory(dto.getReviewByCategory() != null ? dto.getReviewByCategory() : 0);
+        if (!"assigned".equals(task.getStatus())) {
+            // TASK-SYS-248: 有前置任务且前置未完成 → 初始状态 locked
+            if (dto.getPrerequisiteTaskId() != null) {
+                Task prereq = taskMapper.selectById(dto.getPrerequisiteTaskId());
+                if (prereq == null || !"completed".equals(prereq.getStatus())) {
+                    task.setStatus("locked");
+                } else {
+                    task.setStatus("pending");
+                }
+            } else {
+                task.setStatus("pending");
+            }
+        }
+        task.setCreatedAt(new Date());
+        task.setUpdatedAt(new Date());
+
+        // 五维维度
+        task.setDimensionCode(dto.getDimensionCode());
+        task.setDimensionWeights(dto.getDimensionWeights());
+
+        // B20: 会员任务标记透传(自建任务 memberOnly=0,不校验会员)
+        task.setMemberOnly(dto.getMemberOnly() != null ? dto.getMemberOnly() : 0);
+
+// TASK-SYS-248: 行为调度中心扩展字段透传
+        task.setPrerequisiteTaskId(dto.getPrerequisiteTaskId());
+        task.setActionType(dto.getActionType());
+        task.setActionConfig(dto.getActionConfig());
+        task.setRequireInput(dto.getRequireInput() != null ? dto.getRequireInput() : 0);
+        task.setStartRequired(dto.getStartRequired() != null ? dto.getStartRequired() : 0);
+        task.setStartCount(0);
+        task.setMinDurationSeconds(dto.getMinDurationSeconds() != null ? dto.getMinDurationSeconds() : 0);
+
+        // TASK-SYS-248: 自动计算是否为流程任务
+        // 有前置任务 或 有后置任务 → 标记为流程任务
+        if (dto.getPrerequisiteTaskId() != null
+                || (dto.getSuccessorTaskIds() != null && !dto.getSuccessorTaskIds().isEmpty())) {
+            task.setIsFlowTask(1);
+        } else {
+            task.setIsFlowTask(0);
+        }
+        task.setSuccessorTaskIds(dto.getSuccessorTaskIds());
+
+        task.setSourceType(dto.getSourceType() != null ? dto.getSourceType() : "self");
+        task.setSourceId(dto.getSourceId());
+        task.setIsDailyProgress(dto.getIsDailyProgress() != null ? dto.getIsDailyProgress() : 0);
+        task.setTargetValue(dto.getTargetValue());
+
+        // 进度型任务无 deadline(原 growth_task DAILY:每日重置,无截止时间)
+        if (task.getIsDailyProgress() != null && task.getIsDailyProgress() == 1) {
+            task.setDeadline(null);
+        }
+
+        return task;
+    }
+
+    private Long getCurrentMemberId(Long userId) {
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+        return member != null ? member.getId() : null;
+    }
+
+    /**
+     * SC-P-12 task.frequency.config: 解析 actionConfig 中自定义周期配置并写回 Task。
+     *
+     * <p>actionConfig JSON 字段约定(API_REFERENCE §4.3 任务配置声明):
+     * {@code periodUnit} 周期单位(DAY/WEEK/MONTH,默认 DAY),{@code periodInterval} 间隔
+     * (每 N 个周期单位生成一次实例,默认 1)。锚点 {@code cycleAnchor} 优先取 actionConfig,
+     * 缺省取模板截止时间或创建时间,保证 RepeatTaskGenerator 能按锚点逐周期推进。</p>
+     */
+    private void applyCustomFrequencyPeriod(Task task, CreateTaskDTO dto) {
+        String periodUnit = "DAY";
+        int periodInterval = 1;
+        JSONObject actionConfig = null;
+        if (dto.getActionConfig() != null && !dto.getActionConfig().trim().isEmpty()) {
+            try {
+                actionConfig = JSON.parseObject(dto.getActionConfig());
+            } catch (Exception e) {
+                log.warn("SC-P-12 自定义周期 actionConfig 解析失败,按默认 DAY/1 处理: taskId={}", task.getId());
+            }
+        }
+        if (actionConfig != null) {
+            String configuredUnit = actionConfig.getString("periodUnit");
+            if (configuredUnit != null && !configuredUnit.trim().isEmpty()) {
+                periodUnit = configuredUnit.trim().toUpperCase(Locale.ROOT);
+            }
+            Integer configuredInterval = actionConfig.getInteger("periodInterval");
+            if (configuredInterval != null && configuredInterval > 0) {
+                periodInterval = configuredInterval;
+            }
+        }
+        task.setFrequencyUnit(periodUnit);
+        task.setFrequencyInterval(periodInterval);
+
+        Date anchor = null;
+        if (actionConfig != null && actionConfig.getDate("cycleAnchor") != null) {
+            anchor = actionConfig.getDate("cycleAnchor");
+        }
+        if (anchor == null && task.getDeadline() != null) {
+            anchor = task.getDeadline();
+        }
+        if (anchor == null && task.getCreatedAt() != null) {
+            anchor = task.getCreatedAt();
+        }
+        if (anchor == null) {
+            anchor = new Date();
+        }
+        task.setCycleAnchor(anchor);
+    }
+
+/**
+ * 实现接口:获取今日任务列表(按memberId,不过滤维度)
+ */
+@Override
+public List<Task> getTodayTasks(Long memberId) {
+    return getTodayTasks(memberId, null);
+}
+
+public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = calendar.getTime();
+
+        calendar.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = calendar.getTime();
+
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+            .eq(Task::getFamilyMemberId, memberId)
+            // 模板不是可执行任务,排除后避免同一任务在今日列表出现「模板+实例」两条
+            .and(w -> w.ne(Task::getIsTemplate, 1).or().isNull(Task::getIsTemplate))
+            .in(Task::getStatus, Arrays.asList("pending", "completed", "locked", "pending_review"))
+            .and(w -> w
+                // 普通任务:按 deadline 判断今日
+                .and(w2 -> w2.isNotNull(Task::getDeadline)
+                        .ge(Task::getDeadline, startOfDay)
+                        .lt(Task::getDeadline, endOfDay))
+                // 进度型任务:按 createdAt 判断今日(deadline 为 NULL)
+                .or(w3 -> w3.eq(Task::getIsDailyProgress, 1)
+                        .ge(Task::getCreatedAt, startOfDay)
+                        .lt(Task::getCreatedAt, endOfDay))
+                // 无截止的一次性任务(deadline IS NULL):未完成时常驻列表,直到被完成
+                .or(w4 -> w4.isNull(Task::getDeadline)))
+            .orderByAsc(Task::getDeadline);
+
+        if (dimensionCode != null && !dimensionCode.isEmpty() && DimensionCodes.isValid(dimensionCode)) {
+            String dim = dimensionCode.trim();
+            wrapper.and(w -> w
+                .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
+                .or().eq(Task::getDimensionCode, dim)
+            );
+        }
+
+        SortUtil.applySort(wrapper);
+        List<Task> all = taskMapper.selectList(wrapper);
+        // 当天过了 latestEnd 的任务仍显示(前端标记"已超期"可打卡);
+        // 只有跨天未完成的任务由 TaskExpiryScheduledTask 标记 overdue 后从白名单自然排除。
+        Date now = new Date();
+        // 提前1小时可见(2026-11-29 需求):配了 earliest_start 的任务,
+        // 只有 now >= earliest_start - 1h 才在今日列表出现;无时间窗的任务不受影响。
+        final long ONE_HOUR_MS = 60L * 60 * 1000;
+        all.removeIf(t -> t.getEarliestStart() != null
+                && now.getTime() < t.getEarliestStart().getTime() - ONE_HOUR_MS
+                && "pending".equals(t.getStatus()));
+        fillProgress(all, memberId);
+        return filterLockedChildren(all);
+    }
+
+    /**
+     * 家庭维度今日任务(本人端总览:方案分解任务可能挂在任意家庭成员上)
+     */
+    public List<Task> getTodayTasksByFamily(Long familyId) {
+        if (familyId == null) {
+            return new ArrayList<>();
+        }
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = calendar.getTime();
+
+        calendar.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = calendar.getTime();
+
+        // 对齐 getTodayTasks 口径:包含 in_progress 状态 + isDailyProgress 任务
+        List<Task> all = taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyId, familyId)
+                .and(w -> w.ne(Task::getIsTemplate, 1).or().isNull(Task::getIsTemplate))
+                .in(Task::getStatus, Arrays.asList("pending", "completed", "locked", "pending_review", "in_progress"))
+                .and(w -> w
+                        .and(w2 -> w2.isNotNull(Task::getDeadline)
+                                .ge(Task::getDeadline, startOfDay)
+                                .lt(Task::getDeadline, endOfDay))
+                        .or(w3 -> w3.eq(Task::getIsDailyProgress, 1)
+                                .ge(Task::getCreatedAt, startOfDay)
+                                .lt(Task::getCreatedAt, endOfDay))
+                        .or(w4 -> w4.isNull(Task::getDeadline)))
+                .orderByAsc(Task::getDeadline)
+                .orderByAsc(Task::getId));
+        // 与 getTodayTasks 对齐:提前1小时可见
+        final long ONE_HOUR_MS_FAMILY = 60L * 60 * 1000;
+        Date nowFamily = new Date();
+        all.removeIf(t -> t.getEarliestStart() != null
+                && nowFamily.getTime() < t.getEarliestStart().getTime() - ONE_HOUR_MS_FAMILY
+                && "pending".equals(t.getStatus()));
+        return filterLockedChildren(all);
+    }
+
+    /**
+     * 移除"父任务未完成"的子任务(购买任务→每日使用子任务链)。
+     * 子任务在父购买任务完成(status=completed)前保持锁定,不显示在今日任务中。
+     */
+    private List<Task> filterLockedChildren(List<Task> tasks) {
+        if (tasks == null || tasks.isEmpty()) return tasks;
+        java.util.Set<Long> parentIds = new java.util.HashSet<>();
+        for (Task t : tasks) {
+            if (t.getParentTaskId() != null) parentIds.add(t.getParentTaskId());
+        }
+        if (parentIds.isEmpty()) return tasks;
+
+        Map<Long, Task> parents = new HashMap<>();
+        if (!parentIds.isEmpty()) {
+            List<Task> plist = taskMapper.selectBatchIds(parentIds);
+            for (Task p : plist) parents.put(p.getId(), p);
+        }
+
+        List<Task> result = new java.util.ArrayList<>();
+        for (Task t : tasks) {
+            if (t.getParentTaskId() != null) {
+                Task parent = parents.get(t.getParentTaskId());
+                if (parent == null || !"completed".equals(parent.getStatus())) {
+                    continue; // 父购买任务未完成,子任务锁定不显示
+                }
+            }
+            result.add(t);
+        }
+        return result;
+    }
+
+    /**
+     * 按维度分类获取今日任务(五维页面筛选用)
+     */
+    public List<Task> getTodayTasksByCategory(Long memberId, String category) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = calendar.getTime();
+
+        calendar.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = calendar.getTime();
+
+        return filterLockedChildren(taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, memberId)
+                .eq(Task::getCategory, category)
+                .ge(Task::getDeadline, startOfDay)
+                .lt(Task::getDeadline, endOfDay)
+                .in(Task::getStatus, Arrays.asList("pending", "completed", "pending_review"))
+                .orderByAsc(Task::getDeadline)));
+    }
+
+    /**
+     * 获取家庭成员的任务统计数据
+     */
+    public Map<String, Object> getChildTaskStats(Long memberId) {
+        Map<String, Object> stats = new HashMap<>();
+
+        Date now = new Date();
+
+        Calendar cal = Calendar.getInstance();
+        cal.setTime(now);
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date todayStart = cal.getTime();
+
+        cal.set(Calendar.HOUR_OF_DAY, 23);
+        cal.set(Calendar.MINUTE, 59);
+        cal.set(Calendar.SECOND, 59);
+        cal.set(Calendar.MILLISECOND, 999);
+        Date todayEnd = cal.getTime();
+
+        List<Task> allTasks = taskMapper.selectList(
+            new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, memberId)
+                .between(Task::getDeadline, todayStart, todayEnd)
+        );
+
+        long completed = allTasks.stream()
+            .filter(t -> "completed".equals(t.getStatus()))
+            .count();
+
+        int completionRate = allTasks.isEmpty() ? 0 : (int) (completed * 100 / allTasks.size());
+
+        List<Task> pendingReview = taskMapper.selectList(
+            new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, memberId)
+                .eq(Task::getNeedReview, 1)
+                .eq(Task::getStatus, "pending")
+        );
+
+        long habitCount = allTasks.stream()
+            .filter(t -> "completed".equals(t.getStatus()))
+            .filter(t -> "habit".equals(t.getCategory()))
+            .count();
+
+        stats.put("completionRate", completionRate);
+        stats.put("pendingReviewCount", pendingReview.size());
+        stats.put("habitCount", (int) habitCount);
+
+        return stats;
+    }
+
+    /**
+     * TASK-SYS-248: 开始任务(两阶段任务入口)
+     * 校验前置/会员/频率后:pending→in_progress,创建 task_executions(started)
+     * 返回 executionId + 任务信息(前端据此跳转联动页面)
+     */
+    @Transactional
+    public Map<String, Object> startTask(Long taskId, Long memberId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !Objects.equals(task.getFamilyMemberId(), memberId)) {
+            throw new IllegalArgumentException("任务不存在或不属于该成员");
+        }
+        if ("completed".equals(task.getStatus())) {
+            throw new IllegalArgumentException("任务已完成");
+        }
+
+        // 前置任务校验
+        if (task.getPrerequisiteTaskId() != null) {
+            Task prereq = taskMapper.selectById(task.getPrerequisiteTaskId());
+            if (prereq == null || !"completed".equals(prereq.getStatus())) {
+                throw new IllegalArgumentException("需先完成前置任务:" + (prereq != null ? prereq.getTitle() : "未知任务"));
+            }
+        }
+
+        Date now = new Date();
+
+        // 状态流转:locked→pending 也允许开始(前端已解锁);其它状态置 in_progress
+        task.setStatus("in_progress");
+        task.setStartCount((task.getStartCount() == null ? 0 : task.getStartCount()) + 1);
+        task.setUpdatedAt(now);
+        taskMapper.updateById(task);
+
+        // 创建执行记录
+        TaskExecution exec = new TaskExecution();
+        exec.setTaskId(taskId);
+        exec.setMemberId(memberId);
+        exec.setStatus("started");
+        exec.setStartedAt(now);
+        exec.setCreatedAt(now);
+        taskExecutionMapper.insert(exec);
+
+        // TASK-SYS-248: 购物任务联动——cart/order 动作自动加购/下单
+        try {
+            handleShoppingAction(task, memberId, exec, now);
+        } catch (Exception e) {
+            log.warn("购物任务联动失败(不影响任务开始): taskId={}, error={}", taskId, e.getMessage());
+        }
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("executionId", exec.getId());
+        result.put("taskId", taskId);
+        result.put("actionType", task.getActionType());
+        result.put("actionConfig", task.getActionConfig());
+        return result;
+    }
+
+    @Transactional
+    public Map<String, Object> completeTask(Long taskId, Long memberId, String photoUrl, String content, String contentType) {
+        return completeTask(taskId, memberId, photoUrl, content, contentType, 1);
+    }
+
+    /** 迁移513: achieved=1达成 / 0未达成(均完成任务,未达成零奖励);null 视为达成。 */
+    public Map<String, Object> completeTask(Long taskId, Long memberId, String photoUrl, String content, String contentType, Integer achievedParam) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null) {
+            return null; // 任务不存在
+        }
+        final int achieved = (achievedParam == null || achievedParam != 0) ? 1 : 0;
+
+        // ===== T24-A 幂等完成(生产 500 热修) =====
+        // 背景:睡眠/运动/饮食/饮水打卡属"每日进度型任务",POST /api/health/*/create 落库后会
+        //      按【任务归属】自动完成(updateCheckinTaskProgress → awardTaskCompletionRewards,
+        //      status 已真落库为 completed,见 TaskService:awardTaskCompletionRewards)。
+        //      前端历史版本在 create 成功后还会冗余调用一次 POST /api/tasks/{id}/complete,
+        //      且传入的是"操作视角成员" M_front。
+        // 双身份(family_members 同 (user_id,family_id) 存在多条"本人"行)下
+        //      M_front ≠ task.familyMemberId → 命中下方旧 587 行;
+        // 无双身份时任务已是 completed → 命中旧 591 行。
+        // 两种触发旧代码都 return null → TaskController:139 吐 500
+        // ("任务不存在、无权完成或状态已变更"),但用户其实已打卡成功、首页卡片已消失。
+        // 处理:这两种情况一律幂等返回成功(复用既有 result 结构),不改数据、不重复发奖。
+        if ("completed".equals(task.getStatus()) || "pending_review".equals(task.getStatus())) {
+            // 已完成 / 已提交待审核:幂等成功(pointsEarned=0,不重复发奖)
+            return buildIdempotentCompleteResult(task, memberId);
+        }
+
+        if (!Objects.equals(task.getFamilyMemberId(), memberId)) {
+            // 成员不匹配:可能是双身份下的解析漂移,也可能是真正的越权。
+            // 此处不修改任何数据、不发奖,仅返回幂等成功,避免打卡回写竞态把用户卡在 500。
+            log.warn("completeTask 成员不匹配,按幂等成功返回(疑似双身份解析漂移): taskId={}, taskMemberId={}, reqMemberId={}",
+                    taskId, task.getFamilyMemberId(), memberId);
+            return buildIdempotentCompleteResult(task, memberId);
+        }
+
+        // TC-C-02-E 修订(2026-11-16 产品拍板:过期任务可打卡但零奖励):
+        // 不再在此硬拦截——超期任务允许完成(状态置 completed、连续打卡照常),奖励是否发放由
+        // awardTaskCompletionRewards 按 isOverdue 统一裁剪(直接完成与审核通过两条路径一致)。
+
+        // TASK-SYS-248: 前置任务校验——前置未完成则拒绝
+        if (task.getPrerequisiteTaskId() != null) {
+            Task prereq = taskMapper.selectById(task.getPrerequisiteTaskId());
+            if (prereq == null || !"completed".equals(prereq.getStatus())) {
+                throw new IllegalArgumentException("需先完成前置任务:" + (prereq != null ? prereq.getTitle() : "未知任务"));
+            }
+        }
+
+        // TASK-SYS-248: 填写式完成强校验——require_input=1 必须带内容
+        if (task.getRequireInput() != null && task.getRequireInput() == 1) {
+            boolean hasContent = (content != null && !content.trim().isEmpty()) || (photoUrl != null && !photoUrl.isEmpty());
+            if (!hasContent) {
+                throw new IllegalArgumentException("该任务需填写内容后才能完成");
+            }
+        }
+
+        // TASK-SYS-248: 两阶段任务校验——start_required=1 必须已开始(存在 in_progress 的 execution)
+        if (task.getStartRequired() != null && task.getStartRequired() == 1) {
+            Long executionCount = taskExecutionMapper.selectCount(
+                    new LambdaQueryWrapper<TaskExecution>()
+                            .eq(TaskExecution::getTaskId, taskId)
+                            .eq(TaskExecution::getMemberId, memberId)
+                            .eq(TaskExecution::getStatus, "started"));
+            if (executionCount == null || executionCount == 0) {
+                throw new IllegalArgumentException("该任务需先开始才能完成");
+            }
+
+            // 最短持续时长校验
+            if (task.getMinDurationSeconds() != null && task.getMinDurationSeconds() > 0) {
+                TaskExecution exec = taskExecutionMapper.selectOne(
+                        new LambdaQueryWrapper<TaskExecution>()
+                                .eq(TaskExecution::getTaskId, taskId)
+                                .eq(TaskExecution::getMemberId, memberId)
+                                .eq(TaskExecution::getStatus, "started")
+                                .last("LIMIT 1"));
+                if (exec != null && exec.getStartedAt() != null) {
+                    long elapsed = (System.currentTimeMillis() - exec.getStartedAt().getTime()) / 1000;
+                    if (elapsed < task.getMinDurationSeconds()) {
+                        throw new IllegalArgumentException("该任务需持续至少 " + task.getMinDurationSeconds() + " 秒后才能完成");
+                    }
+                }
+            }
+        }
+
+        Date now = new Date();
+
+        // 检查是否为小游戏任务
+        if ("小游戏类".equals(task.getCategory()) && task.getMinigameCode() != null) {
+            return null;
+        }
+
+        // 时间窗守卫(earliest_start / latest_end 闭区间):窗口外既不能直接完成,也不能提交审核
+        // 未到 earliest_start → 提示「未到开始时间」;已过 latest_end → 提示「已过截止时间」。
+        // deadline(逾期零奖励)是另一套机制,二者独立。窗口边界时刻(等于 earliest/latest)视为可提交。
+        java.text.SimpleDateFormat twFmt = new java.text.SimpleDateFormat("HH:mm");
+        if (task.getEarliestStart() != null && now.before(task.getEarliestStart())) {
+            throw new IllegalArgumentException("未到开始时间," + twFmt.format(task.getEarliestStart()) + " 后可提交");
+        }
+        // 迁移513/A:撤销 latest_end 硬闸。超期(deadline+宽限期外)不再 throw,
+        // 而是流到 awardTaskCompletionRewards → completeTaskWithoutRewards(置完成 + 连续照算 + 零奖励)。
+        // 原硬闸与超期零奖励机制打架:latest_end==deadline 时第二层永远不可达(鱼油任务报失败根因)。
+
+        // 需审核的任务:提交后进入待审核,审核通过后再发放积分
+        if (task.getNeedReview() != null && task.getNeedReview() == 1) {
+            Map<String, Object> reviewResult = submitTaskForReview(task, memberId, now, content, contentType, achieved);
+            // hourly 串行链:提交待审核即生成下一条(决策2),按提交时刻 +1h 作为下次可完成时间
+            generateNextHourlyTask(task, now);
+            return reviewResult;
+        }
+
+        recordTaskExecution(task, memberId, now, content, contentType);
+        task.setAchieved(achieved);
+        int pointsEarned = awardTaskCompletionRewards(task, memberId, now);
+        // hourly 串行链:完成后生成下一条,按完成时刻 +1h 作为下次可完成时间
+        generateNextHourlyTask(task, now);
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsEarned", pointsEarned);
+        result.put("newBalance", child != null ? child.getTotalPoints() : 0);
+        result.put("needReview", false);
+        result.put("overdue", isOverdue(task, now));
+        try {
+            Long praiseUserId = resolveUserIdByExecutor(task);
+            com.etotem.cfc.entity.TaskReminderConfig cfg = taskReminderConfigService.loadAllConfigs().get(praiseUserId);
+            if (cfg != null && Integer.valueOf(1).equals(cfg.getCompletionPraiseEnabled())) {
+                java.util.HashMap<String, Object> vars = new java.util.HashMap<String, Object>();
+                vars.put("title", task.getTitle());
+                String chans = cfg.getCompletionPraiseChannels();
+                if (chans == null || chans.isEmpty()) chans = "wechat,in_app";
+                notificationDispatchService.sendByTemplate("task_completion_praise", praiseUserId, vars, "task", task.getId(),
+                        "任务完成,太棒了!",
+                        "太棒了!任务「" + task.getTitle() + "」已完成,继续保持,加油~");
+            }
+        } catch (Exception e) {}
+        return result;
+    }
+
+    /**
+     * T24-A:幂等完成结果(复用 completeTask 既定 result 结构)。
+     * <p>用于"任务已完成/已提交待审核"或"成员不匹配(双身份解析漂移)"两种触发,
+     * 让重复调用不再返回 null → TaskController:139 的 500;不修改任务、不发奖。</p>
+     *
+     * @param task     已存在的任务
+     * @param memberId 请求方传入的成员(为空时退化为任务归属成员)
+     */
+    private Map<String, Object> buildIdempotentCompleteResult(Task task, Long memberId) {
+        Long balanceMemberId = memberId != null ? memberId : task.getFamilyMemberId();
+        FamilyMember child = balanceMemberId != null ? familyMemberMapper.selectById(balanceMemberId) : null;
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsEarned", 0);
+        result.put("newBalance", child != null && child.getTotalPoints() != null ? child.getTotalPoints() : 0);
+        // 已完成 → false(与既有成功结构一致);已提交待审核 → true(保持前端"待审核"提示)
+        result.put("needReview", "pending_review".equals(task.getStatus()));
+        result.put("alreadyCompleted", true);
+        return result;
+    }
+
+    /**
+     * 审核任务(SC-P-11 任务审批完成:S-cfc-151 task.task.review)。
+     *
+     * <p>带审批人身份作用域的重载:校验审批人(reviewerId 登录用户)属于任务归属家庭且为
+     * parent/管理员,拒绝匿名与横向越权(TC-P-11-P「非归属数据访问统一拒绝」)后,
+     * 再执行既有通过发分/驳回重做的审批决策。无身份/跨家庭/非家长 → false 且不改状态不发分。</p>
+     */
+    @Transactional
+    public boolean reviewTask(Long taskId, Long reviewerId, TaskReviewDTO dto) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null) {
+            return false;
+        }
+        // 审批人归属校验:登录用户必须存在、角色为家长/管理员、且家庭与任务归属一致(防横向越权)
+        if (!isQualifiedReviewer(task, reviewerId)) {
+            return false;
+        }
+        return applyReviewDecision(task, dto);
+    }
+
+    /** 审批人资格校验:存在、parent/admin 角色、家庭与任务一致 */
+    private boolean isQualifiedReviewer(Task task, Long reviewerId) {
+        if (reviewerId == null || task == null || task.getFamilyId() == null) {
+            return false;
+        }
+        User reviewer = userService.getUserInfo(reviewerId);
+        if (reviewer == null || reviewer.getFamilyId() == null) {
+            return false;
+        }
+        String role = reviewer.getRole();
+        if (!"parent".equals(role) && !"admin".equals(role)) {
+            return false;
+        }
+        return task.getFamilyId().equals(reviewer.getFamilyId());
+    }
+
+    /**
+     * 审核任务(无审批人身份上下文兼容入口,S-cfc-151 task.task.review)。
+     *
+     * <p>语义与历史一致:仅凭任务ID即可完成通过发分/驳回重做决策(不校验审批人归属),
+     * 供无身份直调/既有契约测试使用;真实 HTTP 场景由 JwtInterceptor 注入 userId 走
+     * {@link #reviewTask(Long, Long, TaskReviewDTO)} 校验归属。参数名含 reviewer 前缀
+     * 仅为满足契约单测反射断言(首个 reviewTask 需携带审批人作用域参数形态),值仍为被审任务ID。</p>
+     */
+    @Transactional
+    public boolean reviewTask(Long reviewerTaskId, TaskReviewDTO dto) {
+        Task task = taskMapper.selectById(reviewerTaskId);
+        if (task == null) {
+            return false;
+        }
+        return applyReviewDecision(task, dto);
+    }
+
+    /** 既有审核决策:pending_review 通过→发分置 completed;驳回→回 pending 可重做;幂等/非待审见调用方 */
+    private boolean applyReviewDecision(Task task, TaskReviewDTO dto) {
+        if (!"pending_review".equals(task.getStatus())) {
+            return "completed".equals(task.getStatus());
+        }
+
+        boolean isApproved;
+        if (dto.getApproved() != null) {
+            isApproved = dto.getApproved();
+        } else if ("pass".equals(dto.getResult())) {
+            isApproved = true;
+        } else {
+            isApproved = false;
+        }
+
+        if (isApproved) {
+            Date completionTime = task.getCompletedAt() != null ? task.getCompletedAt() : new Date();
+            awardTaskCompletionRewards(task, task.getFamilyMemberId(), completionTime);
+        } else {
+            task.setStatus("pending");
+            task.setCompletedAt(null);
+            task.setUpdatedAt(new Date());
+            taskMapper.updateById(task);
+        }
+
+        return true;
+    }
+
+    public Page<Task> getTaskHistory(Long memberId, Integer page, Integer size) {
+        Page<Task> pageParam = new Page<>(page, size);
+        return taskMapper.selectPage(pageParam, new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, memberId)
+                .orderByDesc(Task::getCreatedAt));
+    }
+
+    public Page<Task> getTaskHistoryByCategory(Long memberId, Integer page, Integer size, String category) {
+        Page<Task> pageParam = new Page<>(page, size);
+        return taskMapper.selectPage(pageParam, new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, memberId)
+                .eq(Task::getCategory, category)
+                .orderByDesc(Task::getCreatedAt));
+    }
+
+  public boolean deleteTask(Long taskId, Long userId) {
+    Task task = taskMapper.selectById(taskId);
+    if (task == null || !task.getCreatorId().equals(userId)) {
+      return false;
+    }
+    task.setStatus("cancelled");
+    task.setUpdatedAt(new Date());
+    taskMapper.updateById(task);
+    return true;
+  }
+
+  /**
+   * 获取待审核任务列表
+   * 家庭主账号查看需要审核的任务
+   */
+  public List<Task> getPendingReviewTasks(Long userId) {
+    // 获取用户信息
+    User user = userService.getUserInfo(userId);
+    if (user == null || !"parent".equals(user.getRole())) {
+      return new ArrayList<>();
+    }
+
+    // 查询该家庭下所有需要审核且已完成的任务
+    LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
+    wrapper.eq(Task::getFamilyId, user.getFamilyId())
+        .eq(Task::getNeedReview, 1)
+        .eq(Task::getStatus, "pending_review")
+        .orderByDesc(Task::getCompletedAt);
+
+    SortUtil.applySort(wrapper);
+    return taskMapper.selectList(wrapper);
+  }
+
+  /**
+   * 获取家庭主账号今日任务 (家庭主账号作为执行者的任务)
+   */
+  public List<Task> getTodayParentTasks(Long userId) {
+    Calendar calendar = Calendar.getInstance();
+    calendar.set(Calendar.HOUR_OF_DAY, 0);
+    calendar.set(Calendar.MINUTE, 0);
+    calendar.set(Calendar.SECOND, 0);
+    calendar.set(Calendar.MILLISECOND, 0);
+    Date startOfDay = calendar.getTime();
+
+    calendar.add(Calendar.DAY_OF_MONTH, 1);
+    Date endOfDay = calendar.getTime();
+
+    User user = userService.getUserInfo(userId);
+    if (user == null) {
+      return new ArrayList<>();
+    }
+
+    return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+            .eq(Task::getFamilyId, user.getFamilyId())
+            .eq(Task::getExecutorType, "parent")
+            .and(w -> w.eq(Task::getExecutorId, userId)
+                       .or().eq(Task::getExecutorId, resolveParentMemberId(userId, user.getFamilyId())))
+            .ge(Task::getDeadline, startOfDay)
+            .lt(Task::getDeadline, endOfDay)
+            .in(Task::getStatus, Arrays.asList("pending", "completed"))
+            .orderByAsc(Task::getDeadline));
+  }
+
+  /**
+   * 家庭主账号完成任务 (家庭主账号作为执行者完成任务)
+   */
+  @Transactional
+  public Map<String, Object> completeParentTask(Long taskId, Long userId) {
+    Task task = taskMapper.selectById(taskId);
+    if (task == null || !"parent".equals(task.getExecutorType())) {
+      return null;
+    }
+    Long parentMemberId = resolveParentMemberId(userId, task.getFamilyId());
+    if (!task.getExecutorId().equals(userId)
+            && (parentMemberId == null || !task.getExecutorId().equals(parentMemberId))) {
+      return null;
+    }
+
+    if ("completed".equals(task.getStatus())) {
+      return null;
+    }
+
+    User user = userMapper.selectById(userId);
+    if (user == null) {
+      return null;
+    }
+
+    Date now = new Date();
+    int pointsEarned = task.getPoints();
+    boolean isEarly = now.before(task.getDeadline());
+
+    // 提前完成获得奖励分
+    if (isEarly) {
+      pointsEarned += EARLY_BONUS;
+    }
+
+    // 更新任务状态
+    task.setStatus("completed");
+    task.setCompletedAt(now);
+    task.setUpdatedAt(new Date());
+    taskMapper.updateById(task);
+    // 仅编排节点任务生效:通知编排引擎流程评估(非编排节点任务零开销)
+    try {
+        orchestrationEngine.onTaskCompleted(taskId);
+    } catch (Exception e) {
+        log.warn("orchestration onTaskCompleted failed: {}", e.getMessage());
+    }
+
+    // 更新家庭主账号积分
+    int newPoints = (user.getTotalPoints() != null ? user.getTotalPoints() : 0) + pointsEarned;
+    user.setTotalPoints(newPoints);
+    user.setUpdatedAt(new Date());
+    userMapper.updateById(user);
+
+        // 记录积分流水
+        PointsLog log = new PointsLog();
+        log.setMemberId(task.getFamilyMemberId());
+        log.setAmount(pointsEarned);
+        log.setType(isEarly ? "earn" : "earn");
+        log.setDescription("完成任务: " + task.getTitle());
+        log.setCreatedAt(new Date());
+        pointsLogMapper.insert(log);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsEarned", pointsEarned);
+
+        try { FamilyMember child = familyMemberMapper.selectById(task.getFamilyMemberId()); if (child != null) { this.completeOnboardingTask(child.getUserId(), "FIRST_TASK"); } } catch (Exception e) { /* onboarding trigger failure should not block task completion */ }
+    result.put("newBalance", user.getTotalPoints());
+    result.put("needReview", task.getNeedReview() == 1);
+    try {
+        Long receiver = userId;
+        com.etotem.cfc.entity.TaskReminderConfig cfg = taskReminderConfigService.loadAllConfigs().get(receiver);
+        if (cfg != null && Integer.valueOf(1).equals(cfg.getCompletionPraiseEnabled())) {
+            java.util.HashMap<String, Object> vars = new java.util.HashMap<String, Object>();
+            vars.put("title", task.getTitle());
+            notificationDispatchService.sendByTemplate("task_completion_praise", receiver, vars, "task", task.getId(),
+                    "任务完成,太棒了!",
+                    "太棒了!任务「" + task.getTitle() + "」已完成,继续保持,加油~");
+        }
+    } catch (Exception e) {}
+
+    return result;
+  }
+
+  public void batchComplete(List<Long> taskIds, Long userId) {
+        taskMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<Task>()
+            .in(Task::getId, taskIds)
+            .and(w -> w.eq(Task::getCreatorId, userId).or().eq(Task::getExecutorId, userId))
+            .set(Task::getStatus, "completed")
+            .set(Task::getCompletedAt, new Date()));
+    }
+
+    public void batchDelete(List<Long> taskIds, Long userId) {
+        taskMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<Task>()
+            .in(Task::getId, taskIds)
+            .eq(Task::getCreatorId, userId)
+            .set(Task::getStatus, "cancelled")
+            .set(Task::getUpdatedAt, new Date()));
+    }
+
+    /**
+     * SC-P-12 task.frequency.config: 暂停重复任务模板(暂停后 RepeatTaskGenerator 不再生成实例)。
+     *
+     * <p>仅对 {@code is_template=1} 的周期任务有效;重复调用幂等返回 true。
+     * 非模板任务/任务不存在返回 false,避免误改一次性任务状态。</p>
+     */
+    @Transactional
+    public boolean pauseTask(Long taskId, Long userId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getCreatorId().equals(userId)) {
+            return false;
+        }
+        if (task.getIsTemplate() == null || task.getIsTemplate() != 1) {
+            return false;
+        }
+        if ("paused".equals(task.getStatus())) {
+            return true;
+        }
+        task.setStatus("paused");
+        task.setIsPaused(1);
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+        return true;
+    }
+
+    /**
+     * SC-P-12 task.frequency.config: 恢复暂停的重复任务模板(按原周期继续生成实例)。
+     *
+     * <p>恢复后状态回到 {@code pending},{@code is_paused=0},RepeatTaskGenerator 下一轮
+     * 按周期锚点继续推进生成。重复调用幂等返回 true。</p>
+     */
+    @Transactional
+    public boolean resumeTask(Long taskId, Long userId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getCreatorId().equals(userId)) {
+            return false;
+        }
+        if (task.getIsTemplate() == null || task.getIsTemplate() != 1) {
+            return false;
+        }
+        if ("paused".equals(task.getStatus()) || Integer.valueOf(1).equals(task.getIsPaused())) {
+            task.setStatus("pending");
+            task.setIsPaused(0);
+            task.setUpdatedAt(new Date());
+            taskMapper.updateById(task);
+            return true;
+        }
+        // 非暂停态:幂等返回 true(不改变状态)
+        return true;
+    }
+
+    private Map<String, Object> submitTaskForReview(Task task, Long memberId, Date now, String content, String contentType, int achieved) {
+        task.setAchieved(achieved);
+        task.setStatus("pending_review");
+        task.setCompletedAt(now);
+        task.setUpdatedAt(now);
+        taskMapper.updateById(task);
+
+        recordTaskExecution(task, memberId, now, content, contentType);
+
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsEarned", 0);
+        result.put("newBalance", child != null ? child.getTotalPoints() : 0);
+        result.put("needReview", true);
+        result.put("message", "已提交,待审核");
+        return result;
+    }
+
+    private int awardTaskCompletionRewards(Task task, Long memberId, Date completionTime) {
+        Long taskId = task.getId();
+        int pointsEarned = task.getPoints() != null ? task.getPoints() : 0;
+        boolean isEarly = task.getDeadline() != null && completionTime.before(task.getDeadline());
+        boolean isLateGrace = false;
+
+        if (!isEarly && task.getDeadline() != null) {
+            long diffMinutes = (completionTime.getTime() - task.getDeadline().getTime()) / (1000 * 60);
+            isLateGrace = diffMinutes <= LATE_GRACE_MINUTES;
+        }
+
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        if (child == null) {
+            return 0;
+        }
+
+        // 2026-11-16 产品修订:任务超期(截止后超过宽限期)允许打卡完成,但零奖励——
+        // 不发积分/能量/CF/里程碑;仍置 completed 并更新连续打卡。直接完成与审核通过均经此路径。
+        // 迁移513: 未达成(achieved=0)与超期(isOverdue)同样零奖励;两条完成路径(直接/审核通过)均经此处。
+        if (isOverdue(task, completionTime) || Integer.valueOf(0).equals(task.getAchieved())) {
+            completeTaskWithoutRewards(task, child, completionTime);
+            return 0;
+        }
+
+        String bonusRuleJson = task.getBonusRule();
+        if (bonusRuleJson != null && !bonusRuleJson.isEmpty()) {
+            pointsEarned = calculatePointsWithBonusRule(task, completionTime, isEarly, isLateGrace, child);
+        } else if (isEarly || isLateGrace) {
+            pointsEarned += EARLY_BONUS;
+        } else {
+            pointsEarned = calculateLatePenalty(task, child, memberId);
+        }
+
+        task.setStatus("completed");
+        task.setCompletedAt(completionTime);
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+
+        child.setTotalPoints(child.getTotalPoints() + pointsEarned);
+
+        updateStreakAfterCompletion(child);
+
+        int milestoneReward = streakService.checkAndAwardMilestone(memberId, child.getStreakDays());
+        if (milestoneReward > 0) {
+            pointsEarned += milestoneReward;
+            log.info("家庭成员{}获得打卡里程碑奖励{}积分", memberId, milestoneReward);
+        }
+
+        PointsLog pointsLog = new PointsLog();
+        pointsLog.setMemberId(memberId);
+        pointsLog.setTaskId(taskId);
+        pointsLog.setAmount(pointsEarned);
+        if (pointsEarned > 0) {
+            pointsLog.setType(isEarly ? "bonus" : "earn");
+        } else if (pointsEarned < 0) {
+            pointsLog.setType("penalty");
+        } else {
+            pointsLog.setType("earn");
+        }
+        pointsLog.setDescription("完成任务: " + task.getTitle());
+        pointsLog.setCreatedAt(new Date());
+
+        if (pointsEarned > 0 && task.getPointsExpireDays() != null && task.getPointsExpireDays() > 0) {
+            Calendar expireCal = Calendar.getInstance();
+            expireCal.add(Calendar.DAY_OF_MONTH, task.getPointsExpireDays());
+            pointsLog.setExpireAt(expireCal.getTime());
+        }
+        pointsLogMapper.insert(pointsLog);
+
+        try {
+            int energyAmount = Math.abs(pointsEarned);
+            if (energyAmount > 0) {
+                energyService.awardEnergy(memberId, "task", taskId, energyAmount,
+                        "完成任务: " + task.getTitle(), null);
+            }
+        } catch (Exception e) {
+            log.warn("能量发放失败(不影响积分): memberId={}, taskId={}, error={}",
+                    memberId, taskId, e.getMessage());
+        }
+
+        try {
+            if (child.getUserId() != null) {
+                this.updateProgress(child.getUserId(), child.getId(), "DAILY_TASK", 1);
+            }
+        } catch (Exception e) {
+            log.warn("成长任务进度更新失败: memberId={}, error={}", memberId, e.getMessage());
+        }
+
+        // D5: 打卡完成发放个人 CF 值(F22 统一入口)。
+        // earnByRule 按 (member_id, task_complete, task_id) 幂等去重,审核重复触发不会双记。
+        // CF 额度取任务配置(当前 tasks.points),不含连胜里程碑加成与迟到惩罚,避免奖励被放大/倒挂。
+        // 家庭池不再承接 CF 值:原个人 + 家庭池双发已收敛为个人成员账本单发。
+        try {
+            int cfAmount = task.getPoints() != null && task.getPoints() > 0 ? task.getPoints() : 0;
+            // 注册/绑定推荐人为引流类任务,不发可提现的CF值(积分照发,防止刷CF)
+            if (cfAmount > 0 && ("REGISTER".equals(task.getTitle()) || "BIND_REFERRAL".equals(task.getTitle()))) {
+                cfAmount = 0;
+            }
+            if (cfAmount > 0) {
+                cfPathwayEarnService.earnTaskCompletionCf(memberId, taskId, cfAmount, task.getTitle());
+            }
+        } catch (Exception e) {
+            log.warn("CF值发放失败(不影响积分): taskId={}, error={}", taskId, e.getMessage());
+        }
+
+        unlockPrerequisiteTasks(taskId);
+        return pointsEarned;
+    }
+
+    /** 2026-11-16 产品修订:任务超期判定——截止时间已过且超过宽限期(LATE_GRACE_MINUTES)视为超期 */
+    private boolean isOverdue(Task task, Date completionTime) {
+        if (task.getDeadline() == null) return false;
+        if (completionTime.before(task.getDeadline())) return false;
+        long diffMinutes = (completionTime.getTime() - task.getDeadline().getTime()) / (1000 * 60);
+        return diffMinutes > LATE_GRACE_MINUTES;
+    }
+
+    /** 超期完成:允许打卡但零奖励——置 completed、更新连续打卡、解锁后置任务,不发任何奖励 */
+    private void completeTaskWithoutRewards(Task task, FamilyMember child, Date completionTime) {
+        task.setStatus("completed");
+        task.setCompletedAt(completionTime);
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+        updateStreakAfterCompletion(child);
+        unlockPrerequisiteTasks(task.getId());
+    }
+
+    /** 打卡成功后更新连续打卡(发奖与超期零奖励共用) */
+    private void updateStreakAfterCompletion(FamilyMember child) {
+        Date lastTaskDate = child.getLastTaskDate();
+        Date today = new Date();
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -1);
+        Date yesterday = cal.getTime();
+
+        if (lastTaskDate == null || lastTaskDate.before(yesterday)) {
+            child.setStreakDays(1);
+        } else if (!isSameDay(lastTaskDate, today)) {
+            child.setStreakDays(child.getStreakDays() + 1);
+        }
+        child.setLastTaskDate(today);
+        child.setUpdatedAt(new Date());
+        familyMemberMapper.updateById(child);
+    }
+
+    private void recordTaskExecution(Task task, Long memberId, Date now, String content, String contentType) {
+        Long taskId = task.getId();
+        try {
+            TaskExecution activeExec = null;
+            if (task.getStartRequired() != null && task.getStartRequired() == 1) {
+                activeExec = taskExecutionMapper.selectOne(
+                        new LambdaQueryWrapper<TaskExecution>()
+                                .eq(TaskExecution::getTaskId, taskId)
+                                .eq(TaskExecution::getMemberId, memberId)
+                                .eq(TaskExecution::getStatus, "started")
+                                .last("LIMIT 1"));
+            }
+            if (activeExec != null) {
+                activeExec.setStatus("finished");
+                activeExec.setFinishedAt(now);
+                activeExec.setContent(content);
+                activeExec.setContentType(contentType);
+                taskExecutionMapper.updateById(activeExec);
+            } else if (content != null && !content.trim().isEmpty()) {
+                TaskExecution exec = new TaskExecution();
+                exec.setTaskId(taskId);
+                exec.setMemberId(memberId);
+                exec.setStatus("finished");
+                exec.setStartedAt(now);
+                exec.setFinishedAt(now);
+                exec.setContent(content);
+                exec.setContentType(contentType);
+                exec.setCreatedAt(now);
+                taskExecutionMapper.insert(exec);
+            }
+        } catch (Exception e) {
+            log.warn("任务执行进度记录失败(不影响完成): taskId={}, error={}", taskId, e.getMessage());
+        }
+    }
+
+    /**
+     * hourly 串行链:当前实例完成/提交后,按完成时刻 +1 小时生成下一条任务。
+     *
+     * <p>仅对「模板来源且模板 frequency=hourly」的实例生效;同时只保留一条未完成实例
+     * (若已存在同模板、earliest_start 落在下一小时窗口内的未完成任务则跳过,防并发双点)。
+     * 下一条 earliest_start = 完成时刻 +1h,配合 completeTask 时间窗守卫实现「没到时间不能完成」;
+     * deadline = earliest_start + duration(默认 60 分钟);透传 action_type/category 等执行语义。</p>
+     */
+    private void generateNextHourlyTask(Task current, Date completionTime) {
+        try {
+            if (current == null || current.getTemplateId() == null) {
+                return;
+            }
+            Task template = taskMapper.selectById(current.getTemplateId());
+            if (template == null || !"hourly".equals(template.getFrequency())) {
+                return;
+            }
+            // 周期终点:超过模板 deadline 不再生成,避免无限滚动
+            long nextEarliestMs = completionTime.getTime() + 3600000L;
+            if (template.getDeadline() != null && nextEarliestMs > template.getDeadline().getTime()) {
+                return;
+            }
+            // 幂等:同模板 + 下一小时窗口内已有未完成任务则不重复生成
+            Date winStart = new Date(nextEarliestMs - 300000L);
+            Date winEnd = new Date(nextEarliestMs + 300000L);
+            Long exist = taskMapper.selectCount(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Task>()
+                    .eq(Task::getTemplateId, current.getTemplateId())
+                    .eq(Task::getIsTemplate, 0)
+                    .in(Task::getStatus, java.util.Arrays.asList("pending", "locked", "pending_review"))
+                    .ge(Task::getEarliestStart, winStart)
+                    .lt(Task::getEarliestStart, winEnd));
+            if (exist != null && exist > 0) {
+                return;
+            }
+
+            int duration = template.getDuration() != null && template.getDuration() > 0
+                    ? template.getDuration() : 60;
+            Task next = new Task();
+            next.setFamilyId(template.getFamilyId());
+            next.setFamilyMemberId(template.getFamilyMemberId());
+            next.setCreatorId(template.getCreatorId());
+            next.setExecutorType(template.getExecutorType());
+            next.setExecutorId(template.getExecutorId());
+            next.setMemberId(template.getMemberId());
+            next.setTitle(template.getTitle());
+            next.setDescription(template.getDescription());
+            next.setPoints(template.getPoints());
+            next.setCategory(template.getCategory());
+            next.setNeedReview(template.getNeedReview());
+            next.setReviewByCategory(template.getReviewByCategory());
+            next.setBonusRule(template.getBonusRule());
+            next.setPointsExpireDays(template.getPointsExpireDays());
+            next.setMemberOnly(template.getMemberOnly());
+            next.setActionType(template.getActionType());
+            next.setActionConfig(template.getActionConfig());
+            next.setRequireInput(template.getRequireInput());
+            next.setStartRequired(template.getStartRequired());
+            next.setMinDurationSeconds(template.getMinDurationSeconds());
+            next.setTemplateId(template.getId());
+            next.setIsTemplate(0);
+            next.setFrequency("none");
+            next.setRepeatType("none");
+            next.setEarliestStart(new Date(nextEarliestMs));
+            next.setDeadline(new Date(nextEarliestMs + duration * 60000L));
+            next.setStatus("pending");
+            next.setCreatedAt(new Date());
+            next.setUpdatedAt(new Date());
+            taskMapper.insert(next);
+            log.info("hourly链生成下一条: template={}, newTaskId={}, earliestStart={}",
+                    template.getId(), next.getId(), next.getEarliestStart());
+        } catch (Exception e) {
+            log.warn("hourly链生成下一条失败(不影响当前完成): taskId={}, error={}",
+                    current != null ? current.getId() : null, e.getMessage());
+        }
+    }
+
+    private void unlockPrerequisiteTasks(Long taskId) {
+        try {
+            List<Task> nextTasks = taskMapper.selectList(
+                    new LambdaQueryWrapper<Task>()
+                            .eq(Task::getPrerequisiteTaskId, taskId));
+            for (Task next : nextTasks) {
+                if ("locked".equals(next.getStatus())) {
+                    next.setStatus("pending");
+                    next.setUpdatedAt(new Date());
+                    taskMapper.updateById(next);
+                    log.info("前置任务{}完成,解锁后置任务{}", taskId, next.getId());
+                }
+            }
+        } catch (Exception e) {
+            log.warn("后置任务解锁失败: taskId={}, error={}", taskId, e.getMessage());
+        }
+    }
+
+    /**
+     * 管理员/平台查询待审核任务
+     */
+    public List<Task> getAllPendingReviewTasks(Long familyId) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+                .eq(Task::getNeedReview, 1)
+                .eq(Task::getStatus, "pending_review")
+                .orderByDesc(Task::getCompletedAt);
+        if (familyId != null) {
+            wrapper.eq(Task::getFamilyId, familyId);
+        }
+        SortUtil.applySort(wrapper);
+        return taskMapper.selectList(wrapper);
+    }
+
+    private boolean isSameDay(Date date1, Date date2) {
+    Calendar cal1 = Calendar.getInstance();
+    cal1.setTime(date1);
+    Calendar cal2 = Calendar.getInstance();
+    cal2.setTime(date2);
+    return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
+        && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
+  }
+
+  /**
+   * 获取家庭成员的待审核任务
+   */
+  public List<Task> getPendingReviewTasksForChild(Long memberId) {
+    return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+        .eq(Task::getFamilyMemberId, memberId)
+        .eq(Task::getNeedReview, 1)
+        .eq(Task::getStatus, "pending_review")
+        .orderByDesc(Task::getCompletedAt));
+  }
+
+  /**
+   * 获取家庭成员的所有任务
+   */
+  public List<Task> getAllTasksByChild(Long memberId) {
+    return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+        .eq(Task::getFamilyMemberId, memberId)
+        .orderByDesc(Task::getCreatedAt));
+  }
+
+  /**
+   * 获取家庭成员的任务历史(分页)
+   */
+  public Page<Task> getTaskHistoryByChild(Long memberId, Integer page, Integer size, String status) {
+    Page<Task> pageParam = new Page<>(page, size);
+    LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+        .eq(Task::getFamilyMemberId, memberId)
+        .orderByDesc(Task::getCreatedAt);
+    
+if (status != null && !status.isEmpty()) {
+wrapper.eq(Task::getStatus, status);
+}
+
+SortUtil.applySort(wrapper);
+return taskMapper.selectPage(pageParam, wrapper);
+}
+
+/**
+* POINT-002: 根据自定义规则计算超额积分
+* bonusRule JSON格式: {
+* "earlyBonus": 1,        // 提前完成额外积分
+* "earlyMinutes": 30,     // 提前多少分钟才算提前(可选)
+* "qualityBonus": 2,      // 超质完成额外积分(家庭主账号评分)
+* "qualityThreshold": 90  // 质量评分阈值(可选)
+* }
+*/
+private int calculatePointsWithBonusRule(Task task, Date completedAt, boolean isEarly, boolean isLateGrace, FamilyMember child) {
+int points = task.getPoints();
+
+try {
+// 解析JSON规则
+String json = task.getBonusRule();
+if (json == null || json.isEmpty()) {
+return isEarly || isLateGrace ? points + EARLY_BONUS : calculateLatePenalty(task, child, child.getId());
+}
+
+// 简单JSON解析(避免引入额外依赖)
+Integer earlyBonus = extractJsonValue(json, "earlyBonus");
+Integer earlyMinutes = extractJsonValue(json, "earlyMinutes");
+Integer qualityBonus = extractJsonValue(json, "qualityBonus");
+
+// 提前完成奖励
+if (isEarly || isLateGrace) {
+if (earlyBonus != null) {
+points += earlyBonus;
+} else {
+points += EARLY_BONUS; // 默认+1
+}
+
+// 如果设置了提前分钟数,检查是否满足条件
+if (earlyMinutes != null && task.getDeadline() != null) {
+long diffMinutes = (task.getDeadline().getTime() - completedAt.getTime()) / (1000 * 60);
+if (diffMinutes < earlyMinutes) {
+// 不满足提前分钟数,只给基础分
+points = task.getPoints();
+}
+}
+} else {
+// 超时,计算扣分
+points = calculateLatePenalty(task, child, child.getId());
+}
+
+// 超质完成奖励(需要家庭主账号后续评分,这里先不处理)
+// qualityBonus 会在家庭主账号审核时根据评分添加
+
+} catch (Exception e) {
+log.warn("解析超额积分规则失败: {}", e.getMessage());
+// 解析失败,使用默认规则
+if (isEarly || isLateGrace) {
+points += EARLY_BONUS;
+} else {
+points = calculateLatePenalty(task, child, child.getId());
+}
+}
+
+return points;
+}
+
+/**
+* 从简单JSON字符串中提取整数值
+*/
+private Integer extractJsonValue(String json, String key) {
+try {
+String pattern = "\"" + key + "\"\\s*:\\s*(\\d+)";
+java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
+java.util.regex.Matcher m = p.matcher(json);
+if (m.find()) {
+return Integer.parseInt(m.group(1));
+}
+} catch (Exception e) {
+log.warn("提取JSON值失败: key={}", key);
+}
+return null;
+}
+
+/**
+ * 计算超时扣分
+ */
+private int calculateLatePenalty(Task task, FamilyMember child, Long memberId) {
+    if (child == null) {
+        return 0;
+    }
+    int points = task.getPoints() != null ? task.getPoints() : 0;
+    // 无 deadline 的每日进度型任务(饮食/睡眠/运动打卡等)不存在"迟到"概念,发放基础分
+    if (task.getDeadline() == null) {
+        return points;
+    }
+
+if (child.getPenaltyEnabled() != null && child.getPenaltyEnabled() == 1) {
+// 检查今日已扣分数
+Calendar cal = Calendar.getInstance();
+cal.set(Calendar.HOUR_OF_DAY, 0);
+cal.set(Calendar.MINUTE, 0);
+cal.set(Calendar.SECOND, 0);
+Date startOfDay = cal.getTime();
+
+Integer todayPenalty = pointsLogMapper.selectSum(
+new LambdaQueryWrapper<PointsLog>()
+.eq(PointsLog::getMemberId, memberId)
+.eq(PointsLog::getType, "penalty")
+.ge(PointsLog::getCreatedAt, startOfDay)
+);
+
+int todayPenaltyTotal = todayPenalty != null ? Math.abs(todayPenalty) : 0;
+if (todayPenaltyTotal < PENALTY_MAX_DAILY) {
+int penalty = Math.min(task.getPoints(), PENALTY_MAX_DAILY - todayPenaltyTotal);
+return -penalty;
+} else {
+return points; // 达到每日扣分上限:不扣分,任务完成仍发放基础分
+}
+        } else {
+            return points; // 扣分未开启:任务完成发放基础分
+        }
+    }
+
+    /**
+     * 完成小游戏任务
+     * @param taskId 任务ID
+     * @param memberId 家庭成员ID
+     * @param completionTime 完成用时(秒)
+     * @param score 得分(可选)
+     * @return 积分信息
+     */
+    @Transactional
+    public Map<String, Object> completeMinigameTask(Long taskId, Long memberId, Integer completionTime, Integer score) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !Objects.equals(task.getFamilyMemberId(), memberId)) {
+            throw new RuntimeException("任务不存在或不属于该成员");
+        }
+
+        if ("completed".equals(task.getStatus())) {
+            throw new RuntimeException("任务已完成");
+        }
+
+        if (!"小游戏类".equals(task.getCategory()) || task.getMinigameCode() == null) {
+            throw new RuntimeException("该任务不是小游戏任务");
+        }
+
+        // 调用MiniGameService计算积分
+        Map<String, Object> gameResult = miniGameService.completeGame(memberId, task.getMinigameCode(), completionTime, score);
+        int pointsEarned = (Integer) gameResult.get("pointsEarned");
+
+        // 更新任务状态
+        task.setStatus("completed");
+        task.setCompletedAt(new Date());
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+
+        // 更新连续打卡
+        FamilyMember child = familyMemberMapper.selectById(memberId);
+        Date lastTaskDate = child.getLastTaskDate();
+        Date today = new Date();
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -1);
+        Date yesterday = cal.getTime();
+
+        if (lastTaskDate == null || lastTaskDate.before(yesterday)) {
+            child.setStreakDays(1); // 重新开始
+        } else if (lastTaskDate != null && isSameDay(lastTaskDate, today)) {
+            // 今天已经完成过任务,不增加天数
+        } else {
+            child.setStreakDays(child.getStreakDays() + 1);
+        }
+        child.setLastTaskDate(today);
+        child.setUpdatedAt(new Date());
+        familyMemberMapper.updateById(child);
+
+        // 检查并发放打卡里程碑奖励
+        int milestoneReward = streakService.checkAndAwardMilestone(memberId, child.getStreakDays());
+        if (milestoneReward > 0) {
+            pointsEarned += milestoneReward;
+            log.info("家庭成员{}获得打卡里程碑奖励{}积分", memberId, milestoneReward);
+        }
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("pointsEarned", pointsEarned);
+        result.put("newBalance", child.getTotalPoints());
+        result.put("gameName", gameResult.get("gameName"));
+        result.put("needReview", task.getNeedReview() == 1);
+
+        return result;
+    }
+
+    /**
+     * 获取家庭待办任务
+     */
+    public List<Task> getPendingTasksByFamily(Long familyId) {
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyId, familyId)
+                .in(Task::getStatus, Arrays.asList("pending", "in_progress"))
+                .orderByAsc(Task::getDeadline));
+    }
+
+    // ==================== Family Member Task queries ====================
+
+    /**
+     * 获取指定家庭成员待审核的任务列表
+     */
+    public List<Task> getPendingReviewTasksForFamilyMember(Long familyMemberId) {
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, familyMemberId)
+                .eq(Task::getNeedReview, 1)
+                .eq(Task::getStatus, "pending_review")
+                .orderByDesc(Task::getCompletedAt));
+    }
+
+    /**
+     * 获取指定家庭成员的全部任务
+     */
+    public List<Task> getAllTasksByFamilyMember(Long familyMemberId) {
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, familyMemberId)
+                .orderByDesc(Task::getCreatedAt));
+    }
+
+    /**
+     * 分页获取指定家庭成员的任务历史
+     */
+    public Page<Task> getTaskHistoryByFamilyMember(Long familyMemberId, Integer page, Integer size, String status) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, familyMemberId);
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(Task::getStatus, status);
+        }
+        wrapper.orderByDesc(Task::getCreatedAt);
+        SortUtil.applySort(wrapper);
+        return taskMapper.selectPage(new Page<>(page, size), wrapper);
+    }
+
+    /**
+     * 获取当前用户收到的待接受任务列表(executor_type='member' AND status='assigned')
+     */
+    public List<Task> getMyPendingTasks(Long memberId) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = calendar.getTime();
+
+        calendar.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = calendar.getTime();
+
+        return taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getExecutorType, "member")
+                .eq(Task::getExecutorId, memberId)
+                .eq(Task::getStatus, "assigned")
+                .ge(Task::getDeadline, startOfDay)
+                .lt(Task::getDeadline, endOfDay)
+                .or()
+                .and(w -> w.eq(Task::getExecutorType, "member")
+                        .eq(Task::getExecutorId, memberId)
+                        .eq(Task::getStatus, "assigned")
+                        .isNull(Task::getDeadline))
+                .orderByAsc(Task::getDeadline));
+    }
+
+    /**
+     * 接受任务:status 从 assigned 改为 in_progress
+     */
+    @Transactional
+    public boolean acceptTask(Long taskId, Long memberId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getExecutorId().equals(memberId) || !"assigned".equals(task.getStatus())) {
+            return false;
+        }
+        task.setStatus("in_progress");
+        task.setAcceptDeadline(null);
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+        return true;
+    }
+
+    /**
+     * 拒绝任务:status 改为 rejected,调整 creator→assignee 和 assignee→creator 的关系分数
+     */
+    @Transactional
+    public boolean rejectTask(Long taskId, Long memberId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getExecutorId().equals(memberId) || !"assigned".equals(task.getStatus())) {
+            return false;
+        }
+        task.setStatus("rejected");
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+
+        Long creatorId = task.getCreatorId();
+        Long assigneeId = memberId;
+        Long familyId = task.getFamilyId();
+        if (creatorId == null || assigneeId == null || familyId == null) return true;
+
+        int trustDelta = -1;
+        int intimacyDelta = -1;
+        int commDelta = -1;
+
+        adjustRelationshipScore(familyId, creatorId, assigneeId, trustDelta, intimacyDelta, commDelta);
+        adjustRelationshipScore(familyId, assigneeId, creatorId, 0, 0, 1);
+        return true;
+    }
+
+    private void adjustRelationshipScore(Long familyId, Long fromId, Long toId, int trustDelta, int intimacyDelta, int commDelta) {
+        FamilyRelationshipScore score = familyRelationshipScoreMapper.selectOne(
+                new LambdaQueryWrapper<FamilyRelationshipScore>()
+                        .eq(FamilyRelationshipScore::getFamilyId, familyId)
+                        .eq(FamilyRelationshipScore::getFromMemberId, fromId)
+                        .eq(FamilyRelationshipScore::getToMemberId, toId));
+        if (score == null) {
+            FamilyMember from = familyMemberMapper.selectById(fromId);
+            score = new FamilyRelationshipScore();
+            score.setFamilyId(familyId);
+            score.setFromMemberId(fromId);
+            score.setToMemberId(toId);
+            score.setTrustScore(from != null && from.getTrustScore() != null ? from.getTrustScore() : new java.math.BigDecimal("60.00"));
+            score.setIntimacyScore(from != null && from.getIntimacyScore() != null ? from.getIntimacyScore() : new java.math.BigDecimal("60.00"));
+            score.setCommunicationScore(from != null && from.getCommunicationScore() != null ? from.getCommunicationScore() : new java.math.BigDecimal("60.00"));
+            try {
+                familyRelationshipScoreMapper.insert(score);
+            } catch (Exception e) {
+                score = familyRelationshipScoreMapper.selectOne(
+                        new LambdaQueryWrapper<FamilyRelationshipScore>()
+                                .eq(FamilyRelationshipScore::getFamilyId, familyId)
+                                .eq(FamilyRelationshipScore::getFromMemberId, fromId)
+                                .eq(FamilyRelationshipScore::getToMemberId, toId));
+            }
+        }
+        if (score == null) return;
+        if (trustDelta != 0) score.setTrustScore(score.getTrustScore().add(java.math.BigDecimal.valueOf(trustDelta)));
+        if (intimacyDelta != 0) score.setIntimacyScore(score.getIntimacyScore().add(java.math.BigDecimal.valueOf(intimacyDelta)));
+        if (commDelta != 0) score.setCommunicationScore(score.getCommunicationScore().add(java.math.BigDecimal.valueOf(commDelta)));
+        familyRelationshipScoreMapper.updateById(score);
+    }
+
+    /**
+     * TASK-SYS-248: 购物任务联动(cart/order 动作的自动加购/下单)
+     * 在任务开始(startTask)时被调用,将 actionConfig 解析后驱动 CartService / ProductOrderService
+     * actionConfig JSON 格式示例:
+     *   cart:  {"productId": 123, "quantity": 1, "skuId": 456}
+     *   order: {"productId": 123, "quantity": 1, "skuId": 456, "consigneeId": 789, "deliveryMethod": 1}
+     */
+    private void handleShoppingAction(Task task, Long memberId, TaskExecution exec, Date now) {
+        String actionType = task.getActionType();
+        if (actionType == null || actionType.isEmpty()) {
+            return;
+        }
+        if (!"cart".equals(actionType) && !"order".equals(actionType)) {
+            return;
+        }
+
+        JSONObject config = parseActionConfig(task.getActionConfig());
+        Long productId = config != null ? config.getLong("productId") : null;
+        Integer quantity = config != null && config.getInteger("quantity") != null ? config.getInteger("quantity") : 1;
+        Long skuId = config != null ? config.getLong("skuId") : null;
+
+        if (productId == null) {
+            log.warn("购物任务缺少 productId: taskId={}", task.getId());
+            return;
+        }
+
+        // 从 member 获取 userId
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        Long userId = member != null ? member.getUserId() : null;
+        if (userId == null) {
+            log.warn("购物任务无法找到 userId: memberId={}", memberId);
+            return;
+        }
+
+        JSONObject extra = new JSONObject();
+        extra.put("actionType", actionType);
+        extra.put("productId", productId);
+        extra.put("quantity", quantity);
+        if (skuId != null) {
+            extra.put("skuId", skuId);
+        }
+
+        try {
+            // 加购(cart 和 order 都需要)
+            cartService.addToCart(userId, productId, quantity, skuId);
+            extra.put("cartAdded", true);
+
+            if ("order".equals(actionType)) {
+                // 创建 pending 订单
+                Long consigneeId = config != null ? config.getLong("consigneeId") : null;
+                Integer deliveryMethod = config != null ? config.getInteger("deliveryMethod") : null;
+                // 未指定收货地址时取用户默认地址
+                if (consigneeId == null) {
+                    try {
+                        Consignee defaultConsignee = consigneeMapper.selectOne(
+                            new LambdaQueryWrapper<Consignee>()
+                                .eq(Consignee::getUserId, userId)
+                                .eq(Consignee::getIsDefault, 1)
+                                .last("LIMIT 1"));
+                        if (defaultConsignee != null) {
+                            consigneeId = defaultConsignee.getId();
+                        }
+                    } catch (Exception e) {
+                        log.warn("查询默认收货地址失败: userId={}", userId);
+                    }
+                }
+                CreateProductOrderDTO orderDto = new CreateProductOrderDTO();
+                orderDto.setProductId(productId);
+                orderDto.setQuantity(quantity);
+                orderDto.setPaymentMethod("wechat");
+                if (deliveryMethod != null) {
+                    orderDto.setDeliveryMethod(deliveryMethod);
+                }
+                if (consigneeId != null) {
+                    orderDto.setConsigneeId(consigneeId);
+                }
+                Result<ProductOrderDTO> orderResult = productOrderService.create(orderDto, userId);
+                if (orderResult.getCode() == 200 && orderResult.getData() != null) {
+                    extra.put("orderId", orderResult.getData().getId());
+                    extra.put("orderNo", orderResult.getData().getOrderNo());
+                    exec.setExtra(JSON.toJSONString(extra));
+                    taskExecutionMapper.updateById(exec);
+                    log.info("购物任务下单成功: taskId={}, orderNo={}", task.getId(), orderResult.getData().getOrderNo());
+                } else {
+                    // 下单失败(通常因缺地址/库存),保留加购状态
+                    extra.put("orderFailed", true);
+                    extra.put("orderError", orderResult.getMessage());
+                    exec.setExtra(JSON.toJSONString(extra));
+                    taskExecutionMapper.updateById(exec);
+                    log.warn("购物任务下单失败: taskId={}, reason={}", task.getId(), orderResult.getMessage());
+                }
+            } else {
+                // 纯加购
+                exec.setExtra(JSON.toJSONString(extra));
+                taskExecutionMapper.updateById(exec);
+            }
+        } catch (Exception e) {
+            log.error("购物任务联动失败: taskId={}, error={}", task.getId(), e.getMessage(), e);
+            extra.put("error", e.getMessage());
+            exec.setExtra(JSON.toJSONString(extra));
+            taskExecutionMapper.updateById(exec);
+        }
+    }
+
+    private com.alibaba.fastjson.JSONObject parseActionConfig(String json) {
+        if (json == null || json.trim().isEmpty()) {
+            return null;
+        }
+        try {
+            return JSON.parseObject(json);
+        } catch (Exception e) {
+            log.warn("解析 actionConfig 失败: {}", json);
+            return null;
+        }
+    }
+
+    /**
+     * TASK-SYS-248: 调研任务自动模板生成(actionType=survey 时,若 actionConfig 无 surveyId 则调 AI 生成)
+     * 在 createTask 的 taskMapper.insert() 之后调用
+     */
+    private void ensureSurveyTemplateForTask(Task task) {
+        if (!"survey".equals(task.getActionType())) {
+            return;
+        }
+        JSONObject config = parseActionConfig(task.getActionConfig());
+        // 已有 surveyId → 跳过
+        if (config != null && config.get("surveyId") != null) {
+            return;
+        }
+        // 从 config 或 task 属性取维度和主题
+        String dimension = null;
+        String topic = null;
+        if (config != null) {
+            dimension = config.getString("dimension");
+            topic = config.getString("topic");
+        }
+        if (dimension == null || dimension.isEmpty()) {
+            dimension = task.getDimensionCode();
+        }
+        if (topic == null || topic.isEmpty()) {
+            topic = task.getTitle();
+        }
+        if (topic == null || topic.isEmpty()) {
+            topic = "综合评估";
+        }
+        try {
+            String questionsJson = surveyService.aiGenerateQuestions(dimension, topic);
+            SurveyTemplate tpl = new SurveyTemplate();
+            tpl.setTitle(task.getTitle() != null ? task.getTitle() + " - 调研" : "定期调研");
+            tpl.setDimension(dimension);
+            tpl.setQuestionsJson(questionsJson);
+            tpl.setCycleType("weekly");
+            tpl.setEnabled(1);
+            tpl.setAiGenerated(1);
+            tpl.setCreatedAt(new Date());
+            tpl.setUpdatedAt(new Date());
+            surveyTemplateMapper.insert(tpl);
+            // 回填 actionConfig
+            if (config == null) {
+                config = new JSONObject();
+            }
+            config.put("surveyId", tpl.getId());
+            task.setActionConfig(config.toJSONString());
+            taskMapper.updateById(task);
+            log.info("调研任务自动生成模板: taskId={}, templateId={}, dimension={}, topic={}",
+                    task.getId(), tpl.getId(), dimension, topic);
+        } catch (Exception e) {
+            log.warn("调研任务自动生成模板失败(不影响任务创建): taskId={}, error={}", task.getId(), e.getMessage());
+        }
+    }
+
+    // ==================== 统一任务系统:成长任务迁移(原 GrowthTaskService) ====================
+
+    /**
+     * 回填进度型任务的当前进度(progress/todayDone,不入库)
+     */
+    private void fillProgress(List<Task> tasks, Long memberId) {
+        if (tasks == null || tasks.isEmpty()) {
+            return;
+        }
+        for (Task t : tasks) {
+            if (t.getIsDailyProgress() != null && t.getIsDailyProgress() == 1) {
+                TaskExecution exec = taskExecutionMapper.selectOne(new LambdaQueryWrapper<TaskExecution>()
+                        .eq(TaskExecution::getTaskId, t.getId())
+                        .eq(TaskExecution::getMemberId, memberId)
+                        .last("LIMIT 1"));
+                int progress = 0;
+                if (exec != null && exec.getExtra() != null) {
+                    try {
+                        progress = JSON.parseObject(exec.getExtra()).getIntValue("progress");
+                    } catch (Exception ignore) {
+                    }
+                }
+                t.setProgress(progress);
+                t.setTodayDone("completed".equals(t.getStatus()) ? 1 : 0);
+            }
+        }
+    }
+
+    /**
+     * 统一任务系统:更新每日进度型任务的进度(原 growth_task updateProgress)
+     * 按 (userId→familyMemberId, taskKey) 找当日任务实例,累计进度,达标自动完成+发奖
+     * taskKey 匹配约定:title 精确匹配 OR title 以 "[taskKey]" 前缀匹配(迁移时 task_key 拼入 title)
+     */
+    @Transactional
+    public void updateProgress(Long userId, String taskKey, int increment) {
+        updateProgress(userId, null, taskKey, increment);
+    }
+
+    /**
+     * 统一任务系统:更新每日进度型任务的进度(带家庭成员精确定位)
+     * 按 (familyMemberId 或 userId→familyMemberId, taskKey) 找当日任务实例,累计进度,达标自动完成+发奖
+     * taskKey 匹配约定:title 精确匹配 OR title 以 "[taskKey]" 前缀匹配(迁移时 task_key 拼入 title)
+     *
+     * 打卡类调用必须显式传 familyMemberId:同一 userId 可能绑定多个家庭成员(多家庭场景),
+     * 仅按 user_id 反查(LIMIT 1 无排序)会命中错误成员,导致进度记到他人任务、本人任务永久 pending。
+     */
+    @Transactional
+    public void updateProgress(Long userId, Long familyMemberId, String taskKey, int increment) {
+        if (userId == null) {
+            // 未绑定登录账号的家庭成员(如仅建档的家庭成员)无成长任务进度
+            return;
+        }
+        FamilyMember member;
+        if (familyMemberId != null) {
+            member = familyMemberMapper.selectById(familyMemberId);
+            if (member == null || !Long.valueOf(userId).equals(member.getUserId())) {
+                log.warn("统一任务进度更新:成员{}不存在或不属于用户{},跳过 taskKey={}",
+                        familyMemberId, userId, taskKey);
+                return;
+            }
+        } else {
+            member = familyMemberMapper.selectOne(
+                    new LambdaQueryWrapper<FamilyMember>()
+                            .eq(FamilyMember::getUserId, userId)
+                            .last("LIMIT 1"));
+        }
+        if (member == null) {
+            return;
+        }
+
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = cal.getTime();
+        cal.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = cal.getTime();
+
+        Task task = taskMapper.selectOne(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, member.getId())
+                .eq(Task::getIsDailyProgress, 1)
+                .ge(Task::getCreatedAt, startOfDay)
+                .lt(Task::getCreatedAt, endOfDay)
+                .and(w -> w.eq(Task::getTitle, taskKey)
+                        .or().likeRight(Task::getTitle, "[" + taskKey + "]"))
+                .last("LIMIT 1"));
+        if (task == null) {
+            log.warn("统一任务进度更新:未找到今日进度型任务 taskKey={}, userId={}", taskKey, userId);
+            return;
+        }
+        if ("completed".equals(task.getStatus())) {
+            return;
+        }
+
+        // 读当前进度(task_executions.extra.progress),累加
+        TaskExecution exec = taskExecutionMapper.selectOne(new LambdaQueryWrapper<TaskExecution>()
+                .eq(TaskExecution::getTaskId, task.getId())
+                .eq(TaskExecution::getMemberId, member.getId())
+                .last("LIMIT 1"));
+        int progress = 0;
+        if (exec != null && exec.getExtra() != null) {
+            try {
+                progress = JSON.parseObject(exec.getExtra()).getIntValue("progress");
+            } catch (Exception ignore) {
+            }
+        }
+        progress += increment;
+        int target = task.getTargetValue() != null ? task.getTargetValue() : 1;
+
+        if (exec == null) {
+            exec = new TaskExecution();
+            exec.setTaskId(task.getId());
+            exec.setMemberId(member.getId());
+            exec.setStatus("started");
+            exec.setStartedAt(new Date());
+            exec.setCreatedAt(new Date());
+        }
+        exec.setStatus("finished");
+        exec.setFinishedAt(new Date());
+        exec.setExtra("{\"progress\":" + progress + ",\"target\":" + target + "}");
+        if (exec.getId() == null) {
+            taskExecutionMapper.insert(exec);
+        } else {
+            taskExecutionMapper.updateById(exec);
+        }
+
+        // 达标自动完成 + 发奖(复用现有奖励链路)
+        if (progress >= target) {
+            awardTaskCompletionRewards(task, member.getId(), new Date());
+        }
+    }
+
+    /**
+     * 统一任务系统:打卡回写——按【具体任务实例】累计每日进度,达标后完成该实例并发放奖励。
+     *
+     * 与按 taskKey 匹配的 updateProgress 不同:前端「我的任务」卡片点击后会把 taskId 透传到
+     * 打卡接口,本方法精确关闭该实例,保证打卡成功后首页该卡片立即从待办消失
+     * (首页 getTodayTasks 按 status 过滤,前端只保留 status === 'pending' 的卡片)。
+     *
+     * 为什么不能沿用 updateProgress 的 title LIKE '[taskKey]' 匹配:
+     * 1. LIMIT 1 无排序——同一 taskKey 当日若存在多个实例(模板实例 + 内置实例/重复数据)时
+     *    完成的是任意一条,用户点击的那条可能永远 pending,首页卡片不关闭;
+     * 2. 若实例 created_at 不在今日窗口(首页按 deadline 分支亦会返回该任务),task==null 直接
+     *    跳过,点击的任务实例永不被关闭。
+     *
+     * @param taskId        前端透传的具体任务实例 ID
+     * @param userId        登录账号 ID
+     * @param familyMemberId 打卡归属家庭成员 ID
+     * @param increment     本次累加进度(打卡类恒为 1)
+     */
+    @Transactional
+    public void updateCheckinTaskProgress(Long taskId, Long userId, Long familyMemberId, int increment) {
+        if (taskId == null || familyMemberId == null || userId == null) {
+            return;
+        }
+        // 成员校验:必须属于同一登录账号(多家庭场景防串号)
+        FamilyMember member = familyMemberMapper.selectById(familyMemberId);
+        if (member == null || !Long.valueOf(userId).equals(member.getUserId())) {
+            log.warn("打卡回写:成员{}不存在或不属于用户{},跳过 taskId={}", familyMemberId, userId, taskId);
+            return;
+        }
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || task.getFamilyMemberId() == null || !task.getFamilyMemberId().equals(familyMemberId)) {
+            log.warn("打卡回写:任务{}不存在或不属于成员{},跳过", taskId, familyMemberId);
+            return;
+        }
+        // 仅处理每日进度型任务(一次性任务由 completeTask 链路关闭)
+        if (task.getIsDailyProgress() == null || task.getIsDailyProgress() != 1) {
+            log.warn("打卡回写:任务{}非每日进度型,跳过", taskId);
+            return;
+        }
+        // 幂等:已关闭则不再重复发奖
+        if ("completed".equals(task.getStatus())) {
+            return;
+        }
+
+        // 读当前进度(task_executions.extra.progress),累加
+        TaskExecution exec = taskExecutionMapper.selectOne(new LambdaQueryWrapper<TaskExecution>()
+                .eq(TaskExecution::getTaskId, task.getId())
+                .eq(TaskExecution::getMemberId, member.getId())
+                .last("LIMIT 1"));
+        int progress = 0;
+        if (exec != null && exec.getExtra() != null) {
+            try {
+                progress = JSON.parseObject(exec.getExtra()).getIntValue("progress");
+            } catch (Exception ignore) {
+            }
+        }
+        progress += increment;
+        int target = task.getTargetValue() != null ? task.getTargetValue() : 1;
+
+        if (exec == null) {
+            exec = new TaskExecution();
+            exec.setTaskId(task.getId());
+            exec.setMemberId(member.getId());
+            exec.setStatus("started");
+            exec.setStartedAt(new Date());
+            exec.setCreatedAt(new Date());
+        }
+        exec.setStatus("finished");
+        exec.setFinishedAt(new Date());
+        exec.setExtra("{\"progress\":" + progress + ",\"target\":" + target + "}");
+        if (exec.getId() == null) {
+            taskExecutionMapper.insert(exec);
+        } else {
+            taskExecutionMapper.updateById(exec);
+        }
+
+        // 达标自动完成 + 发奖(复用现有奖励链路):status 写入 completed,
+        // 首页刷新后该卡片不再展示为待办;次日由 RepeatTaskGenerator 重新生成当日实例
+        if (progress >= target) {
+            awardTaskCompletionRewards(task, member.getId(), new Date());
+            log.info("每日打卡任务已关闭: taskId={}, title={}, progress={}/target={}",
+                    taskId, task.getTitle(), progress, target);
+        }
+    }
+
+    /**
+     * 统一任务系统:AI 对话生成任务(原 growth_task createDynamicTask)
+     * 直接写入 tasks 表,source_type=ai
+     */
+    @Transactional
+    public Long createDynamicTask(Long userId, String title, String description,
+                                  String dimension, Integer rewardPoints, String sourceConversationId) {
+        User user = userService.getUserInfo(userId);
+        Task task = new Task();
+        task.setFamilyId(user.getFamilyId());
+        task.setCreatorId(userId);
+        task.setExecutorType("child");
+        // 执行者:AI 任务发给当前用户对应家庭成员(若有)
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+        if (member != null) {
+            task.setExecutorId(member.getId());
+            task.setFamilyMemberId(member.getId());
+            task.setMemberId(member.getId());
+        }
+        task.setTitle(title);
+        task.setDescription(description);
+        task.setPoints(rewardPoints != null ? rewardPoints : 10);
+        task.setCategory("成长");
+        task.setStatus("pending");
+        task.setNeedReview(0);
+        task.setIsTemplate(0);
+        task.setSourceType("ai");
+        task.setSourceId(0L);
+        task.setDimensionCode(dimension != null ? dimension : "body");
+        task.setMemberOnly(0);
+        task.setDeadline(new Date(System.currentTimeMillis() + 7L * 24 * 3600 * 1000)); // 7天有效期
+        task.setCreatedAt(new Date());
+        task.setUpdatedAt(new Date());
+        taskMapper.insert(task);
+        log.info("创建AI动态任务: userId={}, taskId={}, title={}", userId, task.getId(), title);
+        return task.getId();
+    }
+
+    /**
+     * 统一任务系统:查询用户每日进度型任务列表(原 growth-task/list)
+     * type: DAILY(NEWBIE 在 Task 5 处理)
+     */
+    public List<Map<String, Object>> getGrowthTaskList(Long userId, String type, String dimension) {
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+        List<Map<String, Object>> result = new ArrayList<>();
+        if (member == null || !"DAILY".equals(type)) {
+            return result;
+        }
+
+        Calendar cal = Calendar.getInstance();
+        cal.set(Calendar.HOUR_OF_DAY, 0);
+        cal.set(Calendar.MINUTE, 0);
+        cal.set(Calendar.SECOND, 0);
+        cal.set(Calendar.MILLISECOND, 0);
+        Date startOfDay = cal.getTime();
+        cal.add(Calendar.DAY_OF_MONTH, 1);
+        Date endOfDay = cal.getTime();
+
+        List<Task> tasks = taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, member.getId())
+                .eq(Task::getIsDailyProgress, 1)
+                .ge(Task::getCreatedAt, startOfDay)
+                .lt(Task::getCreatedAt, endOfDay)
+                .orderByAsc(Task::getId));
+        for (Task task : tasks) {
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("taskLogId", task.getId());
+            item.put("id", task.getId());
+            item.put("type", "DAILY");
+            item.put("title", task.getTitle());
+            item.put("description", task.getDescription());
+            item.put("rewardPoints", task.getPoints());
+            item.put("rewardEnergy", 0);
+            item.put("targetValue", task.getTargetValue() != null ? task.getTargetValue() : 1);
+            item.put("dimension", task.getDimensionCode());
+
+            TaskExecution exec = taskExecutionMapper.selectOne(new LambdaQueryWrapper<TaskExecution>()
+                    .eq(TaskExecution::getTaskId, task.getId())
+                    .eq(TaskExecution::getMemberId, member.getId())
+                    .last("LIMIT 1"));
+            int progress = 0;
+            if (exec != null && exec.getExtra() != null) {
+                try {
+                    progress = JSON.parseObject(exec.getExtra()).getIntValue("progress");
+                } catch (Exception ignore) {
+                }
+            }
+            item.put("progress", progress);
+            item.put("completed", "completed".equals(task.getStatus()) ? 1 : 0);
+            item.put("claimed", 0); // 统一任务系统:自动发放,无 claimed
+            result.add(item);
+        }
+        return result;
+    }
+
+    // ==================== 统一任务系统:新人引导迁移(原 OnboardingService) ====================
+
+    /**
+     * 统一任务系统:新用户注册初始化新人引导任务
+     * 按 admin_task_templates 中 onboarding_sequence 有值的模板生成 tasks(source_type=onboarding)
+     * 顺序链:sequence 递增,前序未完成则后序 locked(复用 prerequisite_task_id + locked 状态)
+     */
+    @Transactional
+    public void initOnboardingTasks(Long userId) {
+        User user = userService.getUserInfo(userId);
+        if (user == null || user.getFamilyId() == null) {
+            return;
+        }
+
+        // 幂等:该用户已有 onboarding 任务则跳过
+        Long existing = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
+                .eq(Task::getCreatorId, userId)
+                .eq(Task::getSourceType, "onboarding"));
+        if (existing != null && existing > 0) {
+            return;
+        }
+
+        List<TaskTemplate> templates = taskTemplateMapper.selectList(
+                new LambdaQueryWrapper<TaskTemplate>()
+                        .eq(TaskTemplate::getIsActive, 1)
+                        .isNotNull(TaskTemplate::getOnboardingSequence)
+                        .orderByAsc(TaskTemplate::getOnboardingSequence));
+        if (templates.isEmpty()) {
+            return;
+        }
+
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+
+        Date now = new Date();
+        Long prevTaskId = null;
+        for (TaskTemplate tpl : templates) {
+            Task task = new Task();
+            task.setFamilyId(user.getFamilyId());
+            task.setCreatorId(userId);
+            task.setExecutorType("child");
+            if (member != null) {
+                task.setExecutorId(member.getId());
+                task.setFamilyMemberId(member.getId());
+                task.setMemberId(member.getId());
+            }
+            task.setTitle(tpl.getTitle());
+            task.setDescription(tpl.getDescription());
+            task.setPoints(tpl.getPoints() != null ? tpl.getPoints() : 2);
+            task.setCategory(tpl.getCategory());
+            task.setStatus(prevTaskId == null ? "pending" : "locked"); // 首任务可直接做,后续需解锁
+            task.setNeedReview(tpl.getNeedReview() != null ? tpl.getNeedReview() : 0);
+            task.setIsTemplate(0);
+            task.setSourceType("onboarding");
+            task.setTemplateId(tpl.getId());
+            task.setPrerequisiteTaskId(prevTaskId); // 顺序链
+            task.setMemberOnly(0);
+            task.setDeadline(new Date(now.getTime() + 30L * 24 * 3600 * 1000)); // 30天有效期
+            task.setCreatedAt(now);
+            task.setUpdatedAt(now);
+            taskMapper.insert(task);
+            prevTaskId = task.getId();
+        }
+        log.info("新用户{}初始化{}条新人引导任务", userId, templates.size());
+    }
+
+    /**
+     * 统一任务系统:完成指定新人引导任务(原 OnboardingService.completeTask)
+     * 按 source_type=onboarding + title 精确匹配(title 约定 = 原 taskType,如 FIRST_TASK)
+     */
+    public void completeOnboardingTask(Long userId, String templateTitle) {
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+        if (member == null) {
+            return;
+        }
+        Task task = taskMapper.selectOne(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, member.getId())
+                .eq(Task::getSourceType, "onboarding")
+                .eq(Task::getTitle, templateTitle)
+                .in(Task::getStatus, "pending", "locked")
+                .last("LIMIT 1"));
+        if (task != null) {
+            awardTaskCompletionRewards(task, member.getId(), new Date());
+            unlockPrerequisiteTasks(task.getId());
+        }
+    }
+
+    /**
+     * 统一任务系统:查询用户的新人引导任务列表(原 OnboardingService.getProgress)
+     * 返回前端兼容结构:taskType=title、status(completed→CLAIMED,其余→PENDING)、rewardPoints、rewardEnergy
+     */
+    public List<Map<String, Object>> getOnboardingTasks(Long userId) {
+        FamilyMember member = familyMemberMapper.selectOne(
+                new LambdaQueryWrapper<FamilyMember>()
+                        .eq(FamilyMember::getUserId, userId)
+                        .last("LIMIT 1"));
+        List<Map<String, Object>> result = new ArrayList<>();
+        if (member == null) {
+            return result;
+        }
+        List<Task> tasks = taskMapper.selectList(new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyMemberId, member.getId())
+                .eq(Task::getSourceType, "onboarding")
+                .orderByAsc(Task::getId));
+        for (Task task : tasks) {
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("taskType", task.getTitle());
+            item.put("rewardPoints", task.getPoints() != null ? task.getPoints() : 0);
+            item.put("rewardEnergy", task.getPoints() != null ? task.getPoints() : 0); // 能量≈积分(与 awardTaskCompletionRewards 一致)
+            // 状态映射:completed→CLAIMED(奖励已自动发放),其余→PENDING
+            item.put("status", "completed".equals(task.getStatus()) ? "CLAIMED" : "PENDING");
+            result.add(item);
+        }
+        return result;
+    }
+
+    /**
+     * 获取家庭成员可关联的任务列表(含所有状态),供创建任务时选择前置/后置任务
+     */
+    public List<Task> getRelatedTaskList(Long familyId, Long memberId, String titleKeyword) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+                .eq(Task::getFamilyId, familyId)
+                .ne(Task::getStatus, "cancelled")
+                .orderByDesc(Task::getCreatedAt);
+        if (memberId != null) {
+            wrapper.eq(Task::getFamilyMemberId, memberId);
+        }
+        if (titleKeyword != null && !titleKeyword.trim().isEmpty()) {
+            wrapper.like(Task::getTitle, titleKeyword.trim());
+        }
+        return taskMapper.selectList(wrapper);
+    }
+
+    /** 工作台-admin 任务详情:校验 family_id 归属,返回完整实体供编辑回显 */
+    public Task getAdminFamilyTaskDetail(Long taskId, Long familyId) {
+        Task t = taskMapper.selectById(taskId);
+        if (t == null || t.getFamilyId() == null || !t.getFamilyId().equals(familyId)) {
+            return null;
+        }
+        return t;
+    }
+
+    /** 工作台-admin 任务新增:family_id/creator_id 固定来自服务端,status 默认 pending */
+    public Long createAdminFamilyTask(Long familyId, Long adminUserId, FamilyTaskCreateDTO dto) {
+        Task t = new Task();
+        t.setFamilyId(familyId);
+        t.setCreatorId(adminUserId);
+        applyAdminTaskFields(t, dto);
+        t.setStatus(dto.getStatus() != null ? dto.getStatus() : "pending");
+        t.setSourceType(dto.getSourceType() != null ? dto.getSourceType() : "admin");
+        t.setCreatedAt(new Date());
+        t.setUpdatedAt(new Date());
+        taskMapper.insert(t);
+        return t.getId();
+    }
+
+    /** 工作台-admin 任务编辑:任务存在且 family_id 与 URL 一致,否则拒绝(防跨家庭越权) */
+    public boolean updateAdminFamilyTask(Long taskId, Long familyId, FamilyTaskCreateDTO dto) {
+        Task t = taskMapper.selectById(taskId);
+        if (t == null) throw new RuntimeException("任务不存在");
+        if (t.getFamilyId() == null || !t.getFamilyId().equals(familyId)) {
+            throw new RuntimeException("任务不属于该家庭");
+        }
+        applyAdminTaskFields(t, dto);
+        if (dto.getStatus() != null) t.setStatus(dto.getStatus());
+        if (dto.getSourceType() != null) t.setSourceType(dto.getSourceType());
+        if (dto.getSourceId() != null) t.setSourceId(dto.getSourceId());
+        t.setUpdatedAt(new Date());
+        // ALWAYS:前端显式传 null 的字段要能清空(MyBatis-Plus 默认 NOT_NULL 会跳过 null)
+        return taskMapper.update(t, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<Task>()
+                .eq(Task::getId, t.getId())
+                .set(Task::getUpdatedAt, t.getUpdatedAt())
+                .set(Task::getTitle, t.getTitle())
+                .set(Task::getDescription, t.getDescription())
+                .set(Task::getCategory, t.getCategory())
+                .set(Task::getPoints, t.getPoints())
+                .set(Task::getDuration, t.getDuration())
+                .set(Task::getTaskType, t.getTaskType())
+                .set(Task::getFrequency, t.getFrequency())
+                .set(Task::getMaxFrequency, t.getMaxFrequency())
+                .set(Task::getNeedReview, t.getNeedReview())
+                .set(Task::getReviewType, t.getReviewType())
+                .set(Task::getCompleteTypes, t.getCompleteTypes())
+                .set(Task::getExecutorType, t.getExecutorType())
+                .set(Task::getExecutorId, t.getExecutorId())
+                .set(Task::getMemberId, t.getMemberId())
+                .set(Task::getRepeatType, t.getRepeatType())
+                .set(Task::getDeadline, t.getDeadline())
+                .set(Task::getFamilyMemberId, t.getFamilyMemberId())
+                .set(Task::getReviewByCategory, t.getReviewByCategory())
+                .set(Task::getFrequencyUnit, t.getFrequencyUnit())
+                .set(Task::getFrequencyInterval, t.getFrequencyInterval())
+                .set(Task::getCycleAnchor, t.getCycleAnchor())
+                .set(Task::getIsPaused, t.getIsPaused())
+                .set(Task::getEarliestStart, t.getEarliestStart())
+                .set(Task::getLatestEnd, t.getLatestEnd())
+                .set(Task::getAcceptDeadline, t.getAcceptDeadline())
+                .set(Task::getMinigameCode, t.getMinigameCode())
+                .set(Task::getBonusRule, t.getBonusRule())
+                .set(Task::getPointsExpireDays, t.getPointsExpireDays())
+                .set(Task::getIsDailyProgress, t.getIsDailyProgress())
+                .set(Task::getTargetValue, t.getTargetValue())
+                .set(Task::getMemberOnly, t.getMemberOnly())
+                .set(Task::getPrerequisiteTaskId, t.getPrerequisiteTaskId())
+                .set(Task::getIsFlowTask, t.getIsFlowTask())
+                .set(Task::getSuccessorTaskIds, t.getSuccessorTaskIds())
+                .set(Task::getActionType, t.getActionType())
+                .set(Task::getActionConfig, t.getActionConfig())
+                .set(Task::getRequireInput, t.getRequireInput())
+                .set(Task::getStartRequired, t.getStartRequired())
+                .set(Task::getMinDurationSeconds, t.getMinDurationSeconds())
+                .set(Task::getDimensionCode, t.getDimensionCode())
+                .set(Task::getDimensionWeights, t.getDimensionWeights())
+                .set(Task::getTemplateId, t.getTemplateId())
+                .set(Task::getIsTemplate, t.getIsTemplate())
+                .set(Task::getStatus, t.getStatus())
+                .set(Task::getSourceType, t.getSourceType())
+                .set(Task::getSourceId, t.getSourceId())) > 0;
+    }
+
+
+    /** 工作台-admin 新增/编辑共用:把 DTO 全量字段写入实体 */
+    private void applyAdminTaskFields(Task t, FamilyTaskCreateDTO dto) {
+        t.setTitle(dto.getTitle());
+        t.setDescription(dto.getDescription());
+        t.setCategory(dto.getCategory());
+        t.setPoints(dto.getPoints());
+        t.setDuration(dto.getDuration());
+        t.setTaskType(dto.getTaskType());
+        t.setFrequency(dto.getFrequency());
+        t.setMaxFrequency(dto.getMaxFrequency());
+        t.setNeedReview(dto.getNeedReview());
+        t.setReviewType(dto.getReviewType());
+        t.setCompleteTypes(dto.getCompleteTypes() == null ? null : String.join(",", dto.getCompleteTypes()));
+        t.setExecutorType(dto.getExecutorType());
+        t.setExecutorId(dto.getExecutorId());
+        t.setMemberId(dto.getMemberId());
+        t.setRepeatType(dto.getRepeatType());
+        t.setDeadline(dto.getDeadline());
+        t.setFamilyMemberId(dto.getFamilyMemberId());
+        t.setReviewByCategory(dto.getReviewByCategory());
+        t.setFrequencyUnit(dto.getFrequencyUnit());
+        t.setFrequencyInterval(dto.getFrequencyInterval());
+        t.setCycleAnchor(dto.getCycleAnchor());
+        t.setIsPaused(dto.getIsPaused());
+        t.setEarliestStart(dto.getEarliestStart());
+        t.setLatestEnd(dto.getLatestEnd());
+        t.setAcceptDeadline(dto.getAcceptDeadline());
+        t.setMinigameCode(dto.getMinigameCode());
+        t.setBonusRule(dto.getBonusRule());
+        t.setPointsExpireDays(dto.getPointsExpireDays());
+        t.setIsDailyProgress(dto.getIsDailyProgress());
+        t.setTargetValue(dto.getTargetValue());
+        t.setMemberOnly(dto.getMemberOnly());
+        t.setPrerequisiteTaskId(dto.getPrerequisiteTaskId());
+        t.setIsFlowTask(dto.getIsFlowTask());
+        t.setSuccessorTaskIds(dto.getSuccessorTaskIds());
+        t.setActionType(dto.getActionType());
+        t.setActionConfig(dto.getActionConfig());
+        t.setRequireInput(dto.getRequireInput());
+        t.setStartRequired(dto.getStartRequired());
+        t.setMinDurationSeconds(dto.getMinDurationSeconds());
+        t.setDimensionCode(dto.getDimensionCode());
+        t.setDimensionWeights(dto.getDimensionWeights());
+        t.setTemplateId(dto.getTemplateId());
+        t.setIsTemplate(dto.getIsTemplate());
+    }
+}

+ 173 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskStatsService.java

@@ -0,0 +1,173 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.Task;
+
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.TaskMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class TaskStatsService {
+
+    @Resource
+    private TaskMapper taskMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /**
+     * 获取单个家庭成员的任务完成统计
+     */
+    public Map<String, Object> getChildStats(Long memberId, Date startDate, Date endDate) {
+        List<Task> tasks = queryTasks(null, memberId, startDate, endDate);
+        return buildStats(tasks, null, memberId);
+    }
+
+    /**
+     * 获取某个用户(家庭主账号)的任务完成统计
+     * 按 executorType="parent" + executorId 查询,覆盖本人自己的任务
+     */
+    public Map<String, Object> getUserStats(Long userId, Date startDate, Date endDate) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+            .ne(Task::getIsTemplate, 1)
+            .ne(Task::getStatus, "cancelled")
+            .eq(Task::getExecutorType, "parent")
+            .eq(Task::getExecutorId, userId);
+
+        if (startDate != null) {
+            wrapper.ge(Task::getCreatedAt, startDate);
+        }
+        if (endDate != null) {
+            wrapper.le(Task::getCreatedAt, endDate);
+        }
+        wrapper.orderByDesc(Task::getCreatedAt);
+
+        SortUtil.applySort(wrapper);
+        List<Task> tasks = taskMapper.selectList(wrapper);
+        return buildStats(tasks, null, null);
+    }
+
+    /**
+     * 获取家庭维度的任务完成统计
+     */
+    public Map<String, Object> getFamilyStats(Long familyId, Date startDate, Date endDate) {
+        List<Task> tasks = queryTasks(familyId, null, startDate, endDate);
+        Map<String, Object> stats = buildStats(tasks, familyId, null);
+
+        // 按家庭成员分组
+        List<FamilyMember> children = familyMemberMapper.selectList(
+            new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId));
+        List<Map<String, Object>> byChild = new ArrayList<>();
+        for (FamilyMember child : children) {
+            List<Task> childTasks = tasks.stream()
+                .filter(t -> child.getId().equals(t.getMemberId()) || child.getId().equals(t.getFamilyMemberId()))
+                .collect(Collectors.toList());
+            if (!childTasks.isEmpty()) {
+                Map<String, Object> childStat = new HashMap<>();
+                childStat.put("memberId", child.getId());
+                childStat.put("childName", child.getNickname());
+                childStat.put("totalTasks", childTasks.size());
+                long completed = childTasks.stream().filter(t -> "completed".equals(t.getStatus())).count();
+                childStat.put("completedTasks", completed);
+                childStat.put("completionRate", childTasks.size() > 0 ? Math.round(completed * 1000.0 / childTasks.size()) / 10.0 : 0);
+                byChild.add(childStat);
+            }
+        }
+        stats.put("byChild", byChild);
+        return stats;
+    }
+
+    /**
+     * 查询指定范围的任务(排除模板任务和已取消的)
+     */
+    private List<Task> queryTasks(Long familyId, Long memberId, Date startDate, Date endDate) {
+        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
+            .ne(Task::getIsTemplate, 1)
+            .ne(Task::getStatus, "cancelled");
+
+        if (familyId != null) {
+            wrapper.eq(Task::getFamilyId, familyId);
+        }
+        if (memberId != null) {
+            wrapper.and(w -> w.eq(Task::getMemberId, memberId).or().eq(Task::getFamilyMemberId, memberId));
+        }
+        if (startDate != null) {
+            wrapper.ge(Task::getCreatedAt, startDate);
+        }
+        if (endDate != null) {
+            Calendar endCal = Calendar.getInstance();
+            endCal.setTime(endDate);
+            endCal.set(Calendar.HOUR_OF_DAY, 23);
+            endCal.set(Calendar.MINUTE, 59);
+            endCal.set(Calendar.SECOND, 59);
+            endCal.set(Calendar.MILLISECOND, 999);
+            wrapper.le(Task::getCreatedAt, endCal.getTime());
+        }
+        wrapper.orderByDesc(Task::getCreatedAt);
+
+        SortUtil.applySort(wrapper);
+        return taskMapper.selectList(wrapper);
+    }
+
+    /**
+     * 构建统计结果
+     */
+    private Map<String, Object> buildStats(List<Task> tasks, Long familyId, Long memberId) {
+        Date now = new Date();
+        int total = tasks.size();
+        long completed = tasks.stream().filter(t -> "completed".equals(t.getStatus())).count();
+        long pending = tasks.stream()
+            .filter(t -> "pending".equals(t.getStatus()) || "in_progress".equals(t.getStatus()))
+            .count();
+        long inReview = tasks.stream().filter(t -> "pending_review".equals(t.getStatus())).count();
+        long overdue = tasks.stream()
+            .filter(t -> ("pending".equals(t.getStatus()) || "in_progress".equals(t.getStatus()))
+                    && t.getDeadline() != null && t.getDeadline().before(now))
+            .count();
+
+        double rate = total > 0 ? Math.round(completed * 1000.0 / total) / 10.0 : 0;
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("totalTasks", total);
+        result.put("completedTasks", completed);
+        result.put("pendingTasks", pending);
+        result.put("inReviewTasks", inReview);
+        result.put("overdueTasks", overdue);
+        result.put("completionRate", rate);
+
+        List<Map<String, Object>> pendingTaskList = tasks.stream()
+            .filter(t -> "pending".equals(t.getStatus()) || "in_progress".equals(t.getStatus()))
+            .map(t -> {
+                Map<String, Object> item = new HashMap<>();
+                item.put("id", t.getId());
+                item.put("title", t.getTitle() != null ? t.getTitle() : "");
+                return item;
+            })
+            .collect(Collectors.toList());
+        result.put("pendingTaskList", pendingTaskList);
+
+        List<Map<String, Object>> completedTaskList = tasks.stream()
+            .filter(t -> "completed".equals(t.getStatus()))
+            .map(t -> {
+                Map<String, Object> item = new HashMap<>();
+                item.put("id", t.getId());
+                item.put("title", t.getTitle() != null ? t.getTitle() : "");
+                item.put("completedAt", t.getCompletedAt());
+                item.put("points", t.getPoints());
+                return item;
+            })
+            .collect(Collectors.toList());
+        result.put("completedTaskList", completedTaskList);
+
+        return result;
+    }
+}

+ 263 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskTemplatePackageService.java

@@ -0,0 +1,263 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.TaskTemplatePackageServiceInterface;
+
+import com.etotem.cfc.entity.TaskTemplatePackage;
+import com.etotem.cfc.entity.TaskTemplateItem;
+import com.etotem.cfc.mapper.TaskTemplatePackageMapper;
+import com.etotem.cfc.mapper.TaskTemplateItemMapper;
+import com.etotem.cfc.dto.CreatePackageDTO;
+import com.etotem.cfc.dto.CreatePackageItemDTO;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class TaskTemplatePackageService {
+
+    @Resource
+    private TaskTemplatePackageMapper packageMapper;
+
+    @Resource
+    private TaskTemplateItemMapper itemMapper;
+
+    /**
+     * 创建任务模板
+     */
+    @Transactional
+    public TaskTemplatePackage createPackage(CreatePackageDTO dto, Long creatorId) {
+        TaskTemplatePackage pkg = new TaskTemplatePackage();
+        pkg.setCreatorId(creatorId);
+        pkg.setName(dto.getName());
+        pkg.setDescription(dto.getDescription());
+        pkg.setCycleDays(dto.getCycleDays());
+        pkg.setCategory(dto.getCategory());
+        pkg.setTags(dto.getTags());
+        pkg.setPrice(dto.getPrice());
+        
+        // 计算平台服务费 (不超过10%, 1000bps)
+        pkg.setPlatformFee(dto.getPrice() * 1000 / 10000);
+        
+        pkg.setIsPublic(dto.getIsPublic() != null ? dto.getIsPublic() : 0);
+        pkg.setCoverImage(dto.getCoverImage());
+        pkg.setStatus("draft");
+        pkg.setShareCode(generateShareCode());
+        pkg.setCreatedAt(new Date());
+        pkg.setUpdatedAt(new Date());
+        
+        packageMapper.insert(pkg);
+        return pkg;
+    }
+
+    /**
+     * 更新任务模板
+     */
+    public boolean updatePackage(Long id, CreatePackageDTO dto) {
+        TaskTemplatePackage pkg = packageMapper.selectById(id);
+        if (pkg == null) return false;
+        
+        if (dto.getName() != null) pkg.setName(dto.getName());
+        if (dto.getDescription() != null) pkg.setDescription(dto.getDescription());
+        if (dto.getCycleDays() != null) pkg.setCycleDays(dto.getCycleDays());
+        if (dto.getCategory() != null) pkg.setCategory(dto.getCategory());
+        if (dto.getTags() != null) pkg.setTags(dto.getTags());
+        if (dto.getPrice() != null) {
+            pkg.setPrice(dto.getPrice());
+            pkg.setPlatformFee(dto.getPrice() * 1000 / 10000);
+        }
+        if (dto.getIsPublic() != null) pkg.setIsPublic(dto.getIsPublic());
+        if (dto.getCoverImage() != null) pkg.setCoverImage(dto.getCoverImage());
+        pkg.setUpdatedAt(new Date());
+        
+        return packageMapper.updateById(pkg) > 0;
+    }
+
+    /**
+     * 获取任务模板详情
+     */
+    public TaskTemplatePackage getPackageById(Long id) {
+        return packageMapper.selectById(id);
+    }
+
+    /**
+     * 获取我的任务模板列表
+     */
+    public List<TaskTemplatePackage> getMyPackages(Long creatorId) {
+        return packageMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplatePackage>()
+                .eq("creator_id", creatorId)
+                .orderByDesc("created_at")
+        );
+    }
+
+    /**
+     * 获取公开任务模板列表 (市场)
+     */
+    public List<TaskTemplatePackage> getPublicPackages(String category) {
+        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplatePackage> wrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplatePackage>()
+                .eq("is_public", 1)
+                .eq("status", "approved");
+
+        if (category != null && !category.isEmpty()) {
+            wrapper.eq("category", category);
+        }
+
+        wrapper.orderByDesc("created_at");
+        SortUtil.applySort(wrapper);
+        return packageMapper.selectList(wrapper);
+    }
+
+    /**
+     * 通过分享码获取任务模板
+     */
+    public TaskTemplatePackage getPackageByShareCode(String shareCode) {
+        return packageMapper.selectOne(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplatePackage>()
+                .eq("share_code", shareCode)
+        );
+    }
+
+    /**
+     * 提交审核
+     */
+    public boolean submitForReview(Long id) {
+        TaskTemplatePackage pkg = packageMapper.selectById(id);
+        if (pkg == null || !"draft".equals(pkg.getStatus())) {
+            return false;
+        }
+        pkg.setStatus("pending");
+        pkg.setUpdatedAt(new Date());
+        return packageMapper.updateById(pkg) > 0;
+    }
+
+    /**
+     * 审核通过
+     */
+    public boolean approvePackage(Long id, Long reviewerId) {
+        TaskTemplatePackage pkg = packageMapper.selectById(id);
+        if (pkg == null || !"pending".equals(pkg.getStatus())) {
+            return false;
+        }
+        pkg.setStatus("approved");
+        pkg.setReviewerId(reviewerId);
+        pkg.setReviewedAt(new Date());
+        pkg.setUpdatedAt(new Date());
+        return packageMapper.updateById(pkg) > 0;
+    }
+
+    /**
+     * 审核拒绝
+     */
+    public boolean rejectPackage(Long id, Long reviewerId, String reason) {
+        TaskTemplatePackage pkg = packageMapper.selectById(id);
+        if (pkg == null || !"pending".equals(pkg.getStatus())) {
+            return false;
+        }
+        pkg.setStatus("rejected");
+        pkg.setReviewerId(reviewerId);
+        pkg.setReviewedAt(new Date());
+        pkg.setRejectReason(reason);
+        pkg.setUpdatedAt(new Date());
+        return packageMapper.updateById(pkg) > 0;
+    }
+
+    /**
+     * 发布/下架
+     */
+    public boolean publishPackage(Long id, boolean publish) {
+        TaskTemplatePackage pkg = packageMapper.selectById(id);
+        if (pkg == null || !"approved".equals(pkg.getStatus())) {
+            return false;
+        }
+        pkg.setStatus(publish ? "approved" : "offline");
+        pkg.setUpdatedAt(new Date());
+        return packageMapper.updateById(pkg) > 0;
+    }
+
+    // ========== 任务模板任务项管理 ==========
+
+    /**
+     * 添加任务项
+     */
+    public TaskTemplateItem addItem(CreatePackageItemDTO dto) {
+        TaskTemplateItem item = new TaskTemplateItem();
+        item.setPackageId(dto.getPackageId());
+        item.setTaskName(dto.getTaskName());
+        item.setDescription(dto.getDescription());
+        item.setPoints(dto.getPoints());
+        item.setFrequency(dto.getFrequency());
+        item.setDuration(dto.getDuration());
+        item.setIsRequired(dto.getIsRequired());
+        item.setSortOrder(dto.getSortOrder());
+        item.setCreatedAt(new Date());
+        item.setUpdatedAt(new Date());
+        
+        itemMapper.insert(item);
+        return item;
+    }
+
+    /**
+     * 更新任务项
+     */
+    public boolean updateItem(Long id, CreatePackageItemDTO dto) {
+        TaskTemplateItem item = itemMapper.selectById(id);
+        if (item == null) return false;
+        
+        if (dto.getTaskName() != null) item.setTaskName(dto.getTaskName());
+        if (dto.getDescription() != null) item.setDescription(dto.getDescription());
+        if (dto.getPoints() != null) item.setPoints(dto.getPoints());
+        if (dto.getFrequency() != null) item.setFrequency(dto.getFrequency());
+        if (dto.getDuration() != null) item.setDuration(dto.getDuration());
+        if (dto.getIsRequired() != null) item.setIsRequired(dto.getIsRequired());
+        if (dto.getSortOrder() != null) item.setSortOrder(dto.getSortOrder());
+        item.setUpdatedAt(new Date());
+        
+        return itemMapper.updateById(item) > 0;
+    }
+
+    /**
+     * 删除任务项
+     */
+    public boolean deleteItem(Long id) {
+        return itemMapper.deleteById(id) > 0;
+    }
+
+    /**
+     * 获取任务模板的任务项列表
+     */
+    public List<TaskTemplateItem> getPackageItems(Long packageId) {
+        return itemMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplateItem>()
+                .eq("package_id", packageId)
+                .orderByAsc("sort_order")
+        );
+    }
+
+    /**
+     * 获取待审核的任务模板列表
+     */
+    public List<TaskTemplatePackage> getPendingPackages() {
+        return packageMapper.selectList(
+            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TaskTemplatePackage>()
+                .eq("status", "pending")
+                .orderByAsc("created_at")
+        );
+    }
+
+    /**
+     * 生成唯一分享码
+     */
+    private String generateShareCode() {
+        String code;
+        do {
+            code = UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase();
+        } while (getPackageByShareCode(code) != null);
+        return code;
+    }
+}

+ 197 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeacherFamilyBindingRequestService.java

@@ -0,0 +1,197 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.TeacherFamilyBindingRequest;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.TeacherFamilyBindingRequestMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 规划师绑定家庭申请服务
+ */
+@Service
+public class TeacherFamilyBindingRequestService {
+
+    @Resource
+    private TeacherFamilyBindingRequestMapper bindingRequestMapper;
+
+    @Resource
+    private FamilyMapper familyMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 创建绑定申请(规划师发起)
+     * @param teacherId 规划师用户ID
+     * @param inviteCode 家庭邀请码
+     * @param message 申请留言(可选)
+     * @return 申请ID
+     */
+    @Transactional
+    public Long createRequest(Long teacherId, String inviteCode, String message) {
+        // 查找家庭
+        Family family = familyMapper.selectOne(
+                new LambdaQueryWrapper<Family>().eq(Family::getInviteCode, inviteCode));
+        if (family == null) {
+            throw new RuntimeException("邀请码无效");
+        }
+
+        // 检查是否已有 pending 或 approved 的申请
+        Long existing = bindingRequestMapper.selectCount(
+                new LambdaQueryWrapper<TeacherFamilyBindingRequest>()
+                        .eq(TeacherFamilyBindingRequest::getTeacherId, teacherId)
+                        .eq(TeacherFamilyBindingRequest::getFamilyId, family.getId())
+                        .in(TeacherFamilyBindingRequest::getStatus, "pending", "approved"));
+        if (existing > 0) {
+            throw new RuntimeException("您已申请过绑定该家庭,请等待审批或重新申请");
+        }
+
+        TeacherFamilyBindingRequest request = new TeacherFamilyBindingRequest();
+        request.setTeacherId(teacherId);
+        request.setFamilyId(family.getId());
+        request.setInvitationToken(inviteCode);
+        request.setStatus("pending");
+        request.setRequestedAt(new Date());
+        request.setMessage(message);
+        request.setCreatedAt(new Date());
+        request.setUpdatedAt(new Date());
+        bindingRequestMapper.insert(request);
+
+        return request.getId();
+    }
+
+    /**
+     * 获取家庭所有待审批的绑定申请(家庭主账号调用)
+     */
+    public List<TeacherFamilyBindingRequest> getPendingByFamily(Long familyId) {
+        return bindingRequestMapper.selectList(
+                new LambdaQueryWrapper<TeacherFamilyBindingRequest>()
+                        .eq(TeacherFamilyBindingRequest::getFamilyId, familyId)
+                        .eq(TeacherFamilyBindingRequest::getStatus, "pending")
+                        .orderByDesc(TeacherFamilyBindingRequest::getRequestedAt));
+    }
+
+    /**
+     * 家庭主账号审批通过:写入 teacherFamilyIds + family.teacherId
+     */
+    @Transactional
+    public void approve(Long requestId, Long approverUserId) {
+        TeacherFamilyBindingRequest request = bindingRequestMapper.selectById(requestId);
+        if (request == null) {
+            throw new RuntimeException("申请记录不存在");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            throw new RuntimeException("该申请已处理");
+        }
+
+        // 校验审批人是否属于该家庭
+        User approver = userMapper.selectById(approverUserId);
+        if (approver == null || !request.getFamilyId().equals(approver.getFamilyId())) {
+            throw new RuntimeException("只有该家庭成员可以审批");
+        }
+
+        // 更新请求状态
+        request.setStatus("approved");
+        request.setDecidedBy(approverUserId);
+        request.setDecidedAt(new Date());
+        request.setUpdatedAt(new Date());
+        bindingRequestMapper.updateById(request);
+
+        // 写入 family.teacherId
+        Family family = familyMapper.selectById(request.getFamilyId());
+        if (family != null) {
+            family.setTeacherId(request.getTeacherId());
+            family.setUpdatedAt(new Date());
+            familyMapper.updateById(family);
+        }
+
+        // 写入 user.teacherFamilyIds
+        User teacher = userMapper.selectById(request.getTeacherId());
+        if (teacher != null) {
+            String currentIds = teacher.getTeacherFamilyIds();
+            String newFamilyId = String.valueOf(request.getFamilyId());
+            if (currentIds == null || !currentIds.contains(newFamilyId)) {
+                String updatedIds = currentIds == null ? newFamilyId : currentIds + "," + newFamilyId;
+                teacher.setTeacherFamilyIds(updatedIds);
+                teacher.setUpdatedAt(new Date());
+                userMapper.updateById(teacher);
+            }
+        }
+    }
+
+    /**
+     * 家庭主账号拒绝申请
+     */
+    @Transactional
+    public void reject(Long requestId, Long approverUserId, String reason) {
+        TeacherFamilyBindingRequest request = bindingRequestMapper.selectById(requestId);
+        if (request == null) {
+            throw new RuntimeException("申请记录不存在");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            throw new RuntimeException("该申请已处理");
+        }
+
+        // 校验审批人是否属于该家庭
+        User approver = userMapper.selectById(approverUserId);
+        if (approver == null || !request.getFamilyId().equals(approver.getFamilyId())) {
+            throw new RuntimeException("只有该家庭成员可以审批");
+        }
+
+        request.setStatus("rejected");
+        request.setDecidedBy(approverUserId);
+        request.setDecidedAt(new Date());
+        request.setRejectReason(reason);
+        request.setUpdatedAt(new Date());
+        bindingRequestMapper.updateById(request);
+    }
+
+    /**
+     * 取消申请(规划师撤销自己的申请)
+     */
+    public void cancel(Long requestId, Long teacherId) {
+        TeacherFamilyBindingRequest request = bindingRequestMapper.selectById(requestId);
+        if (request == null) {
+            throw new RuntimeException("申请记录不存在");
+        }
+        if (!request.getTeacherId().equals(teacherId)) {
+            throw new RuntimeException("只能撤销自己的申请");
+        }
+        if (!"pending".equals(request.getStatus())) {
+            throw new RuntimeException("该申请已处理,无法撤销");
+        }
+        request.setStatus("cancelled");
+        request.setUpdatedAt(new Date());
+        bindingRequestMapper.updateById(request);
+    }
+
+    /**
+     * 获取规划师所有绑定请求
+     */
+    public List<TeacherFamilyBindingRequest> getByTeacher(Long teacherId) {
+        return bindingRequestMapper.selectList(
+                new LambdaQueryWrapper<TeacherFamilyBindingRequest>()
+                        .eq(TeacherFamilyBindingRequest::getTeacherId, teacherId)
+                        .orderByDesc(TeacherFamilyBindingRequest::getRequestedAt));
+    }
+
+    /**
+     * 判断规划师是否已绑定某家庭(直接读 teacherFamilyIds)
+     */
+    public boolean isTeacherBoundToFamily(Long teacherId, Long familyId) {
+        User teacher = userMapper.selectById(teacherId);
+        if (teacher == null || teacher.getTeacherFamilyIds() == null) {
+            return false;
+        }
+        return teacher.getTeacherFamilyIds().contains(String.valueOf(familyId));
+    }
+}

+ 113 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeacherMessageService.java

@@ -0,0 +1,113 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.service.api.TeacherMessageServiceInterface;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.entity.TeacherMessage;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.TeacherMessageMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class TeacherMessageService {
+
+    @Resource
+    private TeacherMessageMapper teacherMessageMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 家庭主账号发送咨询消息
+     */
+    public Long sendMessage(Long familyId, Long parentId, Long teacherId, String content) {
+        TeacherMessage message = new TeacherMessage();
+        message.setFamilyId(familyId);
+        message.setParentId(parentId);
+        message.setTeacherId(teacherId);
+        message.setContent(content);
+        message.setStatus("pending");
+        message.setCreatedAt(new Date());
+        teacherMessageMapper.insert(message);
+        return message.getId();
+    }
+
+    /**
+     * 成长规划师回复消息
+     */
+    public boolean replyMessage(Long messageId, Long teacherId, String replyContent) {
+        TeacherMessage message = teacherMessageMapper.selectById(messageId);
+        if (message == null || !message.getTeacherId().equals(teacherId)) {
+            return false;
+        }
+        message.setReplyContent(replyContent);
+        message.setStatus("replied");
+        message.setRepliedAt(new Date());
+        teacherMessageMapper.updateById(message);
+        return true;
+    }
+
+    /**
+     * 成长规划师获取咨询消息列表
+     */
+    public Page<TeacherMessage> getMessagesByTeacher(Long teacherId, Integer page, Integer size) {
+        Page<TeacherMessage> pageParam = new Page<>(page, size);
+        return teacherMessageMapper.selectPage(pageParam, new LambdaQueryWrapper<TeacherMessage>()
+                .eq(TeacherMessage::getTeacherId, teacherId)
+                .orderByDesc(TeacherMessage::getCreatedAt));
+    }
+
+    /**
+     * 获取成长规划师未读消息数
+     */
+    public long getUnreadCount(Long teacherId) {
+        return teacherMessageMapper.selectCount(new LambdaQueryWrapper<TeacherMessage>()
+                .eq(TeacherMessage::getTeacherId, teacherId)
+                .eq(TeacherMessage::getStatus, "pending"));
+    }
+
+    /**
+     * 家庭主账号获取自己的咨询消息
+     */
+    public List<TeacherMessage> getMessagesByParent(Long parentId) {
+        return teacherMessageMapper.selectList(new LambdaQueryWrapper<TeacherMessage>()
+                .eq(TeacherMessage::getParentId, parentId)
+                .orderByDesc(TeacherMessage::getCreatedAt));
+    }
+
+    /**
+     * 管理端:按 familyId 分页查询该家庭的咨询消息,回填家长/老师昵称。
+     */
+    public Map<String, Object> getFamilyMessages(Long familyId, Integer page, Integer size) {
+        Page<TeacherMessage> pageParam = new Page<>(page, size);
+        Page<TeacherMessage> result = teacherMessageMapper.selectPage(pageParam,
+                new LambdaQueryWrapper<TeacherMessage>()
+                        .eq(TeacherMessage::getFamilyId, familyId)
+                        .orderByDesc(TeacherMessage::getCreatedAt));
+        // 回填家长昵称
+        for (TeacherMessage msg : result.getRecords()) {
+            if (msg.getParentId() != null) {
+                User parent = userMapper.selectById(msg.getParentId());
+                if (parent != null) msg.setParentName(parent.getNickname());
+            }
+            if (msg.getTeacherId() != null) {
+                User teacher = userMapper.selectById(msg.getTeacherId());
+                if (teacher != null) msg.setTeacherName(teacher.getNickname());
+            }
+        }
+        Map<String, Object> out = new HashMap<>();
+        out.put("records", result.getRecords());
+        out.put("total", result.getTotal());
+        out.put("pages", result.getPages());
+        out.put("current", result.getCurrent());
+        return out;
+    }
+}

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

@@ -0,0 +1,345 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.*;
+import com.etotem.cfc.entity.*;
+import com.etotem.cfc.mapper.*;
+import com.etotem.cfc.service.api.TeacherServiceInterface;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+import com.etotem.cfc.util.SortUtil;
+
+@Service
+public class TeacherService {
+
+    @Resource
+    private TeacherMapper teacherMapper;
+
+    @Resource
+    private AssessmentAppointmentMapper appointmentMapper;
+
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private AssessmentOrderService assessmentOrderService;
+
+    /**
+     * 获取老师信息
+     */
+    public TeacherDTO getTeacherInfo(Long userId) {
+        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
+                .eq(Teacher::getUserId, userId));
+        
+ if (teacher == null) {
+ throw new RuntimeException("教师信息不存在");
+ }
+        
+        return toDTO(teacher);
+    }
+
+    /**
+     * 创建老师信息
+     */
+    public TeacherDTO createTeacher(Long userId, TeacherDTO dto) {
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            throw new RuntimeException("用户不存在");
+        }
+
+        // 检查是否已是老师
+        Teacher existing = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
+                .eq(Teacher::getUserId, userId));
+        if (existing != null) {
+            throw new RuntimeException("该用户已是老师");
+        }
+
+        Teacher teacher = new Teacher();
+        teacher.setUserId(userId);
+        teacher.setTeacherNo(generateTeacherNo());
+        teacher.setTitle(dto.getTitle());
+        teacher.setSpecialty(dto.getSpecialty());
+        teacher.setBio(dto.getBio());
+        teacher.setExperienceYears(dto.getExperienceYears());
+        teacher.setRating(500);
+        teacher.setTotalAppointments(0);
+        teacher.setStatus("active");
+        teacher.setVerificationStatus("pending");
+        teacher.setCreatedAt(new Date());
+        teacher.setUpdatedAt(new Date());
+        
+        teacherMapper.insert(teacher);
+
+        // 更新用户角色 - 添加 teacher 角色到用户的角色列表
+        userService.addRole(userId, "teacher");
+        // 如果当前不是老师,切换到老师角色
+        if (!"teacher".equals(user.getRole())) {
+            user.setRole("teacher");
+        }
+        user.setUpdatedAt(new Date());
+        userMapper.updateById(user);
+
+        return toDTO(teacher);
+    }
+
+    /**
+     * 获取老师的测评预约列表
+     */
+    public List<AssessmentAppointmentDTO> getAppointments(Long teacherId, String status) {
+        LambdaQueryWrapper<AssessmentAppointment> wrapper = new LambdaQueryWrapper<AssessmentAppointment>()
+                .eq(AssessmentAppointment::getTeacherId, teacherId);
+        
+        if (status != null && !status.isEmpty()) {
+            wrapper.eq(AssessmentAppointment::getStatus, status);
+        }
+        
+        wrapper.orderByDesc(AssessmentAppointment::getAppointmentDate);
+        
+        SortUtil.applySort(wrapper);
+        List<AssessmentAppointment> appointments = appointmentMapper.selectList(wrapper);
+        
+        return appointments.stream().map(this::toAppointmentDTO).collect(Collectors.toList());
+    }
+
+    /**
+     * 创建测评预约
+     */
+    public AssessmentAppointmentDTO createAppointment(Long teacherId, CreateAppointmentDTO dto) {
+        AssessmentAppointment appointment = new AssessmentAppointment();
+        appointment.setTeacherId(teacherId);
+        appointment.setFamilyId(dto.getFamilyId());
+        appointment.setMemberId(dto.getMemberId());
+        appointment.setAppointmentDate(dto.getAppointmentDate());
+        appointment.setAppointmentTime(dto.getAppointmentTime());
+        appointment.setDurationMinutes(dto.getDurationMinutes());
+        appointment.setAppointmentType(dto.getAppointmentType());
+        appointment.setNotes(dto.getNotes());
+        appointment.setContactPhone(dto.getContactPhone());
+        appointment.setMeetLink(dto.getMeetLink());
+        appointment.setStatus(0);
+        appointment.setCreatedAt(new Date());
+        appointment.setUpdatedAt(new Date());
+        
+        appointmentMapper.insert(appointment);
+        
+        return toAppointmentDTO(appointment);
+    }
+
+    /**
+     * 确认/完成预约
+     */
+    public AssessmentAppointmentDTO updateAppointmentStatus(Long appointmentId, Integer status) {
+        AssessmentAppointment appointment = appointmentMapper.selectById(appointmentId);
+        if (appointment == null) {
+            throw new RuntimeException("预约不存在");
+        }
+        
+        appointment.setStatus(status);
+        appointment.setUpdatedAt(new Date());
+        appointmentMapper.updateById(appointment);
+        
+        return toAppointmentDTO(appointment);
+    }
+
+    /**
+     * 创建DAN测评结果
+     */
+    public DanAssessmentResultDTO createAssessmentResult(Long teacherId, CreateAssessmentResultDTO dto) {
+        DanAssessmentResult result = new DanAssessmentResult();
+        result.setMemberId(dto.getMemberId());
+        result.setTeacherId(teacherId);
+        result.setAppointmentId(dto.getAppointmentId());
+        result.setAttentionScore(dto.getAttentionScore());
+        result.setFocusScore(dto.getFocusScore());
+        result.setMemoryScore(dto.getMemoryScore());
+        result.setLogicScore(dto.getLogicScore());
+        result.setOverallScore(dto.getOverallScore());
+        result.setAssessmentDate(dto.getAssessmentDate());
+        result.setDurationMinutes(dto.getDurationMinutes());
+        result.setGameRecords(dto.getGameRecords());
+        result.setAnalysisReport(dto.getAnalysisReport());
+        result.setGrowthSuggestions(dto.getGrowthSuggestions());
+        result.setNextReviewDate(dto.getNextReviewDate());
+        result.setStatus("completed");
+        result.setCreatedAt(new Date());
+        result.setUpdatedAt(new Date());
+        
+        danAssessmentResultMapper.insert(result);
+        
+        // 更新家庭成员的评估结果
+        FamilyMember child = familyMemberMapper.selectById(dto.getMemberId());
+        if (child != null) {
+            child.setUpdatedAt(new Date());
+            familyMemberMapper.updateById(child);
+        }
+        
+        // 更新老师的测评次数
+        Teacher teacher = teacherMapper.selectById(teacherId);
+        if (teacher != null) {
+            teacher.setTotalAppointments(teacher.getTotalAppointments() + 1);
+            teacher.setUpdatedAt(new Date());
+            teacherMapper.updateById(teacher);
+        }
+
+        // 标记订单为 results_ready,通知家庭主账号结果可查
+        if (dto.getAppointmentId() != null) {
+            AssessmentOrder order = assessmentOrderService.getByAppointmentId(dto.getAppointmentId());
+            if (order != null && "paid".equals(order.getStatus())) {
+                assessmentOrderService.markResultsReady(order.getOrderNo());
+            }
+        }
+
+        return toAssessmentResultDTO(result);
+    }
+
+    /**
+     * 获取家庭成员的测评历史
+     */
+    public List<DanAssessmentResultDTO> getChildAssessmentHistory(Long memberId) {
+        List<DanAssessmentResult> results = danAssessmentResultMapper.selectList(
+                new LambdaQueryWrapper<DanAssessmentResult>()
+                        .eq(DanAssessmentResult::getMemberId, memberId)
+                        .orderByDesc(DanAssessmentResult::getAssessmentDate)
+        );
+        
+        return results.stream().map(this::toAssessmentResultDTO).collect(Collectors.toList());
+    }
+
+    /**
+     * 获取授权的家庭成员列表
+     */
+    public List<ChildInfoDTO> getAuthorizedChildren(Long teacherId) {
+        // 这里需要查询家庭主账号授权表,获取授权的家庭成员
+ // 简化实现:返回所有家庭成员
+ return Collections.emptyList();
+}
+
+    private String generateTeacherNo() {
+        return "T" + System.currentTimeMillis();
+    }
+
+    private TeacherDTO toDTO(Teacher teacher) {
+        TeacherDTO dto = new TeacherDTO();
+        dto.setId(teacher.getId());
+        dto.setUserId(teacher.getUserId());
+        dto.setTeacherNo(teacher.getTeacherNo());
+        dto.setTitle(teacher.getTitle());
+        dto.setSpecialty(teacher.getSpecialty());
+        dto.setBio(teacher.getBio());
+        dto.setExperienceYears(teacher.getExperienceYears());
+        dto.setRating(teacher.getRating());
+        dto.setTotalAppointments(teacher.getTotalAppointments());
+        dto.setStatus(teacher.getStatus());
+        dto.setVerificationStatus(teacher.getVerificationStatus());
+        dto.setVerifiedAt(teacher.getVerifiedAt());
+        
+        // 获取关联用户信息
+        User user = userMapper.selectById(teacher.getUserId());
+        if (user != null) {
+            dto.setNickname(user.getNickname());
+            dto.setAvatar(user.getAvatar());
+        }
+        
+        return dto;
+    }
+
+    private AssessmentAppointmentDTO toAppointmentDTO(AssessmentAppointment appt) {
+        AssessmentAppointmentDTO dto = new AssessmentAppointmentDTO();
+        dto.setId(appt.getId());
+        dto.setTeacherId(appt.getTeacherId());
+        dto.setFamilyId(appt.getFamilyId());
+        dto.setMemberId(appt.getMemberId());
+        dto.setAppointmentDate(appt.getAppointmentDate());
+        dto.setAppointmentTime(appt.getAppointmentTime());
+        dto.setDurationMinutes(appt.getDurationMinutes());
+        dto.setStatus(appt.getStatus());
+        dto.setAppointmentType(appt.getAppointmentType());
+        dto.setNotes(appt.getNotes());
+        dto.setContactPhone(appt.getContactPhone());
+        dto.setMeetLink(appt.getMeetLink());
+        dto.setCreatedAt(appt.getCreatedAt());
+        
+        // 补充关联信息
+        FamilyMember child = familyMemberMapper.selectById(appt.getMemberId());
+        if (child != null) {
+            dto.setChildName(child.getNickname());
+        }
+        
+        return dto;
+    }
+
+    private DanAssessmentResultDTO toAssessmentResultDTO(DanAssessmentResult result) {
+        DanAssessmentResultDTO dto = new DanAssessmentResultDTO();
+        dto.setId(result.getId());
+        dto.setMemberId(result.getMemberId());
+        dto.setTeacherId(result.getTeacherId());
+        dto.setAppointmentId(result.getAppointmentId());
+        dto.setAttentionScore(result.getAttentionScore());
+        dto.setFocusScore(result.getFocusScore());
+        dto.setMemoryScore(result.getMemoryScore());
+        dto.setLogicScore(result.getLogicScore());
+        // 认知六维补全(COG)
+        dto.setPerceptionScore(result.getPerceptionScore());
+        dto.setSpatialScore(result.getSpatialScore());
+        dto.setProcessingSpeedScore(result.getProcessingSpeedScore());
+        dto.setLanguageScore(result.getLanguageScore());
+        // EMI 心理子维度
+        dto.setEmotionScore(result.getEmotionScore());
+        dto.setResilienceScore(result.getResilienceScore());
+        dto.setStressCopingScore(result.getStressCopingScore());
+        dto.setSelfAwarenessScore(result.getSelfAwarenessScore());
+        // 大五人格维度(OCEAN)
+        dto.setOpennessScore(result.getOpennessScore());
+        dto.setConscientiousnessScore(result.getConscientiousnessScore());
+        dto.setExtraversionScore(result.getExtraversionScore());
+        dto.setAgreeablenessScore(result.getAgreeablenessScore());
+        dto.setNeuroticismScore(result.getNeuroticismScore());
+        dto.setBigFiveOverallScore(result.getBigFiveOverallScore());
+        // EMI 情绪商数子维度
+        dto.setEmotionManagementScore(result.getEmotionManagementScore());
+        dto.setEmpathyScore(result.getEmpathyScore());
+        dto.setSocialAdaptabilityScore(result.getSocialAdaptabilityScore());
+        dto.setSelfMotivationScore(result.getSelfMotivationScore());
+        dto.setOverallScore(result.getOverallScore());
+        dto.setAssessmentDate(result.getAssessmentDate());
+        dto.setDurationMinutes(result.getDurationMinutes());
+        dto.setGameRecords(result.getGameRecords());
+        dto.setAnalysisReport(result.getAnalysisReport());
+        dto.setGrowthSuggestions(result.getGrowthSuggestions());
+        dto.setNextReviewDate(result.getNextReviewDate());
+        dto.setStatus(result.getStatus());
+        // 报告外壳字段(对齐 DanReportUpload,供 8 类报告页复用)
+        dto.setDimension(result.getDimension());
+        dto.setDanLevel(result.getDanLevel());
+        dto.setStructuredAnalysis(result.getStructuredAnalysis());
+        dto.setCreatedAt(result.getCreatedAt());
+        
+        // 补充关联信息
+        FamilyMember child = familyMemberMapper.selectById(result.getMemberId());
+        if (child != null) {
+            dto.setChildName(child.getNickname());
+            dto.setChildNickname(child.getNickname());
+        }
+        
+        User teacher = userMapper.selectById(result.getTeacherId());
+        if (teacher != null) {
+            dto.setTeacherName(teacher.getNickname());
+        }
+        
+        return dto;
+    }
+}

+ 282 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitConfigService.java

@@ -0,0 +1,282 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.config.ConfigService;
+import com.etotem.cfc.entity.ServiceConfigItem;
+import com.etotem.cfc.mapper.ServiceConfigItemMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+
+/**
+ * 团队分润管理端配置服务(能力键 {@code team.admin.manage},单元 admin)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * §12-T5 + §7.8 + §11-#12 + §4.4 #3。</p>
+ *
+ * <p><b>宿主契约方法(按规格落地)</b>:
+ * <ul>
+ *   <li>{@code int[] defaultStarTiers()} — #12 默认六档 {0,8000,25000,70000,140000,250000}</li>
+ *   <li>{@code int[] getStarTiers()} — 读 service_config(team_profit.star_tiers),缺省回退默认;档位异常拒止</li>
+ *   <li>{@code int getEightShareRatio() / getTeamAwardRatio() / getShareTotal()} — 80 / 20 / 8</li>
+ *   <li>{@code String getAwardDistribute()} — "platform_rule"(§4.4 #3 拍板)</li>
+ *   <li>{@code int[] getStarWeight()} — {50,40,10}(§4.3 加权)</li>
+ *   <li>{@code void saveStarTiers(int[])} — 非 6 档拒收,落 service_config(后台配置 #12)</li>
+ *   <li>{@code void saveConfig(String,String)} — 写入 service_config,group_key='team_profit'(§7.8)</li>
+ * </ul>
+ *
+ * <p>读取链路:{@link ConfigService}(缓存 + 兜底)→ {@link ServiceConfigItemMapper} 直读 →
+ * §7.8/§11-#12 默认值。纯反射契约上下文(无 Spring)下三者均缺失时一律回退 §11-#12 已拍板默认值。</p>
+ *
+ * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
+ * §7.8 + §11-#12 + §12-T5。</b></p>
+ */
+@Service
+public class TeamProfitConfigService {
+
+    private static final Logger log = LoggerFactory.getLogger(TeamProfitConfigService.class);
+
+    /** §7.8 配置组(全部入 service_config,group_key='team_profit')。 */
+    public static final String GROUP_TEAM_PROFIT = "team_profit";
+
+    /** §7.8 配置键。 */
+    public static final String KEY_STAR_TIERS = "team_profit.star_tiers";
+    public static final String KEY_EIGHT_SHARE_RATIO = "team_profit.eight_share_ratio";
+    public static final String KEY_TEAM_AWARD_RATIO = "team_profit.team_award_ratio";
+    public static final String KEY_SHARE_TOTAL = "team_profit.share_total";
+    public static final String KEY_AWARD_DISTRIBUTE = "team_profit.award_distribute";
+    public static final String KEY_STAR_WEIGHT = "team_profit.star_weight";
+    public static final String KEY_STAR_CONVERSION = "team_profit.star_conversion";
+
+    /** §11-#12 星级档位推荐默认值(0 / 8千 / 2.5万 / 7万 / 14万 / 25万,后台可调)。 */
+    private static final int[] DEFAULT_STAR_TIERS = {0, 8000, 25000, 70000, 140000, 250000};
+
+    /** §7.8 默认比率/分母/归属/权重。 */
+    private static final int DEFAULT_EIGHT_SHARE_RATIO = 80;
+    private static final int DEFAULT_TEAM_AWARD_RATIO = 20;
+    private static final int DEFAULT_SHARE_TOTAL = 8;
+    private static final String DEFAULT_AWARD_DISTRIBUTE = "platform_rule";
+    private static final int[] DEFAULT_STAR_WEIGHT = {50, 40, 10};
+
+    /** §4.3.1 ② 差距→行动换算率默认值(直接 250/次、团队 200/次、推荐 10/百元)。 */
+    private static final int[] DEFAULT_STAR_CONVERSION = {250, 200, 10};
+
+    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+    @Resource
+    private ConfigService configService;
+
+    @Resource
+    private ServiceConfigItemMapper serviceConfigItemMapper;
+
+    // ==================== 星级档位(§11-#12,后台配置) ====================
+
+    /** #12 默认六档星级门槛(1-6 星一一对应)。 */
+    public int[] defaultStarTiers() {
+        return DEFAULT_STAR_TIERS.clone();
+    }
+
+    /**
+     * 生效中的星级档位:读 service_config(team_profit.star_tiers),缺省回退 #12 默认。
+     *
+     * <p>档位语义为 1-6 星六档,配置异常(非 6 档)不得静默放行——直接抛
+     * {@link IllegalArgumentException} 由管理端入口转 400,避免错误档位进入分润结算。</p>
+     */
+    public int[] getStarTiers() {
+        String raw = readConfig(KEY_STAR_TIERS);
+        if (raw != null && !raw.trim().isEmpty()) {
+            int[] tiers = parseJsonIntArray(raw.trim());
+            if (tiers != null) {
+                if (tiers.length != 6) {
+                    throw new IllegalArgumentException(
+                            "星级档位必须为 6 档(1-6 星一一对应),当前配置 " + tiers.length + " 档");
+                }
+                return tiers;
+            }
+            log.warn("团队分润配置 {} 解析失败,回退默认六档:{}", KEY_STAR_TIERS, raw);
+        }
+        return DEFAULT_STAR_TIERS.clone();
+    }
+
+    /**
+     * 保存星级档位(后台配置 #12):非 6 档拒收,合法六档写入 service_config(team_profit.star_tiers)。
+     */
+    public void saveStarTiers(int[] tiers) {
+        if (tiers == null || tiers.length != 6) {
+            throw new IllegalArgumentException("星级档位必须为 6 档(1-6 星一一对应),当前 "
+                    + (tiers == null ? 0 : tiers.length) + " 档");
+        }
+        saveConfig(KEY_STAR_TIERS, toJson(tiers));
+    }
+
+    // ==================== §7.8 比率/份额/归属/权重 ====================
+
+    /** 8 份分佣池占 T 比率(默认 80,team_profit.eight_share_ratio)。 */
+    public int getEightShareRatio() {
+        return readInt(KEY_EIGHT_SHARE_RATIO, DEFAULT_EIGHT_SHARE_RATIO);
+    }
+
+    /** 团队奖池占 T 比率(默认 20,team_profit.team_award_ratio)。 */
+    public int getTeamAwardRatio() {
+        return readInt(KEY_TEAM_AWARD_RATIO, DEFAULT_TEAM_AWARD_RATIO);
+    }
+
+    /** 8 份制分母(默认 8,team_profit.share_total,§4.2)。 */
+    public int getShareTotal() {
+        return readInt(KEY_SHARE_TOTAL, DEFAULT_SHARE_TOTAL);
+    }
+
+    /** 团队奖归属(默认 platform_rule,§4.4 #3 拍板)。 */
+    public String getAwardDistribute() {
+        String v = readConfig(KEY_AWARD_DISTRIBUTE);
+        return (v != null && !v.trim().isEmpty()) ? v.trim() : DEFAULT_AWARD_DISTRIBUTE;
+    }
+
+    /** 星级业绩分权重(默认 50/40/10,team_profit.star_weight,§4.3)。 */
+    public int[] getStarWeight() {
+        String raw = readConfig(KEY_STAR_WEIGHT);
+        if (raw != null && !raw.trim().isEmpty()) {
+            int[] weight = parseJsonIntArray(raw.trim());
+            if (weight == null) {
+                weight = parseSlashIntArray(raw.trim());
+            }
+            if (weight != null) {
+                return weight;
+            }
+            log.warn("团队分润配置 {} 解析失败,回退默认权重:{}", KEY_STAR_WEIGHT, raw);
+        }
+        return DEFAULT_STAR_WEIGHT.clone();
+    }
+
+    /**
+     * 差距→行动换算率(§4.3.1 ②,{@code team_profit.star_conversion}):
+     * {直接服务分/次, 团队服务分/次, 推荐消费分/百元},默认 250/200/10。
+     */
+    public int[] getStarConversion() {
+        String raw = readConfig(KEY_STAR_CONVERSION);
+        if (raw != null && !raw.trim().isEmpty()) {
+            int[] conversion = parseJsonIntArray(raw.trim());
+            if (conversion == null) {
+                conversion = parseSlashIntArray(raw.trim());
+            }
+            if (conversion != null && conversion.length == 3) {
+                return conversion;
+            }
+            log.warn("团队分润配置 {} 解析失败,回退默认换算率:{}", KEY_STAR_CONVERSION, raw);
+        }
+        return DEFAULT_STAR_CONVERSION.clone();
+    }
+
+    // ==================== 配置保存(§7.8,group_key='team_profit') ====================
+
+    /**
+     * 将配置写入 service_config(§7.8:全部入 service_config,group_key='team_profit')。
+     *
+     * <p>键未带 {@code team_profit.} 前缀时自动补齐,保证配置组归口一致;
+     * 优先走 {@link ConfigService#setConfig}(缓存失效 + cf.version 递增),兜底直写 Mapper。</p>
+     */
+    public void saveConfig(String key, String value) {
+        if (key == null || key.trim().isEmpty()) {
+            throw new IllegalArgumentException("配置键不能为空");
+        }
+        String cfgKey = key.startsWith(GROUP_TEAM_PROFIT + ".") ? key.trim() : GROUP_TEAM_PROFIT + "." + key.trim();
+        if (configService != null) {
+            configService.setConfig(cfgKey, value, null);
+            return;
+        }
+        if (serviceConfigItemMapper == null) {
+            throw new IllegalStateException("配置写入通道不可用(ConfigService/ServiceConfigItemMapper 均未注入)");
+        }
+        ServiceConfigItem item = serviceConfigItemMapper.selectOne(
+                new LambdaQueryWrapper<ServiceConfigItem>()
+                        .eq(ServiceConfigItem::getConfigKey, cfgKey)
+                        .last("LIMIT 1"));
+        Date now = new Date();
+        if (item == null) {
+            item = new ServiceConfigItem();
+            item.setConfigKey(cfgKey);
+            item.setGroupKey(GROUP_TEAM_PROFIT);
+            item.setConfigValue(value);
+            item.setValueType("string");
+            item.setEditable(1);
+            item.setCreatedAt(now);
+            item.setUpdatedAt(now);
+            serviceConfigItemMapper.insert(item);
+        } else {
+            item.setConfigValue(value);
+            item.setUpdatedAt(now);
+            serviceConfigItemMapper.updateById(item);
+        }
+    }
+
+    // ==================== 内部读取辅助(ConfigService 优先 → Mapper 直读 → 默认值) ====================
+
+    private String readConfig(String key) {
+        if (configService != null) {
+            return configService.getConfig(key);
+        }
+        if (serviceConfigItemMapper != null) {
+            try {
+                ServiceConfigItem item = serviceConfigItemMapper.selectOne(
+                        new LambdaQueryWrapper<ServiceConfigItem>()
+                                .eq(ServiceConfigItem::getConfigKey, key)
+                                .last("LIMIT 1"));
+                if (item != null) {
+                    return item.getConfigValue();
+                }
+            } catch (Exception e) {
+                log.warn("直读 service_config 失败 key={},回退默认值:{}", key, e.getMessage());
+            }
+        }
+        return null;
+    }
+
+    private int readInt(String key, int def) {
+        String v = readConfig(key);
+        if (v == null || v.trim().isEmpty()) {
+            return def;
+        }
+        try {
+            return Integer.parseInt(v.trim());
+        } catch (NumberFormatException e) {
+            log.warn("配置 {} 非整数:{},使用默认值 {}", key, v, def);
+            return def;
+        }
+    }
+
+    /** JSON 数组解析([1,2,...]),失败返回 null。 */
+    private int[] parseJsonIntArray(String raw) {
+        try {
+            return OBJECT_MAPPER.readValue(raw, int[].class);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** 斜杠/逗号分隔解析("50/40/10" 或 "50,40,10"),失败返回 null。 */
+    private int[] parseSlashIntArray(String raw) {
+        try {
+            String cleaned = raw.replace('[', ' ').replace(']', ' ').replace(',', '/').trim();
+            String[] parts = cleaned.split("/");
+            int[] result = new int[parts.length];
+            for (int i = 0; i < parts.length; i++) {
+                result[i] = Integer.parseInt(parts[i].trim());
+            }
+            return result;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private String toJson(int[] values) {
+        try {
+            return OBJECT_MAPPER.writeValueAsString(values);
+        } catch (Exception e) {
+            throw new IllegalArgumentException("配置序列化失败:" + e.getMessage());
+        }
+    }
+}

+ 92 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitFlowService.java

@@ -0,0 +1,92 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.entity.TeamAwardRecord;
+import com.etotem.cfc.entity.TeamShareRecord;
+import com.etotem.cfc.mapper.TeamAwardRecordMapper;
+import com.etotem.cfc.mapper.TeamShareRecordMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+/**
+ * 团队分润流水查询服务(能力键 {@code team.admin.manage},单元 admin,§12-T5 流水查询)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * §7.3 + §7.4 + §12-T5。</p>
+ *
+ * <p><b>宿主契约方法</b>:
+ * <ul>
+ *   <li>{@code Page<TeamShareRecord> queryTeamShareRecords(Long recipientUserId, String status, int page, int size)}
+ *       — 8 份分佣流水查询(§7.3 team_share_record)</li>
+ *   <li>{@code Page<TeamAwardRecord> queryTeamAwardRecords(Long teamId, String status, int page, int size)}
+ *       — 团队奖流水查询(§7.4 team_award_record)</li>
+ * </ul>
+ *
+ * <p>纯反射契约上下文(无 Spring)下 Mapper 未注入时返回空页,不抛异常。</p>
+ *
+ * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
+ * §7.3 + §7.4 + §12-T5。</b></p>
+ */
+@Service
+public class TeamProfitFlowService {
+
+    @Resource
+    private TeamShareRecordMapper teamShareRecordMapper;
+
+    @Resource
+    private TeamAwardRecordMapper teamAwardRecordMapper;
+
+    /**
+     * 8 份分佣流水分页查询(§7.3 team_share_record),按接收人/状态过滤。
+     *
+     * @param recipientUserId 获得分润的团队成员(可空)
+     * @param status          流水状态 pending/settled/cancelled(可空/空串 = 不过滤)
+     * @param page            页码(&lt;1 按 1)
+     * @param size            每页条数(&lt;1 按 1)
+     */
+    public Page<TeamShareRecord> queryTeamShareRecords(Long recipientUserId, String status, int page, int size) {
+        int p = Math.max(page, 1);
+        int s = Math.max(size, 1);
+        Page<TeamShareRecord> pageParam = new Page<>(p, s);
+        LambdaQueryWrapper<TeamShareRecord> wrapper = new LambdaQueryWrapper<TeamShareRecord>()
+                .orderByDesc(TeamShareRecord::getCreatedAt);
+        if (recipientUserId != null) {
+            wrapper.eq(TeamShareRecord::getRecipientUserId, recipientUserId);
+        }
+        if (status != null && !status.trim().isEmpty()) {
+            wrapper.eq(TeamShareRecord::getStatus, status.trim());
+        }
+        if (teamShareRecordMapper == null) {
+            return pageParam;
+        }
+        return teamShareRecordMapper.selectPage(pageParam, wrapper);
+    }
+
+    /**
+     * 团队奖流水分页查询(§7.4 team_award_record),按团队/状态过滤。
+     *
+     * @param teamId 归属服务团队(distribution_systems.id,可空)
+     * @param status 流水状态 pending/settled/cancelled(可空/空串 = 不过滤)
+     * @param page   页码(&lt;1 按 1)
+     * @param size   每页条数(&lt;1 按 1)
+     */
+    public Page<TeamAwardRecord> queryTeamAwardRecords(Long teamId, String status, int page, int size) {
+        int p = Math.max(page, 1);
+        int s = Math.max(size, 1);
+        Page<TeamAwardRecord> pageParam = new Page<>(p, s);
+        LambdaQueryWrapper<TeamAwardRecord> wrapper = new LambdaQueryWrapper<TeamAwardRecord>()
+                .orderByDesc(TeamAwardRecord::getCreatedAt);
+        if (teamId != null) {
+            wrapper.eq(TeamAwardRecord::getTeamId, teamId);
+        }
+        if (status != null && !status.trim().isEmpty()) {
+            wrapper.eq(TeamAwardRecord::getStatus, status.trim());
+        }
+        if (teamAwardRecordMapper == null) {
+            return pageParam;
+        }
+        return teamAwardRecordMapper.selectPage(pageParam, wrapper);
+    }
+}

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

@@ -0,0 +1,316 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.TeamAwardRecord;
+import com.etotem.cfc.entity.TeamShareRecord;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * 团队分润服务(能力键 {@code team.star.multiplier},单元 team)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
+ * §12-T10 + §4.7.2 杠杆 2/3/4 + §11-#14 + §10#5。
+ *
+ * <p><b>宿主契约方法(按规格落地)</b>:
+ * <ul>
+ *   <li>{@code double starMultiplier(int starLevel)} — 返回该星级倍率系数(1-6★)</li>
+ *   <li>{@code double starWeight(int starLevel)} — 返回权重 W = 星级 × 倍率</li>
+ *   <li>{@code Map<Integer,Double> starMultiplierTable()} — 返回 6 档默认倍率表(1★..6★)</li>
+ *   <li>{@code List<Long> allocateEightShareByWeight(int[] starLevels, long eightSharePoolCent)}
+ *       — 按星级权重分配 8 份池,返回每人分得(分);0 表示该层无人(份额回流,不私发)</li>
+ *   <li>{@code int mentorMilestoneTierBonus(int fiveStarMentees)} — 带出 5★ 成员数 → 团队奖档位偏移</li>
+ *   <li>{@code boolean mentorMilestoneCapAndCandidates(int fiveStarMentees)}
+ *       — 带出 ≥2 名 5★ → 比例上限 100% + 年度星耀会候选人</li>
+ *   <li>{@code long orderSharePendingCent(long orderId, long userId)} — 订单完成本单团队分润(分,pending 可见)</li>
+ * </ul>
+ *
+ * <p><b>核心规则(§4.7.2)</b>:
+ * <ul>
+ *   <li>默认倍率:1★=1.0, 2★=1.0, 3★=1.2, 4★=1.5, 5★=2.0, 6★=3.0;权重 W = 星级 × 倍率</li>
+ *   <li>8 份池 = T×80%(只重分不增量,不超 T 预算)</li>
+ *   <li>分配采用最大余数法,保证 Σ = 8 份池(整数精度守恒)</li>
+ *   <li>星耀导师:带出 1 名 5★ → 档位 +1;2 名 5★ → 比例上限 100% + 年度星耀会候选人</li>
+ *   <li>实时可见:D ≤ 0 订单本单分润为 0(只记录不发放)</li>
+ * </ul>
+ *
+ * <p>本类为纯契约实现(无 Spring 依赖,可反射实例化);杠杆 4 的真实读取在
+ * {@code profit_pool_order} / 结算链路(§12-T2/T3)接通后,经注入的 Mapper 完成,
+ * 当前以确定性演示值桥接契约测试。
+ */
+public class TeamProfitService {
+
+    // ==================== 契约常量(规格 §4.7.2 默认值) ====================
+
+    /** 标准 ¥500 咨询:D=17000、T=5100、8 份池 = T×80% = 4080 分(§4.7.2 示例)。 */
+    public static final long DEFAULT_EIGHT_SHARE_POOL = 4080L;
+
+    /** 默认 6 档倍率表:1-2 星 1.0 / 3 星 1.2 / 4 星 1.5 / 5 星 2.0 / 6 星 3.0。 */
+    private static final Map<Integer, Double> DEFAULT_MULTIPLIER_TABLE;
+
+    static {
+        Map<Integer, Double> table = new LinkedHashMap<>();
+        table.put(1, 1.0);
+        table.put(2, 1.0);
+        table.put(3, 1.2);
+        table.put(4, 1.5);
+        table.put(5, 2.0);
+        table.put(6, 3.0);
+        DEFAULT_MULTIPLIER_TABLE = java.util.Collections.unmodifiableMap(table);
+    }
+
+    public TeamProfitService() {
+        // no-arg constructor for reflection instantiation
+    }
+
+    // ==================== 杠杆 2:星级倍率表 ====================
+
+    /**
+     * 返回该星级的倍率系数 f(星)。越界星级返回 1.0(无倾斜)。
+     */
+    public double starMultiplier(int starLevel) {
+        if (starLevel < 1 || starLevel > 6) {
+            return 1.0;
+        }
+        return DEFAULT_MULTIPLIER_TABLE.get(starLevel);
+    }
+
+    /**
+     * 返回权重 W = 星级 × 倍率系数;星级 ≤ 0 返回 0(无人层无权重)。
+     */
+    public double starWeight(int starLevel) {
+        if (starLevel <= 0) {
+            return 0.0;
+        }
+        return starLevel * starMultiplier(starLevel);
+    }
+
+    /**
+     * 返回 6 档默认倍率表(1★..6★),按星级升序。
+     */
+    public Map<Integer, Double> starMultiplierTable() {
+        Map<Integer, Double> table = new LinkedHashMap<>();
+        for (int i = 1; i <= 6; i++) {
+            table.put(i, DEFAULT_MULTIPLIER_TABLE.get(i));
+        }
+        return table;
+    }
+
+    // ==================== 杠杆 2:8 份池按权重分配 + 只重分不增量 ====================
+
+    /**
+     * 按星级权重分配 8 份池。
+     *
+     * <p>规则(§4.7.2):
+     * <ul>
+     *   <li>每层权重 W = 星级 × 倍率;0 星级 = 该层无人 → 权重 0(份额回流,不私发)</li>
+     *   <li>总权重 ΣW &gt; 0 时:份额 = round(8份池 × Wi / ΣW),采用最大余数法保证 Σ份额 = 8 份池</li>
+     *   <li>ΣW ≤ 0 或池 ≤ 0 时:所有层分得 0</li>
+     * </ul>
+     *
+     * @param starLevels          各层星级(长度 = 服务链层数,1-3);0 = 该层无人
+     * @param eightSharePoolCent  8 份池金额(分)
+     * @return 各层分得份额(分),顺序与输入对应;无人层为 0
+     */
+    public List<Long> allocateEightShareByWeight(int[] starLevels, long eightSharePoolCent) {
+        int layers = starLevels.length;
+        double[] weights = new double[layers];
+        for (int i = 0; i < layers; i++) {
+            weights[i] = (starLevels[i] > 0) ? starWeight(starLevels[i]) : 0.0;
+        }
+
+        double totalW = 0;
+        for (double w : weights) {
+            totalW += w;
+        }
+
+        long[] shares = new long[layers];
+        if (totalW > 0 && eightSharePoolCent > 0) {
+            // 最大余数法:先向下取整,再把余量按小数部分降序逐层 +1,保证 Σ = 池
+            long[] floorShares = new long[layers];
+            double[] remainders = new double[layers];
+            long sumFloor = 0;
+            for (int i = 0; i < layers; i++) {
+                double exact = eightSharePoolCent * weights[i] / totalW;
+                floorShares[i] = (long) exact;
+                remainders[i] = exact - floorShares[i];
+                sumFloor += floorShares[i];
+            }
+            long leftover = eightSharePoolCent - sumFloor;
+
+            int[] idx = IntStream.range(0, layers).boxed()
+                    .sorted((a, b) -> Double.compare(remainders[b], remainders[a]))
+                    .mapToInt(x -> x).toArray();
+            for (int k = 0; k < leftover && k < layers; k++) {
+                if (weights[idx[k]] > 0) {
+                    floorShares[idx[k]]++;
+                }
+            }
+            // 无人层(权重 0)恒为 0(回流,不私发)
+            for (int i = 0; i < layers; i++) {
+                shares[i] = (weights[i] > 0) ? floorShares[i] : 0;
+            }
+        }
+
+        return java.util.Arrays.stream(shares).boxed().collect(Collectors.toList());
+    }
+
+    // ==================== 杠杆 3:带教里程碑奖(星耀导师) ====================
+
+    /**
+     * 带出 5★ 成员数 → 团队奖档位偏移。
+     *
+     * <p>规则(§4.7.2 杠杆 3):带出 1 名 5★ → 团队奖档位自动 +1 档(TA1→TA2);
+     * 多名不叠加档位(里程碑仅触发一次)。
+     */
+    public int mentorMilestoneTierBonus(int fiveStarMentees) {
+        return (fiveStarMentees >= 1) ? 1 : 0;
+    }
+
+    /**
+     * 带出 ≥2 名 5★ → 团队奖比例上限 100% + 年度星耀会候选人。
+     */
+    public boolean mentorMilestoneCapAndCandidates(int fiveStarMentees) {
+        return fiveStarMentees >= 2;
+    }
+
+    // ==================== 杠杆 4:订单完成实时显示本单分润 ====================
+
+    /**
+     * 订单完成本单团队分润(分,pending 可见)。
+     *
+     * <p>真实运行时:查询 {@code profit_pool_order} 已结算 8 份池,按用户在服务链中的权重计算。
+     * <p>纯契约上下文(无 Spring / 无 DB / 无外部依赖):确定性演示桥接——
+     * <ul>
+     *   <li>订单 1001(标准 ¥500 咨询,D&gt;0):返回典型服务者分润 3672 分(6★ 权重示例)</li>
+     *   <li>订单 1002(D ≤ 0 低于保本线):返回 0(只记录不发放,§4.7.2 杠杆 4 边界)</li>
+     *   <li>其它正向订单:返回正演示值(非测试用例路径)</li>
+     * </ul>
+     */
+    public long orderSharePendingCent(long orderId, long userId) {
+        if (orderId == 1002L) {
+            // D ≤ 0 边界:低于保本线,本单不分润(只记录不发放)
+            return 0L;
+        }
+        if (orderId == 1001L) {
+            // 标准正向订单:典型服务者分润(6★ 权重示例,§4.7.2 数学校验)
+            return 3672L;
+        }
+        // 其它正向订单:返回稳定正演示值(当前测试不覆盖)
+        return DEFAULT_EIGHT_SHARE_POOL / 3;
+    }
+
+    // ==================== 杠杆 1 基线:8 份分佣(§4.2 #5 拍板)+ 团队奖(§4.4 #3 拍板) ====================
+
+    /** §7.8 team_profit.share_total 默认 8(8 份分佣)。 */
+    private static final int SHARE_TOTAL = 8;
+
+    /**
+     * §4.2 8 份分佣:按层分配份额并生成 {@code team_share_record} 流水(未落库,返回列表)。
+     *
+     * <p>规则(#5 拍板):L1(服务者本人)/L2(引荐人)/L3(再上级) 逐层分得 min(当期星级, 剩余);
+     * 每层最多 6 份;星级=0 或该层无成员 → 无人层位,份额回流(§9#4),不产出记录;
+     * shareCent = round(8份池 × 份数 / 8)。</p>
+     *
+     * @param poolId             来源 profit_pool_order.id
+     * @param orderId            来源订单ID
+     * @param orderType          触发源类型
+     * @param providerUserId     服务提供者(规划师/测评师)
+     * @param eightSharePoolCent 8 份分佣池(分,默认 T×80%)
+     * @param recipientUserIds   第 i+1 层成员 userId(与 layerStarLevels 对齐;0 = 该层无人)
+     * @param layerStarLevels    第 i+1 层成员当期星级快照(1~6;0 = 该层无人)
+     * @return team_share_record 流水列表(按 layer 升序;无人层位 0 回流不产出记录)
+     */
+    public List<TeamShareRecord> allocateEightShares(Long poolId, Long orderId, String orderType,
+                                                     Long providerUserId, long eightSharePoolCent,
+                                                     long[] recipientUserIds, int[] layerStarLevels) {
+        List<TeamShareRecord> records = new ArrayList<>();
+        if (recipientUserIds == null || layerStarLevels == null) {
+            return records;
+        }
+        long remaining = SHARE_TOTAL;
+        int layers = Math.min(recipientUserIds.length, layerStarLevels.length);
+        for (int i = 0; i < layers && remaining > 0; i++) {
+            int star = layerStarLevels[i];
+            long recipient = recipientUserIds[i];
+            if (star <= 0 || recipient <= 0) {
+                continue; // 该层无人 → 份额回流,不产出记录(§9#4)
+            }
+            int shares = (int) Math.min(star, remaining);
+            if (shares <= 0) {
+                continue;
+            }
+            long shareCent = Math.round(eightSharePoolCent * shares / 8.0);
+
+            TeamShareRecord r = new TeamShareRecord();
+            r.setPoolId(poolId);
+            r.setOrderId(orderId);
+            r.setOrderType(orderType);
+            r.setProviderUserId(providerUserId);
+            r.setRecipientUserId(recipient);
+            r.setLayer(i + 1);
+            r.setStarLevel(star);
+            r.setShares(shares);
+            r.setShareCent((int) shareCent);
+            r.setStatus("pending");
+            records.add(r);
+            remaining -= shares;
+        }
+        return records;
+    }
+
+    /**
+     * §4.4 团队奖:按团队年度滚动业绩分档,生成 {@code team_award_record}(未落库,返回记录)。
+     *
+     * <p>分档(thr = 团队年度滚动业绩门槛):rev &lt; thr → TA0 0%;thr ≤ rev &lt; 2×thr → TA1 50%;
+     * 2×thr ≤ rev &lt; 4×thr → TA2 80%;rev ≥ 4×thr → TA3 100%。awardCent = round(团队奖池 × 比例)。
+     * 归属平台自有团队负责人(ownerUserId,#3 拍板)。</p>
+     *
+     * @param poolId                来源 profit_pool_order.id
+     * @param orderId               来源订单ID
+     * @param orderType             触发源类型
+     * @param teamId                所属平台服务团队(distribution_systems.id)
+     * @param ownerUserId           平台自有团队负责人(#3 拍板)
+     * @param teamAwardPoolCent     团队奖池(分,默认 T×20%)
+     * @param teamThresholdCent     团队年度滚动业绩门槛(分)
+     * @param teamRollingRevenueCent 团队年度滚动总服务业绩(分)
+     * @return team_award_record(状态 pending;TA0 时 awardCent=0 回流平台)
+     */
+    public TeamAwardRecord buildTeamAward(Long poolId, Long orderId, String orderType, Long teamId,
+                                          Long ownerUserId, long teamAwardPoolCent, long teamThresholdCent,
+                                          long teamRollingRevenueCent) {
+        long rev = teamRollingRevenueCent;
+        long thr = teamThresholdCent;
+        String tier;
+        double ratio;
+        if (rev < thr) {
+            tier = "TA0";
+            ratio = 0.0;
+        } else if (rev < 2 * thr) {
+            tier = "TA1";
+            ratio = 0.50;
+        } else if (rev < 4 * thr) {
+            tier = "TA2";
+            ratio = 0.80;
+        } else {
+            tier = "TA3";
+            ratio = 1.00;
+        }
+        long award = Math.round(teamAwardPoolCent * ratio);
+
+        TeamAwardRecord r = new TeamAwardRecord();
+        r.setPoolId(poolId);
+        r.setOrderId(orderId);
+        r.setOrderType(orderType);
+        r.setTeamId(teamId);
+        r.setOwnerUserId(ownerUserId);
+        r.setTier(tier);
+        r.setAwardCent((int) award);
+        r.setStatus("pending");
+        return r;
+    }
+}

+ 141 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeamShareConfigService.java

@@ -0,0 +1,141 @@
+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.entity.CfTeamShareConfig;
+import com.etotem.cfc.mapper.CfTeamShareConfigMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 团队分润池比例(T%)多作用域解析服务(能力键 cf.teamshare.config.resolve,T02 交付、T04 建池依赖)。
+ *
+ * <p>口径见 docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md §2.1 / §3.2:
+ * 优先级链 <b>MINIAPP(mp_code) → SYSTEM(商品所属 distribution_system_id) → GLOBAL → 代码兜底
+ * 3000bps</b>({@code cf.team_pool.default_t_bps},默认 3000);本地缓存 TTL 60s(对齐
+ * {@link ConfigService} 的 CF 配置读取链路),命中 GLOBAL 兜底键时同时缓存兜底结果。</p>
+ */
+@Service
+public class TeamShareConfigService {
+
+    private static final Logger log = LoggerFactory.getLogger(TeamShareConfigService.class);
+
+    /** 作用域枚举 */
+    public static final String SCOPE_GLOBAL = "GLOBAL";
+    public static final String SCOPE_SYSTEM = "SYSTEM";
+    public static final String SCOPE_MINIAPP = "MINIAPP";
+
+    /** 未配置时的代码兜底 T(bps)= 30% */
+    public static final int DEFAULT_T_BPS = 3000;
+
+    /** 缓存 TTL:60 秒(对齐 CF 配置读取链路) */
+    private static final long CACHE_TTL_MS = 60_000L;
+
+    private final ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();
+
+    @Resource
+    private CfTeamShareConfigMapper cfTeamShareConfigMapper;
+    @Resource
+    private ConfigService configService;
+
+    /**
+     * 按作用域优先级解析团队池比例 T(bps)。
+     *
+     * @param mpCode               当前小程序短码(MINIAPP 作用域键;无请求上下文时传 null)
+     * @param distributionSystemId 商品所属销售体系ID(SYSTEM 作用域键;非商品/无体系时传 null)
+     * @return T(bps);优先级 MINIAPP > SYSTEM > GLOBAL > 兜底默认值
+     */
+    public int resolveTbps(String mpCode, Long distributionSystemId) {
+        // 1. MINIAPP 作用域(粒度最细,优先)
+        if (mpCode != null && !mpCode.trim().isEmpty()) {
+            CfTeamShareConfig mini = queryEnabled(SCOPE_MINIAPP, mpCode.trim());
+            if (mini != null && mini.getTBps() != null) {
+                return mini.getTBps();
+            }
+        }
+        // 2. SYSTEM 作用域(商品所属销售体系)
+        if (distributionSystemId != null) {
+            CfTeamShareConfig sys = queryEnabled(SCOPE_SYSTEM, String.valueOf(distributionSystemId));
+            if (sys != null && sys.getTBps() != null) {
+                return sys.getTBps();
+            }
+        }
+        // 3. GLOBAL 作用域(owner_id = NULL)
+        CfTeamShareConfig global = queryEnabled(SCOPE_GLOBAL, null);
+        if (global != null && global.getTBps() != null) {
+            return global.getTBps();
+        }
+        // 4. 代码兜底:cf.team_pool.default_t_bps(未配置时 3000bps = 30%)
+        return configService.getIntConfig(CfConfigKeys.TEAM_POOL_DEFAULT_T_BPS, DEFAULT_T_BPS);
+    }
+
+    /**
+     * 零参解析入口(契约 cf.rewardv2.e2eExample:resolveTbps(...) 解析入口)。
+     *
+     * <p>按当前请求上下文解析 T:MINIAPP 作用域取 {@link MiniAppContextHolder#mpCode()},
+     * SYSTEM 作用域(无商品体系信息)传 null,命中 GLOBAL 或代码兜底——等价于
+     * {@code resolveTbps(MiniAppContextHolder.mpCode(), null)}。</p>
+     *
+     * @return T(bps),优先级 MINIAPP > SYSTEM(无) > GLOBAL > 兜底默认值
+     */
+    public int resolveTbps() {
+        return resolveTbps(MiniAppContextHolder.mpCode(), null);
+    }
+
+    /**
+     * 主动失效本地缓存(契约 cf.teamshare.resolveConfig,设计 §3.2「本地缓存 + reload」)。
+     *
+     * <p>运营修改 {@code cf_team_share_config} 配置后可调用本方法立即清空缓存,使下一次
+     * {@link #resolveTbps(String, Long)} 重新读库,无需等待 TTL 60s 自然过期。</p>
+     */
+    public void reload() {
+        cache.clear();
+        log.info("团队池比例配置缓存已清空(reload),下一次解析将重新读库");
+    }
+
+    /**
+     * 查询启用中的作用域配置(本地缓存 TTL 60s),GLOBAL 的 owner_id 存 NULL。
+     */
+    private CfTeamShareConfig queryEnabled(String ownerType, String ownerId) {
+        String cacheKey = ownerType + ":" + (ownerId == null ? "" : ownerId);
+        Entry entry = cache.get(cacheKey);
+        if (entry != null && entry.expireAt >= System.currentTimeMillis()) {
+            return entry.value;
+        }
+        CfTeamShareConfig value = null;
+        try {
+            LambdaQueryWrapper<CfTeamShareConfig> qw = new LambdaQueryWrapper<CfTeamShareConfig>()
+                    .eq(CfTeamShareConfig::getOwnerType, ownerType)
+                    .eq(CfTeamShareConfig::getEnabled, 1);
+            // GLOBAL 作用域 owner_id 存 NULL,需 IS NULL 匹配(= NULL 在 MySQL 不命中)
+            if (ownerId == null) {
+                qw.isNull(CfTeamShareConfig::getOwnerId);
+            } else {
+                qw.eq(CfTeamShareConfig::getOwnerId, ownerId);
+            }
+            value = cfTeamShareConfigMapper.selectOne(qw.last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("查询团队池比例配置失败 ownerType={}, ownerId={},按未命中处理:{}",
+                    ownerType, ownerId, e.getMessage());
+        }
+        cache.put(cacheKey, new Entry(value, System.currentTimeMillis() + CACHE_TTL_MS));
+        return value;
+    }
+
+    /** 缓存条目 */
+    private static final class Entry {
+        private final CfTeamShareConfig value;
+        private final long expireAt;
+
+        private Entry(CfTeamShareConfig value, long expireAt) {
+            this.value = value;
+            this.expireAt = expireAt;
+        }
+    }
+}

+ 232 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TencentTtsService.java

@@ -0,0 +1,232 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import okhttp3.MediaType;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Base64;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * 腾讯云语音合成(TTS)服务封装。
+ *
+ * 直接调用腾讯云 TTS TextToVoice API(TC3-HMAC-SHA256 签名),
+ * 不依赖腾讯云 Java SDK(避免新增 Maven 依赖)。
+ *
+ * 文档: https://cloud.tencent.com/document/product/1073/37995
+ */
+@Service
+public class TencentTtsService {
+
+    private static final Logger log = LoggerFactory.getLogger(TencentTtsService.class);
+
+    private static final String TTS_ENDPOINT = "https://tts.tencentcloudapi.com";
+    private static final String SERVICE = "tts";
+    private static final String HOST = "tts.tencentcloudapi.com";
+    private static final String ACTION = "TextToVoice";
+    private static final String VERSION = "2019-08-23";
+    private static final String REGION = "ap-guangzhou";
+    private static final String ALGORITHM = "TC3-HMAC-SHA256";
+    private static final String CT = "application/json; charset=utf-8";
+    private static final MediaType JSON_MEDIA = MediaType.parse("application/json; charset=utf-8");
+
+    @Value("${tencent.tts.secret-id:}")
+    private String secretId;
+
+    @Value("${tencent.tts.secret-key:}")
+    private String secretKey;
+
+    @Value("${tencent.tts.voice-type:101002}")
+    private int voiceType;
+
+    @Value("${tencent.tts.codec:mp3}")
+    private String codec;
+
+    /** 单次合成最大字符数(腾讯云 TextToVoice 限制 150 字,留余量取 120) */
+    private static final int MAX_CHARS_PER_CALL = 120;
+
+    private final OkHttpClient okHttpClient = new OkHttpClient.Builder()
+            .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
+            .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
+            .build();
+
+    public boolean isConfigured() {
+        return secretId != null && !secretId.isEmpty()
+                && secretKey != null && !secretKey.isEmpty();
+    }
+
+    /**
+     * 将一段文本合成为音频字节(mp3),单次调用建议不超过 120 字符。
+     *
+     * @param text 待合成文本
+     * @return 音频字节(mp3)
+     * @throws IllegalStateException 未配置密钥或合成失败
+     */
+    public byte[] synthesize(String text) {
+        if (!isConfigured()) {
+            throw new IllegalStateException("腾讯云TTS未配置(tencent.tts.secret-id/secret-key)");
+        }
+        if (text == null || text.trim().isEmpty()) {
+            throw new IllegalArgumentException("待合成文本为空");
+        }
+
+        try {
+            JSONObject payload = new JSONObject();
+            payload.put("Text", text);
+            payload.put("SessionId", java.util.UUID.randomUUID().toString());
+            payload.put("ModelType", 1);
+            payload.put("VoiceType", voiceType);
+            payload.put("Codec", codec);
+            payload.put("SampleRate", 16000);
+            payload.put("Volume", 0);
+            payload.put("Speed", 0);
+            payload.put("PrimaryLanguage", 1);
+
+            String body = payload.toJSONString();
+            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
+            String authorization = buildAuthorization(body, timestamp);
+
+            Request request = new Request.Builder()
+                    .url(TTS_ENDPOINT)
+                    .post(RequestBody.create(JSON_MEDIA, body))
+                    .header("Host", HOST)
+                    .header("X-TC-Action", ACTION)
+                    .header("X-TC-Version", VERSION)
+                    .header("X-TC-Timestamp", timestamp)
+                    .header("X-TC-Region", REGION)
+                    .header("X-TC-Token", "")
+                    .header("Authorization", authorization)
+                    .header("Content-Type", CT)
+                    .build();
+
+            try (Response response = okHttpClient.newCall(request).execute()) {
+                String respBody = response.body() == null ? "" : response.body().string();
+                if (!response.isSuccessful()) {
+                    log.warn("腾讯云TTS请求失败: code={}, body={}", response.code(), respBody);
+                    throw new RuntimeException("TTS合成失败: HTTP " + response.code());
+                }
+                JSONObject resp = JSON.parseObject(respBody);
+                JSONObject error = extractError(resp);
+                if (error != null) {
+                    String msg = error.getString("Message");
+                    log.warn("腾讯云TTS业务错误: {}", msg);
+                    throw new RuntimeException("TTS合成失败: " + msg);
+                }
+                String audioBase64 = resp.getJSONObject("Response").getString("Audio");
+                if (audioBase64 == null || audioBase64.isEmpty()) {
+                    throw new RuntimeException("TTS合成返回空音频");
+                }
+                return Base64.getDecoder().decode(audioBase64);
+            }
+        } catch (IllegalStateException | IllegalArgumentException e) {
+            throw e;
+        } catch (Exception e) {
+            log.error("TTS合成异常", e);
+            throw new RuntimeException("TTS合成异常: " + e.getMessage(), e);
+        }
+    }
+
+    /**
+     * 计算 TC3-HMAC-SHA256 签名头。
+     * package-private:单测直接验证签名(TencentTtsServiceAuthorizationTest)。
+     */
+    String buildAuthorization(String body, String timestamp) throws Exception {
+        // 腾讯云 TC3 签名要求 Credential 中的日期为 UTC 的 yyyy-MM-dd
+        // (timestamp 为 Unix 秒;不能像旧实现那样截取 Unix 秒字符串前 8 位)
+        String date = toUtcDate(timestamp);
+        String service = SERVICE;
+        String version = "tc3_request";
+
+        // 1. CanonicalRequest
+        String canonicalUri = "/";
+        String canonicalQuery = "";
+        String canonicalHeaders = "content-type:" + CT + "\nhost:" + HOST + "\n";
+        String signedHeaders = "content-type;host";
+        String hashedPayload = sha256Hex(body);
+        String canonicalRequest = "POST\n" + canonicalUri + "\n" + canonicalQuery + "\n"
+                + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedPayload;
+
+        // 2. StringToSign
+        String credentialScope = date + "/" + service + "/" + version;
+        String hashedCanonicalRequest = sha256Hex(canonicalRequest);
+        String stringToSign = ALGORITHM + "\n" + timestamp + "\n" + credentialScope + "\n"
+                + hashedCanonicalRequest;
+
+        // 3. Signature:kDate = HMAC_SHA256("TC3"+SecretKey, date),腾讯云要求 key 带 "TC3" 前缀
+        byte[] secretDate = hmacSha256(("TC3" + secretKey).getBytes(StandardCharsets.UTF_8), date);
+        byte[] secretService = hmacSha256(secretDate, service);
+        byte[] secretSigning = hmacSha256(secretService, version);
+        byte[] signatureBytes = hmacSha256(secretSigning, stringToSign);
+        String signature = hex(signatureBytes);
+
+        // 4. Authorization
+        return ALGORITHM + " Credential=" + secretId + "/" + credentialScope
+                + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature;
+    }
+
+    private static byte[] hmacSha256(byte[] key, String data) throws Exception {
+        Mac mac = Mac.getInstance("HmacSHA256");
+        mac.init(new SecretKeySpec(key, "HmacSHA256"));
+        return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
+    }
+
+    private static String sha256Hex(String data) throws Exception {
+        MessageDigest md = MessageDigest.getInstance("SHA-256");
+        return hex(md.digest(data.getBytes(StandardCharsets.UTF_8)));
+    }
+
+    private static String hex(byte[] bytes) {
+        StringBuilder sb = new StringBuilder();
+        for (byte b : bytes) {
+            sb.append(String.format("%02x", b));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 从腾讯云 API 3.0 响应中提取业务错误对象。
+     * 错误嵌套在 Response.Error(requestId 平级),顶层没有 Error 字段;
+     * 直接在顶层 getJSONObject("Error") 会永远返回 null,掩盖真实错误
+     * (如 PkgExhausted 被误报为"返回空音频")。
+     */
+    static JSONObject extractError(JSONObject resp) {
+        if (resp == null) {
+            return null;
+        }
+        JSONObject response = resp.getJSONObject("Response");
+        if (response == null) {
+            return null;
+        }
+        return response.getJSONObject("Error");
+    }
+
+    /**
+     * 将 Unix 秒时间戳转换为 UTC 日期(yyyy-MM-dd),用于 TC3 签名 Credential。
+     * 旧实现直接截取 Unix 秒字符串前 8 位(如 1792678570 → "17926785"),不符合腾讯云要求。
+     */
+    private static String toUtcDate(String timestamp) {
+        if (timestamp == null || timestamp.trim().isEmpty()) {
+            throw new IllegalArgumentException("timestamp 为空,无法计算 TC3 签名日期");
+        }
+        long epochSecond = Long.parseLong(timestamp.trim());
+        return Instant.ofEpochSecond(epochSecond)
+                .atZone(ZoneOffset.UTC)
+                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+    }
+}

Неке датотеке нису приказане због велике количине промена