CollectionService.java 19 KB

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