UserServiceImpl.java 30 KB

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