CollectionService.java 11 KB

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