UserService.java 35 KB

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