CollectionService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.izouma.nineth.domain.Collection;
  4. import com.izouma.nineth.domain.*;
  5. import com.izouma.nineth.dto.CollectionDTO;
  6. import com.izouma.nineth.dto.CreateBlindBox;
  7. import com.izouma.nineth.dto.PageQuery;
  8. import com.izouma.nineth.enums.CollectionSource;
  9. import com.izouma.nineth.enums.CollectionType;
  10. import com.izouma.nineth.exception.BusinessException;
  11. import com.izouma.nineth.repo.*;
  12. import com.izouma.nineth.utils.JpaUtils;
  13. import com.izouma.nineth.utils.SecurityUtils;
  14. import lombok.AllArgsConstructor;
  15. import org.apache.commons.collections.MapUtils;
  16. import org.apache.commons.lang3.RandomUtils;
  17. import org.apache.commons.lang3.Range;
  18. import org.apache.commons.lang3.StringUtils;
  19. import org.springframework.beans.BeanUtils;
  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.scheduling.TaskScheduler;
  26. import org.springframework.stereotype.Service;
  27. import javax.annotation.PostConstruct;
  28. import javax.persistence.criteria.Predicate;
  29. import javax.transaction.Transactional;
  30. import java.time.LocalDateTime;
  31. import java.time.ZoneId;
  32. import java.util.*;
  33. import java.util.concurrent.ScheduledFuture;
  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 TaskScheduler taskScheduler;
  44. private CacheService cacheService;
  45. private final Map<Long, ScheduledFuture<?>> tasks = new HashMap<>();
  46. @PostConstruct
  47. public void init() {
  48. List<Collection> collections = collectionRepo.findByScheduleSaleTrueAndOnShelfFalseAndStartTimeBeforeAndDelFalse(LocalDateTime.now());
  49. for (Collection collection : collections) {
  50. onShelfTask(collection);
  51. }
  52. }
  53. public Page<Collection> all(PageQuery pageQuery) {
  54. pageQuery.getQuery().put("del", false);
  55. String type = MapUtils.getString(pageQuery.getQuery(), "type", "DEFAULT");
  56. pageQuery.getQuery().remove("type");
  57. Specification<Collection> specification = JpaUtils.toSpecification(pageQuery, Collection.class);
  58. PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
  59. if (pageRequest.getSort().stream().noneMatch(order -> order.getProperty().equals("createdAt"))) {
  60. pageRequest = PageRequest.of(pageRequest.getPageNumber(), pageQuery.getSize(),
  61. pageRequest.getSort().and(Sort.by("createdAt").descending()));
  62. }
  63. specification = specification.and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  64. List<Predicate> and = new ArrayList<>();
  65. if (StringUtils.isNotEmpty(type) && !"all".equalsIgnoreCase(type)) {
  66. try {
  67. if (type.contains(",")) {
  68. and.add(root.get("type")
  69. .in(Arrays.stream(type.split(",")).map(s -> Enum.valueOf(CollectionType.class, s))
  70. .collect(Collectors.toList())));
  71. } else {
  72. and.add(criteriaBuilder.equal(root.get("type"), Enum.valueOf(CollectionType.class, type)));
  73. }
  74. } catch (Exception e) {
  75. }
  76. }
  77. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  78. });
  79. return collectionRepo.findAll(specification, pageRequest);
  80. }
  81. public Collection create(Collection record) {
  82. User minter = userRepo.findById(record.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  83. record.setMinter(minter.getNickname());
  84. record.setMinterId(minter.getId());
  85. record.setMinterAvatar(minter.getAvatar());
  86. record.setOwner(minter.getNickname());
  87. record.setOwnerId(minter.getId());
  88. record.setOwnerAvatar(minter.getAvatar());
  89. record.setStock(record.getTotal());
  90. record.setSale(0);
  91. if (record.isScheduleSale()) {
  92. if (record.getStartTime() == null) {
  93. throw new BusinessException("请填写定时发布时间");
  94. }
  95. if (record.getStartTime().isBefore(LocalDateTime.now())) {
  96. record.setOnShelf(true);
  97. record.setSalable(true);
  98. record.setStartTime(null);
  99. }
  100. }
  101. record = collectionRepo.save(record);
  102. onShelfTask(record);
  103. return record;
  104. }
  105. public Collection update(Collection record) {
  106. collectionRepo.update(record.getId(), record.isOnShelf(), record.isSalable(),
  107. record.getStartTime(), record.isScheduleSale(), record.getSort(),
  108. record.getDetail(), JSON.toJSONString(record.getPrivileges()),
  109. JSON.toJSONString(record.getProperties()), JSON.toJSONString(record.getModel3d()));
  110. record = collectionRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
  111. onShelfTask(record);
  112. return record;
  113. }
  114. private void onShelfTask(Collection record) {
  115. ScheduledFuture<?> task = tasks.get(record.getId());
  116. if (task != null) {
  117. if (!task.cancel(true)) {
  118. return;
  119. }
  120. }
  121. if (record.isScheduleSale()) {
  122. if (record.getStartTime().minusSeconds(2).isAfter(LocalDateTime.now())) {
  123. Date date = Date.from(record.getStartTime().atZone(ZoneId.systemDefault()).toInstant());
  124. ScheduledFuture<?> future = taskScheduler.schedule(() -> {
  125. collectionRepo.scheduleOnShelf(record.getId());
  126. tasks.remove(record.getId());
  127. }, date);
  128. tasks.put(record.getId(), future);
  129. } else {
  130. collectionRepo.scheduleOnShelf(record.getId());
  131. }
  132. }
  133. }
  134. public CollectionDTO toDTO(Collection collection) {
  135. return toDTO(collection, true);
  136. }
  137. public CollectionDTO toDTO(Collection collection, boolean join) {
  138. CollectionDTO collectionDTO = new CollectionDTO();
  139. BeanUtils.copyProperties(collection, collectionDTO);
  140. if (join) {
  141. if (SecurityUtils.getAuthenticatedUser() != null) {
  142. List<Like> list = likeRepo.findByUserIdAndCollectionId(SecurityUtils.getAuthenticatedUser().getId(),
  143. collection.getId());
  144. collectionDTO.setLiked(!list.isEmpty());
  145. if (collection.getType() == CollectionType.BLIND_BOX) {
  146. collectionDTO.setAppointment(appointmentRepo.findFirstByBlindBoxId(collection.getId()).isPresent());
  147. }
  148. }
  149. }
  150. return collectionDTO;
  151. }
  152. public List<CollectionDTO> toDTO(List<Collection> collections) {
  153. List<Like> likes = new ArrayList<>();
  154. List<Appointment> appointments = new ArrayList<>();
  155. if (SecurityUtils.getAuthenticatedUser() != null) {
  156. likes.addAll(likeRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  157. appointments.addAll(appointmentRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  158. }
  159. return collections.stream().parallel().map(collection -> {
  160. CollectionDTO dto = toDTO(collection, false);
  161. if (!likes.isEmpty()) {
  162. dto.setLiked(likes.stream().anyMatch(l -> l.getCollectionId().equals(collection.getId())));
  163. }
  164. if (!appointments.isEmpty()) {
  165. dto.setAppointment(appointments.stream().anyMatch(a -> a.getBlindBoxId().equals(collection.getId())));
  166. }
  167. return dto;
  168. }).collect(Collectors.toList());
  169. }
  170. public Page<CollectionDTO> toDTO(Page<Collection> collections) {
  171. List<CollectionDTO> userDTOS = toDTO(collections.getContent());
  172. return new PageImpl<>(userDTOS, collections.getPageable(), collections.getTotalElements());
  173. }
  174. @Transactional
  175. public Collection createBlindBox(CreateBlindBox createBlindBox) {
  176. Collection blindBox = createBlindBox.getBlindBox();
  177. if (blindBox.getId() != null) {
  178. throw new BusinessException("无法完成此操作");
  179. }
  180. List<Collection> list =
  181. collectionRepo.findAllById(createBlindBox.getItems().stream().map(BlindBoxItem::getCollectionId)
  182. .collect(Collectors.toSet()));
  183. for (BlindBoxItem item : createBlindBox.getItems()) {
  184. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  185. .orElseThrow(new BusinessException("所选藏品不存在"));
  186. if (item.getTotal() > collection.getStock()) {
  187. throw new BusinessException("所选藏品库存不足:" + collection.getName());
  188. }
  189. }
  190. User user = userRepo.findById(blindBox.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  191. blindBox.setMinter(user.getNickname());
  192. blindBox.setMinterId(user.getId());
  193. blindBox.setMinterAvatar(user.getAvatar());
  194. blindBox.setOwner(user.getNickname());
  195. blindBox.setOwnerId(user.getId());
  196. blindBox.setOwnerAvatar(user.getAvatar());
  197. blindBox.setStock(blindBox.getTotal());
  198. blindBox.setSale(0);
  199. collectionRepo.save(blindBox);
  200. for (BlindBoxItem item : createBlindBox.getItems()) {
  201. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  202. .orElseThrow(new BusinessException("所选藏品不存在"));
  203. collection.setStock(collection.getStock() - item.getTotal());
  204. collectionRepo.save(collection);
  205. BlindBoxItem blindBoxItem = new BlindBoxItem();
  206. BeanUtils.copyProperties(collection, blindBoxItem);
  207. blindBoxItem.setId(null);
  208. blindBoxItem.setCollectionId(item.getCollectionId());
  209. blindBoxItem.setSale(0);
  210. blindBoxItem.setTotal(item.getTotal());
  211. blindBoxItem.setStock(item.getTotal());
  212. blindBoxItem.setRare(item.isRare());
  213. blindBoxItem.setBlindBoxId(blindBox.getId());
  214. blindBoxItemRepo.save(blindBoxItem);
  215. }
  216. return blindBox;
  217. }
  218. public void appointment(Long id, Long userId) {
  219. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  220. if (collection.getType() != CollectionType.BLIND_BOX) {
  221. throw new BusinessException("非盲盒,无需预约");
  222. }
  223. if (collection.getStartTime().isBefore(LocalDateTime.now())) {
  224. throw new BusinessException("盲盒已开售,无需预约");
  225. }
  226. appointmentRepo.save(Appointment.builder()
  227. .userId(userId)
  228. .blindBoxId(id)
  229. .build());
  230. }
  231. public BlindBoxItem draw(Long collectionId) {
  232. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(collectionId);
  233. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  234. int c = 0, sum = 0;
  235. for (BlindBoxItem item : items) {
  236. randomRange.put(item, Range.between(c, c + item.getStock()));
  237. c += item.getStock();
  238. sum += item.getStock();
  239. }
  240. int retry = 0;
  241. BlindBoxItem winItem = null;
  242. while (winItem == null) {
  243. retry++;
  244. int rand = RandomUtils.nextInt(0, sum + 1);
  245. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  246. BlindBoxItem item = entry.getKey();
  247. Range<Integer> range = entry.getValue();
  248. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  249. int total = items.stream().filter(i -> !i.isRare())
  250. .mapToInt(BlindBoxItem::getTotal).sum();
  251. int stock = items.stream().filter(i -> !i.isRare())
  252. .mapToInt(BlindBoxItem::getStock).sum();
  253. if (item.isRare()) {
  254. double nRate = stock / (double) total;
  255. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  256. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  257. if (!(nRate > 0.1 && item.getStock() == 1)) {
  258. winItem = item;
  259. }
  260. }
  261. } else {
  262. double nRate = (stock - 1) / (double) total;
  263. double rRate = item.getStock() / (double) item.getTotal();
  264. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  265. winItem = item;
  266. }
  267. }
  268. }
  269. }
  270. if (retry > 100 && winItem == null) {
  271. throw new BusinessException("盲盒抽卡失败");
  272. }
  273. }
  274. winItem.setStock(winItem.getStock() - 1);
  275. winItem.setSale(winItem.getSale() + 1);
  276. blindBoxItemRepo.save(winItem);
  277. return winItem;
  278. }
  279. public synchronized Integer getNextNumber(Long collectionId) {
  280. collectionRepo.increaseNumber(collectionId, 1);
  281. return collectionRepo.getCurrentNumber(collectionId).orElse(0);
  282. }
  283. public synchronized Integer getNextNumber(Collection collection) {
  284. if (collection == null) return 0;
  285. if (collection.getCurrentNumber() == null) {
  286. collection.setCurrentNumber(0);
  287. }
  288. collection.setCurrentNumber(collection.getCurrentNumber() + 1);
  289. collectionRepo.save(collection);
  290. return collection.getCurrentNumber();
  291. }
  292. public void addStock(Long id, int number) {
  293. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  294. if (collection.getSource() != CollectionSource.OFFICIAL) {
  295. throw new BusinessException("用户转售无法增发");
  296. }
  297. if (collection.getType() == CollectionType.BLIND_BOX) {
  298. throw new BusinessException("盲盒无法增发");
  299. }
  300. collection.setStock(collection.getStock() + number);
  301. collection.setTotal(collection.getTotal() + number);
  302. }
  303. }