CollectionService.java 25 KB

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