CollectionService.java 18 KB

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