CollectionService.java 38 KB

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