CollectionService.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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.getAssignment());
  133. record = collectionRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
  134. onShelfTask(record);
  135. return record;
  136. }
  137. private void onShelfTask(Collection record) {
  138. ScheduledFuture<?> task = tasks.get(record.getId());
  139. if (task != null) {
  140. if (!task.cancel(true)) {
  141. return;
  142. }
  143. }
  144. if (record.isScheduleSale()) {
  145. if (record.getStartTime().minusSeconds(2).isAfter(LocalDateTime.now())) {
  146. Date date = Date.from(record.getStartTime().atZone(ZoneId.systemDefault()).toInstant());
  147. ScheduledFuture<?> future = taskScheduler.schedule(() -> {
  148. collectionRepo.scheduleOnShelf(record.getId(), !record.isScanCode());
  149. tasks.remove(record.getId());
  150. }, date);
  151. tasks.put(record.getId(), future);
  152. } else {
  153. collectionRepo.scheduleOnShelf(record.getId(), !record.isScanCode());
  154. }
  155. }
  156. }
  157. public CollectionDTO toDTO(Collection collection) {
  158. return toDTO(collection, true);
  159. }
  160. public CollectionDTO toDTO(Collection collection, boolean join) {
  161. CollectionDTO collectionDTO = new CollectionDTO();
  162. BeanUtils.copyProperties(collection, collectionDTO);
  163. if (join) {
  164. if (SecurityUtils.getAuthenticatedUser() != null) {
  165. List<Like> list = likeRepo.findByUserIdAndCollectionId(SecurityUtils.getAuthenticatedUser().getId(),
  166. collection.getId());
  167. collectionDTO.setLiked(!list.isEmpty());
  168. if (collection.getType() == CollectionType.BLIND_BOX) {
  169. collectionDTO.setAppointment(appointmentRepo.findFirstByBlindBoxId(collection.getId()).isPresent());
  170. }
  171. }
  172. }
  173. return collectionDTO;
  174. }
  175. public List<CollectionDTO> toDTO(List<Collection> collections) {
  176. List<Like> likes = new ArrayList<>();
  177. List<Appointment> appointments = new ArrayList<>();
  178. if (SecurityUtils.getAuthenticatedUser() != null) {
  179. likes.addAll(likeRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  180. appointments.addAll(appointmentRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  181. }
  182. return collections.stream().parallel().map(collection -> {
  183. CollectionDTO dto = toDTO(collection, false);
  184. if (!likes.isEmpty()) {
  185. dto.setLiked(likes.stream().anyMatch(l -> l.getCollectionId().equals(collection.getId())));
  186. }
  187. if (!appointments.isEmpty()) {
  188. dto.setAppointment(appointments.stream().anyMatch(a -> a.getBlindBoxId().equals(collection.getId())));
  189. }
  190. return dto;
  191. }).collect(Collectors.toList());
  192. }
  193. public Page<CollectionDTO> toDTO(Page<Collection> collections) {
  194. List<CollectionDTO> userDTOS = toDTO(collections.getContent());
  195. return new PageImpl<>(userDTOS, collections.getPageable(), collections.getTotalElements());
  196. }
  197. @Transactional
  198. public Collection createBlindBox(CreateBlindBox createBlindBox) {
  199. Collection blindBox = createBlindBox.getBlindBox();
  200. if (blindBox.getId() != null) {
  201. throw new BusinessException("无法完成此操作");
  202. }
  203. List<Collection> list =
  204. collectionRepo.findAllById(createBlindBox.getItems().stream().map(BlindBoxItem::getCollectionId)
  205. .collect(Collectors.toSet()));
  206. for (BlindBoxItem item : createBlindBox.getItems()) {
  207. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  208. .orElseThrow(new BusinessException("所选藏品不存在"));
  209. if (item.getTotal() > collection.getStock()) {
  210. throw new BusinessException("所选藏品库存不足:" + collection.getName());
  211. }
  212. }
  213. User user = userRepo.findById(blindBox.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  214. blindBox.setMinter(user.getNickname());
  215. blindBox.setMinterId(user.getId());
  216. blindBox.setMinterAvatar(user.getAvatar());
  217. blindBox.setOwner(user.getNickname());
  218. blindBox.setOwnerId(user.getId());
  219. blindBox.setOwnerAvatar(user.getAvatar());
  220. blindBox.setTotal(createBlindBox.getItems().stream().mapToInt(BlindBoxItem::getTotal).sum());
  221. blindBox.setStock(blindBox.getTotal());
  222. blindBox.setSale(0);
  223. collectionRepo.save(blindBox);
  224. createBlindBox.getItems().stream().parallel().forEach(item -> {
  225. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  226. .orElseThrow(new BusinessException("所选藏品不存在"));
  227. decreaseStock(collection.getId(), item.getTotal());
  228. BlindBoxItem blindBoxItem = new BlindBoxItem();
  229. BeanUtils.copyProperties(collection, blindBoxItem);
  230. blindBoxItem.setId(null);
  231. blindBoxItem.setCollectionId(item.getCollectionId());
  232. blindBoxItem.setSale(0);
  233. blindBoxItem.setTotal(item.getTotal());
  234. blindBoxItem.setStock(item.getTotal());
  235. blindBoxItem.setRare(item.isRare());
  236. blindBoxItem.setBlindBoxId(blindBox.getId());
  237. blindBoxItemRepo.save(blindBoxItem);
  238. log.info("createBlindBoxItemSuccess" + blindBoxItem.getId());
  239. });
  240. return blindBox;
  241. }
  242. public void appointment(Long id, Long userId) {
  243. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  244. if (collection.getType() != CollectionType.BLIND_BOX) {
  245. throw new BusinessException("非盲盒,无需预约");
  246. }
  247. if (collection.getStartTime().isBefore(LocalDateTime.now())) {
  248. throw new BusinessException("盲盒已开售,无需预约");
  249. }
  250. appointmentRepo.save(Appointment.builder()
  251. .userId(userId)
  252. .blindBoxId(id)
  253. .build());
  254. }
  255. public synchronized BlindBoxItem draw(Long collectionId) {
  256. long t = System.currentTimeMillis();
  257. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(collectionId);
  258. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  259. int c = 0, sum = 0;
  260. for (BlindBoxItem item : items) {
  261. randomRange.put(item, Range.between(c, c + item.getStock()));
  262. c += item.getStock();
  263. sum += item.getStock();
  264. }
  265. int retry = 0;
  266. BlindBoxItem winItem = null;
  267. while (winItem == null) {
  268. retry++;
  269. int rand = RandomUtils.nextInt(0, sum + 1);
  270. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  271. BlindBoxItem item = entry.getKey();
  272. Range<Integer> range = entry.getValue();
  273. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  274. int total = items.stream().filter(i -> !i.isRare())
  275. .mapToInt(BlindBoxItem::getTotal).sum();
  276. int stock = items.stream().filter(i -> !i.isRare())
  277. .mapToInt(BlindBoxItem::getStock).sum();
  278. if (item.isRare()) {
  279. double nRate = stock / (double) total;
  280. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  281. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  282. if (!(nRate > 0.1 && item.getStock() == 1)) {
  283. winItem = item;
  284. }
  285. }
  286. } else {
  287. double nRate = (stock - 1) / (double) total;
  288. double rRate = item.getStock() / (double) item.getTotal();
  289. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  290. winItem = item;
  291. }
  292. }
  293. }
  294. }
  295. if (retry > 100 && winItem == null) {
  296. throw new BusinessException("盲盒抽卡失败");
  297. }
  298. }
  299. winItem.setStock(winItem.getStock() - 1);
  300. winItem.setSale(winItem.getSale() + 1);
  301. blindBoxItemRepo.save(winItem);
  302. return winItem;
  303. }
  304. public synchronized Integer getNextNumber(Long collectionId) {
  305. collectionRepo.increaseNumber(collectionId, 1);
  306. return collectionRepo.getCurrentNumber(collectionId).orElse(0);
  307. }
  308. public void addStock(Long id, int number) {
  309. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  310. if (collection.getSource() != CollectionSource.OFFICIAL) {
  311. throw new BusinessException("用户转售无法增发");
  312. }
  313. if (collection.getType() == CollectionType.BLIND_BOX) {
  314. throw new BusinessException("盲盒无法增发");
  315. }
  316. increaseStock(id, number);
  317. collectionRepo.increaseTotal(id, number);
  318. }
  319. public Long increaseStock(Long id, int number) {
  320. if (redisTemplate.opsForValue().get("collectionStock::" + id) == null) {
  321. redisTemplate.opsForValue().set("collectionStock::" + id,
  322. Optional.ofNullable(collectionRepo.getStock(id)).orElse(0));
  323. }
  324. Long stock = redisTemplate.opsForValue().increment("collectionStock::" + id, number);
  325. rocketMQTemplate.convertAndSend(generalProperties.getUpdateStockTopic(), id);
  326. return stock;
  327. }
  328. public Long decreaseStock(Long id, int number) {
  329. if (redisTemplate.opsForValue().get("collectionStock::" + id) == null) {
  330. redisTemplate.opsForValue().set("collectionStock::" + id,
  331. Optional.ofNullable(collectionRepo.getStock(id)).orElse(0));
  332. }
  333. Long stock = redisTemplate.opsForValue().decrement("collectionStock::" + id, number);
  334. rocketMQTemplate.convertAndSend(generalProperties.getUpdateStockTopic(), id);
  335. return stock;
  336. }
  337. public Long increaseSale(Long id, int number) {
  338. if (redisTemplate.opsForValue().get("collectionSale::" + id) == null) {
  339. redisTemplate.opsForValue().set("collectionSale::" + id,
  340. Optional.ofNullable(collectionRepo.getSale(id)).orElse(0));
  341. }
  342. Long sale = redisTemplate.opsForValue().increment("collectionSale::" + id, number);
  343. rocketMQTemplate.convertAndSend(generalProperties.getUpdateSaleTopic(), id);
  344. return sale;
  345. }
  346. public Long decreaseSale(Long id, int number) {
  347. if (redisTemplate.opsForValue().get("collectionSale::" + id) == null) {
  348. redisTemplate.opsForValue().set("collectionSale::" + id,
  349. Optional.ofNullable(collectionRepo.getSale(id)).orElse(0));
  350. }
  351. Long sale = redisTemplate.opsForValue().decrement("collectionSale::" + id, number);
  352. rocketMQTemplate.convertAndSend(generalProperties.getUpdateSaleTopic(), id);
  353. return sale;
  354. }
  355. @Debounce(key = "#id", delay = 500)
  356. public void syncStock(Long id) {
  357. Integer stock = (Integer) redisTemplate.opsForValue().get("collectionStock::" + id);
  358. if (stock != null) {
  359. log.info("同步库存信息{}", id);
  360. collectionRepo.updateStock(id, stock);
  361. cacheService.clearCollection(id);
  362. }
  363. }
  364. @Debounce(key = "#id", delay = 500)
  365. public void syncSale(Long id) {
  366. Integer sale = (Integer) redisTemplate.opsForValue().get("collectionSale::" + id);
  367. if (sale != null) {
  368. log.info("同步销量信息{}", id);
  369. collectionRepo.updateSale(id, sale);
  370. cacheService.clearCollection(id);
  371. }
  372. }
  373. }