UserService.java 29 KB

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