UserServiceImpl.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. package com.cyksj.service.user.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.date.DateTime;
  5. import cn.hutool.core.date.DateUtil;
  6. import cn.hutool.core.util.RandomUtil;
  7. import cn.hutool.core.util.StrUtil;
  8. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  9. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  10. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  11. import com.cyksj.common.constant.Constant;
  12. import com.cyksj.common.exception.BusinessRuntimeException;
  13. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  14. import com.cyksj.common.util.Codec;
  15. import com.cyksj.common.util.Jsons;
  16. import com.cyksj.common.util.StringUtil;
  17. import com.cyksj.config.wxlogin.WxOpenPlatYHLXLoginConfig;
  18. import com.cyksj.mapper.*;
  19. import com.cyksj.mapper.channel.ChannelPopularizeMapper;
  20. import com.cyksj.mapper.manage.cps.UserDistributePopularizeMapper;
  21. import com.cyksj.mapper.market.task.UserBindDetailMapper;
  22. import com.cyksj.model.dto.*;
  23. import com.cyksj.model.entity.*;
  24. import com.cyksj.model.request.LoginReq;
  25. import com.cyksj.model.views.RenewalView;
  26. import com.cyksj.model.views.UserTicketView;
  27. import com.cyksj.redis.RedisService;
  28. import com.cyksj.service.distribute.DistributeService;
  29. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  30. import com.cyksj.service.exchange.ExchangeCodeService;
  31. import com.cyksj.service.mange.coupon.CouponCommonService;
  32. import com.cyksj.service.market.task.BindTaskService;
  33. import com.cyksj.service.shop.YhShopDistributeService;
  34. import com.cyksj.service.sys.SysConfigService;
  35. import com.cyksj.service.user.UserBindRelationService;
  36. import com.cyksj.service.user.UserService;
  37. import com.cyksj.service.wechat.WeChatService;
  38. import com.ejlchina.searcher.BeanSearcher;
  39. import com.ejlchina.searcher.param.Operator;
  40. import com.ejlchina.searcher.util.MapUtils;
  41. import lombok.RequiredArgsConstructor;
  42. import lombok.extern.slf4j.Slf4j;
  43. import org.springframework.dao.DuplicateKeyException;
  44. import org.springframework.stereotype.Service;
  45. import org.springframework.transaction.annotation.Transactional;
  46. import org.springframework.util.Assert;
  47. import java.util.ArrayList;
  48. import java.util.Date;
  49. import java.util.List;
  50. import java.util.Optional;
  51. /**
  52. * @author chan
  53. * @date 2021/10/10 下午3:27
  54. */
  55. @Slf4j
  56. @Service
  57. @RequiredArgsConstructor
  58. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  59. private final DistributeService distributeService;
  60. private final EquipmentDistributeService equipDistributeService;
  61. private final ChannelPopularizeMapper channelPopularizeMapper;
  62. private final CouponCommonService couponCommonService;
  63. private final RedisService redisService;
  64. private final SysConfigService sysConfigService;
  65. private final UserBindDetailMapper userBindDetailMapper;
  66. private final UserDistributePopularizeMapper distributePopularizeMapper;
  67. private final UserMapper userMapper;
  68. private final PhoneCodeMapper phoneCodeMapper;
  69. private final WeChatService weChatService;
  70. private final BindTaskService bindTaskService;
  71. private final WxOpenPlatYHLXLoginConfig wxOpenPlatYHLXLoginConfig;
  72. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  73. private final ExchangeCodeService exchangeCodeService;
  74. private final GoodsDonSkuMapper goodsDonSkuMapper;
  75. private final GroupsRelationMapper groupsRelationMapper;
  76. private final BeanSearcher beanSearcher;
  77. private final UserBindRelationService userBindRelationService;
  78. private final YhShopDistributeService yhShopDistributeService;
  79. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  80. @Override
  81. public User saveAuth(GzhOAuth2UserInfo info, Long sharedId, Integer dsType, Long pid, User.RegisterEnv registerEnv, String dsCode, String callback, String callbackType, String customId) throws Exception {
  82. final String unionid = info.getUnionid();
  83. if (StrUtil.isEmpty(unionid)) {
  84. throw BusinessRuntimeException.getInstance("授权操作异常,请刷新页面");
  85. }
  86. User user = getSyncUser(info.getOpenid(), info.getUnionid(), null);
  87. user = Optional.ofNullable(user).orElseGet(() -> new User()
  88. .setUnionid(unionid));
  89. user.setCountry(info.getCountry())
  90. .setProvince(info.getProvince())
  91. .setCity(info.getCity());
  92. if (user.getSex() == null) {
  93. user.setSex(info.getSex());
  94. }
  95. if (StrUtil.isEmpty(user.getHeadimgurl())) {
  96. user.setHeadimgurl(info.getHeadimgurl());
  97. }
  98. if (StrUtil.isEmpty(user.getNickname())) {
  99. user.setNickname(info.getNickname());
  100. }
  101. user.setUnionid(unionid);
  102. user.setOpenId(info.getOpenid());
  103. Boolean isNewUser = false;
  104. if (user.getId() == null) {
  105. isNewUser = true;
  106. user.setPopularizeId(pid);
  107. user.setRegisterEnv(registerEnv.name());
  108. if (!redisService.setNx(RedisService.key.REPEAT_USER_KEY.getNameFormat(user.getUnionid()), user.getUnionid(), RedisService.key.REPEAT_USER_KEY.getTimeout())) {
  109. return this.getOne(Wrappers.lambdaQuery(User.class)
  110. .eq(User::getUnionid, unionid).last("limit 1"));
  111. }
  112. this.save(user);
  113. //缓存用户注册 回传信息
  114. if (StrUtil.isNotBlank(callback)) {
  115. OrderDonPostDataDto orderDonPostDataDto = new OrderDonPostDataDto().setCallback(callback)
  116. .setCallbackType(callbackType);
  117. redisService.set(RedisService.key.ORDER_DON_POST_DATA_USER_KEY.getName() + user.getId(), Jsons.toJson(orderDonPostDataDto));
  118. }
  119. //发放新用户福利
  120. final Long fUid = user.getId();
  121. TASK_POOL.execute(() -> {
  122. try {
  123. sendNewUserWelfare(fUid);
  124. } catch (Exception e) {
  125. }
  126. });
  127. } else {
  128. if (StrUtil.isEmpty(user.getRegisterEnv())) {
  129. user.setRegisterEnv(registerEnv.name());
  130. }
  131. this.updateById(user);
  132. }
  133. Long dsPopularizeId = null;
  134. if (StrUtil.isNotBlank(dsCode)) {
  135. dsCode = dsCode.trim();
  136. User sharedUser = getOne(Wrappers.lambdaQuery(User.class)
  137. .eq(User::getShowId, dsCode).last("limit 1"));
  138. if (sharedUser != null) {
  139. sharedId = sharedUser.getId();
  140. } else {
  141. UserDistributePopularize distributePopularize = distributePopularizeMapper.selectOne(Wrappers.lambdaQuery(UserDistributePopularize.class)
  142. .eq(UserDistributePopularize::getCode, dsCode)
  143. .select(UserDistributePopularize::getUserId, UserDistributePopularize::getId).last("limit 1"));
  144. if (distributePopularize != null) {
  145. log.info("渠道sharedId:{}设置固定推广链接用户分销", distributePopularize.getUserId());
  146. sharedId = distributePopularize.getUserId();
  147. dsPopularizeId = distributePopularize.getId();
  148. }
  149. }
  150. }
  151. if (sharedId != null && isNewUser) {
  152. if (dsType == null || dsType == 1) {
  153. distributeService.saveDistributionInvitation(sharedId, user.getId(), dsPopularizeId);
  154. }
  155. }
  156. //店铺注册用户 关联
  157. if (isNewUser && StrUtil.isNotBlank(customId)) {
  158. yhShopDistributeService.saveDistributionInvitation(customId, user.getId());
  159. }
  160. Long userId = user.getId();
  161. if (isNewUser && pid != null) {
  162. TASK_POOL.execute(() -> {
  163. sendFixedCustomerCoupon(pid, userId, unionid);
  164. });
  165. }
  166. //新旧用户都可实物分销
  167. if (sharedId != null && dsType != null && dsType == 2) {
  168. equipDistributeService.saveDistributionInvitation(sharedId, isNewUser, user.getId());
  169. }
  170. return user;
  171. }
  172. @Override
  173. public UserWhoami whoami(long userId) {
  174. User user = this.getById(userId);
  175. Assert.notNull(user, "业务处理失败,请联系客服");
  176. UserWhoami userWhoami = new UserWhoami();
  177. if (StrUtil.isEmpty(user.getShowId())) {
  178. user.setShowId(getUserShowId(userId));
  179. }
  180. BeanUtil.copyProperties(user, userWhoami);
  181. if (StrUtil.isEmpty(user.getLoginPhone())) {
  182. UserBindDetail bindPhone = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  183. .eq(StrUtil.isNotEmpty(user.getOpenId()), UserBindDetail::getUserId, userId)
  184. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  185. //手机号
  186. if (bindPhone != null) {
  187. userWhoami.setBindPhone(bindPhone.getPhone());
  188. userWhoami.setBindEmail(bindPhone.getEmail());
  189. }
  190. }
  191. Integer type = 3;
  192. if (StrUtil.isNotBlank(user.getLoginPhone())) {
  193. type = 1;
  194. } else if (StrUtil.isNotBlank(user.getEmail())) {
  195. type = 2;
  196. }
  197. userWhoami.setType(type);
  198. return userWhoami;
  199. }
  200. @Override
  201. public User getSyncUser(String openId, String unionId, WxSyncLog wxSyncLog) {
  202. User user;
  203. //迁移公众号之后同步授权后信息
  204. //是否是迁移用户
  205. if (wxSyncLog != null) {
  206. user = this.getOne(Wrappers.lambdaQuery(User.class)
  207. .ne(User::getUnionid, unionId)
  208. .eq(User::getOpenId, wxSyncLog.getOriOpenid()).last("limit 1"));
  209. if (user != null) {
  210. user.setOpenId(wxSyncLog.getNewOpenid());
  211. } else {
  212. // 查询用户是否存在
  213. user = Optional.ofNullable(
  214. this.getOne(new LambdaQueryWrapper<User>().eq(User::getUnionid, unionId)
  215. .orderByAsc(User::getId)
  216. .last("limit 1")))
  217. .orElseGet(() -> this.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId)
  218. .orderByAsc(User::getId)
  219. .last("limit 1")));
  220. }
  221. } else {
  222. // 查询用户是否存在
  223. user = Optional.ofNullable(
  224. this.getOne(new LambdaQueryWrapper<User>().eq(User::getUnionid, unionId)
  225. .orderByAsc(User::getId)
  226. .last("limit 1")))
  227. .orElseGet(() -> this.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId)
  228. .orderByAsc(User::getId)
  229. .last("limit 1")));
  230. }
  231. return user;
  232. }
  233. @Override
  234. public void sendFixedCustomerCoupon(Long popularizeId, Long userId, String unionId) {
  235. //若是百度渠道 添加固定客服 注册后直接发放优惠券
  236. ChannelPopularize channelPopularize = channelPopularizeMapper.selectById(popularizeId);
  237. if (channelPopularize != null && channelPopularize.getChannelId() == 34) {
  238. // SysConfig corpConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
  239. // .eq(SysConfig::getSysKey, Constant.CORP_FIXED_CUSTOMER)
  240. // .last("limit 1"));
  241. // if (corpConfig != null) {
  242. // Optional.ofNullable(corpConfig.getSysValue()).ifPresent(value -> {
  243. // try {
  244. // if (StrUtil.isNotBlank(value)) {
  245. // List<String> followIds = Jsons.parseList(value, String.class);
  246. // //添加固定客服发放优惠券
  247. // CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  248. // .field(CorpUserFollowView::getUnionId, unionId)
  249. // .field(CorpUserFollowView::getFollowId, followIds).op(Operator.InList).build());
  250. // if (corpUserFollowView != null) {
  251. // Constant.FIXED_CUSTOMER_COUPON_IDS.forEach(couponId -> couponCommonService.sendCouponToUser(userId, couponId, 0l, 0l, 0l, CouponUser.Channel.wxCorp));
  252. // }
  253. // }
  254. // } catch (Exception e) {
  255. // }
  256. // });
  257. //
  258. // }
  259. SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
  260. .eq(SysConfig::getSysKey, Constant.BAIDU_POPULARIZE_COUPON_IDS).last("limit 1"));
  261. if (config != null) {
  262. String sysValue = config.getSysValue();
  263. if (StrUtil.isNotBlank(sysValue)) {
  264. try {
  265. List<Long> couponIds = Jsons.parseList(sysValue, Long.class);
  266. couponIds.forEach(couponId -> couponCommonService.sendCouponToUser(userId, couponId, 0l, 0l, popularizeId, CouponUser.Channel.manual));
  267. } catch (Exception e) {
  268. log.error("百度渠道优惠券解析错误");
  269. }
  270. }
  271. }
  272. }
  273. }
  274. @Override
  275. public List<Long> getRelationUserIdList(Long userId, User selectUser) {
  276. List<Long> userIds = new ArrayList<>();
  277. userIds.add(userId);
  278. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  279. .eq(UserBindDetail::getUserId, userId).last("limit 1"));
  280. if (userBindDetail == null) {
  281. User user = Optional.ofNullable(selectUser).orElse(this.getById(userId));
  282. if (StrUtil.isEmpty(user.getOpenId()) && StrUtil.isNotEmpty(user.getLoginPhone())) {
  283. userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  284. .eq(UserBindDetail::getPhone, user.getLoginPhone()).last("limit 1"));
  285. if (userBindDetail != null) {
  286. userIds.add(userBindDetail.getUserId());
  287. }
  288. }
  289. } else {
  290. if (StrUtil.isNotBlank(userBindDetail.getPhone())) {
  291. User otherUser = this.getOne(Wrappers.lambdaQuery(User.class)
  292. .eq(User::getLoginPhone, userBindDetail.getPhone()).last("limit 1"));
  293. if (otherUser != null) {
  294. userIds.add(otherUser.getId());
  295. }
  296. }
  297. }
  298. return userIds;
  299. }
  300. @Override
  301. public List<Long> getUserIdsByNickname(String nickname) {
  302. return userMapper.selectListByNickname(nickname);
  303. }
  304. @Override
  305. public String getUserShowId(Long userId) {
  306. Integer update = 0;
  307. String showId = null;
  308. while (update != 1) {
  309. showId = StringUtil.randomString(5);
  310. try {
  311. update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  312. .set(User::getShowId, showId)
  313. .eq(User::getId, userId));
  314. } catch (DuplicateKeyException e) {
  315. update = 0;
  316. }
  317. }
  318. return showId;
  319. }
  320. @Override
  321. public Long getUserIdByShowId(String showId) {
  322. return userMapper.getUserIdByShowId(showId);
  323. }
  324. @Override
  325. public User webLogin(LoginReq loginReq) throws Exception {
  326. LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).last("limit 1");
  327. if (loginReq.getType() == null || loginReq.getType() < 1 && loginReq.getType() > 2) {
  328. throw BusinessRuntimeException.getInstance("系统异常,请刷新页面重新操作");
  329. }
  330. if (loginReq.getType() == 1) {
  331. if (StrUtil.hasEmpty(loginReq.getPhone(), loginReq.getCode())) {
  332. throw BusinessRuntimeException.getInstance("请输入对应信息");
  333. }
  334. DateTime now = DateTime.now();
  335. PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, loginReq.getPhone()).last("limit 1"));
  336. if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
  337. throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
  338. }
  339. //3分钟失效
  340. Date updateTime = phoneCode.getUpdateTime();
  341. DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
  342. if (now.isAfter(afterFiveMinutes)) {
  343. throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
  344. }
  345. if (!StrUtil.equals(loginReq.getCode(), phoneCode.getCode())) {
  346. throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
  347. }
  348. wrapper.eq(User::getLoginPhone, loginReq.getPhone());
  349. }
  350. if (loginReq.getType() == 2) {
  351. if (StrUtil.isEmpty(loginReq.getEmail())) {
  352. throw BusinessRuntimeException.getInstance("邮箱不能为空");
  353. }
  354. String code = redisService.getStr(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginReq.getEmail()));
  355. if (StrUtil.isEmpty(code)) {
  356. throw BusinessRuntimeException.getInstance("邮箱验证码已失效,请重新获取");
  357. }
  358. if (!StrUtil.equals(loginReq.getCode(), code)) {
  359. throw BusinessRuntimeException.getInstance("邮箱验证码错误,请重新输入");
  360. }
  361. redisService.del(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginReq.getEmail()));
  362. wrapper.eq(User::getEmail, loginReq.getEmail());
  363. }
  364. if (loginReq.getType() == 3){
  365. wrapper.eq(User::getEmail, loginReq.getEmail());
  366. }
  367. //保存用户信息
  368. User user = this.getOne(wrapper);
  369. String dsCode = loginReq.getDsCode();
  370. Long sharedId = loginReq.getSharedId();
  371. Long dsPopularizeId = null;
  372. Integer dsType = loginReq.getDsType();
  373. String customId = loginReq.getCustomId();
  374. Boolean isNewUser = false;
  375. if (StrUtil.isNotBlank(dsCode)) {
  376. dsCode = dsCode.trim();
  377. User sharedUser = this.getOne(Wrappers.lambdaQuery(User.class)
  378. .eq(User::getShowId, dsCode).last("limit 1"));
  379. if (sharedUser != null) {
  380. sharedId = sharedUser.getId();
  381. } else {
  382. UserDistributePopularize distributePopularize = distributePopularizeMapper.selectOne(Wrappers.lambdaQuery(UserDistributePopularize.class)
  383. .eq(UserDistributePopularize::getCode, dsCode)
  384. .select(UserDistributePopularize::getUserId, UserDistributePopularize::getId).last("limit 1"));
  385. if (distributePopularize != null) {
  386. log.info("渠道sharedId:{}设置固定推广链接PC用户分销", distributePopularize.getUserId());
  387. sharedId = distributePopularize.getUserId();
  388. dsPopularizeId = distributePopularize.getId();
  389. }
  390. }
  391. }
  392. if (user != null && loginReq.getType() == 3 && !user.getIsGoogle()) {
  393. user.setIsGoogle(true);
  394. this.updateById(user);
  395. }
  396. if (user == null) {
  397. user = new User();
  398. isNewUser = true;
  399. StringBuilder name = new StringBuilder();
  400. name.append(Constant.DEFAULT_NAME);
  401. if (loginReq.getPopularizeId() != null) {
  402. user.setPopularizeId(loginReq.getPopularizeId());
  403. }
  404. if (loginReq.getType() == 1) {
  405. user.setLoginPhone(loginReq.getPhone());
  406. }
  407. if (loginReq.getType() == 2 || loginReq.getType() == 3) {
  408. user.setEmail(loginReq.getEmail());
  409. name.append("@");
  410. }
  411. if (loginReq.getType() == 3) {
  412. user.setIsGoogle(true);
  413. }
  414. user.setNickname(String.format("%s%s", name.toString(), RandomUtil.randomString(6)));
  415. //默认头像
  416. user.setHeadimgurl(Constant.DEFAULT_HEAD_IMG);
  417. String registerEnv = loginReq.getRegisterEnv();
  418. user.setRegisterEnv(StrUtil.isEmpty(registerEnv) ? User.RegisterEnv.pc.name() : registerEnv);
  419. this.save(user);
  420. //新用户分销
  421. if (sharedId != null) {
  422. distributeService.saveDistributionInvitation(sharedId, user.getId(), dsPopularizeId);
  423. }
  424. //店铺注册用户 关联
  425. if (StrUtil.isNotBlank(customId)) {
  426. yhShopDistributeService.saveDistributionInvitation(customId, user.getId());
  427. }
  428. //缓存用户注册 回传信息
  429. String callback = loginReq.getCallback();
  430. String callbackType = loginReq.getCallbackType();
  431. if (StrUtil.isNotBlank(callback)) {
  432. OrderDonPostDataDto orderDonPostDataDto = new OrderDonPostDataDto().setCallback(callback)
  433. .setCallbackType(callbackType);
  434. redisService.set(RedisService.key.ORDER_DON_POST_DATA_USER_KEY.getName() + user.getId(), Jsons.toJson(orderDonPostDataDto));
  435. }
  436. //发放新用户福利
  437. final Long fUid = user.getId();
  438. TASK_POOL.execute(() -> {
  439. try {
  440. sendNewUserWelfare(fUid);
  441. } catch (Exception e) {
  442. }
  443. });
  444. final String login_email = user.getEmail();
  445. final String login_phone = user.getLoginPhone();
  446. UserBindDetail bindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  447. .and(ub -> ub.eq(StrUtil.isNotBlank(login_email), UserBindDetail::getEmail, login_email)
  448. .or().eq(StrUtil.isNotBlank(login_phone), UserBindDetail::getPhone, login_phone))
  449. .last("limit 1"));
  450. if (bindDetail != null) {
  451. if (StrUtil.isNotBlank(login_phone)) {
  452. bindDetail.setPhoneUserId(user.getId());
  453. }
  454. if (StrUtil.isNotBlank(login_email)) {
  455. bindDetail.setEmailUserId(user.getId());
  456. }
  457. userBindDetailMapper.updateById(bindDetail);
  458. }
  459. }
  460. if (StrUtil.isEmpty(user.getShowId())) {
  461. user.setShowId(getUserShowId(user.getId()));
  462. }
  463. //新旧用户都可实物分销
  464. if (sharedId != null && dsType != null && dsType == 2) {
  465. equipDistributeService.saveDistributionInvitation(sharedId, isNewUser, user.getId());
  466. }
  467. return user;
  468. }
  469. @Override
  470. public String bindWxAccountRedirect(String code, String state) throws Exception {
  471. AuthToken token = weChatService.getAuthToken(code, wxOpenPlatYHLXLoginConfig.getAppId());
  472. //重定向
  473. // 根据openid 与 access_token 获取用户信息
  474. GzhOAuth2UserInfo userinfo = weChatService.getUserInfo(token.getAccessToken(), token.getOpenid());
  475. // 转跳参数
  476. String json = Codec.DoBase64.custom().setData(state).decodeAsText();
  477. AuthRedirect re = Jsons.parseObject(json, AuthRedirect.class);
  478. //保存用户信息
  479. User user = saveAuth(userinfo, re.getSharedId(), re.getDsType(), re.getPid(), User.RegisterEnv.pc, re.getDsCode(), re.getCk(), re.getCt(), re.getCd());
  480. if (user == null) {
  481. throw BusinessRuntimeException.getInstance("系统错误,请重新授权");
  482. }
  483. String loginPhone = re.getLp();
  484. String loginEmail = re.getLe();
  485. if (StrUtil.isNotBlank(loginPhone)) {
  486. log.info("手机号phone:{}登录用户,微信扫描网页授权二维码进行用户信息绑定", loginPhone);
  487. try {
  488. bindTaskService.bindPhone(user, loginPhone, null);
  489. } catch (Exception e) {
  490. log.info(StringUtil.getErrorText(e));
  491. }
  492. }
  493. if (StrUtil.isNotBlank(loginEmail)) {
  494. log.info("邮箱email:{}登录用户,微信扫描网页授权二维码进行用户信息绑定", loginEmail);
  495. try {
  496. bindTaskService.bindEmail(user, loginEmail, null);
  497. } catch (Exception e) {
  498. log.info(StringUtil.getErrorText(e));
  499. }
  500. }
  501. return redisService.getStr(re.getMappingId().toString());
  502. }
  503. @Override
  504. @Transactional(rollbackFor = Throwable.class)
  505. public void receiveGiftCardByRc(Long userId, String code, Long relationId) {
  506. GiftCardUserRecord giftCardUserRecord = giftCardUserRecordMapper.selectOne(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  507. .eq(GiftCardUserRecord::getRc, code).last("limit 1"));
  508. if (giftCardUserRecord == null) {
  509. throw BusinessRuntimeException.getInstance("好友赠送礼品卡不存在");
  510. }
  511. if (!giftCardUserRecord.getIsPay()) {
  512. throw BusinessRuntimeException.getInstance("无效礼品卡,好友未购买");
  513. }
  514. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  515. if (relationUserIdList.contains(giftCardUserRecord.getUserId())) {
  516. throw BusinessRuntimeException.getInstance("无法领取自己购买的礼品卡");
  517. }
  518. if (giftCardUserRecord.getToUserId() != 0 && !giftCardUserRecord.getToUserId().equals(userId)) {
  519. throw BusinessRuntimeException.getInstance("好友赠送礼品卡已被领取");
  520. }
  521. if (giftCardUserRecord.getToUserId().equals(userId)) {
  522. throw BusinessRuntimeException.getInstance("您已领取该礼品卡");
  523. }
  524. giftCardUserRecord.setToUserId(userId);
  525. int update = giftCardUserRecordMapper.update(null, Wrappers.lambdaUpdate(GiftCardUserRecord.class)
  526. .set(giftCardUserRecord.getGcType() == 2, GiftCardUserRecord::getIsUsed, true)
  527. .set(GiftCardUserRecord::getToUserId, userId)
  528. .set(GiftCardUserRecord::getIsSend, true)
  529. .set(GiftCardUserRecord::getReceivedTime, DateTime.now())
  530. .eq(GiftCardUserRecord::getId, giftCardUserRecord.getId())
  531. .eq(GiftCardUserRecord::getIsPay, true)
  532. .eq(GiftCardUserRecord::getToUserId, 0));
  533. if (update > 0) {
  534. //虚拟卡
  535. //直接发送 对应规格车票
  536. if (giftCardUserRecord.getGcType() == 2) {
  537. Long gcSkuId = giftCardUserRecord.getGcSkuId();
  538. log.info("用户userId:{}领取礼品卡id:{},开始发放虚拟车票skuId:{}", userId, giftCardUserRecord.getId(), gcSkuId);
  539. GoodsDonSku sku = goodsDonSkuMapper.selectById(gcSkuId);
  540. if (sku == null) {
  541. log.info("礼品卡id:{}虚拟车票skuId:{}不存在", giftCardUserRecord.getId(), gcSkuId);
  542. throw BusinessRuntimeException.getInstance("该礼品卡对应的虚拟卡不存在,请联系客服");
  543. }
  544. if (relationId != null) {
  545. GroupsRelation groupsRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  546. .in(GroupsRelation::getUserId, relationUserIdList)
  547. .eq(GroupsRelation::getId, relationId)
  548. .in(GroupsRelation::getStatus, List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside)).last("limit 1"));
  549. if (groupsRelation == null) {
  550. throw BusinessRuntimeException.getInstance("您选择的车票不存在");
  551. }
  552. Date expiryTime = groupsRelation.getExpiryTime();
  553. if (expiryTime == null) {
  554. throw BusinessRuntimeException.getInstance("请等您该类型下的车票配置账号后再增加对应时长");
  555. }
  556. if (sku.getDays() != null && sku.getDays() > 0) {
  557. expiryTime = DateUtil.offsetDay(expiryTime, sku.getDays());
  558. } else {
  559. expiryTime = DateUtil.offsetMonth(expiryTime, sku.getMonths());
  560. }
  561. log.info("userId:{}领取虚拟卡skuId:{},增加车票时长至:{}", userId, sku.getId(), expiryTime.toString());
  562. groupsRelation.setExpiryTime(expiryTime);
  563. groupsRelationMapper.updateById(groupsRelation);
  564. return;
  565. }
  566. //是否存在对应车票
  567. List<UserTicketView> ticketViews = beanSearcher.searchAll(UserTicketView.class, MapUtils.builder()
  568. .field(UserTicketView::getUserId, relationUserIdList).op(Operator.InList)
  569. .field(UserTicketView::getGoodsId, giftCardUserRecord.getGcGoodsId())
  570. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  571. .orderBy(UserTicketView::getRelationId).asc()
  572. .build());
  573. if (CollUtil.isEmpty(ticketViews)) {
  574. GroupsRelation relationNoOrder = exchangeCodeService.getRelationNoOrder(sku, userId, null);
  575. giftCardUserRecordMapper.update(null, Wrappers.lambdaUpdate(GiftCardUserRecord.class)
  576. .set(GiftCardUserRecord::getRelationId, relationNoOrder.getId())
  577. .eq(GiftCardUserRecord::getId, giftCardUserRecord.getId()));
  578. log.info("用户未有该规格:{}车票,发送至用户userId:{}礼品卡虚拟车票结束", gcSkuId, userId);
  579. return;
  580. }
  581. if (ticketViews.size() > 1) {
  582. throw BusinessRuntimeException.getInstance("您有多张该类型的车票,请选择一张增加时长");
  583. }
  584. UserTicketView userTicketView = ticketViews.get(0);
  585. Date expiryTime = userTicketView.getExpiryTime();
  586. if (expiryTime == null) {
  587. throw BusinessRuntimeException.getInstance("请等您该类型下的车票配置账号后再增加对应时长");
  588. }
  589. if (sku.getDays() != null && sku.getDays() > 0) {
  590. expiryTime = DateUtil.offsetDay(expiryTime, sku.getDays());
  591. } else {
  592. expiryTime = DateUtil.offsetMonth(expiryTime, sku.getMonths());
  593. }
  594. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  595. .set(GroupsRelation::getExpiryTime, expiryTime)
  596. .eq(GroupsRelation::getId, userTicketView.getRelationId()));
  597. }
  598. }
  599. }
  600. /**
  601. * 发放新用户福利
  602. */
  603. public void sendNewUserWelfare(Long userId) throws Exception {
  604. SysConfig newUserWelfareConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
  605. .eq(SysConfig::getSysKey, Constant.NEW_USER_WELFARE_KEY).last("limit 1"));
  606. if (StrUtil.isEmpty(newUserWelfareConfig.getSysValue())) {
  607. return;
  608. }
  609. NewUserWelfareDto newUserWelfareDto = Jsons.parseObject(newUserWelfareConfig.getSysValue(), NewUserWelfareDto.class);
  610. if (newUserWelfareDto != null) {
  611. List<Long> couponIds = newUserWelfareDto.getCouponIds();
  612. couponIds.forEach(couponId -> couponCommonService.sendCouponToUser(userId, couponId, null, null, null, CouponUser.Channel.new_welfare));
  613. }
  614. }
  615. }