CollectionService.java 31 KB

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