lajiyouxi-xu 2 rokov pred
rodič
commit
93736ab5f1

+ 12 - 0
pom.xml

@@ -579,6 +579,18 @@
             <artifactId>javase</artifactId>
             <version>3.3.0</version>
         </dependency>
+
+        <dependency>
+            <groupId>javax.json</groupId>
+            <artifactId>javax.json-api</artifactId>
+            <version>1.1.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.glassfish</groupId>
+            <artifactId>javax.json</artifactId>
+            <version>1.1.4</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 7 - 3
src/main/java/com/izouma/nineth/domain/Rice.java

@@ -7,7 +7,8 @@ import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 
-import javax.persistence.*;
+import javax.persistence.Column;
+import javax.persistence.Entity;
 
 
 @Data
@@ -18,6 +19,7 @@ import javax.persistence.*;
 public class Rice extends BaseEntity {
 
     @ApiModelProperty("用户ID")
+    @Column(name = "user_id")
     private Long userId;
 
     @ApiModelProperty("头像")
@@ -35,8 +37,6 @@ public class Rice extends BaseEntity {
     @ApiModelProperty("签到次数")
     private Long signCount;
 
-    @ApiModelProperty("当前用户排名")
-    private Long selfRank;
 
     @ApiModelProperty("当前用户积分")
     private Long selfScore;
@@ -44,5 +44,9 @@ public class Rice extends BaseEntity {
     @ApiModelProperty("经验值")
     private Long EmpiricalValue;
 
+    @ApiModelProperty("当前用户排行")
+    @Column(name = "score_rank")
+    private Integer scoreRank;
+
 
 }

+ 1 - 10
src/main/java/com/izouma/nineth/utils/R.java → src/main/java/com/izouma/nineth/dto/R.java

@@ -1,39 +1,30 @@
-package com.izouma.nineth.utils;
-
+package com.izouma.nineth.dto;
 
 import lombok.Data;
 import java.util.HashMap;
 import java.util.Map;
-
 /**
  * 通用返回结果,服务端响应的数据最终都会封装成此对象
  * @param <T>
  */
 @Data
 public class R<T> {
-
     private Integer code; //编码:1成功,0和其它数字为失败
-
     private String msg; //错误信息
-
     private T data; //数据
-
     private Map map = new HashMap(); //动态数据
-
     public static <T> R<T> success(T object) {
         R<T> r = new R<T>();
         r.data = object;
         r.code = 1;
         return r;
     }
-
     public static <T> R<T> error(String msg) {
         R r = new R();
         r.msg = msg;
         r.code = 0;
         return r;
     }
-
     public R<T> add(String key, Object value) {
         this.map.put(key, value);
         return this;

+ 20 - 0
src/main/java/com/izouma/nineth/repo/RiceRepo.java

@@ -1,16 +1,36 @@
 package com.izouma.nineth.repo;
 
 import com.izouma.nineth.domain.Rice;
+import io.lettuce.core.dynamic.annotation.Param;
 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 import org.springframework.data.jpa.repository.Modifying;
 import org.springframework.data.jpa.repository.Query;
 
 import javax.transaction.Transactional;
+import java.util.List;
+import java.util.Optional;
 
 public interface RiceRepo extends JpaRepository<Rice, Long>, JpaSpecificationExecutor<Rice> {
     @Query("update Rice t set t.del = true where t.id = ?1")
     @Modifying
     @Transactional
     void softDelete(Long id);
+
+    @Query(value = "select * from rice  where user_id = ?1 ", nativeQuery = true)
+    Optional<Rice> findByUserId(Long userId);
+
+
+
+    @Query("update Rice t set t.nickname = ?2 where t.userId = ?1")
+    @Modifying
+    @Transactional
+    void updateNickName(Long userId, String nickname);
+
+
+
+    @Query("SELECT COUNT(r) + 1 FROM Rice r WHERE r.selfScore > :score")
+    Integer findRankByScore(@Param("score") Long score);
+
+    List<Rice> findTop100ByOrderBySelfScoreDesc();
 }

+ 157 - 0
src/main/java/com/izouma/nineth/service/RiceService.java

@@ -1,20 +1,177 @@
 package com.izouma.nineth.service;
 
 import com.izouma.nineth.domain.Rice;
+import com.izouma.nineth.domain.User;
 import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.dto.R;
+import com.izouma.nineth.exception.BusinessException;
 import com.izouma.nineth.repo.RiceRepo;
+import com.izouma.nineth.repo.UserRepo;
 import com.izouma.nineth.utils.JpaUtils;
+import com.izouma.nineth.utils.SecurityUtils;
 import lombok.AllArgsConstructor;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Page;
 import org.springframework.stereotype.Service;
 
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import java.io.StringReader;
+import java.util.*;
+
 @Service
 @AllArgsConstructor
 public class RiceService {
 
+    private static final int MAX_NICKNAME_LENGTH = 6;
+    private static final String UPDATE_SUCCESS_MSG = "修改成功";
+
+    @Autowired
     private RiceRepo riceRepo;
 
+
+
+    @Autowired
+    private UserRepo userRepo;
+
+    @Autowired
+    private SysConfigService sysConfigService;
+
     public Page<Rice> all(PageQuery pageQuery) {
         return riceRepo.findAll(JpaUtils.toSpecification(pageQuery, Rice.class), JpaUtils.toPageRequest(pageQuery));
     }
+
+    public Optional<Rice> getCurrentRiceUser(User authenticatedUser) throws BusinessException {
+        Long id = authenticatedUser.getId();
+        Optional<User> byId = userRepo.findByIdAndDelFalse(id);
+        String username = null;
+        String avatar = null;
+        if (byId.isPresent()) {
+            User user = byId.get();
+            username = user.getUsername();
+            avatar = user.getAvatar();
+        } else {
+            throw new BusinessException("用户不存在");
+        }
+
+        Optional<Rice> byUserId = riceRepo.findByUserId(id);
+        if (byUserId.isPresent()) {
+            return byUserId;
+        } else {
+            Rice rice = new Rice();
+            rice.setUserId(id);
+            rice.setAvatar(avatar);
+            rice.setNickname(username);
+            rice.setLevel(0L);
+            rice.setWaterDropCount(0L);
+            rice.setSignCount(0L);
+            rice.setSelfScore(0L);
+            rice.setEmpiricalValue(0L);
+            riceRepo.save(rice);
+            return Optional.of(rice);
+        }
+    }
+
+
+    public R updateNickName(Long userId, String nickname) {
+        String trimmedNickname = StringUtils.trim(nickname);
+        if (trimmedNickname.length() > MAX_NICKNAME_LENGTH) {
+            return R.error("昵称不能超过" + MAX_NICKNAME_LENGTH + "个字符");
+        }
+        riceRepo.updateNickName(userId, trimmedNickname);
+        return R.success(UPDATE_SUCCESS_MSG);
+    }
+
+
+    /**
+     * 在RiceService中,我们注入了SysConfigService和RiceRepo,这两个类的实现需要您自己完成。
+     * 在getCurrentLevel()方法中,我们将原来在@GetMapping注解中的代码全部迁移到了这里,并将返回类型从R<String>改为了String,
+     * 因为我们不再需要将查询结果封装为R对象了。最后,我们根据返回结果的不同,抛出了不同的异常,这些异常同样需要您自己定义实现。
+     * @return
+     * @param empiricalValue
+     */
+    public String 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();
+            empiricalValue= rice.getEmpiricalValue();
+
+            JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
+            JsonArray jsonArray = jsonReader.readArray();
+
+            String currentLevel = null;
+            for (int i = 0; i < jsonArray.size(); i++) {
+                JsonObject jsonObject = jsonArray.getJsonObject(i);
+                int start = jsonObject.getInt("start");
+
+                if (empiricalValue >= start) {
+                    currentLevel = jsonObject.getString("name");
+                }
+            }
+
+            if (currentLevel != null) {
+                return currentLevel;
+            } else {
+                throw new BusinessException("没有配置对应的等级对应经验值");
+            }
+        } else {
+            throw new BusinessException("用户不存在");
+        }
+    }
+
+
+    /**
+     * 获取当前用户积分
+     */
+    public R<String> getCurrentScore() {
+        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
+        Long authId = authenticatedUser.getId();
+        Optional<Rice> byUserId = riceRepo.findByUserId(authId);
+        if (byUserId.isPresent()) {
+            Rice rice = byUserId.get();
+            Long selfScore = rice.getSelfScore();
+            return R.success("获取到当前用户积分").add("selfScore",selfScore);
+        }
+        return R.error("获取失败");
+    }
+
+
+    //在RiceService中添加一个方法用于更新所有用户的排名。
+    public void updateScoreRank() {
+        List<Rice> allRices = riceRepo.findAll();
+        allRices.sort(Comparator.comparing(Rice::getSelfScore).reversed());
+        for (int i = 0; i < allRices.size(); i++) {
+            Rice rice = allRices.get(i);
+            rice.setScoreRank(i + 1);
+            riceRepo.save(rice);
+        }
+    }
+
+
+    public List<Map<String, Object>> getTop100() {
+        List<Rice> top100Rices = riceRepo.findTop100ByOrderBySelfScoreDesc();
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (Rice rice : top100Rices) {
+            Map<String, Object> map = new HashMap<>();
+            map.put("avatarUrl", rice.getAvatar());
+            map.put("nickName", rice.getNickname());
+            map.put("level", rice.getLevel());
+            map.put("scoreRank", rice.getScoreRank());
+            map.put("selfScore", rice.getSelfScore());
+            result.add(map);
+        }
+        return result;
+    }
+
+
+
+
+
+
 }

+ 73 - 3
src/main/java/com/izouma/nineth/web/RiceController.java

@@ -1,12 +1,24 @@
 package com.izouma.nineth.web;
+
+
 import com.izouma.nineth.domain.Rice;
-import com.izouma.nineth.service.RiceService;
+import com.izouma.nineth.domain.User;
 import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.dto.R;
 import com.izouma.nineth.exception.BusinessException;
 import com.izouma.nineth.repo.RiceRepo;
+import com.izouma.nineth.repo.SysConfigRepo;
+import com.izouma.nineth.repo.UserDetailRepo;
+import com.izouma.nineth.repo.UserRepo;
+import com.izouma.nineth.service.RiceService;
+import com.izouma.nineth.service.SysConfigService;
+import com.izouma.nineth.service.UserDetailService;
+import com.izouma.nineth.service.UserService;
 import com.izouma.nineth.utils.ObjUtils;
+import com.izouma.nineth.utils.SecurityUtils;
 import com.izouma.nineth.utils.excel.ExcelUtils;
 import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.data.domain.Page;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
@@ -14,15 +26,28 @@ import org.springframework.web.bind.annotation.*;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 
 @RestController
 @RequestMapping("/rice")
 @AllArgsConstructor
+@Slf4j
 public class RiceController extends BaseController {
     private RiceService riceService;
     private RiceRepo riceRepo;
+    private UserDetailService userDetailService;
+    private UserDetailRepo userDetailRepo;
+    private UserService userService;
+    private UserRepo userRepo;
+
+    private SysConfigService sysConfigService;
+    private SysConfigRepo sysConfigRepo;
+
+    private static final int MAX_NICKNAME_LENGTH = 14;
+    private static final String UPDATE_SUCCESS_MSG = "修改成功";
 
-    //@PreAuthorize("hasRole('ADMIN')")
+    @PreAuthorize("hasRole('ADMIN')")
     @PostMapping("/save")
     public Rice save(@RequestBody Rice record) {
         if (record.getId() != null) {
@@ -34,7 +59,7 @@ public class RiceController extends BaseController {
     }
 
 
-    //@PreAuthorize("hasRole('ADMIN')")
+    @PreAuthorize("hasRole('ADMIN')")
     @PostMapping("/all")
     public Page<Rice> all(@RequestBody PageQuery pageQuery) {
         return riceService.all(pageQuery);
@@ -56,5 +81,50 @@ public class RiceController extends BaseController {
         List<Rice> data = all(pageQuery).getContent();
         ExcelUtils.export(response, data);
     }
+
+    //点击水稻游戏后对riceuser进行初始化赋值
+    @GetMapping("/current")
+    public R<Optional<Rice>> getCurrentUser() throws BusinessException {
+        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
+        return R.success(riceService.getCurrentRiceUser(authenticatedUser));
+    }
+
+    //修改用户昵称
+    @PostMapping("/updateNickName")
+    public R updateNickName(@RequestParam("userId") Long userId, @RequestParam("nickname") String nickname) {
+        return riceService.updateNickName(userId, nickname);
+    }
+
+    //等级显示
+    @GetMapping("/showLevel")
+    public R<String> getCurrentLevel() {
+        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
+        Long authId = authenticatedUser.getId();
+        Optional<Rice> byUserId = riceRepo.findByUserId(authId);
+        if (byUserId.isPresent()) {
+            Rice rice = byUserId.get();
+            String currentLevel = riceService.getCurrentLevel(rice.getEmpiricalValue());
+            return R.success("查询成功").add("riceLevel", currentLevel);
+        } else {
+            throw new BusinessException("用户不存在");
+        }
+    }
+
+    //获取用户积分
+    @GetMapping("/selfScore")
+    public R<String> getCurrentScore() {
+        return riceService.getCurrentScore();
+    }
+
+
+    //一个获取积分排行榜的接口
+    @GetMapping("/scoreRanking")
+    public R<List<Map<String, Object>>> getScoreRanking() {
+        List<Map<String, Object>> top100 = riceService.getTop100();
+        return R.success(top100);
+    }
+
+
+
 }
 

+ 1 - 1
src/main/java/com/izouma/nineth/web/RiceMonkeyTextController.java

@@ -1,9 +1,9 @@
 package com.izouma.nineth.web;
 
 
+import com.izouma.nineth.dto.R;
 import com.izouma.nineth.repo.SysConfigRepo;
 import com.izouma.nineth.service.SysConfigService;
-import com.izouma.nineth.utils.R;
 import lombok.AllArgsConstructor;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;