CollectionService.java 29 KB

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