AssetService.java 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. package com.izouma.nineth.service;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.google.common.collect.Lists;
  6. import com.google.common.hash.Hashing;
  7. import com.izouma.nineth.TokenHistory;
  8. import com.izouma.nineth.config.Constants;
  9. import com.izouma.nineth.config.GeneralProperties;
  10. import com.izouma.nineth.converter.LongArrayConverter;
  11. import com.izouma.nineth.domain.Collection;
  12. import com.izouma.nineth.domain.*;
  13. import com.izouma.nineth.dto.*;
  14. import com.izouma.nineth.enums.*;
  15. import com.izouma.nineth.exception.BusinessException;
  16. import com.izouma.nineth.repo.*;
  17. import com.izouma.nineth.repo.nftdomain.DomainAskRepo;
  18. import com.izouma.nineth.utils.JpaUtils;
  19. import com.izouma.nineth.utils.SecurityUtils;
  20. import com.izouma.nineth.utils.TokenUtils;
  21. import lombok.AllArgsConstructor;
  22. import lombok.extern.slf4j.Slf4j;
  23. import org.apache.commons.collections.CollectionUtils;
  24. import org.apache.commons.lang3.ObjectUtils;
  25. import org.apache.commons.lang3.RandomStringUtils;
  26. import org.apache.commons.lang3.StringUtils;
  27. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  28. import org.springframework.beans.BeanUtils;
  29. import org.springframework.cache.annotation.Cacheable;
  30. import org.springframework.data.domain.Page;
  31. import org.springframework.data.domain.PageImpl;
  32. import org.springframework.data.domain.PageRequest;
  33. import org.springframework.data.domain.Pageable;
  34. import org.springframework.data.jpa.domain.Specification;
  35. import org.springframework.scheduling.annotation.Async;
  36. import org.springframework.scheduling.annotation.Scheduled;
  37. import org.springframework.security.crypto.password.PasswordEncoder;
  38. import org.springframework.stereotype.Service;
  39. import javax.persistence.criteria.Predicate;
  40. import javax.transaction.Transactional;
  41. import java.math.BigDecimal;
  42. import java.nio.charset.StandardCharsets;
  43. import java.time.Duration;
  44. import java.time.LocalDateTime;
  45. import java.time.format.DateTimeFormatter;
  46. import java.time.temporal.ChronoUnit;
  47. import java.util.*;
  48. import java.util.concurrent.ExecutionException;
  49. import java.util.concurrent.ForkJoinPool;
  50. import java.util.concurrent.atomic.AtomicInteger;
  51. import java.util.regex.Matcher;
  52. import java.util.regex.Pattern;
  53. import java.util.stream.Collectors;
  54. import java.util.stream.Stream;
  55. import static java.util.stream.Collectors.toList;
  56. @Service
  57. @AllArgsConstructor
  58. @Slf4j
  59. public class AssetService {
  60. private AssetRepo assetRepo;
  61. private UserRepo userRepo;
  62. private CollectionRepo collectionRepo;
  63. private OrderRepo orderRepo;
  64. private TokenHistoryRepo tokenHistoryRepo;
  65. private SysConfigService sysConfigService;
  66. private RocketMQTemplate rocketMQTemplate;
  67. private GeneralProperties generalProperties;
  68. private ShowroomRepo showroomRepo;
  69. private ShowCollectionRepo showCollectionRepo;
  70. private CollectionPrivilegeRepo collectionPrivilegeRepo;
  71. private PasswordEncoder passwordEncoder;
  72. private MintActivityRepo mintActivityRepo;
  73. private DestroyRecordRepo destroyRecordRepo;
  74. private AirDropService airDropService;
  75. private HCChainService hcChainService;
  76. private RockRecordService rockRecordService;
  77. private RockRecordRepo rockRecordRepo;
  78. private AssetLockRepo assetLockRepo;
  79. private UserBalanceService userBalanceService;
  80. private PhotoAssetRepo photoAssetRepo;
  81. private NumberSeqRepo numberSeqRepo;
  82. private DomainAskRepo domainAskRepo;
  83. private DomainOrderRepo domainOrderRepo;
  84. public Page<Asset> all(PageQuery pageQuery) {
  85. Map<String, Object> query = pageQuery.getQuery();
  86. Specification<Asset> specification = JpaUtils.toSpecification(pageQuery, Asset.class);
  87. PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
  88. if (query.containsKey("lock")) {
  89. LocalDateTime now = LocalDateTime.now();
  90. query.remove("lock");
  91. specification = specification.and((Specification<Asset>) (root, criteriaQuery, criteriaBuilder) -> {
  92. List<Predicate> and = new ArrayList<>();
  93. and.add(criteriaBuilder.greaterThan(root.get("lockTo"), now));
  94. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  95. });
  96. }
  97. Page<Asset> all = assetRepo.findAll(specification, pageRequest);
  98. // Map<String, Object> query = pageQuery.getQuery();
  99. // if (query.containsKey("userId")) {
  100. // List<Long> orderId = orderRepo
  101. // .findAllByUserIdAndOpenedFalse(Convert.convert(Long.class, query.get("userId")));
  102. // return all.map(asset -> {
  103. // if (orderId.contains(asset.getOrderId())) {
  104. // asset.setOpened(false);
  105. // }
  106. // return asset;
  107. // });
  108. // }
  109. return new PageWrapper<>(all.getContent(), all.getPageable().getPageNumber(),
  110. all.getPageable().getPageSize(), all.getTotalElements()).toPage();
  111. }
  112. public List<AssetDTO> userSummary(PageQuery pageQuery) {
  113. List<AssetDTO> assetDTOs = new ArrayList<>();
  114. // 根据条件查询所有资产
  115. List<Asset> assets = assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class));
  116. if (CollectionUtils.isEmpty(assets)) {
  117. return assetDTOs;
  118. }
  119. // 取出资产中未开启盲盒数据
  120. List<Asset> blindBoxClosedAssets = assets.stream()
  121. .filter(asset -> !asset.isOpened() && CollectionType.BLIND_BOX
  122. .equals(asset.getType()))
  123. .collect(toList());
  124. if (CollectionUtils.isNotEmpty(blindBoxClosedAssets)) {
  125. blindBoxClosedAssets.forEach(asset -> {
  126. assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
  127. });
  128. // 移除资产中未开启盲盒数据
  129. assets.removeAll(blindBoxClosedAssets);
  130. }
  131. // 取出资产中所有未设置prefixName的值
  132. List<Asset> prefixNameIsNullAssets = assets.stream()
  133. .filter(asset -> StringUtils.isBlank(asset.getPrefixName()))
  134. .collect(toList());
  135. if (CollectionUtils.isNotEmpty(prefixNameIsNullAssets)) {
  136. prefixNameIsNullAssets.forEach(asset -> {
  137. assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
  138. });
  139. assets.removeAll(prefixNameIsNullAssets);
  140. }
  141. if (CollectionUtils.isNotEmpty(assets)) {
  142. // 取出资产中所有prefixName
  143. List<String> prefixNames = assets.stream()
  144. .map(Asset::getPrefixName)
  145. .distinct()
  146. .collect(toList());
  147. // 将资产中相同prefixName归类(除未开启盲盒和未设置prefixName)
  148. prefixNames.forEach(str -> {
  149. List<Asset> collect = assets.stream()
  150. .filter(asset -> str.equals(asset.getPrefixName()))
  151. .collect(toList());
  152. assetDTOs.add(AssetDTO.create(collect));
  153. });
  154. }
  155. return assetDTOs;
  156. }
  157. public Asset createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type,
  158. Integer number, boolean safeFlag) {
  159. if (collection.isMessNumber() && number != null) {
  160. number = getMessedNumber(collection.getId(), number, collection.getTotal());
  161. }
  162. Asset asset = Asset.create(collection, user);
  163. asset.setTokenId(TokenUtils.genTokenId());
  164. asset.setNumber(number);
  165. asset.setOasisId(collection.getOasisId());
  166. asset.setOrderId(orderId);
  167. asset.setPrice(price);
  168. asset.setPrefixName(collection.getPrefixName());
  169. asset.setTags(new HashSet<>());
  170. if (collection.getTags() != null) {
  171. asset.getTags().addAll(collection.getTags());
  172. }
  173. User fakeUser = null;
  174. if (safeFlag) {
  175. fakeUser = createFakeUser();
  176. asset.setOwner(fakeUser.getNickname());
  177. asset.setOwnerId(fakeUser.getId());
  178. asset.setOwnerAvatar(fakeUser.getAvatar());
  179. }
  180. assetRepo.saveAndFlush(asset);
  181. tokenHistoryRepo.save(TokenHistory.builder()
  182. .tokenId(asset.getTokenId())
  183. .fromUser(collection.getMinter())
  184. .fromUserId(collection.getMinterId())
  185. .fromAvatar(collection.getMinterAvatar())
  186. .toUser((safeFlag ? fakeUser : user).getNickname())
  187. .toUserId((safeFlag ? fakeUser : user).getId())
  188. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  189. .operation(type)
  190. .price(price)
  191. .companyId(asset.getCompanyId())
  192. .build());
  193. //绿洲石
  194. rockRecordService.addRock(user.getId(), price, "购买");
  195. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  196. if (asset.getOasisId() != null & asset.getSource().equals(AssetSource.OFFICIAL)) {
  197. AirDrop airDrop = new AirDrop();
  198. airDrop.setName("建筑空投展厅");
  199. airDrop.setCollectionId(207012L);
  200. List<Long> userIds = new ArrayList<>();
  201. userIds.add(user.getId());
  202. List<Long> nums = new ArrayList<>();
  203. nums.add(1L);
  204. airDrop.setType(AirDropType.asset);
  205. List<DropTarget> dropTargets = new ArrayList<>();
  206. DropTarget dropTarget = new DropTarget();
  207. dropTarget.setNickname(user.getNickname());
  208. dropTarget.setNum(1);
  209. dropTarget.setPhone(user.getPhone());
  210. dropTarget.setUserId(user.getId());
  211. dropTargets.add(dropTarget);
  212. airDrop.setTargets(dropTargets);
  213. airDrop.setUserIds(userIds);
  214. airDrop.setNum(nums);
  215. airDropService.create(airDrop);
  216. }
  217. return asset;
  218. }
  219. public Asset createAsset(PhotoAsset photoAsset, User user, Long orderId, BigDecimal price, String type,
  220. Integer number, boolean safeFlag) {
  221. Asset asset = Asset.create(photoAsset, user);
  222. asset.setTokenId(TokenUtils.genTokenId());
  223. asset.setNumber(number);
  224. asset.setOrderId(orderId);
  225. asset.setPrice(price);
  226. asset.setPrefixName("星图");
  227. asset.setTags(new HashSet<>());
  228. User fakeUser = null;
  229. if (safeFlag) {
  230. fakeUser = createFakeUser();
  231. asset.setOwner(fakeUser.getNickname());
  232. asset.setOwnerId(fakeUser.getId());
  233. asset.setOwnerAvatar(fakeUser.getAvatar());
  234. }
  235. assetRepo.saveAndFlush(asset);
  236. tokenHistoryRepo.save(TokenHistory.builder()
  237. .tokenId(asset.getTokenId())
  238. .fromUser(photoAsset.getUserName())
  239. .fromUserId(photoAsset.getUserId())
  240. .fromAvatar(photoAsset.getUserAvatar())
  241. .toUser((safeFlag ? fakeUser : user).getNickname())
  242. .toUserId((safeFlag ? fakeUser : user).getId())
  243. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  244. .operation(type)
  245. .price(price)
  246. .companyId(asset.getCompanyId())
  247. .build());
  248. //绿洲石
  249. // rockRecordService.addRock(user.getId(), price, "购买");
  250. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  251. return asset;
  252. }
  253. public Asset createAsset(DomainOrder domainOrder, User user, Long orderId, BigDecimal price, String type,
  254. Integer number, boolean safeFlag) {
  255. Asset asset = Asset.create(domainOrder, user);
  256. asset.setTokenId(TokenUtils.genTokenId());
  257. asset.setNumber(number);
  258. asset.setOrderId(orderId);
  259. asset.setPrice(price);
  260. asset.setStatus(AssetStatus.PENDING);
  261. if (StringUtils.isNumeric(domainOrder.getPicName())) {
  262. if (domainOrder.getPicName().length() < 6) {
  263. asset.setPrefixName("RIDN" + domainOrder.getPicName().length());
  264. } else {
  265. asset.setPrefixName("RIDN6");
  266. }
  267. } else {
  268. Pattern p;
  269. p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");
  270. Matcher m = p.matcher(domainOrder.getPicName());
  271. if (m.find()) {
  272. asset.setPrefixName("RIDC");
  273. } else {
  274. if (domainOrder.getPicName().length() < 6) {
  275. asset.setPrefixName("RID" + domainOrder.getPicName().length());
  276. } else {
  277. asset.setPrefixName("RID");
  278. }
  279. }
  280. }
  281. asset.setTags(new HashSet<>());
  282. User fakeUser = null;
  283. if (safeFlag) {
  284. fakeUser = createFakeUser();
  285. asset.setOwner(fakeUser.getNickname());
  286. asset.setOwnerId(fakeUser.getId());
  287. asset.setOwnerAvatar(fakeUser.getAvatar());
  288. }
  289. assetRepo.saveAndFlush(asset);
  290. tokenHistoryRepo.save(TokenHistory.builder()
  291. .tokenId(asset.getTokenId())
  292. .fromUser(domainOrder.getUserName())
  293. .fromUserId(domainOrder.getUserId())
  294. .fromAvatar(domainOrder.getUserAvatar())
  295. .toUser((safeFlag ? fakeUser : user).getNickname())
  296. .toUserId((safeFlag ? fakeUser : user).getId())
  297. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  298. .operation(type)
  299. .price(price)
  300. .companyId(asset.getCompanyId())
  301. .build());
  302. //绿洲石
  303. // rockRecordService.addRock(user.getId(), price, "购买");
  304. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  305. return asset;
  306. }
  307. public Asset createAsset(TradeAuction tradeAuction, User user, Long orderId, BigDecimal price, String type,
  308. Integer number, boolean safeFlag) {
  309. Asset asset = Asset.create(tradeAuction, user);
  310. asset.setTokenId(TokenUtils.genTokenId());
  311. asset.setNumber(number);
  312. asset.setOrderId(orderId);
  313. asset.setPrice(price);
  314. asset.setPrefixName("易拍");
  315. asset.setTags(new HashSet<>());
  316. User fakeUser = null;
  317. if (safeFlag) {
  318. fakeUser = createFakeUser();
  319. asset.setOwner(fakeUser.getNickname());
  320. asset.setOwnerId(fakeUser.getId());
  321. asset.setOwnerAvatar(fakeUser.getAvatar());
  322. }
  323. assetRepo.saveAndFlush(asset);
  324. tokenHistoryRepo.save(TokenHistory.builder()
  325. .tokenId(asset.getTokenId())
  326. .fromUser(tradeAuction.getMinter())
  327. .fromUserId(Long.valueOf(tradeAuction.getMinterId()))
  328. .fromAvatar(tradeAuction.getMinterAvatar())
  329. .toUser((safeFlag ? fakeUser : user).getNickname())
  330. .toUserId((safeFlag ? fakeUser : user).getId())
  331. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  332. .operation(type)
  333. .price(null)
  334. .companyId(asset.getCompanyId())
  335. .build());
  336. //绿洲石
  337. // rockRecordService.addRock(user.getId(), price, "购买");
  338. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  339. return asset;
  340. }
  341. public synchronized int getMessedNumber(Long collectionId, int number, int total) {
  342. NumberSeq numberSeq = numberSeqRepo.findById(collectionId).orElse(null);
  343. if (numberSeq == null || numberSeq.getTotal() != total) {
  344. numberSeq = new NumberSeq();
  345. numberSeq.setId(collectionId);
  346. numberSeq.setTotal(total);
  347. Map<Integer, Integer> map = new HashMap<>();
  348. for (int i = 0; i < total; i++) {
  349. map.put(i, Hashing.md5().hashString(collectionId + ":" + i, StandardCharsets.UTF_8).asInt());
  350. }
  351. numberSeq.setNumbers(map.entrySet().stream()
  352. .sorted(Map.Entry.comparingByValue())
  353. .map(Map.Entry::getKey)
  354. .collect(toList()));
  355. numberSeqRepo.save(numberSeq);
  356. }
  357. return numberSeq.getNumbers().get(number);
  358. }
  359. public Asset createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type,
  360. Integer number, Integer holdDays, boolean safeFlag) {
  361. Collection blindBox = collectionRepo.findDetailById(winItem.getBlindBoxId())
  362. .orElseThrow(new BusinessException("盲盒不存在"));
  363. Collection collection = collectionRepo.findDetailById(winItem.getCollectionId())
  364. .orElseThrow(new BusinessException("藏品不存在"));
  365. if (collection.isMessNumber() && number != null) {
  366. number = getMessedNumber(collection.getId(), number, collection.getTotal());
  367. }
  368. winItem.setCollection(collection);
  369. Asset asset = Asset.create(winItem, user, holdDays);
  370. if (collection.getType().equals(CollectionType.DOMAIN)) {
  371. asset.setType(CollectionType.DOMAIN);
  372. }
  373. asset.setTokenId(TokenUtils.genTokenId());
  374. asset.setNumber(number);
  375. asset.setOasisId(winItem.getOasisId());
  376. asset.setOrderId(orderId);
  377. asset.setPrice(price);
  378. asset.setPrefixName(collection.getPrefixName());
  379. asset.setEmpower(collection.getEmpower());
  380. asset.setTags(new HashSet<>());
  381. if (blindBox.getTags() != null) {
  382. asset.getTags().addAll(blindBox.getTags());
  383. }
  384. if (collection.getTags() != null) {
  385. asset.getTags().addAll(collection.getTags());
  386. }
  387. User fakeUser = null;
  388. if (safeFlag) {
  389. fakeUser = createFakeUser();
  390. asset.setOwner(fakeUser.getNickname());
  391. asset.setOwnerId(fakeUser.getId());
  392. asset.setOwnerAvatar(fakeUser.getAvatar());
  393. }
  394. assetRepo.saveAndFlush(asset);
  395. tokenHistoryRepo.save(TokenHistory.builder()
  396. .tokenId(asset.getTokenId())
  397. .fromUser(winItem.getMinter())
  398. .fromUserId(winItem.getMinterId())
  399. .fromAvatar(winItem.getMinterAvatar())
  400. .toUser((safeFlag ? fakeUser : user).getNickname())
  401. .toUserId((safeFlag ? fakeUser : user).getId())
  402. .toAvatar((safeFlag ? fakeUser : user).getAvatar())
  403. .operation(type)
  404. .price(price)
  405. .companyId(asset.getCompanyId())
  406. .build());
  407. //绿洲石
  408. rockRecordService.addRock(user.getId(), price, "购买");
  409. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  410. return asset;
  411. }
  412. public void publicShow(Long id) {
  413. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  414. Set<DomainAskStatus> statuses = new HashSet<>();
  415. statuses.add(DomainAskStatus.ASKING);
  416. if (domainAskRepo
  417. .countByAssetIdAndOwnerIdAndStatusInAndDelFalse(asset.getId(), asset.getOwnerId(), statuses) > 0) {
  418. throw new BusinessException("已有叫价,不可上架");
  419. }
  420. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  421. throw new BusinessException("此藏品不属于你");
  422. }
  423. if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
  424. throw new BusinessException("已锁仓,不能上架展示");
  425. }
  426. if (asset.isPublicShow()) {
  427. return;
  428. }
  429. if (asset.getStatus() != AssetStatus.NORMAL) {
  430. throw new BusinessException("当前状态不可展示");
  431. }
  432. User owner = asset.isSafeFlag() ?
  433. userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
  434. : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  435. Collection collection = Collection.builder()
  436. .name(asset.getName())
  437. .pic(asset.getPic())
  438. .minter(asset.getMinter())
  439. .minterId(asset.getMinterId())
  440. .minterAvatar(asset.getMinterAvatar())
  441. .owner(owner.getNickname())
  442. .oasisId(asset.getOasisId())
  443. .ownerId(owner.getId())
  444. .ownerAvatar(owner.getAvatar())
  445. .detail(asset.getDetail())
  446. .type(CollectionType.DEFAULT)
  447. .source(CollectionSource.TRANSFER)
  448. .sale(0)
  449. .stock(1)
  450. .total(1)
  451. .onShelf(true)
  452. .salable(false)
  453. .price(BigDecimal.valueOf(0))
  454. .properties(asset.getProperties())
  455. .canResale(asset.isCanResale())
  456. .royalties(asset.getRoyalties())
  457. .serviceCharge(asset.getServiceCharge())
  458. .assetId(id)
  459. .number(asset.getNumber())
  460. .tags(new HashSet<>())
  461. .prefixName(asset.getPrefixName())
  462. .companyId(asset.getCompanyId())
  463. .build();
  464. if (asset.getTags() != null) {
  465. collection.getTags().addAll(asset.getTags());
  466. }
  467. if (asset.getType().equals(CollectionType.PICTURE)) {
  468. collection.setType(CollectionType.PICTURE);
  469. }
  470. if (asset.getType().equals(CollectionType.DOMAIN)) {
  471. collection.setType(CollectionType.DOMAIN);
  472. }
  473. collectionRepo.save(collection);
  474. asset.setPublicShow(true);
  475. asset.setPublicCollectionId(collection.getId());
  476. assetRepo.saveAndFlush(asset);
  477. }
  478. public synchronized void consignment(Long id, BigDecimal price, String tradeCode, boolean safeFlag) {
  479. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  480. Set<DomainAskStatus> statuses = new HashSet<>();
  481. statuses.add(DomainAskStatus.ASKING);
  482. if (domainAskRepo
  483. .countByAssetIdAndOwnerIdAndStatusInAndDelFalse(asset.getId(), asset.getOwnerId(), statuses) > 0) {
  484. throw new BusinessException("已有叫价,不可上架");
  485. }
  486. String mapString = sysConfigService.getString("collection_price");
  487. if (StringUtils.isNotBlank(mapString)) {
  488. JSONObject json = JSONObject.parseObject(mapString);
  489. String assetName = asset.getName();
  490. json.forEach((k, v) -> {
  491. if (assetName.contains(k)) {
  492. Map<String, Object> map = (Map<String, Object>) v;
  493. BigDecimal max = BigDecimal.valueOf(Double.parseDouble(map.get("maxPrice").toString()));
  494. BigDecimal min = BigDecimal.valueOf(Double.parseDouble(map.get("minPrice").toString()));
  495. if (price.compareTo(max) > 0) {
  496. throw new BusinessException("已经超过藏品最高限价" + max + "元");
  497. }
  498. if (price.compareTo(min) < 0) {
  499. throw new BusinessException("低于藏品最低限价" + min + "元");
  500. }
  501. }
  502. });
  503. }
  504. if (Objects.nonNull(asset.getType()) && asset.getType().equals(CollectionType.SHOWROOM)) {
  505. throw new BusinessException("展厅类型的藏品不能上架");
  506. }
  507. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  508. throw new BusinessException("此藏品不属于你");
  509. }
  510. if (asset.getType().equals(CollectionType.PICTURE)) {
  511. throw new BusinessException("星图藏品不可寄售");
  512. }
  513. if (!sysConfigService.getBoolean("domain_transfer")) {
  514. throw new BusinessException("域名暂不可以寄售");
  515. }
  516. if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
  517. throw new BusinessException("已锁仓,不能寄售");
  518. }
  519. List<String> bannedAssets = Arrays.asList(sysConfigService.getString("older_collections").split(",").clone());
  520. bannedAssets.forEach(name -> {
  521. if (asset.getName().contains(name)) {
  522. throw new BusinessException("编年史藏品无法寄售");
  523. }
  524. });
  525. int holdDays = 0;
  526. if (!asset.getType().equals(CollectionType.DOMAIN)) {
  527. if (asset.getSource() == AssetSource.GIFT) {
  528. LocalDateTime localDateTime = asset.getCreatedAt();
  529. LocalDateTime gift_change_time = LocalDateTime
  530. .parse(sysConfigService.getString("gift_change_time"), DateTimeFormatter
  531. .ofPattern("yyyy-MM-dd HH:mm:ss"));
  532. if (localDateTime.compareTo(gift_change_time) < 0) {
  533. holdDays = 20;
  534. } else {
  535. holdDays = sysConfigService.getInt("gift_days");
  536. }
  537. } else {
  538. if (ObjectUtils.isEmpty(asset.getHoldDays())) {
  539. holdDays = sysConfigService.getInt("hold_days");
  540. } else {
  541. holdDays = asset.getHoldDays();
  542. }
  543. }
  544. } else {
  545. if (!ObjectUtils.isEmpty(asset.getHoldDays())) {
  546. holdDays = asset.getHoldDays();
  547. }
  548. }
  549. if (holdDays == 0 && AssetSource.OFFICIAL.equals(asset.getSource())) {
  550. BigDecimal officialConsignment = sysConfigService.getBigDecimal("OFFICIAL_CONSIGNMENT");
  551. //天转小时
  552. int hour = officialConsignment.multiply(new BigDecimal("24")).intValue();
  553. if (ChronoUnit.HOURS.between(asset.getCreatedAt(), LocalDateTime.now()) < hour) {
  554. throw new BusinessException("需持有满" + hour + "小时后才能寄售上架");
  555. }
  556. }
  557. if (ChronoUnit.DAYS.between(asset.getCreatedAt(), LocalDateTime.now()) < holdDays) {
  558. throw new BusinessException("需持有满" + holdDays + "天才能寄售上架");
  559. }
  560. User owner;
  561. if (safeFlag && !asset.isSafeFlag()) {
  562. owner = createFakeUser();
  563. asset.setOwner(owner.getNickname());
  564. asset.setOwnerId(owner.getId());
  565. asset.setOwnerAvatar(owner.getAvatar());
  566. asset.setSafeFlag(true);
  567. tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(asset.getTokenId()).stream()
  568. .filter(t -> t.getToUserId().equals(asset.getUserId())).findFirst()
  569. .ifPresent(tokenHistory -> {
  570. tokenHistory.setToUserId(owner.getId());
  571. tokenHistory.setToUser(owner.getNickname());
  572. tokenHistory.setToAvatar(owner.getAvatar());
  573. tokenHistoryRepo.save(tokenHistory);
  574. });
  575. } else {
  576. owner = asset.isSafeFlag() ?
  577. userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
  578. : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  579. }
  580. if (!passwordEncoder.matches(tradeCode, userRepo.findTradeCode(asset.getUserId()))) {
  581. throw new BusinessException("交易密码错误");
  582. }
  583. // if (StringUtils.isBlank(owner.getSettleAccountId())) {
  584. // throw new BusinessException("请先绑定银行卡");
  585. // }
  586. if (asset.isConsignment()) {
  587. throw new BusinessException("已寄售,请勿重新操作");
  588. }
  589. if (asset.getStatus() != AssetStatus.NORMAL) {
  590. throw new BusinessException("当前状态不可寄售");
  591. }
  592. if (asset.isPublicShow()) {
  593. cancelPublic(asset);
  594. }
  595. //寄售中的展厅需要先删除展厅
  596. if (CollectionType.SHOWROOM.equals(asset.getType())) {
  597. if (showroomRepo.findByAssetId(id).isPresent()) {
  598. throw new BusinessException("请先删除展厅");
  599. }
  600. }
  601. Collection collection = Collection.builder()
  602. .name(asset.getName())
  603. .pic(asset.getPic())
  604. .minter(asset.getMinter())
  605. .minterId(asset.getMinterId())
  606. .minterAvatar(asset.getMinterAvatar())
  607. .owner(owner.getNickname())
  608. .ownerId(owner.getId())
  609. .oasisId(asset.getOasisId())
  610. .ownerAvatar(owner.getAvatar())
  611. .detail(asset.getDetail())
  612. .type(CollectionType.DEFAULT)
  613. .source(CollectionSource.TRANSFER)
  614. .sale(0)
  615. .stock(1)
  616. .total(1)
  617. .onShelf(true)
  618. .salable(true)
  619. .price(price)
  620. .properties(asset.getProperties())
  621. .canResale(asset.isCanResale())
  622. .royalties(asset.getRoyalties())
  623. .serviceCharge(asset.getServiceCharge())
  624. .assetId(id)
  625. .number(asset.getNumber())
  626. .tags(new HashSet<>())
  627. .prefixName(asset.getPrefixName())
  628. .companyId(asset.getCompanyId())
  629. .build();
  630. if (asset.getType().equals(CollectionType.DOMAIN)) {
  631. collection.setType(CollectionType.DOMAIN);
  632. }
  633. if (asset.getTags() != null) {
  634. collection.getTags().addAll(asset.getTags());
  635. }
  636. collectionRepo.save(collection);
  637. asset.setPublicShow(true);
  638. asset.setConsignment(true);
  639. asset.setPublicCollectionId(collection.getId());
  640. asset.setSellPrice(price);
  641. assetRepo.saveAndFlush(asset);
  642. }
  643. public Asset cancelConsignmentAndStore(Long id) {
  644. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  645. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  646. throw new BusinessException("此藏品不属于你");
  647. }
  648. if (asset.getStatus() != AssetStatus.NORMAL) {
  649. throw new BusinessException("当前状态不可寄售");
  650. }
  651. if (asset.getPublicCollectionId() != null) {
  652. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  653. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  654. throw new BusinessException("已有订单不可取消");
  655. }
  656. collectionRepo.findById(asset.getPublicCollectionId())
  657. .ifPresent(collection -> {
  658. collection.setSalable(false);
  659. collection.setOnShelf(false);
  660. collectionRepo.save(collection);
  661. });
  662. }
  663. asset.setConsignment(false);
  664. asset.setPublicShow(false);
  665. asset.setStatus(AssetStatus.DESTROYING);
  666. return assetRepo.saveAndFlush(asset);
  667. }
  668. public void batchCancelConsignment(String search) {
  669. List<Asset> onShelf = assetRepo.findOnShelfByNameLike("%" + search + "%");
  670. onShelf.forEach(this::cancelConsignmentBySystem);
  671. }
  672. public void cancelConsignment(Long id) {
  673. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  674. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  675. throw new BusinessException("此藏品不属于你");
  676. }
  677. cancelConsignment(asset);
  678. }
  679. public void cancelConsignment(Asset asset) {
  680. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  681. throw new BusinessException("此藏品不属于你");
  682. }
  683. if (asset.getPublicCollectionId() != null) {
  684. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  685. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  686. throw new BusinessException("已有订单不可取消");
  687. }
  688. collectionRepo.findById(asset.getPublicCollectionId())
  689. .ifPresent(collection -> {
  690. collection.setSalable(false);
  691. collectionRepo.save(collection);
  692. });
  693. }
  694. try {
  695. List<DomainOrder> filteredDomainOrders = domainOrderRepo.findAllByHyperLinkType(HyperLinkType.COLLECTION);
  696. for (DomainOrder filteredDomainOrder : filteredDomainOrders) {
  697. String url = filteredDomainOrder.getAddress();
  698. int secondSlashIndex = url.indexOf('/', url.indexOf('/') + 1);
  699. if (url.length() > secondSlashIndex + 1) {
  700. String secondNumber = url.substring(secondSlashIndex + 1);
  701. if (!secondNumber.isBlank()) {
  702. if (asset.getPublicCollectionId() != null && asset.getPublicCollectionId().equals(Long.parseLong(secondNumber))) {
  703. filteredDomainOrder.setOpenHyperLink(false);
  704. filteredDomainOrder.setHyperLinkType(null);
  705. filteredDomainOrder.setAddress(null);
  706. filteredDomainOrder.setCurrentOwnerId(null);
  707. domainOrderRepo.save(filteredDomainOrder);
  708. }
  709. }
  710. }
  711. }
  712. } catch (Exception e) {
  713. log.error("超链报错:assetId" + asset.getId(), e);
  714. }
  715. asset.setConsignment(false);
  716. assetRepo.saveAndFlush(asset);
  717. }
  718. public void cancelPublic(Long id) {
  719. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  720. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  721. throw new BusinessException("此藏品不属于你");
  722. }
  723. cancelPublic(asset);
  724. }
  725. public void cancelPublic(Asset asset) {
  726. if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
  727. throw new BusinessException("此藏品不属于你");
  728. }
  729. if (!asset.isPublicShow()) {
  730. return;
  731. }
  732. if (asset.isConsignment()) {
  733. cancelConsignment(asset);
  734. }
  735. Collection collection = collectionRepo.findById(asset.getPublicCollectionId())
  736. .orElseThrow(new BusinessException("无展示记录"));
  737. collectionRepo.delete(collection);
  738. // 如果展厅有此藏品
  739. showCollectionRepo.deleteAllByCollectionId(asset.getPublicCollectionId());
  740. try {
  741. List<DomainOrder> filteredDomainOrders = domainOrderRepo.findAllByHyperLinkType(HyperLinkType.COLLECTION);
  742. for (DomainOrder filteredDomainOrder : filteredDomainOrders) {
  743. String url = filteredDomainOrder.getAddress();
  744. int secondSlashIndex = url.indexOf('/', url.indexOf('/') + 1);
  745. if (url.length() > secondSlashIndex + 1) {
  746. String secondNumber = url.substring(secondSlashIndex + 1);
  747. if (!secondNumber.isBlank()) {
  748. if (asset.getPublicCollectionId() != null && asset.getPublicCollectionId().equals(Long.parseLong(secondNumber))) {
  749. filteredDomainOrder.setOpenHyperLink(false);
  750. filteredDomainOrder.setHyperLinkType(null);
  751. filteredDomainOrder.setAddress(null);
  752. filteredDomainOrder.setCurrentOwnerId(null);
  753. domainOrderRepo.save(filteredDomainOrder);
  754. }
  755. }
  756. }
  757. }
  758. } catch (Exception e) {
  759. log.error("超链报错:assetId" + asset.getId(), e);
  760. }
  761. asset.setPublicShow(false);
  762. asset.setPublicCollectionId(null);
  763. assetRepo.saveAndFlush(asset);
  764. }
  765. public void usePrivilege(Long assetId, Long privilegeId) {
  766. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("无记录"));
  767. asset.getPrivileges().stream().filter(p -> p.getId().equals(privilegeId)).forEach(p -> {
  768. if (!p.getName().equals("铸造")) {
  769. p.setOpened(true);
  770. p.setOpenTime(LocalDateTime.now());
  771. p.setOpenedBy(SecurityUtils.getAuthenticatedUser().getId());
  772. }
  773. });
  774. assetRepo.saveAndFlush(asset);
  775. }
  776. public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId) {
  777. transfer(asset, price, toUser, reason, orderId, false, asset.getTags());
  778. }
  779. private User createFakeUser() {
  780. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  781. return userRepo.save(User.builder()
  782. .username(name)
  783. .nickname(name)
  784. .avatar(Constants.DEFAULT_AVATAR)
  785. .isPublicShow(true)
  786. .build());
  787. }
  788. public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId, boolean safeFlag, Set<Tag> tags) {
  789. Objects.requireNonNull(asset, "原藏品不能为空");
  790. Objects.requireNonNull(toUser, "转让人不能为空");
  791. Objects.requireNonNull(reason, "转让原因不能为空");
  792. try {
  793. if (asset.getType() == CollectionType.DOMAIN) {
  794. String domainName = asset.getName().substring(9);
  795. DomainOrder domainOrder = domainOrderRepo
  796. .findFirstByDomainNameAndOrderStatus(domainName, OrderStatus.FINISH);
  797. if (ObjectUtils.isNotEmpty(domainOrder)) {
  798. domainOrder.setOpenHyperLink(false);
  799. domainOrder.setHyperLinkType(null);
  800. domainOrder.setAddress(null);
  801. domainOrder.setCurrentOwnerId(null);
  802. }
  803. }
  804. //铸造清除超链
  805. if (asset.getPublicCollectionId() != null) {
  806. List<DomainOrder> filteredDomainOrders = domainOrderRepo.findAllByHyperLinkType(HyperLinkType.COLLECTION);
  807. for (DomainOrder filteredDomainOrder : filteredDomainOrders) {
  808. String url = filteredDomainOrder.getAddress();
  809. int secondSlashIndex = url.indexOf('/', url.indexOf('/') + 1);
  810. if (url.length() > secondSlashIndex + 1) {
  811. String secondNumber = url.substring(secondSlashIndex + 1);
  812. if (!secondNumber.isBlank()) {
  813. if (asset.getPublicCollectionId() != null && asset.getPublicCollectionId().equals(Long.parseLong(secondNumber))) {
  814. filteredDomainOrder.setOpenHyperLink(false);
  815. filteredDomainOrder.setHyperLinkType(null);
  816. filteredDomainOrder.setAddress(null);
  817. filteredDomainOrder.setCurrentOwnerId(null);
  818. domainOrderRepo.save(filteredDomainOrder);
  819. }
  820. }
  821. }
  822. }
  823. }
  824. } catch (Exception e) {
  825. log.error("超链报错:assetId" + asset.getId(), e);
  826. }
  827. User newOwner = toUser;
  828. if (safeFlag) {
  829. newOwner = createFakeUser();
  830. }
  831. Asset newAsset = new Asset();
  832. BeanUtils.copyProperties(asset, newAsset);
  833. newAsset.setId(null);
  834. newAsset.setUserId(toUser.getId());
  835. newAsset.setOwner(newOwner.getNickname());
  836. newAsset.setOwnerId(newOwner.getId());
  837. newAsset.setOwnerAvatar(newOwner.getAvatar());
  838. newAsset.setPublicShow(false);
  839. newAsset.setConsignment(false);
  840. newAsset.setPublicCollectionId(null);
  841. newAsset.setTags(new HashSet<>(tags));
  842. asset.setTags(new HashSet<>());
  843. newAsset.setStatus(AssetStatus.NORMAL);
  844. newAsset.setPrice(price);
  845. newAsset.setSellPrice(null);
  846. newAsset.setOrderId(orderId);
  847. newAsset.setOasisId(asset.getOasisId());
  848. newAsset.setFromAssetId(asset.getId());
  849. newAsset.setType(CollectionType.DEFAULT);
  850. if (asset.getType() == CollectionType.DOMAIN) {
  851. newAsset.setType(CollectionType.DOMAIN);
  852. }
  853. newAsset.setSource(TransferReason.GIFT == reason ? AssetSource.GIFT : AssetSource.TRANSFER);
  854. newAsset.setSafeFlag(safeFlag);
  855. newAsset.setHoldDays(asset.getOldHoldDays());
  856. if (asset.getType().equals(CollectionType.PICTURE)) {
  857. newAsset.setType(CollectionType.PICTURE);
  858. newAsset.setHoldDays(0);
  859. }
  860. Long savedId = assetRepo.saveAndFlush(newAsset).getId();
  861. if (asset.getType().equals(CollectionType.PICTURE)) {
  862. newAsset.setType(CollectionType.PICTURE);
  863. PhotoAsset photoAsset = photoAssetRepo.findFirstByCreateAssetId(asset.getId());
  864. photoAsset.setGifted(true);
  865. photoAsset.setOwnerId(toUser.getId());
  866. photoAsset.setCreateAssetId(savedId);
  867. photoAssetRepo.save(photoAsset);
  868. }
  869. TokenHistory tokenHistory = TokenHistory.builder()
  870. .tokenId(asset.getTokenId())
  871. .fromUser(asset.getOwner())
  872. .fromUserId(asset.getOwnerId())
  873. .fromAvatar(asset.getOwnerAvatar())
  874. .toUser(newOwner.getNickname())
  875. .toUserId(newOwner.getId())
  876. .toAvatar(newOwner.getAvatar())
  877. .operation(reason.getDescription())
  878. .price(TransferReason.GIFT == reason ? null : price)
  879. .companyId(asset.getCompanyId())
  880. .build();
  881. tokenHistoryRepo.save(tokenHistory);
  882. //购买者加绿洲石
  883. if (TransferReason.TRANSFER.equals(reason) || TransferReason.AUCTION.equals(reason)) {
  884. rockRecordService.addRock(newOwner.getId(), price, "购买");
  885. }
  886. asset.setPublicShow(false);
  887. asset.setConsignment(false);
  888. asset.setPublicCollectionId(null);
  889. switch (reason) {
  890. case GIFT:
  891. asset.setStatus(AssetStatus.GIFTED);
  892. break;
  893. case AUCTION:
  894. asset.setStatus(AssetStatus.AUCTIONED);
  895. break;
  896. case TRANSFER:
  897. asset.setStatus(AssetStatus.TRANSFERRED);
  898. break;
  899. case ASK:
  900. asset.setStatus(AssetStatus.TRANSFERRED);
  901. break;
  902. }
  903. asset.setOwner(newOwner.getNickname());
  904. asset.setOwnerId(newOwner.getId());
  905. asset.setOwnerAvatar(newOwner.getAvatar());
  906. assetRepo.saveAndFlush(asset);
  907. //vip权限转让
  908. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(asset.getCollectionId());
  909. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  910. if (collectionPrivilege.isVip()) {
  911. //更新vip信息
  912. userRepo.updateVipPurchase(toUser.getId(), 1);
  913. userRepo.updateVipPurchase(asset.getUserId(), 0);
  914. }
  915. }
  916. }
  917. public List<TokenHistory> tokenHistory(String tokenId, Long assetId) {
  918. if (tokenId == null) {
  919. if (assetId == null) return new ArrayList<>();
  920. tokenId = assetRepo.findById(assetId).map(Asset::getTokenId).orElse(null);
  921. }
  922. if (tokenId == null) return new ArrayList<>();
  923. return tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(tokenId);
  924. }
  925. public Page<UserHistory> userHistory(Long userId, Long toUserId, Long fromUserId, Pageable pageable) {
  926. Page<TokenHistory> page;
  927. if (ObjectUtils.isNotEmpty(toUserId)) {
  928. page = tokenHistoryRepo.userHistoryTo(userId, toUserId, pageable);
  929. } else if (ObjectUtils.isNotEmpty(fromUserId)) {
  930. page = tokenHistoryRepo.userHistoryFrom(userId, fromUserId, pageable);
  931. } else {
  932. page = tokenHistoryRepo.userHistory(userId, pageable);
  933. }
  934. Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
  935. List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
  936. return page.map(tokenHistory -> {
  937. UserHistory userHistory = new UserHistory();
  938. BeanUtils.copyProperties(tokenHistory, userHistory);
  939. Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
  940. .findAny();
  941. userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
  942. userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
  943. switch (tokenHistory.getOperation()) {
  944. case "出售":
  945. case "转让":
  946. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
  947. break;
  948. case "转赠":
  949. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
  950. break;
  951. default:
  952. userHistory.setDescription(tokenHistory.getOperation());
  953. }
  954. return userHistory;
  955. });
  956. }
  957. public Page<UserHistory> userHistory(Long userId, PageQuery pageQuery) {
  958. Page<TokenHistory> page = tokenHistoryRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
  959. List<Predicate> and = JpaUtils
  960. .toPredicates(pageQuery, TokenHistory.class, root, criteriaQuery, criteriaBuilder);
  961. Map<String, Object> query = pageQuery.getQuery();
  962. if (ObjectUtils.isEmpty(query.get("toUserId")) && ObjectUtils.isEmpty(query.get("fromUserId"))) {
  963. and.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("toUserId"), userId), criteriaBuilder
  964. .equal(root.get("fromUserId"), userId)));
  965. } else {
  966. if (ObjectUtils.isNotEmpty(query.get("toUserId"))) {
  967. and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("toUserId"), userId)));
  968. } else {
  969. and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("fromUserId"), userId)));
  970. }
  971. }
  972. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  973. }), JpaUtils.toPageRequest(pageQuery));
  974. Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
  975. List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
  976. return page.map(tokenHistory -> {
  977. UserHistory userHistory = new UserHistory();
  978. BeanUtils.copyProperties(tokenHistory, userHistory);
  979. Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
  980. .findAny();
  981. userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
  982. userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
  983. switch (tokenHistory.getOperation()) {
  984. case "出售":
  985. case "转让":
  986. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
  987. break;
  988. case "转赠":
  989. userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
  990. break;
  991. default:
  992. userHistory.setDescription(tokenHistory.getOperation());
  993. }
  994. return userHistory;
  995. });
  996. }
  997. public String mint(LocalDateTime time) {
  998. if (time == null) {
  999. time = LocalDateTime.now();
  1000. }
  1001. for (Asset asset : assetRepo.toMint(time)) {
  1002. rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
  1003. }
  1004. return "ok";
  1005. }
  1006. @Cacheable(value = "userStat", key = "#userId")
  1007. public Map<String, BigDecimal> breakdown(Long userId) {
  1008. // List<TokenHistory> page = tokenHistoryRepo.userHistory(userId);
  1009. // BigDecimal sale = page.stream()
  1010. // .filter(th -> th.getFromUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
  1011. // .map(TokenHistory::getPrice)
  1012. // .reduce(BigDecimal.ZERO, BigDecimal::add);
  1013. // BigDecimal buy = page.stream()
  1014. // .filter(th -> th.getToUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
  1015. // .map(TokenHistory::getPrice)
  1016. // .reduce(BigDecimal.ZERO, BigDecimal::add);
  1017. Map<String, BigDecimal> map = new HashMap<>();
  1018. map.put("sale", tokenHistoryRepo.userSale(userId));
  1019. map.put("buy", rockRecordService.getRock(userId).getRecord());
  1020. return map;
  1021. }
  1022. public void transferCDN() throws ExecutionException, InterruptedException {
  1023. ForkJoinPool customThreadPool = new ForkJoinPool(100);
  1024. customThreadPool.submit(() -> {
  1025. collectionRepo.selectResource().parallelStream().forEach(list -> {
  1026. for (int i = 0; i < list.size(); i++) {
  1027. list.set(i, replaceCDN(list.get(i)));
  1028. }
  1029. collectionRepo.updateCDN(Long.parseLong(list.get(0)),
  1030. list.get(1),
  1031. list.get(2),
  1032. list.get(3),
  1033. list.get(4),
  1034. list.get(5));
  1035. });
  1036. assetRepo.selectResource().parallelStream().forEach(list -> {
  1037. for (int i = 0; i < list.size(); i++) {
  1038. list.set(i, replaceCDN(list.get(i)));
  1039. }
  1040. assetRepo.updateCDN(Long.parseLong(list.get(0)),
  1041. list.get(1),
  1042. list.get(2),
  1043. list.get(3),
  1044. list.get(4),
  1045. list.get(5));
  1046. });
  1047. }).get();
  1048. }
  1049. public String replaceCDN(String url) {
  1050. if (url == null) return null;
  1051. return url.replaceAll("https://raex-meta\\.oss-cn-shenzhen\\.aliyuncs\\.com",
  1052. "https://cdn.raex.vip");
  1053. }
  1054. // @Scheduled(cron = "0 0 0/1 * * ?")
  1055. // public void offTheShelf() {
  1056. // LocalDateTime lastTime = LocalDateTime.now().minusHours(120);
  1057. // Set<Long> assetIds = collectionRepo
  1058. // .findResaleCollectionPriceOver20K(BigDecimal
  1059. // .valueOf(20000L), CollectionSource.TRANSFER, lastTime, true);
  1060. // assetIds.forEach(this::cancelConsignmentBySystem);
  1061. // }
  1062. @Scheduled(cron = "0 0 0/1 * * ?")
  1063. public void offTheShelfAll() {
  1064. LocalDateTime lastTime = LocalDateTime.now().minusDays(15);
  1065. LocalDateTime newRuleStartTime = LocalDateTime.of(2022, 12, 9, 17, 0, 0);
  1066. Set<Long> assetIds = collectionRepo
  1067. .findResaleCollectionOverTime(lastTime, newRuleStartTime);
  1068. LocalDateTime newRuleLastTime = LocalDateTime.now().minusDays(30);
  1069. assetIds.addAll(collectionRepo
  1070. .findResaleCollectionOverTimeV2(newRuleLastTime, newRuleStartTime));
  1071. assetIds.forEach(this::cancelConsignmentBySystem);
  1072. }
  1073. public void cancelConsignmentBySystem(Long id) {
  1074. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  1075. cancelConsignmentBySystem(asset);
  1076. }
  1077. public void cancelConsignmentBySystem(Asset asset) {
  1078. try {
  1079. if (asset.getPublicCollectionId() != null) {
  1080. List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
  1081. if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
  1082. throw new BusinessException("已有订单不可取消");
  1083. }
  1084. collectionRepo.findById(asset.getPublicCollectionId())
  1085. .ifPresent(collection -> {
  1086. collection.setSalable(false);
  1087. collection.setOnShelf(false);
  1088. collectionRepo.save(collection);
  1089. });
  1090. }
  1091. asset.setConsignment(false);
  1092. asset.setPublicShow(false);
  1093. assetRepo.saveAndFlush(asset);
  1094. } catch (Exception e) {
  1095. log.info("自动下架报错,assetId:" + asset.getId());
  1096. }
  1097. }
  1098. // @Cacheable(cacheNames = "fmaa", key = "#userId+'#'+#mintActivityId+'#'+#pageable.hashCode()")
  1099. public PageWrapper<Asset> findMintActivityAssetsWrap(Long userId, Long mintActivityId, Long companyId, Pageable pageable) {
  1100. return PageWrapper.of(findMintActivityAssets(userId, mintActivityId, companyId, pageable));
  1101. }
  1102. public Page<Asset> findMintActivityAssets(Long userId, Long mintActivityId, Long companyId, Pageable pageable) {
  1103. MintActivity mintActivity = mintActivityRepo.findById(mintActivityId).orElse(null);
  1104. if (mintActivity == null) return new PageImpl<>(Collections.emptyList());
  1105. return findMintActivityAssetsCommon(userId, companyId, new CommonMatchDTO(mintActivity.getRule(),
  1106. mintActivity.isAudit(), mintActivity.getCollectionName()), pageable);
  1107. }
  1108. public Page<Asset> findMintActivityAssetsCommon(Long userId, Long companyId, CommonMatchDTO commonMatchDTO, Pageable pageable) {
  1109. if (!commonMatchDTO.isAudit()) {
  1110. Set<Tag> tags = commonMatchDTO.getRule().getTags();
  1111. if (tags.isEmpty()) return new PageImpl<>(Collections.emptyList());
  1112. return assetRepo.findAll((Specification<Asset>) (root, query, criteriaBuilder) ->
  1113. query.distinct(true).where(
  1114. // where userId=some id
  1115. criteriaBuilder.equal(root.get("userId"), userId),
  1116. // and (lockTo is null or (lockTo is not null and lockTo < now))
  1117. criteriaBuilder.or(criteriaBuilder.isNull(root.get("lockTo")),
  1118. criteriaBuilder.and(criteriaBuilder.isNotNull(root.get("lockTo")),
  1119. criteriaBuilder.lessThan(root.get("lockTo"), LocalDateTime.now()))),
  1120. // and status = 'NORMAL'
  1121. criteriaBuilder.equal(root.get("status"), AssetStatus.NORMAL),
  1122. criteriaBuilder.equal(root.get("consignment"), false),
  1123. // and has some tagId
  1124. root.join("tags").get("id").in(tags.stream().map(Tag::getId).toArray()))
  1125. .getRestriction(), pageable);
  1126. } else {
  1127. return assetRepo
  1128. .findByUserIdAndStatusAndCompanyIdAndNameLikeAndConsignment(userId, AssetStatus.NORMAL, companyId,
  1129. "%" + commonMatchDTO.getCollectionName() + "%", pageable, false);
  1130. }
  1131. }
  1132. public void destroy(Long id, Long userId, String tradeCode, OperationSource source) {
  1133. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  1134. if (!asset.getUserId().equals(userId)) {
  1135. throw new BusinessException("此藏品不属于你");
  1136. }
  1137. if (asset.getStatus() != AssetStatus.NORMAL) {
  1138. throw new BusinessException("当前状态不可销毁");
  1139. }
  1140. if (asset.isPublicShow()) {
  1141. throw new BusinessException("请先取消公开展示");
  1142. // cancelPublic(asset);
  1143. }
  1144. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  1145. if (StringUtils.isEmpty(user.getTradeCode())) {
  1146. throw new BusinessException("未设置交易密码");
  1147. }
  1148. if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
  1149. throw new BusinessException("交易密码错误");
  1150. }
  1151. User toUser = userRepo.findById(Constants.BLACK_HOLE_USER_ID).orElseThrow(new BusinessException("无记录"));
  1152. TokenHistory tokenHistory = TokenHistory.builder()
  1153. .tokenId(asset.getTokenId())
  1154. .fromUser(asset.getOwner())
  1155. .fromUserId(asset.getOwnerId())
  1156. .fromAvatar(asset.getOwnerAvatar())
  1157. .toUser(toUser.getNickname())
  1158. .toUserId(toUser.getId())
  1159. .toAvatar(toUser.getAvatar())
  1160. .operation(TransferReason.DESTROY.getDescription())
  1161. .price(null)
  1162. .companyId(asset.getCompanyId())
  1163. .build();
  1164. tokenHistoryRepo.save(tokenHistory);
  1165. asset.setPublicShow(false);
  1166. asset.setConsignment(false);
  1167. asset.setPublicCollectionId(null);
  1168. asset.setStatus(AssetStatus.DESTROYED);
  1169. asset.setOwner(toUser.getNickname());
  1170. asset.setOwnerId(toUser.getId());
  1171. asset.setOwnerAvatar(toUser.getAvatar());
  1172. assetRepo.saveAndFlush(asset);
  1173. //积分记录
  1174. destroyRecordRepo.save(DestroyRecord.builder()
  1175. .userId(userId)
  1176. .assetId(asset.getId())
  1177. .name(asset.getName())
  1178. .pic(asset.getPic().get(0).getUrl())
  1179. .record(1)
  1180. .type(RecordType.OBTAIN)
  1181. .companyId(asset.getCompanyId())
  1182. .source(source)
  1183. .build());
  1184. //加积分
  1185. userRepo.addDestroyPoint(userId, 1);
  1186. }
  1187. @Transactional
  1188. public void metaDestroyWithoutTradeCode(MetaDestroyParam metaDestroyParam, Long userId, OperationSource source) {
  1189. List<Long> ids = metaDestroyParam.getIds();
  1190. String remark = metaDestroyParam.getRemark();
  1191. if (CollectionUtils.isEmpty(ids)) {
  1192. throw new BusinessException("要销毁的藏品id为空");
  1193. }
  1194. ids.forEach(id -> {
  1195. destroyWithoutTradeCode(id, userId, source, remark);
  1196. });
  1197. }
  1198. public void destroyWithoutTradeCode(Long id, Long userId, OperationSource source, String remark) {
  1199. Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  1200. if (!asset.getUserId().equals(userId)) {
  1201. throw new BusinessException("此藏品不属于该用户");
  1202. }
  1203. if (OperationSource.META.equals(source)) {
  1204. if (asset.getStatus() != AssetStatus.NORMAL) {
  1205. throw new BusinessException("当前状态不可销毁");
  1206. }
  1207. } else {
  1208. if (asset.getStatus() != AssetStatus.DESTROYING) {
  1209. throw new BusinessException("当前状态不可销毁");
  1210. }
  1211. }
  1212. if (asset.isPublicShow()) {
  1213. throw new BusinessException("请先取消公开展示");
  1214. // cancelPublic(asset);
  1215. }
  1216. User toUser = userRepo.findById(Constants.BLACK_HOLE_USER_ID).orElseThrow(new BusinessException("无记录"));
  1217. TokenHistory tokenHistory = TokenHistory.builder()
  1218. .tokenId(asset.getTokenId())
  1219. .fromUser(asset.getOwner())
  1220. .fromUserId(asset.getOwnerId())
  1221. .fromAvatar(asset.getOwnerAvatar())
  1222. .toUser(toUser.getNickname())
  1223. .toUserId(toUser.getId())
  1224. .toAvatar(toUser.getAvatar())
  1225. .operation(TransferReason.DESTROY.getDescription())
  1226. .price(null)
  1227. .companyId(asset.getCompanyId())
  1228. .build();
  1229. tokenHistoryRepo.save(tokenHistory);
  1230. asset.setPublicShow(false);
  1231. asset.setConsignment(false);
  1232. asset.setPublicCollectionId(null);
  1233. asset.setStatus(AssetStatus.DESTROYED);
  1234. asset.setOwner(toUser.getNickname());
  1235. asset.setOwnerId(toUser.getId());
  1236. asset.setOwnerAvatar(toUser.getAvatar());
  1237. assetRepo.saveAndFlush(asset);
  1238. //积分记录
  1239. DestroyRecord destroyRecord = DestroyRecord.builder()
  1240. .userId(userId)
  1241. .assetId(asset.getId())
  1242. .name(asset.getName())
  1243. .record(1)
  1244. .type(RecordType.OBTAIN)
  1245. .companyId(asset.getCompanyId())
  1246. .source(source)
  1247. .remark(remark)
  1248. .build();
  1249. destroyRecord
  1250. .setPic("video/mp4".equals(asset.getPic().get(0).getType()) ? asset.getPic().get(0).getThumb() : asset
  1251. .getPic().get(0).getUrl());
  1252. destroyRecordRepo.save(destroyRecord);
  1253. //加积分
  1254. userRepo.addDestroyPoint(userId, 1);
  1255. }
  1256. public double getRoyalties(Long minterId, double royalties, Long userId) {
  1257. if (royalties == 2) {
  1258. return 2;
  1259. }
  1260. LongArrayConverter converter = new LongArrayConverter();
  1261. String discountMinter = sysConfigService.getString("discount_minter");
  1262. List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
  1263. if (minterIds.contains(minterId)) {
  1264. String discountCollection = sysConfigService.getString("discount_collection");
  1265. List<Long> collectionIds = converter.convertToEntityAttribute(discountCollection);
  1266. Long assetId = assetRepo.findDiscount(userId, collectionIds);
  1267. if (ObjectUtils.isNotEmpty(assetId)) {
  1268. return 2;
  1269. }
  1270. }
  1271. return royalties;
  1272. }
  1273. public double getServicecharge(double servicecharge, Long userId) {
  1274. // if (servicecharge == 3) {
  1275. // return 3;
  1276. // }
  1277. LongArrayConverter converter = new LongArrayConverter();
  1278. // String discountMinter = sysConfigService.getString("discount_minter");
  1279. // List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
  1280. // if (minterIds.contains(minterId)) {
  1281. String discountCollection = sysConfigService.getString("discount_charge");
  1282. List<Long> collectionIds = converter.convertToEntityAttribute(discountCollection);
  1283. Long assetId = assetRepo.findDiscount(userId, collectionIds);
  1284. if (ObjectUtils.isNotEmpty(assetId)) {
  1285. return 3;
  1286. }
  1287. // }
  1288. return servicecharge;
  1289. }
  1290. public double getDomainServiceCharge(Long userId) {
  1291. // if (servicecharge == 3) {
  1292. // return 3;
  1293. // }
  1294. // LongArrayConverter converter = new LongArrayConverter();
  1295. // String discountMinter = sysConfigService.getString("discount_minter");
  1296. // List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
  1297. // if (minterIds.contains(minterId)) {
  1298. String discountCollection = sysConfigService.getString("domain_discount");
  1299. JSONObject json = JSONObject.parseObject(discountCollection);
  1300. Set<String> keys = json.keySet();
  1301. List<Long> collectionIds = keys.stream().map(Long::parseLong).collect(toList());
  1302. Set<Long> holdCollections = assetRepo.findDiscounts(userId, collectionIds);
  1303. double result = sysConfigService.getBigDecimal("domain_service_charge").doubleValue();
  1304. if (holdCollections.size() > 0) {
  1305. for (Long id : holdCollections) {
  1306. double discount = json.getDouble(id.toString());
  1307. if (discount < result) {
  1308. result = discount;
  1309. }
  1310. }
  1311. }
  1312. // }
  1313. return result;
  1314. }
  1315. @Async
  1316. public void hcChain() throws ExecutionException, InterruptedException {
  1317. new ForkJoinPool(1000).submit(() -> {
  1318. AtomicInteger num = new AtomicInteger();
  1319. assetRepo.findByStatus(AssetStatus.NORMAL).parallelStream()
  1320. .forEach(asset -> {
  1321. if (asset.getHcTxHash() == null) {
  1322. User user = userRepo.findById(asset.getUserId()).orElse(null);
  1323. if (user != null) {
  1324. if (user.getHcChainAddress() == null) {
  1325. user.setHcChainAddress(hcChainService.createAccount(asset.getUserId()));
  1326. }
  1327. NFT nft = hcChainService.mint(user.getHcChainAddress(), asset.getTokenId());
  1328. asset.setHcTokenId(nft.getTokenId());
  1329. asset.setHcTxHash(nft.getTxHash());
  1330. asset.setGasUsed(nft.getGasUsed());
  1331. assetRepo.saveAndFlush(asset);
  1332. }
  1333. }
  1334. log.info("hcChain:" + num.getAndIncrement());
  1335. });
  1336. }).get();
  1337. }
  1338. public void lockAsset(Long userId, Long assetId, Duration duration) {
  1339. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  1340. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("藏品不存在"));
  1341. if (!asset.getUserId().equals(userId)) {
  1342. throw new BusinessException("无权限");
  1343. }
  1344. if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
  1345. throw new BusinessException("已是锁仓状态");
  1346. }
  1347. if (asset.getType() == CollectionType.SHOWROOM) {
  1348. throw new BusinessException("展厅不可锁定");
  1349. }
  1350. if (asset.getStatus() != AssetStatus.NORMAL) {
  1351. throw new BusinessException("当前状态不可锁定");
  1352. }
  1353. if (asset.isPublicShow() || asset.isConsignment()) {
  1354. throw new BusinessException("请先取消展示和寄售");
  1355. }
  1356. if (duration.compareTo(Duration.parse("P1D")) < 0) {
  1357. throw new BusinessException("最小锁定1天");
  1358. }
  1359. asset.setLockAt(LocalDateTime.now());
  1360. asset.setLockTo(asset.getLockAt().plus(duration));
  1361. assetRepo.saveAndFlush(asset);
  1362. assetLockRepo.save(AssetLock.builder()
  1363. .userId(userId)
  1364. .phone(user.getPhone())
  1365. .nickname(user.getNickname())
  1366. .assetId(assetId)
  1367. .name(asset.getName())
  1368. .number(asset.getNumber())
  1369. .lockAt(asset.getLockAt())
  1370. .lockTo(asset.getLockTo())
  1371. .duration(duration)
  1372. .build());
  1373. }
  1374. public List<TransactionTopTenDTO> transactionTopTen() {
  1375. LocalDateTime localDateTime = LocalDateTime.now().plusDays(-7);
  1376. List<Map<String, String>> map = orderRepo.transactionTopTen(localDateTime);
  1377. JSONArray jsonArray = new JSONArray();
  1378. if (CollectionUtil.isEmpty(map)) {
  1379. return null;
  1380. }
  1381. jsonArray.addAll(map);
  1382. List<TransactionTopTenDTO> transactionTopTenDTOS = jsonArray.toJavaList(TransactionTopTenDTO.class);
  1383. if (CollectionUtil.isEmpty(transactionTopTenDTOS)) {
  1384. return null;
  1385. }
  1386. transactionTopTenDTOS.forEach(transactionTopTenDTO -> {
  1387. if (Objects.nonNull(transactionTopTenDTO.getId())) {
  1388. if (transactionTopTenDTO.getSource().equals(CollectionSource.OFFICIAL)) {
  1389. Collection collection = collectionRepo.findById(transactionTopTenDTO.getId()).orElse(null);
  1390. if (Objects.nonNull(collection)) {
  1391. transactionTopTenDTO.setPic(collection.getPic());
  1392. }
  1393. }
  1394. if (transactionTopTenDTO.getSource().equals(CollectionSource.TRANSFER)) {
  1395. Asset asset = assetRepo.findById(transactionTopTenDTO.getId()).orElse(null);
  1396. if (Objects.nonNull(asset)) {
  1397. transactionTopTenDTO.setPic(asset.getPic());
  1398. }
  1399. }
  1400. }
  1401. transactionTopTenDTO.setId(null);
  1402. transactionTopTenDTO.setSource(null);
  1403. });
  1404. return transactionTopTenDTOS;
  1405. }
  1406. public List<FuAssetDTO> queryFu() {
  1407. Long userId = SecurityUtils.getAuthenticatedUser().getId();
  1408. String prefixName = sysConfigService.getString("fu_prefixName");
  1409. if (StringUtils.isBlank(prefixName)) {
  1410. throw new BusinessException("缺少福分类配置");
  1411. }
  1412. String[] split = prefixName.split(",");
  1413. List<String> prefixNames = Arrays.asList(split);
  1414. return assetRepo.queryFu(userId, Constants.META_NORMAL_STATUS, prefixNames);
  1415. }
  1416. }