| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- package com.train.controller;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.train.cfc.entity.CfcUser;
- import com.train.cfc.mapper.CfcUserMapper;
- import com.train.common.Result;
- import com.train.entity.TrainInvite;
- import com.train.entity.TrainUser;
- import com.train.mapper.TrainInviteMapper;
- import com.train.mapper.TrainUserMapper;
- import com.train.service.CfcReferralSyncService;
- import com.train.service.StorageService;
- import com.train.service.WechatService;
- import io.swagger.v3.oas.annotations.Operation;
- import io.swagger.v3.oas.annotations.tags.Tag;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.util.StringUtils;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestAttribute;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import javax.annotation.Resource;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
- /**
- * 裂变分享:专属海报/邀请码、我的转介绍统计。
- * <p>邀请码复用 train_user.invite_code;未设置时按需生成(折校:可进校友校验证写入)。
- * 海报小程序码:test-mode 返回空(前端用邀请码本地渲染海报);
- * 生产环境调用微信 getwxacodeunlimit 生成带参小程序码,缓存到本地上传目录并回填 posterUrl。
- * 同时返回 sharePath(小程序带参路径)/ shareText(分享文案),便于前端拼装分享卡。
- */
- @Tag(name = "裂变分享", description = "专属海报/邀请码、转介绍统计")
- @RestController
- @Slf4j
- @RequestMapping("/api/invite")
- public class InviteController {
- @Resource
- private TrainUserMapper trainUserMapper;
- @Resource
- private TrainInviteMapper trainInviteMapper;
- @Resource
- private CfcUserMapper cfcUserMapper;
- @Resource
- private WechatService wechatService;
- @Resource
- private CfcReferralSyncService cfcReferralSyncService;
- @Resource
- private StorageService storageService;
- /**
- * 我的专属海报 + 邀请码 + 分享文案。
- * @return {inviteCode, posterUrl, sharePath, shareText}
- */
- @Operation(summary = "我的专属海报+邀请码")
- @PostMapping("/myposter")
- public Result<Map<String, Object>> myPoster(@RequestAttribute("userId") Long userId) {
- TrainUser user = trainUserMapper.selectById(userId);
- String inviteCode = user != null ? user.getInviteCode() : null;
- if (!StringUtils.hasText(inviteCode)) {
- // 按需生成邀请码(6位字母数字,预留幂等冲突补试)
- inviteCode = genInviteCode(userId);
- if (user != null) {
- user.setInviteCode(inviteCode);
- trainUserMapper.updateById(user);
- }
- }
- // 小程序带参路径(扫码/长按识别进入报名页)
- String sharePath = "/pages/enroll/list?inviteCode=" + inviteCode;
- // 分享文案(可复制的纯文本,分享给微信好友时粘贴用)
- // nickname 取自 cfc users.nickname(TrainUser 不冗余该字段,cfc 同库)
- String nickname = "营员";
- if (user != null && StringUtils.hasText(user.getPhone())) {
- CfcUser cfcUser = cfcUserMapper.selectOne(
- new LambdaQueryWrapper<CfcUser>().eq(CfcUser::getPhone, user.getPhone()).last("LIMIT 1"));
- if (cfcUser != null && StringUtils.hasText(cfcUser.getNickname())) {
- nickname = cfcUser.getNickname();
- }
- }
- String shareText = "【" + nickname + "】邀请你加入「爱伴·AI之旅」训练营\n" +
- "邀请码:" + inviteCode + "\n" +
- "报名时填写邀请码可享专属权益,扫码或点击:\n" +
- sharePath;
- Map<String, Object> row = new HashMap<>();
- row.put("inviteCode", inviteCode);
- row.put("posterUrl", generatePosterCode(inviteCode)); // test-mode 返回空串(前端本地渲染)
- row.put("sharePath", sharePath);
- row.put("shareText", shareText);
- return Result.success(row);
- }
- /**
- * 生成带参小程序码(getwxacodeunlimit)。
- * scene 传邀请码(最长 32 字符),page 固定报名列表页;
- * 图片字节存对象存储(生产京东云 / 本地磁盘),返回可访问 URL。
- * test-mode 或失败返回空串(前端降级本地海报)。
- */
- private String generatePosterCode(String inviteCode) {
- // 统一走 WechatService:test-mode/接口失败返回 null,由前端降级为本地海报
- byte[] bytes = wechatService.generateWxacodeBytes(inviteCode, "pages/enroll/list");
- if (bytes == null || bytes.length == 0) {
- return "";
- }
- try {
- return storageService.storeBytes(bytes, "poster", "invite_" + inviteCode + ".png", "image/png");
- } catch (Exception e) {
- // 存储失败:降级为前端本地海报,不阻塞分享
- log.error("海报存储失败,降级本地海报 inviteCode={}", inviteCode, e);
- return "";
- }
- }
- /**
- * 我的转介绍统计。
- * @return {invited, paid, rewards}
- */
- @Operation(summary = "我的转介绍统计")
- @PostMapping("/stats")
- public Result<Map<String, Object>> stats(@RequestAttribute("userId") Long userId) {
- Long invited = trainInviteMapper.selectCount(
- new LambdaQueryWrapper<TrainInvite>().eq(TrainInvite::getInviterId, userId));
- Long paid = trainInviteMapper.selectCount(
- new LambdaQueryWrapper<TrainInvite>()
- .eq(TrainInvite::getInviterId, userId)
- .eq(TrainInvite::getSuccessful, 1));
- Long rewards = trainInviteMapper.selectCount(
- new LambdaQueryWrapper<TrainInvite>()
- .eq(TrainInvite::getInviterId, userId)
- .eq(TrainInvite::getRewardStatus, "granted"));
- Map<String, Object> row = new HashMap<>();
- row.put("invited", invited == null ? 0L : invited);
- row.put("paid", paid == null ? 0L : paid);
- row.put("rewards", rewards == null ? 0L : rewards);
- return Result.success(row);
- }
- /**
- * 主动绑定推荐人:输入 cfc/爱伴统一邀请码(referralCode)即时关联推荐人。
- * 语义对齐 cfc /api/invite/bind。请求体: { "referralCode": "..." }。
- * 成功后返回 { referrerCfcId, bound: true }。
- */
- @Operation(summary = "主动绑定推荐人(输入邀请码)")
- @PostMapping("/bind")
- public Result<Map<String, Object>> bind(@RequestBody Map<String, String> body,
- @RequestAttribute("userId") Long userId) {
- if (userId == null) {
- return Result.error(401, "请先登录");
- }
- String referralCode = body != null ? body.get("referralCode") : null;
- try {
- Long referrerCfcId = cfcReferralSyncService.bindByReferralCode(userId, referralCode);
- Map<String, Object> row = new HashMap<>();
- row.put("referrerCfcId", referrerCfcId);
- row.put("bound", true);
- return Result.success(row);
- } catch (RuntimeException e) {
- return Result.error(e.getMessage() != null ? e.getMessage() : "绑定失败,请稍后重试");
- }
- }
- /** 生成 6 位字母数字邀请码(低概率冲突靠唯一索引兜底,冲突时补试) */
- private String genInviteCode(Long userId) {
- String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
- for (int i = 0; i < 5; i++) {
- String code = randomCode(chars, 6);
- Long exists = trainUserMapper.selectCount(
- new LambdaQueryWrapper<TrainUser>().eq(TrainUser::getInviteCode, code));
- if (exists == null || exists == 0) {
- return code;
- }
- }
- // 兜底:含 userId 的编码保证唯一
- return UUID.randomUUID().toString().substring(0, 6).toUpperCase();
- }
- private String randomCode(String chars, int len) {
- StringBuilder sb = new StringBuilder();
- java.util.concurrent.ThreadLocalRandom r = java.util.concurrent.ThreadLocalRandom.current();
- for (int i = 0; i < len; i++) {
- sb.append(chars.charAt(r.nextInt(chars.length())));
- }
- return sb.toString();
- }
- }
|