AssetService.java 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. package com.izouma.nineth.service;
  2. import com.google.common.collect.Lists;
  3. import com.izouma.nineth.TokenHistory;
  4. import com.izouma.nineth.config.Constants;
  5. import com.izouma.nineth.config.GeneralProperties;
  6. import com.izouma.nineth.converter.LongArrayConverter;
  7. import com.izouma.nineth.domain.Collection;
  8. import com.izouma.nineth.domain.*;
  9. import com.izouma.nineth.dto.*;
  10. import com.izouma.nineth.enums.*;
  11. import com.izouma.nineth.exception.BusinessException;
  12. import com.izouma.nineth.repo.*;
  13. import com.izouma.nineth.utils.JpaUtils;
  14. import com.izouma.nineth.utils.SecurityUtils;
  15. import com.izouma.nineth.utils.TokenUtils;
  16. import lombok.AllArgsConstructor;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.apache.commons.collections.CollectionUtils;
  19. import org.apache.commons.lang3.ObjectUtils;
  20. import org.apache.commons.lang3.RandomStringUtils;
  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.cache.annotation.Cacheable;
  25. import org.springframework.data.domain.Page;
  26. import org.springframework.data.domain.PageImpl;
  27. import org.springframework.data.domain.Pageable;
  28. import org.springframework.data.jpa.domain.Specification;
  29. import org.springframework.scheduling.annotation.Async;
  30. import org.springframework.scheduling.annotation.Scheduled;
  31. import org.springframework.security.crypto.password.PasswordEncoder;
  32. import org.springframework.stereotype.Service;
  33. import javax.persistence.criteria.Predicate;
  34. import java.math.BigDecimal;
  35. import java.time.LocalDateTime;
  36. import java.time.temporal.ChronoUnit;
  37. import java.util.*;
  38. import java.util.concurrent.ExecutionException;
  39. import java.util.concurrent.ForkJoinPool;
  40. import java.util.concurrent.atomic.AtomicInteger;
  41. import java.util.stream.Collectors;
  42. @Service
  43. @AllArgsConstructor
  44. @Slf4j
  45. public class AssetService {
  46. private AssetRepo assetRepo;
  47. private UserRepo userRepo;
  48. private CollectionRepo collectionRepo;
  49. private OrderRepo orderRepo;
  50. private TokenHistoryRepo tokenHistoryRepo;
  51. private SysConfigService sysConfigService;
  52. private RocketMQTemplate rocketMQTemplate;
  53. private GeneralProperties generalProperties;
  54. private ShowroomRepo showroomRepo;
  55. private ShowCollectionRepo showCollectionRepo;
  56. private CollectionPrivilegeRepo collectionPrivilegeRepo;
  57. private PasswordEncoder passwordEncoder;
  58. private MintActivityRepo mintActivityRepo;
  59. private DestroyRecordRepo destroyRecordRepo;
  60. private AirDropService airDropService;
  61. private HCChainService hcChainService;
  62. private RockRecordService rockRecordService;
  63. private RockRecordRepo rockRecordRepo;
  64. public Page<Asset> all(PageQuery pageQuery) {
  65. Page<Asset> all = assetRepo
  66. .findAll(JpaUtils.toSpecification(pageQuery, Asset.class), JpaUtils.toPageRequest(pageQuery));
  67. // Map<String, Object> query = pageQuery.getQuery();
  68. // if (query.containsKey("userId")) {
  69. // List<Long> orderId = orderRepo
  70. // .findAllByUserIdAndOpenedFalse(Convert.convert(Long.class, query.get("userId")));
  71. // return all.map(asset -> {
  72. // if (orderId.contains(asset.getOrderId())) {
  73. // asset.setOpened(false);
  74. // }
  75. // return asset;
  76. // });
  77. // }
  78. return all;
  79. }
  80. public List<AssetDTO> superimposition(PageQuery pageQuery) {
  81. List<AssetDTO> assetDTOs = new ArrayList<>();
  82. // 根据条件查询所有资产
  83. List<Asset> assets = assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class));
  84. if (CollectionUtils.isEmpty(assets)) {
  85. return assetDTOs;
  86. }
  87. // 取出资产中未开启盲盒数据
  88. List<Asset> blindBoxClosedAssets = assets.stream()
  89. .filter(asset -> !asset.isOpened() && CollectionType.BLIND_BOX.equals(asset.getType()))
  90. .collect(Collectors.toList());
  91. if (CollectionUtils.isNotEmpty(blindBoxClosedAssets)) {
  92. blindBoxClosedAssets.forEach(asset -> {
  93. assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
  94. });
  95. // 移除资产中未开启盲盒数据
  96. assets.removeAll(blindBoxClosedAssets);
  97. }
  98. // 取出资产中所有未设置prefixName的值
  99. List<Asset> prefixNameIsNullAssets = assets.stream()
  100. .filter(asset -> StringUtils.isBlank(asset.getPrefixName()))
  101. .collect(Collectors.toList());
  102. if (CollectionUtils.isNotEmpty(prefixNameIsNullAssets)) {
  103. prefixNameIsNullAssets.forEach(asset -> {
  104. assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
  105. });
  106. assets.removeAll(prefixNameIsNullAssets);
  107. }
  108. if (CollectionUtils.isNotEmpty(assets)) {
  109. // 取出资产中所有prefixName
  110. List<String> prefixNames = assets.stream()
  111. .map(Asset::getPrefixName)
  112. .distinct()
  113. .collect(Collectors.toList());
  114. // 将资产中相同prefixName归类(除未开启盲盒和未设置prefixName)
  115. prefixNames.forEach(str -> {
  116. List<Asset> collect = assets.stream()
  117. .filter(asset -> str.equals(asset.getPrefixName()))
  118. .collect(Collectors.toList());
  119. assetDTOs.add(AssetDTO.create(collect));
  120. });
  121. }
  122. return assetDTOs;
  123. }
  124. public Asset createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type,
  125. Integer number, boolean safeFlag) {
  126. Asset asset = Asset.create(collection, user);
  127. asset.setTokenId(TokenUtils.genTokenId());
  128. asset.setNumber(number);
  129. asset.setOasisId(collection.getOasisId());
  130. asset.setOrderId(orderId);
  131. asset.setPrice(price);
  132. asset.setTags(new HashSet<>());
  133. if (collection.getTags() != null) {
  134. asset.getTags().addAll(collection.getTags());
  135. }
  136. User fakeUser = null;
  137. if (safeFlag) {
  138. fakeUser = createFakeUser();
  139. asset.setOwner(fakeUser.getNickname());
  140. asset.setOwnerId(fakeUser.getId());
  141. asset.setOwnerAvatar(fakeUser.getAvatar());
  142. }
  143. assetRepo.saveAndFlush(asset);
  144. tokenHistoryRepo.save(TokenHistory.builder()
  145. .tokenId(asset.getTokenId())
  146. .fromUser(collection.getMinter())
  147. .fromUserId(collection.getMinterId())
  148. .fromAvatar(collection.getMinterAvatar())
  149. .toUser((safeFlag ? fakeUser : user).getNickname())
  150. .toUserId((safeFlag ? fakeUser : user).getId())
  151. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  152. .operation(type)
  153. .price(price)
  154. .build());
  155. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  156. if (asset.getOasisId() != null & asset.getSource().equals(AssetSource.OFFICIAL)) {
  157. AirDrop airDrop = new AirDrop();
  158. airDrop.setName("建筑空投展厅");
  159. airDrop.setCollectionId(207012L);
  160. List<Long> userIds = new ArrayList<>();
  161. userIds.add(user.getId());
  162. List<Long> nums = new ArrayList<>();
  163. nums.add(1L);
  164. airDrop.setType(AirDropType.asset);
  165. List<DropTarget> dropTargets = new ArrayList<>();
  166. DropTarget dropTarget = new DropTarget();
  167. dropTarget.setNickname(user.getNickname());
  168. dropTarget.setNum(1);
  169. dropTarget.setPhone(user.getPhone());
  170. dropTarget.setUserId(user.getId());
  171. dropTargets.add(dropTarget);
  172. airDrop.setTargets(dropTargets);
  173. airDrop.setUserIds(userIds);
  174. airDrop.setNum(nums);
  175. airDropService.create(airDrop);
  176. }
  177. return asset;
  178. }
  179. public Asset createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type,
  180. Integer number, Integer holdDays, boolean safeFlag) {
  181. Collection blindBox = collectionRepo.findDetailById(winItem.getBlindBoxId())
  182. .orElseThrow(new BusinessException("盲盒不存在"));
  183. Collection collection = collectionRepo.findDetailById(winItem.getCollectionId())
  184. .orElseThrow(new BusinessException("藏品不存在"));
  185. Asset asset = Asset.create(winItem, user, holdDays);
  186. asset.setTokenId(TokenUtils.genTokenId());
  187. asset.setNumber(number);
  188. asset.setOasisId(winItem.getOasisId());
  189. asset.setOrderId(orderId);
  190. asset.setPrice(price);
  191. asset.setPrefixName(collection.getPrefixName());
  192. asset.setTags(new HashSet<>());
  193. if (blindBox.getTags() != null) {
  194. asset.getTags().addAll(blindBox.getTags());
  195. }
  196. if (collection.getTags() != null) {
  197. asset.getTags().addAll(collection.getTags());
  198. }
  199. User fakeUser = null;
  200. if (safeFlag) {
  201. fakeUser = createFakeUser();
  202. asset.setOwner(fakeUser.getNickname());
  203. asset.setOwnerId(fakeUser.getId());
  204. asset.setOwnerAvatar(fakeUser.getAvatar());
  205. }
  206. assetRepo.saveAndFlush(asset);
  207. tokenHistoryRepo.save(TokenHistory.builder()
  208. .tokenId(asset.getTokenId())
  209. .fromUser(winItem.getMinter())
  210. .fromUserId(winItem.getMinterId())
  211. .fromAvatar(winItem.getMinterAvatar())
  212. .toUser((safeFlag ? fakeUser : user).getNickname())
  213. .toUserId((safeFlag ? fakeUser : user).getId())
  214. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  215. .operation(type)
  216. .price(price)
  217. .build());
  218. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  219. return asset;
  220. }
  221. public void publicShow(Long id) {
  222. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  223. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  224. throw new BusinessException("此藏品不属于你");
  225. }
  226. if (asset.isPublicShow()) {
  227. return;
  228. }
  229. if (asset.getStatus() != AssetStatus.NORMAL) {
  230. throw new BusinessException("当前状态不可展示");
  231. }
  232. User owner = asset.isSafeFlag() ?
  233. userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
  234. : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  235. Collection collection = Collection.builder()
  236. .name(asset.getName())
  237. .pic(asset.getPic())
  238. .minter(asset.getMinter())
  239. .minterId(asset.getMinterId())
  240. .minterAvatar(asset.getMinterAvatar())
  241. .owner(owner.getNickname())
  242. .oasisId(asset.getOasisId())
  243. .ownerId(owner.getId())
  244. .ownerAvatar(owner.getAvatar())
  245. .detail(asset.getDetail())
  246. .type(CollectionType.DEFAULT)
  247. .source(CollectionSource.TRANSFER)
  248. .sale(0)
  249. .stock(1)
  250. .total(1)
  251. .onShelf(true)
  252. .salable(false)
  253. .price(BigDecimal.valueOf(0))
  254. .properties(asset.getProperties())
  255. .canResale(asset.isCanResale())
  256. .royalties(asset.getRoyalties())
  257. .serviceCharge(asset.getServiceCharge())
  258. .assetId(id)
  259. .number(asset.getNumber())
  260. .tags(new HashSet<>())
  261. .build();
  262. if (asset.getTags() != null) {
  263. collection.getTags().addAll(asset.getTags());
  264. }
  265. collectionRepo.save(collection);
  266. asset.setPublicShow(true);
  267. asset.setPublicCollectionId(collection.getId());
  268. assetRepo.save(asset);
  269. }
  270. public synchronized void consignment(Long id, BigDecimal price, String tradeCode, boolean safeFlag) {
  271. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  272. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  273. throw new BusinessException("此藏品不属于你");
  274. }
  275. int holdDays;
  276. if (asset.getSource() == AssetSource.GIFT) {
  277. holdDays = sysConfigService.getInt("gift_days");
  278. } else {
  279. if (ObjectUtils.isEmpty(asset.getHoldDays())) {
  280. holdDays = sysConfigService.getInt("hold_days");
  281. } else {
  282. holdDays = asset.getHoldDays();
  283. }
  284. }
  285. if (holdDays == 0 && AssetSource.OFFICIAL.equals(asset.getSource())) {
  286. BigDecimal officialConsignment = sysConfigService.getBigDecimal("OFFICIAL_CONSIGNMENT");
  287. //天转小时
  288. int hour = officialConsignment.multiply(new BigDecimal("24")).intValue();
  289. if (ChronoUnit.HOURS.between(asset.getCreatedAt(), LocalDateTime.now()) < hour) {
  290. throw new BusinessException("需持有满" + hour + "小时后才能寄售上架");
  291. }
  292. }
  293. if (ChronoUnit.DAYS.between(asset.getCreatedAt(), LocalDateTime.now()) < holdDays) {
  294. throw new BusinessException("需持有满" + holdDays + "天才能寄售上架");
  295. }
  296. User owner;
  297. if (safeFlag && !asset.isSafeFlag()) {
  298. owner = createFakeUser();
  299. asset.setOwner(owner.getNickname());
  300. asset.setOwnerId(owner.getId());
  301. asset.setOwnerAvatar(owner.getAvatar());
  302. asset.setSafeFlag(true);
  303. tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(asset.getTokenId()).stream()
  304. .filter(t -> t.getToUserId().equals(asset.getUserId())).findFirst()
  305. .ifPresent(tokenHistory -> {
  306. tokenHistory.setToUserId(owner.getId());
  307. tokenHistory.setToUser(owner.getNickname());
  308. tokenHistory.setToAvatar(owner.getAvatar());
  309. tokenHistoryRepo.save(tokenHistory);
  310. });
  311. } else {
  312. owner = asset.isSafeFlag() ?
  313. userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
  314. : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  315. }
  316. if (!passwordEncoder.matches(tradeCode, userRepo.findTradeCode(asset.getUserId()))) {
  317. throw new BusinessException("交易密码错误");
  318. }
  319. // if (StringUtils.isBlank(owner.getSettleAccountId())) {
  320. // throw new BusinessException("请先绑定银行卡");
  321. // }
  322. if (asset.isConsignment()) {
  323. throw new BusinessException("已寄售,请勿重新操作");
  324. }
  325. if (asset.getStatus() != AssetStatus.NORMAL) {
  326. throw new BusinessException("当前状态不可寄售");
  327. }
  328. if (asset.isPublicShow()) {
  329. cancelPublic(asset);
  330. }
  331. //寄售中的展厅需要先删除展厅
  332. if (CollectionType.SHOWROOM.equals(asset.getType())) {
  333. if (showroomRepo.findByAssetId(id).isPresent()) {
  334. throw new BusinessException("请先删除展厅");
  335. }
  336. }
  337. Collection collection = Collection.builder()
  338. .name(asset.getName())
  339. .pic(asset.getPic())
  340. .minter(asset.getMinter())
  341. .minterId(asset.getMinterId())
  342. .minterAvatar(asset.getMinterAvatar())
  343. .owner(owner.getNickname())
  344. .ownerId(owner.getId())
  345. .oasisId(asset.getOasisId())
  346. .ownerAvatar(owner.getAvatar())
  347. .detail(asset.getDetail())
  348. .type(CollectionType.DEFAULT)
  349. .source(CollectionSource.TRANSFER)
  350. .sale(0)
  351. .stock(1)
  352. .total(1)
  353. .onShelf(true)
  354. .salable(true)
  355. .price(price)
  356. .properties(asset.getProperties())
  357. .canResale(asset.isCanResale())
  358. .royalties(asset.getRoyalties())
  359. .serviceCharge(asset.getServiceCharge())
  360. .assetId(id)
  361. .number(asset.getNumber())
  362. .tags(new HashSet<>())
  363. .build();
  364. if (asset.getTags() != null) {
  365. collection.getTags().addAll(asset.getTags());
  366. }
  367. collectionRepo.save(collection);
  368. asset.setPublicShow(true);
  369. asset.setConsignment(true);
  370. asset.setPublicCollectionId(collection.getId());
  371. asset.setSellPrice(price);
  372. assetRepo.save(asset);
  373. }
  374. public void cancelConsignment(Long id) {
  375. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  376. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  377. throw new BusinessException("此藏品不属于你");
  378. }
  379. cancelConsignment(asset);
  380. }
  381. public void cancelConsignment(Asset asset) {
  382. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  383. throw new BusinessException("此藏品不属于你");
  384. }
  385. if (asset.getPublicCollectionId() != null) {
  386. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  387. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  388. throw new BusinessException("已有订单不可取消");
  389. }
  390. collectionRepo.findById(asset.getPublicCollectionId())
  391. .ifPresent(collection -> {
  392. collection.setSalable(false);
  393. collectionRepo.save(collection);
  394. });
  395. }
  396. asset.setConsignment(false);
  397. assetRepo.save(asset);
  398. }
  399. public void cancelPublic(Long id) {
  400. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  401. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  402. throw new BusinessException("此藏品不属于你");
  403. }
  404. cancelPublic(asset);
  405. }
  406. public void cancelPublic(Asset asset) {
  407. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  408. throw new BusinessException("此藏品不属于你");
  409. }
  410. if (!asset.isPublicShow()) {
  411. return;
  412. }
  413. if (asset.isConsignment()) {
  414. cancelConsignment(asset);
  415. }
  416. Collection collection = collectionRepo.findById(asset.getPublicCollectionId())
  417. .orElseThrow(new BusinessException("无展示记录"));
  418. collectionRepo.delete(collection);
  419. // 如果展厅有此藏品
  420. showCollectionRepo.deleteAllByCollectionId(asset.getPublicCollectionId());
  421. asset.setPublicShow(false);
  422. asset.setPublicCollectionId(null);
  423. assetRepo.save(asset);
  424. }
  425. public void usePrivilege(Long assetId, Long privilegeId) {
  426. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("无记录"));
  427. asset.getPrivileges().stream().filter(p -> p.getId().equals(privilegeId)).forEach(p -> {
  428. if (!p.getName().equals("铸造")) {
  429. p.setOpened(true);
  430. p.setOpenTime(LocalDateTime.now());
  431. p.setOpenedBy(SecurityUtils.getAuthenticatedUser().getId());
  432. }
  433. });
  434. assetRepo.save(asset);
  435. }
  436. public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId) {
  437. transfer(asset, price, toUser, reason, orderId, false);
  438. }
  439. private User createFakeUser() {
  440. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  441. return userRepo.save(User.builder()
  442. .username(name)
  443. .nickname(name)
  444. .avatar(Constants.DEFAULT_AVATAR)
  445. .isPublicShow(true)
  446. .build());
  447. }
  448. public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId, boolean safeFlag) {
  449. Objects.requireNonNull(asset, "原藏品不能为空");
  450. Objects.requireNonNull(toUser, "转让人不能为空");
  451. Objects.requireNonNull(reason, "转让原因不能为空");
  452. User newOwner = toUser;
  453. if (safeFlag) {
  454. newOwner = createFakeUser();
  455. }
  456. Asset newAsset = new Asset();
  457. BeanUtils.copyProperties(asset, newAsset);
  458. newAsset.setId(null);
  459. newAsset.setUserId(toUser.getId());
  460. newAsset.setOwner(newOwner.getNickname());
  461. newAsset.setOwnerId(newOwner.getId());
  462. newAsset.setOwnerAvatar(newOwner.getAvatar());
  463. newAsset.setPublicShow(false);
  464. newAsset.setConsignment(false);
  465. newAsset.setPublicCollectionId(null);
  466. newAsset.setStatus(AssetStatus.NORMAL);
  467. newAsset.setPrice(price);
  468. newAsset.setSellPrice(null);
  469. newAsset.setOrderId(orderId);
  470. newAsset.setOasisId(asset.getOasisId());
  471. newAsset.setFromAssetId(asset.getId());
  472. newAsset.setType(CollectionType.DEFAULT);
  473. newAsset.setSource(TransferReason.GIFT == reason ? AssetSource.GIFT : AssetSource.TRANSFER);
  474. newAsset.setTags(new HashSet<>(asset.getTags()));
  475. newAsset.setSafeFlag(safeFlag);
  476. newAsset.setHoldDays(asset.getOldHoldDays());
  477. assetRepo.save(newAsset);
  478. TokenHistory tokenHistory = TokenHistory.builder()
  479. .tokenId(asset.getTokenId())
  480. .fromUser(asset.getOwner())
  481. .fromUserId(asset.getOwnerId())
  482. .fromAvatar(asset.getOwnerAvatar())
  483. .toUser(newOwner.getNickname())
  484. .toUserId(newOwner.getId())
  485. .toAvatar(newOwner.getAvatar())
  486. .operation(reason.getDescription())
  487. .price(TransferReason.GIFT == reason ? null : price)
  488. .build();
  489. tokenHistoryRepo.save(tokenHistory);
  490. //购买者加绿洲石
  491. if (TransferReason.TRANSFER.equals(reason) || TransferReason.AUCTION.equals(reason)) {
  492. rockRecordService.addRock(newOwner.getId(), price, "购买");
  493. }
  494. asset.setPublicShow(false);
  495. asset.setConsignment(false);
  496. asset.setPublicCollectionId(null);
  497. switch (reason) {
  498. case GIFT:
  499. asset.setStatus(AssetStatus.GIFTED);
  500. break;
  501. case AUCTION:
  502. asset.setStatus(AssetStatus.AUCTIONED);
  503. break;
  504. case TRANSFER:
  505. asset.setStatus(AssetStatus.TRANSFERRED);
  506. }
  507. asset.setOwner(newOwner.getNickname());
  508. asset.setOwnerId(newOwner.getId());
  509. asset.setOwnerAvatar(newOwner.getAvatar());
  510. assetRepo.save(asset);
  511. //vip权限转让
  512. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(asset.getCollectionId());
  513. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  514. if (collectionPrivilege.isVip()) {
  515. //更新vip信息
  516. userRepo.updateVipPurchase(toUser.getId(), 1);
  517. userRepo.updateVipPurchase(asset.getUserId(), 0);
  518. }
  519. }
  520. }
  521. public List<TokenHistory> tokenHistory(String tokenId, Long assetId) {
  522. if (tokenId == null) {
  523. if (assetId == null) return new ArrayList<>();
  524. tokenId = assetRepo.findById(assetId).map(Asset::getTokenId).orElse(null);
  525. }
  526. if (tokenId == null) return new ArrayList<>();
  527. return tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(tokenId);
  528. }
  529. public void setHistory() {
  530. List<Asset> assets = assetRepo.findByCreatedAtBefore(LocalDateTime.of(2021, 11, 22, 23, 59, 59));
  531. assets.parallelStream().forEach(asset -> {
  532. try {
  533. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException(""));
  534. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException(""));
  535. TokenHistory t = TokenHistory.builder()
  536. .tokenId(asset.getTokenId())
  537. .fromUser(asset.getMinter())
  538. .fromUserId(asset.getMinterId())
  539. .fromAvatar(asset.getMinterAvatar())
  540. .toUser(owner.getNickname())
  541. .toUserId(owner.getId())
  542. .toAvatar(owner.getAvatar())
  543. .operation("出售")
  544. .price(order.getPrice())
  545. .build();
  546. t.setCreatedAt(asset.getCreatedAt());
  547. tokenHistoryRepo.save(t);
  548. } catch (Exception e) {
  549. }
  550. });
  551. }
  552. public Page<UserHistory> userHistory(Long userId, Long toUserId, Long fromUserId, Pageable pageable) {
  553. Page<TokenHistory> page;
  554. if (ObjectUtils.isNotEmpty(toUserId)) {
  555. page = tokenHistoryRepo.userHistoryTo(userId, toUserId, pageable);
  556. } else if (ObjectUtils.isNotEmpty(fromUserId)) {
  557. page = tokenHistoryRepo.userHistoryFrom(userId, fromUserId, pageable);
  558. } else {
  559. page = tokenHistoryRepo.userHistory(userId, pageable);
  560. }
  561. Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
  562. List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
  563. return page.map(tokenHistory -> {
  564. UserHistory userHistory = new UserHistory();
  565. BeanUtils.copyProperties(tokenHistory, userHistory);
  566. Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
  567. .findAny();
  568. userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
  569. userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
  570. switch (tokenHistory.getOperation()) {
  571. case "出售":
  572. case "转让":
  573. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
  574. break;
  575. case "转赠":
  576. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
  577. break;
  578. default:
  579. userHistory.setDescription(tokenHistory.getOperation());
  580. }
  581. return userHistory;
  582. });
  583. }
  584. public Page<UserHistory> userHistory(Long userId, PageQuery pageQuery) {
  585. Page<TokenHistory> page = tokenHistoryRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
  586. List<Predicate> and = JpaUtils
  587. .toPredicates(pageQuery, TokenHistory.class, root, criteriaQuery, criteriaBuilder);
  588. Map<String, Object> query = pageQuery.getQuery();
  589. if (ObjectUtils.isEmpty(query.get("toUserId")) && ObjectUtils.isEmpty(query.get("fromUserId"))) {
  590. and.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("toUserId"), userId), criteriaBuilder
  591. .equal(root.get("fromUserId"), userId)));
  592. } else {
  593. if (ObjectUtils.isNotEmpty(query.get("toUserId"))) {
  594. and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("toUserId"), userId)));
  595. } else {
  596. and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("fromUserId"), userId)));
  597. }
  598. }
  599. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  600. }), JpaUtils.toPageRequest(pageQuery));
  601. Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
  602. List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
  603. return page.map(tokenHistory -> {
  604. UserHistory userHistory = new UserHistory();
  605. BeanUtils.copyProperties(tokenHistory, userHistory);
  606. Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
  607. .findAny();
  608. userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
  609. userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
  610. switch (tokenHistory.getOperation()) {
  611. case "出售":
  612. case "转让":
  613. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
  614. break;
  615. case "转赠":
  616. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
  617. break;
  618. default:
  619. userHistory.setDescription(tokenHistory.getOperation());
  620. }
  621. return userHistory;
  622. });
  623. }
  624. public String mint(LocalDateTime time) {
  625. if (time == null) {
  626. time = LocalDateTime.now();
  627. }
  628. for (Asset asset : assetRepo.toMint(time)) {
  629. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  630. }
  631. return "ok";
  632. }
  633. @Cacheable(value = "userStat", key = "#userId")
  634. public Map<String, BigDecimal> breakdown(Long userId) {
  635. // List<TokenHistory> page = tokenHistoryRepo.userHistory(userId);
  636. // BigDecimal sale = page.stream()
  637. // .filter(th -> th.getFromUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
  638. // .map(TokenHistory::getPrice)
  639. // .reduce(BigDecimal.ZERO, BigDecimal::add);
  640. // BigDecimal buy = page.stream()
  641. // .filter(th -> th.getToUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
  642. // .map(TokenHistory::getPrice)
  643. // .reduce(BigDecimal.ZERO, BigDecimal::add);
  644. Map<String, BigDecimal> map = new HashMap<>();
  645. map.put("sale", tokenHistoryRepo.userSale(userId));
  646. map.put("buy", rockRecordService.getRock(userId).getRecord());
  647. return map;
  648. }
  649. public void transferCDN() throws ExecutionException, InterruptedException {
  650. ForkJoinPool customThreadPool = new ForkJoinPool(100);
  651. customThreadPool.submit(() -> {
  652. collectionRepo.selectResource().parallelStream().forEach(list -> {
  653. for (int i = 0; i < list.size(); i++) {
  654. list.set(i, replaceCDN(list.get(i)));
  655. }
  656. collectionRepo.updateCDN(Long.parseLong(list.get(0)),
  657. list.get(1),
  658. list.get(2),
  659. list.get(3),
  660. list.get(4),
  661. list.get(5));
  662. });
  663. assetRepo.selectResource().parallelStream().forEach(list -> {
  664. for (int i = 0; i < list.size(); i++) {
  665. list.set(i, replaceCDN(list.get(i)));
  666. }
  667. assetRepo.updateCDN(Long.parseLong(list.get(0)),
  668. list.get(1),
  669. list.get(2),
  670. list.get(3),
  671. list.get(4),
  672. list.get(5));
  673. });
  674. }).get();
  675. }
  676. public String replaceCDN(String url) {
  677. if (url == null) return null;
  678. return url.replaceAll("https://raex-meta\\.oss-cn-shenzhen\\.aliyuncs\\.com",
  679. "https://cdn.raex.vip");
  680. }
  681. // @Scheduled(cron = "0 0 0/1 * * ?")
  682. // public void offTheShelf() {
  683. // LocalDateTime lastTime = LocalDateTime.now().minusHours(120);
  684. // Set<Long> assetIds = collectionRepo
  685. // .findResaleCollectionPriceOver20K(BigDecimal
  686. // .valueOf(20000L), CollectionSource.TRANSFER, lastTime, true);
  687. // assetIds.forEach(this::cancelConsignmentBySystem);
  688. // }
  689. @Scheduled(cron = "0 0 0/1 * * ?")
  690. public void offTheShelfAll() {
  691. LocalDateTime lastTime = LocalDateTime.now().minusHours(240);
  692. Set<Long> assetIds = collectionRepo
  693. .findResaleCollectionPriceOver20K(BigDecimal
  694. .valueOf(0L), CollectionSource.TRANSFER, lastTime, true);
  695. assetIds.forEach(this::cancelConsignmentBySystem);
  696. }
  697. public void cancelConsignmentBySystem(Long id) {
  698. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  699. if (asset.getPublicCollectionId() != null) {
  700. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  701. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  702. throw new BusinessException("已有订单不可取消");
  703. }
  704. collectionRepo.findById(asset.getPublicCollectionId())
  705. .ifPresent(collection -> {
  706. collection.setSalable(false);
  707. collectionRepo.save(collection);
  708. });
  709. }
  710. asset.setConsignment(false);
  711. assetRepo.save(asset);
  712. }
  713. // @Cacheable(cacheNames = "fmaa", key = "#userId+'#'+#mintActivityId+'#'+#pageable.hashCode()")
  714. public PageWrapper<Asset> findMintActivityAssetsWrap(Long userId, Long mintActivityId, Pageable pageable) {
  715. return PageWrapper.of(findMintActivityAssets(userId, mintActivityId, pageable));
  716. }
  717. public Page<Asset> findMintActivityAssets(Long userId, Long mintActivityId, Pageable pageable) {
  718. MintActivity mintActivity = mintActivityRepo.findById(mintActivityId).orElse(null);
  719. if (mintActivity == null) return new PageImpl<>(Collections.emptyList());
  720. if (!mintActivity.isAudit()) {
  721. Set<Tag> tags = mintActivity.getRule().getTags();
  722. if (tags.isEmpty()) return new PageImpl<>(Collections.emptyList());
  723. return assetRepo.findAll((Specification<Asset>) (root, query, criteriaBuilder) ->
  724. query.distinct(true).where(criteriaBuilder.equal(root.get("userId"), userId),
  725. criteriaBuilder.equal(root.get("status"), AssetStatus.NORMAL),
  726. root.join("tags").get("id").in(tags.stream().map(Tag::getId).toArray()))
  727. .getRestriction(), pageable);
  728. } else {
  729. return assetRepo.findByUserIdAndStatusAndNameLike(userId, AssetStatus.NORMAL,
  730. "%" + mintActivity.getCollectionName() + "%", pageable);
  731. }
  732. }
  733. public void destroy(Long id, Long userId) {
  734. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  735. if (!asset.getUserId().equals(userId)) {
  736. throw new BusinessException("此藏品不属于你");
  737. }
  738. if (asset.getStatus() != AssetStatus.NORMAL) {
  739. throw new BusinessException("当前状态不可寄售");
  740. }
  741. if (asset.isPublicShow()) {
  742. throw new BusinessException("请先取消公开展示");
  743. // cancelPublic(asset);
  744. }
  745. User toUser = userRepo.findById(1435297L).orElseThrow(new BusinessException("无记录"));
  746. TokenHistory tokenHistory = TokenHistory.builder()
  747. .tokenId(asset.getTokenId())
  748. .fromUser(asset.getOwner())
  749. .fromUserId(asset.getOwnerId())
  750. .fromAvatar(asset.getOwnerAvatar())
  751. .toUser(toUser.getNickname())
  752. .toUserId(toUser.getId())
  753. .toAvatar(toUser.getAvatar())
  754. .operation(TransferReason.DESTROY.getDescription())
  755. .price(null)
  756. .build();
  757. tokenHistoryRepo.save(tokenHistory);
  758. asset.setPublicShow(false);
  759. asset.setConsignment(false);
  760. asset.setPublicCollectionId(null);
  761. asset.setStatus(AssetStatus.DESTROYED);
  762. asset.setOwner(toUser.getNickname());
  763. asset.setOwnerId(toUser.getId());
  764. asset.setOwnerAvatar(toUser.getAvatar());
  765. assetRepo.save(asset);
  766. //积分记录
  767. destroyRecordRepo.save(DestroyRecord.builder()
  768. .userId(userId)
  769. .assetId(asset.getId())
  770. .name(asset.getName())
  771. .pic(asset.getPic().get(0).getUrl())
  772. .record(1)
  773. .type(RecordType.OBTAIN)
  774. .build());
  775. //加积分
  776. userRepo.addDestroyPoint(userId, 1);
  777. }
  778. public int getRoyalties(Long minterId, int royalties, Long userId) {
  779. if (royalties == 3) {
  780. return 3;
  781. }
  782. LongArrayConverter converter = new LongArrayConverter();
  783. String discountMinter = sysConfigService.getString("discount_minter");
  784. List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
  785. if (minterIds.contains(minterId)) {
  786. String discountCollection = sysConfigService.getString("discount_collection");
  787. List<Long> collectionIds = converter.convertToEntityAttribute(discountCollection);
  788. Long assetId = assetRepo.findDiscount(userId, collectionIds);
  789. if (ObjectUtils.isNotEmpty(assetId)) {
  790. return 3;
  791. }
  792. }
  793. return royalties;
  794. }
  795. @Async
  796. public void hcChain() throws ExecutionException, InterruptedException {
  797. new ForkJoinPool(1000).submit(() -> {
  798. AtomicInteger num = new AtomicInteger();
  799. assetRepo.findByStatus(AssetStatus.NORMAL).parallelStream()
  800. .forEach(asset -> {
  801. if (asset.getHcTxHash() == null) {
  802. User user = userRepo.findById(asset.getUserId()).orElse(null);
  803. if (user != null) {
  804. if (user.getHcChainAddress() == null) {
  805. user.setHcChainAddress(hcChainService.createAccount(asset.getUserId()));
  806. }
  807. NFT nft = hcChainService.mint(user.getHcChainAddress(), asset.getTokenId());
  808. asset.setHcTokenId(nft.getTokenId());
  809. asset.setHcTxHash(nft.getTxHash());
  810. asset.setGasUsed(nft.getGasUsed());
  811. assetRepo.save(asset);
  812. }
  813. }
  814. log.info("hcChain:" + num.getAndIncrement());
  815. });
  816. }).get();
  817. }
  818. }