UserServiceImpl.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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.station.CollegeStudentStationUserRelateMapper;
  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.relation.GroupRelationFrontService;
  38. import com.cyksj.service.shop.YhShopDistributeService;
  39. import com.cyksj.service.sys.SysConfigService;
  40. import com.cyksj.service.user.BadIntentionOpService;
  41. import com.cyksj.service.user.UserBindRelationService;
  42. import com.cyksj.service.user.UserLoginRecordService;
  43. import com.cyksj.service.user.UserService;
  44. import com.cyksj.service.wechat.WeChatService;
  45. import com.ejlchina.searcher.BeanSearcher;
  46. import com.ejlchina.searcher.param.Operator;
  47. import com.ejlchina.searcher.util.MapUtils;
  48. import lombok.RequiredArgsConstructor;
  49. import lombok.extern.slf4j.Slf4j;
  50. import org.springframework.dao.DuplicateKeyException;
  51. import org.springframework.stereotype.Service;
  52. import org.springframework.transaction.annotation.Transactional;
  53. import org.springframework.util.Assert;
  54. import javax.servlet.http.HttpServletRequest;
  55. import java.util.ArrayList;
  56. import java.util.Date;
  57. import java.util.List;
  58. import java.util.Optional;
  59. /**
  60. * @author chan
  61. * @date 2021/10/10 下午3:27
  62. */
  63. @Slf4j
  64. @Service
  65. @RequiredArgsConstructor
  66. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  67. private final DistributeService distributeService;
  68. private final EquipmentDistributeService equipDistributeService;
  69. private final ChannelPopularizeMapper channelPopularizeMapper;
  70. private final CouponCommonService couponCommonService;
  71. private final RedisService redisService;
  72. private final SysConfigService sysConfigService;
  73. private final UserBindDetailMapper userBindDetailMapper;
  74. private final UserDistributePopularizeMapper distributePopularizeMapper;
  75. private final UserMapper userMapper;
  76. private final PhoneCodeMapper phoneCodeMapper;
  77. private final WeChatService weChatService;
  78. private final BindTaskService bindTaskService;
  79. private final WxOpenPlatYHLXLoginConfig wxOpenPlatYHLXLoginConfig;
  80. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  81. private final ExchangeCodeService exchangeCodeService;
  82. private final GoodsDonSkuMapper goodsDonSkuMapper;
  83. private final GroupsRelationMapper groupsRelationMapper;
  84. private final BeanSearcher beanSearcher;
  85. private final UserBindRelationService userBindRelationService;
  86. private final YhShopDistributeService yhShopDistributeService;
  87. private final CorpUserMapper corpUserMapper;
  88. private final CorpUserTagMapper corpUserTagMapper;
  89. private final CorpFollowActiveCodeMapper corpFollowActiveCodeMapper;
  90. private final CorpCustomerAcquisitionLinkMapper corpCustomerAcquisitionLinkMapper;
  91. private final CorpWelcomeTemplateMapper corpWelcomeTemplateMapper;
  92. private final UserLoginRecordService userLoginRecordService;
  93. private final UserDistributeSharedMapper userDistributeSharedMapper;
  94. private final BadIntentionOpService badIntentionOpService;
  95. private final CollegeStudentStationUserRelateMapper collegeStudentStationUserRelateMapper;
  96. private final GroupRelationFrontService groupRelationFrontService;
  97. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  98. @Override
  99. public User saveAuth(GzhOAuth2UserInfo info, AuthRedirect re, User.RegisterEnv registerEnv) throws Exception {
  100. Long sharedId = re.getSharedId();
  101. Integer dsType = re.getDsType();
  102. Long pid = re.getPid();
  103. String dsCode = re.getDsCode();
  104. String callback = re.getCk();
  105. String callbackType = re.getCt();
  106. String customId = re.getCd();
  107. final String unionid = info.getUnionid();
  108. if (StrUtil.isEmpty(unionid)) {
  109. throw BusinessRuntimeException.getInstance("授权操作异常,请刷新页面");
  110. }
  111. User user = getSyncUser(info.getOpenid(), info.getUnionid(), null);
  112. user = Optional.ofNullable(user).orElseGet(() -> new User()
  113. .setUnionid(unionid));
  114. user.setCountry(info.getCountry())
  115. .setProvince(info.getProvince())
  116. .setCity(info.getCity());
  117. if (user.getSex() == null) {
  118. user.setSex(info.getSex());
  119. }
  120. if (StrUtil.isEmpty(user.getHeadimgurl())) {
  121. user.setHeadimgurl(info.getHeadimgurl());
  122. }
  123. if (StrUtil.isEmpty(user.getNickname())) {
  124. user.setNickname(info.getNickname());
  125. }
  126. user.setUnionid(unionid);
  127. user.setOpenId(info.getOpenid());
  128. Boolean isNewUser = false;
  129. if (user.getId() == null) {
  130. isNewUser = true;
  131. user.setPopularizeId(pid);
  132. user.setRegisterEnv(registerEnv.name());
  133. if (!redisService.setNx(RedisService.key.REPEAT_USER_KEY.getNameFormat(user.getUnionid()), user.getUnionid(), RedisService.key.REPEAT_USER_KEY.getTimeout())) {
  134. return this.getOne(Wrappers.lambdaQuery(User.class)
  135. .eq(User::getUnionid, unionid).last("limit 1"));
  136. }
  137. this.save(user);
  138. //缓存用户注册 回传信息
  139. if (StrUtil.isNotBlank(callback)) {
  140. OrderDonPostDataDto orderDonPostDataDto = new OrderDonPostDataDto().setCallback(callback)
  141. .setCallbackType(callbackType);
  142. redisService.set(RedisService.key.ORDER_DON_POST_DATA_USER_KEY.getName() + user.getId(), Jsons.toJson(orderDonPostDataDto));
  143. }
  144. //发放新用户福利
  145. final Long fUid = user.getId();
  146. TASK_POOL.execute(() -> {
  147. try {
  148. sendNewUserWelfare(fUid);
  149. } catch (Exception e) {
  150. }
  151. //去关联对应企业微信用户
  152. relateCorpUserAndSengWelfare(fUid, unionid);
  153. });
  154. } else {
  155. if (StrUtil.isEmpty(user.getRegisterEnv())) {
  156. user.setRegisterEnv(registerEnv.name());
  157. }
  158. this.updateById(user);
  159. }
  160. Long dsPopularizeId = null;
  161. if (StrUtil.isNotBlank(dsCode)) {
  162. UserSharedDto userSharedDto = getUserShredDtoByDsCode(dsCode);
  163. sharedId = userSharedDto.getSharedId();
  164. dsPopularizeId = userSharedDto.getDsPopularizeId();
  165. }
  166. if (sharedId != null && isNewUser) {
  167. if (dsType == null || dsType == 1) {
  168. distributeService.saveDistributionInvitation(sharedId, user.getId(), dsPopularizeId);
  169. }
  170. }
  171. //店铺注册用户 关联
  172. if (isNewUser && StrUtil.isNotBlank(customId)) {
  173. yhShopDistributeService.saveDistributionInvitation(customId, user.getId());
  174. }
  175. Long userId = user.getId();
  176. if (isNewUser && pid != null) {
  177. TASK_POOL.execute(() -> {
  178. sendFixedCustomerCoupon(pid, userId, unionid);
  179. });
  180. }
  181. //新旧用户都可实物分销
  182. if (sharedId != null && dsType != null && dsType == 2) {
  183. equipDistributeService.saveDistributionInvitation(sharedId, isNewUser, user.getId());
  184. }
  185. //每日活跃记录
  186. userLoginRecordService.saveUserLoginDayRecord(user.getId());
  187. //是否是大学生快递站进来的用户
  188. Integer cst = re.getCst();
  189. if (cst != null) {
  190. TASK_POOL.execute(() -> {
  191. handlerCollegeStudentUser(userId, cst);
  192. });
  193. }
  194. return user;
  195. }
  196. @Override
  197. public UserWhoami whoami(long userId) {
  198. User user = this.getById(userId);
  199. Assert.notNull(user, "业务处理失败,请联系客服");
  200. UserWhoami userWhoami = new UserWhoami();
  201. if (StrUtil.isEmpty(user.getShowId())) {
  202. user.setShowId(getUserShowId(userId));
  203. }
  204. BeanUtil.copyProperties(user, userWhoami);
  205. UserBindDetail bindPhone = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  206. .eq(StrUtil.isNotEmpty(user.getOpenId()), UserBindDetail::getUserId, userId)
  207. .eq(StrUtil.isNotBlank(user.getLoginPhone()), UserBindDetail::getPhoneUserId, userId)
  208. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  209. //手机号
  210. if (bindPhone != null) {
  211. userWhoami.setBindPhone(bindPhone.getPhone());
  212. userWhoami.setBindEmail(bindPhone.getEmail());
  213. }
  214. Integer type = 3;
  215. if (StrUtil.isNotBlank(user.getLoginPhone())) {
  216. type = 1;
  217. } else if (StrUtil.isNotBlank(user.getEmail())) {
  218. type = 2;
  219. }
  220. userWhoami.setType(type);
  221. return userWhoami;
  222. }
  223. @Override
  224. public User getSyncUser(String openId, String unionId, WxSyncLog wxSyncLog) {
  225. User user;
  226. //迁移公众号之后同步授权后信息
  227. //是否是迁移用户
  228. if (wxSyncLog != null) {
  229. user = this.getOne(Wrappers.lambdaQuery(User.class)
  230. .ne(User::getUnionid, unionId)
  231. .eq(User::getOpenId, wxSyncLog.getOriOpenid()).last("limit 1"));
  232. if (user != null) {
  233. user.setOpenId(wxSyncLog.getNewOpenid());
  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. } else {
  245. // 查询用户是否存在
  246. user = Optional.ofNullable(
  247. this.getOne(new LambdaQueryWrapper<User>().eq(User::getUnionid, unionId)
  248. .orderByAsc(User::getId)
  249. .last("limit 1")))
  250. .orElseGet(() -> this.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId)
  251. .orderByAsc(User::getId)
  252. .last("limit 1")));
  253. }
  254. return user;
  255. }
  256. @Override
  257. public void sendFixedCustomerCoupon(Long popularizeId, Long userId, String unionId) {
  258. //若是百度渠道 添加固定客服 注册后直接发放优惠券
  259. ChannelPopularize channelPopularize = channelPopularizeMapper.selectById(popularizeId);
  260. if (channelPopularize != null && channelPopularize.getChannelId() == 34) {
  261. // SysConfig corpConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
  262. // .eq(SysConfig::getSysKey, Constant.CORP_FIXED_CUSTOMER)
  263. // .last("limit 1"));
  264. // if (corpConfig != null) {
  265. // Optional.ofNullable(corpConfig.getSysValue()).ifPresent(value -> {
  266. // try {
  267. // if (StrUtil.isNotBlank(value)) {
  268. // List<String> followIds = Jsons.parseList(value, String.class);
  269. // //添加固定客服发放优惠券
  270. // CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  271. // .field(CorpUserFollowView::getUnionId, unionId)
  272. // .field(CorpUserFollowView::getFollowId, followIds).op(Operator.InList).build());
  273. // if (corpUserFollowView != null) {
  274. // Constant.FIXED_CUSTOMER_COUPON_IDS.forEach(couponId -> couponCommonService.sendCouponToUser(userId, couponId, 0l, 0l, 0l, CouponUser.Channel.wxCorp));
  275. // }
  276. // }
  277. // } catch (Exception e) {
  278. // }
  279. // });
  280. //
  281. // }
  282. SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
  283. .eq(SysConfig::getSysKey, Constant.BAIDU_POPULARIZE_COUPON_IDS).last("limit 1"));
  284. if (config != null) {
  285. String sysValue = config.getSysValue();
  286. if (StrUtil.isNotBlank(sysValue)) {
  287. try {
  288. List<Long> couponIds = Jsons.parseList(sysValue, Long.class);
  289. couponIds.forEach(couponId -> couponCommonService.sendCouponToUser(userId, couponId, 0l, 0l, popularizeId, CouponUser.Channel.manual));
  290. } catch (Exception e) {
  291. log.error("百度渠道优惠券解析错误");
  292. }
  293. }
  294. }
  295. }
  296. }
  297. @Override
  298. public List<Long> getRelationUserIdList(Long userId, User selectUser) {
  299. List<Long> userIds = new ArrayList<>();
  300. userIds.add(userId);
  301. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  302. .eq(UserBindDetail::getUserId, userId).last("limit 1"));
  303. if (userBindDetail == null) {
  304. User user = Optional.ofNullable(selectUser).orElse(this.getById(userId));
  305. if (StrUtil.isEmpty(user.getOpenId()) && StrUtil.isNotEmpty(user.getLoginPhone())) {
  306. userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  307. .eq(UserBindDetail::getPhone, user.getLoginPhone()).last("limit 1"));
  308. if (userBindDetail != null) {
  309. userIds.add(userBindDetail.getUserId());
  310. }
  311. }
  312. } else {
  313. if (StrUtil.isNotBlank(userBindDetail.getPhone())) {
  314. User otherUser = this.getOne(Wrappers.lambdaQuery(User.class)
  315. .eq(User::getLoginPhone, userBindDetail.getPhone()).last("limit 1"));
  316. if (otherUser != null) {
  317. userIds.add(otherUser.getId());
  318. }
  319. }
  320. }
  321. return userIds;
  322. }
  323. @Override
  324. public List<Long> getUserIdsByNickname(String nickname) {
  325. return userMapper.selectListByNickname(nickname);
  326. }
  327. @Override
  328. public String getUserShowId(Long userId) {
  329. Integer update = 0;
  330. String showId = null;
  331. while (update != 1) {
  332. showId = StringUtil.randomString(5);
  333. try {
  334. update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  335. .set(User::getShowId, showId)
  336. .eq(User::getId, userId));
  337. } catch (DuplicateKeyException e) {
  338. update = 0;
  339. }
  340. }
  341. return showId;
  342. }
  343. @Override
  344. public Long getUserIdByShowId(String showId) {
  345. return userMapper.getUserIdByShowId(showId);
  346. }
  347. @Override
  348. public User webLogin(LoginReq loginReq, HttpServletRequest request) throws Exception {
  349. LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).last("limit 1");
  350. if (loginReq.getType() == null || loginReq.getType() < 1 || loginReq.getType() > 3) {
  351. throw BusinessRuntimeException.getInstance("系统异常,请刷新页面重新操作");
  352. }
  353. if (loginReq.getType() == 1) {
  354. if (StrUtil.hasEmpty(loginReq.getPhone(), loginReq.getCode())) {
  355. throw BusinessRuntimeException.getInstance("请输入对应信息");
  356. }
  357. DateTime now = DateTime.now();
  358. PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, loginReq.getPhone()).last("limit 1"));
  359. if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
  360. throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
  361. }
  362. //3分钟失效
  363. Date updateTime = phoneCode.getUpdateTime();
  364. DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
  365. if (now.isAfter(afterFiveMinutes)) {
  366. throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
  367. }
  368. if (!StrUtil.equals(loginReq.getCode(), phoneCode.getCode())) {
  369. //是否是恶意用户
  370. badIntentionOpService.isBadOpLoginPhone(request, loginReq.getPhone());
  371. throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
  372. }
  373. wrapper.eq(User::getLoginPhone, loginReq.getPhone());
  374. }
  375. if (loginReq.getType() == 2) {
  376. if (StrUtil.isEmpty(loginReq.getEmail())) {
  377. throw BusinessRuntimeException.getInstance("邮箱不能为空");
  378. }
  379. String code = redisService.getStr(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginReq.getEmail()));
  380. if (StrUtil.isEmpty(code)) {
  381. throw BusinessRuntimeException.getInstance("邮箱验证码已失效,请重新获取");
  382. }
  383. if (!StrUtil.equals(loginReq.getCode(), code)) {
  384. throw BusinessRuntimeException.getInstance("邮箱验证码错误,请重新输入");
  385. }
  386. redisService.del(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginReq.getEmail()));
  387. wrapper.eq(User::getEmail, loginReq.getEmail());
  388. }
  389. if (loginReq.getType() == 3) {
  390. wrapper.eq(User::getEmail, loginReq.getEmail());
  391. }
  392. //保存用户信息
  393. User user = this.getOne(wrapper);
  394. String dsCode = loginReq.getDsCode();
  395. Long sharedId = loginReq.getSharedId();
  396. Long dsPopularizeId = null;
  397. Integer dsType = loginReq.getDsType();
  398. String customId = loginReq.getCustomId();
  399. Boolean isNewUser = false;
  400. if (StrUtil.isNotBlank(dsCode)) {
  401. UserSharedDto userSharedDto = getUserShredDtoByDsCode(dsCode);
  402. sharedId = userSharedDto.getSharedId();
  403. dsPopularizeId = userSharedDto.getDsPopularizeId();
  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, User.RegisterEnv.pc);
  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 && StrUtil.isNotBlank(corpWelcomeTemplate.getCouponIds())) {
  659. final CouponUser.Channel fChannel = channel;
  660. try {
  661. List<Long> couponIds = Jsons.parseList(corpWelcomeTemplate.getCouponIds(), Long.class);
  662. couponIds.forEach(couponId -> couponCommonService.sendCouponToUser(fUid, couponId, 0l, 0l, 0l, fChannel));
  663. } catch (Exception e) {
  664. }
  665. }
  666. }
  667. //是否有对应获客链接的标签
  668. List<Long> tagIds = corpUserTagMapper.getTagIdByCorpUserId(corpUser.getId());
  669. if (CollUtil.isNotEmpty(tagIds)) {
  670. List<String> couponIdsStrList = corpCustomerAcquisitionLinkMapper.selectAcLinkCorpTemplateCouponIdsByTagIds(tagIds);
  671. if (CollUtil.isNotEmpty(couponIdsStrList)) {
  672. log.info("用户userId:{}存在获客链接标记的标签:{}", fUid, tagIds);
  673. couponIdsStrList.forEach(couponIdsStr -> {
  674. try {
  675. Jsons.parseList(couponIdsStr, Long.class).forEach(couponId -> couponCommonService.sendCouponToUser(fUid, couponId, 0l, 0l, 0l, CouponUser.Channel.customer_link));
  676. } catch (Exception e) {
  677. }
  678. });
  679. }
  680. }
  681. }
  682. }
  683. @Override
  684. public UserSharedDto getUserShredDtoByDsCode(String dsCode) {
  685. Long sharedId = 0l;
  686. Long dsPopularizeId = 0l;
  687. dsCode = dsCode.trim();
  688. User sharedUser = getOne(Wrappers.lambdaQuery(User.class)
  689. .eq(User::getShowId, dsCode).last("limit 1"));
  690. if (sharedUser != null) {
  691. sharedId = sharedUser.getId();
  692. } else {
  693. UserDistributePopularize distributePopularize = distributePopularizeMapper.selectOne(Wrappers.lambdaQuery(UserDistributePopularize.class)
  694. .eq(UserDistributePopularize::getCode, dsCode)
  695. .select(UserDistributePopularize::getUserId, UserDistributePopularize::getId).last("limit 1"));
  696. if (distributePopularize != null) {
  697. log.info("渠道sharedId:{}设置固定推广链接用户分销", distributePopularize.getUserId());
  698. sharedId = distributePopularize.getUserId();
  699. dsPopularizeId = distributePopularize.getId();
  700. }
  701. }
  702. UserSharedDto sharedDto = new UserSharedDto();
  703. sharedDto.setSharedId(sharedId);
  704. sharedDto.setDsPopularizeId(dsPopularizeId);
  705. return sharedDto;
  706. }
  707. @Override
  708. public Long getSharedIdByUserId(Long userId) {
  709. UserDistributeShared distributeShared = userDistributeSharedMapper.selectOne(Wrappers.lambdaQuery(UserDistributeShared.class)
  710. .eq(UserDistributeShared::getUserId, userId)
  711. .last("limit 1")
  712. .select(UserDistributeShared::getSharedId));
  713. if (distributeShared == null) {
  714. return 0l;
  715. }
  716. return distributeShared.getSharedId();
  717. }
  718. @Override
  719. public void bindUserDistributeShared(Long userId, String dsCode) {
  720. User user = userMapper.selectById(userId);
  721. if (StrUtil.equals(user.getShowId(), dsCode)) {
  722. return;
  723. }
  724. UserSharedDto userSharedDto = getUserShredDtoByDsCode(dsCode);
  725. Long sharedId = userSharedDto.getSharedId();
  726. Long dsPopularizeId = userSharedDto.getDsPopularizeId();
  727. //建立绑定关系
  728. log.info("建立用户userId:{}与sharedId:{}绑定关系", userId, sharedId);
  729. distributeService.saveDistributionInvitation(sharedId, user.getId(), dsPopularizeId);
  730. }
  731. @Override
  732. public void saveEpDistributeShared(Long userId, String dsCode) {
  733. if (StrUtil.isEmpty(dsCode)) {
  734. log.info("设备好友邀请userId:{},code为空", userId);
  735. return;
  736. }
  737. User user = getById(userId);
  738. Date createdTime = user.getCreatedTime();
  739. String createDate = new DateTime(createdTime).toDateStr();
  740. Boolean isNewUser = false;
  741. if (StrUtil.equals(createDate, DateTime.now().toDateStr())) {
  742. isNewUser = true;
  743. }
  744. UserSharedDto userSharedDto = getUserShredDtoByDsCode(dsCode);
  745. if (userSharedDto != null) {
  746. log.info("实物好友分销邀请sharedId:{},被邀请用户id:{}", userSharedDto.getSharedId(), userId);
  747. equipDistributeService.saveDistributionInvitation(userSharedDto.getSharedId(), isNewUser, user.getId());
  748. }
  749. }
  750. /**
  751. * 处理大学生快递站用户
  752. */
  753. public void handlerCollegeStudentUser(Long userId, Integer cst) {
  754. try {
  755. CollegeStudentStationUserRelate cstRelate = new CollegeStudentStationUserRelate();
  756. cstRelate.setType(cst);
  757. cstRelate.setUserId(userId);
  758. collegeStudentStationUserRelateMapper.insert(cstRelate);
  759. //赠送1天的GPT镜像车票
  760. groupRelationFrontService.getCollegeStudentUserGptTicket(userId);
  761. } catch (DuplicateKeyException e) {
  762. }
  763. }
  764. }