“xubinhui 2 лет назад
Родитель
Сommit
ef93ee14ca

+ 140 - 206
src/main/java/com/izouma/nineth/service/RiceService.java

@@ -35,6 +35,7 @@ import java.time.LocalTime;
 import java.time.ZoneOffset;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
 
 import static com.izouma.nineth.enums.RiceWaterType.ACTIVITY_AWARD;
 
@@ -61,42 +62,32 @@ public class RiceService {
     //点击水稻游戏,进行初始化
     public Rice getCurrentRiceUser(User authenticatedUser) throws BusinessException {
         Long id = authenticatedUser.getId();
-        Optional<User> byId = userRepo.findByIdAndDelFalse(id);
-        String nickname = null;
-        String avatar = null;
-        String phone = null;
-        if (byId.isPresent()) {
-            User user = byId.get();
-            nickname = user.getNickname();
-            avatar = user.getAvatar();
-            phone = user.getPhone();
-        } else {
-            throw new BusinessException("用户不存在");
-        }
-        Optional<Rice> byUserId = riceRepo.findByUserId(id);
-        if (byUserId.isPresent()) {
-            Rice rice = byUserId.get();
-            rice.setAvatar(avatar);
-            rice.setPhone(phone);
-            riceRepo.save(rice);
-            return rice;
-        } else {
-            Rice rice = new Rice();
-            rice.setUserId(id);
-            rice.setAvatar(avatar);
-            rice.setNickname(nickname);
-            rice.setPhone(phone);
-            rice.setLevel(0L);
-            rice.setSignCount(0L);
-            rice.setSelfScore(0L);
-            rice.setSelfActivityScore(0L);
-            rice.setEmpiricalValue(0L);
-            riceRepo.save(rice);
-            return rice;
-        }
+        User user = userRepo.findByIdAndDelFalse(id).orElseThrow(() -> new BusinessException("用户不存在"));
+        String nickname = user.getNickname();
+        String avatar = user.getAvatar();
+        String phone = user.getPhone();
+
+        Rice rice = riceRepo.findByUserId(id).orElseGet(() -> {
+            Rice newRice = new Rice();
+            newRice.setUserId(id);
+            newRice.setNickname(nickname);
+            newRice.setAvatar(avatar);
+            newRice.setPhone(phone);
+            newRice.setLevel(0L);
+            newRice.setSignCount(0L);
+            newRice.setSelfScore(0L);
+            newRice.setSelfActivityScore(0L);
+            newRice.setEmpiricalValue(0L);
+            return riceRepo.save(newRice);
+        });
+
+        rice.setAvatar(avatar);
+        rice.setPhone(phone);
+        return riceRepo.save(rice);
     }
 
 
+
     //修改昵称
     public R updateNickName(Long userId, String nickname) {
         String trimmedNickname = StringUtils.trim(nickname);
@@ -110,123 +101,87 @@ public class RiceService {
 
     //获取当前等级
     public Map<String, Object> getCurrentLevel(Long empiricalValue) {
-        String jsonString = sysConfigService.getString("rice_level");
         User authenticatedUser = SecurityUtils.getAuthenticatedUser();
         Long authId = authenticatedUser.getId();
-        Optional<Rice> byUserId = riceRepo.findByUserId(authId);
-        if (byUserId.isPresent()) {
-            Rice rice = byUserId.get();
-            JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
-            JsonArray jsonArray = jsonReader.readArray();
-            Long currentLevel = null;
-            Long currentStart = null;
-            Long nextStart = null;
-            for (int i = 0; i < jsonArray.size(); i++) {
-                JsonObject jsonObject = jsonArray.getJsonObject(i);
-                Long start = Long.valueOf(jsonObject.getInt("start"));
-                if (empiricalValue >= start && empiricalValue < (i < jsonArray.size() - 1 ? Long.valueOf(jsonArray.getJsonObject(i + 1).getInt("start")) : Long.MAX_VALUE)) {
-                    String currentLevelStr = jsonObject.getString("name").replace("Lv", "");
-                    currentLevel = Long.parseLong(currentLevelStr);
-                    rice.setLevel(currentLevel);
-                    riceRepo.save(rice);
-                    currentStart = Long.valueOf(jsonObject.getInt("start"));
-                    if (i < jsonArray.size() - 1) {
-                        JsonObject nextObject = jsonArray.getJsonObject(i + 1);
-                        nextStart = nextObject.getJsonNumber("start").longValue();
-                    }
-                    break;
-                }
-            }
 
-            if (currentLevel != null && currentStart != null) {
-                Map<String, Object> result = new HashMap<>();
-                result.put("currentLevel", currentLevel);
-                double levelUpPercentage;
-                if (nextStart != null) {
-                    levelUpPercentage = (double) (empiricalValue - currentStart) / (nextStart - currentStart);
-                } else {
-                    levelUpPercentage = 1.0;
-                }
-                result.put("levelUpPercentage", levelUpPercentage);
-                return result;
-            } else {
-                throw new BusinessException("没有配置对应的等级对应经验值");
-            }
-        } else {
-            throw new BusinessException("用户不存在");
-        }
+        Optional<Rice> optionalRice = riceRepo.findByUserId(authId);
+        Rice rice = optionalRice.orElseThrow(() -> new BusinessException("用户不存在"));
+
+        Map<String, Object> result = getRiceLevelJsonArray().stream()
+                                                            .map(JsonObject.class::cast)
+                                                            .map(jsonObject -> {
+                                                                Long start = Long.valueOf(jsonObject.getInt("start"));
+                                                                String currentLevelStr = jsonObject.getString("name").replace("Lv", "");
+                                                                Long currentLevel = Long.parseLong(currentLevelStr);
+                                                                return new AbstractMap.SimpleEntry<>(start, currentLevel);
+                                                            })
+                                                            .filter(entry -> empiricalValue >= entry.getKey())
+                                                            .reduce((a, b) -> b)
+                                                            .map(entry -> {
+                                                                Long currentStart = entry.getKey();
+                                                                Long currentLevel = entry.getValue();
+                                                                rice.setLevel(currentLevel);
+                                                                riceRepo.save(rice);
+                                                                Long nextStart = getRiceLevelJsonArray().stream()
+                                                                                                        .skip(1)
+                                                                                                        .findFirst()
+                                                                                                        .map(JsonObject.class::cast)
+                                                                                                        .map(jsonObject -> jsonObject.getJsonNumber("start").longValue())
+                                                                                                        .orElse(null);
+
+                                                                Map<String, Object> map = new HashMap<>();
+                                                                map.put("currentLevel", currentLevel);
+                                                                double levelUpPercentage = nextStart != null ? (double) (empiricalValue - currentStart) / (nextStart - currentStart) : 1.0;
+                                                                map.put("levelUpPercentage", levelUpPercentage);
+                                                                return map;
+                                                            })
+                                                            .orElseThrow(() -> new BusinessException("没有配置对应的等级对应经验值"));
+
+        return result;
+    }
+
+    private JsonArray getRiceLevelJsonArray() {
+        String jsonString = sysConfigService.getString("rice_level");
+        JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
+        return jsonReader.readArray();
     }
 
 
+
     /**
      * 任务初始化.显示各个任务能否点击
      *
      * @return R<?>
      */
     public R<?> taskInitialization() {
-
         Optional<Rice> byUserId = riceRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId());
-        if (byUserId.isPresent()) {
-            Rice rice = byUserId.get();
-            int i = riceInviteRepo.countRiceInviteBy(rice.getUserId(), getTodayStartTime(), getTodayEndTime());
-            int InviteHelpOthersCounts = riceInviteRepo.countRiceInviteByHelperId(SecurityUtils.getAuthenticatedUser().getId(), getTodayStartTime(), getTodayEndTime());
-
-            Long lastSignInTime = rice.getLastSignInTime();
-            Long currentTime = System.currentTimeMillis();
-
-            Boolean isCanExchangeActivityScoreForWater;
-            Boolean isInvited;
-            Boolean isCanExchangeScore;
-
-            if (rice.getExchangeCount() < 10 && rice.getSelfScore() >= 10) {
-                isCanExchangeScore = true;
-            } else {
-                isCanExchangeScore = false;
-            }
-
-            if (rice.getInviteCount() <= 1) {
-                isInvited = false;
-
-            } else {
-                isInvited = true;
-            }
+        if (!byUserId.isPresent()) {
+            return R.error("查询失败");
+        }
 
+        Rice rice = byUserId.get();
+        int i = riceInviteRepo.countRiceInviteBy(rice.getUserId(), getTodayStartTime(), getTodayEndTime());
+        int InviteHelpOthersCounts = riceInviteRepo.countRiceInviteByHelperId(SecurityUtils.getAuthenticatedUser().getId(), getTodayStartTime(), getTodayEndTime());
 
-            if (rice.getSelfActivityScore() >= 2) {
-                isCanExchangeActivityScoreForWater = true;
-            } else {
-                isCanExchangeActivityScoreForWater = false;
-            }
-            // 判断上次签到时间是否为空,如果为空,则默认为从未签到过
-            if (lastSignInTime == null) {
-                return R.success("未签到").add("isSignedIn", false)
-                        .add("exchangeCount", rice.getExchangeCount())
-                        .add("isCanExchangeActivityScoreForWater", isCanExchangeActivityScoreForWater)
-                        .add("isInvited", isInvited)
-                        .add("isCanExchangeScore", isCanExchangeScore)
-                        .add("InviteHelpOthersCounts", InviteHelpOthersCounts);
-            }
-            // 判断今天是否已经签到过
-            if (DateUtils.isSameDay(new Date(lastSignInTime), new Date(currentTime))) {
-                return R.success("已签到").add("isSignedIn", true)
-                        .add("exchangeCount", rice.getExchangeCount())
-                        .add("isCanExchangeActivityScoreForWater", isCanExchangeActivityScoreForWater)
-                        .add("isInvited", isInvited)
-                        .add("isCanExchangeScore", isCanExchangeScore)
-                        .add("InviteHelpOthersCounts", InviteHelpOthersCounts);
-            } else {
-                return R.success("未签到").add("isSignedIn", false)
-                        .add("exchangeCount", rice.getExchangeCount())
-                        .add("isCanExchangeActivityScoreForWater", isCanExchangeActivityScoreForWater)
-                        .add("isInvited", isInvited)
-                        .add("isCanExchangeScore", isCanExchangeScore)
-                        .add("InviteHelpOthersCounts", InviteHelpOthersCounts);
-            }
-        }
-        return R.error("查询失败");
+        Long lastSignInTime = rice.getLastSignInTime();
+        Long currentTime = System.currentTimeMillis();
+
+        boolean isCanExchangeActivityScoreForWater = rice.getSelfActivityScore() >= 2;
+        boolean isInvited = rice.getInviteCount() > 1;
+        boolean isCanExchangeScore = rice.getExchangeCount() < 10 && rice.getSelfScore() >= 10;
+        boolean isSignedIn = lastSignInTime != null && DateUtils.isSameDay(new Date(lastSignInTime), new Date(currentTime));
+
+        return R.success(isSignedIn ? "已签到" : "未签到")
+                .add("isSignedIn", isSignedIn)
+                .add("exchangeCount", rice.getExchangeCount())
+                .add("isCanExchangeActivityScoreForWater", isCanExchangeActivityScoreForWater)
+                .add("isInvited", isInvited)
+                .add("isCanExchangeScore", isCanExchangeScore)
+                .add("InviteHelpOthersCounts", InviteHelpOthersCounts);
     }
 
 
+
     /**
      * 获取当前用户积分
      */
@@ -239,15 +194,13 @@ public class RiceService {
 
     //在RiceService中添加一个方法用于更新所有用户的排名。
     public void updateLvRank() {
-        List<Rice> allRices = riceRepo.findAll();
-        for (int i = 0; i < allRices.size(); i++) {
-            Rice rice = allRices.get(i);
+        String jsonString = sysConfigService.getString("rice_level");
+        JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
+        JsonArray jsonArray = jsonReader.readArray();
 
-            String jsonString = sysConfigService.getString("rice_level");
-            JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
-            JsonArray jsonArray = jsonReader.readArray();
+        List<Rice> allRices = riceRepo.findAll();
+        allRices.forEach(rice -> {
             Long currentLevel = null;
-
             for (int j = 0; j < jsonArray.size(); j++) {
                 JsonObject jsonObject = jsonArray.getJsonObject(j);
                 Long start = Long.valueOf(jsonObject.getInt("start"));
@@ -255,57 +208,38 @@ public class RiceService {
                     String currentLevelStr = jsonObject.getString("name").replace("Lv", "");
                     currentLevel = Long.parseLong(currentLevelStr);
                     rice.setLevel(currentLevel);
-                    riceRepo.save(rice);
                     break;
                 }
             }
-        }
+        });
+        riceRepo.saveAll(allRices);
     }
 
 
-    //一个获取积分排行榜的接口
+
     public List<RiceDTO> getTop100(Long userId) {
-        this.updateLvRank();
+       // this.updateLvRank();
         List<Rice> top100Rices = riceRepo.findTop100OrderByEmpiricalValueDesc();
-        List<RiceDTO> result = new ArrayList<>();
-
-        // 计算自己的排名
-//        int selfRank = 0;
-//        for (int i = 0; i < top100Rices.size(); i++) {
-//            if (top100Rices.get(i).getId().equals(userId)) {
-//                selfRank = i + 1;
-//                break;
-//            }
-//        }
-
-        for (int i = 0; i < top100Rices.size(); i++) {
-            Rice rice = top100Rices.get(i);
+        boolean isOnTop100 = top100Rices.size() < 100 ? true : false;
+        List<RiceDTO> result = top100Rices.stream().map(rice -> {
             RiceDTO riceDTO = new RiceDTO();
             BeanUtils.copyProperties(rice, riceDTO);
-            riceDTO.setScoreRank(i + 1);
-            // 判断是否上榜
-            if (i < 100) {
-                riceDTO.setOnTop100(true);
-            } else {
-                riceDTO.setOnTop100(false);
-            }
-            // 如果是自己,则设置自己的头像、昵称、等级和离上榜还差多少名
+            riceDTO.setScoreRank(top100Rices.indexOf(rice) + 1);
+            riceDTO.setOnTop100(isOnTop100);
             if (rice.getId().equals(userId)) {
                 riceDTO.setAvatar(rice.getAvatar());
                 riceDTO.setNickname(rice.getNickname());
                 riceDTO.setLevel(rice.getLevel());
-                if (i < 100) {
-                    riceDTO.setRankGap(0);
-                } else {
-                    riceDTO.setRankGap(i + 1 - 100);
-                }
+                riceDTO.setRankGap(isOnTop100 ? 0 : top100Rices.indexOf(rice) + 1 - 100);
             }
-            result.add(riceDTO);
-        }
+            return riceDTO;
+        }).collect(Collectors.toList());
+
         return result;
     }
 
 
+
     //获取当前等级
     public R<Map<String, Object>> showLevel() {
         Rice rice = riceRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()).orElseThrow(new BusinessException("用户不存在"));
@@ -328,47 +262,21 @@ public class RiceService {
             return R.error("用户不存在");
         }
         List<Rice> top100Rices = riceRepo.findTop100OrderByEmpiricalValueDesc();
-        List<RiceDTO> result = new ArrayList<>();
-        RiceDTO dto = new RiceDTO();
-        // 计算自己的排名
-        int selfRank = 0;
-        for (int i = 0; i < top100Rices.size(); i++) {
-            if (top100Rices.get(i).getUserId().equals(userId)) {
-                selfRank = i + 1;
-                break;
-            }
-        }
-        for (int i = 0; i < top100Rices.size(); i++) {
-            Rice rice = top100Rices.get(i);
-            RiceDTO riceDTO = new RiceDTO();
-            BeanUtils.copyProperties(rice, riceDTO);
-            riceDTO.setScoreRank(i + 1);
-            // 判断是否上榜
-            if (i < 100) {
-                riceDTO.setOnTop100(true);
-            } else {
-                riceDTO.setOnTop100(false);
-            }
-            // 如果是自己,则设置自己的头像、昵称、等级和离上榜还差多少名
-            if (rice.getUserId().equals(userId)) {
-                riceDTO.setAvatar(rice.getAvatar());
-                riceDTO.setNickname(rice.getNickname());
-                riceDTO.setLevel(rice.getLevel());
-                if (i < 100) {
-                    riceDTO.setRankGap(0);
-                } else {
-                    riceDTO.setRankGap(i + 1 - 100);
-                }
-                BeanUtils.copyProperties(riceDTO, dto);
-            }
-        }
-        if (dto == null) {
+        int selfRank = top100Rices.indexOf(rice1.get()) + 1;
+        if (selfRank == 0) {
             return R.error("用户不存在");
         }
+        RiceDTO dto = new RiceDTO();
+        Rice selfRice = top100Rices.get(selfRank - 1);
+        BeanUtils.copyProperties(selfRice, dto);
+        dto.setScoreRank(selfRank);
+        dto.setOnTop100(selfRank <= 100);
+        dto.setRankGap(Math.max(0, selfRank - 100));
         return R.success(dto);
     }
 
 
+
     //浇水
     public R<? extends Object> waterDrop(RiceWaterType riceWaterType, Long riceId) {
 
@@ -819,4 +727,30 @@ public class RiceService {
 
 
 
+    @Scheduled(cron = "0 0 12 * * ?")
+    public void updateAllRiceLevel() {
+        String jsonString = sysConfigService.getString("rice_level");
+        JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
+        JsonArray jsonArray = jsonReader.readArray();
+
+        List<Rice> allRices = riceRepo.findAll();
+        allRices.forEach(rice -> {
+            Long currentLevel = null;
+            for (int j = 0; j < jsonArray.size(); j++) {
+                JsonObject jsonObject = jsonArray.getJsonObject(j);
+                Long start = Long.valueOf(jsonObject.getInt("start"));
+                if (rice.getEmpiricalValue() >= start && rice.getEmpiricalValue() < (j < jsonArray.size() - 1 ? Long.valueOf(jsonArray.getJsonObject(j + 1).getInt("start")) : Long.MAX_VALUE)) {
+                    String currentLevelStr = jsonObject.getString("name").replace("Lv", "");
+                    currentLevel = Long.parseLong(currentLevelStr);
+                    rice.setLevel(currentLevel);
+                    break;
+                }
+            }
+        });
+        riceRepo.saveAll(allRices);
+    }
+
+
+
+
 }

+ 22 - 0
src/test/java/com/izouma/nineth/service/UserBalanceServiceTest.java

@@ -1,9 +1,14 @@
 package com.izouma.nineth.service;
 
 import com.izouma.nineth.ApplicationTests;
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.enums.BalanceType;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.UserRepo;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 
+import java.math.BigDecimal;
 import java.time.LocalDate;
 import java.util.concurrent.ExecutionException;
 
@@ -14,6 +19,9 @@ class UserBalanceServiceTest extends ApplicationTests {
     @Autowired
     private UserBalanceService userBalanceService;
 
+    @Autowired
+    private  UserRepo userRepo;
+
     @Test
     void settle() {
         userBalanceService.settle(LocalDate.of(2022, 04, 8), LocalDate.of(2022, 4, 10));
@@ -28,4 +36,18 @@ class UserBalanceServiceTest extends ApplicationTests {
     public void revert() throws ExecutionException, InterruptedException {
         userBalanceService.revert();
     }
+
+
+    @Test
+    void setBonu() {
+        //String phone = "18698398831";
+        String[] phoneNumbers = {"13148878839", "13332310629", "18595901697", "18105779531"};
+
+        for (String phone : phoneNumbers) {
+            User user = userRepo.findByPhoneAndDelFalse(phone)
+                                .orElseThrow(() -> new BusinessException("暂无"));
+            userBalanceService.modifyBalance(user.getId(), BigDecimal.valueOf(50), BalanceType.BONUS, null, false, null);
+        }
+    }
+
 }