UserServiceImpl.java 36 KB

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