Преглед изворни кода

登录统一: 新增 bind-cross-program 手动绑定接口+upsertTrainUser cfcUserId 强制回填

liaoxg пре 1 месец
родитељ
комит
2245f50b51

+ 68 - 0
train-backend/src/main/java/com/train/controller/auth/AuthController.java

@@ -251,6 +251,64 @@ public class AuthController {
         return Result.success(buildLoginResult(user, token, cfcUser, isNew(user), null));
     }
 
+    /**
+     * 跨小程序手动绑定:按手机号关联 cfc 已有会员。
+     * 适用于:用户在爱伴已注册(openid_B),但在浠艾福已注册(openid_A,手机号相同)。
+     * 逻辑:
+     *   1. 取当前登录 userId → 查 train_user
+     *   2. 按 phone 在 cfc users 中查找已有会员
+     *   3. 该会员即当前已关联会员 → 提示已绑定;否则更新 train_user.cfcUserId + phone
+     *   4. 返回最新 buildLoginResult(含 totalPoints/memberLevel/referralCode)
+     */
+    @Operation(summary = "跨小程序绑定(按手机号关联 cfc 已有会员)")
+    @PostMapping("/bind-cross-program")
+    public Result<LoginResultDTO> bindCrossProgram(@RequestBody Map<String, String> body,
+                                                    @org.springframework.web.bind.annotation.RequestAttribute("userId") Long userId) {
+        if (userId == null) {
+            return Result.error(401, "请先登录");
+        }
+        String phone = body != null ? body.get("phone") : null;
+        if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) {
+            return Result.error("手机号格式不正确");
+        }
+        TrainUser user = trainUserMapper.selectById(userId);
+        if (user == null) {
+            return Result.error("用户不存在");
+        }
+        // 按 phone 查 cfc 已有会员
+        CfcUser targetCfc = cfcUserMapper.selectOne(
+                new LambdaQueryWrapper<CfcUser>()
+                        .eq(CfcUser::getPhone, phone)
+                        .last("LIMIT 1"));
+        if (targetCfc == null) {
+            return Result.error("未找到该手机号对应的浠艾福账号");
+        }
+        // 该手机号对应的就是当前已关联的会员 → 已绑定,无需重复操作
+        if (user.getCfcUserId() != null && user.getCfcUserId().equals(targetCfc.getId())) {
+            return Result.error("该手机号已与当前账号绑定");
+        }
+        // 更新 train_user.cfcUserId + phone
+        user.setCfcUserId(targetCfc.getId());
+        if (!phone.equals(user.getPhone())) {
+            user.setPhone(phone);
+        }
+        user.setUpdatedAt(new Date());
+        trainUserMapper.updateById(user);
+        // 同步 phone 到 cfc 会员(若 cfc 会员 phone 尚未设置)
+        if (!phone.equals(targetCfc.getPhone())) {
+            targetCfc.setPhone(phone);
+            targetCfc.setUpdatedAt(new Date());
+            try {
+                cfcUserMapper.updateById(targetCfc);
+            } catch (Exception e) {
+                log.warn("绑定跨小程序时同步 cfc phone 失败: cfcUserId={}, err={}", targetCfc.getId(), e.getMessage());
+            }
+        }
+        log.info("跨小程序绑定: trainUid={} 已关联 cfcUserId={}(phone={})", user.getId(), targetCfc.getId(), phone);
+        String token = jwtConfig.generateToken(user.getId(), user.getRole());
+        return Result.success(buildLoginResult(user, token, targetCfc, isNew(user), user.getOpenid()));
+    }
+
     // ========== 内部方法 ==========
 
     private CfcUser upsertCfcUser(String openid, String unionid) {
@@ -300,9 +358,19 @@ public class AuthController {
             trainUserMapper.insert(user);
         } else {
             boolean dirty = false;
+            // cfcUserId 为空则回填
             if (user.getCfcUserId() == null) {
                 user.setCfcUserId(cfcUser.getId());
                 dirty = true;
+            } else {
+                // phone 冲突复用场景:cfc 侧已指向另一个会员(如跨小程序),
+                // 强制更新 cfcUserId,避免历史数据遗留导致 train_user 仍指向旧 cfc 用户。
+                if (!user.getCfcUserId().equals(cfcUser.getId())) {
+                    log.warn("train_user.id={} cfcUserId {} 与本次登录 cfcUser {} 不一致(phone 冲突复用),强制更新",
+                            user.getId(), user.getCfcUserId(), cfcUser.getId());
+                    user.setCfcUserId(cfcUser.getId());
+                    dirty = true;
+                }
             }
             if (StringUtils.hasText(unionid) && !StringUtils.hasText(user.getUnionid())) {
                 user.setUnionid(unionid);

+ 64 - 2
train-frontend/pages/mine/index.vue

@@ -16,6 +16,22 @@
       <text class="merge-sub">您在浠艾福的能量值和会员等级已同步</text>
     </view>
 
+    <!-- 【新增】未关联浠艾福时的手动绑定入口(自动合并未触发时兜底) -->
+    <view v-if="isLoggedIn && !crossProgramMerge" class="bind-card">
+      <text class="bind-title">🔗 绑定浠艾福账号</text>
+      <text class="bind-tip">输入您在浠艾福已注册的手机号,关联后能量值与会员等级即时同步</text>
+      <input
+        class="bind-input"
+        v-model="bindPhone"
+        type="number"
+        maxlength="11"
+        placeholder="请输入浠艾福已注册手机号"
+      />
+      <button class="bind-btn" :disabled="binding" @click="doBindCrossProgram">
+        {{ binding ? '绑定中...' : '绑定' }}
+      </button>
+    </view>
+
     <view class="section-card">
       <text class="section-title">🎓 完课证书</text>
       <view v-if="certLoading" class="empty-text">加载中...</view>
@@ -116,7 +132,7 @@
 </template>
 
 <script>
-import { getMyCert, getMyCoupons, redeemCoupon, verifyCert, getMyBadges } from '@/utils/api.js'
+import { getMyCert, getMyCoupons, redeemCoupon, verifyCert, getMyBadges, bindCrossProgram } from '@/utils/api.js'
 import { jumpToCfc } from '@/utils/sso.js'
 
 export default {
@@ -129,7 +145,9 @@ export default {
       verifyInput: '',
       verifyResult: null,
       verifying: false,
-      crossProgramMerge: false
+      crossProgramMerge: false,
+      bindPhone: '',
+      binding: false
     }
   },
   computed: {
@@ -194,6 +212,42 @@ export default {
     goCfc() {
       jumpToCfc()
     },
+    // 手动绑定浠艾福账号:按手机号关联 cfc 已有会员(自动合并未触发时兜底)
+    doBindCrossProgram() {
+      var self = this
+      var phone = (self.bindPhone || '').trim()
+      if (!phone) {
+        uni.showToast({ title: '请输入手机号', icon: 'none' })
+        return
+      }
+      if (!/^1[3-9]\d{9}$/.test(phone)) {
+        uni.showToast({ title: '手机号格式不正确', icon: 'none' })
+        return
+      }
+      self.binding = true
+      bindCrossProgram(phone).then(function(resp) {
+        self.binding = false
+        var data = resp && resp.data
+        if (!data) {
+          uni.showToast({ title: '绑定失败,请稍后重试', icon: 'none' })
+          return
+        }
+        // 后端返回新签发的 token 与合并标识,刷新登录态(store + storage)
+        self.$store.dispatch('login', data)
+        var merged = !!(data.crossProgramMerge)
+        uni.setStorageSync('crossProgramMerge', merged)
+        self.crossProgramMerge = merged
+        self.bindPhone = ''
+        if (merged) {
+          uni.showToast({ title: '绑定成功,浠艾福数据已同步', icon: 'success' })
+        } else {
+          uni.showToast({ title: '操作成功,可进入成长家庭查看', icon: 'success' })
+        }
+      }).catch(function(e) {
+        self.binding = false
+        uni.showToast({ title: (e && e.message) || '绑定失败,请确认手机号已在浠艾福注册', icon: 'none' })
+      })
+    },
     goBadgeWall() {
       uni.navigateTo({ url: '/pages/badge/index' })
     },
@@ -349,4 +403,12 @@ export default {
 .merge-icon { font-size: 40rpx; margin-right: 16rpx; }
 .merge-text { display: block; font-size: 26rpx; font-weight: 600; color: #D97706; }
 .merge-sub { display: block; font-size: 22rpx; color: #92400E; margin-top: 4rpx; }
+
+/* 跨小程序手动绑定入口 */
+.bind-card { background: #FFF; border-radius: 16rpx; padding: 28rpx 32rpx; margin-bottom: 24rpx; display: flex; flex-direction: column; }
+.bind-title { font-size: 30rpx; font-weight: 600; color: #2A2326; margin-bottom: 8rpx; }
+.bind-tip { font-size: 22rpx; color: #5A4F4B; margin-bottom: 20rpx; }
+.bind-input { height: 76rpx; background: #F1F5F9; border-radius: 8rpx; padding: 0 24rpx; font-size: 28rpx; color: #2A2326; margin-bottom: 20rpx; }
+.bind-btn { width: 100%; height: 80rpx; line-height: 80rpx; background: linear-gradient(135deg, #F97316, #FB923C); color: #FFF; font-size: 30rpx; font-weight: 600; border-radius: 12rpx; }
+.bind-btn[disabled] { opacity: 0.6; }
 </style>