CollectionService.java 13 KB

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