UserService.java 34 KB

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