UserService.java 33 KB

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