UserService.java 30 KB

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