UserServiceImpl.java 29 KB

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