CollectionService.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. package com.izouma.nineth.service;
  2. import cn.hutool.core.convert.Convert;
  3. import com.izouma.nineth.TokenHistory;
  4. import com.izouma.nineth.annotations.Debounce;
  5. import com.izouma.nineth.config.Constants;
  6. import com.izouma.nineth.config.GeneralProperties;
  7. import com.izouma.nineth.config.RedisKeys;
  8. import com.izouma.nineth.converter.LongArrayConverter;
  9. import com.izouma.nineth.converter.StringArrayConverter;
  10. import com.izouma.nineth.domain.Collection;
  11. import com.izouma.nineth.domain.*;
  12. import com.izouma.nineth.dto.*;
  13. import com.izouma.nineth.enums.*;
  14. import com.izouma.nineth.exception.BusinessException;
  15. import com.izouma.nineth.repo.*;
  16. import com.izouma.nineth.utils.JpaUtils;
  17. import com.izouma.nineth.utils.SecurityUtils;
  18. import lombok.AllArgsConstructor;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.apache.commons.lang3.ObjectUtils;
  21. import org.apache.commons.lang3.RandomUtils;
  22. import org.apache.commons.lang3.Range;
  23. import org.apache.commons.lang3.StringUtils;
  24. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  25. import org.springframework.beans.BeanUtils;
  26. import org.springframework.cache.annotation.Cacheable;
  27. import org.springframework.core.env.Environment;
  28. import org.springframework.data.domain.*;
  29. import org.springframework.data.jpa.domain.Specification;
  30. import org.springframework.data.redis.core.BoundHashOperations;
  31. import org.springframework.data.redis.core.BoundValueOperations;
  32. import org.springframework.data.redis.core.RedisTemplate;
  33. import org.springframework.scheduling.TaskScheduler;
  34. import org.springframework.stereotype.Service;
  35. import org.springframework.web.bind.annotation.RequestParam;
  36. import javax.annotation.PostConstruct;
  37. import javax.persistence.criteria.*;
  38. import javax.transaction.Transactional;
  39. import java.math.BigDecimal;
  40. import java.time.LocalDateTime;
  41. import java.time.ZoneId;
  42. import java.time.format.DateTimeFormatter;
  43. import java.util.*;
  44. import java.util.concurrent.ExecutionException;
  45. import java.util.concurrent.ForkJoinPool;
  46. import java.util.concurrent.ScheduledFuture;
  47. import java.util.concurrent.TimeUnit;
  48. import java.util.concurrent.atomic.AtomicInteger;
  49. import java.util.stream.Collectors;
  50. @Service
  51. @AllArgsConstructor
  52. @Slf4j
  53. public class CollectionService {
  54. private CollectionRepo collectionRepo;
  55. private LikeRepo likeRepo;
  56. private BlindBoxItemRepo blindBoxItemRepo;
  57. private AppointmentRepo appointmentRepo;
  58. private UserRepo userRepo;
  59. private TaskScheduler taskScheduler;
  60. private CacheService cacheService;
  61. private RedisTemplate<String, Object> redisTemplate;
  62. private RocketMQTemplate rocketMQTemplate;
  63. private GeneralProperties generalProperties;
  64. private Environment env;
  65. private OrderRepo orderRepo;
  66. private TokenHistoryRepo tokenHistoryRepo;
  67. private TagRepo tagRepo;
  68. private UserBalanceService userBalanceService;
  69. private SysConfigService sysConfigService;
  70. private NewsRepo newsRepo;
  71. private final Map<Long, ScheduledFuture<?>> tasks = new HashMap<>();
  72. @PostConstruct
  73. public void init() {
  74. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  75. return;
  76. }
  77. List<Collection> collections = collectionRepo
  78. .findByScheduleSaleTrueAndOnShelfFalseAndStartTimeBeforeAndDelFalse(LocalDateTime.now());
  79. for (Collection collection : collections) {
  80. onShelfTask(collection);
  81. }
  82. }
  83. @Cacheable(value = "collectionList", key = "#pageQuery.hashCode()")
  84. public PageWrapper<Collection> all(PageQuery pageQuery) {
  85. Map<String, Object> query = pageQuery.getQuery();
  86. query.put("del", false);
  87. // String type = MapUtils.getString(pageQuery.getQuery(), "type", "DEFAULT");
  88. // pageQuery.getQuery().remove("type");
  89. Specification<Collection> specification = JpaUtils.toSpecification(pageQuery, Collection.class);
  90. PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
  91. //筛选最低价格
  92. if (query.containsKey("minPrice")) {
  93. BigDecimal minPrice = Convert.toBigDecimal(query.get("minPrice"));
  94. query.remove("minPrice");
  95. if (minPrice.compareTo(BigDecimal.ZERO) > 0) {
  96. specification = specification
  97. .and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  98. List<Predicate> and = new ArrayList<>();
  99. and.add(criteriaBuilder.greaterThanOrEqualTo(root.get("price"), minPrice));
  100. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  101. });
  102. }
  103. }
  104. if (query.containsKey("rarityLabel")) {
  105. String rarityLabel = String.valueOf(query.get("rarityLabel"));
  106. query.remove("rarityLabel");
  107. String not = null;
  108. if (StringUtils.isNotBlank(rarityLabel)) {
  109. if (Constants.Rarity.SSR.equals(rarityLabel)) {
  110. not = Constants.Rarity.U_LIKE;
  111. }
  112. if (Constants.Rarity.SR.equals(rarityLabel)) {
  113. not = Constants.Rarity.SSR_LIKE;
  114. }
  115. if (Constants.Rarity.U.equals(rarityLabel)) {
  116. not = Constants.Rarity.R_LIKE;
  117. }
  118. if (Constants.Rarity.R.equals(rarityLabel)) {
  119. not = Constants.Rarity.SR_LIKE;
  120. }
  121. String finalNotLike = not;
  122. String finalLike = "%" + rarityLabel + " #%";
  123. specification = specification
  124. .and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  125. List<Predicate> and = new ArrayList<>();
  126. and.add(criteriaBuilder.like(root.get("name"), finalLike));
  127. and.add(criteriaBuilder.notLike(root.get("name"), finalNotLike));
  128. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  129. });
  130. }
  131. }
  132. // 筛选去除指定名称不展示
  133. if (query.containsKey("notLike")) {
  134. String notLike = Convert.toStr(query.get("notLike"));
  135. query.remove("notLike");
  136. StringArrayConverter converter = new StringArrayConverter();
  137. List<String> notLikes = converter.convertToEntityAttribute(notLike);
  138. specification = specification.and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  139. List<Predicate> and = new ArrayList<>();
  140. notLikes.forEach(str -> {
  141. and.add(criteriaBuilder.notLike(root.get("name"), "%" + str + "%"));
  142. });
  143. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  144. });
  145. }
  146. // if (pageRequest.getSort().stream().noneMatch(order -> order.getProperty().equals("createdAt"))) {
  147. // pageRequest = PageRequest.of(pageRequest.getPageNumber(), pageQuery.getSize(),
  148. // pageRequest.getSort().and(Sort.by("createdAt").descending()));
  149. // }
  150. // specification = specification.and((Specification<Collection>) (root, criteriaQuery, criteriaBuilder) -> {
  151. // List<Predicate> and = new ArrayList<>();
  152. //
  153. // if (StringUtils.isNotEmpty(type) && !"all".equalsIgnoreCase(type)) {
  154. // try {
  155. // if (type.contains(",")) {
  156. // and.add(root.get("type")
  157. // .in(Arrays.stream(type.split(",")).map(s -> Enum.valueOf(CollectionType.class, s))
  158. // .collect(Collectors.toList())));
  159. // } else {
  160. // and.add(criteriaBuilder.equal(root.get("type"), Enum.valueOf(CollectionType.class, type)));
  161. // }
  162. // } catch (Exception e) {
  163. //
  164. // }
  165. // }
  166. // return criteriaBuilder.and(and.toArray(new Predicate[0]));
  167. // });
  168. Page<Collection> page = collectionRepo.findAll(specification, pageRequest);
  169. return new PageWrapper<>(page.getContent(), page.getPageable().getPageNumber(),
  170. page.getPageable().getPageSize(), page.getTotalElements());
  171. }
  172. @Transactional
  173. public Collection create(Collection record) {
  174. User minter = userRepo.findById(record.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  175. if (record.getCompanyId() != 1L) {
  176. BigDecimal price = sysConfigService.getBigDecimal("company_collection_price");
  177. BigDecimal totalPrice = new BigDecimal(record.getTotal()).multiply(price);
  178. if (!userBalanceService.checkBalance(record.getCompanyId(), totalPrice)) {
  179. throw new BusinessException("余额不足");
  180. }
  181. userBalanceService
  182. .modifyBalance(record.getCompanyId(), totalPrice.negate(), BalanceType.PAY, null, false, null);
  183. }
  184. if (record.getNewsId() != null) {
  185. News news = newsRepo.findById(record.getNewsId()).orElseThrow(new BusinessException("未找到"));
  186. record.setNewsId(news.getId());
  187. record.setNewsPic(news.getPic());
  188. record.setNewsTitle(news.getTitle());
  189. record.setNewsCreatedTime(news.getCreatedAt());
  190. }
  191. record.setMinter(minter.getNickname());
  192. record.setMinterId(minter.getId());
  193. record.setMinterAvatar(minter.getAvatar());
  194. record.setOwner(minter.getNickname());
  195. record.setOwnerId(minter.getId());
  196. record.setOwnerAvatar(minter.getAvatar());
  197. record.setStock(record.getTotal());
  198. record.setSale(0);
  199. record.setVipQuota(record.getTotalQuota());
  200. if (!record.getTags().isEmpty()) {
  201. record.setTags(new HashSet<>(tagRepo.findAllById(record.getTags().stream().map(Tag::getId)
  202. .collect(Collectors.toList()))));
  203. }
  204. if (record.isScheduleSale()) {
  205. if (record.getStartTime() == null) {
  206. throw new BusinessException("请填写定时发布时间");
  207. }
  208. if (record.getStartTime().isBefore(LocalDateTime.now())) {
  209. record.setOnShelf(true);
  210. record.setSalable(true);
  211. record.setStartTime(null);
  212. }
  213. }
  214. record = collectionRepo.save(record);
  215. onShelfTask(record);
  216. redisTemplate.opsForValue().set(RedisKeys.COLLECTION_STOCK + record.getId(), record.getStock());
  217. redisTemplate.opsForValue().set(RedisKeys.COLLECTION_SALE + record.getId(), record.getSale());
  218. return record;
  219. }
  220. public Collection update(Collection record) {
  221. // collectionRepo.update(record.getId(), record.isOnShelf(), record.isSalable(),
  222. // record.getStartTime(), record.isScheduleSale(), record.getSort(),
  223. // record.getDetail(), JSON.toJSONString(record.getPrivileges()),
  224. // JSON.toJSONString(record.getProperties()), JSON.toJSONString(record.getModel3d()),
  225. // record.getMaxCount(), record.getCountId(), record.isScanCode(), record.isNoSoldOut(),
  226. // record.getAssignment(), record.isCouponPayment(), record.getShareBg(), record.getRegisterBg(),
  227. // record.getVipQuota(), record.getTimeDelay(), record.getSaleTime(), record.getHoldDays(),
  228. // record.getOpenQuota(), record.getTotalQuota(), record.getMinimumCharge());
  229. Collection collection = collectionRepo.findDetailById(record.getId()).orElseThrow(new BusinessException("无记录"));
  230. collection.setOnShelf(record.isOnShelf());
  231. collection.setSalable(record.isSalable());
  232. collection.setStartTime(record.getStartTime());
  233. collection.setScheduleSale(record.isScheduleSale());
  234. collection.setSort(record.getSort());
  235. collection.setDetail(record.getDetail());
  236. collection.setPrivileges(record.getPrivileges());
  237. collection.setProperties(record.getProperties());
  238. collection.setModel3d(record.getModel3d());
  239. collection.setMaxCount(record.getMaxCount());
  240. collection.setCountId(record.getCountId());
  241. collection.setScanCode(record.isScanCode());
  242. collection.setNoSoldOut(record.isNoSoldOut());
  243. collection.setAssignment(record.getAssignment());
  244. collection.setCouponPayment(record.isCouponPayment());
  245. collection.setShareBg(record.getShareBg());
  246. collection.setRegisterBg(record.getRegisterBg());
  247. collection.setVipQuota(record.getVipQuota());
  248. collection.setTimeDelay(record.getTimeDelay());
  249. collection.setSaleTime(record.getSaleTime());
  250. collection.setHoldDays(record.getHoldDays());
  251. collection.setOpenQuota(record.getOpenQuota());
  252. collection.setTotalQuota(record.getTotalQuota());
  253. collection.setMinimumCharge(record.getMinimumCharge());
  254. collection.setRule(record.getRule());
  255. collection.setPrefixName(record.getPrefixName());
  256. if (record.getTags().isEmpty()) {
  257. collection.setTags(null);
  258. } else {
  259. collection.setTags(new HashSet<>(tagRepo.findAllById(record.getTags().stream().map(Tag::getId)
  260. .collect(Collectors.toList()))));
  261. }
  262. if (record.getNewsId() != null) {
  263. News news = newsRepo.findById(record.getNewsId()).orElseThrow(new BusinessException("未找到新闻"));
  264. collection.setNewsId(news.getId());
  265. collection.setNewsTitle(news.getTitle());
  266. collection.setNewsPic(news.getPic());
  267. collection.setNewsCreatedTime(news.getCreatedAt());
  268. }
  269. collection = collectionRepo.save(collection);
  270. onShelfTask(collection);
  271. return collection;
  272. }
  273. private void onShelfTask(Collection record) {
  274. ScheduledFuture<?> task = tasks.get(record.getId());
  275. if (task != null) {
  276. if (!task.cancel(true)) {
  277. return;
  278. }
  279. }
  280. if (record.isScheduleSale()) {
  281. if (record.getStartTime().minusSeconds(2).isAfter(LocalDateTime.now())) {
  282. Date date = Date.from(record.getStartTime().atZone(ZoneId.systemDefault()).toInstant());
  283. ScheduledFuture<?> future = taskScheduler.schedule(() -> {
  284. collectionRepo.scheduleOnShelf(record.getId(), !record.isScanCode());
  285. tasks.remove(record.getId());
  286. }, date);
  287. tasks.put(record.getId(), future);
  288. } else {
  289. collectionRepo.scheduleOnShelf(record.getId(), !record.isScanCode());
  290. }
  291. }
  292. }
  293. public CollectionDTO toDTO(Collection collection) {
  294. return toDTO(collection, true, false);
  295. }
  296. public CollectionDTO toDTO(Collection collection, boolean join, boolean showVip) {
  297. CollectionDTO collectionDTO = new CollectionDTO();
  298. BeanUtils.copyProperties(collection, collectionDTO);
  299. if (join) {
  300. User user = SecurityUtils.getAuthenticatedUser();
  301. if (user != null) {
  302. List<Like> list = likeRepo.findByUserIdAndCollectionId(user.getId(),
  303. collection.getId());
  304. collectionDTO.setLiked(!list.isEmpty());
  305. if (collection.getType() == CollectionType.BLIND_BOX) {
  306. collectionDTO.setAppointment(appointmentRepo.findFirstByBlindBoxId(collection.getId()).isPresent());
  307. }
  308. if (showVip && collection.getAssignment() > 0 && user.getVipPurchase() > 0) {
  309. int purchase = orderRepo
  310. .countByUserIdAndCollectionIdAndVipTrueAndStatusIn(user.getId(), collection.getId(), Arrays
  311. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  312. collectionDTO.setVipSurplus(user.getVipPurchase() - purchase);
  313. }
  314. }
  315. }
  316. return collectionDTO;
  317. }
  318. public Collection queryUserDetail(Collection collection, boolean join, boolean showVip) {
  319. if (join) {
  320. User user = SecurityUtils.getAuthenticatedUser();
  321. if (user != null) {
  322. List<Like> list = likeRepo.findByUserIdAndCollectionId(user.getId(),
  323. collection.getId());
  324. collection.setLiked(!list.isEmpty());
  325. if (collection.getType() == CollectionType.BLIND_BOX) {
  326. collection.setAppointment(appointmentRepo.findFirstByBlindBoxId(collection.getId()).isPresent());
  327. }
  328. // if (showVip && collection.getAssignment() > 0 && user.getVipPurchase() > 0) {
  329. // int purchase = orderRepo.countByUserIdAndCollectionIdAndVipTrueAndStatusIn(user.getId(), collection.getId(), Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  330. collection.setVipSurplus(user.getVipPurchase());
  331. // }
  332. }
  333. }
  334. return collection;
  335. }
  336. public List<CollectionDTO> toDTO(List<Collection> collections) {
  337. List<Like> likes = new ArrayList<>();
  338. List<Appointment> appointments = new ArrayList<>();
  339. if (SecurityUtils.getAuthenticatedUser() != null) {
  340. likes.addAll(likeRepo.findByUserIdAndCollectionIdIsNotNull(SecurityUtils.getAuthenticatedUser().getId()));
  341. appointments.addAll(appointmentRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  342. }
  343. return collections.stream().parallel().map(collection -> {
  344. CollectionDTO dto = toDTO(collection, false, false);
  345. if (!likes.isEmpty()) {
  346. dto.setLiked(likes.stream().anyMatch(l -> l.getCollectionId().equals(collection.getId())));
  347. }
  348. if (!appointments.isEmpty()) {
  349. dto.setAppointment(appointments.stream().anyMatch(a -> a.getBlindBoxId().equals(collection.getId())));
  350. }
  351. return dto;
  352. }).collect(Collectors.toList());
  353. }
  354. public void queryUserDetail(List<Collection> collections) {
  355. List<Like> likes = new ArrayList<>();
  356. List<Appointment> appointments = new ArrayList<>();
  357. if (SecurityUtils.getAuthenticatedUser() != null) {
  358. likes.addAll(likeRepo.findByUserIdAndCollectionIdIsNotNull(SecurityUtils.getAuthenticatedUser().getId()));
  359. appointments.addAll(appointmentRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  360. }
  361. collections.stream().parallel().forEach(collection -> {
  362. queryUserDetail(collection, false, false);
  363. if (!likes.isEmpty()) {
  364. collection.setLiked(likes.stream().anyMatch(l -> l.getCollectionId().equals(collection.getId())));
  365. }
  366. if (!appointments.isEmpty()) {
  367. collection.setAppointment(appointments.stream()
  368. .anyMatch(a -> a.getBlindBoxId().equals(collection.getId())));
  369. }
  370. });
  371. }
  372. public Page<CollectionDTO> toDTO(Page<Collection> collections) {
  373. List<CollectionDTO> userDTOS = toDTO(collections.getContent());
  374. return new PageImpl<>(userDTOS, collections.getPageable(), collections.getTotalElements());
  375. }
  376. @Transactional
  377. public Collection createBlindBox(CreateBlindBox createBlindBox) throws Exception {
  378. Collection blindBox = createBlindBox.getBlindBox();
  379. blindBox.setCompanyId(Optional.ofNullable(createBlindBox.getCompanyId()).orElse(1L));
  380. if (blindBox.getId() != null) {
  381. throw new BusinessException("无法完成此操作");
  382. }
  383. List<Collection> list =
  384. collectionRepo.findAllById(createBlindBox.getItems().stream().map(BlindBoxItem::getCollectionId)
  385. .collect(Collectors.toSet()));
  386. for (BlindBoxItem item : createBlindBox.getItems()) {
  387. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId())).findAny()
  388. .orElseThrow(new BusinessException("所选藏品不存在"));
  389. if (item.getTotal() > collection.getStock()) {
  390. throw new BusinessException("所选藏品库存不足:" + collection.getName());
  391. }
  392. }
  393. User user = userRepo.findById(blindBox.getMinterId()).orElse(SecurityUtils.getAuthenticatedUser());
  394. blindBox.setMinter(user.getNickname());
  395. blindBox.setMinterId(user.getId());
  396. blindBox.setMinterAvatar(user.getAvatar());
  397. blindBox.setOwner(user.getNickname());
  398. blindBox.setOwnerId(user.getId());
  399. blindBox.setOwnerAvatar(user.getAvatar());
  400. blindBox.setTotal(createBlindBox.getItems().stream().mapToInt(BlindBoxItem::getTotal).sum());
  401. blindBox.setStock(blindBox.getTotal());
  402. blindBox.setSale(0);
  403. collectionRepo.save(blindBox);
  404. new ForkJoinPool(128).submit(() -> {
  405. createBlindBox.getItems().stream().parallel().forEach(item -> {
  406. Collection collection = list.stream().filter(i -> i.getId().equals(item.getCollectionId()))
  407. .findFirst().get();
  408. decreaseStock(collection.getId(), item.getTotal());
  409. BlindBoxItem blindBoxItem = new BlindBoxItem();
  410. BeanUtils.copyProperties(collection, blindBoxItem);
  411. blindBoxItem.setId(null);
  412. blindBoxItem.setOasisId(collection.getOasisId());
  413. blindBoxItem.setCollectionId(item.getCollectionId());
  414. blindBoxItem.setSale(0);
  415. blindBoxItem.setTotal(item.getTotal());
  416. blindBoxItem.setStock(item.getTotal());
  417. blindBoxItem.setRare(item.isRare());
  418. blindBoxItem.setRaceId(collection.getRaceId());
  419. blindBoxItem.setGroupId(collection.getGroupId());
  420. blindBoxItem.setItemId(collection.getItemId());
  421. blindBoxItem.setBlindBoxId(blindBox.getId());
  422. blindBoxItem.setCompanyId(collection.getCompanyId());
  423. blindBoxItemRepo.saveAndFlush(blindBoxItem);
  424. log.info("createBlindBoxItemSuccess" + blindBoxItem.getId());
  425. });
  426. }).get();
  427. return blindBox;
  428. }
  429. public void appointment(Long id, Long userId) {
  430. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  431. if (collection.getType() != CollectionType.BLIND_BOX) {
  432. throw new BusinessException("非盲盒,无需预约");
  433. }
  434. if (collection.getStartTime().isBefore(LocalDateTime.now())) {
  435. throw new BusinessException("盲盒已开售,无需预约");
  436. }
  437. appointmentRepo.save(Appointment.builder()
  438. .userId(userId)
  439. .blindBoxId(id)
  440. .build());
  441. }
  442. public BlindBoxItem draw(Long userId, Long collectionId) {
  443. log.info("blindBoxDraw, userId={}, collectionId={}", userId, collectionId);
  444. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(collectionId);
  445. BoundHashOperations<String, Object, Object> operations = redisTemplate
  446. .boundHashOps(RedisKeys.DRAW_BLIND_BOX + collectionId);
  447. Map<Object, Object> entries = operations.entries();
  448. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  449. int c = 0, sum = 0;
  450. for (BlindBoxItem item : items) {
  451. if (item.getStock() > 0) {
  452. int stock = Optional.ofNullable(entries.get(item.getCollectionId() + "")).map(i -> (int) i)
  453. .orElse(item.getStock());
  454. randomRange.put(item, Range.between(c, c + item.getStock()));
  455. c += stock;
  456. sum += stock;
  457. }
  458. }
  459. int retry = 0;
  460. BlindBoxItem winItem = null;
  461. while (winItem == null) {
  462. retry++;
  463. if (userId == 3453161L || userId == 7194L || userId == 134613L) {
  464. winItem = items.stream().filter(i -> i.getName().contains("SSR") && i.getStock() > 0).findFirst()
  465. .orElse(null);
  466. }
  467. if (winItem == null) {
  468. int rand = RandomUtils.nextInt(0, sum + 1);
  469. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  470. BlindBoxItem item = entry.getKey();
  471. Range<Integer> range = entry.getValue();
  472. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  473. int total = items.stream().filter(i -> !i.isRare())
  474. .mapToInt(BlindBoxItem::getTotal).sum();
  475. int stock = items.stream().filter(i -> !i.isRare())
  476. .mapToInt(BlindBoxItem::getStock).sum();
  477. if (item.isRare()) {
  478. double nRate = stock / (double) total;
  479. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  480. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  481. if (!(nRate > 0.1 && item.getStock() == 1)) {
  482. winItem = item;
  483. }
  484. }
  485. } else {
  486. double nRate = (stock - 1) / (double) total;
  487. double rRate = item.getStock() / (double) item.getTotal();
  488. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  489. winItem = item;
  490. }
  491. }
  492. }
  493. }
  494. }
  495. if (retry > 100 && winItem == null) {
  496. throw new BusinessException("盲盒抽卡失败");
  497. }
  498. if (winItem != null) {
  499. operations.putIfAbsent(winItem.getCollectionId() + "", winItem.getStock());
  500. int stock = Math.toIntExact(operations.increment(winItem.getCollectionId() + "", -1));
  501. if (stock < 0) {
  502. log.info("over draw {} {}", stock, winItem.getCollectionId());
  503. operations.increment(winItem.getCollectionId() + "", 1);
  504. winItem = null;
  505. }
  506. }
  507. }
  508. // winItem.setStock(winItem.getStock() - 1);
  509. // winItem.setSale(winItem.getSale() + 1);
  510. // blindBoxItemRepo.saveAndFlush(winItem);
  511. blindBoxItemRepo.decreaseStockAndIncreaseSale(winItem.getId(), 1);
  512. blindBoxItemRepo.flush();
  513. return winItem;
  514. }
  515. public synchronized Integer getNextNumber(Long collectionId) {
  516. BoundValueOperations<String, Object> opt = redisTemplate
  517. .boundValueOps(RedisKeys.COLLECTION_NUMBER + collectionId);
  518. opt.setIfAbsent(collectionRepo.getCurrentNumber(collectionId).orElse(0));
  519. int num = Math.toIntExact(Optional.ofNullable(opt.increment()).orElse(1L));
  520. collectionRepo.setNumber(collectionId, num);
  521. return num;
  522. }
  523. public synchronized Integer getNextNumber(Collection collection) {
  524. return collection.getTotal() > 1 ? getNextNumber(collection.getId()) : null;
  525. }
  526. public synchronized Integer getNextNumber(BlindBoxItem collection) {
  527. return collection.getTotal() > 1 ? getNextNumber(collection.getId()) : null;
  528. }
  529. public void addStock(Long id, int number) {
  530. Collection collection = collectionRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  531. if (collection.getSource() != CollectionSource.OFFICIAL) {
  532. throw new BusinessException("用户转售无法增发");
  533. }
  534. if (collection.getType() == CollectionType.BLIND_BOX) {
  535. throw new BusinessException("盲盒无法增发");
  536. }
  537. increaseStock(id, number);
  538. collectionRepo.increaseTotal(id, number);
  539. }
  540. public synchronized Long increaseStock(Long id, int number) {
  541. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.COLLECTION_STOCK + id);
  542. if (ops.get() == null) {
  543. Boolean success = ops.setIfAbsent(Optional.ofNullable(collectionRepo.getStock(id))
  544. .orElse(0), 7, TimeUnit.DAYS);
  545. log.info("创建redis库存:{}", success);
  546. }
  547. Long stock = ops.increment(number);
  548. rocketMQTemplate.convertAndSend(generalProperties.getUpdateStockTopic(), id);
  549. return stock;
  550. }
  551. public synchronized Integer getStock(Long id) {
  552. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.COLLECTION_STOCK + id);
  553. Integer stock = (Integer) ops.get();
  554. if (stock == null) {
  555. Boolean success = ops.setIfAbsent(Optional.ofNullable(collectionRepo.getStock(id))
  556. .orElse(0), 7, TimeUnit.DAYS);
  557. log.info("创建redis库存:{}", success);
  558. return (Integer) ops.get();
  559. } else {
  560. return stock;
  561. }
  562. }
  563. public synchronized Long decreaseStock(Long id, int number) {
  564. return increaseStock(id, -number);
  565. }
  566. public synchronized Long increaseSale(Long id, int number) {
  567. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.COLLECTION_SALE + id);
  568. if (ops.get() == null) {
  569. Boolean success = ops.setIfAbsent(Optional.ofNullable(collectionRepo.getSale(id))
  570. .orElse(0), 7, TimeUnit.DAYS);
  571. log.info("创建redis销量:{}", success);
  572. }
  573. Long sale = ops.increment(number);
  574. redisTemplate.opsForHash().increment(RedisKeys.UPDATE_SALE, id.toString(), 1);
  575. // rocketMQTemplate.convertAndSend(generalProperties.getUpdateSaleTopic(), id);
  576. return sale;
  577. }
  578. public synchronized Long decreaseSale(Long id, int number) {
  579. return increaseSale(id, -number);
  580. }
  581. // @Debounce(key = "#id", delay = 500)
  582. public void syncStock(Long id) {
  583. Integer stock = (Integer) redisTemplate.opsForValue().get(RedisKeys.COLLECTION_STOCK + id);
  584. if (stock != null) {
  585. log.info("同步库存信息{}", id);
  586. collectionRepo.updateStock(id, stock);
  587. cacheService.clearCollection(id);
  588. }
  589. }
  590. // @Debounce(key = "#id", delay = 500)
  591. public void syncSale(Long id) {
  592. Integer sale = (Integer) redisTemplate.opsForValue().get(RedisKeys.COLLECTION_SALE + id);
  593. if (sale != null) {
  594. log.info("同步销量信息{}", id);
  595. collectionRepo.updateSale(id, sale);
  596. cacheService.clearCollection(id);
  597. }
  598. }
  599. @Debounce(key = "#id", delay = 500)
  600. public void syncQuota(Long id) {
  601. Integer quota = (Integer) redisTemplate.opsForValue().get(RedisKeys.COLLECTION_QUOTA + id);
  602. if (quota != null) {
  603. log.info("同步额度信息{}", id);
  604. collectionRepo.updateVipQuota(id, quota);
  605. cacheService.clearCollection(id);
  606. }
  607. }
  608. public synchronized Long decreaseQuota(Long id, int number) {
  609. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.COLLECTION_QUOTA + id);
  610. if (ops.get() == null) {
  611. Boolean success = ops.setIfAbsent(Optional.ofNullable(collectionRepo.getVipQuota(id))
  612. .orElse(0), 7, TimeUnit.DAYS);
  613. log.info("创建redis额度:{}", success);
  614. }
  615. Long stock = ops.increment(-number);
  616. rocketMQTemplate.convertAndSend(generalProperties.getUpdateQuotaTopic(), id);
  617. return stock;
  618. }
  619. @Cacheable(value = "recommendLegacy", key = "#type")
  620. public List<CollectionDTO> recommendLegacy(@RequestParam String type, Long companyId) {
  621. return collectionRepo.recommend(type, companyId).stream().map(rc -> {
  622. if (StringUtils.isNotBlank(rc.getRecommend().getPic())) {
  623. rc.getCollection().setPic(Collections.singletonList(new FileObject(null, rc.getRecommend()
  624. .getPic(), null, null)));
  625. }
  626. CollectionDTO collectionDTO = new CollectionDTO();
  627. BeanUtils.copyProperties(rc.getCollection(), collectionDTO);
  628. return collectionDTO;
  629. }).collect(Collectors.toList());
  630. }
  631. public List<PointDTO> savePoint(Long collectionId, LocalDateTime time) {
  632. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("无藏品"));
  633. //库存
  634. // int stock = collection.getStock();
  635. //是否开启白名单
  636. int assignment = collection.getAssignment();
  637. if (assignment <= 0) {
  638. return null;
  639. }
  640. List<User> users = userRepo.findAllByCollectionId(collectionId);
  641. //邀请者
  642. Map<Long, List<User>> userMap = users.stream()
  643. .filter(user -> ObjectUtils.isNotEmpty(user.getCollectionInvitor()))
  644. .collect(Collectors.groupingBy(User::getCollectionInvitor));
  645. AtomicInteger sum = new AtomicInteger();
  646. AtomicInteger sum1 = new AtomicInteger();
  647. List<PointDTO> dtos = new ArrayList<>();
  648. Map<Long, BigDecimal> historyMap = tokenHistoryRepo.userBuy(userMap.keySet())
  649. .stream()
  650. .collect(Collectors.groupingBy(TokenHistory::getToUserId, Collectors.reducing(BigDecimal.ZERO,
  651. TokenHistory::getPrice,
  652. BigDecimal::add)));
  653. DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  654. userMap.forEach((key, value) -> {
  655. //邀请达到数量
  656. if (value.size() >= collection.getAssignment()) {
  657. value.sort(Comparator.comparing(User::getCreatedAt));
  658. BigDecimal buy = historyMap.get(key);
  659. //满足条件的时间
  660. User user = value.get(collection.getAssignment() - 1);
  661. //作弊得已屏蔽
  662. if ((ObjectUtils.isEmpty(buy) || buy.compareTo(BigDecimal.valueOf(500)) < 0) && user.getCreatedAt()
  663. .isBefore(time)) {
  664. sum1.getAndIncrement();
  665. System.out.println(key + "," + dft.format(user.getCreatedAt()) + "," + buy);
  666. } else {
  667. //实名数量
  668. long identitySum = value.stream().filter(u -> AuthStatus.SUCCESS.equals(u.getAuthStatus())).count();
  669. dtos.add(new PointDTO(key, user.getCreatedAt(), value.size(), (int) identitySum, buy));
  670. sum.getAndIncrement();
  671. }
  672. }
  673. });
  674. log.info("完成任务人数:{}", sum);
  675. log.info("作弊任务人数:{}", sum1);
  676. LongArrayConverter longArrayConverter = new LongArrayConverter();
  677. List<Long> collect = dtos.stream()
  678. .filter(dto -> time.isBefore(dto.getCreatedAt()))
  679. .map(PointDTO::getId)
  680. .collect(Collectors.toList());
  681. log.info(dft.format(time) + "前完成任务人数:{}", collect.size());
  682. // log.info("sql: update user set vip_point = 1 where id in ({})", longArrayConverter.convertToDatabaseColumn(collect));
  683. List<PointDTO> collect1 = dtos.stream()
  684. .filter(dto -> time.isAfter(dto.getCreatedAt()))
  685. .collect(Collectors.toList());
  686. log.info(dft.format(time) + "后完成任务人数:{}", collect1.size());
  687. List<Long> collect2 = dtos.stream()
  688. .filter(dto -> dto.getIdentitySum() > 0)
  689. .map(PointDTO::getId)
  690. .collect(Collectors.toList());
  691. log.info("邀请实名认证人量:{}", collect2.size());
  692. // log.info("sql: update user set vip_point = 1 where id in ({})", longArrayConverter.convertToDatabaseColumn(collect2));
  693. return dtos;
  694. }
  695. public Page<Collection> byTag(Long tagId, List<Long> excludeUserId, Pageable pageable) {
  696. if (excludeUserId.isEmpty()) {
  697. excludeUserId.add(0L);
  698. }
  699. return collectionRepo.findAll((Specification<Collection>) (root, query, criteriaBuilder) -> {
  700. Join join = root.join("tags");
  701. return criteriaBuilder.and(criteriaBuilder.equal(join.get("id"), tagId),
  702. criteriaBuilder.equal(root.get("source"), CollectionSource.TRANSFER),
  703. criteriaBuilder.equal(root.get("salable"), true),
  704. criteriaBuilder.equal(root.get("onShelf"), true),
  705. criteriaBuilder.not(root.get("ownerId").in(excludeUserId)));
  706. }, pageable);
  707. }
  708. public List<Collection> setOasisScancode(List<Long> oasisIds) {
  709. List<CollectionSource> collectionSources = new ArrayList<>();
  710. collectionSources.add(CollectionSource.COMPANY);
  711. collectionSources.add(CollectionSource.OFFICIAL);
  712. List<Collection> collections = collectionRepo
  713. .findAllByOasisIdInAndSourceInAndStockGreaterThan(oasisIds, collectionSources, 0);
  714. List<Collection> result = new ArrayList<>();
  715. collections.forEach(collection -> {
  716. collection.setOnShelf(false);
  717. collection.setScanCode(true);
  718. collection.setSalable(true);
  719. collectionRepo.save(collection);
  720. result.add(collection);
  721. });
  722. return result;
  723. }
  724. public List<Collection> setOasisOnShelf(List<Long> oasisIds) {
  725. List<CollectionSource> collectionSources = new ArrayList<>();
  726. collectionSources.add(CollectionSource.COMPANY);
  727. collectionSources.add(CollectionSource.OFFICIAL);
  728. List<Collection> collections = collectionRepo
  729. .findAllByOasisIdInAndSourceInAndStockGreaterThan(oasisIds, collectionSources, 0);
  730. List<Collection> result = new ArrayList<>();
  731. collections.forEach(collection -> {
  732. collection.setOnShelf(true);
  733. collection.setScanCode(false);
  734. collection.setSalable(true);
  735. collectionRepo.save(collection);
  736. result.add(collection);
  737. });
  738. return result;
  739. }
  740. }