UserService.java 29 KB

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