| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- package com.izouma.nineth.service;
- import cn.hutool.core.collection.CollUtil;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.alipay.api.domain.PriceInfo;
- import com.github.kevinsawicki.http.HttpRequest;
- import com.izouma.nineth.domain.BalanceRecord;
- import com.izouma.nineth.domain.Order;
- import com.izouma.nineth.domain.RechargeOrder;
- import com.izouma.nineth.domain.User;
- import com.izouma.nineth.enums.BalanceType;
- import com.izouma.nineth.enums.CollectionSource;
- import com.izouma.nineth.enums.OrderStatus;
- import com.izouma.nineth.enums.OrderType;
- import com.izouma.nineth.exception.BusinessException;
- import com.izouma.nineth.repo.*;
- import com.izouma.nineth.utils.netease.CheckSumBuilder;
- import lombok.AllArgsConstructor;
- import org.apache.commons.lang.RandomStringUtils;
- import org.springframework.stereotype.Service;
- import javax.xml.stream.events.EndDocument;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.sql.Timestamp;
- import java.time.*;
- import java.time.format.DateTimeFormatter;
- import java.util.*;
- import java.util.stream.Collectors;
- @Service
- @AllArgsConstructor
- public class StatisticService {
- private UserRepo userRepo;
- private OrderRepo orderRepo;
- private TokenHistoryRepo tokenHistoryRepo;
- private BalanceRecordRepo balanceRecordRepo;
- private PhotoAssetRepo photoAssetRepo;
- private DomainOrderRepo domainOrderRepo;
- public Map<String, Object> total(Long userId, Long companyId) {
- User user1 = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("无用户"));
- Map<String, Object> total = new HashMap<>();
- List<Order> orders;
- if (user1.isAdmin()) {
- long user = userRepo.countAllByDelFalse();
- total.put("userNum", user);
- Set<OrderType> orderTypes = new HashSet<>();
- orderTypes.add(OrderType.MIX);
- orders = orderRepo.findAllByStatusAndCompanyIdAndOrderTypeNotIn(OrderStatus.FINISH, companyId, orderTypes);
- BigDecimal allRecharged = balanceRecordRepo.sumRechargeAll();
- total.put("rechargePrice", allRecharged);
- } else {
- orders = orderRepo.findAllByStatusAndMinterId(OrderStatus.FINISH, userId);
- }
- Map<CollectionSource, List<Order>> orderMap = orders.stream().collect(Collectors.groupingBy(Order::getSource));
- List<Order> officialOrders = Optional.ofNullable(orderMap.get(CollectionSource.OFFICIAL))
- .orElse(Collections.emptyList());
- List<Order> transferOrders = Optional.ofNullable(orderMap.get(CollectionSource.TRANSFER))
- .orElse(Collections.emptyList());
- total.put("officialNum", officialOrders.size());
- total.put("transferNum", transferOrders.size());
- BigDecimal officialPrice = officialOrders.stream()
- .map(Order::getTotalPrice)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- BigDecimal transferPrice = transferOrders.stream()
- .map(Order::getTotalPrice)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- total.put("officialPrice", officialPrice);
- total.put("transferPrice", transferPrice);
- return total;
- }
- /*
- 按天
- */
- public Map<String, Long> userTrend(int day) {
- Map<String, Long> map = new HashMap<>();
- for (int i = 0; i < day; i++) {
- LocalDate date = LocalDate.now().minusDays(i);
- map.put(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(date),
- userRepo.countByCreatedAtBetween(date.atStartOfDay(), date.atTime(LocalTime.MAX)));
- }
- return map;
- }
- /*
- 按月
- */
- public Map<String, Long> userTrendV2(String yearMonth) {
- Map<String, Long> map = new HashMap<>();
- YearMonth month = YearMonth.parse(yearMonth);
- LocalDateTime end = month.atEndOfMonth().atTime(LocalTime.MAX);
- LocalDateTime start = month.atDay(1).atStartOfDay();
- map.put(yearMonth, userRepo.countByCreatedAtBetween(start, end));
- return map;
- }
- public Map<String, Map<String, Long>> orderNumTrend(int day, Long userId, Long companyId) {
- LocalDateTime date = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
- LocalDateTime start = date.minusDays(day);
- User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("无用户"));
- List<Order> orders;
- if (user.isAdmin()) {
- orders = orderRepo.findAllByCreatedAtIsAfterAndStatusInAndCompanyIdAndOrderTypeNot(start,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH), companyId, OrderType.MIX);
- } else {
- orders = orderRepo.findAllByCreatedAtIsAfterAndMinterIdAndStatusIn(start, userId,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
- }
- Map<CollectionSource, List<Order>> orderMap = orders.stream().collect(Collectors.groupingBy(Order::getSource));
- Map<String, Long> official = null;
- if (CollUtil.isNotEmpty(orderMap.get(CollectionSource.OFFICIAL))) {
- official = orderMap.get(CollectionSource.OFFICIAL).stream().collect(Collectors.groupingBy(
- item -> DateTimeFormatter.ofPattern("yyyy-MM-dd")
- .format(item.getCreatedAt()), Collectors.counting()));
- }
- Map<String, Long> transfer = null;
- if (CollUtil.isNotEmpty(orderMap.get(CollectionSource.TRANSFER))) {
- transfer = orderMap.get(CollectionSource.TRANSFER).stream().collect(Collectors.groupingBy(
- item -> DateTimeFormatter.ofPattern("yyyy-MM-dd")
- .format(item.getCreatedAt()), Collectors.counting()));
- }
- Map<String, Map<String, Long>> trend = new HashMap<>();
- trend.put("official", official);
- trend.put("transfer", transfer);
- return trend;
- }
- public Map<String, Map<String, BigDecimal>> orderPriceTrend(int day, Long userId, Long companyId) {
- LocalDateTime date = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
- LocalDateTime start = date.minusDays(day);
- User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("无用户"));
- List<Order> orders;
- Map<String, Map<String, BigDecimal>> trend = new HashMap<>();
- if (user.isAdmin()) {
- orders = orderRepo.findAllByCreatedAtIsAfterAndStatusInAndCompanyIdAndOrderTypeNot(start,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH), companyId, OrderType.MIX);
- List<BalanceRecord> balanceRecords = balanceRecordRepo
- .findByTypeAndCreatedAtBetween(BalanceType.RECHARGE, start, LocalDateTime.now());
- Map<String, BigDecimal> recharged = null;
- if (balanceRecords.size() > 0) {
- recharged = balanceRecords.stream()
- .collect(Collectors
- .groupingBy(item -> DateTimeFormatter.ofPattern("yyyy-MM-dd")
- .format(item
- .getCreatedAt()), Collectors
- .mapping(BalanceRecord::getAmount,
- Collectors
- .reducing(BigDecimal.ZERO, BigDecimal::add))));
- }
- trend.put("recharged", recharged);
- } else {
- orders = orderRepo.findAllByCreatedAtIsAfterAndMinterIdAndStatusIn(start, userId,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
- }
- Map<CollectionSource, List<Order>> orderMap = orders.stream().collect(Collectors.groupingBy(Order::getSource));
- Map<String, BigDecimal> official = null;
- if (CollUtil.isNotEmpty(orderMap.get(CollectionSource.OFFICIAL))) {
- official = orderMap.get(CollectionSource.OFFICIAL)
- .stream()
- .collect(Collectors.groupingBy(
- item -> DateTimeFormatter.ofPattern("yyyy-MM-dd")
- .format(item.getCreatedAt()), Collectors
- .mapping(Order::getTotalPrice,
- Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
- }
- Map<String, BigDecimal> transfer = null;
- if (CollUtil.isNotEmpty(orderMap.get(CollectionSource.TRANSFER))) {
- transfer = orderMap.get(CollectionSource.TRANSFER)
- .stream()
- .collect(Collectors.groupingBy(
- item -> DateTimeFormatter.ofPattern("yyyy-MM-dd")
- .format(item.getCreatedAt()), Collectors
- .mapping(Order::getTotalPrice,
- Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
- }
- trend.put("official", official);
- trend.put("transfer", transfer);
- return trend;
- }
- public String top(LocalDateTime start, LocalDateTime end, int size) {
- List<Map<String, Object>> maps = tokenHistoryRepo.sumPrice(start, end, size);
- return JSONObject.toJSONString(maps);
- }
- public Map<String, BigDecimal> orderPriceTrendV2(String yearMonth, Long userId, Long companyId) {
- YearMonth month = YearMonth.parse(yearMonth);
- LocalDateTime end = month.atEndOfMonth().atTime(LocalTime.MAX);
- LocalDateTime start = month.atDay(1).atStartOfDay();
- User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("无用户"));
- List<Order> orders;
- Map<String, BigDecimal> map = new HashMap<>();
- if (user.isAdmin()) {
- orders = orderRepo.findAllByCreatedAtBetweenAndStatusInAndCompanyIdAndOrderTypeNot(start, end,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH), companyId, OrderType.MIX);
- BigDecimal allRecharged = balanceRecordRepo.sumRechargeToday(start, end);
- map.put("recharged", allRecharged);
- } else {
- orders = orderRepo.findAllByCreatedAtBetweenAndMinterIdAndStatusIn(start, end, userId,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
- }
- map.put("official", orders.stream().filter(order -> order.getSource().equals(CollectionSource.OFFICIAL))
- .map(Order::getPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
- map.put("transfer", orders.stream().filter(order -> order.getSource().equals(CollectionSource.TRANSFER))
- .map(Order::getPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
- return map;
- }
- //其他平台统计
- public Map<String, Object> otherStatistic() {
- Map<String, Object> resultMap = new HashMap<>();
- Map<String, Object> amountMap = new HashMap<>();
- Map<String, Object> transfer = new HashMap<>();
- Map<String, Object> official = new HashMap<>();
- Map<String, Object> transferNum = new HashMap<>();
- Map<String, Object> officialNum = new HashMap<>();
- Map<String, Object> userNum = new HashMap<>();
- Map<String, Object> numMap = new HashMap<>();
- //modern point
- try {
- String mpToken = getToken("admin", "pZ&VYa^Na&l6n^sMMdDtL", "https://modern.9space.vip/auth/login");
- Map<String, Object> mpParams = new HashMap<>();
- String mpResultString = httpPost(mpParams, "https://modern.9space.vip/statistic/total", mpToken);
- JSONObject mpResult = JSONObject.parseObject(mpResultString);
- transfer.put("MP", mpResult.getBigDecimal("transferPrice"));
- transferNum.put("MP", mpResult.getLong("transferNum"));
- official.put("MP", mpResult.getBigDecimal("officialPrice"));
- officialNum.put("MP", mpResult.getLong("officialNum"));
- userNum.put("MP", mpResult.getLong("userNum"));
- } catch (Exception ignored) {
- }
- //art
- try {
- String artToken = getToken("xingadmin", "eq6bVqLqkZpoqLpH", "https://art.hopesilence.com/auth/login");
- Map<String, Object> artParams = new HashMap<>();
- String artResultString = httpPost(artParams, "https://art.hopesilence.com/statistic/total", artToken);
- JSONObject artResult = JSONObject.parseObject(artResultString);
- transfer.put("ART", artResult.getBigDecimal("transferPrice"));
- transferNum.put("ART", artResult.getLong("transferNum"));
- official.put("ART", artResult.getBigDecimal("officialPrice"));
- officialNum.put("ART", artResult.getLong("officialNum"));
- userNum.put("ART", artResult.getLong("userNum"));
- } catch (Exception ignored) {
- }
- //cosmos
- try {
- String cosToken = getToken("xingadmin", "EnLs#(CkQdLS23BaY", "https://cos.9space.vip/auth/login");
- Map<String, Object> params = new HashMap<>();
- params.put("page", 0);
- params.put("search", "");
- params.put("size", 1);
- params.put("sort", "createdAt,desc");
- Map<String, Object> query = new HashMap<>();
- query.put("collectionId", "");
- query.put("createdAt", "");
- query.put("name", "");
- query.put("officialCollectionId", "");
- query.put("orderNo", "");
- query.put("transactionId", "");
- query.put("del", false);
- query.put("projectId", "1");
- query.put("source", "TRANSFER");
- query.put("status", "FINISH");
- params.put("query", query);
- String resultString = httpPost(params, "https://cos.9space.vip/order/all", cosToken);
- JSONObject result = JSONObject.parseObject(resultString);
- BigDecimal transferAmount = result.getBigDecimal("totalAmount");
- String transferElements = result.getString("totalElements");
- transfer.put("COS", transferAmount);
- transferNum.put("COS", transferElements);
- query.put("source", "OFFICIAL");
- params.put("query", query);
- resultString = httpPost(params, "https://cos.9space.vip/order/all", cosToken);
- result = JSONObject.parseObject(resultString);
- BigDecimal officialAmount = result.getBigDecimal("totalAmount");
- String officialElements = result.getString("totalElements");
- official.put("COS", officialAmount);
- officialNum.put("COS", officialElements);
- Map<String, Object> userQuery = new HashMap<>();
- userQuery.put("createdAt", "");
- userQuery.put("del", false);
- userQuery.put("phone", "");
- userQuery.put("invitor", "");
- userQuery.put("projectId", "1");
- params.put("query", userQuery);
- //用户
- resultString = httpPost(params, "https://cos.9space.vip/user/all", cosToken);
- result = JSONObject.parseObject(resultString);
- Long cosUserCount = result.getLong("totalElements");
- userNum.put("COS", cosUserCount);
- } catch (Exception ignored2) {
- }
- //第九空间
- try {
- String ninthToken = getToken("xingadmin", "123456", "https://nft.9space.vip/auth/login");
- Map<String, Object> params1 = new HashMap<>();
- params1.put("page", 0);
- params1.put("search", "");
- params1.put("size", 1);
- params1.put("sort", "createdAt,desc");
- Map<String, Object> query1 = new HashMap<>();
- query1.put("collectionId", "");
- query1.put("createdAt", "");
- query1.put("name", "");
- query1.put("officialCollectionId", "");
- query1.put("orderNo", "");
- query1.put("transactionId", "");
- query1.put("del", false);
- query1.put("projectId", "0");
- query1.put("source", "TRANSFER");
- query1.put("status", "FINISH");
- params1.put("query", query1);
- //二手市场
- String resultString1 = httpPost(params1, "https://nft.9space.vip/order/all", ninthToken);
- JSONObject result1 = JSONObject.parseObject(resultString1);
- BigDecimal transferAmount1 = result1.getBigDecimal("totalAmount");
- String transferElements1 = result1.getString("totalElements");
- transfer.put("NINTH", transferAmount1);
- transferNum.put("NINTH", transferElements1);
- query1.put("source", "OFFICIAL");
- params1.put("query", query1);
- //官方订单
- resultString1 = httpPost(params1, "https://nft.9space.vip/order/all", ninthToken);
- result1 = JSONObject.parseObject(resultString1);
- BigDecimal officialAmount1 = result1.getBigDecimal("totalAmount");
- String officialElements1 = result1.getString("totalElements");
- official.put("NINTH", officialAmount1);
- officialNum.put("NINTH", officialElements1);
- Map<String, Object> userQuery1 = new HashMap<>();
- userQuery1.put("createdAt", "");
- userQuery1.put("del", false);
- userQuery1.put("phone", "");
- userQuery1.put("invitor", "");
- userQuery1.put("projectId", "0");
- params1.put("query", userQuery1);
- //用户
- resultString1 = httpPost(params1, "https://nft.9space.vip/user/all", ninthToken);
- result1 = JSONObject.parseObject(resultString1);
- Long ninthUserCount = result1.getLong("totalElements");
- userNum.put("NINTH", ninthUserCount);
- } catch (Exception ignored) {
- }
- amountMap.put("transfer", transfer);
- amountMap.put("official", official);
- numMap.put("transfer", transferNum);
- numMap.put("official", officialNum);
- numMap.put("userCount", userNum);
- resultMap.put("priceInfo", amountMap);
- resultMap.put("numInfo", numMap);
- return resultMap;
- }
- public String httpPost(Map<String, Object> params, String url, String token) {
- Map<String, String> headers = new HashMap<>();
- headers.put("Authorization", "Bearer " + token);
- headers.put("Content-Type", "application/json; charset=UTF-8");
- headers.put("Accept", "application/json, text/plain, */*");
- return HttpRequest.post(url)
- .contentType(HttpRequest.CONTENT_TYPE_JSON)
- .headers(headers)
- .send(JSON.toJSONString(params))
- .body();
- }
- public String getToken(String username, String password, String url) {
- Map<String, Object> params = new HashMap<>();
- Map<String, String> headers = new HashMap<>();
- params.put("username", username);
- params.put("password", password);
- return HttpRequest.post(url)
- .contentType("application/x-www-form-urlencoded")
- .headers(headers)
- .form(params)
- .body();
- }
- public Map<String, Map<String, Object>> statisticDetail() {
- Map<String, Map<String, Object>> result = new HashMap<>();
- //今日
- LocalDateTime todayStart = LocalDate.now().atStartOfDay();
- LocalDateTime todayEnd = LocalDateTime.now();
- Map<String, Object> today = statisticDetail(todayStart, todayEnd);
- result.put("today", today);
- LocalDateTime lastStart = LocalDate.now().atStartOfDay().minusDays(1);
- LocalDateTime lastEnd = LocalDate.now().atTime(LocalTime.MAX).minusDays(1);
- Map<String, Object> last = statisticDetail(lastStart, lastEnd);
- result.put("yesterday", last);
- LocalDateTime yesterStart = LocalDate.now().atStartOfDay().minusDays(2);
- LocalDateTime yesterEnd = LocalDate.now().atTime(LocalTime.MAX).minusDays(2);
- Map<String, Object> yesterday = statisticDetail(yesterStart, yesterEnd);
- result.put("last", yesterday);
- return result;
- }
- public Map<String, Object> statisticDetail(LocalDateTime todayStart, LocalDateTime todayEnd) {
- Map<String, Object> today = new HashMap<>();
- //充值
- BigDecimal rcToday = Optional.ofNullable(balanceRecordRepo.sumRechargeToday(todayStart, todayEnd))
- .orElse(BigDecimal.ZERO);
- today.put("recharge", rcToday);
- //提现
- BigDecimal wdToday = Optional.ofNullable(balanceRecordRepo.sumWithdrawToday(todayStart, todayEnd))
- .orElse(BigDecimal.ZERO);
- today.put("withdraw", wdToday);
- //星图
- BigDecimal paToday = Optional.ofNullable(photoAssetRepo.sumPaid(todayStart, todayEnd)).orElse(BigDecimal.ZERO);
- today.put("photoAsset", paToday);
- List<Order> orders = orderRepo
- .findAllByCreatedAtBetweenAndStatusInAndCompanyIdAndOrderTypeNot(todayStart, todayEnd,
- Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH), 1L, OrderType.MIX);
- ///手续费
- List<BigDecimal> ros = new ArrayList<>();
- List<BigDecimal> scs = new ArrayList<>();
- for (Order order : orders) {
- BigDecimal amount = order.getTotalPrice();
- BigDecimal ro = BigDecimal.valueOf(order.getRoyalties());
- BigDecimal sc = BigDecimal.valueOf(order.getServiceCharge());
- BigDecimal orderRo = amount.multiply(ro).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_DOWN);
- ros.add(orderRo);
- BigDecimal orderSc = amount.multiply(sc).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_DOWN);
- scs.add(orderSc);
- }
- BigDecimal todayRo = Optional.of(ros.stream().reduce(BigDecimal::add).orElse(BigDecimal.ZERO))
- .orElse(BigDecimal.ZERO);
- today.put("royalties", todayRo);
- //版权费
- BigDecimal todaySc = scs.stream().reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
- today.put("serviceCharge", todaySc);
- //域名
- BigDecimal domainOrder = domainOrderRepo.sumToday(todayStart, todayEnd);
- today.put("domainOrder", Optional.ofNullable(domainOrder).orElse(BigDecimal.ZERO));
- //saas
- BigDecimal saas = orderRepo.sumSaas(todayStart, todayEnd);
- today.put("saas", Optional.ofNullable(saas).orElse(BigDecimal.ZERO));
- return today;
- }
- }
|