CollectionService.java 26 KB

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