UserService.java 35 KB

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