InviteController.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package com.train.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.cfc.entity.CfcUser;
  4. import com.train.cfc.mapper.CfcUserMapper;
  5. import com.train.common.Result;
  6. import com.train.entity.TrainInvite;
  7. import com.train.entity.TrainUser;
  8. import com.train.mapper.TrainInviteMapper;
  9. import com.train.mapper.TrainUserMapper;
  10. import com.train.service.CfcReferralSyncService;
  11. import com.train.service.StorageService;
  12. import com.train.service.WechatService;
  13. import io.swagger.v3.oas.annotations.Operation;
  14. import io.swagger.v3.oas.annotations.tags.Tag;
  15. import lombok.extern.slf4j.Slf4j;
  16. import org.springframework.util.StringUtils;
  17. import org.springframework.web.bind.annotation.PostMapping;
  18. import org.springframework.web.bind.annotation.RequestAttribute;
  19. import org.springframework.web.bind.annotation.RequestBody;
  20. import org.springframework.web.bind.annotation.RequestMapping;
  21. import org.springframework.web.bind.annotation.RestController;
  22. import javax.annotation.Resource;
  23. import java.util.HashMap;
  24. import java.util.Map;
  25. import java.util.UUID;
  26. /**
  27. * 裂变分享:专属海报/邀请码、我的转介绍统计。
  28. * <p>邀请码复用 train_user.invite_code;未设置时按需生成(折校:可进校友校验证写入)。
  29. * 海报小程序码:test-mode 返回空(前端用邀请码本地渲染海报);
  30. * 生产环境调用微信 getwxacodeunlimit 生成带参小程序码,缓存到本地上传目录并回填 posterUrl。
  31. * 同时返回 sharePath(小程序带参路径)/ shareText(分享文案),便于前端拼装分享卡。
  32. */
  33. @Tag(name = "裂变分享", description = "专属海报/邀请码、转介绍统计")
  34. @RestController
  35. @Slf4j
  36. @RequestMapping("/api/invite")
  37. public class InviteController {
  38. @Resource
  39. private TrainUserMapper trainUserMapper;
  40. @Resource
  41. private TrainInviteMapper trainInviteMapper;
  42. @Resource
  43. private CfcUserMapper cfcUserMapper;
  44. @Resource
  45. private WechatService wechatService;
  46. @Resource
  47. private CfcReferralSyncService cfcReferralSyncService;
  48. @Resource
  49. private StorageService storageService;
  50. /**
  51. * 我的专属海报 + 邀请码 + 分享文案。
  52. * @return {inviteCode, posterUrl, sharePath, shareText}
  53. */
  54. @Operation(summary = "我的专属海报+邀请码")
  55. @PostMapping("/myposter")
  56. public Result<Map<String, Object>> myPoster(@RequestAttribute("userId") Long userId) {
  57. TrainUser user = trainUserMapper.selectById(userId);
  58. String inviteCode = user != null ? user.getInviteCode() : null;
  59. if (!StringUtils.hasText(inviteCode)) {
  60. // 按需生成邀请码(6位字母数字,预留幂等冲突补试)
  61. inviteCode = genInviteCode(userId);
  62. if (user != null) {
  63. user.setInviteCode(inviteCode);
  64. trainUserMapper.updateById(user);
  65. }
  66. }
  67. // 小程序带参路径(扫码/长按识别进入报名页)
  68. String sharePath = "/pages/enroll/list?inviteCode=" + inviteCode;
  69. // 分享文案(可复制的纯文本,分享给微信好友时粘贴用)
  70. // nickname 取自 cfc users.nickname(TrainUser 不冗余该字段,cfc 同库)
  71. String nickname = "营员";
  72. if (user != null && StringUtils.hasText(user.getPhone())) {
  73. CfcUser cfcUser = cfcUserMapper.selectOne(
  74. new LambdaQueryWrapper<CfcUser>().eq(CfcUser::getPhone, user.getPhone()).last("LIMIT 1"));
  75. if (cfcUser != null && StringUtils.hasText(cfcUser.getNickname())) {
  76. nickname = cfcUser.getNickname();
  77. }
  78. }
  79. String shareText = "【" + nickname + "】邀请你加入「爱伴·AI之旅」训练营\n" +
  80. "邀请码:" + inviteCode + "\n" +
  81. "报名时填写邀请码可享专属权益,扫码或点击:\n" +
  82. sharePath;
  83. Map<String, Object> row = new HashMap<>();
  84. row.put("inviteCode", inviteCode);
  85. row.put("posterUrl", generatePosterCode(inviteCode)); // test-mode 返回空串(前端本地渲染)
  86. row.put("sharePath", sharePath);
  87. row.put("shareText", shareText);
  88. return Result.success(row);
  89. }
  90. /**
  91. * 生成带参小程序码(getwxacodeunlimit)。
  92. * scene 传邀请码(最长 32 字符),page 固定报名列表页;
  93. * 图片字节存对象存储(生产京东云 / 本地磁盘),返回可访问 URL。
  94. * test-mode 或失败返回空串(前端降级本地海报)。
  95. */
  96. private String generatePosterCode(String inviteCode) {
  97. // 统一走 WechatService:test-mode/接口失败返回 null,由前端降级为本地海报
  98. byte[] bytes = wechatService.generateWxacodeBytes(inviteCode, "pages/enroll/list");
  99. if (bytes == null || bytes.length == 0) {
  100. return "";
  101. }
  102. try {
  103. return storageService.storeBytes(bytes, "poster", "invite_" + inviteCode + ".png", "image/png");
  104. } catch (Exception e) {
  105. // 存储失败:降级为前端本地海报,不阻塞分享
  106. log.error("海报存储失败,降级本地海报 inviteCode={}", inviteCode, e);
  107. return "";
  108. }
  109. }
  110. /**
  111. * 我的转介绍统计。
  112. * @return {invited, paid, rewards}
  113. */
  114. @Operation(summary = "我的转介绍统计")
  115. @PostMapping("/stats")
  116. public Result<Map<String, Object>> stats(@RequestAttribute("userId") Long userId) {
  117. Long invited = trainInviteMapper.selectCount(
  118. new LambdaQueryWrapper<TrainInvite>().eq(TrainInvite::getInviterId, userId));
  119. Long paid = trainInviteMapper.selectCount(
  120. new LambdaQueryWrapper<TrainInvite>()
  121. .eq(TrainInvite::getInviterId, userId)
  122. .eq(TrainInvite::getSuccessful, 1));
  123. Long rewards = trainInviteMapper.selectCount(
  124. new LambdaQueryWrapper<TrainInvite>()
  125. .eq(TrainInvite::getInviterId, userId)
  126. .eq(TrainInvite::getRewardStatus, "granted"));
  127. Map<String, Object> row = new HashMap<>();
  128. row.put("invited", invited == null ? 0L : invited);
  129. row.put("paid", paid == null ? 0L : paid);
  130. row.put("rewards", rewards == null ? 0L : rewards);
  131. return Result.success(row);
  132. }
  133. /**
  134. * 主动绑定推荐人:输入 cfc/爱伴统一邀请码(referralCode)即时关联推荐人。
  135. * 语义对齐 cfc /api/invite/bind。请求体: { "referralCode": "..." }。
  136. * 成功后返回 { referrerCfcId, bound: true }。
  137. */
  138. @Operation(summary = "主动绑定推荐人(输入邀请码)")
  139. @PostMapping("/bind")
  140. public Result<Map<String, Object>> bind(@RequestBody Map<String, String> body,
  141. @RequestAttribute("userId") Long userId) {
  142. if (userId == null) {
  143. return Result.error(401, "请先登录");
  144. }
  145. String referralCode = body != null ? body.get("referralCode") : null;
  146. try {
  147. Long referrerCfcId = cfcReferralSyncService.bindByReferralCode(userId, referralCode);
  148. Map<String, Object> row = new HashMap<>();
  149. row.put("referrerCfcId", referrerCfcId);
  150. row.put("bound", true);
  151. return Result.success(row);
  152. } catch (RuntimeException e) {
  153. return Result.error(e.getMessage() != null ? e.getMessage() : "绑定失败,请稍后重试");
  154. }
  155. }
  156. /** 生成 6 位字母数字邀请码(低概率冲突靠唯一索引兜底,冲突时补试) */
  157. private String genInviteCode(Long userId) {
  158. String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  159. for (int i = 0; i < 5; i++) {
  160. String code = randomCode(chars, 6);
  161. Long exists = trainUserMapper.selectCount(
  162. new LambdaQueryWrapper<TrainUser>().eq(TrainUser::getInviteCode, code));
  163. if (exists == null || exists == 0) {
  164. return code;
  165. }
  166. }
  167. // 兜底:含 userId 的编码保证唯一
  168. return UUID.randomUUID().toString().substring(0, 6).toUpperCase();
  169. }
  170. private String randomCode(String chars, int len) {
  171. StringBuilder sb = new StringBuilder();
  172. java.util.concurrent.ThreadLocalRandom r = java.util.concurrent.ThreadLocalRandom.current();
  173. for (int i = 0; i < len; i++) {
  174. sb.append(chars.charAt(r.nextInt(chars.length())));
  175. }
  176. return sb.toString();
  177. }
  178. }