Просмотр исходного кода

邀请统一: 新增主动绑定推荐人接口 /api/invite/bind(前端绑定页与入口)

liaoxg 1 месяц назад
Родитель
Сommit
154c36cc8e

+ 28 - 0
train-backend/src/main/java/com/train/controller/InviteController.java

@@ -9,6 +9,7 @@ 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.WechatService;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
@@ -21,6 +22,7 @@ import org.springframework.http.ResponseEntity;
 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 org.springframework.web.client.RestTemplate;
@@ -53,6 +55,8 @@ public class InviteController {
     private CfcUserMapper cfcUserMapper;
     @Resource
     private WechatService wechatService;
+    @Resource
+    private CfcReferralSyncService cfcReferralSyncService;
 
     @Value("${wechat.test-mode}")
     private boolean testMode;
@@ -175,6 +179,30 @@ public class InviteController {
         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";

+ 96 - 0
train-backend/src/main/java/com/train/service/CfcReferralSyncService.java

@@ -5,7 +5,9 @@ import com.train.cfc.entity.CfcUser;
 import com.train.cfc.entity.ReferralTree;
 import com.train.cfc.mapper.CfcUserMapper;
 import com.train.cfc.mapper.ReferralTreeMapper;
+import com.train.entity.TrainInvite;
 import com.train.entity.TrainUser;
+import com.train.mapper.TrainInviteMapper;
 import com.train.mapper.TrainUserMapper;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
@@ -34,10 +36,104 @@ public class CfcReferralSyncService {
     @Resource
     private TrainUserMapper trainUserMapper;
     @Resource
+    private TrainInviteMapper trainInviteMapper;
+    @Resource
     private CfcUserMapper cfcUserMapper;
     @Resource
     private ReferralTreeMapper referralTreeMapper;
 
+    /**
+     * 主动绑定:被邀请人(inviteeUid)输入 cfc referralCode 即时关联推荐人。
+     * 语义对齐 cfc CommissionService.bindReferral:
+     * <ul>
+     *   <li>必须已关联 cfc 会员(train_user.cfc_user_id 非空)</li>
+     *   <li>已有推荐人 → 抛「已绑定推荐人,不可修改」</li>
+     *   <li>邀请码无效 / 自己邀请自己 → 抛错</li>
+     * </ul>
+     * 成功后:写 users.referrer_id + 物化 referral_tree + 能反查到 train 账号时补写 train_invite
+     * (让 train 侧后续报名付费可沿用本条关系发放转介绍激励)。
+     *
+     * @param inviteeUid   被邀请人 train_user.id(当前登录用户)
+     * @param referralCode cfc/爱伴统一邀请码(两侧字段已双向同步,同值)
+     * @return 推荐人 cfc 会员ID
+     */
+    public Long bindByReferralCode(Long inviteeUid, String referralCode) {
+        if (inviteeUid == null) {
+            throw new RuntimeException("请先登录");
+        }
+        if (referralCode == null || referralCode.trim().isEmpty()) {
+            throw new RuntimeException("邀请码不能为空");
+        }
+        TrainUser invitee = trainUserMapper.selectById(inviteeUid);
+        if (invitee == null) {
+            throw new RuntimeException("用户不存在");
+        }
+        Long inviteeCfcId = invitee.getCfcUserId();
+        if (inviteeCfcId == null) {
+            throw new RuntimeException("尚未关联会员,无法绑定推荐人");
+        }
+        CfcUser inviteeCfc = cfcUserMapper.selectById(inviteeCfcId);
+        if (inviteeCfc == null) {
+            throw new RuntimeException("会员不存在,无法绑定推荐人");
+        }
+        if (inviteeCfc.getReferrerId() != null) {
+            throw new RuntimeException("已绑定推荐人,不可修改");
+        }
+        CfcUser referrerCfc = cfcUserMapper.selectOne(
+                new LambdaQueryWrapper<CfcUser>()
+                        .eq(CfcUser::getReferralCode, referralCode.trim())
+                        .last("LIMIT 1"));
+        if (referrerCfc == null) {
+            throw new RuntimeException("邀请码无效");
+        }
+        if (referrerCfc.getId().equals(inviteeCfcId)) {
+            throw new RuntimeException("不能邀请自己");
+        }
+        // 写 users.referrer_id
+        inviteeCfc.setReferrerId(referrerCfc.getId());
+        inviteeCfc.setUpdatedAt(new Date());
+        cfcUserMapper.updateById(inviteeCfc);
+        log.info("推荐人已绑定: inviteeCfc={}, referrerCfc={}, code={}", inviteeCfcId, referrerCfc.getId(), referralCode);
+        // 物化 referral_tree(失败不阻塞绑定结果)
+        try {
+            materializeReferralTree(inviteeCfcId);
+        } catch (Exception e) {
+            log.warn("绑定后物化 referral_tree 失败: cfcUserId={}, err={}", inviteeCfcId, e.getMessage());
+        }
+        // 推荐人有 train 账号时补写 train_invite(幂等:inviteCode+inviteeId 唯一键),
+        // 让后续报名付费可沿用本条关系发放转介绍激励
+        try {
+            TrainUser referrerTrain = trainUserMapper.selectOne(
+                    new LambdaQueryWrapper<TrainUser>()
+                            .eq(TrainUser::getCfcUserId, referrerCfc.getId())
+                            .last("LIMIT 1"));
+            if (referrerTrain != null && !referrerTrain.getId().equals(inviteeUid)) {
+                Long invCount = trainInviteMapper.selectCount(
+                        new LambdaQueryWrapper<TrainInvite>()
+                                .eq(TrainInvite::getInviteCode, referralCode.trim())
+                                .eq(TrainInvite::getInviteeId, inviteeUid));
+                if (invCount == null || invCount == 0) {
+                    TrainInvite inv = new TrainInvite();
+                    inv.setInviterId(referrerTrain.getId());
+                    inv.setInviteeId(inviteeUid);
+                    inv.setInviteCode(referralCode.trim());
+                    inv.setSuccessful(0);
+                    inv.setRewardStatus("pending");
+                    try {
+                        trainInviteMapper.insert(inv);
+                    } catch (Exception ex) {
+                        // 唯一键冲突(并发绑定)可忽略
+                        log.debug("train_invite 已存在,跳过: code={}, invitee={}", referralCode, inviteeUid);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            // 补写 train_invite 失败不影响 cfc 绑定结果
+            log.warn("补写 train_invite 失败: code={}, inviteeUid={}, err={}", referralCode, inviteeUid, e.getMessage());
+        }
+        return referrerCfc.getId();
+    }
+
     /**
      * 同步推荐关系:被邀请人(inviteeUid)的 cfc 会员 referrer_id = 邀请人(inviterUid)的 cfc 会员 id。
      *

+ 6 - 0
train-frontend/pages.json

@@ -156,6 +156,12 @@
         "navigationBarTitleText": "我的海报"
       }
     },
+    {
+      "path": "pages/share/bind",
+      "style": {
+        "navigationBarTitleText": "绑定推荐人"
+      }
+    },
     {
       "path": "pages/share/stats",
       "style": {

+ 80 - 0
train-frontend/pages/share/bind.vue

@@ -0,0 +1,80 @@
+<template>
+  <view class="bind-page">
+    <view class="form-card">
+      <text class="form-title">输入推荐人邀请码</text>
+      <text class="form-desc">由好友分享给你的专属邀请码(6 位字母数字),可在好友的海报页复制</text>
+      <input
+        class="code-input"
+        v-model="referralCode"
+        placeholder="请输入邀请码"
+        placeholder-class="code-placeholder"
+        maxlength="16"
+        :disabled="binding"
+      />
+      <button class="bind-btn" @click="submitBind" :loading="binding" :disabled="binding || !referralCode.trim()">
+        {{ binding ? '绑定中…' : '确认绑定' }}
+      </button>
+    </view>
+
+    <view class="tip-card">
+      <text class="tip-title">绑定说明</text>
+      <text class="tip-desc">1. 绑定后推荐关系立即生效,与报名时填写邀请码效果一致</text>
+      <text class="tip-desc">2. 每位用户仅可绑定一次,绑定后不可修改</text>
+      <text class="tip-desc">3. 不能填写自己的邀请码</text>
+    </view>
+  </view>
+</template>
+
+<script>
+import { bindReferrer } from '@/utils/api.js'
+import { guardPage } from '@/utils/guard.js'
+
+export default {
+  data() {
+    return {
+      referralCode: '',
+      binding: false
+    }
+  },
+  onLoad() {
+    if (!guardPage()) return
+  },
+  methods: {
+    submitBind() {
+      var self = this
+      var code = this.referralCode ? this.referralCode.trim() : ''
+      if (!code) {
+        uni.showToast({ title: '请输入邀请码', icon: 'none' })
+        return
+      }
+      if (this.binding) return
+      this.binding = true
+      bindReferrer(code).then(function() {
+        uni.showToast({ title: '绑定成功', icon: 'success' })
+        setTimeout(function() {
+          uni.navigateBack({})
+        }, 800)
+      }).catch(function() {
+        // 业务错误已由全局请求层 toast
+      }).then(function() {
+        self.binding = false
+      })
+    }
+  }
+}
+</script>
+
+<style scoped>
+.bind-page { min-height: 100vh; background: #F5F5F5; padding: 24rpx 32rpx; }
+.form-card { background: #FFF; border-radius: 16rpx; padding: 32rpx; margin-bottom: 24rpx; }
+.form-title { display: block; font-size: 30rpx; font-weight: 700; color: #2A2326; margin-bottom: 12rpx; }
+.form-desc { display: block; font-size: 24rpx; color: #5A4F4B; line-height: 40rpx; margin-bottom: 24rpx; }
+.code-input { height: 88rpx; border: 2rpx solid #E2E8F0; border-radius: 12rpx; padding: 0 24rpx; font-size: 32rpx; color: #2A2326; font-family: monospace; letter-spacing: 4rpx; margin-bottom: 24rpx; background: #FAFAFA; }
+.code-placeholder { font-size: 28rpx; color: #94877F; letter-spacing: 0; }
+.bind-btn { width: 100%; height: 88rpx; line-height: 88rpx; background: #FC7A57; color: #FFF; font-size: 30rpx; font-weight: 600; border-radius: 44rpx; border: none; }
+.bind-btn:active { opacity: 0.85; }
+.bind-btn[disabled] { background: #FDBA74; color: #FFF; }
+.tip-card { background: #FFF; border-radius: 16rpx; padding: 32rpx; }
+.tip-title { display: block; font-size: 30rpx; font-weight: 700; color: #2A2326; margin-bottom: 16rpx; border-left: 8rpx solid #FC7A57; padding-left: 16rpx; }
+.tip-desc { display: block; font-size: 26rpx; color: #475569; line-height: 48rpx; }
+</style>

+ 10 - 0
train-frontend/pages/share/index.vue

@@ -26,6 +26,11 @@
       <text>查看我的转介绍统计</text>
       <text class="arrow">›</text>
     </view>
+
+    <view class="bind-link" @click="goBind">
+      <text>我是被邀请的,绑定推荐人</text>
+      <text class="arrow">›</text>
+    </view>
   </view>
 </template>
 
@@ -223,6 +228,9 @@ export default {
     },
     goStats() {
       uni.navigateTo({ url: '/pages/share/stats' })
+    },
+    goBind() {
+      uni.navigateTo({ url: '/pages/share/bind' })
     }
   }
 }
@@ -245,4 +253,6 @@ export default {
 .save-btn:active { opacity: 0.85; }
 .stats-link { display: flex; align-items: center; justify-content: center; padding: 32rpx 0; color: #5A4F4B; font-size: 28rpx; }
 .stats-link .arrow { color: #94877F; font-size: 32rpx; margin-left: 8rpx; }
+.bind-link { display: flex; align-items: center; justify-content: center; padding: 8rpx 0 32rpx; color: #FC7A57; font-size: 26rpx; }
+.bind-link .arrow { color: #FC7A57; font-size: 30rpx; margin-left: 8rpx; }
 </style>

+ 3 - 0
train-frontend/utils/api.js

@@ -281,6 +281,9 @@ export const getMyPoster = () => {
 export const getInviteStats = () => {
   return request('/api/invite/stats', 'POST')
 }
+export const bindReferrer = (referralCode) => {
+  return request('/api/invite/bind', 'POST', { referralCode })
+}
 
 // 年度会员(体验卡/爱伴星伙卡)
 export const createMemberOrder = (cardType) => {