UserService.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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.domain.Follow;
  9. import com.izouma.nineth.domain.IdentityAuth;
  10. import com.izouma.nineth.domain.Invite;
  11. import com.izouma.nineth.domain.User;
  12. import com.izouma.nineth.dto.*;
  13. import com.izouma.nineth.enums.AuthStatus;
  14. import com.izouma.nineth.enums.AuthorityName;
  15. import com.izouma.nineth.event.AccountCreatedEvent;
  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.springframework.beans.BeanUtils;
  37. import org.springframework.cache.annotation.CacheEvict;
  38. import org.springframework.context.ApplicationContext;
  39. import org.springframework.context.event.EventListener;
  40. import org.springframework.data.domain.Page;
  41. import org.springframework.data.domain.PageImpl;
  42. import org.springframework.data.jpa.domain.Specification;
  43. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  44. import org.springframework.stereotype.Service;
  45. import javax.persistence.criteria.Predicate;
  46. import java.math.BigDecimal;
  47. import java.text.SimpleDateFormat;
  48. import java.util.*;
  49. import java.util.regex.Pattern;
  50. import java.util.stream.Collectors;
  51. @Service
  52. @Slf4j
  53. @AllArgsConstructor
  54. public class UserService {
  55. private UserRepo userRepo;
  56. private WxMaService wxMaService;
  57. private WxMpService wxMpService;
  58. private SmsService smsService;
  59. private StorageService storageService;
  60. private JwtTokenUtil jwtTokenUtil;
  61. private CaptchaService captchaService;
  62. private FollowService followService;
  63. private FollowRepo followRepo;
  64. private IdentityAuthRepo identityAuthRepo;
  65. private SysConfigService sysConfigService;
  66. private CollectionService collectionService;
  67. private AdapayService adapayService;
  68. private UserBankCardRepo userBankCardRepo;
  69. private InviteRepo inviteRepo;
  70. private NFTService nftService;
  71. private CacheService cacheService;
  72. private ApplicationContext context;
  73. private TokenHistoryRepo tokenHistoryRepo;
  74. public User update(User user) {
  75. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  76. ObjUtils.merge(orig, user);
  77. orig = save(orig);
  78. userRepo.updateAssetMinter(orig.getId());
  79. userRepo.updateAssetOwner(orig.getId());
  80. userRepo.updateCollectionMinter(orig.getId());
  81. userRepo.updateCollectionOwner(orig.getId());
  82. userRepo.updateOrderMinter(orig.getId());
  83. userRepo.updateHistoryFromUser(orig.getId());
  84. userRepo.updateHistoryToUser(orig.getId());
  85. cacheService.clearCollection();
  86. return orig;
  87. }
  88. public User save(User user) {
  89. cacheService.clearUserInfo(user.getId());
  90. cacheService.clearUser(user.getUsername());
  91. return userRepo.save(user);
  92. }
  93. public Page<User> all(PageQuery pageQuery) {
  94. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  95. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  96. List<Predicate> and = new ArrayList<>();
  97. and.add(criteriaBuilder.equal(root.get("del"), false));
  98. if (!pageQuery.getQuery().containsKey("admin")) {
  99. and.add(criteriaBuilder.equal(root.get("admin"), false));
  100. }
  101. if (pageQuery.getQuery().containsKey("hasRole")) {
  102. String roleName = (String) pageQuery.getQuery().get("hasRole");
  103. and.add(criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  104. }
  105. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  106. });
  107. return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  108. }
  109. public User create(UserRegister userRegister) {
  110. if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhoneAndDelFalse(userRegister.getPhone())
  111. .orElse(null) != null) {
  112. throw new BusinessException("该手机号已注册");
  113. }
  114. User user = new User();
  115. BeanUtils.copyProperties(userRegister, user);
  116. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  117. user.setAuthStatus(AuthStatus.NOT_AUTH);
  118. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  119. user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
  120. }
  121. user = userRepo.saveAndFlush(user);
  122. nftService.createAccount(user.getId());
  123. return user;
  124. }
  125. @EventListener
  126. public void accountCreated(AccountCreatedEvent event) {
  127. userRepo.findById(event.getUserId()).ifPresent(user -> {
  128. user.setNftAccount(event.getAccount().getAccountId());
  129. user.setKmsId(event.getAccount().getAccountKmsId());
  130. user.setPublicKey(event.getAccount().getPublicKey());
  131. userRepo.save(user);
  132. });
  133. }
  134. public User phoneRegister(String phone, String code, String password, String inviteCode) {
  135. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  136. Invite invite = null;
  137. if (StringUtils.isNotBlank(inviteCode)) {
  138. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  139. }
  140. smsService.verify(phone, code);
  141. User user = create(UserRegister.builder()
  142. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  143. .username(name)
  144. .nickname(name)
  145. .password(password)
  146. .avatar(Constants.DEFAULT_AVATAR)
  147. .phone(phone)
  148. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  149. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  150. .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
  151. .build());
  152. if (invite != null) {
  153. inviteRepo.increaseNum(invite.getId());
  154. }
  155. return user;
  156. }
  157. public void del(Long id) {
  158. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  159. user.setDel(true);
  160. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  161. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  162. }
  163. if (StringUtils.isNoneEmpty(user.getPhone())) {
  164. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  165. }
  166. userRepo.save(user);
  167. //删除实名认证
  168. identityAuthRepo.softDeleteByUserId(id);
  169. }
  170. public User loginByPhone(String phone, String code) {
  171. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("该手机未注册"));
  172. smsService.verify(phone, code);
  173. if (user == null) {
  174. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  175. user = create(UserRegister.builder()
  176. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  177. .username(name)
  178. .nickname(name)
  179. .avatar(Constants.DEFAULT_AVATAR)
  180. .phone(phone)
  181. .build());
  182. }
  183. return user;
  184. }
  185. public User loginByPhonePwd(String phone, String password) {
  186. if (StringUtils.isEmpty(phone)) {
  187. throw new BusinessException("手机号错误");
  188. }
  189. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  190. if (StringUtils.isEmpty(user.getPassword())) {
  191. throw new BusinessException("账号或密码错误");
  192. }
  193. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  194. !new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  195. throw new BusinessException("账号或密码错误");
  196. }
  197. return user;
  198. }
  199. public User loginMp(String code) throws WxErrorException {
  200. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  201. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  202. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  203. if (user == null) {
  204. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  205. user = User.builder()
  206. .username(name)
  207. .nickname(name)
  208. .avatar(wxMpUser.getHeadImgUrl())
  209. .sex(wxMpUser.getSexDesc())
  210. .country(wxMpUser.getCountry())
  211. .province(wxMpUser.getProvince())
  212. .city(wxMpUser.getCity())
  213. .openId(wxMpUser.getOpenId())
  214. .language(wxMpUser.getLanguage())
  215. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  216. .authStatus(AuthStatus.NOT_AUTH)
  217. .build();
  218. userRepo.save(user);
  219. }
  220. return user;
  221. }
  222. public String code2openId(String code) throws WxErrorException {
  223. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  224. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  225. }
  226. public User loginMa(String code) {
  227. try {
  228. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  229. String openId = result.getOpenid();
  230. String sessionKey = result.getSessionKey();
  231. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  232. ;
  233. if (userInfo != null) {
  234. return userInfo;
  235. }
  236. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  237. userInfo = User.builder()
  238. .username(name)
  239. .nickname(name)
  240. .openId(openId)
  241. .avatar(Constants.DEFAULT_AVATAR)
  242. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  243. .authStatus(AuthStatus.NOT_AUTH)
  244. .build();
  245. userInfo = userRepo.save(userInfo);
  246. return userInfo;
  247. } catch (WxErrorException e) {
  248. e.printStackTrace();
  249. }
  250. throw new BusinessException("登录失败");
  251. }
  252. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  253. String encryptedData, String iv) {
  254. // 用户信息校验
  255. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  256. throw new BusinessException("获取用户信息失败");
  257. }
  258. // 解密用户信息
  259. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  260. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  261. String avatarUrl = Constants.DEFAULT_AVATAR;
  262. try {
  263. String path = "image/avatar/" +
  264. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  265. RandomStringUtils.randomAlphabetic(8) +
  266. ".jpg";
  267. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  268. } catch (Exception e) {
  269. log.error("获取头像失败", e);
  270. }
  271. if (user == null) {
  272. user = User.builder()
  273. .username(UUID.randomUUID().toString())
  274. .nickname(wxUserInfo.getNickName())
  275. .openId(wxUserInfo.getOpenId())
  276. .avatar(avatarUrl)
  277. .sex(wxUserInfo.getGender())
  278. .country(wxUserInfo.getCountry())
  279. .province(wxUserInfo.getProvince())
  280. .city(wxUserInfo.getCity())
  281. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  282. .build();
  283. user = userRepo.save(user);
  284. } else {
  285. user.setAvatar(avatarUrl);
  286. user.setNickname(wxUserInfo.getNickName());
  287. user.setSex(wxUserInfo.getGender());
  288. user.setCountry(wxUserInfo.getCountry());
  289. user.setProvince(wxUserInfo.getProvince());
  290. user.setCity(wxUserInfo.getCity());
  291. user = userRepo.save(user);
  292. }
  293. return user;
  294. }
  295. public String setPassword(Long userId, String password) {
  296. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  297. user.setPassword(new BCryptPasswordEncoder().encode(password));
  298. user = userRepo.save(user);
  299. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  300. }
  301. public String setPassword(Long userId, String code, String password) {
  302. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  303. smsService.verify(user.getPhone(), code);
  304. return setPassword(userId, password);
  305. }
  306. public String forgotPassword(String phone, String password, String code) {
  307. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  308. smsService.verify(user.getPhone(), code);
  309. return setPassword(user.getId(), password);
  310. }
  311. public void bindPhone(Long userId, String phone) {
  312. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  313. if (StringUtils.isNoneEmpty(user.getPhone())) {
  314. throw new BusinessException("该账号已绑定手机");
  315. }
  316. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  317. if (!user1.getId().equals(userId)) {
  318. throw new BusinessException("该手机号已绑定其他账号");
  319. }
  320. });
  321. user.setPhone(phone);
  322. userRepo.save(user);
  323. }
  324. public UserDTO toDTO(User user) {
  325. return toDTO(user, true);
  326. }
  327. public UserDTO toDTO(User user, boolean join) {
  328. UserDTO userDTO = new UserDTO();
  329. BeanUtils.copyProperties(user, userDTO);
  330. if (user.getAuthorities() != null) {
  331. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  332. }
  333. if (join) {
  334. if (SecurityUtils.getAuthenticatedUser() != null) {
  335. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  336. }
  337. }
  338. return userDTO;
  339. }
  340. public List<UserDTO> toDTO(List<User> users) {
  341. List<Follow> follows = new ArrayList<>();
  342. if (SecurityUtils.getAuthenticatedUser() != null) {
  343. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  344. }
  345. return users.stream().parallel().map(user -> {
  346. UserDTO dto = toDTO(user, false);
  347. if (!follows.isEmpty()) {
  348. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  349. }
  350. return dto;
  351. }).collect(Collectors.toList());
  352. }
  353. public Page<UserDTO> toDTO(Page<User> users) {
  354. List<UserDTO> userDTOS = toDTO(users.getContent());
  355. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  356. }
  357. @CacheEvict(value = "user", allEntries = true)
  358. public void setTradeCode(Long userId, String token, String tradeCode) {
  359. String phone = smsService.verifyToken(token);
  360. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  361. if (!StringUtils.equals(phone, user.getPhone())) {
  362. throw new BusinessException("验证码无效");
  363. }
  364. user.setTradeCode(new BCryptPasswordEncoder().encode(tradeCode));
  365. userRepo.save(user);
  366. }
  367. public void verifyTradeCode(Long userId, String tradeCode) {
  368. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  369. if (!new BCryptPasswordEncoder().matches(tradeCode, user.getTradeCode())) {
  370. throw new BusinessException("校验失败");
  371. }
  372. }
  373. public Map<String, Object> searchByPhone(String phone) {
  374. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  375. throw new BusinessException("实名认证后才能赠送");
  376. }
  377. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  378. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  379. throw new BusinessException("用户不存在或未认证");
  380. }
  381. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  382. user.getId(), AuthStatus.SUCCESS)
  383. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  384. Map<String, Object> map = new HashMap<>();
  385. map.put("id", user.getId());
  386. map.put("avatar", user.getAvatar());
  387. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  388. map.put("realName", realName);
  389. return map;
  390. }
  391. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  392. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  393. .replaceAll("\r\n", " ")
  394. .split(" "))
  395. .map(String::trim)
  396. .filter(s -> !StringUtils.isEmpty(s))
  397. .collect(Collectors.toList());
  398. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  399. Map<String, Object> map = new HashMap<>();
  400. map.put("users", users);
  401. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  402. .collect(Collectors.toList());
  403. map.put("notFound", notFound);
  404. return map;
  405. }
  406. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  407. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  408. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  409. .orElseThrow(new BusinessException("用户未认证"));
  410. if (identityAuth.isOrg()) {
  411. //throw new BusinessException("企业认证用户请绑定对公账户");
  412. }
  413. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  414. throw new BusinessException("此账号已绑定");
  415. }
  416. BankValidate bankValidate = BankUtils.validate(bankNo);
  417. if (!bankValidate.isValidated()) {
  418. throw new BusinessException("暂不支持此卡");
  419. }
  420. if (StringUtils.isEmpty(user.getMemberId())) {
  421. user.setMemberId(adapayService.createMember(userId, user.getPhone(), identityAuth.getRealName(),
  422. identityAuth.getIdNo()));
  423. userRepo.saveAndFlush(user);
  424. }
  425. smsService.verify(phone, code);
  426. String accountId = adapayService.createSettleAccount(user.getMemberId(), identityAuth.getRealName(),
  427. identityAuth.getIdNo(), phone, bankNo);
  428. user.setSettleAccountId(accountId);
  429. userRepo.save(user);
  430. userBankCardRepo.save(UserBankCard.builder()
  431. .bank(bankValidate.getBank())
  432. .bankName(bankValidate.getBankName())
  433. .bankNo(bankNo)
  434. .cardType(bankValidate.getCardType())
  435. .cardTypeDesc(bankValidate.getCardTypeDesc())
  436. .userId(userId)
  437. .build());
  438. }
  439. public void removeBankCard(Long userId) throws BaseAdaPayException {
  440. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  441. if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  442. adapayService.delSettleAccount(user.getMemberId(), user.getSettleAccountId());
  443. user.setSettleAccountId(null);
  444. userRepo.save(user);
  445. userBankCardRepo.deleteByUserId(userId);
  446. } else {
  447. throw new BusinessException("未绑定");
  448. }
  449. }
  450. public void removeAuth(Long userId) {
  451. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  452. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  453. user.setAuthStatus(AuthStatus.NOT_AUTH);
  454. userRepo.save(user);
  455. identityAuthRepo.deleteAll(identityAuthRepo.findByUserIdAndDelFalse(userId));
  456. }
  457. }
  458. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  459. List<String> exist = new ArrayList<>();
  460. List<String> err = new ArrayList<>();
  461. List<String> success = new ArrayList<>();
  462. Arrays.stream(phones.replaceAll(",", " ")
  463. .replaceAll(",", " ")
  464. .replaceAll("\n", " ")
  465. .replaceAll("\r\n", " ")
  466. .split(" ")).forEach(phone -> {
  467. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  468. exist.add(phone);
  469. } else {
  470. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  471. err.add(phone);
  472. } else {
  473. try {
  474. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  475. User user = create(UserRegister.builder()
  476. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  477. .username(name)
  478. .nickname(name)
  479. .password(defaultPassword)
  480. .avatar(Constants.DEFAULT_AVATAR)
  481. .phone(phone)
  482. .build());
  483. success.add(phone);
  484. } catch (Exception e) {
  485. log.error("注册失败", e);
  486. err.add(phone);
  487. }
  488. }
  489. }
  490. });
  491. Map<String, Object> map = new HashMap<>();
  492. map.put("exist", exist);
  493. map.put("error", err);
  494. map.put("success", success);
  495. return map;
  496. }
  497. public Map<String, Object> invite(PageQuery pageQuery) {
  498. Page<User> all = this.all(pageQuery);
  499. List<Long> userIds = all.map(User::getId).getContent();
  500. List<TokenHistory> page = tokenHistoryRepo.userBuy(userIds);
  501. Map<Long, BigDecimal> buy = page.stream()
  502. .collect(Collectors.groupingBy(TokenHistory::getToUserId,
  503. Collectors.mapping(TokenHistory::getPrice,
  504. Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
  505. Page<InvitePhoneDTO> users = all.map(user -> {
  506. InvitePhoneDTO dto = new InvitePhoneDTO(user);
  507. dto.setTotal(buy.get(user.getId()) == null ? BigDecimal.ZERO : buy.get(user.getId()));
  508. return dto;
  509. });
  510. BigDecimal total = buy.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
  511. Map<String, Object> map = new HashMap<>();
  512. map.put("user", users);
  513. map.put("total", total);
  514. return map;
  515. }
  516. }