CollectionService.java 12 KB

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