UserService.java 25 KB

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