AssetService.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. package com.izouma.nineth.service;
  2. import com.izouma.nineth.TokenHistory;
  3. import com.izouma.nineth.config.GeneralProperties;
  4. import com.izouma.nineth.domain.Collection;
  5. import com.izouma.nineth.domain.*;
  6. import com.izouma.nineth.dto.PageQuery;
  7. import com.izouma.nineth.dto.UserHistory;
  8. import com.izouma.nineth.enums.AssetStatus;
  9. import com.izouma.nineth.enums.CollectionSource;
  10. import com.izouma.nineth.enums.CollectionType;
  11. import com.izouma.nineth.enums.OrderStatus;
  12. import com.izouma.nineth.event.TransferAssetEvent;
  13. import com.izouma.nineth.exception.BusinessException;
  14. import com.izouma.nineth.lock.RedisLockable;
  15. import com.izouma.nineth.repo.*;
  16. import com.izouma.nineth.utils.JpaUtils;
  17. import com.izouma.nineth.utils.SecurityUtils;
  18. import com.izouma.nineth.utils.TokenUtils;
  19. import lombok.AllArgsConstructor;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.apache.commons.lang3.StringUtils;
  22. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  23. import org.springframework.beans.BeanUtils;
  24. import org.springframework.context.ApplicationContext;
  25. import org.springframework.data.domain.Page;
  26. import org.springframework.data.domain.Pageable;
  27. import org.springframework.scheduling.annotation.Async;
  28. import org.springframework.stereotype.Service;
  29. import java.math.BigDecimal;
  30. import java.time.LocalDateTime;
  31. import java.time.temporal.ChronoUnit;
  32. import java.util.*;
  33. import java.util.stream.Collectors;
  34. @Service
  35. @AllArgsConstructor
  36. @Slf4j
  37. public class AssetService {
  38. private AssetRepo assetRepo;
  39. private UserRepo userRepo;
  40. private CollectionRepo collectionRepo;
  41. private ApplicationContext applicationContext;
  42. private OrderRepo orderRepo;
  43. private TokenHistoryRepo tokenHistoryRepo;
  44. private SysConfigService sysConfigService;
  45. private RocketMQTemplate rocketMQTemplate;
  46. private GeneralProperties generalProperties;
  47. public Page<Asset> all(PageQuery pageQuery) {
  48. return assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class), JpaUtils.toPageRequest(pageQuery));
  49. }
  50. public Asset createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type, Integer number) {
  51. Asset asset = Asset.create(collection, user);
  52. asset.setTokenId(TokenUtils.genTokenId());
  53. asset.setNumber(number);
  54. asset.setOrderId(orderId);
  55. asset.setPrice(price);
  56. assetRepo.saveAndFlush(asset);
  57. tokenHistoryRepo.save(TokenHistory.builder()
  58. .tokenId(asset.getTokenId())
  59. .fromUser(collection.getMinter())
  60. .fromUserId(collection.getMinterId())
  61. .fromAvatar(collection.getMinterAvatar())
  62. .toUser(user.getNickname())
  63. .toUserId(user.getId())
  64. .toAvatar(user.getAvatar())
  65. .operation(type)
  66. .price(price)
  67. .projectId(asset.getProjectId())
  68. .build());
  69. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  70. return asset;
  71. }
  72. public Asset createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type, Integer number) {
  73. Asset asset = Asset.create(winItem, user);
  74. asset.setTokenId(TokenUtils.genTokenId());
  75. asset.setNumber(number);
  76. asset.setOrderId(orderId);
  77. asset.setPrice(price);
  78. assetRepo.saveAndFlush(asset);
  79. tokenHistoryRepo.save(TokenHistory.builder()
  80. .tokenId(asset.getTokenId())
  81. .fromUser(winItem.getMinter())
  82. .fromUserId(winItem.getMinterId())
  83. .fromAvatar(winItem.getMinterAvatar())
  84. .toUser(user.getNickname())
  85. .toUserId(user.getId())
  86. .toAvatar(user.getAvatar())
  87. .operation(type)
  88. .price(price)
  89. .projectId(asset.getProjectId())
  90. .build());
  91. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  92. return asset;
  93. }
  94. public void publicShow(Long id) {
  95. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  96. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  97. throw new BusinessException("此藏品不属于你");
  98. }
  99. if (asset.isPublicShow()) {
  100. return;
  101. }
  102. if (asset.getStatus() != AssetStatus.NORMAL) {
  103. throw new BusinessException("当前状态不可展示");
  104. }
  105. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  106. Collection collection = Collection.builder()
  107. .name(asset.getName())
  108. .pic(asset.getPic())
  109. .minter(asset.getMinter())
  110. .minterId(asset.getMinterId())
  111. .minterAvatar(asset.getMinterAvatar())
  112. .owner(owner.getNickname())
  113. .ownerId(owner.getId())
  114. .ownerAvatar(owner.getAvatar())
  115. .detail(asset.getDetail())
  116. .type(CollectionType.DEFAULT)
  117. .source(CollectionSource.TRANSFER)
  118. .sale(0)
  119. .stock(1)
  120. .total(1)
  121. .onShelf(true)
  122. .salable(false)
  123. .price(BigDecimal.valueOf(0))
  124. .properties(asset.getProperties())
  125. .canResale(asset.isCanResale())
  126. .royalties(asset.getRoyalties())
  127. .serviceCharge(asset.getServiceCharge())
  128. .assetId(id)
  129. .number(asset.getNumber())
  130. .projectId(asset.getProjectId())
  131. .build();
  132. collectionRepo.save(collection);
  133. asset.setPublicShow(true);
  134. asset.setPublicCollectionId(collection.getId());
  135. assetRepo.save(asset);
  136. }
  137. public void consignment(Long id, BigDecimal price) {
  138. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  139. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  140. throw new BusinessException("此藏品不属于你");
  141. }
  142. int holdDays = sysConfigService.getInt("hold_days");
  143. if (ChronoUnit.DAYS.between(asset.getCreatedAt(), LocalDateTime.now()) < holdDays) {
  144. throw new BusinessException("需持有满" + holdDays + "天才能寄售上架");
  145. }
  146. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  147. if (StringUtils.isBlank(owner.getSettleAccountId())) {
  148. throw new BusinessException("请先绑定银行卡");
  149. }
  150. if (asset.isConsignment()) {
  151. throw new BusinessException("已寄售,请勿重新操作");
  152. }
  153. if (asset.getStatus() != AssetStatus.NORMAL) {
  154. throw new BusinessException("当前状态不可寄售");
  155. }
  156. if (asset.isPublicShow()) {
  157. cancelPublic(asset);
  158. }
  159. Collection collection = Collection.builder()
  160. .name(asset.getName())
  161. .pic(asset.getPic())
  162. .minter(asset.getMinter())
  163. .minterId(asset.getMinterId())
  164. .minterAvatar(asset.getMinterAvatar())
  165. .owner(owner.getNickname())
  166. .ownerId(owner.getId())
  167. .ownerAvatar(owner.getAvatar())
  168. .detail(asset.getDetail())
  169. .type(CollectionType.DEFAULT)
  170. .source(CollectionSource.TRANSFER)
  171. .sale(0)
  172. .stock(1)
  173. .total(1)
  174. .onShelf(true)
  175. .salable(true)
  176. .price(price)
  177. .properties(asset.getProperties())
  178. .canResale(asset.isCanResale())
  179. .royalties(asset.getRoyalties())
  180. .serviceCharge(asset.getServiceCharge())
  181. .assetId(id)
  182. .number(asset.getNumber())
  183. .projectId(asset.getProjectId())
  184. .build();
  185. collectionRepo.save(collection);
  186. asset.setPublicShow(true);
  187. asset.setConsignment(true);
  188. asset.setPublicCollectionId(collection.getId());
  189. asset.setSellPrice(price);
  190. assetRepo.save(asset);
  191. }
  192. public void cancelConsignment(Long id) {
  193. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  194. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  195. throw new BusinessException("此藏品不属于你");
  196. }
  197. cancelConsignment(asset);
  198. }
  199. public void cancelConsignment(Asset asset) {
  200. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  201. throw new BusinessException("此藏品不属于你");
  202. }
  203. if (asset.getPublicCollectionId() != null) {
  204. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  205. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  206. throw new BusinessException("已有订单不可取消");
  207. }
  208. collectionRepo.findById(asset.getPublicCollectionId())
  209. .ifPresent(collection -> {
  210. collection.setSalable(false);
  211. collectionRepo.save(collection);
  212. });
  213. }
  214. asset.setConsignment(false);
  215. assetRepo.save(asset);
  216. }
  217. public void cancelPublic(Long id) {
  218. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  219. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  220. throw new BusinessException("此藏品不属于你");
  221. }
  222. cancelPublic(asset);
  223. }
  224. public void cancelPublic(Asset asset) {
  225. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  226. throw new BusinessException("此藏品不属于你");
  227. }
  228. if (!asset.isPublicShow()) {
  229. return;
  230. }
  231. if (asset.isConsignment()) {
  232. cancelConsignment(asset);
  233. }
  234. Collection collection = collectionRepo.findById(asset.getPublicCollectionId())
  235. .orElseThrow(new BusinessException("无展示记录"));
  236. collectionRepo.delete(collection);
  237. asset.setPublicShow(false);
  238. asset.setPublicCollectionId(null);
  239. assetRepo.save(asset);
  240. }
  241. public void usePrivilege(Long assetId, Long privilegeId) {
  242. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("无记录"));
  243. asset.getPrivileges().stream().filter(p -> p.getId().equals(privilegeId)).forEach(p -> {
  244. p.setOpened(true);
  245. p.setOpenTime(LocalDateTime.now());
  246. p.setOpenedBy(SecurityUtils.getAuthenticatedUser().getId());
  247. });
  248. assetRepo.save(asset);
  249. }
  250. @Async
  251. public void transfer(Asset asset, BigDecimal price, User toUser, String reason, Long orderId) {
  252. log.info("转让藏品 fromAssetId={} toUser={}", asset.getId(), toUser.getId());
  253. Asset newAsset = new Asset();
  254. BeanUtils.copyProperties(asset, newAsset);
  255. newAsset.setId(null);
  256. newAsset.setUserId(toUser.getId());
  257. newAsset.setOwner(toUser.getNickname());
  258. newAsset.setOwnerId(toUser.getId());
  259. newAsset.setOwnerAvatar(toUser.getAvatar());
  260. newAsset.setPublicShow(false);
  261. newAsset.setConsignment(false);
  262. newAsset.setPublicCollectionId(null);
  263. newAsset.setStatus(AssetStatus.NORMAL);
  264. newAsset.setPrice(price);
  265. newAsset.setSellPrice(null);
  266. newAsset.setOrderId(orderId);
  267. newAsset.setFromAssetId(asset.getId());
  268. assetRepo.save(newAsset);
  269. tokenHistoryRepo.save(TokenHistory.builder()
  270. .tokenId(asset.getTokenId())
  271. .fromUser(asset.getOwner())
  272. .fromUserId(asset.getOwnerId())
  273. .fromAvatar(asset.getOwnerAvatar())
  274. .toUser(toUser.getNickname())
  275. .toUserId(toUser.getId())
  276. .toAvatar(toUser.getAvatar())
  277. .operation(reason)
  278. .price("转赠".equals(reason) ? null : price)
  279. .projectId(asset.getProjectId())
  280. .build());
  281. asset.setPublicShow(false);
  282. asset.setConsignment(false);
  283. asset.setPublicCollectionId(null);
  284. asset.setStatus("转赠".equals(reason) ? AssetStatus.GIFTED : AssetStatus.TRANSFERRED);
  285. asset.setOwner(toUser.getNickname());
  286. asset.setOwnerId(toUser.getId());
  287. asset.setOwnerAvatar(toUser.getAvatar());
  288. asset.setOutTime(LocalDateTime.now());
  289. assetRepo.save(asset);
  290. if (orderId != null) {
  291. applicationContext.publishEvent(new TransferAssetEvent(this, true, newAsset));
  292. }
  293. }
  294. public List<TokenHistory> tokenHistory(String tokenId, Long assetId) {
  295. if (tokenId == null) {
  296. if (assetId == null) return new ArrayList<>();
  297. tokenId = assetRepo.findById(assetId).map(Asset::getTokenId).orElse(null);
  298. }
  299. if (tokenId == null) return new ArrayList<>();
  300. return tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(tokenId);
  301. }
  302. @RedisLockable(key = "#id", expiration = 60, isWaiting = true)
  303. public void testLock(String id, String i) throws InterruptedException {
  304. Thread.sleep(1000);
  305. log.info("" + i);
  306. }
  307. public void setHistory() {
  308. List<Asset> assets = assetRepo.findByCreatedAtBefore(LocalDateTime.of(2021, 11, 22, 23, 59, 59));
  309. assets.parallelStream().forEach(asset -> {
  310. try {
  311. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException(""));
  312. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException(""));
  313. TokenHistory t = TokenHistory.builder()
  314. .tokenId(asset.getTokenId())
  315. .fromUser(asset.getMinter())
  316. .fromUserId(asset.getMinterId())
  317. .fromAvatar(asset.getMinterAvatar())
  318. .toUser(owner.getNickname())
  319. .toUserId(owner.getId())
  320. .toAvatar(owner.getAvatar())
  321. .operation("出售")
  322. .price(order.getPrice())
  323. .projectId(asset.getProjectId())
  324. .build();
  325. t.setCreatedAt(asset.getCreatedAt());
  326. tokenHistoryRepo.save(t);
  327. } catch (Exception e) {
  328. }
  329. });
  330. }
  331. public Page<UserHistory> userHistory(Long userId, int projectId, Pageable pageable) {
  332. Page<TokenHistory> page = tokenHistoryRepo.userHistoryAndProjectId(userId, projectId, pageable);
  333. Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
  334. List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
  335. return page.map(tokenHistory -> {
  336. UserHistory userHistory = new UserHistory();
  337. BeanUtils.copyProperties(tokenHistory, userHistory);
  338. Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
  339. .findAny();
  340. userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
  341. userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
  342. switch (tokenHistory.getOperation()) {
  343. case "出售":
  344. case "转让":
  345. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
  346. break;
  347. case "空投":
  348. userHistory.setDescription("空投");
  349. break;
  350. case "转赠":
  351. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
  352. break;
  353. }
  354. return userHistory;
  355. });
  356. }
  357. public Map<User, Integer> holdQuery(List<String> names, LocalDateTime startTime, LocalDateTime endTime) {
  358. Map<User, Integer> result = new HashMap<>();
  359. userRepo.findAll().stream().parallel().forEach(user -> {
  360. List<Asset> assets = assetRepo.findByUserId(user.getId());
  361. assets = assets.stream().filter(a -> names.stream().anyMatch(n -> n.equals(a.getName())))
  362. .collect(Collectors.toList());
  363. if (assets.size() < names.size()) {
  364. return;
  365. }
  366. assets = assets.stream().filter(a -> a.getCreatedAt().isBefore(startTime))
  367. .collect(Collectors.toList());
  368. if (assets.size() < names.size()) {
  369. return;
  370. }
  371. assets = assets.stream().filter(a -> {
  372. if (a.getStatus() != AssetStatus.GIFTED && a.getStatus() != AssetStatus.TRANSFERRED) {
  373. return true;
  374. } else {
  375. Asset a1 = assetRepo.findFirstByTokenIdAndCreatedAtAfterOrderByCreatedAt(a.getTokenId(), a.getCreatedAt());
  376. return a1 != null && a.getCreatedAt().isAfter(endTime);
  377. }
  378. })
  379. .collect(Collectors.toList());
  380. boolean flag = true;
  381. Map<String, Integer> map = new HashMap<>();
  382. for (String name : names) {
  383. int c = (int) assets.stream().filter(a -> name.equals(a.getName())).count();
  384. map.put(name, c);
  385. flag = flag && (c > 0);
  386. }
  387. if (flag) {
  388. result.put(user, map.values().stream().mapToInt(i -> i).min().orElse(0));
  389. }
  390. });
  391. return result;
  392. }
  393. public Map<User, Integer> holdQuery1(List<Long> names, LocalDateTime startTime, LocalDateTime endTime) {
  394. Map<User, Integer> result = new HashMap<>();
  395. userRepo.findAll().stream().parallel().forEach(user -> {
  396. List<Asset> assets = assetRepo.findByUserId(user.getId());
  397. assets = assets.stream().filter(a -> names.stream().anyMatch(n -> n.equals(a.getCollectionId())))
  398. .collect(Collectors.toList());
  399. if (assets.size() < names.size()) {
  400. return;
  401. }
  402. assets = assets.stream().filter(a -> a.getCreatedAt().isBefore(startTime))
  403. .collect(Collectors.toList());
  404. if (assets.size() < names.size()) {
  405. return;
  406. }
  407. assets = assets.stream().filter(a -> {
  408. if (a.getStatus() != AssetStatus.GIFTED && a.getStatus() != AssetStatus.TRANSFERRED) {
  409. return true;
  410. } else {
  411. Asset a1 = assetRepo.findFirstByTokenIdAndCreatedAtAfterOrderByCreatedAt(a.getTokenId(), a.getCreatedAt());
  412. return a1 != null && a.getCreatedAt().isAfter(endTime);
  413. }
  414. })
  415. .collect(Collectors.toList());
  416. boolean flag = true;
  417. Map<Long, Integer> map = new HashMap<>();
  418. for (Long name : names) {
  419. int c = (int) assets.stream().filter(a -> name.equals(a.getCollectionId())).count();
  420. map.put(name, c);
  421. flag = flag && (c > 0);
  422. }
  423. if (flag) {
  424. result.put(user, map.values().stream().mapToInt(i -> i).min().orElse(0));
  425. }
  426. });
  427. return result;
  428. }
  429. }