ButlerResourceMatchService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package com.etotem.cfc.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.etotem.cfc.common.Result;
  4. import com.etotem.cfc.entity.Activity;
  5. import com.etotem.cfc.entity.ButlerResourceFollowUp;
  6. import com.etotem.cfc.entity.ButlerResourceMatchLog;
  7. import com.etotem.cfc.entity.ButlerResourceMatchResult;
  8. import com.etotem.cfc.mapper.ActivityMapper;
  9. import com.etotem.cfc.mapper.ButlerResourceFollowUpMapper;
  10. import com.etotem.cfc.mapper.ButlerResourceMatchLogMapper;
  11. import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.stereotype.Service;
  14. import org.springframework.transaction.annotation.Transactional;
  15. import javax.annotation.Resource;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.Date;
  19. import java.util.List;
  20. import java.util.Map;
  21. /**
  22. * 线下资源/活动与家庭需求匹配(能力键 {@code butler.resource.match},SC-H-05)。
  23. *
  24. * <p>正常流:按家长需求与孩子画像匹配资源 → 推送匹配结果 → 协助预约/报名 → 参与后回访并沉淀偏好。
  25. * 候选仅来自<b>已审核</b>资源(AC1,{@code auditStatus=approved} 且 {@code status=published});
  26. * 推送留痕表按同类资源频次受控(TC-H-05-E-4);预约/报名联动 {@link ActivityRegistrationService#register}
  27. * (内部 {@code occupyQuota} 原子占用,满员提示「名额已满」,AC3/TC-H-05-E-2/3)。</p>
  28. */
  29. @Slf4j
  30. @Service
  31. public class ButlerResourceMatchService {
  32. /** 同类资源高频推送阈值:超过后限制推送(TC-H-05-E-4) */
  33. private static final int PUSH_FREQUENCY_LIMIT = 5;
  34. @Resource
  35. private ActivityMapper activityMapper;
  36. @Resource
  37. private ButlerResourceMatchResultMapper matchResultMapper;
  38. @Resource
  39. private ButlerResourceMatchLogMapper matchLogMapper;
  40. @Resource
  41. private ButlerResourceFollowUpMapper butlerResourceFollowUpMapper;
  42. @Resource
  43. private ActivityRegistrationService activityRegistrationService;
  44. /**
  45. * 匹配入口:按家长需求与孩子画像匹配线下资源/活动(TC-H-05 正常流步骤1)。
  46. *
  47. * <p>候选仅已审核资源({@code auditStatus=approved} 且 {@code status=published},AC1/TC-H-05-E-1);
  48. * 每个候选携带距离/时间/适龄信息(AC1);匹配结果落库供家长端查看选择(AC2);
  49. * 推送留痕频次受控(TC-H-05-E-4)。</p>
  50. *
  51. * @param butlerUserId 推荐管家用户 ID
  52. * @param familyId 家庭 ID
  53. * @param memberId 目标成员 ID(孩子画像)
  54. * @param requirements 家长需求:dimensionCode(五维)/keyword(关键词)/childAge(年龄,适龄判定)/location(位置,距离估算)
  55. */
  56. @Transactional
  57. public Result<List<ButlerResourceMatchResult>> match(Long butlerUserId, Long familyId, Long memberId,
  58. Map<String, Object> requirements) {
  59. // 仅已审核 + 已发布资源入候选(未审核/已下架资源不出现,TC-H-05-E-1)
  60. LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<Activity>()
  61. .eq(Activity::getStatus, "published")
  62. .eq(Activity::getAuditStatus, "approved");
  63. String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
  64. if (dimensionCode != null && !dimensionCode.trim().isEmpty()) {
  65. wrapper.eq(Activity::getDimensionCode, dimensionCode.trim());
  66. }
  67. String keyword = requirements != null ? asString(requirements.get("keyword")) : null;
  68. if (keyword != null && !keyword.trim().isEmpty()) {
  69. wrapper.and(w -> w.like(Activity::getTitle, keyword.trim())
  70. .or().like(Activity::getIntro, keyword.trim())
  71. .or().like(Activity::getLocation, keyword.trim()));
  72. }
  73. wrapper.orderByDesc(Activity::getStartTime);
  74. List<Activity> activities = activityMapper.selectList(wrapper);
  75. if (activities.isEmpty()) {
  76. return Result.success(Collections.emptyList());
  77. }
  78. List<ButlerResourceMatchResult> results = new ArrayList<>();
  79. for (Activity activity : activities) {
  80. String category = activity.getDimensionCode() != null ? activity.getDimensionCode() : "general";
  81. // 频次受控:同类资源已达推送阈值则跳过(TC-H-05-E-4)
  82. if (isCategoryPushLimited(butlerUserId, memberId, category)) {
  83. continue;
  84. }
  85. ButlerResourceMatchResult result = buildMatchResult(butlerUserId, familyId, memberId, activity, requirements);
  86. matchResultMapper.insert(result);
  87. recordPush(butlerUserId, memberId, activity, category);
  88. results.add(result);
  89. }
  90. return Result.success(results);
  91. }
  92. /**
  93. * 协助预约/报名入口(AC3):联动名额实时校验(occupyQuota 原子占用,满员提示「名额已满」)。
  94. *
  95. * @param userId 操作家长用户 ID
  96. * @param memberId 报名成员 ID
  97. * @param matchResultId 匹配结果 ID
  98. */
  99. @Transactional
  100. public Result<Map<String, Object>> book(Long userId, Long memberId, Long matchResultId) {
  101. ButlerResourceMatchResult matchResult = matchResultMapper.selectById(matchResultId);
  102. if (matchResult == null) {
  103. return Result.notFound("匹配结果不存在");
  104. }
  105. // 归属校验(TC-H-05-P-②/③):仅本家庭成员可操作该匹配结果
  106. if (matchResult.getMemberId() != null && !matchResult.getMemberId().equals(memberId)) {
  107. return Result.forbidden("无权操作该匹配结果");
  108. }
  109. if (!"activity".equals(matchResult.getResourceType())) {
  110. return Result.error("该资源暂不支持在线预约,请联系统筹管家");
  111. }
  112. Result<Map<String, Object>> regResult = activityRegistrationService.register(
  113. matchResult.getResourceId(), userId, memberId);
  114. if (regResult.getCode() == 200) {
  115. matchResult.setStatus("booked");
  116. matchResult.setUpdatedAt(new Date());
  117. matchResultMapper.updateById(matchResult);
  118. }
  119. return regResult;
  120. }
  121. /**
  122. * 回访沉淀偏好(AC4):参与后回访记录写入家长档案,后续推荐参考偏好。
  123. */
  124. @Transactional
  125. public Result<String> recordFollowUp(Long butlerUserId, Long familyId, Long memberId,
  126. Map<String, Object> params) {
  127. if (params == null) {
  128. return Result.badRequest("回访参数不能为空");
  129. }
  130. ButlerResourceFollowUp followUp = new ButlerResourceFollowUp();
  131. followUp.setFamilyId(familyId);
  132. followUp.setMemberId(memberId);
  133. followUp.setButlerUserId(butlerUserId);
  134. followUp.setResourceId(params.get("resourceId") != null ? Long.valueOf(params.get("resourceId").toString()) : null);
  135. followUp.setResourceType(asString(params.getOrDefault("resourceType", "activity")));
  136. followUp.setFollowUpContent(asString(params.get("followUpContent")));
  137. followUp.setPreferenceTags(params.get("preferenceTags") != null
  138. ? params.get("preferenceTags").toString() : null);
  139. followUp.setFollowUpAt(new Date());
  140. followUp.setCreatedAt(new Date());
  141. followUp.setUpdatedAt(new Date());
  142. butlerResourceFollowUpMapper.insert(followUp);
  143. return Result.success("回访记录已沉淀");
  144. }
  145. // ------------------------------------------------------------------
  146. // 内部辅助
  147. // ------------------------------------------------------------------
  148. private ButlerResourceMatchResult buildMatchResult(Long butlerUserId, Long familyId, Long memberId,
  149. Activity activity, Map<String, Object> requirements) {
  150. ButlerResourceMatchResult result = new ButlerResourceMatchResult();
  151. result.setButlerUserId(butlerUserId);
  152. result.setFamilyId(familyId);
  153. result.setMemberId(memberId);
  154. result.setResourceType("activity");
  155. result.setResourceId(activity.getId());
  156. result.setResourceName(activity.getTitle());
  157. result.setDistanceKm(estimateDistanceKm(activity, requirements));
  158. result.setStartTime(activity.getStartTime());
  159. result.setAgeSuitability(resolveAgeSuitability(activity, requirements));
  160. result.setReviewStatus(activity.getAuditStatus()); // approved 门禁(候选仅已审核)
  161. result.setMatchReason(buildMatchReason(activity, requirements));
  162. result.setMatchScore(buildMatchScore(activity, requirements));
  163. result.setStatus("matched");
  164. Date now = new Date();
  165. result.setCreatedAt(now);
  166. result.setUpdatedAt(now);
  167. return result;
  168. }
  169. /** AC1:距离估算——位置关键词命中则按区域相近给低值,否则给默认值;无位置信息返回 null。 */
  170. private Double estimateDistanceKm(Activity activity, Map<String, Object> requirements) {
  171. String location = activity.getLocation();
  172. String preferred = requirements != null ? asString(requirements.get("location")) : null;
  173. if (location == null || location.trim().isEmpty()) {
  174. return null;
  175. }
  176. if (preferred != null && !preferred.trim().isEmpty()) {
  177. // 同区域(省/市/区关键词)视为近距离
  178. return location.contains(preferred.trim()) ? 2.0 : 8.0;
  179. }
  180. return 5.0;
  181. }
  182. /** AC1:适龄判定——按参与人群构成与孩子年龄给出可读标签。 */
  183. private String resolveAgeSuitability(Activity activity, Map<String, Object> requirements) {
  184. String audienceType = activity.getAudienceType();
  185. String childAge = requirements != null ? asString(requirements.get("childAge")) : null;
  186. if ("adult".equals(audienceType)) {
  187. return "仅成人参与";
  188. }
  189. if (childAge != null && !childAge.trim().isEmpty()) {
  190. return childAge.trim() + "岁可参与";
  191. }
  192. if ("include_child".equals(audienceType) || "include_child_elder".equals(audienceType)) {
  193. return "含孩子参与";
  194. }
  195. return "通用";
  196. }
  197. private String buildMatchReason(Activity activity, Map<String, Object> requirements) {
  198. String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
  199. StringBuilder reason = new StringBuilder("匹配维度匹配");
  200. if (dimensionCode != null && dimensionCode.equals(activity.getDimensionCode())) {
  201. reason.append(",契合需求五维「").append(dimensionCode).append("」");
  202. }
  203. if (activity.getMaxParticipants() != null && activity.getMaxParticipants() > 0) {
  204. int remain = activity.getMaxParticipants()
  205. - (activity.getApprovedCount() != null ? activity.getApprovedCount() : 0);
  206. reason.append(",余位 ").append(Math.max(remain, 0)).append(" 人");
  207. }
  208. return reason.toString();
  209. }
  210. private Integer buildMatchScore(Activity activity, Map<String, Object> requirements) {
  211. int score = 60;
  212. String dimensionCode = requirements != null ? asString(requirements.get("dimensionCode")) : null;
  213. if (dimensionCode != null && dimensionCode.equals(activity.getDimensionCode())) {
  214. score += 20;
  215. }
  216. if ("include_child".equals(activity.getAudienceType())
  217. || "include_child_elder".equals(activity.getAudienceType())) {
  218. score += 10;
  219. }
  220. if (activity.getApprovedCount() != null && activity.getMaxParticipants() != null
  221. && activity.getMaxParticipants() > 0
  222. && activity.getApprovedCount() < activity.getMaxParticipants()) {
  223. score += 10;
  224. }
  225. return Math.min(score, 100);
  226. }
  227. /** TC-H-05-E-4:同类资源累计推送次数是否已达阈值(超过则限制推送)。 */
  228. private boolean isCategoryPushLimited(Long butlerUserId, Long memberId, String category) {
  229. ButlerResourceMatchLog latest = matchLogMapper.selectOne(new LambdaQueryWrapper<ButlerResourceMatchLog>()
  230. .eq(ButlerResourceMatchLog::getButlerUserId, butlerUserId)
  231. .eq(ButlerResourceMatchLog::getMemberId, memberId)
  232. .eq(ButlerResourceMatchLog::getResourceCategory, category)
  233. .orderByDesc(ButlerResourceMatchLog::getPushedAt)
  234. .last("LIMIT 1"));
  235. return latest != null && latest.getPushCount() != null
  236. && latest.getPushCount() >= PUSH_FREQUENCY_LIMIT;
  237. }
  238. /** 推送留痕:同类资源累计次数 +1(幂等按 管家+成员+分类 聚合)。 */
  239. private void recordPush(Long butlerUserId, Long memberId, Activity activity, String category) {
  240. ButlerResourceMatchLog latest = matchLogMapper.selectOne(new LambdaQueryWrapper<ButlerResourceMatchLog>()
  241. .eq(ButlerResourceMatchLog::getButlerUserId, butlerUserId)
  242. .eq(ButlerResourceMatchLog::getMemberId, memberId)
  243. .eq(ButlerResourceMatchLog::getResourceCategory, category)
  244. .orderByDesc(ButlerResourceMatchLog::getPushedAt)
  245. .last("LIMIT 1"));
  246. Date now = new Date();
  247. if (latest == null) {
  248. ButlerResourceMatchLog logEntry = new ButlerResourceMatchLog();
  249. logEntry.setButlerUserId(butlerUserId);
  250. logEntry.setMemberId(memberId);
  251. logEntry.setResourceId(activity.getId());
  252. logEntry.setResourceType("activity");
  253. logEntry.setResourceCategory(category);
  254. logEntry.setPushedAt(now);
  255. logEntry.setPushCount(1);
  256. logEntry.setCreatedAt(now);
  257. logEntry.setUpdatedAt(now);
  258. matchLogMapper.insert(logEntry);
  259. } else {
  260. latest.setResourceId(activity.getId());
  261. latest.setPushedAt(now);
  262. latest.setPushCount((latest.getPushCount() == null ? 0 : latest.getPushCount()) + 1);
  263. latest.setUpdatedAt(now);
  264. matchLogMapper.updateById(latest);
  265. }
  266. }
  267. private String asString(Object value) {
  268. return value != null ? value.toString() : null;
  269. }
  270. }