CollectionService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package com.izouma.nineth.service;
  2. import com.izouma.nineth.domain.*;
  3. import com.izouma.nineth.domain.Collection;
  4. import com.izouma.nineth.dto.CollectionDTO;
  5. import com.izouma.nineth.dto.CreateBlindBox;
  6. import com.izouma.nineth.dto.PageQuery;
  7. import com.izouma.nineth.enums.CollectionSource;
  8. import com.izouma.nineth.enums.CollectionType;
  9. import com.izouma.nineth.exception.BusinessException;
  10. import com.izouma.nineth.repo.*;
  11. import com.izouma.nineth.utils.JpaUtils;
  12. import com.izouma.nineth.utils.SecurityUtils;
  13. import lombok.AllArgsConstructor;
  14. import org.apache.commons.collections.MapUtils;
  15. import org.apache.commons.lang3.RandomUtils;
  16. import org.apache.commons.lang3.Range;
  17. import org.apache.commons.lang3.StringUtils;
  18. import org.springframework.beans.BeanUtils;
  19. import org.springframework.cache.annotation.CacheEvict;
  20. import org.springframework.data.domain.Page;
  21. import org.springframework.data.domain.PageImpl;
  22. import org.springframework.data.domain.PageRequest;
  23. import org.springframework.data.domain.Sort;
  24. import org.springframework.data.jpa.domain.Specification;
  25. import org.springframework.data.redis.core.RedisTemplate;
  26. import org.springframework.scheduling.annotation.Scheduled;
  27. import org.springframework.stereotype.Service;
  28. import javax.persistence.criteria.Predicate;
  29. import javax.transaction.Transactional;
  30. import java.time.LocalDateTime;
  31. import java.util.*;
  32. import java.util.stream.Collectors;
  33. @Service
  34. @AllArgsConstructor
  35. public class CollectionService {
  36. private CollectionRepo collectionRepo;
  37. private LikeRepo likeRepo;
  38. private BlindBoxItemRepo blindBoxItemRepo;
  39. private AppointmentRepo appointmentRepo;
  40. private UserRepo userRepo;
  41. private AssetService assetService;
  42. private RedisTemplate<String, Object> redisTemplate;
  43. @CacheEvict(value = "collection", allEntries = true)
  44. public void clearCache() {
  45. }
  46. public Page<Collection> all(PageQuery pageQuery) {
  47. pageQuery.getQuery().put("del", false);
  48. String type = MapUtils.getString(pageQuery.getQuery(), "type", "DEFAULT");
  49. pageQuery.getQuery().remove("type");
  50. Specification<Collection> specification = JpaUtils.toSpecification(pageQuery, Collection.class);
  51. PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
  52. if (pageRequest.getSort().stream().noneMatch(order -> order.getProperty().equals("createdAt"))) {
  53. pageRequest = PageRequest.of(pageRequest.getPageNumber(), pageQuery.getSize(),
  54. pageRequest.getSort().and(Sort.by("createdAt").descending()));
  55. }
  56. specification = specification.and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  57. List<Predicate> and = new ArrayList<>();
  58. if (StringUtils.isNotEmpty(type) && !"all".equalsIgnoreCase(type)) {
  59. try {
  60. if (type.contains(",")) {
  61. and.add(root.get("type")
  62. .in(Arrays.stream(type.split(",")).map(s -> Enum.valueOf(CollectionType.class, s))
  63. .collect(Collectors.toList())));
  64. } else {
  65. and.add(criteriaBuilder.equal(root.get("type"), Enum.valueOf(CollectionType.class, type)));
  66. }
  67. } catch (Exception e) {
  68. }
  69. }
  70. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  71. });
  72. return collectionRepo.findAll(specification, pageRequest);
  73. }
  74. public Collection create(Collection record) {
  75. User minter = userRepo.findById(record.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  76. record.setMinter(minter.getNickname());
  77. record.setMinterId(minter.getId());
  78. record.setMinterAvatar(minter.getAvatar());
  79. record.setOwner(minter.getNickname());
  80. record.setOwnerId(minter.getId());
  81. record.setOwnerAvatar(minter.getAvatar());
  82. record.setStock(record.getTotal());
  83. record.setSale(0);
  84. if (record.isScheduleSale()) {
  85. if (record.getStartTime() == null) {
  86. throw new BusinessException("请填写定时发布时间");
  87. }
  88. record.setOnShelf(record.getStartTime().isBefore(LocalDateTime.now()));
  89. }
  90. return collectionRepo.save(record);
  91. }
  92. public CollectionDTO toDTO(Collection collection) {
  93. return toDTO(collection, true);
  94. }
  95. public CollectionDTO toDTO(Collection collection, boolean join) {
  96. CollectionDTO collectionDTO = new CollectionDTO();
  97. BeanUtils.copyProperties(collection, collectionDTO);
  98. if (join) {
  99. if (SecurityUtils.getAuthenticatedUser() != null) {
  100. List<Like> list = likeRepo.findByUserIdAndCollectionId(SecurityUtils.getAuthenticatedUser().getId(),
  101. collection.getId());
  102. collectionDTO.setLiked(!list.isEmpty());
  103. if (collection.getType() == CollectionType.BLIND_BOX) {
  104. collectionDTO.setAppointment(appointmentRepo.findFirstByBlindBoxId(collection.getId()).isPresent());
  105. }
  106. }
  107. }
  108. return collectionDTO;
  109. }
  110. public List<CollectionDTO> toDTO(List<Collection> collections) {
  111. List<Like> likes = new ArrayList<>();
  112. List<Appointment> appointments = new ArrayList<>();
  113. if (SecurityUtils.getAuthenticatedUser() != null) {
  114. likes.addAll(likeRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  115. appointments.addAll(appointmentRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  116. }
  117. return collections.stream().parallel().map(collection -> {
  118. CollectionDTO dto = toDTO(collection, false);
  119. if (!likes.isEmpty()) {
  120. dto.setLiked(likes.stream().anyMatch(l -> l.getCollectionId().equals(collection.getId())));
  121. }
  122. if (!appointments.isEmpty()) {
  123. dto.setAppointment(appointments.stream().anyMatch(a -> a.getBlindBoxId().equals(collection.getId())));
  124. }
  125. return dto;
  126. }).collect(Collectors.toList());
  127. }
  128. public Page<CollectionDTO> toDTO(Page<Collection> collections) {
  129. List<CollectionDTO> userDTOS = toDTO(collections.getContent());
  130. return new PageImpl<>(userDTOS, collections.getPageable(), collections.getTotalElements());
  131. }
  132. @Transactional
  133. public Collection createBlindBox(CreateBlindBox createBlindBox) {
  134. Collection blindBox = createBlindBox.getBlindBox();
  135. List<Collection> list =
  136. collectionRepo.findAllById(createBlindBox.getItems().stream().map(BlindBoxItem::getCollectionId)
  137. .collect(Collectors.toSet()));
  138. for (BlindBoxItem item : createBlindBox.getItems()) {
  139. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  140. .orElseThrow(new BusinessException("所选藏品不存在"));
  141. if (item.getTotal() > collection.getStock()) {
  142. throw new BusinessException("所选藏品库存不足:" + collection.getName());
  143. }
  144. }
  145. User user = userRepo.findById(blindBox.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  146. blindBox.setMinter(user.getNickname());
  147. blindBox.setMinterId(user.getId());
  148. blindBox.setMinterAvatar(user.getAvatar());
  149. blindBox.setOwner(user.getNickname());
  150. blindBox.setOwnerId(user.getId());
  151. blindBox.setOwnerAvatar(user.getAvatar());
  152. blindBox.setStock(blindBox.getTotal());
  153. blindBox.setSale(0);
  154. collectionRepo.save(blindBox);
  155. for (BlindBoxItem item : createBlindBox.getItems()) {
  156. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  157. .orElseThrow(new BusinessException("所选藏品不存在"));
  158. collection.setStock(collection.getStock() - item.getTotal());
  159. collectionRepo.save(collection);
  160. BlindBoxItem blindBoxItem = new BlindBoxItem();
  161. BeanUtils.copyProperties(collection, blindBoxItem);
  162. blindBoxItem.setId(null);
  163. blindBoxItem.setCollectionId(item.getCollectionId());
  164. blindBoxItem.setSale(0);
  165. blindBoxItem.setTotal(item.getTotal());
  166. blindBoxItem.setStock(item.getTotal());
  167. blindBoxItem.setRare(item.isRare());
  168. blindBoxItem.setBlindBoxId(blindBox.getId());
  169. blindBoxItemRepo.save(blindBoxItem);
  170. }
  171. return blindBox;
  172. }
  173. public void appointment(Long id, Long userId) {
  174. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  175. if (collection.getType() != CollectionType.BLIND_BOX) {
  176. throw new BusinessException("非盲盒,无需预约");
  177. }
  178. if (collection.getStartTime().isBefore(LocalDateTime.now())) {
  179. throw new BusinessException("盲盒已开售,无需预约");
  180. }
  181. appointmentRepo.save(Appointment.builder()
  182. .userId(userId)
  183. .blindBoxId(id)
  184. .build());
  185. }
  186. @Scheduled(fixedRate = 60000)
  187. public void scheduleOnShelf() {
  188. List<Collection> collections = collectionRepo.findByScheduleSaleTrueAndOnShelfFalseAndStartTimeBeforeAndDelFalse(LocalDateTime.now());
  189. for (Collection collection : collections) {
  190. collection.setOnShelf(true);
  191. }
  192. collectionRepo.saveAll(collections);
  193. }
  194. public BlindBoxItem draw(Long collectionId) {
  195. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(collectionId);
  196. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  197. int c = 0, sum = 0;
  198. for (BlindBoxItem item : items) {
  199. randomRange.put(item, Range.between(c, c + item.getStock()));
  200. c += item.getStock();
  201. sum += item.getStock();
  202. }
  203. int retry = 0;
  204. BlindBoxItem winItem = null;
  205. while (winItem == null) {
  206. retry++;
  207. int rand = RandomUtils.nextInt(0, sum + 1);
  208. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  209. BlindBoxItem item = entry.getKey();
  210. Range<Integer> range = entry.getValue();
  211. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  212. int total = items.stream().filter(i -> !i.isRare())
  213. .mapToInt(BlindBoxItem::getTotal).sum();
  214. int stock = items.stream().filter(i -> !i.isRare())
  215. .mapToInt(BlindBoxItem::getStock).sum();
  216. if (item.isRare()) {
  217. double nRate = stock / (double) total;
  218. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  219. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  220. if (!(nRate > 0.1 && item.getStock() == 1)) {
  221. winItem = item;
  222. }
  223. }
  224. } else {
  225. double nRate = (stock - 1) / (double) total;
  226. double rRate = item.getStock() / (double) item.getTotal();
  227. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  228. winItem = item;
  229. }
  230. }
  231. }
  232. }
  233. if (retry > 100 && winItem == null) {
  234. throw new BusinessException("盲盒抽卡失败");
  235. }
  236. }
  237. winItem.setStock(winItem.getStock() - 1);
  238. winItem.setSale(winItem.getSale() + 1);
  239. blindBoxItemRepo.save(winItem);
  240. return winItem;
  241. }
  242. public synchronized Integer getNextNumber(Long collectionId) {
  243. Collection collection = collectionRepo.findById(collectionId).orElse(null);
  244. if (collection == null) return 0;
  245. if (collection.getCurrentNumber() == null) {
  246. collection.setCurrentNumber(0);
  247. }
  248. collection.setCurrentNumber(collection.getCurrentNumber() + 1);
  249. collectionRepo.save(collection);
  250. return collection.getCurrentNumber();
  251. }
  252. public synchronized Integer getNextNumber(Collection collection) {
  253. if (collection == null) return 0;
  254. if (collection.getCurrentNumber() == null) {
  255. collection.setCurrentNumber(0);
  256. }
  257. collection.setCurrentNumber(collection.getCurrentNumber() + 1);
  258. collectionRepo.save(collection);
  259. return collection.getCurrentNumber();
  260. }
  261. public void addStock(Long id, int number) {
  262. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  263. if (collection.getSource() != CollectionSource.OFFICIAL) {
  264. throw new BusinessException("用户转售无法增发");
  265. }
  266. if (collection.getType() == CollectionType.BLIND_BOX) {
  267. throw new BusinessException("盲盒无法增发");
  268. }
  269. collection.setStock(collection.getStock() + number);
  270. collection.setTotal(collection.getTotal() + number);
  271. }
  272. }