UserServiceImpl.java 31 KB

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