UserService.java 31 KB

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