CollectionService.java 33 KB

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