CollectionService.java 26 KB

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