UserService.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. package com.izouma.nineth.service;
  2. import cn.binarywang.wx.miniapp.api.WxMaService;
  3. import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
  4. import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
  5. import com.huifu.adapay.core.exception.BaseAdaPayException;
  6. import com.izouma.nineth.TokenHistory;
  7. import com.izouma.nineth.config.Constants;
  8. import com.izouma.nineth.config.GeneralProperties;
  9. import com.izouma.nineth.domain.Collection;
  10. import com.izouma.nineth.domain.*;
  11. import com.izouma.nineth.dto.*;
  12. import com.izouma.nineth.enums.AuthStatus;
  13. import com.izouma.nineth.enums.AuthorityName;
  14. import com.izouma.nineth.event.AccountCreatedEvent;
  15. import com.izouma.nineth.event.RegisterEvent;
  16. import com.izouma.nineth.exception.BusinessException;
  17. import com.izouma.nineth.repo.*;
  18. import com.izouma.nineth.security.Authority;
  19. import com.izouma.nineth.security.JwtTokenUtil;
  20. import com.izouma.nineth.security.JwtUserFactory;
  21. import com.izouma.nineth.service.sms.SmsService;
  22. import com.izouma.nineth.service.storage.StorageService;
  23. import com.izouma.nineth.utils.BankUtils;
  24. import com.izouma.nineth.utils.JpaUtils;
  25. import com.izouma.nineth.utils.ObjUtils;
  26. import com.izouma.nineth.utils.SecurityUtils;
  27. import lombok.AllArgsConstructor;
  28. import lombok.extern.slf4j.Slf4j;
  29. import me.chanjar.weixin.common.error.WxErrorException;
  30. import me.chanjar.weixin.mp.api.WxMpService;
  31. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  32. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  33. import org.apache.commons.lang3.ObjectUtils;
  34. import org.apache.commons.lang3.RandomStringUtils;
  35. import org.apache.commons.lang3.StringUtils;
  36. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  37. import org.springframework.beans.BeanUtils;
  38. import org.springframework.cache.annotation.CacheEvict;
  39. import org.springframework.cache.annotation.Cacheable;
  40. import org.springframework.context.event.EventListener;
  41. import org.springframework.core.env.Environment;
  42. import org.springframework.data.domain.Page;
  43. import org.springframework.data.domain.PageImpl;
  44. import org.springframework.data.jpa.domain.Specification;
  45. import org.springframework.data.redis.core.RedisTemplate;
  46. import org.springframework.scheduling.annotation.Async;
  47. import org.springframework.security.crypto.password.PasswordEncoder;
  48. import org.springframework.stereotype.Service;
  49. import javax.persistence.criteria.Predicate;
  50. import java.math.BigDecimal;
  51. import java.text.SimpleDateFormat;
  52. import java.util.*;
  53. import java.util.concurrent.atomic.AtomicInteger;
  54. import java.util.regex.Pattern;
  55. import java.util.stream.Collectors;
  56. @Service
  57. @Slf4j
  58. @AllArgsConstructor
  59. public class UserService {
  60. private UserRepo userRepo;
  61. private WxMaService wxMaService;
  62. private WxMpService wxMpService;
  63. private SmsService smsService;
  64. private StorageService storageService;
  65. private JwtTokenUtil jwtTokenUtil;
  66. private FollowService followService;
  67. private FollowRepo followRepo;
  68. private IdentityAuthRepo identityAuthRepo;
  69. private SysConfigService sysConfigService;
  70. private UserBankCardRepo userBankCardRepo;
  71. private InviteRepo inviteRepo;
  72. private NFTService nftService;
  73. private CacheService cacheService;
  74. private TokenHistoryRepo tokenHistoryRepo;
  75. private CollectionRepo collectionRepo;
  76. private AdapayMerchantService adapayMerchantService;
  77. private Environment env;
  78. private RocketMQTemplate rocketMQTemplate;
  79. private GeneralProperties generalProperties;
  80. private RedisTemplate<String, Object> redisTemplate;
  81. private PasswordEncoder passwordEncoder;
  82. public User update(User user) {
  83. if (!SecurityUtils.hasRole(AuthorityName.ROLE_ADMIN)) {
  84. if (!SecurityUtils.getAuthenticatedUser().getId().equals(user.getId())) {
  85. throw new BusinessException("无权限");
  86. }
  87. }
  88. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  89. ObjUtils.merge(orig, user);
  90. orig = save(orig);
  91. userRepo.updateAssetMinter(orig.getId());
  92. userRepo.updateAssetOwner(orig.getId());
  93. userRepo.updateCollectionMinter(orig.getId());
  94. userRepo.updateCollectionOwner(orig.getId());
  95. userRepo.updateOrderMinter(orig.getId());
  96. userRepo.updateHistoryFromUser(orig.getId());
  97. userRepo.updateHistoryToUser(orig.getId());
  98. userRepo.updateShowroomToUser(orig.getId());
  99. cacheService.clearCollection();
  100. cacheService.clearUserMy(user.getId());
  101. return orig;
  102. }
  103. public User save(User user) {
  104. cacheService.clearUserInfo(user.getId());
  105. cacheService.clearUser(user.getUsername());
  106. return userRepo.save(user);
  107. }
  108. @Cacheable(value = "userList", key = "#pageQuery.hashCode()")
  109. public PageWrapper<User> all(PageQuery pageQuery) {
  110. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  111. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  112. List<Predicate> and = new ArrayList<>();
  113. and.add(criteriaBuilder.equal(root.get("del"), false));
  114. if (!pageQuery.getQuery().containsKey("admin")) {
  115. and.add(criteriaBuilder.equal(root.get("admin"), false));
  116. }
  117. if (pageQuery.getQuery().containsKey("hasRole")) {
  118. String roleName = (String) pageQuery.getQuery().get("hasRole");
  119. if (roleName.equals("ROLE_MINTER")) {
  120. and.add(criteriaBuilder.equal(root.get("minter"), true));
  121. } else {
  122. and.add(criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  123. }
  124. }
  125. if (pageQuery.getQuery().containsKey("vip")) {
  126. boolean vip = (boolean) pageQuery.getQuery().get("vip");
  127. if (vip) {
  128. and.add(criteriaBuilder.greaterThan(root.get("vipPurchase"), 0));
  129. } else {
  130. and.add(criteriaBuilder.lessThanOrEqualTo(root.get("vipPurchase"), 0));
  131. }
  132. }
  133. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  134. });
  135. Page<User> page = userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  136. return PageWrapper.of(page);
  137. }
  138. public User create(UserRegister userRegister) {
  139. User user = new User();
  140. BeanUtils.copyProperties(userRegister, user);
  141. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  142. user.setAuthStatus(AuthStatus.NOT_AUTH);
  143. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  144. user.setPassword(passwordEncoder.encode(userRegister.getPassword()));
  145. }
  146. return userRepo.save(user);
  147. }
  148. @EventListener
  149. public void accountCreated(AccountCreatedEvent event) {
  150. userRepo.findById(event.getUserId()).ifPresent(user -> {
  151. user.setNftAccount(event.getAccount().getAccountId());
  152. user.setKmsId(event.getAccount().getAccountKmsId());
  153. user.setPublicKey(event.getAccount().getPublicKey());
  154. userRepo.save(user);
  155. });
  156. }
  157. public User phoneRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
  158. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  159. Invite invite = null;
  160. if (StringUtils.isNotBlank(inviteCode)) {
  161. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  162. }
  163. smsService.verify(phone, code);
  164. Collection collection;
  165. if (collectionId != null) {
  166. collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("无藏品"));
  167. // if (!collection.isOnShelf() || !collection.isSalable()) {
  168. // collectionId = null;
  169. // } else if (collection.isScheduleSale()) {
  170. // if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  171. // collectionId = null;
  172. // }
  173. // }
  174. // 只看是否开去分享
  175. if (ObjectUtils.isEmpty(collection.getOpenQuota()) || !collection.getOpenQuota()) {
  176. collectionId = null;
  177. }
  178. }
  179. User user = create(UserRegister.builder()
  180. .username(name)
  181. .nickname(name)
  182. .password(password)
  183. .avatar(Constants.DEFAULT_AVATAR)
  184. .phone(phone)
  185. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  186. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  187. .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
  188. .collectionInvitor(invitor)
  189. .collectionId(collectionId)
  190. .build());
  191. if (invite != null) {
  192. inviteRepo.increaseNum(invite.getId());
  193. }
  194. // 加积分
  195. // if (collectionId != null && invitor != null) {
  196. // // 额度或者额度为空, 库存不为空
  197. // if (collection.getStock() > 0 && (collection.getVipQuota() > 0 || ObjectUtils.isEmpty(collection.getVipQuota()))) {
  198. // int countUser = userRepo.countAllByCollectionIdAndCollectionInvitor(collectionId, invitor);
  199. // // 邀请人数
  200. // if (countUser >= collection.getAssignment()) {
  201. // int point = pointRecordRepo.countByUserIdAndCollectionId(invitor, collectionId);
  202. // // 是否已有积分
  203. // if (point <= 0) {
  204. // long count = userRepo.countAllByCollectionIdAndCollectionInvitor(collectionId, invitor);
  205. // if (count >= collection.getAssignment()) {
  206. // // 扣除藏品额度
  207. // if (ObjectUtils.isNotEmpty(collection.getVipQuota())) {
  208. // collectionService.decreaseQuota(collectionId, 1);
  209. // }
  210. // userRepo.updateVipPoint(invitor, 1);
  211. // pointRecordRepo.save(PointRecord.builder()
  212. // .collectionId(collectionId)
  213. // .userId(invitor)
  214. // .type("VIP_POINT")
  215. // .point(1)
  216. // .build());
  217. //
  218. // }
  219. // }
  220. // }
  221. // }
  222. // }
  223. return user;
  224. }
  225. public String mqRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
  226. rocketMQTemplate.convertAndSend(generalProperties.getRegisterTopic(),
  227. new RegisterEvent(phone, code, password, inviteCode, invitor, collectionId));
  228. return phone;
  229. }
  230. public Object getRegisterResult(String phone) {
  231. return redisTemplate.opsForValue().get("register::" + phone);
  232. }
  233. public User testPhoneRegister(String phone) {
  234. return create(UserRegister.builder()
  235. .avatar(Constants.DEFAULT_AVATAR)
  236. .username(RandomStringUtils.randomAlphabetic(32))
  237. .nickname(RandomStringUtils.randomAlphabetic(32))
  238. .phone(RandomStringUtils.randomNumeric(16))
  239. .password("123456")
  240. .build());
  241. }
  242. public void del(Long id) {
  243. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  244. user.setDel(true);
  245. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  246. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  247. }
  248. if (StringUtils.isNoneEmpty(user.getPhone())) {
  249. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  250. }
  251. userRepo.save(user);
  252. //删除实名认证
  253. identityAuthRepo.softDeleteByUserId(id);
  254. }
  255. public User loginByPhone(String phone, String code) {
  256. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  257. smsService.verify(phone, code);
  258. if (user == null) {
  259. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  260. user = create(UserRegister.builder()
  261. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  262. .username(name)
  263. .nickname(name)
  264. .avatar(Constants.DEFAULT_AVATAR)
  265. .phone(phone)
  266. .build());
  267. }
  268. return user;
  269. }
  270. public User loginByPhonePwd(String phone, String password) {
  271. if (StringUtils.isEmpty(phone)) {
  272. throw new BusinessException("手机号错误");
  273. }
  274. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  275. if (StringUtils.isEmpty(user.getPassword())) {
  276. throw new BusinessException("账号或密码错误");
  277. }
  278. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  279. !passwordEncoder.matches(password, user.getPassword())) {
  280. throw new BusinessException("账号或密码错误");
  281. }
  282. return user;
  283. }
  284. public User loginByUsernamePwd(String username, String password) {
  285. if (StringUtils.isEmpty(username)) {
  286. throw new BusinessException("用户名错误");
  287. }
  288. User user = userRepo.findByUsernameAndDelFalse(username).orElseThrow(new BusinessException("账号或密码错误"));
  289. if (StringUtils.isEmpty(user.getPassword())
  290. || !passwordEncoder.matches(password, user.getPassword())) {
  291. throw new BusinessException("账号或密码错误");
  292. }
  293. return user;
  294. }
  295. public User loginMp(String code) throws WxErrorException {
  296. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  297. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  298. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  299. if (user == null) {
  300. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  301. user = User.builder()
  302. .username(name)
  303. .nickname(name)
  304. .avatar(wxMpUser.getHeadImgUrl())
  305. .sex(wxMpUser.getSexDesc())
  306. .country(wxMpUser.getCountry())
  307. .province(wxMpUser.getProvince())
  308. .city(wxMpUser.getCity())
  309. .openId(wxMpUser.getOpenId())
  310. .language(wxMpUser.getLanguage())
  311. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  312. .authStatus(AuthStatus.NOT_AUTH)
  313. .build();
  314. userRepo.save(user);
  315. }
  316. return user;
  317. }
  318. public String code2openId(String code) throws WxErrorException {
  319. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  320. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  321. }
  322. public User loginMa(String code) {
  323. try {
  324. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  325. String openId = result.getOpenid();
  326. String sessionKey = result.getSessionKey();
  327. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  328. ;
  329. if (userInfo != null) {
  330. return userInfo;
  331. }
  332. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  333. userInfo = User.builder()
  334. .username(name)
  335. .nickname(name)
  336. .openId(openId)
  337. .avatar(Constants.DEFAULT_AVATAR)
  338. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  339. .authStatus(AuthStatus.NOT_AUTH)
  340. .build();
  341. userInfo = userRepo.save(userInfo);
  342. return userInfo;
  343. } catch (WxErrorException e) {
  344. e.printStackTrace();
  345. }
  346. throw new BusinessException("登录失败");
  347. }
  348. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  349. String encryptedData, String iv) {
  350. // 用户信息校验
  351. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  352. throw new BusinessException("获取用户信息失败");
  353. }
  354. // 解密用户信息
  355. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  356. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  357. String avatarUrl = Constants.DEFAULT_AVATAR;
  358. try {
  359. String path = "image/avatar/" +
  360. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  361. RandomStringUtils.randomAlphabetic(8) +
  362. ".jpg";
  363. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  364. } catch (Exception e) {
  365. log.error("获取头像失败", e);
  366. }
  367. if (user == null) {
  368. user = User.builder()
  369. .username(UUID.randomUUID().toString())
  370. .nickname(wxUserInfo.getNickName())
  371. .openId(wxUserInfo.getOpenId())
  372. .avatar(avatarUrl)
  373. .sex(wxUserInfo.getGender())
  374. .country(wxUserInfo.getCountry())
  375. .province(wxUserInfo.getProvince())
  376. .city(wxUserInfo.getCity())
  377. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  378. .build();
  379. user = userRepo.save(user);
  380. } else {
  381. user.setAvatar(avatarUrl);
  382. user.setNickname(wxUserInfo.getNickName());
  383. user.setSex(wxUserInfo.getGender());
  384. user.setCountry(wxUserInfo.getCountry());
  385. user.setProvince(wxUserInfo.getProvince());
  386. user.setCity(wxUserInfo.getCity());
  387. user = userRepo.save(user);
  388. }
  389. return user;
  390. }
  391. public String setPassword(Long userId, String password) {
  392. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  393. user.setPassword(passwordEncoder.encode(password));
  394. user = userRepo.save(user);
  395. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  396. }
  397. public String setPassword(Long userId, String code, String password) {
  398. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  399. smsService.verify(user.getPhone(), code);
  400. return setPassword(userId, password);
  401. }
  402. public String forgotPassword(String phone, String password, String code) {
  403. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  404. smsService.verify(user.getPhone(), code);
  405. return setPassword(user.getId(), password);
  406. }
  407. public void bindPhone(Long userId, String phone) {
  408. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  409. if (StringUtils.isNoneEmpty(user.getPhone())) {
  410. throw new BusinessException("该账号已绑定手机");
  411. }
  412. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  413. if (!user1.getId().equals(userId)) {
  414. throw new BusinessException("该手机号已绑定其他账号");
  415. }
  416. });
  417. user.setPhone(phone);
  418. userRepo.save(user);
  419. }
  420. public UserDTO toDTO(User user) {
  421. return toDTO(user, true);
  422. }
  423. public UserDTO toDTO(User user, boolean join) {
  424. UserDTO userDTO = new UserDTO();
  425. BeanUtils.copyProperties(user, userDTO);
  426. if (user.getAuthorities() != null) {
  427. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  428. }
  429. if (join) {
  430. if (SecurityUtils.getAuthenticatedUser() != null) {
  431. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  432. }
  433. }
  434. return userDTO;
  435. }
  436. public List<UserDTO> toDTO(List<User> users) {
  437. List<Follow> follows = new ArrayList<>();
  438. if (SecurityUtils.getAuthenticatedUser() != null) {
  439. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  440. }
  441. return users.stream().parallel().map(user -> {
  442. UserDTO dto = toDTO(user, false);
  443. if (!follows.isEmpty()) {
  444. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  445. }
  446. return dto;
  447. }).collect(Collectors.toList());
  448. }
  449. public Page<UserDTO> toDTO(Page<User> users) {
  450. List<UserDTO> userDTOS = toDTO(users.getContent());
  451. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  452. }
  453. @CacheEvict(value = "user", allEntries = true)
  454. public void setTradeCode(Long userId, String token, String tradeCode) {
  455. String phone = smsService.verifyToken(token);
  456. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  457. if (!StringUtils.equals(phone, user.getPhone())) {
  458. throw new BusinessException("验证码无效");
  459. }
  460. user.setTradeCode(passwordEncoder.encode(tradeCode));
  461. userRepo.save(user);
  462. }
  463. public void verifyTradeCode(Long userId, String tradeCode) {
  464. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  465. if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
  466. throw new BusinessException("校验失败");
  467. }
  468. }
  469. public Map<String, Object> searchByPhone(String phone) {
  470. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  471. throw new BusinessException("实名认证后才能赠送");
  472. }
  473. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  474. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  475. throw new BusinessException("用户不存在或未认证");
  476. }
  477. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  478. user.getId(), AuthStatus.SUCCESS)
  479. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  480. Map<String, Object> map = new HashMap<>();
  481. map.put("id", user.getId());
  482. map.put("avatar", user.getAvatar());
  483. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  484. map.put("realName", realName);
  485. return map;
  486. }
  487. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  488. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  489. .replaceAll("\r\n", " ")
  490. .split(" "))
  491. .map(String::trim)
  492. .filter(s -> !StringUtils.isEmpty(s))
  493. .collect(Collectors.toList());
  494. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  495. Map<String, Object> map = new HashMap<>();
  496. map.put("users", users);
  497. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  498. .collect(Collectors.toList());
  499. map.put("notFound", notFound);
  500. return map;
  501. }
  502. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  503. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  504. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  505. .orElseThrow(new BusinessException("用户未认证"));
  506. if (identityAuth.isOrg()) {
  507. //throw new BusinessException("企业认证用户请绑定对公账户");
  508. }
  509. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  510. throw new BusinessException("此账号已绑定");
  511. }
  512. BankValidate bankValidate = BankUtils.validate(bankNo);
  513. if (!bankValidate.isValidated()) {
  514. throw new BusinessException("暂不支持此卡");
  515. }
  516. smsService.verify(phone, code);
  517. adapayMerchantService.createMemberForAll(userId.toString(), user.getPhone(), identityAuth.getRealName(), identityAuth.getIdNo());
  518. user.setMemberId(user.getId().toString());
  519. userRepo.save(user);
  520. String accountId = adapayMerchantService.createSettleAccountForAll
  521. (user.getMemberId(), identityAuth.getRealName(),
  522. identityAuth.getIdNo(), phone, bankNo);
  523. user.setSettleAccountId(Optional.ofNullable(accountId).orElse("1"));
  524. userRepo.save(user);
  525. userBankCardRepo.save(UserBankCard.builder()
  526. .bank(bankValidate.getBank())
  527. .bankName(bankValidate.getBankName())
  528. .bankNo(bankNo)
  529. .cardType(bankValidate.getCardType())
  530. .cardTypeDesc(bankValidate.getCardTypeDesc())
  531. .userId(userId)
  532. .phone(phone)
  533. .realName(identityAuth.getRealName())
  534. .idNo(identityAuth.getIdNo())
  535. .build());
  536. }
  537. public void removeBankCard(Long userId) throws BaseAdaPayException {
  538. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  539. if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  540. adapayMerchantService.delSettleAccountForAll(user.getMemberId());
  541. user.setSettleAccountId(null);
  542. userRepo.save(user);
  543. userBankCardRepo.deleteByUserId(userId);
  544. } else {
  545. throw new BusinessException("未绑定");
  546. }
  547. }
  548. public void removeAuth(Long userId) {
  549. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  550. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  551. user.setAuthStatus(AuthStatus.NOT_AUTH);
  552. userRepo.save(user);
  553. identityAuthRepo.deleteAll(identityAuthRepo.findByUserIdAndDelFalse(userId));
  554. }
  555. }
  556. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  557. List<String> exist = new ArrayList<>();
  558. List<String> err = new ArrayList<>();
  559. List<String> success = new ArrayList<>();
  560. Arrays.stream(phones.replaceAll(",", " ")
  561. .replaceAll(",", " ")
  562. .replaceAll("\n", " ")
  563. .replaceAll("\r\n", " ")
  564. .split(" ")).forEach(phone -> {
  565. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  566. exist.add(phone);
  567. } else {
  568. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  569. err.add(phone);
  570. } else {
  571. try {
  572. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  573. User user = create(UserRegister.builder()
  574. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  575. .username(name)
  576. .nickname(name)
  577. .password(defaultPassword)
  578. .avatar(Constants.DEFAULT_AVATAR)
  579. .phone(phone)
  580. .build());
  581. success.add(phone);
  582. } catch (Exception e) {
  583. log.error("注册失败", e);
  584. err.add(phone);
  585. }
  586. }
  587. }
  588. });
  589. Map<String, Object> map = new HashMap<>();
  590. map.put("exist", exist);
  591. map.put("error", err);
  592. map.put("success", success);
  593. return map;
  594. }
  595. public Map<String, Object> invite(PageQuery pageQuery) {
  596. Page<User> all = this.all(pageQuery).toPage();
  597. List<Long> userIds = all.map(User::getId).getContent();
  598. List<TokenHistory> page = tokenHistoryRepo.userBuy(userIds);
  599. Map<Long, BigDecimal> buy = page.stream()
  600. .collect(Collectors.groupingBy(TokenHistory::getToUserId,
  601. Collectors.mapping(TokenHistory::getPrice,
  602. Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
  603. Page<InvitePhoneDTO> users = all.map(user -> {
  604. InvitePhoneDTO dto = new InvitePhoneDTO(user);
  605. dto.setTotal(buy.get(user.getId()) == null ? BigDecimal.ZERO : buy.get(user.getId()));
  606. return dto;
  607. });
  608. BigDecimal total = buy.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
  609. Map<String, Object> map = new HashMap<>();
  610. map.put("user", users);
  611. map.put("total", total);
  612. return map;
  613. }
  614. @Async
  615. public void checkSettleAccountAsync() {
  616. checkSettleAccount();
  617. }
  618. public void checkSettleAccount() {
  619. List<User> list = userRepo.findBySettleAccountIdIsNotNull();
  620. AtomicInteger count = new AtomicInteger();
  621. list.forEach(user -> {
  622. try {
  623. Thread.sleep(500);
  624. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
  625. .orElseThrow(new BusinessException("用户未认证"));
  626. UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
  627. .orElseThrow(new BusinessException("未绑卡"));
  628. adapayMerchantService.createMemberForAll(
  629. user.getId().toString(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  630. identityAuth.getRealName(), identityAuth.getIdNo());
  631. adapayMerchantService.createSettleAccountForAll(
  632. user.getId().toString(), identityAuth.getRealName(),
  633. identityAuth.getIdNo(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  634. userBankCard.getBankNo());
  635. userBankCard.setPhone(Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()));
  636. userBankCardRepo.save(userBankCard);
  637. } catch (Exception e) {
  638. user.setSettleAccountId(null);
  639. userRepo.save(user);
  640. userBankCardRepo.deleteByUserId(user.getId());
  641. }
  642. count.getAndIncrement();
  643. log.info("checkSettleAccount {}/{}", count.get(), list.size());
  644. });
  645. }
  646. @Cacheable(value = "myUserInfo", key = "#id")
  647. public User my(Long id) {
  648. return userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  649. }
  650. }