CollectionService.java 15 KB

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