Преглед на файлове

完善积分兑换,操作记录

lajiyouxi-xu преди 3 години
родител
ревизия
ab271353ee

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

@@ -45,7 +45,7 @@ public class Rice extends BaseEntity {
     @ApiModelProperty("当前用户积分")
     private Long selfScore;
 
-    @ApiModelProperty("当前用户积分")
+    @ApiModelProperty("当前用户活动积分")
     private Long selfActivityScore;
 
 
@@ -54,10 +54,9 @@ public class Rice extends BaseEntity {
     private Long EmpiricalValue;
 
     @Column(name = "exchange_count", columnDefinition = "int(11) DEFAULT 0 COMMENT '今日已兑换次数'")
-    @Transient
-    private Integer exchangeCount = 0;
+    private Integer exchangeCount;
 
-    @Column(name = "exchange_count", columnDefinition = "int(11) DEFAULT 0 COMMENT '今日已邀请次数'")
+    @Column(name = "Invite_count", columnDefinition = "int(11) DEFAULT 0 COMMENT '今日已邀请次数'")
     private Integer InviteCount = 0;
 
 

+ 38 - 0
src/main/java/com/izouma/nineth/domain/RiceOperationRecord.java

@@ -0,0 +1,38 @@
+package com.izouma.nineth.domain;
+
+
+import com.izouma.nineth.enums.OperationType;
+import com.izouma.nineth.enums.RiceOperationType;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Entity
+@ApiModel("操作记录表")
+public class RiceOperationRecord extends BaseEntity {
+
+    @ApiModelProperty("用户ID")
+    private Long userId;
+
+    @ApiModelProperty("类型:水滴,活动积分,积分,经验值")
+    @Enumerated(EnumType.STRING)
+    private RiceOperationType type;
+
+    @ApiModelProperty("数量")
+    private Long amount;
+
+    @ApiModelProperty("操作前的数量")
+    private Long beforeAmount;
+
+    @ApiModelProperty("操作后的数量")
+    private Long afterAmount;
+}

+ 21 - 0
src/main/java/com/izouma/nineth/enums/RiceOperationType.java

@@ -0,0 +1,21 @@
+package com.izouma.nineth.enums;
+
+public enum RiceOperationType {
+    WATER_DROP("水滴类型"),
+    SELF_SCORE("积分类型"),
+    EMPIRICAL_VALUE("经验值类型"),
+    SELF_ACTIVITY_SCORE("活动积分类型");
+
+
+
+
+    private final String description;
+
+    RiceOperationType(String description) {
+        this.description = description;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+}

+ 16 - 0
src/main/java/com/izouma/nineth/repo/RiceOperationRecordRepo.java

@@ -0,0 +1,16 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.RiceOperationRecord;
+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;
+
+public interface RiceOperationRecordRepo extends JpaRepository<RiceOperationRecord, Long>, JpaSpecificationExecutor<RiceOperationRecord> {
+    @Query("update RiceOperationRecord t set t.del = true where t.id = ?1")
+    @Modifying
+    @Transactional
+    void softDelete(Long id);
+}

+ 20 - 0
src/main/java/com/izouma/nineth/service/RiceOperationRecordService.java

@@ -0,0 +1,20 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.domain.RiceOperationRecord;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.repo.RiceOperationRecordRepo;
+import com.izouma.nineth.utils.JpaUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.stereotype.Service;
+
+@Service
+@AllArgsConstructor
+public class RiceOperationRecordService {
+
+    private RiceOperationRecordRepo riceOperationRecordRepo;
+
+    public Page<RiceOperationRecord> all(PageQuery pageQuery) {
+        return riceOperationRecordRepo.findAll(JpaUtils.toSpecification(pageQuery, RiceOperationRecord.class), JpaUtils.toPageRequest(pageQuery));
+    }
+}

+ 94 - 38
src/main/java/com/izouma/nineth/service/RiceService.java

@@ -1,12 +1,15 @@
 package com.izouma.nineth.service;
 
 import com.izouma.nineth.domain.Rice;
+import com.izouma.nineth.domain.RiceOperationRecord;
 import com.izouma.nineth.domain.RiceUserWaterDropRecord;
 import com.izouma.nineth.domain.User;
 import com.izouma.nineth.dto.PageQuery;
 import com.izouma.nineth.dto.R;
 import com.izouma.nineth.dto.RiceDTO;
+import com.izouma.nineth.enums.RiceOperationType;
 import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.RiceOperationRecordRepo;
 import com.izouma.nineth.repo.RiceRepo;
 import com.izouma.nineth.repo.RiceUserWaterDropRecordRepo;
 import com.izouma.nineth.repo.UserRepo;
@@ -35,23 +38,16 @@ public class RiceService {
 
     private static final int MAX_NICKNAME_LENGTH = 6;
     private static final String UPDATE_SUCCESS_MSG = "修改成功";
-
-    @Autowired
     private RiceRepo riceRepo;
-
-
     private RiceUserWaterDropRecordRepo riceUserWaterDropRecordRepo;
-
-    @Autowired
+    private RiceOperationRecordRepo riceOperationRecordRepo;
     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 Rice getCurrentRiceUser(User authenticatedUser) throws BusinessException {
         Long id = authenticatedUser.getId();
         Optional<User> byId = userRepo.findByIdAndDelFalse(id);
@@ -64,13 +60,11 @@ public class RiceService {
         } else {
             throw new BusinessException("用户不存在");
         }
-
         Optional<Rice> byUserId = riceRepo.findByUserId(id);
         if (byUserId.isPresent()) {
             Rice rice = byUserId.get();
             return rice;
         } else {
-
             Rice rice = new Rice();
             rice.setUserId(id);
             rice.setAvatar(avatar);
@@ -86,6 +80,7 @@ public class RiceService {
     }
 
 
+    //修改昵称
     public R updateNickName(Long userId, String nickname) {
         String trimmedNickname = StringUtils.trim(nickname);
         if (trimmedNickname.length() > MAX_NICKNAME_LENGTH) {
@@ -97,14 +92,12 @@ public class RiceService {
 
 
     /**
-     * 在RiceService中,我们注入了SysConfigService和RiceRepo,这两个类的实现需要您自己完成。
-     * 在getCurrentLevel()方法中,我们将原来在@GetMapping注解中的代码全部迁移到了这里,并将返回类型从R<String>改为了String,
-     * 因为我们不再需要将查询结果封装为R对象了。最后,我们根据返回结果的不同,抛出了不同的异常,这些异常同样需要您自己定义实现。
+     * 获取当前等级
      *
      * @param empiricalValue
      * @return
      */
-    public String getCurrentLevel(Long empiricalValue) {
+    public Map<String, Object> getCurrentLevel(Long empiricalValue) {
         String jsonString = sysConfigService.getString("rice_level");
         User authenticatedUser = SecurityUtils.getAuthenticatedUser();
         Long authId = authenticatedUser.getId();
@@ -116,18 +109,37 @@ public class RiceService {
             JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
             JsonArray jsonArray = jsonReader.readArray();
 
-            String currentLevel = null;
+            Long currentLevel = null;
+            Long currentStart = null;
+            Long nextStart = 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");
+                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);
+                    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) {
-                return currentLevel;
+            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("没有配置对应的等级对应经验值");
             }
@@ -137,6 +149,36 @@ public class RiceService {
     }
 
 
+    /**
+     * 任务初始化.显示各个任务能否点击
+     *
+     * @return R<?>
+     */
+    public R<?> taskInitialization() {
+        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
+        Long authId = authenticatedUser.getId();
+        Optional<Rice> byUserId = riceRepo.findByUserId(authId);
+        if (byUserId.isPresent()) {
+            Rice rice = byUserId.get();
+            Long lastSignInTime = rice.getLastSignInTime();
+            Long currentTime = System.currentTimeMillis();
+            // 判断上次签到时间是否为空,如果为空,则默认为从未签到过
+            if (lastSignInTime == null) {
+                return R.success("未签到").add("isSignedIn", false).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
+            }
+            // 判断今天是否已经签到过
+            if (DateUtils.isSameDay(new Date(lastSignInTime), new Date(currentTime))) {
+                return R.success("已签到").add("isSignedIn", true).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
+            } else {
+                return R.success("未签到").add("isSignedIn", false).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
+            }
+        }
+        return R.error("查询失败");
+    }
+
+
+
+
     /**
      * 获取当前用户积分
      */
@@ -214,6 +256,8 @@ public class RiceService {
         if (byUserId.isPresent()) {
             Rice rice = byUserId.get();
             Long waterDropCount = rice.getWaterDropCount();
+            Long beforeWaterDropCount = rice.getWaterDropCount();
+            Long beforeEmpiricalValue = rice.getEmpiricalValue();
             // 如果水滴次数为 0,返回不能浇水的提示
             if (waterDropCount == 0) {
                 return R.error("水滴次数已用完,无法浇水").add("can", false);
@@ -222,19 +266,12 @@ public class RiceService {
             rice.setWaterDropCount(waterDropCount - 1);
             rice.setEmpiricalValue(rice.getEmpiricalValue()+2);
             riceRepo.save(rice);
-
-            // 记录浇水记录
-            RiceUserWaterDropRecord record = new RiceUserWaterDropRecord();
-            record.setUserId(authId);
-            record.setWateringTime(LocalDateTime.now());
-            riceUserWaterDropRecordRepo.save(record);
-
+            createRiceOperationRecord(authId, RiceOperationType.WATER_DROP, 1L,beforeWaterDropCount , rice.getWaterDropCount());
+            createRiceOperationRecord(authId, RiceOperationType.EMPIRICAL_VALUE, 2L,beforeEmpiricalValue , rice.getEmpiricalValue());
             return R.success("浇水成功").add("can", true).add("time", waterDropCount - 1);
         }
         return R.error("浇水失败").add("can", false);
     }
-
-
     //根据用户ID和今日时间获取今日浇水次数的方法
     public Long getTodayWateringCount(Long userId) {
         List<RiceUserWaterDropRecord> records = riceUserWaterDropRecordRepo.findByUserId(userId);
@@ -249,7 +286,7 @@ public class RiceService {
      * @param rice
      * @return
      */
-    public int getWaterDropNeededForLevelUp(Rice rice) {
+    public Long getWaterDropNeededForLevelUp(Rice rice) {
         Long currentEmpiricalValue = rice.getEmpiricalValue();
         String jsonString = sysConfigService.getString("rice_level");
         JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
@@ -257,15 +294,15 @@ public class RiceService {
 
         for (int i = 0; i < jsonArray.size(); i++) {
             JsonObject jsonObject = jsonArray.getJsonObject(i);
-            int start = jsonObject.getInt("start");
-            int nextStart = 0;
+            Long start = Long.valueOf(jsonObject.getInt("start"));
+            Long nextStart = 0L;
             if (i + 1 < jsonArray.size()) {
                 JsonObject nextJsonObject = jsonArray.getJsonObject(i + 1);
-                nextStart = nextJsonObject.getInt("start");
+                nextStart = Long.valueOf(nextJsonObject.getInt("start"));
             }
             if (currentEmpiricalValue >= start && currentEmpiricalValue < nextStart) {
-                int levelUpEmpiricalValue = (int) (nextStart - currentEmpiricalValue);
-                int waterDropNeededForLevelUp = levelUpEmpiricalValue / 2;
+                Long levelUpEmpiricalValue = nextStart - currentEmpiricalValue;
+                Long waterDropNeededForLevelUp = levelUpEmpiricalValue / 2;
                 return waterDropNeededForLevelUp;
             }
         }
@@ -281,12 +318,15 @@ public class RiceService {
             Rice rice = byUserId.get();
             Long lastSignInTime = rice.getLastSignInTime();
             Long currentTime = System.currentTimeMillis();
+            Long beforeWaterDropCount = rice.getWaterDropCount();
+            Long beforeEmpiricalValue = rice.getEmpiricalValue();
             // 判断上次签到时间是否为空,如果为空,则默认为从未签到过
             if (lastSignInTime == null) {
                 rice.setWaterDropCount(rice.getWaterDropCount() + 1);
                 rice.setSignCount(rice.getSignCount() + 1);
                 rice.setLastSignInTime(currentTime);
                 riceRepo.save(rice);
+                createRiceOperationRecord(userId,RiceOperationType.WATER_DROP, (long) 1,beforeWaterDropCount,rice.getWaterDropCount());
                 return R.success("签到成功").add("can",true).add("waterDropCount",rice.getWaterDropCount());
             }
             // 判断今天是否已经签到过
@@ -298,20 +338,23 @@ public class RiceService {
             rice.setSignCount(rice.getSignCount() + 1);
             rice.setLastSignInTime(currentTime);
             riceRepo.save(rice);
+            createRiceOperationRecord(userId,RiceOperationType.WATER_DROP, (long) 1,beforeWaterDropCount,rice.getWaterDropCount());
             return R.success("签到成功").add("can",true).add("waterDropCount",rice.getWaterDropCount());
         }
         return R.error("签到失败").add("can",false);
     }
 
 
-    @Transactional
+
     public R<?> exchangeScoreForWaterDrop(User authenticatedUser) {
         Long authId = authenticatedUser.getId();
         Optional<Rice> byUserId = riceRepo.findByUserId(authId);
         if (byUserId.isPresent()) {
             Rice rice = byUserId.get();
             Long selfScore = rice.getSelfScore();
+            Long beforeSelfScore = rice.getSelfScore();
             Integer waterDropCount = Math.toIntExact(rice.getWaterDropCount());
+            Long beforeWaterDropCount = rice.getWaterDropCount();
 
             // 每次兑换需要消耗的积分和最大兑换次数
             int exchangeScore = 2;
@@ -324,7 +367,9 @@ public class RiceService {
             if (exchangeCount > 0) {
                 rice.setSelfScore(selfScore - totalScore);
                 rice.setWaterDropCount((long) (waterDropCount + exchangeCount));
+                rice.setExchangeCount(exchangeCount);
                 riceRepo.save(rice);
+                createRiceOperationRecord(authId,RiceOperationType.WATER_DROP, (long) exchangeCount,beforeWaterDropCount,rice.getWaterDropCount());
                 return R.success("兑换成功").add("exchangeCount", exchangeCount).add("waterDropCount", rice.getWaterDropCount());
             } else {
                 return R.error("兑换失败,当前积分不足").add("exchangeCount", 0).add("waterDropCount", rice.getWaterDropCount());
@@ -334,4 +379,15 @@ public class RiceService {
     }
 
 
+    private void createRiceOperationRecord(Long userId, RiceOperationType type, Long amount, Long beforeAmount, Long afterAmount) {
+        RiceOperationRecord record = new RiceOperationRecord();
+        record.setUserId(userId);
+        record.setType(type);
+        record.setAmount(amount);
+        record.setBeforeAmount(beforeAmount);
+        record.setAfterAmount(afterAmount);
+        riceOperationRecordRepo.save(record);
+    }
+
+
 }

+ 13 - 48
src/main/java/com/izouma/nineth/web/RiceController.java

@@ -1,9 +1,6 @@
 package com.izouma.nineth.web;
 
-
-import com.izouma.nineth.domain.Invite;
 import com.izouma.nineth.domain.Rice;
-import com.izouma.nineth.domain.RiceInvite;
 import com.izouma.nineth.domain.User;
 import com.izouma.nineth.dto.PageQuery;
 import com.izouma.nineth.dto.R;
@@ -23,10 +20,7 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
 
 @RestController
 @RequestMapping("/rice")
@@ -39,13 +33,10 @@ public class RiceController extends BaseController {
     private UserDetailRepo userDetailRepo;
     private UserService userService;
     private UserRepo userRepo;
-
     private RiceInviteRepo RiceInviteRepo;
     private RiceInviteService RiceInviteService;
-
     private SysConfigService sysConfigService;
     private SysConfigRepo sysConfigRepo;
-
     private static final int MAX_NICKNAME_LENGTH = 14;
     private static final String UPDATE_SUCCESS_MSG = "修改成功";
 
@@ -59,8 +50,6 @@ public class RiceController extends BaseController {
         }
         return riceRepo.save(record);
     }
-
-
     @PreAuthorize("hasRole('ADMIN')")
     @PostMapping("/all")
     public Page<Rice> all(@RequestBody PageQuery pageQuery) {
@@ -99,14 +88,21 @@ public class RiceController extends BaseController {
 
     //等级显示
     @GetMapping("/showLevel")
-    public R<String> getCurrentLevel() {
+    public R<Map<String, Object>> 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);
+            Map<String, Object> currentLevel = riceService.getCurrentLevel(rice.getEmpiricalValue());
+            Long riceLevel = (Long) currentLevel.get("currentLevel");
+            Double levelUpPercentage = (Double) currentLevel.get("levelUpPercentage");
+            rice.setLevel(riceLevel);
+            riceRepo.save(rice);
+            Map<String, Object> responseData = new HashMap<>();
+            responseData.put("riceLevel", currentLevel);
+            responseData.put("levelUpPercentage", levelUpPercentage);
+            return R.success(responseData).add("msg", "查询成功");
         } else {
             throw new BusinessException("用户不存在");
         }
@@ -118,11 +114,9 @@ public class RiceController extends BaseController {
         return riceService.getCurrentScore();
     }
 
-
     //一个获取积分排行榜的接口
     @GetMapping("/scoreRanking")
     public R<List<RiceDTO>> getTop100AndSelf() {
-
         // 获取当前用户的id,假设这个方法可以获取当前用户的id
         User authenticatedUser = SecurityUtils.getAuthenticatedUser();
         Long authId = authenticatedUser.getId();
@@ -130,7 +124,6 @@ public class RiceController extends BaseController {
         return R.success(top100);
     }
 
-
     //浇水响应
     @GetMapping("/watering")
     public R<String> watering() {
@@ -138,8 +131,6 @@ public class RiceController extends BaseController {
     }
 
 
-
-
     //获取今日已浇水次数和还需浇水次数升级的接口
     @GetMapping("/watering/count")
     public R<?> getWateringCount() {
@@ -149,13 +140,12 @@ public class RiceController extends BaseController {
         Optional<Rice> byUserId = riceRepo.findByUserId(userId);
         if (byUserId.isPresent()) {
             Rice rice = byUserId.get();
-            int waterDropNeededForLevelUp = riceService.getWaterDropNeededForLevelUp(rice);
+            Long waterDropNeededForLevelUp = riceService.getWaterDropNeededForLevelUp(rice);
             return R.success(Map.of("todayWateringCount", todayWateringCount, "waterDropNeededForLevelUp", waterDropNeededForLevelUp));
         }
         return R.error("获取用户信息失败");
     }
 
-
     //签到
     @GetMapping("/signin")
     public R<?> signIn() {
@@ -164,36 +154,13 @@ public class RiceController extends BaseController {
         return riceService.signIn(authId);
     }
 
-
-
-
     //任务初始化
     // 任务初始化.显示各个任务能否点击
     @GetMapping("/taskInitialization")
     public R<?> taskInitialization() {
-        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
-        Long authId = authenticatedUser.getId();
-        Optional<Rice> byUserId = riceRepo.findByUserId(authId);
-        if (byUserId.isPresent()) {
-            Rice rice = byUserId.get();
-            Long lastSignInTime = rice.getLastSignInTime();
-            Long currentTime = System.currentTimeMillis();
-            // 判断上次签到时间是否为空,如果为空,则默认为从未签到过
-            if (lastSignInTime == null) {
-                return R.success("未签到").add("isSignedIn", false).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
-            }
-            // 判断今天是否已经签到过
-            if (DateUtils.isSameDay(new Date(lastSignInTime), new Date(currentTime))) {
-                return R.success("已签到").add("isSignedIn", true).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
-            } else {
-                return R.success("未签到").add("isSignedIn", false).add("exchangeCount", rice.getExchangeCount() == null ? 0 : rice.getExchangeCount()).add("waterDropCount", rice.getWaterDropCount());
-            }
-        }
-        return R.error("查询失败");
+        return riceService.taskInitialization();
     }
 
-
-
     //积分兑换水滴
     @GetMapping("/exchangeScoreForWaterDrop")
     public R<?> exchangeScoreForWaterDrop() {
@@ -202,7 +169,5 @@ public class RiceController extends BaseController {
     }
 
 
-
-
 }
 

+ 16 - 53
src/main/java/com/izouma/nineth/web/RiceInviteController.java

@@ -2,7 +2,9 @@ package com.izouma.nineth.web;
 import com.izouma.nineth.domain.Invite;
 import com.izouma.nineth.domain.Rice;
 import com.izouma.nineth.domain.RiceInvite;
+import com.izouma.nineth.domain.RiceOperationRecord;
 import com.izouma.nineth.dto.R;
+import com.izouma.nineth.enums.RiceOperationType;
 import com.izouma.nineth.repo.*;
 import com.izouma.nineth.service.*;
 import com.izouma.nineth.dto.PageQuery;
@@ -25,21 +27,17 @@ import java.util.Optional;
 public class RiceInviteController extends BaseController {
     private RiceInviteService riceInviteService;
     private RiceInviteRepo riceInviteRepo;
-
     private RiceService riceService;
     private RiceRepo riceRepo;
     private UserDetailService userDetailService;
     private UserDetailRepo userDetailRepo;
     private UserService userService;
     private UserRepo userRepo;
-
     private RiceInviteRepo RiceInviteRepo;
     private RiceInviteService RiceInviteService;
-
     private SysConfigService sysConfigService;
     private SysConfigRepo sysConfigRepo;
-
-
+    private RiceOperationRecordRepo riceOperationRecordRepo;
 
 
     //@PreAuthorize("hasRole('ADMIN')")
@@ -52,24 +50,19 @@ public class RiceInviteController extends BaseController {
         }
         return riceInviteRepo.save(record);
     }
-
-
     //@PreAuthorize("hasRole('ADMIN')")
     @PostMapping("/all")
     public Page<RiceInvite> all(@RequestBody PageQuery pageQuery) {
         return riceInviteService.all(pageQuery);
     }
-
     @GetMapping("/get/{id}")
     public RiceInvite get(@PathVariable Long id) {
         return riceInviteRepo.findById(id).orElseThrow(new BusinessException("无记录"));
     }
-
     @PostMapping("/del/{id}")
     public void del(@PathVariable Long id) {
         riceInviteRepo.softDelete(id);
     }
-
     @GetMapping("/excel")
     @ResponseBody
     public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
@@ -79,48 +72,6 @@ public class RiceInviteController extends BaseController {
 
 
 
-    //邀请别人
-    @PostMapping("/invite")
-    public R<?> invite(@RequestParam Long inviterId, @RequestParam Long inviteeId) {
-        // 检查邀请是否重复
-        Optional<RiceInvite> invite = riceInviteRepo.findByInviterIdAndInviteeId(inviterId, inviteeId);
-        if (invite.isPresent()) {
-            return R.error("邀请已发送,请勿重复发送");
-        }
-        // 创建邀请记录
-        RiceInvite newInvite = new RiceInvite();
-        newInvite.setInviterId(inviterId);
-        newInvite.setInviteeId(inviteeId);
-        newInvite.setCreateTime(System.currentTimeMillis());
-        riceInviteRepo.save(newInvite);
-        return R.success("邀请成功");
-    }
-
-
-
-
-    //认领水滴
-    @PostMapping("/claimWaterDrop")
-    public R<?> claimWaterDrop(@RequestParam Long inviteeId) {
-        // 检查是否有邀请记录
-        Optional<RiceInvite> invite = riceInviteRepo.findByInviteeId(inviteeId);
-        if (invite.isPresent()) {
-            return R.error("未找到邀请记录,请先完成邀请任务");
-        }
-        // 增加邀请者的水滴数
-        Long inviterId = invite.get().getInviterId();
-        Optional<Rice> inviterRice = riceRepo.findById(inviterId);
-        if (!inviterRice.isPresent()) {
-            return R.error("未找到邀请者的用户信息");
-        }
-        Rice rice = inviterRice.get();
-        rice.setWaterDropCount(rice.getWaterDropCount() + 1);
-        riceRepo.save(rice);
-        return R.success("领取成功").add("waterDropCount", rice.getWaterDropCount());
-    }
-
-
-
     //邀请别人并认领水滴
     @PostMapping("/inviteAndClaimWaterDrop")
     public R<?> inviteAndClaimWaterDrop(@RequestParam Long inviterId, @RequestParam Long inviteeId) {
@@ -142,11 +93,23 @@ public class RiceInviteController extends BaseController {
             return R.error("未找到邀请者的用户信息");
         }
         Rice rice = inviterRice.get();
+        Long beforeWaterDropCount = rice.getWaterDropCount();
         rice.setWaterDropCount(rice.getWaterDropCount() + 1);
         riceRepo.save(rice);
-
+        createRiceOperationRecord(inviterId,RiceOperationType.WATER_DROP,1L,beforeWaterDropCount,rice.getWaterDropCount());
         return R.success("邀请成功并领取水滴").add("waterDropCount", rice.getWaterDropCount());
     }
 
+
+    private void createRiceOperationRecord(Long userId, RiceOperationType type, Long amount, Long beforeAmount, Long afterAmount) {
+        RiceOperationRecord record = new RiceOperationRecord();
+        record.setUserId(userId);
+        record.setType(type);
+        record.setAmount(amount);
+        record.setBeforeAmount(beforeAmount);
+        record.setAfterAmount(afterAmount);
+        riceOperationRecordRepo.save(record);
+    }
+
 }
 

+ 60 - 0
src/main/java/com/izouma/nineth/web/RiceOperationRecordController.java

@@ -0,0 +1,60 @@
+package com.izouma.nineth.web;
+import com.izouma.nineth.domain.RiceOperationRecord;
+import com.izouma.nineth.service.RiceOperationRecordService;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.RiceOperationRecordRepo;
+import com.izouma.nineth.utils.ObjUtils;
+import com.izouma.nineth.utils.excel.ExcelUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+@RestController
+@RequestMapping("/riceOperationRecord")
+@AllArgsConstructor
+public class RiceOperationRecordController extends BaseController {
+    private RiceOperationRecordService riceOperationRecordService;
+    private RiceOperationRecordRepo riceOperationRecordRepo;
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/save")
+    public RiceOperationRecord save(@RequestBody RiceOperationRecord record) {
+        if (record.getId() != null) {
+            RiceOperationRecord orig = riceOperationRecordRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
+            ObjUtils.merge(orig, record);
+            return riceOperationRecordRepo.save(orig);
+        }
+        return riceOperationRecordRepo.save(record);
+    }
+
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/all")
+    public Page<RiceOperationRecord> all(@RequestBody PageQuery pageQuery) {
+        return riceOperationRecordService.all(pageQuery);
+    }
+
+    @GetMapping("/get/{id}")
+    public RiceOperationRecord get(@PathVariable Long id) {
+        return riceOperationRecordRepo.findById(id).orElseThrow(new BusinessException("无记录"));
+    }
+
+    @PostMapping("/del/{id}")
+    public void del(@PathVariable Long id) {
+        riceOperationRecordRepo.softDelete(id);
+    }
+
+    @GetMapping("/excel")
+    @ResponseBody
+    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
+        List<RiceOperationRecord> data = all(pageQuery).getContent();
+        ExcelUtils.export(response, data);
+    }
+}
+

+ 16 - 0
src/main/vue/src/router.js

@@ -1909,6 +1909,22 @@ const router = new Router({
                     meta: {
                        title: '邀请',
                     },
+               },
+                {
+                    path: '/riceOperationRecordEdit',
+                    name: 'RiceOperationRecordEdit',
+                    component: () => import(/* webpackChunkName: "riceOperationRecordEdit" */ '@/views/RiceOperationRecordEdit.vue'),
+                    meta: {
+                       title: '水稻用户操作记录表编辑',
+                    },
+                },
+                {
+                    path: '/riceOperationRecordList',
+                    name: 'RiceOperationRecordList',
+                    component: () => import(/* webpackChunkName: "riceOperationRecordList" */ '@/views/RiceOperationRecordList.vue'),
+                    meta: {
+                       title: '水稻用户操作记录表',
+                    },
                }
                 /**INSERT_LOCATION**/
             ]

+ 120 - 0
src/main/vue/src/views/RiceOperationRecordEdit.vue

@@ -0,0 +1,120 @@
+<template>
+    <div class="edit-view">
+        <page-title>
+            <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
+            <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
+                删除
+            </el-button>
+            <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
+        </page-title>
+        <div class="edit-view__content-wrapper">
+            <div class="edit-view__content-section">
+                <el-form :model="formData" :rules="rules" ref="form" label-width="196px" label-position="right"
+                         size="small"
+                         style="max-width: 500px;">
+                        <el-form-item prop="userId" label="用户ID">
+                                    <el-input-number type="number" v-model="formData.userId"></el-input-number>
+                        </el-form-item>
+                        <el-form-item prop="type" label="类型:水滴,活动积分,积分">
+                                    <el-select v-model="formData.type" clearable filterable placeholder="请选择">
+                                        <el-option
+                                                v-for="item in typeOptions"
+                                                :key="item.value"
+                                                :label="item.label"
+                                                :value="item.value">
+                                        </el-option>
+                                    </el-select>
+                        </el-form-item>
+                        <el-form-item prop="amount" label="数量">
+                                    <el-input-number type="number" v-model="formData.amount"></el-input-number>
+                        </el-form-item>
+                        <el-form-item prop="beforeAmount" label="操作前的数量">
+                                    <el-input-number type="number" v-model="formData.beforeAmount"></el-input-number>
+                        </el-form-item>
+                        <el-form-item prop="afterAmount" label="操作后的数量">
+                                    <el-input-number type="number" v-model="formData.afterAmount"></el-input-number>
+                        </el-form-item>
+                    <el-form-item class="form-submit">
+                        <el-button @click="onSave" :loading="saving" type="primary">
+                            保存
+                        </el-button>
+                        <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
+                            删除
+                        </el-button>
+                        <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
+                    </el-form-item>
+                </el-form>
+            </div>
+        </div>
+    </div>
+</template>
+<script>
+    export default {
+        name: 'RiceOperationRecordEdit',
+        created() {
+            if (this.$route.query.id) {
+                this.$http
+                    .get('riceOperationRecord/get/' + this.$route.query.id)
+                    .then(res => {
+                        this.formData = res;
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.$message.error(e.error);
+                    });
+            }
+        },
+        data() {
+            return {
+                saving: false,
+                formData: {
+                },
+                rules: {
+                },
+                typeOptions: [{"label":"水滴类型","value":"WATER_DROP"},{"label":"积分类型","value":"SELF_SCORE"},{"label":"活动积分类型","value":"SELF_ACTIVITY_SCORE"}],
+            }
+        },
+        methods: {
+            onSave() {
+                this.$refs.form.validate((valid) => {
+                    if (valid) {
+                        this.submit();
+                    } else {
+                        return false;
+                    }
+                });
+            },
+            submit() {
+                let data = {...this.formData};
+
+                this.saving = true;
+                this.$http
+                    .post('/riceOperationRecord/save', data, {body: 'json'})
+                    .then(res => {
+                        this.saving = false;
+                        this.$message.success('成功');
+                        this.$router.go(-1);
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.saving = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            onDelete() {
+                this.$confirm('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/riceOperationRecord/del/${this.formData.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.$router.go(-1);
+                }).catch(e => {
+                    if (e !== 'cancel') {
+                        console.log(e);
+                        this.$message.error((e || {}).error || '删除失败');
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped></style>

+ 184 - 0
src/main/vue/src/views/RiceOperationRecordList.vue

@@ -0,0 +1,184 @@
+<template>
+    <div  class="list-view">
+        <page-title>
+            <el-button @click="addRow" type="primary" icon="el-icon-plus" :disabled="fetchingData || downloading" class="filter-item">
+                新增
+            </el-button>
+            <el-button @click="download" icon="el-icon-upload2" :loading="downloading" :disabled="fetchingData" class="filter-item">
+                导出
+            </el-button>
+        </page-title>
+        <div class="filters-container">
+            <el-input
+                    placeholder="搜索..."
+                    v-model="search"
+                    clearable
+                    class="filter-item search"
+                    @keyup.enter.native="getData"
+            >
+                <el-button @click="getData" slot="append" icon="el-icon-search"> </el-button>
+            </el-input>
+        </div>
+        <el-table :data="tableData" row-key="id" ref="table"
+                  header-row-class-name="table-header-row"
+                  header-cell-class-name="table-header-cell"
+                  row-class-name="table-row" cell-class-name="table-cell"
+                  :height="tableHeight" v-loading="fetchingData">
+            <el-table-column v-if="multipleMode" align="center" type="selection"
+                             width="50">
+            </el-table-column>
+            <el-table-column prop="id" label="ID" width="100">
+            </el-table-column>
+                                <el-table-column prop="userId" label="用户ID"
+>
+                    </el-table-column>
+                    <el-table-column prop="type" label="类型:水滴,活动积分,积分"
+                            :formatter="typeFormatter"
+                        >
+                    </el-table-column>
+                    <el-table-column prop="amount" label="数量"
+>
+                    </el-table-column>
+                    <el-table-column prop="beforeAmount" label="操作前的数量"
+>
+                    </el-table-column>
+                    <el-table-column prop="afterAmount" label="操作后的数量"
+>
+                    </el-table-column>
+            <el-table-column
+                    label="操作"
+                    align="center"
+                    fixed="right"
+                    width="150">
+                <template slot-scope="{row}">
+                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
+                    <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button>
+                </template>
+            </el-table-column>
+        </el-table>
+        <div class="pagination-wrapper">
+            <!-- <div class="multiple-mode-wrapper">
+                <el-button v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
+                <el-button-group v-else>
+                    <el-button @click="operation1">批量操作1</el-button>
+                    <el-button @click="operation2">批量操作2</el-button>
+                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
+                </el-button-group>
+            </div> -->
+            <el-pagination background @size-change="onSizeChange"
+                           @current-change="onCurrentChange" :current-page="page"
+                           :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize"
+                           layout="total, sizes, prev, pager, next, jumper"
+                           :total="totalElements">
+            </el-pagination>
+        </div>
+
+    </div>
+</template>
+<script>
+    import { mapState } from "vuex";
+    import pageableTable from "@/mixins/pageableTable";
+
+    export default {
+        name: 'RiceOperationRecordList',
+        mixins: [pageableTable],
+        data() {
+            return {
+                multipleMode: false,
+                search: "",
+                url: "/riceOperationRecord/all",
+                downloading: false,
+                        typeOptions:[{"label":"水滴类型","value":"WATER_DROP"},{"label":"积分类型","value":"SELF_SCORE"},{"label":"活动积分类型","value":"SELF_ACTIVITY_SCORE"}],
+            }
+        },
+        computed: {
+            selection() {
+                return this.$refs.table.selection.map(i => i.id);
+            }
+        },
+        methods: {
+                    typeFormatter(row, column, cellValue, index) {
+                        let selectedOption = this.typeOptions.find(i => i.value === cellValue);
+                        if (selectedOption) {
+                            return selectedOption.label;
+                        }
+                        return '';
+                    },
+            beforeGetData() {
+                return { search: this.search, query: { del: false } };
+            },
+            toggleMultipleMode(multipleMode) {
+                this.multipleMode = multipleMode;
+                if (!multipleMode) {
+                    this.$refs.table.clearSelection();
+                }
+            },
+            addRow() {
+                this.$router.push({
+                    path: "/riceOperationRecordEdit",
+                    query: {
+                        ...this.$route.query
+                    }
+                });
+            },
+            editRow(row) {
+                this.$router.push({
+                    path: "/riceOperationRecordEdit",
+                    query: {
+                    id: row.id
+                    }
+                });
+            },
+            download() {
+                this.downloading = true;
+                this.$axios
+                    .get("/riceOperationRecord/excel", { 
+                        responseType: "blob",
+                        params: { size: 10000 }
+                    })
+                    .then(res => {
+                        console.log(res);
+                        this.downloading = false;
+                        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
+                        const link = document.createElement("a");
+                        link.href = downloadUrl;
+                        link.setAttribute(
+                            "download",
+                            res.headers["content-disposition"].split("filename=")[1]
+                        );
+                        document.body.appendChild(link);
+                        link.click();
+                        link.remove();
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.downloading = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            operation1() {
+                this.$notify({
+                    title: '提示',
+                    message: this.selection
+                });
+            },
+            operation2() {
+                this.$message('操作2');
+            },
+            deleteRow(row) {
+                this.$alert('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/riceOperationRecord/del/${row.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.getData();
+                }).catch(e => {
+                    if (e !== 'cancel') {
+                        this.$message.error(e.error);
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped>
+</style>