CollectionService.java 12 KB

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