CollectionService.java 14 KB

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