UserServiceImpl.java 29 KB

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