x1ongzhu 6 years ago
parent
commit
6c74b6e9f1

BIN
image.png


+ 10 - 0
src/main/java/com/izouma/walkchina/constant/Strings.java

@@ -9,7 +9,17 @@ public interface Strings {
 
     String MSG_MEMBER_GRABBED = "你的队员%s,被%s抢走了";
 
+    String MSG_RECEIVE_STAGE_AWARD = "你领取了%s商城币";
+
+    String MSG_STEAL_AWARD = "你偷了%s%s商城币";
+
+    String MSG_AWARD_STOLEN = "%s偷了你%s商城币";
+
     String REMARK_HIRE = "雇佣队员";
 
     String REMARK_BE_HIRED = "队员佣金";
+
+    String REMARK_RECEIVE_STAGE_AWARD = "领取阶段奖金";
+
+    String REMARK_STEAL_STAGE_AWARD = "偷奖金";
 }

+ 5 - 0
src/main/java/com/izouma/walkchina/domain/StageAward.java

@@ -39,6 +39,8 @@ public class StageAward {
 
     private Double needProgress;
 
+    private Long needStep;
+
     @Column(precision = 10, scale = 2)
     private BigDecimal coin;
 
@@ -46,6 +48,9 @@ public class StageAward {
 
     private Long receiveUser;
 
+    @Temporal(TemporalType.TIMESTAMP)
+    private Date receiveTime;
+
     @CreatedBy
     private String createdBy;
 

+ 5 - 2
src/main/java/com/izouma/walkchina/dto/UserMap.java

@@ -19,7 +19,6 @@ public class UserMap {
     private List<Object>     progressPolyline;
     private City             origin;
     private City             destination;
-    private Location         current;
     private Double           progress;
     private UserInfo         userInfo;
     private List<StageAward> stageAwards;
@@ -27,5 +26,9 @@ public class UserMap {
     private Long             teamStep;
     private Long             currentStep;
     private Integer          days;
-
+    private String           nickname;
+    private String           avatar;
+    private Integer          level;
+    private Long             totalSteps;
+    private Integer          walkCities;
 }

+ 16 - 0
src/main/java/com/izouma/walkchina/dto/UserProfile.java

@@ -0,0 +1,16 @@
+package com.izouma.walkchina.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class UserProfile {
+    private Long id;
+    private String nickname;
+    private String avatar;
+    private Integer level;
+
+}

+ 8 - 1
src/main/java/com/izouma/walkchina/exception/ServiceException.java

@@ -1,9 +1,16 @@
 package com.izouma.walkchina.exception;
 
-public class ServiceException extends RuntimeException {
+import java.util.function.Supplier;
+
+public class ServiceException extends RuntimeException implements Supplier<ServiceException> {
     private static final long serialVersionUID = 3779880207424189309L;
 
     public ServiceException(String message) {
         super(message);
     }
+
+    @Override
+    public ServiceException get() {
+        return this;
+    }
 }

+ 4 - 4
src/main/java/com/izouma/walkchina/repo/WalkDataRepository.java

@@ -23,9 +23,9 @@ public interface WalkDataRepository extends JpaRepository<WalkData, Long> {
             "JOIN walk_data ON team_member.user_id = walk_data.user_id " +
             "AND walk_data.date >= team_member.start_date " +
             "AND walk_data.date <= team_member.end_date " +
-            "WHERE leader = ?1 AND walk_data.date >= ?2 AND walk_data.date <= ?3", nativeQuery = true)
-    Optional<Long> sumTeamWalkSteps(Long userId, @Temporal(TemporalType.DATE) Date start, @Temporal(TemporalType.DATE) Date end);
+            "WHERE leader = ?1 AND walk_data.date >= DATE(?2) AND walk_data.date <= DATE(?3)", nativeQuery = true)
+    Optional<Long> sumTeamWalkSteps(Long userId, Date start, Date end);
 
-    @Query(value = "SELECT SUM(steps) FROM walk_data WHERE user_id = ?1 AND date >= ?2 AND date <= ?3", nativeQuery = true)
-    Optional<Long> sumUserWalkSteps(Long userId, @Temporal(TemporalType.DATE) Date start, @Temporal(TemporalType.DATE) Date end);
+    @Query(value = "SELECT SUM(steps) FROM walk_data WHERE user_id = ?1 AND date >= DATE(?2) AND date <= DATE(?3)", nativeQuery = true)
+    Optional<Long> sumUserWalkSteps(Long userId, Date start, Date end);
 }

+ 102 - 0
src/main/java/com/izouma/walkchina/service/AwardService.java

@@ -0,0 +1,102 @@
+package com.izouma.walkchina.service;
+
+import com.izouma.walkchina.constant.AppConstants;
+import com.izouma.walkchina.constant.Strings;
+import com.izouma.walkchina.domain.*;
+import com.izouma.walkchina.exception.ServiceException;
+import com.izouma.walkchina.repo.*;
+import lombok.ToString;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.util.Date;
+import java.util.Optional;
+
+@ToString
+@Slf4j
+@Service
+public class AwardService {
+    @Autowired
+    private StageAwardRepository     stageAwardRepository;
+    @Autowired
+    private MessageRepository        messageRepository;
+    @Autowired
+    private UserInfoRepository       userInfoRepository;
+    @Autowired
+    private UserCoinRecordRepository userCoinRecordRepository;
+    @Autowired
+    private JourneyStageRepository   journeyStageRepository;
+
+    public BigDecimal receiveStageAward(Long userId, Long stageAwardId) {
+        StageAward stageAward = stageAwardRepository.findById(stageAwardId).orElseThrow(new ServiceException("无记录"));
+        if (stageAward.getReceived()) {
+            throw new ServiceException("重复领取");
+        }
+        JourneyStage journeyStage = journeyStageRepository.findById(stageAward.getStageId()).orElseThrow(new ServiceException("无记录"));
+        if (journeyStage.getProgress() < stageAward.getNeedProgress()) {
+            throw new ServiceException("步数不足");
+        }
+        UserInfo owner = userInfoRepository.findById(stageAward.getUserId()).orElseThrow(new ServiceException("用户不存在"));
+        UserInfo receiver;
+        if (userId.equals(stageAward.getUserId())) {
+            receiver = userInfoRepository.findById(userId).orElseThrow(new ServiceException("用户不存在"));
+        } else {
+            receiver = owner;
+        }
+
+        stageAward.setReceived(true);
+        stageAward.setReceiveUser(userId);
+        stageAward.setReceiveTime(new Date());
+        stageAwardRepository.save(stageAward);
+
+        BigDecimal balance = Optional.ofNullable(receiver.getCoin()).orElse(BigDecimal.ZERO);
+        balance = balance.add(stageAward.getCoin());
+        receiver.setCoin(balance);
+        userInfoRepository.save(receiver);
+
+        if (userId.equals(stageAward.getUserId())) {
+            userCoinRecordRepository.save(UserCoinRecord.builder()
+                    .userId(userId)
+                    .balance(balance)
+                    .modify(stageAward.getCoin())
+                    .remark(Strings.REMARK_RECEIVE_STAGE_AWARD)
+                    .type(AppConstants.CoinRecordType.STAGE)
+                    .build());
+
+            Message msg = Message.builder()
+                    .userId(userId)
+                    .content(String.format(Strings.MSG_RECEIVE_STAGE_AWARD, stageAward.getCoin()))
+                    .isRead(false)
+                    .active(true)
+                    .build();
+            messageRepository.save(msg);
+        } else {
+            userCoinRecordRepository.save(UserCoinRecord.builder()
+                    .userId(receiver.getId())
+                    .balance(balance)
+                    .modify(stageAward.getCoin())
+                    .remark(Strings.REMARK_STEAL_STAGE_AWARD)
+                    .type(AppConstants.CoinRecordType.STEAL)
+                    .build());
+
+            Message stealMsg = Message.builder()
+                    .userId(userId)
+                    .content(String.format(Strings.MSG_STEAL_AWARD, owner.getNickname(), stageAward.getCoin()))
+                    .isRead(false)
+                    .active(true)
+                    .build();
+            messageRepository.save(stealMsg);
+
+            Message stolenMsg = Message.builder()
+                    .userId(stageAward.getUserId())
+                    .content(String.format(Strings.MSG_AWARD_STOLEN, receiver.getNickname(), stageAward.getCoin()))
+                    .isRead(false)
+                    .active(true)
+                    .build();
+            messageRepository.save(stolenMsg);
+        }
+        return stageAward.getCoin();
+    }
+}

+ 5 - 13
src/main/java/com/izouma/walkchina/service/JourneyService.java

@@ -42,14 +42,8 @@ public class JourneyService {
     }
 
     public void newJourney(Long userId, Long originId, Long destinationId) {
-        City origin = cityRepository.findById(originId).orElse(null);
-        if (origin == null) {
-            throw new ServiceException("起始地不存在");
-        }
-        City destination = cityRepository.findById(destinationId).orElse(null);
-        if (destination == null) {
-            throw new ServiceException("目的地不存在");
-        }
+        City origin = cityRepository.findById(originId).orElseThrow(new ServiceException("起始地不存在"));
+        City destination = cityRepository.findById(destinationId).orElseThrow(new ServiceException("目的地不存在"));
         DirectionResponse directionResponse = mapService.direction(new Location(origin.getLatitude(), origin.getLongitude()),
                 new Location(destination.getLatitude(), destination.getLongitude()));
         if (directionResponse.getStatus() != 0) {
@@ -82,10 +76,7 @@ public class JourneyService {
     }
 
     public void newDestination(Long userId, Long id) {
-        City destination = cityRepository.findById(id).orElse(null);
-        if (destination == null) {
-            throw new ServiceException("目的地不存在");
-        }
+        City destination = cityRepository.findById(id).orElseThrow(new ServiceException("目的地不存在"));
         UserJourney userJourney = userJourneyRepository.findByUserId(userId);
         JourneyStage journeyStage = journeyStageRepository.findByUserIdAndJourneyIdOrderByIdDesc(userId, userJourney.getId());
         DirectionResponse directionResponse = mapService.direction(new Location(journeyStage.getDestination().getLatitude(), journeyStage.getDestination().getLongitude()),
@@ -129,7 +120,8 @@ public class JourneyService {
                     .longitude(extracted.get(end))
                     .journeyId(journeyId)
                     .coin(new BigDecimal(10))
-                    .needProgress(points.get(0))
+                    .needProgress(p)
+                    .needStep((long) (p * route.getDistance() / AppConstants.STEP_TO_DISTANCE_RATE))
                     .received(false)
                     .build();
             stageAwardRepository.save(stageAward);

+ 18 - 24
src/main/java/com/izouma/walkchina/service/MapService.java

@@ -5,6 +5,7 @@ import com.google.gson.Gson;
 import com.izouma.walkchina.constant.AppConstants;
 import com.izouma.walkchina.domain.City;
 import com.izouma.walkchina.domain.JourneyStage;
+import com.izouma.walkchina.domain.UserInfo;
 import com.izouma.walkchina.domain.UserJourney;
 import com.izouma.walkchina.dto.Location;
 import com.izouma.walkchina.dto.MapRegion;
@@ -15,6 +16,8 @@ import com.izouma.walkchina.dto.webservice.RouteStep;
 import com.izouma.walkchina.exception.ServiceException;
 import com.izouma.walkchina.repo.*;
 import lombok.extern.slf4j.Slf4j;
+import org.joda.time.Days;
+import org.joda.time.LocalDate;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.jpa.domain.Specification;
@@ -75,22 +78,19 @@ public class MapService {
     }
 
     public UserMap userMap(Long userId) {
-        UserJourney userJourney = userJourneyRepository.findByUserId(userId);
-        if (userJourney == null) {
-            throw new ServiceException("无记录");
-        }
-        City origin = userJourney.getOrigin();
-        if (origin == null) {
-            throw new ServiceException("无记录");
-        }
-        City destination = userJourney.getDestination();
-        if (destination == null) {
-            throw new ServiceException("无记录");
-        }
+        UserJourney userJourney = Optional.ofNullable(userJourneyRepository.findByUserId(userId)).orElseThrow(new ServiceException("无记录"));
+        City origin = Optional.ofNullable(userJourney.getOrigin()).orElseThrow(new ServiceException("无记录"));
+        City destination = Optional.ofNullable(userJourney.getDestination()).orElseThrow(new ServiceException("无记录"));
+        UserInfo userInfo = userInfoRepository.findById(userId).orElseThrow(new ServiceException("用户不存在"));
         UserMap userMap = UserMap.builder()
                 .polyline(minifyPolyline(userJourney.getPolyline()))
                 .origin(origin)
                 .destination(destination)
+                .nickname(userInfo.getNickname())
+                .avatar(userInfo.getAvatar())
+                .totalSteps(userInfo.getTotalSteps())
+                .walkCities(userInfo.getWalkCities())
+                .level(userInfo.getLevel())
                 .build();
         List<Double> progressPolyline = new ArrayList<>();
         List<JourneyStage> stages = journeyStageRepository.findAllByJourneyIdOrderById(userJourney.getId());
@@ -100,11 +100,11 @@ public class MapService {
         JourneyStage latestStage = stages.get(stages.size() - 1);
 
         userMap.setProgress(latestStage.getProgress());
-        Date now = new Date();
-        userMap.setTeamStep(walkDataRepository.sumTeamWalkSteps(userId, now, now).orElse(0L));
-        userMap.setTodayStep(walkDataRepository.sumUserWalkSteps(userId, now, now).orElse(0L));
+        userMap.setTeamStep(walkDataRepository.sumTeamWalkSteps(userId, new Date(), new Date()).orElse(0L));
+        userMap.setTodayStep(walkDataRepository.sumUserWalkSteps(userId, new Date(), new Date()).orElse(0L));
         userMap.setCurrentStep(latestStage.getCurrentSteps());
         userMap.setStageAwards(stageAwardRepository.findAllByUserIdAndStageId(userId, latestStage.getId()));
+        userMap.setDays(Days.daysBetween(LocalDate.fromDateFields(latestStage.getCreatedAt()), LocalDate.fromDateFields(new Date())).getDays());
 
         List<RouteStep> steps = latestStage.getRouteSteps();
         // int distance = 0;
@@ -132,7 +132,7 @@ public class MapService {
         //         break;
         //     }
         // }
-        for (int i = 0; i < endPoint(steps, latestStage.getDistance() * latestStage.getProgress()); i++) {
+        for (int i = 0; i <= endPoint(steps, latestStage.getDistance() * latestStage.getProgress()); i++) {
             progressPolyline.add(latestStage.getPolyline().get(i));
         }
 
@@ -199,14 +199,8 @@ public class MapService {
     }
 
     public Map<String, Object> calcAward(Long originId, Long destinationId) {
-        City origin = cityRepository.findById(originId).orElse(null);
-        if (origin == null) {
-            throw new ServiceException("无记录");
-        }
-        City destination = cityRepository.findById(destinationId).orElse(null);
-        if (destination == null) {
-            throw new ServiceException("无记录");
-        }
+        City origin = cityRepository.findById(originId).orElseThrow(new ServiceException("无记录"));
+        City destination = cityRepository.findById(destinationId).orElseThrow(new ServiceException("无记录"));
         DirectionResponse response = direction(new Location(origin.getLatitude(), origin.getLongitude()), new Location(destination.getLatitude(), destination.getLongitude()));
         if (response.getStatus() != 0) {
             throw new ServiceException(response.getMessage());

+ 3 - 9
src/main/java/com/izouma/walkchina/service/TeamService.java

@@ -34,14 +34,8 @@ public class TeamService {
 
     public void hire(Long userId, Long target) {
         Date now = new Date();
-        UserInfo userInfo = userInfoRepository.findById(userId).orElse(null);
-        if (userInfo == null) {
-            throw new ServiceException("用户不存在");
-        }
-        UserInfo targetUserInfo = userInfoRepository.findById(target).orElse(null);
-        if (targetUserInfo == null) {
-            throw new ServiceException("用户不存在");
-        }
+        UserInfo userInfo = userInfoRepository.findById(userId).orElseThrow(new ServiceException("用户不存在"));
+        UserInfo targetUserInfo = userInfoRepository.findById(target).orElseThrow(new ServiceException("用户不存在"));
         TeamMember teamMember = teamMemberRepository.findActive(target, now);
         if (teamMember != null) {
             teamMember.setEndDate(now);
@@ -49,7 +43,7 @@ public class TeamService {
             Message grabMsg = Message.builder()
                     .userId(teamMember.getLeader())
                     .type(AppConstants.MessageType.NORMAL)
-                    .content(String.format(Strings.MSG_MEMBER_GRABBED, targetUserInfo.getNickname(),userInfo.getNickname()))
+                    .content(String.format(Strings.MSG_MEMBER_GRABBED, targetUserInfo.getNickname(), userInfo.getNickname()))
                     .active(true)
                     .isRead(false)
                     .build();

+ 1 - 4
src/main/java/com/izouma/walkchina/service/UserInfoService.java

@@ -152,10 +152,7 @@ public class UserInfoService implements UserDetailsService {
     }
 
     public void updateLocation(Long userId, Double latitude, Double longitude) {
-        UserInfo userInfo = userInfoRepository.findById(userId).orElse(null);
-        if (userInfo == null) {
-            throw new ServiceException("用户不存在");
-        }
+        UserInfo userInfo = userInfoRepository.findById(userId).orElseThrow(new ServiceException("用户不存在"));
         userInfo.setLatitude(latitude);
         userInfo.setLongitude(longitude);
         userInfoRepository.save(userInfo);

+ 1 - 5
src/main/java/com/izouma/walkchina/service/WalkDataService.java

@@ -27,11 +27,7 @@ public class WalkDataService {
 
     public void saveWalkData(Long userId, String encryptedData, String iv) {
         log.info("saveWalkData\nuserId:{}\nencryptedData:{}\niv:{}", userId, encryptedData, iv);
-        UserInfo userInfo = userInfoRepository.findById(userId).orElse(null);
-        if (userInfo == null) {
-            log.error("user {} is null", userId);
-            throw new ServiceException("用户不存在");
-        }
+        UserInfo userInfo = userInfoRepository.findById(userId).orElseThrow(new ServiceException("用户不存在"));
         String sessionKey = userInfo.getSessionKey();
         List<WxMaRunStepInfo> wxMaRunStepInfoList = wxMaService.getRunService().getRunStepInfo(sessionKey, encryptedData, iv);
         for (WxMaRunStepInfo stepInfo : wxMaRunStepInfoList) {

+ 25 - 0
src/main/java/com/izouma/walkchina/web/AwardController.java

@@ -0,0 +1,25 @@
+package com.izouma.walkchina.web;
+
+import com.izouma.walkchina.domain.UserInfo;
+import com.izouma.walkchina.dto.Result;
+import com.izouma.walkchina.service.AwardService;
+import com.izouma.walkchina.utils.SecurityUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/award")
+public class AwardController {
+
+    @Autowired
+    private AwardService awardService;
+
+    @GetMapping("/receiveStageAward")
+    public Result receiveStageAward(@RequestParam("stageAwardId") Long stageAwardId) {
+        UserInfo userInfo = SecurityUtils.getAuthenticatedUser();
+        return Result.ok(awardService.receiveStageAward(userInfo.getId(), stageAwardId));
+    }
+}

+ 7 - 4
src/main/java/com/izouma/walkchina/web/MapController.java

@@ -34,10 +34,13 @@ public class MapController {
     }
 
     @GetMapping("/userMap")
-    public Result userMap() {
-        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-        UserInfo userInfo = (UserInfo) authentication.getPrincipal();
-        return Result.ok(mapService.userMap(userInfo.getId()));
+    public Result userMap(Long userId) {
+        if (userId == null) {
+            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+            UserInfo userInfo = (UserInfo) authentication.getPrincipal();
+            userId = userInfo.getId();
+        }
+        return Result.ok(mapService.userMap(userId));
     }
 
     @GetMapping("/calcAward")

+ 7 - 25
src/main/java/com/izouma/walkchina/web/UserInfoController.java

@@ -2,6 +2,7 @@ package com.izouma.walkchina.web;
 
 import com.izouma.walkchina.dto.Result;
 import com.izouma.walkchina.domain.UserInfo;
+import com.izouma.walkchina.exception.ServiceException;
 import com.izouma.walkchina.repo.UserInfoRepository;
 import com.izouma.walkchina.service.UserInfoService;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -22,35 +23,16 @@ public class UserInfoController {
 
     @GetMapping("/my")
     public Result my() {
-        try {
-            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-            UserInfo userInfo = (UserInfo) authentication.getPrincipal();
-            userInfo = userInfoRepository.findById(userInfo.getId()).orElse(null);
-            if (userInfo != null) {
-                return Result.ok(userInfo);
-            }
-        } catch (Exception ignored) {
-        }
-        return Result.error("无记录");
+        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+        UserInfo userInfo = (UserInfo) authentication.getPrincipal();
+        userInfo = userInfoRepository.findById(userInfo.getId()).orElseThrow(new ServiceException("无记录"));
+        return Result.ok(userInfo);
     }
 
     @GetMapping("/get")
     public Result get(UserInfo probe) {
-        UserInfo userInfo = userInfoRepository.findOne(Example.of(probe)).orElse(null);
-        if (userInfo != null) {
-            return Result.ok(userInfo);
-        } else {
-            return Result.error("无结果");
-        }
-    }
-
-    @GetMapping("/get/{id}")
-    public Result getOne(@PathVariable Long id) {
-        UserInfo userInfo = userInfoRepository.findById(id).orElse(null);
-        if (userInfo != null) {
-            return Result.ok(userInfo);
-        }
-        return Result.error("无记录");
+        UserInfo userInfo = userInfoRepository.findOne(Example.of(probe)).orElseThrow(new ServiceException("无结果"));
+        return Result.ok(userInfo);
     }
 
     @GetMapping("/all")

+ 3 - 3
src/main/resources/application.yaml

@@ -30,11 +30,11 @@ spring:
       max_file_size: 100MB
       max_request_size: 100MB
 jwt:
-  secret: javainuse
+  secret: XvAD0kboD76Dpebm
 wx:
   miniapp:
-    app_id: wx47bde0e3d49633b4
-    app_secret: 152f70e353fb0b42a656678b34d41252
+    app_id: wx6517cbf58115c508
+    app_secret: 8af0e8ba28ffddfb7e574e6c7cb6aaf1
     msg_token: msgToken
     msg_aes_key: aesKey
     msg_format: JSON