CollectionService.java 13 KB

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