| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416 |
- package com.izouma.nineth.service;
- import cn.hutool.core.collection.CollectionUtil;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.google.common.collect.Lists;
- import com.google.common.hash.Hashing;
- import com.izouma.nineth.TokenHistory;
- import com.izouma.nineth.config.Constants;
- import com.izouma.nineth.config.GeneralProperties;
- import com.izouma.nineth.converter.LongArrayConverter;
- import com.izouma.nineth.domain.Collection;
- import com.izouma.nineth.domain.*;
- import com.izouma.nineth.dto.*;
- import com.izouma.nineth.enums.*;
- import com.izouma.nineth.exception.BusinessException;
- import com.izouma.nineth.repo.*;
- import com.izouma.nineth.utils.JpaUtils;
- import com.izouma.nineth.utils.SecurityUtils;
- import com.izouma.nineth.utils.TokenUtils;
- import lombok.AllArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.collections.CollectionUtils;
- import org.apache.commons.lang3.ObjectUtils;
- import org.apache.commons.lang3.RandomStringUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.rocketmq.spring.core.RocketMQTemplate;
- import org.springframework.beans.BeanUtils;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.PageImpl;
- import org.springframework.data.domain.PageRequest;
- import org.springframework.data.domain.Pageable;
- import org.springframework.data.jpa.domain.Specification;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
- import javax.persistence.criteria.Predicate;
- import javax.transaction.Transactional;
- import java.math.BigDecimal;
- import java.nio.charset.StandardCharsets;
- import java.time.Duration;
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- import java.time.temporal.ChronoUnit;
- import java.util.*;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ForkJoinPool;
- import java.util.concurrent.atomic.AtomicInteger;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import java.util.stream.Collectors;
- @Service
- @AllArgsConstructor
- @Slf4j
- public class AssetService {
- private AssetRepo assetRepo;
- private UserRepo userRepo;
- private CollectionRepo collectionRepo;
- private OrderRepo orderRepo;
- private TokenHistoryRepo tokenHistoryRepo;
- private SysConfigService sysConfigService;
- private RocketMQTemplate rocketMQTemplate;
- private GeneralProperties generalProperties;
- private ShowroomRepo showroomRepo;
- private ShowCollectionRepo showCollectionRepo;
- private CollectionPrivilegeRepo collectionPrivilegeRepo;
- private PasswordEncoder passwordEncoder;
- private MintActivityRepo mintActivityRepo;
- private DestroyRecordRepo destroyRecordRepo;
- private AirDropService airDropService;
- private HCChainService hcChainService;
- private RockRecordService rockRecordService;
- private RockRecordRepo rockRecordRepo;
- private AssetLockRepo assetLockRepo;
- private UserBalanceService userBalanceService;
- private PhotoAssetRepo photoAssetRepo;
- private NumberSeqRepo numberSeqRepo;
- public Page<Asset> all(PageQuery pageQuery) {
- Map<String, Object> query = pageQuery.getQuery();
- Specification<Asset> specification = JpaUtils.toSpecification(pageQuery, Asset.class);
- PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
- if (query.containsKey("lock")) {
- LocalDateTime now = LocalDateTime.now();
- query.remove("lock");
- specification = specification.and((Specification<Asset>) (root, criteriaQuery, criteriaBuilder) -> {
- List<Predicate> and = new ArrayList<>();
- and.add(criteriaBuilder.greaterThan(root.get("lockTo"), now));
- return criteriaBuilder.and(and.toArray(new Predicate[0]));
- });
- }
- Page<Asset> all = assetRepo.findAll(specification, pageRequest);
- // Map<String, Object> query = pageQuery.getQuery();
- // if (query.containsKey("userId")) {
- // List<Long> orderId = orderRepo
- // .findAllByUserIdAndOpenedFalse(Convert.convert(Long.class, query.get("userId")));
- // return all.map(asset -> {
- // if (orderId.contains(asset.getOrderId())) {
- // asset.setOpened(false);
- // }
- // return asset;
- // });
- // }
- return new PageWrapper<>(all.getContent(), all.getPageable().getPageNumber(),
- all.getPageable().getPageSize(), all.getTotalElements()).toPage();
- }
- public List<AssetDTO> userSummary(PageQuery pageQuery) {
- List<AssetDTO> assetDTOs = new ArrayList<>();
- // 根据条件查询所有资产
- List<Asset> assets = assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class));
- if (CollectionUtils.isEmpty(assets)) {
- return assetDTOs;
- }
- // 取出资产中未开启盲盒数据
- List<Asset> blindBoxClosedAssets = assets.stream()
- .filter(asset -> !asset.isOpened() && CollectionType.BLIND_BOX
- .equals(asset.getType()))
- .collect(Collectors.toList());
- if (CollectionUtils.isNotEmpty(blindBoxClosedAssets)) {
- blindBoxClosedAssets.forEach(asset -> {
- assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
- });
- // 移除资产中未开启盲盒数据
- assets.removeAll(blindBoxClosedAssets);
- }
- // 取出资产中所有未设置prefixName的值
- List<Asset> prefixNameIsNullAssets = assets.stream()
- .filter(asset -> StringUtils.isBlank(asset.getPrefixName()))
- .collect(Collectors.toList());
- if (CollectionUtils.isNotEmpty(prefixNameIsNullAssets)) {
- prefixNameIsNullAssets.forEach(asset -> {
- assetDTOs.add(AssetDTO.create(Lists.newArrayList(asset)));
- });
- assets.removeAll(prefixNameIsNullAssets);
- }
- if (CollectionUtils.isNotEmpty(assets)) {
- // 取出资产中所有prefixName
- List<String> prefixNames = assets.stream()
- .map(Asset::getPrefixName)
- .distinct()
- .collect(Collectors.toList());
- // 将资产中相同prefixName归类(除未开启盲盒和未设置prefixName)
- prefixNames.forEach(str -> {
- List<Asset> collect = assets.stream()
- .filter(asset -> str.equals(asset.getPrefixName()))
- .collect(Collectors.toList());
- assetDTOs.add(AssetDTO.create(collect));
- });
- }
- return assetDTOs;
- }
- public Asset createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type,
- Integer number, boolean safeFlag) {
- if (collection.isMessNumber() && number != null) {
- number = getMessedNumber(collection.getId(), number, collection.getTotal());
- }
- Asset asset = Asset.create(collection, user);
- asset.setTokenId(TokenUtils.genTokenId());
- asset.setNumber(number);
- asset.setOasisId(collection.getOasisId());
- asset.setOrderId(orderId);
- asset.setPrice(price);
- asset.setPrefixName(collection.getPrefixName());
- asset.setTags(new HashSet<>());
- if (collection.getTags() != null) {
- asset.getTags().addAll(collection.getTags());
- }
- User fakeUser = null;
- if (safeFlag) {
- fakeUser = createFakeUser();
- asset.setOwner(fakeUser.getNickname());
- asset.setOwnerId(fakeUser.getId());
- asset.setOwnerAvatar(fakeUser.getAvatar());
- }
- assetRepo.saveAndFlush(asset);
- tokenHistoryRepo.save(TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(collection.getMinter())
- .fromUserId(collection.getMinterId())
- .fromAvatar(collection.getMinterAvatar())
- .toUser((safeFlag ? fakeUser : user).getNickname())
- .toUserId((safeFlag ? fakeUser : user).getId())
- .toAvatar((safeFlag ? fakeUser : user).getAvatar())
- .operation(type)
- .price(price)
- .companyId(asset.getCompanyId())
- .build());
- //绿洲石
- rockRecordService.addRock(user.getId(), price, "购买");
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- if (asset.getOasisId() != null & asset.getSource().equals(AssetSource.OFFICIAL)) {
- AirDrop airDrop = new AirDrop();
- airDrop.setName("建筑空投展厅");
- airDrop.setCollectionId(207012L);
- List<Long> userIds = new ArrayList<>();
- userIds.add(user.getId());
- List<Long> nums = new ArrayList<>();
- nums.add(1L);
- airDrop.setType(AirDropType.asset);
- List<DropTarget> dropTargets = new ArrayList<>();
- DropTarget dropTarget = new DropTarget();
- dropTarget.setNickname(user.getNickname());
- dropTarget.setNum(1);
- dropTarget.setPhone(user.getPhone());
- dropTarget.setUserId(user.getId());
- dropTargets.add(dropTarget);
- airDrop.setTargets(dropTargets);
- airDrop.setUserIds(userIds);
- airDrop.setNum(nums);
- airDropService.create(airDrop);
- }
- return asset;
- }
- public Asset createAsset(PhotoAsset photoAsset, User user, Long orderId, BigDecimal price, String type,
- Integer number, boolean safeFlag) {
- Asset asset = Asset.create(photoAsset, user);
- asset.setTokenId(TokenUtils.genTokenId());
- asset.setNumber(number);
- asset.setOrderId(orderId);
- asset.setPrice(price);
- asset.setPrefixName("星图");
- asset.setTags(new HashSet<>());
- User fakeUser = null;
- if (safeFlag) {
- fakeUser = createFakeUser();
- asset.setOwner(fakeUser.getNickname());
- asset.setOwnerId(fakeUser.getId());
- asset.setOwnerAvatar(fakeUser.getAvatar());
- }
- assetRepo.saveAndFlush(asset);
- tokenHistoryRepo.save(TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(photoAsset.getUserName())
- .fromUserId(photoAsset.getUserId())
- .fromAvatar(photoAsset.getUserAvatar())
- .toUser((safeFlag ? fakeUser : user).getNickname())
- .toUserId((safeFlag ? fakeUser : user).getId())
- .toAvatar((safeFlag ? fakeUser : user).getAvatar())
- .operation(type)
- .price(price)
- .companyId(asset.getCompanyId())
- .build());
- //绿洲石
- // rockRecordService.addRock(user.getId(), price, "购买");
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- return asset;
- }
- public Asset createAsset(DomainOrder domainOrder, User user, Long orderId, BigDecimal price, String type,
- Integer number, boolean safeFlag) {
- Asset asset = Asset.create(domainOrder, user);
- asset.setTokenId(TokenUtils.genTokenId());
- asset.setNumber(number);
- asset.setOrderId(orderId);
- asset.setPrice(price);
- asset.setStatus(AssetStatus.PENDING);
- if (StringUtils.isNumeric(domainOrder.getPicName())) {
- if (domainOrder.getPicName().length() < 6) {
- asset.setPrefixName("RIDN" + domainOrder.getPicName().length());
- } else {
- asset.setPrefixName("RIDN6");
- }
- } else {
- Pattern p;
- p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");
- Matcher m = p.matcher(domainOrder.getPicName());
- if (m.find()) {
- asset.setPrefixName("RIDC");
- } else {
- if (domainOrder.getPicName().length() < 6) {
- asset.setPrefixName("RID" + domainOrder.getPicName().length());
- } else {
- asset.setPrefixName("RID");
- }
- }
- }
- asset.setTags(new HashSet<>());
- User fakeUser = null;
- if (safeFlag) {
- fakeUser = createFakeUser();
- asset.setOwner(fakeUser.getNickname());
- asset.setOwnerId(fakeUser.getId());
- asset.setOwnerAvatar(fakeUser.getAvatar());
- }
- assetRepo.saveAndFlush(asset);
- tokenHistoryRepo.save(TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(domainOrder.getUserName())
- .fromUserId(domainOrder.getUserId())
- .fromAvatar(domainOrder.getUserAvatar())
- .toUser((safeFlag ? fakeUser : user).getNickname())
- .toUserId((safeFlag ? fakeUser : user).getId())
- .toAvatar((safeFlag ? fakeUser : user).getAvatar())
- .operation(type)
- .price(price)
- .companyId(asset.getCompanyId())
- .build());
- //绿洲石
- // rockRecordService.addRock(user.getId(), price, "购买");
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- return asset;
- }
- public Asset createAsset(TradeAuction tradeAuction, User user, Long orderId, BigDecimal price, String type,
- Integer number, boolean safeFlag) {
- Asset asset = Asset.create(tradeAuction, user);
- asset.setTokenId(TokenUtils.genTokenId());
- asset.setNumber(number);
- asset.setOrderId(orderId);
- asset.setPrice(price);
- asset.setPrefixName("易拍");
- asset.setTags(new HashSet<>());
- User fakeUser = null;
- if (safeFlag) {
- fakeUser = createFakeUser();
- asset.setOwner(fakeUser.getNickname());
- asset.setOwnerId(fakeUser.getId());
- asset.setOwnerAvatar(fakeUser.getAvatar());
- }
- assetRepo.saveAndFlush(asset);
- tokenHistoryRepo.save(TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(tradeAuction.getMinter())
- .fromUserId(Long.valueOf(tradeAuction.getMinterId()))
- .fromAvatar(tradeAuction.getMinterAvatar())
- .toUser((safeFlag ? fakeUser : user).getNickname())
- .toUserId((safeFlag ? fakeUser : user).getId())
- .toAvatar((safeFlag ? fakeUser : user).getAvatar())
- .operation(type)
- .price(null)
- .companyId(asset.getCompanyId())
- .build());
- //绿洲石
- // rockRecordService.addRock(user.getId(), price, "购买");
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- return asset;
- }
- public synchronized int getMessedNumber(Long collectionId, int number, int total) {
- NumberSeq numberSeq = numberSeqRepo.findById(collectionId).orElse(null);
- if (numberSeq == null || numberSeq.getTotal() != total) {
- numberSeq = new NumberSeq();
- numberSeq.setId(collectionId);
- numberSeq.setTotal(total);
- Map<Integer, Integer> map = new HashMap<>();
- for (int i = 0; i < total; i++) {
- map.put(i, Hashing.md5().hashString(collectionId + ":" + i, StandardCharsets.UTF_8).asInt());
- }
- numberSeq.setNumbers(map.entrySet().stream()
- .sorted(Map.Entry.comparingByValue())
- .map(Map.Entry::getKey)
- .collect(Collectors.toList()));
- numberSeqRepo.save(numberSeq);
- }
- return numberSeq.getNumbers().get(number);
- }
- public Asset createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type,
- Integer number, Integer holdDays, boolean safeFlag) {
- Collection blindBox = collectionRepo.findDetailById(winItem.getBlindBoxId())
- .orElseThrow(new BusinessException("盲盒不存在"));
- Collection collection = collectionRepo.findDetailById(winItem.getCollectionId())
- .orElseThrow(new BusinessException("藏品不存在"));
- if (collection.isMessNumber() && number != null) {
- number = getMessedNumber(collection.getId(), number, collection.getTotal());
- }
- winItem.setCollection(collection);
- Asset asset = Asset.create(winItem, user, holdDays);
- if (collection.getType().equals(CollectionType.DOMAIN)) {
- asset.setType(CollectionType.DOMAIN);
- }
- asset.setTokenId(TokenUtils.genTokenId());
- asset.setNumber(number);
- asset.setOasisId(winItem.getOasisId());
- asset.setOrderId(orderId);
- asset.setPrice(price);
- asset.setPrefixName(collection.getPrefixName());
- asset.setEmpower(collection.getEmpower());
- asset.setTags(new HashSet<>());
- if (blindBox.getTags() != null) {
- asset.getTags().addAll(blindBox.getTags());
- }
- if (collection.getTags() != null) {
- asset.getTags().addAll(collection.getTags());
- }
- User fakeUser = null;
- if (safeFlag) {
- fakeUser = createFakeUser();
- asset.setOwner(fakeUser.getNickname());
- asset.setOwnerId(fakeUser.getId());
- asset.setOwnerAvatar(fakeUser.getAvatar());
- }
- assetRepo.saveAndFlush(asset);
- tokenHistoryRepo.save(TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(winItem.getMinter())
- .fromUserId(winItem.getMinterId())
- .fromAvatar(winItem.getMinterAvatar())
- .toUser((safeFlag ? fakeUser : user).getNickname())
- .toUserId((safeFlag ? fakeUser : user).getId())
- .toAvatar((safeFlag ? fakeUser : user).getAvatar())
- .operation(type)
- .price(price)
- .companyId(asset.getCompanyId())
- .build());
- //绿洲石
- rockRecordService.addRock(user.getId(), price, "购买");
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- return asset;
- }
- public void publicShow(Long id) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
- throw new BusinessException("已锁仓,不能上架展示");
- }
- if (asset.isPublicShow()) {
- return;
- }
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可展示");
- }
- User owner = asset.isSafeFlag() ?
- userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
- : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
- Collection collection = Collection.builder()
- .name(asset.getName())
- .pic(asset.getPic())
- .minter(asset.getMinter())
- .minterId(asset.getMinterId())
- .minterAvatar(asset.getMinterAvatar())
- .owner(owner.getNickname())
- .oasisId(asset.getOasisId())
- .ownerId(owner.getId())
- .ownerAvatar(owner.getAvatar())
- .detail(asset.getDetail())
- .type(CollectionType.DEFAULT)
- .source(CollectionSource.TRANSFER)
- .sale(0)
- .stock(1)
- .total(1)
- .onShelf(true)
- .salable(false)
- .price(BigDecimal.valueOf(0))
- .properties(asset.getProperties())
- .canResale(asset.isCanResale())
- .royalties(asset.getRoyalties())
- .serviceCharge(asset.getServiceCharge())
- .assetId(id)
- .number(asset.getNumber())
- .tags(new HashSet<>())
- .prefixName(asset.getPrefixName())
- .companyId(asset.getCompanyId())
- .build();
- if (asset.getTags() != null) {
- collection.getTags().addAll(asset.getTags());
- }
- if (asset.getType().equals(CollectionType.PICTURE)) {
- collection.setType(CollectionType.PICTURE);
- }
- if (asset.getType().equals(CollectionType.DOMAIN)) {
- collection.setType(CollectionType.DOMAIN);
- }
- collectionRepo.save(collection);
- asset.setPublicShow(true);
- asset.setPublicCollectionId(collection.getId());
- assetRepo.saveAndFlush(asset);
- }
- public synchronized void consignment(Long id, BigDecimal price, String tradeCode, boolean safeFlag) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- String mapString = sysConfigService.getString("collection_price");
- if (StringUtils.isNotBlank(mapString)) {
- JSONObject json = JSONObject.parseObject(mapString);
- String assetName = asset.getName();
- json.forEach((k, v) -> {
- if (assetName.contains(k)) {
- Map<String, Object> map = (Map<String, Object>) v;
- BigDecimal max = BigDecimal.valueOf(Double.parseDouble(map.get("maxPrice").toString()));
- BigDecimal min = BigDecimal.valueOf(Double.parseDouble(map.get("minPrice").toString()));
- if (price.compareTo(max) > 0) {
- throw new BusinessException("已经超过藏品最高限价" + max + "元");
- }
- if (price.compareTo(min) < 0) {
- throw new BusinessException("低于藏品最低限价" + min + "元");
- }
- }
- });
- }
- if (Objects.nonNull(asset.getType()) && asset.getType().equals(CollectionType.SHOWROOM)) {
- throw new BusinessException("展厅类型的藏品不能上架");
- }
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- if (asset.getType().equals(CollectionType.PICTURE)) {
- throw new BusinessException("星图藏品不可寄售");
- }
- if (!sysConfigService.getBoolean("domain_transfer")) {
- throw new BusinessException("域名暂不可以寄售");
- }
- if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
- throw new BusinessException("已锁仓,不能寄售");
- }
- List<String> bannedAssets = Arrays.asList(sysConfigService.getString("older_collections").split(",").clone());
- bannedAssets.forEach(name -> {
- if (asset.getName().contains(name)) {
- throw new BusinessException("编年史藏品无法寄售");
- }
- });
- int holdDays = 0;
- if (!asset.getType().equals(CollectionType.DOMAIN)) {
- if (asset.getSource() == AssetSource.GIFT) {
- LocalDateTime localDateTime = asset.getCreatedAt();
- LocalDateTime gift_change_time = LocalDateTime
- .parse(sysConfigService.getString("gift_change_time"), DateTimeFormatter
- .ofPattern("yyyy-MM-dd HH:mm:ss"));
- if (localDateTime.compareTo(gift_change_time) < 0) {
- holdDays = 20;
- } else {
- holdDays = sysConfigService.getInt("gift_days");
- }
- } else {
- if (ObjectUtils.isEmpty(asset.getHoldDays())) {
- holdDays = sysConfigService.getInt("hold_days");
- } else {
- holdDays = asset.getHoldDays();
- }
- }
- } else {
- if (!ObjectUtils.isEmpty(asset.getHoldDays())) {
- holdDays = asset.getHoldDays();
- }
- }
- if (holdDays == 0 && AssetSource.OFFICIAL.equals(asset.getSource())) {
- BigDecimal officialConsignment = sysConfigService.getBigDecimal("OFFICIAL_CONSIGNMENT");
- //天转小时
- int hour = officialConsignment.multiply(new BigDecimal("24")).intValue();
- if (ChronoUnit.HOURS.between(asset.getCreatedAt(), LocalDateTime.now()) < hour) {
- throw new BusinessException("需持有满" + hour + "小时后才能寄售上架");
- }
- }
- if (ChronoUnit.DAYS.between(asset.getCreatedAt(), LocalDateTime.now()) < holdDays) {
- throw new BusinessException("需持有满" + holdDays + "天才能寄售上架");
- }
- User owner;
- if (safeFlag && !asset.isSafeFlag()) {
- owner = createFakeUser();
- asset.setOwner(owner.getNickname());
- asset.setOwnerId(owner.getId());
- asset.setOwnerAvatar(owner.getAvatar());
- asset.setSafeFlag(true);
- tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(asset.getTokenId()).stream()
- .filter(t -> t.getToUserId().equals(asset.getUserId())).findFirst()
- .ifPresent(tokenHistory -> {
- tokenHistory.setToUserId(owner.getId());
- tokenHistory.setToUser(owner.getNickname());
- tokenHistory.setToAvatar(owner.getAvatar());
- tokenHistoryRepo.save(tokenHistory);
- });
- } else {
- owner = asset.isSafeFlag() ?
- userRepo.findById(asset.getOwnerId()).orElseThrow(new BusinessException("用户不存在"))
- : userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
- }
- if (!passwordEncoder.matches(tradeCode, userRepo.findTradeCode(asset.getUserId()))) {
- throw new BusinessException("交易密码错误");
- }
- // if (StringUtils.isBlank(owner.getSettleAccountId())) {
- // throw new BusinessException("请先绑定银行卡");
- // }
- if (asset.isConsignment()) {
- throw new BusinessException("已寄售,请勿重新操作");
- }
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可寄售");
- }
- if (asset.isPublicShow()) {
- cancelPublic(asset);
- }
- //寄售中的展厅需要先删除展厅
- if (CollectionType.SHOWROOM.equals(asset.getType())) {
- if (showroomRepo.findByAssetId(id).isPresent()) {
- throw new BusinessException("请先删除展厅");
- }
- }
- Collection collection = Collection.builder()
- .name(asset.getName())
- .pic(asset.getPic())
- .minter(asset.getMinter())
- .minterId(asset.getMinterId())
- .minterAvatar(asset.getMinterAvatar())
- .owner(owner.getNickname())
- .ownerId(owner.getId())
- .oasisId(asset.getOasisId())
- .ownerAvatar(owner.getAvatar())
- .detail(asset.getDetail())
- .type(CollectionType.DEFAULT)
- .source(CollectionSource.TRANSFER)
- .sale(0)
- .stock(1)
- .total(1)
- .onShelf(true)
- .salable(true)
- .price(price)
- .properties(asset.getProperties())
- .canResale(asset.isCanResale())
- .royalties(asset.getRoyalties())
- .serviceCharge(asset.getServiceCharge())
- .assetId(id)
- .number(asset.getNumber())
- .tags(new HashSet<>())
- .prefixName(asset.getPrefixName())
- .companyId(asset.getCompanyId())
- .build();
- if (asset.getType().equals(CollectionType.DOMAIN)) {
- collection.setType(CollectionType.DOMAIN);
- }
- if (asset.getTags() != null) {
- collection.getTags().addAll(asset.getTags());
- }
- collectionRepo.save(collection);
- asset.setPublicShow(true);
- asset.setConsignment(true);
- asset.setPublicCollectionId(collection.getId());
- asset.setSellPrice(price);
- assetRepo.saveAndFlush(asset);
- }
- public Asset cancelConsignmentAndStore(Long id) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可寄售");
- }
- if (asset.getPublicCollectionId() != null) {
- List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
- if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
- throw new BusinessException("已有订单不可取消");
- }
- collectionRepo.findById(asset.getPublicCollectionId())
- .ifPresent(collection -> {
- collection.setSalable(false);
- collection.setOnShelf(false);
- collectionRepo.save(collection);
- });
- }
- asset.setConsignment(false);
- asset.setPublicShow(false);
- asset.setStatus(AssetStatus.DESTROYING);
- return assetRepo.saveAndFlush(asset);
- }
- public void batchCancelConsignment(String search) {
- List<Asset> onShelf = assetRepo.findOnShelfByNameLike("%" + search + "%");
- onShelf.forEach(this::cancelConsignmentBySystem);
- }
- public void cancelConsignment(Long id) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- cancelConsignment(asset);
- }
- public void cancelConsignment(Asset asset) {
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- if (asset.getPublicCollectionId() != null) {
- List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
- if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
- throw new BusinessException("已有订单不可取消");
- }
- collectionRepo.findById(asset.getPublicCollectionId())
- .ifPresent(collection -> {
- collection.setSalable(false);
- collectionRepo.save(collection);
- });
- }
- asset.setConsignment(false);
- assetRepo.saveAndFlush(asset);
- }
- public void cancelPublic(Long id) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- cancelPublic(asset);
- }
- public void cancelPublic(Asset asset) {
- if (!asset.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())) {
- throw new BusinessException("此藏品不属于你");
- }
- if (!asset.isPublicShow()) {
- return;
- }
- if (asset.isConsignment()) {
- cancelConsignment(asset);
- }
- Collection collection = collectionRepo.findById(asset.getPublicCollectionId())
- .orElseThrow(new BusinessException("无展示记录"));
- collectionRepo.delete(collection);
- // 如果展厅有此藏品
- showCollectionRepo.deleteAllByCollectionId(asset.getPublicCollectionId());
- asset.setPublicShow(false);
- asset.setPublicCollectionId(null);
- assetRepo.saveAndFlush(asset);
- }
- public void usePrivilege(Long assetId, Long privilegeId) {
- Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("无记录"));
- asset.getPrivileges().stream().filter(p -> p.getId().equals(privilegeId)).forEach(p -> {
- if (!p.getName().equals("铸造")) {
- p.setOpened(true);
- p.setOpenTime(LocalDateTime.now());
- p.setOpenedBy(SecurityUtils.getAuthenticatedUser().getId());
- }
- });
- assetRepo.saveAndFlush(asset);
- }
- public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId) {
- transfer(asset, price, toUser, reason, orderId, false, asset.getTags());
- }
- private User createFakeUser() {
- String name = "0x" + RandomStringUtils.randomAlphabetic(8);
- return userRepo.save(User.builder()
- .username(name)
- .nickname(name)
- .avatar(Constants.DEFAULT_AVATAR)
- .isPublicShow(true)
- .build());
- }
- public void transfer(Asset asset, BigDecimal price, User toUser, TransferReason reason, Long orderId, boolean safeFlag, Set<Tag> tags) {
- Objects.requireNonNull(asset, "原藏品不能为空");
- Objects.requireNonNull(toUser, "转让人不能为空");
- Objects.requireNonNull(reason, "转让原因不能为空");
- User newOwner = toUser;
- if (safeFlag) {
- newOwner = createFakeUser();
- }
- Asset newAsset = new Asset();
- BeanUtils.copyProperties(asset, newAsset);
- newAsset.setId(null);
- newAsset.setUserId(toUser.getId());
- newAsset.setOwner(newOwner.getNickname());
- newAsset.setOwnerId(newOwner.getId());
- newAsset.setOwnerAvatar(newOwner.getAvatar());
- newAsset.setPublicShow(false);
- newAsset.setConsignment(false);
- newAsset.setPublicCollectionId(null);
- newAsset.setTags(new HashSet<>(tags));
- asset.setTags(new HashSet<>());
- newAsset.setStatus(AssetStatus.NORMAL);
- newAsset.setPrice(price);
- newAsset.setSellPrice(null);
- newAsset.setOrderId(orderId);
- newAsset.setOasisId(asset.getOasisId());
- newAsset.setFromAssetId(asset.getId());
- newAsset.setType(CollectionType.DEFAULT);
- if (asset.getType() == CollectionType.DOMAIN) {
- newAsset.setType(CollectionType.DOMAIN);
- }
- newAsset.setSource(TransferReason.GIFT == reason ? AssetSource.GIFT : AssetSource.TRANSFER);
- newAsset.setSafeFlag(safeFlag);
- newAsset.setHoldDays(asset.getOldHoldDays());
- if (asset.getType().equals(CollectionType.PICTURE)) {
- newAsset.setType(CollectionType.PICTURE);
- newAsset.setHoldDays(0);
- }
- Long savedId = assetRepo.saveAndFlush(newAsset).getId();
- if (asset.getType().equals(CollectionType.PICTURE)) {
- newAsset.setType(CollectionType.PICTURE);
- PhotoAsset photoAsset = photoAssetRepo.findFirstByCreateAssetId(asset.getId());
- photoAsset.setGifted(true);
- photoAsset.setOwnerId(toUser.getId());
- photoAsset.setCreateAssetId(savedId);
- photoAssetRepo.save(photoAsset);
- }
- TokenHistory tokenHistory = TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(asset.getOwner())
- .fromUserId(asset.getOwnerId())
- .fromAvatar(asset.getOwnerAvatar())
- .toUser(newOwner.getNickname())
- .toUserId(newOwner.getId())
- .toAvatar(newOwner.getAvatar())
- .operation(reason.getDescription())
- .price(TransferReason.GIFT == reason ? null : price)
- .companyId(asset.getCompanyId())
- .build();
- tokenHistoryRepo.save(tokenHistory);
- //购买者加绿洲石
- if (TransferReason.TRANSFER.equals(reason) || TransferReason.AUCTION.equals(reason)) {
- rockRecordService.addRock(newOwner.getId(), price, "购买");
- }
- asset.setPublicShow(false);
- asset.setConsignment(false);
- asset.setPublicCollectionId(null);
- switch (reason) {
- case GIFT:
- asset.setStatus(AssetStatus.GIFTED);
- break;
- case AUCTION:
- asset.setStatus(AssetStatus.AUCTIONED);
- break;
- case TRANSFER:
- asset.setStatus(AssetStatus.TRANSFERRED);
- break;
- case ASK:
- asset.setStatus(AssetStatus.TRANSFERRED);
- break;
- }
- asset.setOwner(newOwner.getNickname());
- asset.setOwnerId(newOwner.getId());
- asset.setOwnerAvatar(newOwner.getAvatar());
- assetRepo.saveAndFlush(asset);
- //vip权限转让
- CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(asset.getCollectionId());
- if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
- if (collectionPrivilege.isVip()) {
- //更新vip信息
- userRepo.updateVipPurchase(toUser.getId(), 1);
- userRepo.updateVipPurchase(asset.getUserId(), 0);
- }
- }
- }
- public List<TokenHistory> tokenHistory(String tokenId, Long assetId) {
- if (tokenId == null) {
- if (assetId == null) return new ArrayList<>();
- tokenId = assetRepo.findById(assetId).map(Asset::getTokenId).orElse(null);
- }
- if (tokenId == null) return new ArrayList<>();
- return tokenHistoryRepo.findByTokenIdOrderByCreatedAtDesc(tokenId);
- }
- public Page<UserHistory> userHistory(Long userId, Long toUserId, Long fromUserId, Pageable pageable) {
- Page<TokenHistory> page;
- if (ObjectUtils.isNotEmpty(toUserId)) {
- page = tokenHistoryRepo.userHistoryTo(userId, toUserId, pageable);
- } else if (ObjectUtils.isNotEmpty(fromUserId)) {
- page = tokenHistoryRepo.userHistoryFrom(userId, fromUserId, pageable);
- } else {
- page = tokenHistoryRepo.userHistory(userId, pageable);
- }
- Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
- List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
- return page.map(tokenHistory -> {
- UserHistory userHistory = new UserHistory();
- BeanUtils.copyProperties(tokenHistory, userHistory);
- Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
- .findAny();
- userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
- userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
- switch (tokenHistory.getOperation()) {
- case "出售":
- case "转让":
- userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
- break;
- case "转赠":
- userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
- break;
- default:
- userHistory.setDescription(tokenHistory.getOperation());
- }
- return userHistory;
- });
- }
- public Page<UserHistory> userHistory(Long userId, PageQuery pageQuery) {
- Page<TokenHistory> page = tokenHistoryRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
- List<Predicate> and = JpaUtils
- .toPredicates(pageQuery, TokenHistory.class, root, criteriaQuery, criteriaBuilder);
- Map<String, Object> query = pageQuery.getQuery();
- if (ObjectUtils.isEmpty(query.get("toUserId")) && ObjectUtils.isEmpty(query.get("fromUserId"))) {
- and.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("toUserId"), userId), criteriaBuilder
- .equal(root.get("fromUserId"), userId)));
- } else {
- if (ObjectUtils.isNotEmpty(query.get("toUserId"))) {
- and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("toUserId"), userId)));
- } else {
- and.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("fromUserId"), userId)));
- }
- }
- return criteriaBuilder.and(and.toArray(new Predicate[0]));
- }), JpaUtils.toPageRequest(pageQuery));
- Set<String> tokenIds = page.stream().map(TokenHistory::getTokenId).collect(Collectors.toSet());
- List<Asset> assets = tokenIds.isEmpty() ? new ArrayList<>() : assetRepo.findByTokenIdIn(tokenIds);
- return page.map(tokenHistory -> {
- UserHistory userHistory = new UserHistory();
- BeanUtils.copyProperties(tokenHistory, userHistory);
- Optional<Asset> asset = assets.stream().filter(a -> a.getTokenId().equals(tokenHistory.getTokenId()))
- .findAny();
- userHistory.setAssetName(asset.map(Asset::getName).orElse(null));
- userHistory.setPic(asset.map(Asset::getPic).orElse(new ArrayList<>()));
- switch (tokenHistory.getOperation()) {
- case "出售":
- case "转让":
- userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "作品交易——买入" : "作品交易——售出");
- break;
- case "转赠":
- userHistory.setDescription(tokenHistory.getToUserId().equals(userId) ? "他人赠送" : "作品赠送");
- break;
- default:
- userHistory.setDescription(tokenHistory.getOperation());
- }
- return userHistory;
- });
- }
- public String mint(LocalDateTime time) {
- if (time == null) {
- time = LocalDateTime.now();
- }
- for (Asset asset : assetRepo.toMint(time)) {
- rocketMQTemplate.syncSend(generalProperties.getMintTopic(), asset.getId());
- }
- return "ok";
- }
- @Cacheable(value = "userStat", key = "#userId")
- public Map<String, BigDecimal> breakdown(Long userId) {
- // List<TokenHistory> page = tokenHistoryRepo.userHistory(userId);
- // BigDecimal sale = page.stream()
- // .filter(th -> th.getFromUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
- // .map(TokenHistory::getPrice)
- // .reduce(BigDecimal.ZERO, BigDecimal::add);
- // BigDecimal buy = page.stream()
- // .filter(th -> th.getToUserId().equals(userId) && ObjectUtils.isNotEmpty(th.getPrice()))
- // .map(TokenHistory::getPrice)
- // .reduce(BigDecimal.ZERO, BigDecimal::add);
- Map<String, BigDecimal> map = new HashMap<>();
- map.put("sale", tokenHistoryRepo.userSale(userId));
- map.put("buy", rockRecordService.getRock(userId).getRecord());
- return map;
- }
- public void transferCDN() throws ExecutionException, InterruptedException {
- ForkJoinPool customThreadPool = new ForkJoinPool(100);
- customThreadPool.submit(() -> {
- collectionRepo.selectResource().parallelStream().forEach(list -> {
- for (int i = 0; i < list.size(); i++) {
- list.set(i, replaceCDN(list.get(i)));
- }
- collectionRepo.updateCDN(Long.parseLong(list.get(0)),
- list.get(1),
- list.get(2),
- list.get(3),
- list.get(4),
- list.get(5));
- });
- assetRepo.selectResource().parallelStream().forEach(list -> {
- for (int i = 0; i < list.size(); i++) {
- list.set(i, replaceCDN(list.get(i)));
- }
- assetRepo.updateCDN(Long.parseLong(list.get(0)),
- list.get(1),
- list.get(2),
- list.get(3),
- list.get(4),
- list.get(5));
- });
- }).get();
- }
- public String replaceCDN(String url) {
- if (url == null) return null;
- return url.replaceAll("https://raex-meta\\.oss-cn-shenzhen\\.aliyuncs\\.com",
- "https://cdn.raex.vip");
- }
- // @Scheduled(cron = "0 0 0/1 * * ?")
- // public void offTheShelf() {
- // LocalDateTime lastTime = LocalDateTime.now().minusHours(120);
- // Set<Long> assetIds = collectionRepo
- // .findResaleCollectionPriceOver20K(BigDecimal
- // .valueOf(20000L), CollectionSource.TRANSFER, lastTime, true);
- // assetIds.forEach(this::cancelConsignmentBySystem);
- // }
- @Scheduled(cron = "0 0 0/1 * * ?")
- public void offTheShelfAll() {
- LocalDateTime lastTime = LocalDateTime.now().minusDays(15);
- LocalDateTime newRuleStartTime = LocalDateTime.of(2022, 12, 9, 17, 0, 0);
- Set<Long> assetIds = collectionRepo
- .findResaleCollectionOverTime(lastTime, newRuleStartTime);
- LocalDateTime newRuleLastTime = LocalDateTime.now().minusDays(30);
- assetIds.addAll(collectionRepo
- .findResaleCollectionOverTimeV2(newRuleLastTime, newRuleStartTime));
- assetIds.forEach(this::cancelConsignmentBySystem);
- }
- public void cancelConsignmentBySystem(Long id) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- cancelConsignmentBySystem(asset);
- }
- public void cancelConsignmentBySystem(Asset asset) {
- try {
- if (asset.getPublicCollectionId() != null) {
- List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
- if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
- throw new BusinessException("已有订单不可取消");
- }
- collectionRepo.findById(asset.getPublicCollectionId())
- .ifPresent(collection -> {
- collection.setSalable(false);
- collection.setOnShelf(false);
- collectionRepo.save(collection);
- });
- }
- asset.setConsignment(false);
- asset.setPublicShow(false);
- assetRepo.saveAndFlush(asset);
- } catch (Exception e) {
- log.info("自动下架报错,assetId:" + asset.getId());
- }
- }
- // @Cacheable(cacheNames = "fmaa", key = "#userId+'#'+#mintActivityId+'#'+#pageable.hashCode()")
- public PageWrapper<Asset> findMintActivityAssetsWrap(Long userId, Long mintActivityId, Long companyId, Pageable pageable) {
- return PageWrapper.of(findMintActivityAssets(userId, mintActivityId, companyId, pageable));
- }
- public Page<Asset> findMintActivityAssets(Long userId, Long mintActivityId, Long companyId, Pageable pageable) {
- MintActivity mintActivity = mintActivityRepo.findById(mintActivityId).orElse(null);
- if (mintActivity == null) return new PageImpl<>(Collections.emptyList());
- return findMintActivityAssetsCommon(userId, companyId, new CommonMatchDTO(mintActivity.getRule(),
- mintActivity.isAudit(), mintActivity.getCollectionName()), pageable);
- }
- public Page<Asset> findMintActivityAssetsCommon(Long userId, Long companyId, CommonMatchDTO commonMatchDTO, Pageable pageable) {
- if (!commonMatchDTO.isAudit()) {
- Set<Tag> tags = commonMatchDTO.getRule().getTags();
- if (tags.isEmpty()) return new PageImpl<>(Collections.emptyList());
- return assetRepo.findAll((Specification<Asset>) (root, query, criteriaBuilder) ->
- query.distinct(true).where(
- // where userId=some id
- criteriaBuilder.equal(root.get("userId"), userId),
- // and (lockTo is null or (lockTo is not null and lockTo < now))
- criteriaBuilder.or(criteriaBuilder.isNull(root.get("lockTo")),
- criteriaBuilder.and(criteriaBuilder.isNotNull(root.get("lockTo")),
- criteriaBuilder.lessThan(root.get("lockTo"), LocalDateTime.now()))),
- // and status = 'NORMAL'
- criteriaBuilder.equal(root.get("status"), AssetStatus.NORMAL),
- criteriaBuilder.equal(root.get("consignment"), false),
- // and has some tagId
- root.join("tags").get("id").in(tags.stream().map(Tag::getId).toArray()))
- .getRestriction(), pageable);
- } else {
- return assetRepo
- .findByUserIdAndStatusAndCompanyIdAndNameLikeAndConsignment(userId, AssetStatus.NORMAL, companyId,
- "%" + commonMatchDTO.getCollectionName() + "%", pageable, false);
- }
- }
- public void destroy(Long id, Long userId, String tradeCode, OperationSource source) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(userId)) {
- throw new BusinessException("此藏品不属于你");
- }
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可销毁");
- }
- if (asset.isPublicShow()) {
- throw new BusinessException("请先取消公开展示");
- // cancelPublic(asset);
- }
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- if (StringUtils.isEmpty(user.getTradeCode())) {
- throw new BusinessException("未设置交易密码");
- }
- if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
- throw new BusinessException("交易密码错误");
- }
- User toUser = userRepo.findById(Constants.BLACK_HOLE_USER_ID).orElseThrow(new BusinessException("无记录"));
- TokenHistory tokenHistory = TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(asset.getOwner())
- .fromUserId(asset.getOwnerId())
- .fromAvatar(asset.getOwnerAvatar())
- .toUser(toUser.getNickname())
- .toUserId(toUser.getId())
- .toAvatar(toUser.getAvatar())
- .operation(TransferReason.DESTROY.getDescription())
- .price(null)
- .companyId(asset.getCompanyId())
- .build();
- tokenHistoryRepo.save(tokenHistory);
- asset.setPublicShow(false);
- asset.setConsignment(false);
- asset.setPublicCollectionId(null);
- asset.setStatus(AssetStatus.DESTROYED);
- asset.setOwner(toUser.getNickname());
- asset.setOwnerId(toUser.getId());
- asset.setOwnerAvatar(toUser.getAvatar());
- assetRepo.saveAndFlush(asset);
- //积分记录
- destroyRecordRepo.save(DestroyRecord.builder()
- .userId(userId)
- .assetId(asset.getId())
- .name(asset.getName())
- .pic(asset.getPic().get(0).getUrl())
- .record(1)
- .type(RecordType.OBTAIN)
- .companyId(asset.getCompanyId())
- .source(source)
- .build());
- //加积分
- userRepo.addDestroyPoint(userId, 1);
- }
- @Transactional
- public void metaDestroyWithoutTradeCode(MetaDestroyParam metaDestroyParam, Long userId, OperationSource source) {
- List<Long> ids = metaDestroyParam.getIds();
- String remark = metaDestroyParam.getRemark();
- if (CollectionUtils.isEmpty(ids)) {
- throw new BusinessException("要销毁的藏品id为空");
- }
- ids.forEach(id -> {
- destroyWithoutTradeCode(id, userId, source, remark);
- });
- }
- public void destroyWithoutTradeCode(Long id, Long userId, OperationSource source, String remark) {
- Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
- if (!asset.getUserId().equals(userId)) {
- throw new BusinessException("此藏品不属于该用户");
- }
- if (OperationSource.META.equals(source)) {
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可销毁");
- }
- } else {
- if (asset.getStatus() != AssetStatus.DESTROYING) {
- throw new BusinessException("当前状态不可销毁");
- }
- }
- if (asset.isPublicShow()) {
- throw new BusinessException("请先取消公开展示");
- // cancelPublic(asset);
- }
- User toUser = userRepo.findById(Constants.BLACK_HOLE_USER_ID).orElseThrow(new BusinessException("无记录"));
- TokenHistory tokenHistory = TokenHistory.builder()
- .tokenId(asset.getTokenId())
- .fromUser(asset.getOwner())
- .fromUserId(asset.getOwnerId())
- .fromAvatar(asset.getOwnerAvatar())
- .toUser(toUser.getNickname())
- .toUserId(toUser.getId())
- .toAvatar(toUser.getAvatar())
- .operation(TransferReason.DESTROY.getDescription())
- .price(null)
- .companyId(asset.getCompanyId())
- .build();
- tokenHistoryRepo.save(tokenHistory);
- asset.setPublicShow(false);
- asset.setConsignment(false);
- asset.setPublicCollectionId(null);
- asset.setStatus(AssetStatus.DESTROYED);
- asset.setOwner(toUser.getNickname());
- asset.setOwnerId(toUser.getId());
- asset.setOwnerAvatar(toUser.getAvatar());
- assetRepo.saveAndFlush(asset);
- //积分记录
- DestroyRecord destroyRecord = DestroyRecord.builder()
- .userId(userId)
- .assetId(asset.getId())
- .name(asset.getName())
- .record(1)
- .type(RecordType.OBTAIN)
- .companyId(asset.getCompanyId())
- .source(source)
- .remark(remark)
- .build();
- destroyRecord
- .setPic("video/mp4".equals(asset.getPic().get(0).getType()) ? asset.getPic().get(0).getThumb() : asset
- .getPic().get(0).getUrl());
- destroyRecordRepo.save(destroyRecord);
- //加积分
- userRepo.addDestroyPoint(userId, 1);
- }
- public double getRoyalties(Long minterId, double royalties, Long userId) {
- if (royalties == 2) {
- return 2;
- }
- LongArrayConverter converter = new LongArrayConverter();
- String discountMinter = sysConfigService.getString("discount_minter");
- List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
- if (minterIds.contains(minterId)) {
- String discountCollection = sysConfigService.getString("discount_collection");
- List<Long> collectionIds = converter.convertToEntityAttribute(discountCollection);
- Long assetId = assetRepo.findDiscount(userId, collectionIds);
- if (ObjectUtils.isNotEmpty(assetId)) {
- return 2;
- }
- }
- return royalties;
- }
- public double getServicecharge(double servicecharge, Long userId) {
- // if (servicecharge == 3) {
- // return 3;
- // }
- LongArrayConverter converter = new LongArrayConverter();
- // String discountMinter = sysConfigService.getString("discount_minter");
- // List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
- // if (minterIds.contains(minterId)) {
- String discountCollection = sysConfigService.getString("discount_charge");
- List<Long> collectionIds = converter.convertToEntityAttribute(discountCollection);
- Long assetId = assetRepo.findDiscount(userId, collectionIds);
- if (ObjectUtils.isNotEmpty(assetId)) {
- return 3;
- }
- // }
- return servicecharge;
- }
- public double getDomainServiceCharge(Long userId) {
- // if (servicecharge == 3) {
- // return 3;
- // }
- // LongArrayConverter converter = new LongArrayConverter();
- // String discountMinter = sysConfigService.getString("discount_minter");
- // List<Long> minterIds = converter.convertToEntityAttribute(discountMinter);
- // if (minterIds.contains(minterId)) {
- String discountCollection = sysConfigService.getString("domain_discount");
- JSONObject json = JSONObject.parseObject(discountCollection);
- Set<String> keys = json.keySet();
- List<Long> collectionIds = keys.stream().map(Long::parseLong).collect(Collectors.toList());
- Set<Long> holdCollections = assetRepo.findDiscounts(userId, collectionIds);
- double result = sysConfigService.getBigDecimal("domain_service_charge").doubleValue();
- if (holdCollections.size() > 0) {
- for (Long id : holdCollections) {
- double discount = json.getDouble(id.toString());
- if (discount < result) {
- result = discount;
- }
- }
- }
- // }
- return result;
- }
- @Async
- public void hcChain() throws ExecutionException, InterruptedException {
- new ForkJoinPool(1000).submit(() -> {
- AtomicInteger num = new AtomicInteger();
- assetRepo.findByStatus(AssetStatus.NORMAL).parallelStream()
- .forEach(asset -> {
- if (asset.getHcTxHash() == null) {
- User user = userRepo.findById(asset.getUserId()).orElse(null);
- if (user != null) {
- if (user.getHcChainAddress() == null) {
- user.setHcChainAddress(hcChainService.createAccount(asset.getUserId()));
- }
- NFT nft = hcChainService.mint(user.getHcChainAddress(), asset.getTokenId());
- asset.setHcTokenId(nft.getTokenId());
- asset.setHcTxHash(nft.getTxHash());
- asset.setGasUsed(nft.getGasUsed());
- assetRepo.saveAndFlush(asset);
- }
- }
- log.info("hcChain:" + num.getAndIncrement());
- });
- }).get();
- }
- public void lockAsset(Long userId, Long assetId, Duration duration) {
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("藏品不存在"));
- if (!asset.getUserId().equals(userId)) {
- throw new BusinessException("无权限");
- }
- if (asset.getLockTo() != null && asset.getLockTo().isAfter(LocalDateTime.now())) {
- throw new BusinessException("已是锁仓状态");
- }
- if (asset.getType() == CollectionType.SHOWROOM) {
- throw new BusinessException("展厅不可锁定");
- }
- if (asset.getStatus() != AssetStatus.NORMAL) {
- throw new BusinessException("当前状态不可锁定");
- }
- if (asset.isPublicShow() || asset.isConsignment()) {
- throw new BusinessException("请先取消展示和寄售");
- }
- if (duration.compareTo(Duration.parse("P1D")) < 0) {
- throw new BusinessException("最小锁定1天");
- }
- asset.setLockAt(LocalDateTime.now());
- asset.setLockTo(asset.getLockAt().plus(duration));
- assetRepo.saveAndFlush(asset);
- assetLockRepo.save(AssetLock.builder()
- .userId(userId)
- .phone(user.getPhone())
- .nickname(user.getNickname())
- .assetId(assetId)
- .name(asset.getName())
- .number(asset.getNumber())
- .lockAt(asset.getLockAt())
- .lockTo(asset.getLockTo())
- .duration(duration)
- .build());
- }
- public List<TransactionTopTenDTO> transactionTopTen() {
- LocalDateTime localDateTime = LocalDateTime.now().plusDays(-7);
- List<Map<String, String>> map = orderRepo.transactionTopTen(localDateTime);
- JSONArray jsonArray = new JSONArray();
- if (CollectionUtil.isEmpty(map)) {
- return null;
- }
- jsonArray.addAll(map);
- List<TransactionTopTenDTO> transactionTopTenDTOS = jsonArray.toJavaList(TransactionTopTenDTO.class);
- if (CollectionUtil.isEmpty(transactionTopTenDTOS)) {
- return null;
- }
- transactionTopTenDTOS.forEach(transactionTopTenDTO -> {
- if (Objects.nonNull(transactionTopTenDTO.getId())) {
- if (transactionTopTenDTO.getSource().equals(CollectionSource.OFFICIAL)) {
- Collection collection = collectionRepo.findById(transactionTopTenDTO.getId()).orElse(null);
- if (Objects.nonNull(collection)) {
- transactionTopTenDTO.setPic(collection.getPic());
- }
- }
- if (transactionTopTenDTO.getSource().equals(CollectionSource.TRANSFER)) {
- Asset asset = assetRepo.findById(transactionTopTenDTO.getId()).orElse(null);
- if (Objects.nonNull(asset)) {
- transactionTopTenDTO.setPic(asset.getPic());
- }
- }
- }
- transactionTopTenDTO.setId(null);
- transactionTopTenDTO.setSource(null);
- });
- return transactionTopTenDTOS;
- }
- public List<FuAssetDTO> queryFu() {
- Long userId = SecurityUtils.getAuthenticatedUser().getId();
- String prefixName = sysConfigService.getString("fu_prefixName");
- if (StringUtils.isBlank(prefixName)) {
- throw new BusinessException("缺少福分类配置");
- }
- String[] split = prefixName.split(",");
- List<String> prefixNames = Arrays.asList(split);
- return assetRepo.queryFu(userId, Constants.META_NORMAL_STATUS, prefixNames);
- }
- }
|