UserServiceImpl.java 36 KB

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