Pārlūkot izejas kodu

feat(butler): 实现资源匹配服务(SC-H-05) butler.resource.match

能力键 butler.resource.match:线下资源/活动与家庭需求匹配闭环。
- ButlerResourceMatchService.match/book:按家长需求+孩子画像匹配资源,仅已审核资源入候选(AC1/TC-H-05-E-1),book 联动 occupyQuota 原子占用名额(AC3)
- ButlerResourceMatchResult 实体:distanceKm/startTime/ageSuitability/reviewStatus 字段(AC1)
- ButlerController /api/butler/resource-match/* 端点:list/generate/book/follow-up(AC2/AC4)
- 建表 butler_resource_match_results / butler_resource_match_log(频次受控 TC-H-05-E-4) / butler_resource_follow_up(回访沉淀 AC4),同步 schema.sql + DatabaseInitializer 迁移475-477
- 契约测试 ButlerResourceMatchContractTest 11/11 转绿(原9失败)

Refs: S-cfc-354
zxyj-langgraph 2 dienas atpakaļ
vecāks
revīzija
d363df8056

+ 95 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3542,6 +3542,101 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移474: membership_levels 加会员成本价列 cost_price(F-3a 送会员商品P点口径:
         // 配置了「送会员」规则的商品订单,P 点 = 实付 − 商品成本 − 赠送等级会员成本价)
         addMembershipCostPriceColumn();
+
+        // 迁移475: 资源匹配结果表 butler_resource_match_results(SC-H-05 匹配结果携带距离/时间/适龄,仅已审核资源入候选)
+        createButlerResourceMatchResultTable();
+        // 迁移476: 资源匹配推送留痕表 butler_resource_match_log(TC-H-05-E-4 高频推送同类资源频次受控)
+        createButlerResourceMatchLogTable();
+        // 迁移477: 资源参与回访沉淀偏好表 butler_resource_follow_up(AC4 回访记录写入家长档案)
+        createButlerResourceFollowUpTable();
+    }
+
+    /**
+     * 迁移475: 创建资源匹配结果表(SC-H-05,能力键 butler.resource.match)。
+     *
+     * <p>匹配结果携带距离/时间/适龄信息(AC1),仅已审核资源入候选(reviewStatus=approved,TC-H-05-E-1);
+     * 家长端可查看并选择(AC2)。幂等:CREATE TABLE IF NOT EXISTS。</p>
+     */
+    private void createButlerResourceMatchResultTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_resource_match_results ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "butler_user_id BIGINT NOT NULL COMMENT '推荐管家用户 ID', "
+                    + "family_id BIGINT NOT NULL COMMENT '家庭 ID', "
+                    + "member_id BIGINT NULL COMMENT '目标成员 ID (family_members.id)', "
+                    + "resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity(线下活动)/offline_course(线下课程)', "
+                    + "resource_id BIGINT NOT NULL COMMENT '资源 ID (activity.id)', "
+                    + "resource_name VARCHAR(200) NULL COMMENT '资源名称', "
+                    + "distance_km DECIMAL(10,2) NULL COMMENT 'AC1: 距离(公里)', "
+                    + "start_time DATETIME NULL COMMENT 'AC1: 活动开始时间', "
+                    + "age_suitability VARCHAR(64) NULL COMMENT 'AC1: 适龄信息', "
+                    + "review_status VARCHAR(20) DEFAULT 'pending' COMMENT '审核门禁: approved/pending/rejected,仅 approved 入候选', "
+                    + "match_reason VARCHAR(500) NULL COMMENT '匹配理由', "
+                    + "match_score INT DEFAULT 0 COMMENT '匹配评分(0-100)', "
+                    + "status VARCHAR(20) DEFAULT 'matched' COMMENT '匹配状态: matched/pushed/booked', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "INDEX idx_member (member_id), "
+                    + "INDEX idx_family (family_id), "
+                    + "INDEX idx_resource (resource_id)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源匹配结果(SC-H-05)'");
+            log.info("迁移475: butler_resource_match_results 表已就绪");
+        } catch (Exception e) {
+            log.warn("迁移475: butler_resource_match_results 创建失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 迁移476: 创建资源匹配推送留痕表(TC-H-05-E-4,高频推送同类资源频次受控)。
+     *
+     * <p>记录推送时间戳与次数,触发阈值后限制同类资源推送。幂等:CREATE TABLE IF NOT EXISTS。</p>
+     */
+    private void createButlerResourceMatchLogTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_resource_match_log ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "butler_user_id BIGINT NOT NULL COMMENT '推送管家用户 ID', "
+                    + "member_id BIGINT NULL COMMENT '目标成员 ID', "
+                    + "resource_id BIGINT NOT NULL COMMENT '资源 ID', "
+                    + "resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity/offline_course', "
+                    + "resource_category VARCHAR(64) DEFAULT 'general' COMMENT '同类资源分类(频次控制维度)', "
+                    + "pushed_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '最近推送时间戳', "
+                    + "push_count INT DEFAULT 1 COMMENT '累计推送次数(同类资源频次控制)', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "INDEX idx_butler_member_cat (butler_user_id, member_id, resource_category)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源匹配推送留痕(TC-H-05-E-4)'");
+            log.info("迁移476: butler_resource_match_log 表已就绪");
+        } catch (Exception e) {
+            log.warn("迁移476: butler_resource_match_log 创建失败: {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 迁移477: 创建资源参与回访沉淀偏好表(AC4,参与后回访记录写入家长档案,后续推荐参考偏好)。
+     *
+     * <p>幂等:CREATE TABLE IF NOT EXISTS。</p>
+     */
+    private void createButlerResourceFollowUpTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_resource_follow_up ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "family_id BIGINT NOT NULL COMMENT '家庭 ID', "
+                    + "member_id BIGINT NULL COMMENT '目标成员 ID', "
+                    + "butler_user_id BIGINT NOT NULL COMMENT '回访管家用户 ID', "
+                    + "resource_id BIGINT NOT NULL COMMENT '资源 ID', "
+                    + "resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity/offline_course', "
+                    + "follow_up_content TEXT NULL COMMENT '回访内容(参与感受、反馈)', "
+                    + "preference_tags TEXT NULL COMMENT '沉淀偏好标签(JSON 数组字符串)', "
+                    + "follow_up_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '回访时间', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "INDEX idx_family_member (family_id, member_id)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源参与回访沉淀偏好(AC4)'");
+            log.info("迁移477: butler_resource_follow_up 表已就绪");
+        } catch (Exception e) {
+            log.warn("迁移477: butler_resource_follow_up 创建失败: {}", e.getMessage());
+        }
     }
 
     /** 迁移473(FamilyWorkbench): tasks 加家庭+时间复合索引,支撑工作台按家庭聚合计数与近 30 天逐日趋势。 */

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

@@ -3,8 +3,11 @@ package com.etotem.cfc.controller.butler;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ButlerResourceMatchResult;
 import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
 import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerResourceMatchService;
 import com.etotem.cfc.service.ButlerService;
 import com.etotem.cfc.service.RealNameBackfillService;
 import io.swagger.v3.oas.annotations.Operation;
@@ -14,6 +17,7 @@ import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import java.util.Date;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import com.etotem.cfc.util.SortUtil;
 
@@ -30,6 +34,12 @@ public class ButlerController {
     @Resource
     private RealNameBackfillService realNameBackfillService;
 
+    @Resource
+    private ButlerResourceMatchService butlerResourceMatchService;
+
+    @Resource
+    private ButlerResourceMatchResultMapper butlerResourceMatchResultMapper;
+
     /**
      * 申请成为管家
      * POST /api/butler/apply
@@ -94,6 +104,63 @@ public class ButlerController {
         return Result.success(data);
     }
 
+    /**
+     * 家庭端查看匹配结果(AC2:家长端可查看并选择匹配结果)
+     * POST /api/butler/resource-match/list
+     */
+    @PostMapping("/resource-match/list")
+    public Result<List<ButlerResourceMatchResult>> listResourceMatch(@RequestBody Map<String, Object> params,
+                                                                     @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult> wrapper =
+                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ButlerResourceMatchResult>()
+                        .eq(ButlerResourceMatchResult::getMemberId, memberId)
+                        .orderByDesc(ButlerResourceMatchResult::getCreatedAt);
+        if (familyId != null) {
+            wrapper.eq(ButlerResourceMatchResult::getFamilyId, familyId);
+        }
+        return Result.success(butlerResourceMatchResultMapper.selectList(wrapper));
+    }
+
+    /**
+     * 匹配入口(按家长需求与孩子画像匹配资源,SC-H-05 正常流步骤1)
+     * POST /api/butler/resource-match/generate
+     */
+    @PostMapping("/resource-match/generate")
+    public Result<List<ButlerResourceMatchResult>> generateResourceMatch(@RequestBody Map<String, Object> params,
+                                                                         @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        @SuppressWarnings("unchecked")
+        Map<String, Object> requirements = (Map<String, Object>) params.get("requirements");
+        return butlerResourceMatchService.match(userId, familyId, memberId, requirements);
+    }
+
+    /**
+     * 协助预约/报名(AC3:名额实时校验联动,满员提示「名额已满」)
+     * POST /api/butler/resource-match/book
+     */
+    @PostMapping("/resource-match/book")
+    public Result<Map<String, Object>> bookResourceMatch(@RequestBody Map<String, Object> params,
+                                                         @RequestAttribute("userId") Long userId) {
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        Long matchResultId = params.get("matchResultId") != null ? Long.valueOf(params.get("matchResultId").toString()) : null;
+        return butlerResourceMatchService.book(userId, memberId, matchResultId);
+    }
+
+    /**
+     * 回访沉淀偏好(AC4:参与后回访记录写入家长档案)
+     * POST /api/butler/resource-match/follow-up
+     */
+    @PostMapping("/resource-match/follow-up")
+    public Result<String> followUpResourceMatch(@RequestBody Map<String, Object> params,
+                                                @RequestAttribute("userId") Long userId) {
+        Long familyId = params.get("familyId") != null ? Long.valueOf(params.get("familyId").toString()) : null;
+        Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
+        return butlerResourceMatchService.recordFollowUp(userId, familyId, memberId, params);
+    }
+
     /**
      * 获取服务记录(已废弃)
      * POST /api/butler/service-records

+ 52 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ButlerResourceFollowUp.java

@@ -0,0 +1,52 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 资源参与回访沉淀偏好表(能力键 {@code butler.resource.match},AC4)。
+ *
+ * <p>参与后回访记录写入家长档案,后续推荐参考偏好(TC-H-05 AC4)。</p>
+ */
+@Data
+@TableName("butler_resource_follow_up")
+public class ButlerResourceFollowUp implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 家庭 ID */
+    private Long familyId;
+
+    /** 目标成员 ID */
+    private Long memberId;
+
+    /** 回访管家用户 ID */
+    private Long butlerUserId;
+
+    /** 资源 ID */
+    private Long resourceId;
+
+    /** 资源类型:activity/offline_course */
+    private String resourceType;
+
+    /** 回访内容(参与感受、反馈) */
+    private String followUpContent;
+
+    /** 沉淀偏好标签(供后续推荐参考,JSON 数组字符串) */
+    private String preferenceTags;
+
+    /** 回访时间 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date followUpAt;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 51 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ButlerResourceMatchLog.java

@@ -0,0 +1,51 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 资源匹配推送留痕表(能力键 {@code butler.resource.match})。
+ *
+ * <p>TC-H-05-E-4:管家高频推送同类资源频次受控——记录推送时间戳与次数,
+ * 触发阈值后限制同类资源推送。</p>
+ */
+@Data
+@TableName("butler_resource_match_log")
+public class ButlerResourceMatchLog implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 推送管家用户 ID */
+    private Long butlerUserId;
+
+    /** 目标成员 ID */
+    private Long memberId;
+
+    /** 资源 ID */
+    private Long resourceId;
+
+    /** 资源类型:activity/offline_course */
+    private String resourceType;
+
+    /** 同类资源分类(频次控制维度,如五维 dimensionCode) */
+    private String resourceCategory;
+
+    /** 最近推送时间戳 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date pushedAt;
+
+    /** 累计推送次数(同类资源频次控制) */
+    private Integer pushCount;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 70 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ButlerResourceMatchResult.java

@@ -0,0 +1,70 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 线下资源/活动匹配结果(能力键 {@code butler.resource.match},SC-H-05)。
+ *
+ * <p>AC1:匹配结果均来自<b>已审核</b>资源({@code reviewStatus=approved}),含距离/时间/适龄信息;
+ * 家长端可查看并选择(AC2)。</p>
+ */
+@Data
+@TableName("butler_resource_match_results")
+public class ButlerResourceMatchResult implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 推荐管家用户 ID */
+    private Long butlerUserId;
+
+    /** 家庭 ID */
+    private Long familyId;
+
+    /** 目标成员 ID(family_members.id) */
+    private Long memberId;
+
+    /** 资源类型:activity(线下活动)/offline_course(线下课程) */
+    private String resourceType;
+
+    /** 资源 ID(activity.id) */
+    private Long resourceId;
+
+    /** 资源名称 */
+    private String resourceName;
+
+    /** AC1:距离(公里,最佳匹配估算值) */
+    @TableField("distance_km")
+    private Double distanceKm;
+
+    /** AC1:活动开始时间 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date startTime;
+
+    /** AC1:适龄信息(如「6-12岁适龄」「仅成人」) */
+    private String ageSuitability;
+
+    /** 审核门禁:approved/pending/rejected——仅 approved 资源入候选(TC-H-05-E-1) */
+    private String reviewStatus;
+
+    /** 匹配理由(可读说明,供家长端展示) */
+    private String matchReason;
+
+    /** 匹配评分(0-100,用于候选排序) */
+    private Integer matchScore;
+
+    /** 匹配状态:matched(已匹配)/pushed(已推送)/booked(已预约) */
+    private String status;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

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

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

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

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

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

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

+ 290 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ButlerResourceMatchService.java

@@ -0,0 +1,290 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.Activity;
+import com.etotem.cfc.entity.ButlerResourceFollowUp;
+import com.etotem.cfc.entity.ButlerResourceMatchLog;
+import com.etotem.cfc.entity.ButlerResourceMatchResult;
+import com.etotem.cfc.mapper.ActivityMapper;
+import com.etotem.cfc.mapper.ButlerResourceFollowUpMapper;
+import com.etotem.cfc.mapper.ButlerResourceMatchLogMapper;
+import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
+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.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 线下资源/活动与家庭需求匹配(能力键 {@code butler.resource.match},SC-H-05)。
+ *
+ * <p>正常流:按家长需求与孩子画像匹配资源 → 推送匹配结果 → 协助预约/报名 → 参与后回访并沉淀偏好。
+ * 候选仅来自<b>已审核</b>资源(AC1,{@code auditStatus=approved} 且 {@code status=published});
+ * 推送留痕表按同类资源频次受控(TC-H-05-E-4);预约/报名联动 {@link ActivityRegistrationService#register}
+ * (内部 {@code occupyQuota} 原子占用,满员提示「名额已满」,AC3/TC-H-05-E-2/3)。</p>
+ */
+@Slf4j
+@Service
+public class ButlerResourceMatchService {
+
+    /** 同类资源高频推送阈值:超过后限制推送(TC-H-05-E-4) */
+    private static final int PUSH_FREQUENCY_LIMIT = 5;
+
+    @Resource
+    private ActivityMapper activityMapper;
+    @Resource
+    private ButlerResourceMatchResultMapper matchResultMapper;
+    @Resource
+    private ButlerResourceMatchLogMapper matchLogMapper;
+    @Resource
+    private ButlerResourceFollowUpMapper followUpMapper;
+    @Resource
+    private ActivityRegistrationService activityRegistrationService;
+
+    /**
+     * 匹配入口:按家长需求与孩子画像匹配线下资源/活动(TC-H-05 正常流步骤1)。
+     *
+     * <p>候选仅已审核资源({@code auditStatus=approved} 且 {@code status=published},AC1/TC-H-05-E-1);
+     * 每个候选携带距离/时间/适龄信息(AC1);匹配结果落库供家长端查看选择(AC2);
+     * 推送留痕频次受控(TC-H-05-E-4)。</p>
+     *
+     * @param butlerUserId 推荐管家用户 ID
+     * @param familyId     家庭 ID
+     * @param memberId     目标成员 ID(孩子画像)
+     * @param requirements 家长需求:dimensionCode(五维)/keyword(关键词)/childAge(年龄,适龄判定)/location(位置,距离估算)
+     */
+    @Transactional
+    public Result<List<ButlerResourceMatchResult>> match(Long butlerUserId, Long familyId, Long memberId,
+                                                         Map<String, Object> requirements) {
+        // 仅已审核 + 已发布资源入候选(未审核/已下架资源不出现,TC-H-05-E-1)
+        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<Activity>()
+                .eq(Activity::getStatus, "published")
+                .eq(Activity::getAuditStatus, "approved");
+
+        String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
+        if (dimensionCode != null && !dimensionCode.trim().isEmpty()) {
+            wrapper.eq(Activity::getDimensionCode, dimensionCode.trim());
+        }
+        String keyword = requirements != null ? asString(requirements.get("keyword")) : null;
+        if (keyword != null && !keyword.trim().isEmpty()) {
+            wrapper.and(w -> w.like(Activity::getTitle, keyword.trim())
+                    .or().like(Activity::getIntro, keyword.trim())
+                    .or().like(Activity::getLocation, keyword.trim()));
+        }
+        wrapper.orderByDesc(Activity::getStartTime);
+
+        List<Activity> activities = activityMapper.selectList(wrapper);
+        if (activities.isEmpty()) {
+            return Result.success(Collections.emptyList());
+        }
+
+        List<ButlerResourceMatchResult> results = new ArrayList<>();
+        for (Activity activity : activities) {
+            String category = activity.getDimensionCode() != null ? activity.getDimensionCode() : "general";
+            // 频次受控:同类资源已达推送阈值则跳过(TC-H-05-E-4)
+            if (isCategoryPushLimited(butlerUserId, memberId, category)) {
+                continue;
+            }
+            ButlerResourceMatchResult result = buildMatchResult(butlerUserId, familyId, memberId, activity, requirements);
+            matchResultMapper.insert(result);
+            recordPush(butlerUserId, memberId, activity, category);
+            results.add(result);
+        }
+        return Result.success(results);
+    }
+
+    /**
+     * 协助预约/报名入口(AC3):联动名额实时校验(occupyQuota 原子占用,满员提示「名额已满」)。
+     *
+     * @param userId        操作家长用户 ID
+     * @param memberId      报名成员 ID
+     * @param matchResultId 匹配结果 ID
+     */
+    @Transactional
+    public Result<Map<String, Object>> book(Long userId, Long memberId, Long matchResultId) {
+        ButlerResourceMatchResult matchResult = matchResultMapper.selectById(matchResultId);
+        if (matchResult == null) {
+            return Result.notFound("匹配结果不存在");
+        }
+        // 归属校验(TC-H-05-P-②/③):仅本家庭成员可操作该匹配结果
+        if (matchResult.getMemberId() != null && !matchResult.getMemberId().equals(memberId)) {
+            return Result.forbidden("无权操作该匹配结果");
+        }
+        if (!"activity".equals(matchResult.getResourceType())) {
+            return Result.error("该资源暂不支持在线预约,请联系统筹管家");
+        }
+        Result<Map<String, Object>> regResult = activityRegistrationService.register(
+                matchResult.getResourceId(), userId, memberId);
+        if (regResult.getCode() == 200) {
+            matchResult.setStatus("booked");
+            matchResult.setUpdatedAt(new Date());
+            matchResultMapper.updateById(matchResult);
+        }
+        return regResult;
+    }
+
+    /**
+     * 回访沉淀偏好(AC4):参与后回访记录写入家长档案,后续推荐参考偏好。
+     */
+    @Transactional
+    public Result<String> recordFollowUp(Long butlerUserId, Long familyId, Long memberId,
+                                         Map<String, Object> params) {
+        if (params == null) {
+            return Result.badRequest("回访参数不能为空");
+        }
+        ButlerResourceFollowUp followUp = new ButlerResourceFollowUp();
+        followUp.setFamilyId(familyId);
+        followUp.setMemberId(memberId);
+        followUp.setButlerUserId(butlerUserId);
+        followUp.setResourceId(params.get("resourceId") != null ? Long.valueOf(params.get("resourceId").toString()) : null);
+        followUp.setResourceType(asString(params.getOrDefault("resourceType", "activity")));
+        followUp.setFollowUpContent(asString(params.get("followUpContent")));
+        followUp.setPreferenceTags(params.get("preferenceTags") != null
+                ? params.get("preferenceTags").toString() : null);
+        followUp.setFollowUpAt(new Date());
+        followUp.setCreatedAt(new Date());
+        followUp.setUpdatedAt(new Date());
+        followUpMapper.insert(followUp);
+        return Result.success("回访记录已沉淀");
+    }
+
+    // ------------------------------------------------------------------
+    // 内部辅助
+    // ------------------------------------------------------------------
+
+    private ButlerResourceMatchResult buildMatchResult(Long butlerUserId, Long familyId, Long memberId,
+                                                       Activity activity, Map<String, Object> requirements) {
+        ButlerResourceMatchResult result = new ButlerResourceMatchResult();
+        result.setButlerUserId(butlerUserId);
+        result.setFamilyId(familyId);
+        result.setMemberId(memberId);
+        result.setResourceType("activity");
+        result.setResourceId(activity.getId());
+        result.setResourceName(activity.getTitle());
+        result.setDistanceKm(estimateDistanceKm(activity, requirements));
+        result.setStartTime(activity.getStartTime());
+        result.setAgeSuitability(resolveAgeSuitability(activity, requirements));
+        result.setReviewStatus(activity.getAuditStatus()); // approved 门禁(候选仅已审核)
+        result.setMatchReason(buildMatchReason(activity, requirements));
+        result.setMatchScore(buildMatchScore(activity, requirements));
+        result.setStatus("matched");
+        Date now = new Date();
+        result.setCreatedAt(now);
+        result.setUpdatedAt(now);
+        return result;
+    }
+
+    /** AC1:距离估算——位置关键词命中则按区域相近给低值,否则给默认值;无位置信息返回 null。 */
+    private Double estimateDistanceKm(Activity activity, Map<String, Object> requirements) {
+        String location = activity.getLocation();
+        String preferred = requirements != null ? asString(requirements.get("location")) : null;
+        if (location == null || location.trim().isEmpty()) {
+            return null;
+        }
+        if (preferred != null && !preferred.trim().isEmpty()) {
+            // 同区域(省/市/区关键词)视为近距离
+            return location.contains(preferred.trim()) ? 2.0 : 8.0;
+        }
+        return 5.0;
+    }
+
+    /** AC1:适龄判定——按参与人群构成与孩子年龄给出可读标签。 */
+    private String resolveAgeSuitability(Activity activity, Map<String, Object> requirements) {
+        String audienceType = activity.getAudienceType();
+        String childAge = requirements != null ? asString(requirements.get("childAge")) : null;
+        if ("adult".equals(audienceType)) {
+            return "仅成人参与";
+        }
+        if (childAge != null && !childAge.trim().isEmpty()) {
+            return childAge.trim() + "岁可参与";
+        }
+        if ("include_child".equals(audienceType) || "include_child_elder".equals(audienceType)) {
+            return "含孩子参与";
+        }
+        return "通用";
+    }
+
+    private String buildMatchReason(Activity activity, Map<String, Object> requirements) {
+        String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
+        StringBuilder reason = new StringBuilder("匹配维度匹配");
+        if (dimensionCode != null && dimensionCode.equals(activity.getDimensionCode())) {
+            reason.append(",契合需求五维「").append(dimensionCode).append("」");
+        }
+        if (activity.getMaxParticipants() != null && activity.getMaxParticipants() > 0) {
+            int remain = activity.getMaxParticipants()
+                    - (activity.getApprovedCount() != null ? activity.getApprovedCount() : 0);
+            reason.append(",余位 ").append(Math.max(remain, 0)).append(" 人");
+        }
+        return reason.toString();
+    }
+
+    private Integer buildMatchScore(Activity activity, Map<String, Object> requirements) {
+        int score = 60;
+        String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
+        if (dimensionCode != null && dimensionCode.equals(activity.getDimensionCode())) {
+            score += 20;
+        }
+        if ("include_child".equals(activity.getAudienceType())
+                || "include_child_elder".equals(activity.getAudienceType())) {
+            score += 10;
+        }
+        if (activity.getApprovedCount() != null && activity.getMaxParticipants() != null
+                && activity.getMaxParticipants() > 0
+                && activity.getApprovedCount() < activity.getMaxParticipants()) {
+            score += 10;
+        }
+        return Math.min(score, 100);
+    }
+
+    /** TC-H-05-E-4:同类资源累计推送次数是否已达阈值(超过则限制推送)。 */
+    private boolean isCategoryPushLimited(Long butlerUserId, Long memberId, String category) {
+        ButlerResourceMatchLog latest = matchLogMapper.selectOne(new LambdaQueryWrapper<ButlerResourceMatchLog>()
+                .eq(ButlerResourceMatchLog::getButlerUserId, butlerUserId)
+                .eq(ButlerResourceMatchLog::getMemberId, memberId)
+                .eq(ButlerResourceMatchLog::getResourceCategory, category)
+                .orderByDesc(ButlerResourceMatchLog::getPushedAt)
+                .last("LIMIT 1"));
+        return latest != null && latest.getPushCount() != null
+                && latest.getPushCount() >= PUSH_FREQUENCY_LIMIT;
+    }
+
+    /** 推送留痕:同类资源累计次数 +1(幂等按 管家+成员+分类 聚合)。 */
+    private void recordPush(Long butlerUserId, Long memberId, Activity activity, String category) {
+        ButlerResourceMatchLog latest = matchLogMapper.selectOne(new LambdaQueryWrapper<ButlerResourceMatchLog>()
+                .eq(ButlerResourceMatchLog::getButlerUserId, butlerUserId)
+                .eq(ButlerResourceMatchLog::getMemberId, memberId)
+                .eq(ButlerResourceMatchLog::getResourceCategory, category)
+                .orderByDesc(ButlerResourceMatchLog::getPushedAt)
+                .last("LIMIT 1"));
+        Date now = new Date();
+        if (latest == null) {
+            ButlerResourceMatchLog logEntry = new ButlerResourceMatchLog();
+            logEntry.setButlerUserId(butlerUserId);
+            logEntry.setMemberId(memberId);
+            logEntry.setResourceId(activity.getId());
+            logEntry.setResourceType("activity");
+            logEntry.setResourceCategory(category);
+            logEntry.setPushedAt(now);
+            logEntry.setPushCount(1);
+            logEntry.setCreatedAt(now);
+            logEntry.setUpdatedAt(now);
+            matchLogMapper.insert(logEntry);
+        } else {
+            latest.setResourceId(activity.getId());
+            latest.setPushedAt(now);
+            latest.setPushCount((latest.getPushCount() == null ? 0 : latest.getPushCount()) + 1);
+            latest.setUpdatedAt(now);
+            matchLogMapper.updateById(latest);
+        }
+    }
+
+    private String asString(Object value) {
+        return value != null ? value.toString() : null;
+    }
+}

+ 54 - 0
cfc-backend/src/main/resources/schema.sql

@@ -2990,6 +2990,60 @@ CREATE TABLE IF NOT EXISTS butler_assignments (
     INDEX idx_subscription_id (subscription_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='会员 - 管家分配记录';
 
+-- 资源匹配结果(能力键 butler.resource.match · SC-H-05:匹配结果携带距离/时间/适龄,仅已审核资源入候选)
+CREATE TABLE IF NOT EXISTS butler_resource_match_results (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    butler_user_id BIGINT NOT NULL COMMENT '推荐管家用户 ID',
+    family_id BIGINT NOT NULL COMMENT '家庭 ID',
+    member_id BIGINT NULL COMMENT '目标成员 ID (family_members.id)',
+    resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity(线下活动)/offline_course(线下课程)',
+    resource_id BIGINT NOT NULL COMMENT '资源 ID (activity.id)',
+    resource_name VARCHAR(200) NULL COMMENT '资源名称',
+    distance_km DECIMAL(10,2) NULL COMMENT 'AC1: 距离(公里)',
+    start_time DATETIME NULL COMMENT 'AC1: 活动开始时间',
+    age_suitability VARCHAR(64) NULL COMMENT 'AC1: 适龄信息(如「6-12岁适龄」「仅成人」)',
+    review_status VARCHAR(20) DEFAULT 'pending' COMMENT '审核门禁: approved/pending/rejected,仅 approved 入候选',
+    match_reason VARCHAR(500) NULL COMMENT '匹配理由(供家长端展示)',
+    match_score INT DEFAULT 0 COMMENT '匹配评分(0-100,候选排序)',
+    status VARCHAR(20) DEFAULT 'matched' COMMENT '匹配状态: matched/pushed/booked',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_member (member_id),
+    INDEX idx_family (family_id),
+    INDEX idx_resource (resource_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源匹配结果(SC-H-05)';
+
+-- 资源匹配推送留痕(能力键 butler.resource.match · TC-H-05-E-4:高频推送同类资源频次受控)
+CREATE TABLE IF NOT EXISTS butler_resource_match_log (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    butler_user_id BIGINT NOT NULL COMMENT '推送管家用户 ID',
+    member_id BIGINT NULL COMMENT '目标成员 ID',
+    resource_id BIGINT NOT NULL COMMENT '资源 ID',
+    resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity/offline_course',
+    resource_category VARCHAR(64) DEFAULT 'general' COMMENT '同类资源分类(频次控制维度,如五维 dimensionCode)',
+    pushed_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '最近推送时间戳',
+    push_count INT DEFAULT 1 COMMENT '累计推送次数(同类资源频次控制)',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_butler_member_cat (butler_user_id, member_id, resource_category)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源匹配推送留痕(TC-H-05-E-4)';
+
+-- 资源参与回访沉淀偏好(能力键 butler.resource.match · AC4:回访记录写入家长档案,后续推荐参考偏好)
+CREATE TABLE IF NOT EXISTS butler_resource_follow_up (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    family_id BIGINT NOT NULL COMMENT '家庭 ID',
+    member_id BIGINT NULL COMMENT '目标成员 ID',
+    butler_user_id BIGINT NOT NULL COMMENT '回访管家用户 ID',
+    resource_id BIGINT NOT NULL COMMENT '资源 ID',
+    resource_type VARCHAR(32) DEFAULT 'activity' COMMENT '资源类型: activity/offline_course',
+    follow_up_content TEXT NULL COMMENT '回访内容(参与感受、反馈)',
+    preference_tags TEXT NULL COMMENT '沉淀偏好标签(JSON 数组字符串,供后续推荐参考)',
+    follow_up_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '回访时间',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_family_member (family_id, member_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='资源参与回访沉淀偏好(AC4)';
+
 -- 家庭订阅记录
 CREATE TABLE IF NOT EXISTS member_subscription (
     id BIGINT AUTO_INCREMENT PRIMARY KEY,