From c83d72533dbe487315aa2c7d4bbc1538c0a1804a Mon Sep 17 00:00:00 2001 From: yujiyea <54650556+yujiyea@users.noreply.github.com> Date: Thu, 11 Apr 2024 22:45:36 +0900 Subject: [PATCH 01/10] =?UTF-8?q?feat:=20=EC=9E=84=EC=8B=9C=20=EC=BB=A4?= =?UTF-8?q?=EB=B0=8B(=EC=BB=A4=EC=8A=A4=ED=85=80=20=EC=B6=9C=EC=84=9D=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=ED=85=9C=20=EB=AC=B4=EC=A1=B0=EA=B1=B4=20?= =?UTF-8?q?=EC=A3=BC=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95=20&=20?= =?UTF-8?q?=ED=86=B5=EA=B3=84=20=EB=B3=80=EC=88=98=EB=A1=9C=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mada/custom/service/CustomService.java | 2 +- .../mada/todo/dto/StatisticsResponseDto.java | 23 ++++--------------- .../mada/todo/repository/ChartRepository.java | 6 ++--- 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/umc/mada/custom/service/CustomService.java b/src/main/java/com/umc/mada/custom/service/CustomService.java index 552ef96..be784aa 100644 --- a/src/main/java/com/umc/mada/custom/service/CustomService.java +++ b/src/main/java/com/umc/mada/custom/service/CustomService.java @@ -78,7 +78,7 @@ public CustomItemsResponse checkHaveItem(List itemList, User user){ boolean haveItemCheck = haveItemRepository.existsByCustomItemAndUser(item, user); //출석 아이템인데 소유하고 있지 않다면 목록에 추가하지 않기 - if(!haveItemCheck && item.getUnlockCondition().equals(CustomItem.ItemUnlockCondition.ATTENDANCE)) continue; +// if(!haveItemCheck && item.getUnlockCondition().equals(CustomItem.ItemUnlockCondition.ATTENDANCE)) continue; //해당 아이템을 소유하고 있다면 true; if(haveItemCheck) have = true; diff --git a/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java b/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java index 9bece77..c6fd3cc 100644 --- a/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java +++ b/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java @@ -13,26 +13,18 @@ public class StatisticsResponseDto { private final List categoryStatistics; private final String mostCategory; //가장 많이 완료한 카테고리 - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float totalTodo; //추가한 todo 개수 private final float nowCategoryCount; //오늘, 이번주, 이번달 가장 많이 완료한 카테고리 수 private final float beforeCategoryCount; - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float diffCountA; private final List todoStatistics; private final float nowTotalCount; //오늘, 이번주, 이번달 전체 투두 수 - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float ratio; //비율 private final float nowCountCompleted; // 완료한 투두 수 - private final float diffCountB; //어제, 지난주, 지난 달에 완료한 투두 수보다 얼마나 더 많이 했는지 + private final float diffCount; //어제, 지난주, 지난 달에 완료한 투두 수보다 얼마나 더 많이 했는지 private final List achievementStatistics; private final float nowAchievementRate; //오늘, 이번주, 이번달 투두 달성도의 상승, 하락 비율 @JsonInclude(JsonInclude.Include.NON_DEFAULT) private final float nowCountCompletedA; - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float diffCountC; //오늘, 이번주, 이번달에 어제, 저번주, 저번달보다 얼마나 더 많이 했는지 public static StatisticsResponseDto ofDay(List categoryStatisticsVOList, PreviousCategoryStatisticsVO previousCategoryStatisticsVO, List todoBarGraphStatisticsVOList, int totalCount, List achievementRateStatisticsVOList){ @@ -45,11 +37,10 @@ public static StatisticsResponseDto ofDay(List categorySta .todoStatistics(todoBarGraphStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getTodoDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) .nowCountCompleted(todoBarGraphStatisticsVOList.get(0).getCount()) - .diffCountB(todoBarGraphStatisticsVOList.get(0).getCount() - todoBarGraphStatisticsVOList.get(1).getCount()) + .diffCount(todoBarGraphStatisticsVOList.get(0).getCount() - todoBarGraphStatisticsVOList.get(1).getCount()) .achievementStatistics(achievementRateStatisticsVOList.stream().map(vo-> AchievementStatisticsDto.of(vo.getDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(achievementRateStatisticsVOList.get(0).getRate() - achievementRateStatisticsVOList.get(1).getRate()) .nowCountCompletedA(achievementRateStatisticsVOList.get(0).getCount()) - .diffCountC(achievementRateStatisticsVOList.get(0).getCount() - achievementRateStatisticsVOList.get(1).getCount()) .build(); } @@ -57,19 +48,16 @@ public static StatisticsResponseDto ofWeek(List categorySt List weeklyBarGraphAndRateStatisticsVOList){ return StatisticsResponseDto.builder() .categoryStatistics(categoryStatisticsVOList.stream().map(vo -> CategoryStatisticsDto.of(vo.getCategoryName(), vo.getColor(), vo.getRate())).collect(Collectors.toList())) - .totalTodo(totalCount) .mostCategory(categoryStatisticsVOList.get(0).getCategoryName()) .nowCategoryCount(categoryStatisticsVOList.get(0).getCount()) .beforeCategoryCount(previousCategoryStatisticsVO.getCount()) .todoStatistics(weeklyBarGraphAndRateStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getStartDate(), vo.getEndDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) - .ratio(weeklyBarGraphAndRateStatisticsVOList.get(0).getRate()) .nowCountCompleted(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountB(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) + .diffCount(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) .achievementStatistics(weeklyBarGraphAndRateStatisticsVOList.stream().map(vo-> AchievementStatisticsDto.of(vo.getStartDate(), vo.getEndDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(weeklyBarGraphAndRateStatisticsVOList.get(0).getRate() - weeklyBarGraphAndRateStatisticsVOList.get(1).getRate()) .nowCountCompletedA(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountC(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) .build(); } @@ -80,14 +68,13 @@ public static StatisticsResponseDto ofMonth(List categoryS .mostCategory(categoryStatisticsVOList.get(0).getCategoryName()) .nowCategoryCount(categoryStatisticsVOList.get(0).getCount()) .beforeCategoryCount(previousCategoryStatisticsVO.getCount()) - .diffCountA(categoryStatisticsVOList.get(0).getCount() - previousCategoryStatisticsVO.getCount()) .todoStatistics(monthlyBarGraphAndRateStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getMonthDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) - .ratio(monthlyBarGraphAndRateStatisticsVOList.get(0).getRate()) .nowCountCompleted(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountB(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount() - monthlyBarGraphAndRateStatisticsVOList.get(1).getCount()) + .diffCount(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount() - monthlyBarGraphAndRateStatisticsVOList.get(1).getCount()) .achievementStatistics(monthlyBarGraphAndRateStatisticsVOList.stream().map(vo-> AchievementStatisticsDto.of(vo.getMonthDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(monthlyBarGraphAndRateStatisticsVOList.get(0).getRate() - monthlyBarGraphAndRateStatisticsVOList.get(1).getRate()) + .nowCountCompletedA(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount()) .build(); } } diff --git a/src/main/java/com/umc/mada/todo/repository/ChartRepository.java b/src/main/java/com/umc/mada/todo/repository/ChartRepository.java index 9cc1b25..b1c1306 100644 --- a/src/main/java/com/umc/mada/todo/repository/ChartRepository.java +++ b/src/main/java/com/umc/mada/todo/repository/ChartRepository.java @@ -49,7 +49,7 @@ public interface ChartRepository extends JpaRepository { @Query(value = "select DATE_FORMAT(DATE_SUB(T.date, INTERVAL (DAYOFWEEK(T.date)-1) DAY), '%Y-%m-%d') as startDate,\n" + " DATE_FORMAT(DATE_SUB(T.date, INTERVAL (DAYOFWEEK(T.date)-7) DAY), '%Y-%m-%d') as endDate,\n" + " DATE_FORMAT(T.date, '%Y%U') AS weekDate,\n" + - " COUNT(T.id) as count, ROUND(COUNT(*)/(select COUNT(*) as count from TODO A where A.user_id = 55 and DATE_FORMAT(A.date, '%Y%U') = weekDate GROUP BY DATE_FORMAT(A.date, '%Y%U'))*100, 1) as rate\n" + + " COUNT(T.id) as count, ROUND(COUNT(*)/(select COUNT(*) as count from TODO A where A.user_id = :uid and DATE_FORMAT(A.date, '%Y%U') = weekDate GROUP BY DATE_FORMAT(A.date, '%Y%U'))*100, 1) as rate\n" + "from TODO T\n" + "where T.user_id = :uid and T.date between :startDate and :endDate and T.complete=1\n" + "GROUP BY weekDate\n" + @@ -57,9 +57,9 @@ public interface ChartRepository extends JpaRepository { List weeklyTodoBarGraphAndRateStatistics(@Param("uid") Long uid, @Param("startDate") LocalDate startDate , @Param("endDate") LocalDate endDate); @Query(value = "select DATE_FORMAT(A.date, '%Y-%m') AS monthDate, COUNT(*) as count, \n" + - " ROUND(COUNT(*)/(select COUNT(*) as count from TODO T where T.user_id = 55 and DATE_FORMAT(T.date, '%Y-%m') = monthDate GROUP BY DATE_FORMAT(T.date, '%Y-%m'))*100, 1) as rate\n" + + " ROUND(COUNT(*)/(select COUNT(*) as count from TODO T where T.user_id = :uid and DATE_FORMAT(T.date, '%Y-%m') = monthDate GROUP BY DATE_FORMAT(T.date, '%Y-%m'))*100, 1) as rate\n" + "from TODO A\n" + - "where user_id = 55 and (A.date between '2023-12-01' and '2024-01-31') and A.complete=1\n" + + "where user_id = :uid and (A.date between :startDate and :endDate) and A.complete=1\n" + "group by monthDate\n" + "ORDER BY monthDate desc;", nativeQuery = true) List monthlyTodoBarGraphAndRateStatistics(@Param("uid") Long uid, @Param("startDate") LocalDate startDate , @Param("endDate") LocalDate endDate); From 346ca4a085335aef311e28e069473391bfbd6a38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=A7=80=ED=9B=88?= Date: Wed, 8 May 2024 15:23:16 +0900 Subject: [PATCH 02/10] Feat : User Subscribe -> User VIP Custom append Service --- .../custom/repository/HaveItemRepository.java | 1 + .../umc/mada/user/service/UserService.java | 33 +++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java b/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java index f80233c..d4a44d8 100644 --- a/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java +++ b/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java @@ -19,6 +19,7 @@ public interface HaveItemRepository extends JpaRepository { List findByUserAndWearing(User user, boolean wearing); boolean existsByCustomItemAndUser(CustomItem customItem, User user); + Boolean deleteByUserAndCustomItem(User user, CustomItem customItem); @Query("select h.customItem from HaveItem h where h.user = :user and h.wearing = :wearing") List findCustomItemByUserAndWearing(@Param("user") User user, @Param("wearing") boolean wearing); } diff --git a/src/main/java/com/umc/mada/user/service/UserService.java b/src/main/java/com/umc/mada/user/service/UserService.java index 44dffa5..6743ffd 100644 --- a/src/main/java/com/umc/mada/user/service/UserService.java +++ b/src/main/java/com/umc/mada/user/service/UserService.java @@ -1,5 +1,9 @@ package com.umc.mada.user.service; +import com.umc.mada.custom.domain.CustomItem; +import com.umc.mada.custom.domain.HaveItem; +import com.umc.mada.custom.repository.CustomRepository; +import com.umc.mada.custom.repository.HaveItemRepository; import com.umc.mada.user.domain.User; import com.umc.mada.user.dto.nickname.NicknameRequestDto; import com.umc.mada.user.dto.nickname.NicknameResponseDto; @@ -12,6 +16,7 @@ import java.security.Key; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -20,10 +25,13 @@ @Service public class UserService { private final UserRepository userRepository; - + private final CustomRepository customRepository; + private final HaveItemRepository haveItemRepository; @Autowired - public UserService(UserRepository userRepository){ + public UserService(UserRepository userRepository,CustomRepository customRepository, HaveItemRepository haveItemRepository){ + this.haveItemRepository = haveItemRepository; this.userRepository = userRepository; + this.customRepository = customRepository; } public User update(Long id, UserRequestDto.UpdateNickname request){ @@ -49,11 +57,30 @@ public NicknameResponseDto modifyNickname(User userAccount, NicknameRequestDto c userRepository.save(user); return NicknameResponseDto.of(changeNicknameRequestDto.getNickname()); } - + @Transactional public Boolean isSubscribe(Authentication authentication, Map is_subscribe) { + boolean condition = true; User user = this.getUser(authentication); + if(user.getSubscribe() != is_subscribe.get("is_subscribe")) + condition = false; user.updateSubscribe(is_subscribe.get("is_subscribe")); userRepository.save(user); + if(!condition){ + if(user.getSubscribe()){ + List subscribeCustomItems = customRepository.findByUnlockCondition(CustomItem.ItemUnlockCondition.PREMINUM); + for (CustomItem customItem : subscribeCustomItems){ + haveItemRepository.save(HaveItem.builder().user(user).customItem(customItem).build()); + } + } + else{ + List subscribeCustomItems = customRepository.findByUnlockCondition(CustomItem.ItemUnlockCondition.PREMINUM); + for (CustomItem customItem : subscribeCustomItems){ + haveItemRepository.deleteByUserAndCustomItem(user,customItem); + } + } + } + + return user.getSubscribe(); } From 733f005dd6d191769f6c87b29e664ec4e6c4af1a Mon Sep 17 00:00:00 2001 From: honeybears Date: Sat, 11 May 2024 23:43:07 +0900 Subject: [PATCH 03/10] Fix : Calendar Bug --- Dockerfile | 2 +- .../repository/CalendarRepository.java | 3 + .../calendar/service/CalendarService.java | 17 ---- .../controller/TimetableController.java | 21 ++++- .../repository/TimetableRepository.java | 1 - .../timetable/service/TimetableService.java | 92 ++++++++++--------- 6 files changed, 69 insertions(+), 67 deletions(-) diff --git a/Dockerfile b/Dockerfile index bbfac50..b92cb3e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM openjdk:11-jdk EXPOSE 8080 -ARG JAR_FILE=build/libs/*.jar +ARG JAR_FILE=build/libs/*-SNAPSHOT.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java", "-jar","-Dspring.config.location=classpath:/application.properties,classpath:/application-DB.properties,classpath:/application-jwt.properties,classpath:/application-oauth2.properties","/app.jar"] diff --git a/src/main/java/com/umc/mada/calendar/repository/CalendarRepository.java b/src/main/java/com/umc/mada/calendar/repository/CalendarRepository.java index 058cd5f..e90da4c 100644 --- a/src/main/java/com/umc/mada/calendar/repository/CalendarRepository.java +++ b/src/main/java/com/umc/mada/calendar/repository/CalendarRepository.java @@ -27,4 +27,7 @@ public interface CalendarRepository extends JpaRepository { "and MONTH(c.startDate) <= :m and MONTH(c.endDate) >= :m " ) List findCalendarMonth(User user , int y, int m); + + @Query("select c from Calendar c where c.user = :user and c.startDate <= :date and c.endDate >= :date") + List findCalendarDay(User user, LocalDate date); } diff --git a/src/main/java/com/umc/mada/calendar/service/CalendarService.java b/src/main/java/com/umc/mada/calendar/service/CalendarService.java index b6886b9..5148937 100644 --- a/src/main/java/com/umc/mada/calendar/service/CalendarService.java +++ b/src/main/java/com/umc/mada/calendar/service/CalendarService.java @@ -27,12 +27,6 @@ public CalendarService(CalendarRepository calendarRepository ,UserRepository use this.userRepository = userRepository; } -// -// public Map getCalendar(Authentication authentication,CalendarRequestDto calendarRequestDto){ -// calendarRepository.find -// } - - public Map readDday(Authentication authentication){ User user = this.getUser(authentication); List calendarList = calendarRepository.findAllByUserAndDday(user,'Y').stream().filter(calendar -> !calendar.isExpired()).collect(Collectors.toList());; @@ -87,17 +81,6 @@ public Map readDayCalendars(Authentication authentication, LocalD } -// public Map readRepeats(Authentication authentication) { -// User user = this.getUser(authentication); -// List calendarList = calendarRepository.findCalendarsByUserAndRepeatIsNotContaining(user,"No").stream().filter(calendar -> !calendar.isExpired()).collect(Collectors.toList()); -// List calendarResponseDtoList = calendarList.stream().map(this::calendarToDto).collect(Collectors.toList()); -// Map map = new LinkedHashMap<>(); -// Map data = new LinkedHashMap<>(); -// data.put("startTodoAtMonday",user.isStartTodoAtMonday()); -// data.put("calendars",calendarResponseDtoList); -// map.put("data",data); -// return map; -// } public Map readCalendars(Authentication authentication) { User user = this.getUser(authentication); List calendarList = calendarRepository.findAllByUser(user).stream().filter(calendar -> !calendar.isExpired()).collect(Collectors.toList());; diff --git a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java index 9172c35..8c924a5 100644 --- a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java +++ b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java @@ -55,7 +55,7 @@ public ResponseEntity> createTimetableComment(Authentication return ResponseEntity.ok().body(result); } - @PatchMapping("/comment/update/{date}") + @PatchMapping("/comment/{date}") public ResponseEntity> updateTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, @RequestBody CommentRequestDto commentRequestDto){ // comment 수정 API Optional userOptional = userRepository.findByAuthId(authentication.getName()); @@ -68,11 +68,24 @@ public ResponseEntity> updateTimetableComment(Authentication return ResponseEntity.ok().body(result); } - @GetMapping("/comment/date/{date}") - public ResponseEntity> getUserTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ + @PostMapping("/comment/{date}") + public ResponseEntity> addTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, @RequestBody CommentRequestDto commentRequestDto){ + // comment 수정 API + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); + CommentResponseDto updatedComment = timetableService.updateComment(user, date, commentRequestDto); + Map data = new LinkedHashMap<>(); + data.put("Comment", updatedComment); + Map result = new LinkedHashMap<>(); + result.put("data", data); + return ResponseEntity.ok().body(result); + } + + @GetMapping("/comment/{date}") + public ResponseEntity> readTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ Optional userOptional = userRepository.findByAuthId(authentication.getName()); User user = userOptional.get(); - CommentResponseDto userComment = timetableService.getUserComment(user, date); + CommentResponseDto userComment = timetableService.readComment(user, date); Map data = new LinkedHashMap<>(); data.put("Comment", userComment); Map result = new LinkedHashMap<>(); diff --git a/src/main/java/com/umc/mada/timetable/repository/TimetableRepository.java b/src/main/java/com/umc/mada/timetable/repository/TimetableRepository.java index 932201c..300353c 100644 --- a/src/main/java/com/umc/mada/timetable/repository/TimetableRepository.java +++ b/src/main/java/com/umc/mada/timetable/repository/TimetableRepository.java @@ -17,5 +17,4 @@ public interface TimetableRepository extends JpaRepository { List findTimetablesByUserIdAndDayOfWeekIsNot(User userId, DayOfWeek dayOfWeek); List findTimetablesByUserIdAndDateIsAndDayOfWeek(User userId, LocalDate date, DayOfWeek dayOfWeek); List findTimetablesByUserIdAndDayOfWeekAndIsDeletedIsFalse(User userId, DayOfWeek dayOfWeek); - } diff --git a/src/main/java/com/umc/mada/timetable/service/TimetableService.java b/src/main/java/com/umc/mada/timetable/service/TimetableService.java index a363621..0857bf1 100644 --- a/src/main/java/com/umc/mada/timetable/service/TimetableService.java +++ b/src/main/java/com/umc/mada/timetable/service/TimetableService.java @@ -16,6 +16,7 @@ import com.umc.mada.todo.domain.Todo; import com.umc.mada.timetable.domain.DayOfWeek; import com.umc.mada.todo.dto.RepeatTodoResponseDto; +import com.umc.mada.todo.dto.TodoResponseDto; import com.umc.mada.todo.repository.RepeatTodoRepository; import com.umc.mada.todo.repository.TodoRepository; import com.umc.mada.user.domain.User; @@ -49,6 +50,49 @@ public TimetableService(UserRepository userRepository, TimetableRepository timet this.repeatTodoRepository = repeatTodoRepository; } + // comment 생성 로직 + public CommentResponseDto createComment(User user, CommentRequestDto commentRequestDto){ + validateUserId(user); + + Comment comment = new Comment(user, commentRequestDto.getDate(), commentRequestDto.getContent()); + Comment savedComment = commentRepository.save(comment); + + return new CommentResponseDto(savedComment.getId(), savedComment.getDate(), savedComment.getContent()); + } + + @Transactional + // comment 수정 로직 + public CommentResponseDto updateComment (User user, LocalDate date, CommentRequestDto commentRequestDto){ + validateUserId(user); + + Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) + .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); + + // 날짜 변경 처리 + if (commentRequestDto.getDate() != null){ + comment.setDate(commentRequestDto.getDate()); + } + + // 내용 변경 처리 + if (commentRequestDto.getContent() != null){ + comment.setContent(commentRequestDto.getContent()); + } + + Comment updatedComment = commentRepository.save(comment); + return new CommentResponseDto(updatedComment.getId(), updatedComment.getDate(), updatedComment.getContent()); + } + + + // 특정 유저 comment 조회 로직 + public CommentResponseDto readComment(User user, LocalDate date) { + validateUserId(user); + + Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) + .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); + + return new CommentResponseDto(comment.getId(), comment.getDate(), comment.getContent()); + } + // 시간표 일정 생성 로직 public TimetableResponseDto createTimetable(User user, TimetableRequestDto timetableRequestDto){ // 유효성 검사 메서드를 호출하여 해당 ID가 데이터베이스에 존재하는지 확인 @@ -72,7 +116,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ validateUserId(user); List userTodos = todoRepository.findTodosByUserIdAndIsDeletedIsFalse(user); List repeatTodos = repeatTodoRepository.findRepeatTodosByDateIsAndIsDeletedIsFalse(date); - List calendars = calendarRepository.findAllByUser(user); + List calendars = calendarRepository.findCalendarDay(user,date); List> todoList = new ArrayList<>(); for (Todo todo : userTodos) { Map todoMap = new LinkedHashMap<>(); @@ -101,7 +145,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ List> calendarList = new ArrayList<>(); for (Calendar calendar : calendars) { // 시작일과 종료일 사이에 date가 있는 경우만 추가 - if (!date.isBefore(calendar.getStartDate()) && !date.isAfter(calendar.getEndDate())) { + Map calendarMap = new LinkedHashMap<>(); calendarMap.put("CalendarName", calendar.getCalendarName()); calendarMap.put("color", calendar.getColor()); @@ -109,7 +153,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ calendarMap.put("endTime", calendar.getEndTime()); // 종료 시간 calendarMap.put("d-day", calendar.getDday()); calendarList.add(calendarMap); - } + } Map data = new LinkedHashMap<>(); data.put("calendarList", calendarList); @@ -262,48 +306,7 @@ public Map checkAndLoadDailyData(User user, LocalDate date) { return result; } - // comment 생성 로직 - public CommentResponseDto createComment(User user, CommentRequestDto commentRequestDto){ - validateUserId(user); - - Comment comment = new Comment(user, commentRequestDto.getDate(), commentRequestDto.getContent()); - Comment savedComment = commentRepository.save(comment); - - return new CommentResponseDto(savedComment.getId(), savedComment.getDate(), savedComment.getContent()); - } - - @Transactional - // comment 수정 로직 - public CommentResponseDto updateComment (User user, LocalDate date, CommentRequestDto commentRequestDto){ - validateUserId(user); - Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) - .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); - - // 날짜 변경 처리 - if (commentRequestDto.getDate() != null){ - comment.setDate(commentRequestDto.getDate()); - } - - // 내용 변경 처리 - if (commentRequestDto.getContent() != null){ - comment.setContent(commentRequestDto.getContent()); - } - - Comment updatedComment = commentRepository.save(comment); - return new CommentResponseDto(updatedComment.getId(), updatedComment.getDate(), updatedComment.getContent()); - } - - - // 특정 유저 comment 조회 로직 - public CommentResponseDto getUserComment(User user, LocalDate date) { - validateUserId(user); - - Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) - .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); - - return new CommentResponseDto(comment.getId(), comment.getDate(), comment.getContent()); - } // 투두 이름 유효성 검사 메서드 private void validateTimetableName(String timetableName) { @@ -327,4 +330,5 @@ private boolean isSameSchedule(Timetable dailyEntry, Timetable weeklyEntry) { dailyEntry.getColor().equals(weeklyEntry.getColor()) && Objects.equals(dailyEntry.getMemo(), weeklyEntry.getMemo()); } + } From 71d2a819828db2eab00259bbb01ae8f965a34e94 Mon Sep 17 00:00:00 2001 From: yujiyea <54650556+yujiyea@users.noreply.github.com> Date: Mon, 13 May 2024 22:29:09 +0900 Subject: [PATCH 04/10] =?UTF-8?q?feat:=20=ED=86=B5=EA=B3=84=20responseDTO?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=B9=84=EC=8A=B7=ED=95=9C=20=EB=9C=BB?= =?UTF-8?q?=EC=9D=84=20=EA=B0=80=EC=A7=80=EB=8A=94=20=EB=B3=80=EC=88=98=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mada/todo/dto/StatisticsResponseDto.java | 34 ++++--------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java b/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java index aa868e6..73e4f6c 100644 --- a/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java +++ b/src/main/java/com/umc/mada/todo/dto/StatisticsResponseDto.java @@ -14,26 +14,18 @@ public class StatisticsResponseDto { private final List categoryStatistics; private final String mostCategory; //가장 많이 완료한 카테고리 - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float totalTodo; //추가한 todo 개수 private final float nowCategoryCount; //오늘, 이번주, 이번달 가장 많이 완료한 카테고리 수 private final float beforeCategoryCount; - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float diffCountA; private final List todoStatistics; private final float nowTotalCount; //오늘, 이번주, 이번달 전체 투두 수 - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float ratio; //비율 private final float nowCountCompleted; // 완료한 투두 수 - private final float diffCountB; //어제, 지난주, 지난 달에 완료한 투두 수보다 얼마나 더 많이 했는지 + private final float diffCount; //어제, 지난주, 지난 달에 완료한 투두 수보다 얼마나 더 많이 했는지 private final List achievementStatistics; private final float nowAchievementRate; //오늘, 이번주, 이번달 투두 달성도의 상승, 하락 비율 @JsonInclude(JsonInclude.Include.NON_DEFAULT) private final float nowCountCompletedA; - @JsonInclude(JsonInclude.Include.NON_DEFAULT) - private final float diffCountC; //오늘, 이번주, 이번달에 어제, 저번주, 저번달보다 얼마나 더 많이 했는지 public static StatisticsResponseDto ofDay(List categoryStatisticsVOList, PreviousCategoryStatisticsVO previousCategoryStatisticsVO, List todoBarGraphStatisticsVOList, int totalCount, List achievementRateStatisticsVOList){ @@ -47,11 +39,10 @@ public static StatisticsResponseDto ofDay(List categorySta .todoStatistics(todoBarGraphStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getTodoDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) .nowCountCompleted(todoBarGraphStatisticsVOList.get(0).getCount()) - .diffCountB(todoBarGraphStatisticsVOList.get(0).getCount() - todoBarGraphStatisticsVOList.get(1).getCount()) + .diffCount(todoBarGraphStatisticsVOList.get(0).getCount() - todoBarGraphStatisticsVOList.get(1).getCount()) .achievementStatistics(achievementRateStatisticsVOList.stream().map(vo -> AchievementStatisticsDto.of(vo.getDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(achievementRateStatisticsVOList.get(0).getRate() - achievementRateStatisticsVOList.get(1).getRate()) .nowCountCompletedA(achievementRateStatisticsVOList.get(0).getCount()) - .diffCountC(achievementRateStatisticsVOList.get(0).getCount() - achievementRateStatisticsVOList.get(1).getCount()) .build(); } else{ return StatisticsResponseDto.builder() @@ -62,11 +53,10 @@ public static StatisticsResponseDto ofDay(List categorySta .todoStatistics(Collections.emptyList()) .nowTotalCount(0) .nowCountCompleted(0) - .diffCountB(0) + .diffCount(0) .achievementStatistics(Collections.emptyList()) .nowAchievementRate(0.0f) .nowCountCompletedA(0.0f) - .diffCountC(0) .build(); } } @@ -76,36 +66,30 @@ public static StatisticsResponseDto ofWeek(List categorySt if (!categoryStatisticsVOList.isEmpty()) { return StatisticsResponseDto.builder() .categoryStatistics(categoryStatisticsVOList.stream().map(vo -> CategoryStatisticsDto.of(vo.getCategoryName(), vo.getColor(), vo.getRate())).collect(Collectors.toList())) - .totalTodo(totalCount) .mostCategory(categoryStatisticsVOList.get(0).getCategoryName()) .nowCategoryCount(categoryStatisticsVOList.get(0).getCount()) .beforeCategoryCount(previousCategoryStatisticsVO.getCount()) .todoStatistics(weeklyBarGraphAndRateStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getStartDate(), vo.getEndDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) - .ratio(weeklyBarGraphAndRateStatisticsVOList.get(0).getRate()) .nowCountCompleted(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountB(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) + .diffCount(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) .achievementStatistics(weeklyBarGraphAndRateStatisticsVOList.stream().map(vo -> AchievementStatisticsDto.of(vo.getStartDate(), vo.getEndDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(weeklyBarGraphAndRateStatisticsVOList.get(0).getRate() - weeklyBarGraphAndRateStatisticsVOList.get(1).getRate()) .nowCountCompletedA(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountC(weeklyBarGraphAndRateStatisticsVOList.get(0).getCount() - weeklyBarGraphAndRateStatisticsVOList.get(1).getCount()) .build(); } else{ return StatisticsResponseDto.builder() .categoryStatistics(Collections.emptyList()) - .totalTodo(0) .mostCategory("기본 카테고리") .nowCategoryCount(0) .beforeCategoryCount(0) .todoStatistics(Collections.emptyList()) .nowTotalCount(0) - .ratio(0.0f) .nowCountCompleted(0) - .diffCountB(0) + .diffCount(0) .achievementStatistics(Collections.emptyList()) .nowAchievementRate(0.0f) .nowCountCompletedA(0.0f) - .diffCountC(0) .build(); } } @@ -118,12 +102,10 @@ public static StatisticsResponseDto ofMonth(List categoryS .mostCategory(categoryStatisticsVOList.get(0).getCategoryName()) .nowCategoryCount(categoryStatisticsVOList.get(0).getCount()) .beforeCategoryCount(previousCategoryStatisticsVO.getCount()) - .diffCountA(categoryStatisticsVOList.get(0).getCount() - previousCategoryStatisticsVO.getCount()) .todoStatistics(monthlyBarGraphAndRateStatisticsVOList.stream().map(vo -> TodoStatisticsDto.of(vo.getMonthDate(), vo.getCount())).collect(Collectors.toList())) .nowTotalCount(totalCount) - .ratio(monthlyBarGraphAndRateStatisticsVOList.get(0).getRate()) .nowCountCompleted(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount()) - .diffCountB(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount() - monthlyBarGraphAndRateStatisticsVOList.get(1).getCount()) + .diffCount(monthlyBarGraphAndRateStatisticsVOList.get(0).getCount() - monthlyBarGraphAndRateStatisticsVOList.get(1).getCount()) .achievementStatistics(monthlyBarGraphAndRateStatisticsVOList.stream().map(vo-> AchievementStatisticsDto.of(vo.getMonthDate(), vo.getRate())).collect(Collectors.toList())) .nowAchievementRate(monthlyBarGraphAndRateStatisticsVOList.get(0).getRate() - monthlyBarGraphAndRateStatisticsVOList.get(1).getRate()) .build(); @@ -133,12 +115,10 @@ public static StatisticsResponseDto ofMonth(List categoryS .mostCategory("기본 카테고리") .nowCategoryCount(0) .beforeCategoryCount(0) - .diffCountA(0) .todoStatistics(Collections.emptyList()) .nowTotalCount(0) - .ratio(0.0f) .nowCountCompleted(0) - .diffCountB(0) + .diffCount(0) .achievementStatistics(Collections.emptyList()) .nowAchievementRate(0.0f) .build(); From 15bc5d92b21f6138d34eace766edc0cd4423020f Mon Sep 17 00:00:00 2001 From: yujiyea <54650556+yujiyea@users.noreply.github.com> Date: Wed, 15 May 2024 21:28:18 +0900 Subject: [PATCH 05/10] =?UTF-8?q?refactor:=20=ED=9A=8C=EC=9B=90=ED=83=88?= =?UTF-8?q?=ED=87=B4=ED=95=9C=20=EC=9C=A0=EC=A0=80=EB=8A=94=20=EC=82=AC?= =?UTF-8?q?=EC=9A=A9=ED=95=A0=20=EC=88=98=20=EC=97=86=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/OAuth2LoginSuccessHandler.java | 6 +-- .../auth/service/CustomUserDetailService.java | 2 +- .../calendar/service/CalendarService.java | 3 +- .../controller/CategoryController.java | 21 +++------ .../custom/controller/CustomController.java | 4 +- .../umc/mada/exception/ControllerAdvice.java | 6 +++ .../mada/exception/NotFoundUserException.java | 7 +++ .../com/umc/mada/my/service/MyService.java | 5 +-- .../controller/TimetableController.java | 43 ++++++------------- .../mada/todo/controller/TodoController.java | 30 ++++--------- .../umc/mada/todo/service/ChartService.java | 11 +++-- .../mada/user/controller/UserController.java | 22 +++++----- .../mada/user/domain/CusomtUserDetails.java | 2 +- .../java/com/umc/mada/user/domain/User.java | 8 ++-- .../mada/user/repository/UserRepository.java | 3 +- .../umc/mada/user/service/UserService.java | 9 +--- 16 files changed, 74 insertions(+), 108 deletions(-) create mode 100644 src/main/java/com/umc/mada/exception/NotFoundUserException.java diff --git a/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java b/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java index a77c48e..6cd4f59 100644 --- a/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java +++ b/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java @@ -15,7 +15,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.util.Optional; @Component @RequiredArgsConstructor @@ -27,15 +26,14 @@ public class OAuth2LoginSuccessHandler implements AuthenticationSuccessHandler { public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { OAuth2User oAuth2User = (OAuth2User)authentication.getPrincipal(); // OAuth2Attributes oAuth2Attributes = OAuth2Attributes.of(provider, userNameAttributeName, oAuth2User.getAttributes()); -// Optional findUser = userRepository.findByAuthId() +// Optional findUser = userRepository.findByAuthIdAndAccountExpired() //jwt 생성 String accessToken = jwtTokenProvider.createAccessToken(oAuth2User); String refreshToken = jwtTokenProvider.createRefreshToken(oAuth2User); //refreshtoken을 DB에 저장해야함 - Optional userOptional = userRepository.findByAuthId(oAuth2User.getName()); - User user = userOptional.get(); //TODO: null값 체크하기 + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); user.setRefreshToken(refreshToken); // tokenResponse(response, accessToken); diff --git a/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java b/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java index db15552..a4e1cdb 100644 --- a/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java +++ b/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java @@ -49,7 +49,7 @@ private OAuth2User process(OAuth2UserRequest userRequest, OAuth2User oAuth2User) OAuth2Attributes oAuth2Attributes = OAuth2Attributes.of(provider, userNameAttributeName, oAuth2User.getAttributes()); - Optional userOptional = userRepository.findByAuthId(oAuth2Attributes.getAuthId()); + Optional userOptional = userRepository.findByAuthIdAndAccountExpired(oAuth2Attributes.getAuthId(), false); User user; boolean newUser=false; diff --git a/src/main/java/com/umc/mada/calendar/service/CalendarService.java b/src/main/java/com/umc/mada/calendar/service/CalendarService.java index 641346c..2a3e83b 100644 --- a/src/main/java/com/umc/mada/calendar/service/CalendarService.java +++ b/src/main/java/com/umc/mada/calendar/service/CalendarService.java @@ -164,8 +164,7 @@ public List readCalendarsByDate(List calendarList, LocalDate private User getUser(Authentication authentication) throws NoSuchElementException { try{ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - return userOptional.get(); + return userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); }catch (RuntimeException e){ throw new NoSuchElementException(); } diff --git a/src/main/java/com/umc/mada/category/controller/CategoryController.java b/src/main/java/com/umc/mada/category/controller/CategoryController.java index 9073ae1..1ba0d0a 100644 --- a/src/main/java/com/umc/mada/category/controller/CategoryController.java +++ b/src/main/java/com/umc/mada/category/controller/CategoryController.java @@ -33,8 +33,7 @@ public CategoryController(CategoryService categoryService, UserRepository userRe @PostMapping public ResponseEntity> addCategory(Authentication authentication, @Valid @RequestBody CategoryRequestDto categoryRequestDto) { // 카테고리 생성 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); CategoryResponseDto newCategory = categoryService.createCategory(user, categoryRequestDto); Map data = new LinkedHashMap<>(); data.put("Category", newCategory); @@ -49,8 +48,7 @@ public ResponseEntity> addCategory(Authentication authentica @PatchMapping("/{categoryId}") public ResponseEntity> updateCategory(Authentication authentication,@PathVariable int categoryId, @Valid @RequestBody CategoryRequestDto categoryRequestDto) { // 카테고리 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); CategoryResponseDto updatedCategory = categoryService.updateCategory(user, categoryId, categoryRequestDto); Map data = new LinkedHashMap<>(); data.put("Category", updatedCategory); @@ -70,8 +68,7 @@ public ResponseEntity> updateCategory(Authentication authent public ResponseEntity> deleteCategory(Authentication authentication, @PathVariable int categoryId) { // 카테고리 삭제 API try{ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); categoryService.deleteCategory(user,categoryId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -87,8 +84,7 @@ public ResponseEntity> deleteCategory(Authentication authent public ResponseEntity> inactiveCategory(Authentication authentication, @PathVariable int categoryId) { //카테고리 종료 API try{ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); categoryService.inactiveCategory(user, categoryId); Map result = new LinkedHashMap<>(); return ResponseEntity.ok().body(result); @@ -101,8 +97,7 @@ public ResponseEntity> inactiveCategory(Authentication authe public ResponseEntity> activeCategory(Authentication authentication, @PathVariable int categoryId) { //종료된 카테고리 복원 API try{ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); categoryService.activeCategory(user, categoryId); Map result = new LinkedHashMap<>(); return ResponseEntity.ok().body(result); @@ -115,8 +110,7 @@ public ResponseEntity> activeCategory(Authentication authent public ResponseEntity> getAllCategories(Authentication authentication) { // 특정 유저 카테고리 목록 조회 API (카테고리 목록) try { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List allCategories = categoryService.getAllCategories(user); Map data = new LinkedHashMap<>(); data.put("CategoryList", allCategories); @@ -135,8 +129,7 @@ public ResponseEntity> getAllCategories(Authentication authe public ResponseEntity> getHomeCategories(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) { // 특정 유저 카테고리 목록 조회 API (home) try { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List homeCategories = categoryService.getHomeCategories(user, date); Map data = new LinkedHashMap<>(); data.put("CategoryList", homeCategories); diff --git a/src/main/java/com/umc/mada/custom/controller/CustomController.java b/src/main/java/com/umc/mada/custom/controller/CustomController.java index 100d657..551d6f7 100644 --- a/src/main/java/com/umc/mada/custom/controller/CustomController.java +++ b/src/main/java/com/umc/mada/custom/controller/CustomController.java @@ -94,8 +94,8 @@ public ResponseEntity buyItem(Authentication authentication, @PathVariable private User findUser(Authentication authentication){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); // User user = userOptional.get(); //TODO: get값이 NULL인 경우를 체크해줘야함 - return userOptional.get(); + return user; } } diff --git a/src/main/java/com/umc/mada/exception/ControllerAdvice.java b/src/main/java/com/umc/mada/exception/ControllerAdvice.java index 20629e7..33bb2d9 100644 --- a/src/main/java/com/umc/mada/exception/ControllerAdvice.java +++ b/src/main/java/com/umc/mada/exception/ControllerAdvice.java @@ -18,6 +18,12 @@ public ResponseEntity buyDuplicateItemHandler(final BuyOwnedItemE public ResponseEntity notAllowToWearingHandler(final NotAllowToWearingException e){ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResponse(e.getMessage())); } + + @ExceptionHandler(NotFoundUserException.class) + public ResponseEntity notFoundUserHandler(final NotFoundUserException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResponse(e.getMessage())); + } + @ExceptionHandler(ServerInternalException.class) public ResponseEntity testErrorHandler(final ServerInternalException e, HttpServletRequest httpServletRequest){ ErrorResponse errorResponse = ErrorResponse.builder() diff --git a/src/main/java/com/umc/mada/exception/NotFoundUserException.java b/src/main/java/com/umc/mada/exception/NotFoundUserException.java new file mode 100644 index 0000000..86785fd --- /dev/null +++ b/src/main/java/com/umc/mada/exception/NotFoundUserException.java @@ -0,0 +1,7 @@ +package com.umc.mada.exception; + +public class NotFoundUserException extends RuntimeException{ + public NotFoundUserException(final String message){ + super(message); + } +} diff --git a/src/main/java/com/umc/mada/my/service/MyService.java b/src/main/java/com/umc/mada/my/service/MyService.java index f59cedd..a7d8489 100644 --- a/src/main/java/com/umc/mada/my/service/MyService.java +++ b/src/main/java/com/umc/mada/my/service/MyService.java @@ -4,7 +4,6 @@ import com.umc.mada.my.dto.MyResponseDto; import com.umc.mada.my.repository.MyRepository; import com.umc.mada.user.domain.User; -import com.umc.mada.user.service.UserService; import com.umc.mada.user.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; @@ -36,8 +35,8 @@ public List findRandomSaying() { } private User getUser(Authentication authentication){ - Optional optionalUser = userRepository.findByAuthId(authentication.getName()); - return optionalUser.get(); + User user= userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + return user; } public Map findMyProfileList(Authentication authentication) { diff --git a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java index 9172c35..d9b89f7 100644 --- a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java +++ b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java @@ -1,20 +1,16 @@ package com.umc.mada.timetable.controller; -import com.umc.mada.calendar.domain.Calendar; import com.umc.mada.calendar.repository.CalendarRepository; -import com.umc.mada.timetable.domain.DayOfWeek; import com.umc.mada.timetable.dto.CommentRequestDto; import com.umc.mada.timetable.dto.CommentResponseDto; import com.umc.mada.timetable.dto.TimetableRequestDto; import com.umc.mada.timetable.dto.TimetableResponseDto; import com.umc.mada.timetable.service.TimetableService; -import com.umc.mada.todo.domain.Todo; import com.umc.mada.todo.repository.TodoRepository; import com.umc.mada.user.domain.User; import com.umc.mada.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; @@ -45,8 +41,7 @@ public TimetableController(TodoRepository todoRepository, CalendarRepository cal @PostMapping("/comment") public ResponseEntity> createTimetableComment(Authentication authentication, @RequestBody CommentRequestDto commentRequestDto){ // comment 생성 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); CommentResponseDto newComment = timetableService.createComment(user, commentRequestDto); Map data = new LinkedHashMap<>(); data.put("Comment", newComment); @@ -58,8 +53,7 @@ public ResponseEntity> createTimetableComment(Authentication @PatchMapping("/comment/update/{date}") public ResponseEntity> updateTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, @RequestBody CommentRequestDto commentRequestDto){ // comment 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); CommentResponseDto updatedComment = timetableService.updateComment(user, date, commentRequestDto); Map data = new LinkedHashMap<>(); data.put("Comment", updatedComment); @@ -70,8 +64,7 @@ public ResponseEntity> updateTimetableComment(Authentication @GetMapping("/comment/date/{date}") public ResponseEntity> getUserTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); CommentResponseDto userComment = timetableService.getUserComment(user, date); Map data = new LinkedHashMap<>(); data.put("Comment", userComment); @@ -88,8 +81,7 @@ public ResponseEntity> getUserTimetableComment(Authenticatio @PostMapping("/daily") public ResponseEntity> createDailyTimetable(Authentication authentication, @RequestBody TimetableRequestDto timetableRequestDto){ // 일일 시간표 일정 생성 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); TimetableResponseDto newTimetable = timetableService.createTimetable(user, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("DailyTimetable", newTimetable); @@ -104,8 +96,7 @@ public ResponseEntity> createDailyTimetable(Authentication a @PostMapping("/daily/loadWeekly/{date}") public ResponseEntity> loadDailyTimetableFromWeekly(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ // 주간시간표 불러오기 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = timetableService.checkAndLoadDailyData(user, date); //result.put("status", 200); //result.put("success", true); @@ -116,8 +107,7 @@ public ResponseEntity> loadDailyTimetableFromWeekly(Authenti @PatchMapping("/daily/update/{scheduleId}") public ResponseEntity> updateDailyTimetable(Authentication authentication, @PathVariable int scheduleId, @RequestBody TimetableRequestDto timetableRequestDto){ // 일일 시간표 일정 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); TimetableResponseDto updatedTimetable = timetableService.updateTimetable(user, scheduleId, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("DailyTimetable", updatedTimetable); @@ -132,8 +122,7 @@ public ResponseEntity> updateDailyTimetable(Authentication a @PatchMapping("/daily/delete/{scheduleId}") public ResponseEntity> deleteDailyTimetable(Authentication authentication, @PathVariable int scheduleId) { // 일일 시간표 일정 삭제 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); timetableService.deleteTimetable(user, scheduleId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -145,8 +134,7 @@ public ResponseEntity> deleteDailyTimetable(Authentication a @GetMapping("/daily/date/{date}") // 일일 시간표 조회 API public ResponseEntity> getUserDailyTimetable(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List userTimetables = timetableService.getDailyTimetable(user, date); Map data = new LinkedHashMap<>(); data.put("DailyTimetableList", userTimetables); @@ -165,8 +153,7 @@ public ResponseEntity> getUserDailyTimetable(Authentication @PostMapping("/weekly/create") public ResponseEntity> createWeeklyTimetable(Authentication authentication, @RequestBody TimetableRequestDto timetableRequestDto){ // 주간 시간표 일정 생성 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); TimetableResponseDto newTimetable = timetableService.createTimetable(user, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetable", newTimetable); @@ -181,8 +168,7 @@ public ResponseEntity> createWeeklyTimetable(Authentication @PatchMapping("/weekly/update/{scheduleId}") public ResponseEntity> updateWeeklyTimetable(Authentication authentication, @PathVariable int scheduleId, @RequestBody TimetableRequestDto timetableRequestDto){ // 주간 시간표 일정 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); TimetableResponseDto updatedTimetable = timetableService.updateTimetable(user, scheduleId, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetable", updatedTimetable); @@ -197,8 +183,7 @@ public ResponseEntity> updateWeeklyTimetable(Authentication @PatchMapping("/weekly/delete/{scheduleId}") public ResponseEntity> deleteWeeklyTimetable(Authentication authentication, @PathVariable int scheduleId) { // 주간 시간표 일정 삭제 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); timetableService.deleteTimetable(user, scheduleId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -210,8 +195,7 @@ public ResponseEntity> deleteWeeklyTimetable(Authentication @GetMapping("/weekly") // 주간 시간표 일정 조회 API public ResponseEntity> getUserWeeklyTimetable(Authentication authentication){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List userTimetables = timetableService.getWeeklyTimetable(user); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetableList", userTimetables); @@ -227,8 +211,7 @@ public ResponseEntity> getUserWeeklyTimetable(Authentication @GetMapping("search/date/{date}") // 시간표 추가 시, 특정 유저 일정(캘린더)과 투두 조회 API public ResponseEntity> getTodoAndCalendar(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = timetableService.getTodoAndCalendar(user, date); return ResponseEntity.ok().body(map); } diff --git a/src/main/java/com/umc/mada/todo/controller/TodoController.java b/src/main/java/com/umc/mada/todo/controller/TodoController.java index fcea4dd..a0b9d00 100644 --- a/src/main/java/com/umc/mada/todo/controller/TodoController.java +++ b/src/main/java/com/umc/mada/todo/controller/TodoController.java @@ -1,11 +1,9 @@ package com.umc.mada.todo.controller; -import com.umc.mada.todo.domain.Todo; import com.umc.mada.todo.dto.RepeatTodoRequestDto; import com.umc.mada.todo.dto.RepeatTodoResponseDto; import com.umc.mada.todo.dto.TodoRequestDto; import com.umc.mada.todo.dto.TodoResponseDto; -import com.umc.mada.todo.repository.TodoRepository; import com.umc.mada.todo.service.TodoService; import com.umc.mada.user.domain.User; import com.umc.mada.user.repository.UserRepository; @@ -13,7 +11,6 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.time.LocalDate; @@ -35,8 +32,7 @@ public TodoController(TodoService todoService, UserRepository userRepository) { @PostMapping public ResponseEntity> createTodo(Authentication authentication, @RequestBody TodoRequestDto todoRequestDto) { // 투두 생성 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = todoService.createTodo(user, todoRequestDto); //TodoResponseDto newTodo = todoService.createTodo(user, todoRequestDto); //Map data = new LinkedHashMap<>(); @@ -52,8 +48,7 @@ public ResponseEntity> createTodo(Authentication authenticat @PatchMapping("/update/{todoId}") public ResponseEntity> updateTodo(Authentication authentication, @PathVariable int todoId, @RequestBody TodoRequestDto todoRequestDto){ // 투두 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = todoService.updateTodo(user, todoId, todoRequestDto); //TodoResponseDto updatedTodo = todoService.updateTodo(user, todoId, todoRequestDto); //Map data = new LinkedHashMap<>(); @@ -69,8 +64,7 @@ public ResponseEntity> updateTodo(Authentication authenticat @PatchMapping("/delete/{todoId}") public ResponseEntity> deleteTodo(Authentication authentication, @PathVariable int todoId) { // 투두 삭제 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); todoService.deleteTodo(user, todoId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -82,8 +76,7 @@ public ResponseEntity> deleteTodo(Authentication authenticat @PatchMapping("/repeat/update/{repeatTodoId}") public ResponseEntity> updateRepeatTodo(Authentication authentication, @PathVariable int repeatTodoId, @RequestBody RepeatTodoRequestDto repeatTodoRequestDto) { // 반복 투두 수정 API - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); RepeatTodoResponseDto updatedRepeatTodo = todoService.updateRepeatTodo(user, repeatTodoId, repeatTodoRequestDto); Map data = new LinkedHashMap<>(); data.put("RepeatTodo", updatedRepeatTodo); @@ -98,8 +91,7 @@ public ResponseEntity> updateRepeatTodo(Authentication authe @PatchMapping("/repeat/delete/{repeatTodoId}") public ResponseEntity> deleteRepeatTodo(Authentication authentication, @PathVariable int repeatTodoId) { // 반복 투두 삭제 API (이 반복 투두) - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); todoService.deleteRepeatTodo(user, repeatTodoId); Map result = new LinkedHashMap<>(); result.put("message", "반복 투두 삭제가 완료되었습니다."); @@ -109,8 +101,7 @@ public ResponseEntity> deleteRepeatTodo(Authentication authe @PatchMapping("/repeat/delete-all-future/{repeatTodoId}") public ResponseEntity> deleteRepeatTodoAndFuture(Authentication authentication, @PathVariable int repeatTodoId) { // 반복 투두 삭제 API (이 반복 투두 및 향후 반복 투두) - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); todoService.deleteRepeatTodoAndFuture(user, repeatTodoId); Map result = new LinkedHashMap<>(); result.put("message", "해당 반복 투두 및 향후 반복 투두 삭제가 완료되었습니다."); @@ -120,8 +111,7 @@ public ResponseEntity> deleteRepeatTodoAndFuture(Authenticat @PatchMapping("/repeat/delete-all/{repeatTodoId}") public ResponseEntity> deleteAllRepeatTodos(Authentication authentication, @PathVariable int repeatTodoId) { // 반복 투두 삭제 API (모든 반복 투두) - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); todoService.deleteAllRepeatTodos(user, repeatTodoId); Map result = new LinkedHashMap<>(); result.put("message", "모든 반복 투두 삭제가 완료되었습니다."); @@ -131,8 +121,7 @@ public ResponseEntity> deleteAllRepeatTodos(Authentication a @GetMapping("/date/{date}") // 특정 유저 투두 조회 API public ResponseEntity> getUserTodo(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = todoService.getUserTodo(user, date); //List userTodos = todoService.getUserTodo(user, date); //Map data = new LinkedHashMap<>(); @@ -148,8 +137,7 @@ public ResponseEntity> getUserTodo(Authentication authentica @GetMapping("/repeat/all") // 반복 투두 조회 API public ResponseEntity> getUserRepeatTodo(Authentication authentication){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List repeatTodos = todoService.getUserRepeatTodo(user); Map data = new LinkedHashMap<>(); data.put("RepeatTodoList", repeatTodos); diff --git a/src/main/java/com/umc/mada/todo/service/ChartService.java b/src/main/java/com/umc/mada/todo/service/ChartService.java index ec70c93..ec032d8 100644 --- a/src/main/java/com/umc/mada/todo/service/ChartService.java +++ b/src/main/java/com/umc/mada/todo/service/ChartService.java @@ -1,5 +1,6 @@ package com.umc.mada.todo.service; +import com.umc.mada.exception.NotFoundUserException; import com.umc.mada.todo.dto.StatisticsResponseDto; import com.umc.mada.todo.repository.ChartRepository; import com.umc.mada.todo.repository.RepeatTodoRepository; @@ -26,7 +27,9 @@ public class ChartService { private final RepeatTodoRepository repeatTodoRepository; public StatisticsResponseDto dailyStatistics(Authentication authentication, LocalDate date){ - User user = userRepository.findByAuthId(authentication.getName()).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); +// User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName()).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); +// User user = userRepository.findByAuthIdAndAccountExpiredAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new NotFoundUserException("유저를 찾을 수 없습니다")); //카테고리 통계 List categoryStatisticsVOList = chartRepository.statisticsOnCategories(user.getId(), date, date); @@ -52,7 +55,7 @@ public StatisticsResponseDto dailyStatistics(Authentication authentication, Loca } public StatisticsResponseDto weeklyStatistics(Authentication authentication, LocalDate date){ - User user = userRepository.findByAuthId(authentication.getName()).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); //date에 해당하는 주의 시작 날짜와 마지막 날짜 구하기 LocalDate startDate = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)); @@ -79,7 +82,7 @@ public StatisticsResponseDto weeklyStatistics(Authentication authentication, Loc } public StatisticsResponseDto monthlyStatistics(Authentication authentication, LocalDate date){ - User user = userRepository.findByAuthId(authentication.getName()).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); //date에 해당하는 주의 시작 날짜와 마지막 날짜 구하기 LocalDate startDate = date.with(TemporalAdjusters.firstDayOfMonth()); @@ -106,7 +109,7 @@ public StatisticsResponseDto monthlyStatistics(Authentication authentication, Lo } public Map findDatesWithTodosByMonth(Authentication authentication, YearMonth yearMonth) { - User user = userRepository.findByAuthId(authentication.getName()).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); // 투두 Set datesWithTodosSet = new HashSet<>(todoRepository.findDistinctDaysByUserIdAndYearMonth(user.getId(), yearMonth.toString())); diff --git a/src/main/java/com/umc/mada/user/controller/UserController.java b/src/main/java/com/umc/mada/user/controller/UserController.java index e053bf7..a32d53d 100644 --- a/src/main/java/com/umc/mada/user/controller/UserController.java +++ b/src/main/java/com/umc/mada/user/controller/UserController.java @@ -1,5 +1,6 @@ package com.umc.mada.user.controller; +import com.umc.mada.exception.NotFoundUserException; import com.umc.mada.timetable.domain.Timetable; import com.umc.mada.todo.domain.Todo; import com.umc.mada.todo.dto.TodoStatisticsRequestDto; @@ -52,8 +53,8 @@ public void test(Authentication authentication, HttpServletResponse response, @R // System.out.println("oAuth2User = " + oAuth2User); // authentication.getPrincipal() // System.out.println(cusomtUserDetails.getUser()); -// System.out.println(authentication.getName()); -// return ResponseEntity.status(HttpStatus.OK).body(authentication.getName()); +// System.out.println(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); +// return ResponseEntity.status(HttpStatus.OK).body(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); //httpServletResponse 방법 response.setHeader("Content-type", "text/plain"); @@ -87,8 +88,8 @@ public void signupToken(HttpServletResponse response, @RequestParam String token @Operation(description = "회원가입한 유저가 닉네임 입력하는 곳") @PostMapping("/signup/nickName") public ResponseEntity signupNickname(@RequestBody Map nickname, Authentication authentication) { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - userService.setNickname(nickname, userOptional.get()); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + userService.setNickname(nickname, user); // return ResponseEntity.status(HttpStatus.OK).body("닉네임 입력 성공했습니다."); return ResponseEntity.ok().build(); } @@ -105,8 +106,8 @@ public ResponseEntity logout() { @DeleteMapping("/withdrawal") public ResponseEntity userRemove (Authentication authentication){ //@AuthenticationPrincipal CusomtUserDetails cusomtUserDetails // User user = cusomtUserDetails.getUser(); - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - userService.removeUser(userOptional.get()); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + userService.removeUser(user); return ResponseEntity.ok().build(); } @@ -126,8 +127,7 @@ public ResponseEntity userRemove (Authentication authentication){ //@Aut @PatchMapping("/profile/change/nickname") public ResponseEntity>nicknameModify(Authentication authentication, @Validated @RequestBody NicknameRequestDto changeNicknameRequestDto) { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); Map map = new HashMap<>(); map.put("data", userService.modifyNickname(user, changeNicknameRequestDto)); // if(bindingResult.hasErrors()){ @@ -203,8 +203,7 @@ public ResponseEntity> alarmToggleList(Authentication authen */ @GetMapping("/statistics/day/{date}") public ResponseEntity> findDailyTodoAndTimetableAvg(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user= userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); List todos = todoRepository.findTodosByUserIdAndDateIs(user, date); List timetables = timetableRepository.findTimetablesByUserIdAndDateIs(user, date); @@ -242,8 +241,7 @@ public ResponseEntity> findDailyTodoAndTimetableAvg(Authenti */ @PostMapping("/statistics") public ResponseEntity> userTodoAvg(Authentication authentication, @RequestBody TodoStatisticsRequestDto todoStatisticsRequestDto) { - Optional userOptional = userRepository.findByAuthId(authentication.getName()); - User user = userOptional.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new NotFoundUserException("유저를 찾을 수 없습니다.")); Map map = new LinkedHashMap<>(); // Map data = new LinkedHashMap<>(); // data.put("average", todoService.calcTodoAverage(user,todoAverageRequestDto)); diff --git a/src/main/java/com/umc/mada/user/domain/CusomtUserDetails.java b/src/main/java/com/umc/mada/user/domain/CusomtUserDetails.java index 9d96a24..f285a55 100644 --- a/src/main/java/com/umc/mada/user/domain/CusomtUserDetails.java +++ b/src/main/java/com/umc/mada/user/domain/CusomtUserDetails.java @@ -83,6 +83,6 @@ public boolean isCredentialsNonExpired() { @Override public boolean isEnabled() { //계정이 사용가능한 계정인지, true면 사용가능한 계정 - return user.isAccount_expired(); + return user.isAccountExpired(); } } diff --git a/src/main/java/com/umc/mada/user/domain/User.java b/src/main/java/com/umc/mada/user/domain/User.java index 15d350a..02420ed 100644 --- a/src/main/java/com/umc/mada/user/domain/User.java +++ b/src/main/java/com/umc/mada/user/domain/User.java @@ -2,14 +2,11 @@ import javax.persistence.*; -//import com.umc.mada.BaseTimeEntity; import com.umc.mada.custom.domain.HaveItem; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.umc.mada.user.dto.user.UserRequestDto; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; -import org.springframework.security.oauth2.core.OAuth2AccessToken; import java.time.LocalDateTime; import java.util.ArrayList; @@ -47,7 +44,8 @@ public class User { private boolean endTodoBackSetting; @Column(name = "new_todo_start_setting") //TODO: Cannot resolve column private boolean newTodoStartSetting; - private boolean account_expired; + @Column(name="account_expired") + private boolean accountExpired; //회원탈퇴 여부 private String refreshToken; @Column(name = "google_access_token") private String googleAccessToken; //TODO: 테이블 분리하기 @@ -100,7 +98,7 @@ public User update(String authId, String email, String googleAccessToken) { } public User expiredUserUpdate() { - this.account_expired = true; + this.accountExpired = true; return this; } diff --git a/src/main/java/com/umc/mada/user/repository/UserRepository.java b/src/main/java/com/umc/mada/user/repository/UserRepository.java index 738f216..d7e5826 100644 --- a/src/main/java/com/umc/mada/user/repository/UserRepository.java +++ b/src/main/java/com/umc/mada/user/repository/UserRepository.java @@ -2,16 +2,15 @@ import com.umc.mada.user.domain.User; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import java.util.List; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository { Optional findUserById(Long id); Optional findByAuthId(String authId); + Optional findByAuthIdAndAccountExpired(String authId, Boolean accountExpired); Optional findUserByNickname(String nickName); } diff --git a/src/main/java/com/umc/mada/user/service/UserService.java b/src/main/java/com/umc/mada/user/service/UserService.java index 44dffa5..b409d6d 100644 --- a/src/main/java/com/umc/mada/user/service/UserService.java +++ b/src/main/java/com/umc/mada/user/service/UserService.java @@ -4,18 +4,13 @@ import com.umc.mada.user.dto.nickname.NicknameRequestDto; import com.umc.mada.user.dto.nickname.NicknameResponseDto; import com.umc.mada.user.dto.user.UserRequestDto; -import com.umc.mada.user.dto.user.UserResponseDto; import com.umc.mada.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; -import java.security.Key; import java.util.HashMap; import java.util.Map; -import java.util.Optional; - -import javax.transaction.Transactional; @Service public class UserService { @@ -120,7 +115,7 @@ public void removeUser(User user){ } private User getUser(Authentication authentication){ - Optional optionalUser = userRepository.findByAuthId(authentication.getName()); - return optionalUser.get(); + User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + return user; } } From 8f8a51c5aa6137a4076e83d65b4694a4ee5fecc0 Mon Sep 17 00:00:00 2001 From: yujiyea <54650556+yujiyea@users.noreply.github.com> Date: Fri, 17 May 2024 00:04:16 +0900 Subject: [PATCH 06/10] =?UTF-8?q?fix:=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20?= =?UTF-8?q?=EC=8B=9C=20=ED=9A=8C=EC=9B=90=ED=83=88=ED=87=B4=20=EC=97=AC?= =?UTF-8?q?=EB=B6=80=20=EC=B2=B4=ED=81=AC=ED=95=98=EB=A9=B4=EC=84=9C=20?= =?UTF-8?q?=EB=B0=9C=EC=83=9D=ED=95=9C=20=EC=98=A4=EB=A5=98=20=ED=95=B4?= =?UTF-8?q?=EA=B2=B0(=ED=9A=8C=EC=9B=90=ED=83=88=ED=87=B4=ED=95=9C=20?= =?UTF-8?q?=EC=9C=A0=EC=A0=80=EA=B0=80=20=EB=A1=9C=EA=B7=B8=EC=9D=B8?= =?UTF-8?q?=ED=95=A0=20=EB=95=8C=20=EC=96=B4=EB=96=BB=EA=B2=8C=20=ED=95=A0?= =?UTF-8?q?=EC=A7=80=20=EC=83=9D=EA=B0=81=ED=95=B4=EC=95=BC=20=ED=95=A8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java | 4 +++- .../com/umc/mada/auth/service/CustomUserDetailService.java | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java b/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java index 6cd4f59..acfa1d0 100644 --- a/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java +++ b/src/main/java/com/umc/mada/auth/handler/OAuth2LoginSuccessHandler.java @@ -1,6 +1,7 @@ package com.umc.mada.auth.handler; import com.umc.mada.auth.handler.jwt.JwtTokenProvider; +import com.umc.mada.exception.NotFoundUserException; import com.umc.mada.user.domain.CusomtUserDetails; import com.umc.mada.user.domain.User; import com.umc.mada.user.repository.UserRepository; @@ -33,7 +34,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo String refreshToken = jwtTokenProvider.createRefreshToken(oAuth2User); //refreshtoken을 DB에 저장해야함 - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); +// User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + User user = userRepository.findByAuthId(oAuth2User.getName()).orElseThrow(()-> new NotFoundUserException("유저를 찾을 수 없습니다.")); user.setRefreshToken(refreshToken); // tokenResponse(response, accessToken); diff --git a/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java b/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java index a4e1cdb..2200933 100644 --- a/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java +++ b/src/main/java/com/umc/mada/auth/service/CustomUserDetailService.java @@ -49,7 +49,8 @@ private OAuth2User process(OAuth2UserRequest userRequest, OAuth2User oAuth2User) OAuth2Attributes oAuth2Attributes = OAuth2Attributes.of(provider, userNameAttributeName, oAuth2User.getAttributes()); - Optional userOptional = userRepository.findByAuthIdAndAccountExpired(oAuth2Attributes.getAuthId(), false); + Optional userOptional = userRepository.findByAuthId(oAuth2Attributes.getAuthId()); +// Optional userOptional = userRepository.findByAuthIdAndAccountExpired(oAuth2Attributes.getAuthId(), false); User user; boolean newUser=false; From 7be944a83eac6fa5fe56a04831cde1dd3b8e1d3e Mon Sep 17 00:00:00 2001 From: yujiyea <54650556+yujiyea@users.noreply.github.com> Date: Mon, 20 May 2024 22:23:06 +0900 Subject: [PATCH 07/10] =?UTF-8?q?fix:=20=EB=94=94=ED=8F=B4=ED=8A=B8=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=ED=85=9C=EC=9C=BC=EB=A1=9C=20=EB=B0=94?= =?UTF-8?q?=EA=BF=80=20=EA=B2=BD=EC=9A=B0,=20=EC=95=84=EC=9D=B4=ED=85=9C?= =?UTF-8?q?=20=EC=B9=B4=ED=85=8C=EA=B3=A0=EB=A6=AC=EA=B0=80=20=EA=B2=B9?= =?UTF-8?q?=EC=B9=98=EB=8A=94=20=EA=B2=83=EC=9C=BC=EB=A1=9C=20=EB=93=A4?= =?UTF-8?q?=EC=96=B4=EA=B0=80=EC=A7=80=20=EC=95=8A=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/umc/mada/custom/domain/ItemType.java | 4 ++-- src/main/java/com/umc/mada/custom/service/CustomService.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/umc/mada/custom/domain/ItemType.java b/src/main/java/com/umc/mada/custom/domain/ItemType.java index 07b18a3..8534f61 100644 --- a/src/main/java/com/umc/mada/custom/domain/ItemType.java +++ b/src/main/java/com/umc/mada/custom/domain/ItemType.java @@ -6,8 +6,8 @@ public enum ItemType { I1("color"), I2("set"), I3("item"), - I4("background"); - //UNKNOWN("알수없음"); + I4("background"), + I5("default"); private final String itemType; diff --git a/src/main/java/com/umc/mada/custom/service/CustomService.java b/src/main/java/com/umc/mada/custom/service/CustomService.java index be784aa..4ecfd7b 100644 --- a/src/main/java/com/umc/mada/custom/service/CustomService.java +++ b/src/main/java/com/umc/mada/custom/service/CustomService.java @@ -107,7 +107,7 @@ public UserCharacterResponse changeUserItem(User user, List items_id){/ //아이템의 카테고리가 겹치지 않도록 확인 String[] itemCategories = item.getCategory().split(","); for(String category: itemCategories){ - if(itemsCategory.contains(category)){ + if(!category.equals(ItemType.I5.getItemType())&&itemsCategory.contains(category)){ throw new DuplicationItemException(ErrorType.DUPLICATE_ITEM_CATEGORY.getMessage()); } itemsCategory.add(category); From ed1fcc4f735254b2d03d29e2df419d5ad3d7f4e4 Mon Sep 17 00:00:00 2001 From: honeybears Date: Wed, 22 May 2024 17:09:59 +0900 Subject: [PATCH 08/10] Fix : UserController -> PREMINUM Error --- build.gradle | 1 + .../com/umc/mada/custom/repository/HaveItemRepository.java | 5 +++-- .../java/com/umc/mada/user/controller/UserController.java | 1 + src/main/java/com/umc/mada/user/service/UserService.java | 5 +---- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 998eb89..5460260 100644 --- a/build.gradle +++ b/build.gradle @@ -25,6 +25,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // security 설정 유의, 개발 후 적용 // implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-test:2.7.13' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web-services' implementation 'org.springframework.boot:spring-boot-starter-validation' diff --git a/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java b/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java index d4a44d8..1372fa5 100644 --- a/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java +++ b/src/main/java/com/umc/mada/custom/repository/HaveItemRepository.java @@ -2,6 +2,7 @@ import com.umc.mada.custom.domain.CustomItem; import com.umc.mada.custom.domain.HaveItem; +import com.umc.mada.custom.domain.ItemType; import com.umc.mada.user.domain.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -18,8 +19,8 @@ public interface HaveItemRepository extends JpaRepository { List findByUser(User user); List findByUserAndWearing(User user, boolean wearing); boolean existsByCustomItemAndUser(CustomItem customItem, User user); - - Boolean deleteByUserAndCustomItem(User user, CustomItem customItem); + @Query("delete from HaveItem h where h.user = :user and h.customItem.unlockCondition = :unlockCond") + Boolean deleteByUserAndUnlockCond(@Param("user") User user, @Param("unlockCond") CustomItem.ItemUnlockCondition unlockCond); @Query("select h.customItem from HaveItem h where h.user = :user and h.wearing = :wearing") List findCustomItemByUserAndWearing(@Param("user") User user, @Param("wearing") boolean wearing); } diff --git a/src/main/java/com/umc/mada/user/controller/UserController.java b/src/main/java/com/umc/mada/user/controller/UserController.java index e053bf7..c990a42 100644 --- a/src/main/java/com/umc/mada/user/controller/UserController.java +++ b/src/main/java/com/umc/mada/user/controller/UserController.java @@ -154,6 +154,7 @@ public ResponseEntity userRemove (Authentication authentication){ //@Aut /** * 구독 설정 API */ + @Operation(description = "유료 회원 관리") @PatchMapping("/subscribe") public ResponseEntity subscribeToggleSave(Authentication authentication,@RequestBody Map is_subscribe){ // Map map = new HashMap<>(); diff --git a/src/main/java/com/umc/mada/user/service/UserService.java b/src/main/java/com/umc/mada/user/service/UserService.java index 6743ffd..47b071f 100644 --- a/src/main/java/com/umc/mada/user/service/UserService.java +++ b/src/main/java/com/umc/mada/user/service/UserService.java @@ -73,10 +73,7 @@ public Boolean isSubscribe(Authentication authentication, Map is } } else{ - List subscribeCustomItems = customRepository.findByUnlockCondition(CustomItem.ItemUnlockCondition.PREMINUM); - for (CustomItem customItem : subscribeCustomItems){ - haveItemRepository.deleteByUserAndCustomItem(user,customItem); - } + haveItemRepository.deleteByUserAndUnlockCond(user, CustomItem.ItemUnlockCondition.PREMINUM); } } From 2002c711339559df7255834b51a91f2ebb4ce569 Mon Sep 17 00:00:00 2001 From: honeybears Date: Thu, 23 May 2024 23:22:24 +0900 Subject: [PATCH 09/10] Fix : UserController -> PREMINUM Error --- .../controller/TimetableController.java | 45 ++++++--- .../timetable/service/TimetableService.java | 94 +++++++++---------- 2 files changed, 76 insertions(+), 63 deletions(-) diff --git a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java index d9b89f7..1f91e11 100644 --- a/src/main/java/com/umc/mada/timetable/controller/TimetableController.java +++ b/src/main/java/com/umc/mada/timetable/controller/TimetableController.java @@ -1,16 +1,20 @@ package com.umc.mada.timetable.controller; +import com.umc.mada.calendar.domain.Calendar; import com.umc.mada.calendar.repository.CalendarRepository; +import com.umc.mada.timetable.domain.DayOfWeek; import com.umc.mada.timetable.dto.CommentRequestDto; import com.umc.mada.timetable.dto.CommentResponseDto; import com.umc.mada.timetable.dto.TimetableRequestDto; import com.umc.mada.timetable.dto.TimetableResponseDto; import com.umc.mada.timetable.service.TimetableService; +import com.umc.mada.todo.domain.Todo; import com.umc.mada.todo.repository.TodoRepository; import com.umc.mada.user.domain.User; import com.umc.mada.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; @@ -41,7 +45,8 @@ public TimetableController(TodoRepository todoRepository, CalendarRepository cal @PostMapping("/comment") public ResponseEntity> createTimetableComment(Authentication authentication, @RequestBody CommentRequestDto commentRequestDto){ // comment 생성 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); CommentResponseDto newComment = timetableService.createComment(user, commentRequestDto); Map data = new LinkedHashMap<>(); data.put("Comment", newComment); @@ -53,7 +58,8 @@ public ResponseEntity> createTimetableComment(Authentication @PatchMapping("/comment/update/{date}") public ResponseEntity> updateTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, @RequestBody CommentRequestDto commentRequestDto){ // comment 수정 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); CommentResponseDto updatedComment = timetableService.updateComment(user, date, commentRequestDto); Map data = new LinkedHashMap<>(); data.put("Comment", updatedComment); @@ -64,7 +70,8 @@ public ResponseEntity> updateTimetableComment(Authentication @GetMapping("/comment/date/{date}") public ResponseEntity> getUserTimetableComment(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); CommentResponseDto userComment = timetableService.getUserComment(user, date); Map data = new LinkedHashMap<>(); data.put("Comment", userComment); @@ -81,7 +88,8 @@ public ResponseEntity> getUserTimetableComment(Authenticatio @PostMapping("/daily") public ResponseEntity> createDailyTimetable(Authentication authentication, @RequestBody TimetableRequestDto timetableRequestDto){ // 일일 시간표 일정 생성 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); TimetableResponseDto newTimetable = timetableService.createTimetable(user, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("DailyTimetable", newTimetable); @@ -96,7 +104,8 @@ public ResponseEntity> createDailyTimetable(Authentication a @PostMapping("/daily/loadWeekly/{date}") public ResponseEntity> loadDailyTimetableFromWeekly(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ // 주간시간표 불러오기 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); Map map = timetableService.checkAndLoadDailyData(user, date); //result.put("status", 200); //result.put("success", true); @@ -107,7 +116,8 @@ public ResponseEntity> loadDailyTimetableFromWeekly(Authenti @PatchMapping("/daily/update/{scheduleId}") public ResponseEntity> updateDailyTimetable(Authentication authentication, @PathVariable int scheduleId, @RequestBody TimetableRequestDto timetableRequestDto){ // 일일 시간표 일정 수정 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); TimetableResponseDto updatedTimetable = timetableService.updateTimetable(user, scheduleId, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("DailyTimetable", updatedTimetable); @@ -122,7 +132,8 @@ public ResponseEntity> updateDailyTimetable(Authentication a @PatchMapping("/daily/delete/{scheduleId}") public ResponseEntity> deleteDailyTimetable(Authentication authentication, @PathVariable int scheduleId) { // 일일 시간표 일정 삭제 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); timetableService.deleteTimetable(user, scheduleId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -134,7 +145,8 @@ public ResponseEntity> deleteDailyTimetable(Authentication a @GetMapping("/daily/date/{date}") // 일일 시간표 조회 API public ResponseEntity> getUserDailyTimetable(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){ - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); List userTimetables = timetableService.getDailyTimetable(user, date); Map data = new LinkedHashMap<>(); data.put("DailyTimetableList", userTimetables); @@ -153,7 +165,8 @@ public ResponseEntity> getUserDailyTimetable(Authentication @PostMapping("/weekly/create") public ResponseEntity> createWeeklyTimetable(Authentication authentication, @RequestBody TimetableRequestDto timetableRequestDto){ // 주간 시간표 일정 생성 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); TimetableResponseDto newTimetable = timetableService.createTimetable(user, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetable", newTimetable); @@ -168,7 +181,8 @@ public ResponseEntity> createWeeklyTimetable(Authentication @PatchMapping("/weekly/update/{scheduleId}") public ResponseEntity> updateWeeklyTimetable(Authentication authentication, @PathVariable int scheduleId, @RequestBody TimetableRequestDto timetableRequestDto){ // 주간 시간표 일정 수정 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); TimetableResponseDto updatedTimetable = timetableService.updateTimetable(user, scheduleId, timetableRequestDto); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetable", updatedTimetable); @@ -183,7 +197,8 @@ public ResponseEntity> updateWeeklyTimetable(Authentication @PatchMapping("/weekly/delete/{scheduleId}") public ResponseEntity> deleteWeeklyTimetable(Authentication authentication, @PathVariable int scheduleId) { // 주간 시간표 일정 삭제 API - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); timetableService.deleteTimetable(user, scheduleId); Map result = new LinkedHashMap<>(); //result.put("status", 200); @@ -195,7 +210,8 @@ public ResponseEntity> deleteWeeklyTimetable(Authentication @GetMapping("/weekly") // 주간 시간표 일정 조회 API public ResponseEntity> getUserWeeklyTimetable(Authentication authentication){ - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); List userTimetables = timetableService.getWeeklyTimetable(user); Map data = new LinkedHashMap<>(); data.put("WeeklyTimetableList", userTimetables); @@ -211,8 +227,9 @@ public ResponseEntity> getUserWeeklyTimetable(Authentication @GetMapping("search/date/{date}") // 시간표 추가 시, 특정 유저 일정(캘린더)과 투두 조회 API public ResponseEntity> getTodoAndCalendar(Authentication authentication, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) { - User user = userRepository.findByAuthIdAndAccountExpired(authentication.getName(), false).orElseThrow(()-> new RuntimeException("올바른 유저 ID가 아닙니다.")); + Optional userOptional = userRepository.findByAuthId(authentication.getName()); + User user = userOptional.get(); Map map = timetableService.getTodoAndCalendar(user, date); return ResponseEntity.ok().body(map); } -} +} \ No newline at end of file diff --git a/src/main/java/com/umc/mada/timetable/service/TimetableService.java b/src/main/java/com/umc/mada/timetable/service/TimetableService.java index 0857bf1..d83d7e6 100644 --- a/src/main/java/com/umc/mada/timetable/service/TimetableService.java +++ b/src/main/java/com/umc/mada/timetable/service/TimetableService.java @@ -16,7 +16,6 @@ import com.umc.mada.todo.domain.Todo; import com.umc.mada.timetable.domain.DayOfWeek; import com.umc.mada.todo.dto.RepeatTodoResponseDto; -import com.umc.mada.todo.dto.TodoResponseDto; import com.umc.mada.todo.repository.RepeatTodoRepository; import com.umc.mada.todo.repository.TodoRepository; import com.umc.mada.user.domain.User; @@ -50,49 +49,6 @@ public TimetableService(UserRepository userRepository, TimetableRepository timet this.repeatTodoRepository = repeatTodoRepository; } - // comment 생성 로직 - public CommentResponseDto createComment(User user, CommentRequestDto commentRequestDto){ - validateUserId(user); - - Comment comment = new Comment(user, commentRequestDto.getDate(), commentRequestDto.getContent()); - Comment savedComment = commentRepository.save(comment); - - return new CommentResponseDto(savedComment.getId(), savedComment.getDate(), savedComment.getContent()); - } - - @Transactional - // comment 수정 로직 - public CommentResponseDto updateComment (User user, LocalDate date, CommentRequestDto commentRequestDto){ - validateUserId(user); - - Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) - .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); - - // 날짜 변경 처리 - if (commentRequestDto.getDate() != null){ - comment.setDate(commentRequestDto.getDate()); - } - - // 내용 변경 처리 - if (commentRequestDto.getContent() != null){ - comment.setContent(commentRequestDto.getContent()); - } - - Comment updatedComment = commentRepository.save(comment); - return new CommentResponseDto(updatedComment.getId(), updatedComment.getDate(), updatedComment.getContent()); - } - - - // 특정 유저 comment 조회 로직 - public CommentResponseDto readComment(User user, LocalDate date) { - validateUserId(user); - - Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) - .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); - - return new CommentResponseDto(comment.getId(), comment.getDate(), comment.getContent()); - } - // 시간표 일정 생성 로직 public TimetableResponseDto createTimetable(User user, TimetableRequestDto timetableRequestDto){ // 유효성 검사 메서드를 호출하여 해당 ID가 데이터베이스에 존재하는지 확인 @@ -116,7 +72,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ validateUserId(user); List userTodos = todoRepository.findTodosByUserIdAndIsDeletedIsFalse(user); List repeatTodos = repeatTodoRepository.findRepeatTodosByDateIsAndIsDeletedIsFalse(date); - List calendars = calendarRepository.findCalendarDay(user,date); + List calendars = calendarRepository.findAllByUser(user); List> todoList = new ArrayList<>(); for (Todo todo : userTodos) { Map todoMap = new LinkedHashMap<>(); @@ -145,7 +101,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ List> calendarList = new ArrayList<>(); for (Calendar calendar : calendars) { // 시작일과 종료일 사이에 date가 있는 경우만 추가 - + if (!date.isBefore(calendar.getStartDate()) && !date.isAfter(calendar.getEndDate())) { Map calendarMap = new LinkedHashMap<>(); calendarMap.put("CalendarName", calendar.getCalendarName()); calendarMap.put("color", calendar.getColor()); @@ -153,7 +109,7 @@ public Map getTodoAndCalendar (User user, LocalDate date){ calendarMap.put("endTime", calendar.getEndTime()); // 종료 시간 calendarMap.put("d-day", calendar.getDday()); calendarList.add(calendarMap); - + } } Map data = new LinkedHashMap<>(); data.put("calendarList", calendarList); @@ -306,7 +262,48 @@ public Map checkAndLoadDailyData(User user, LocalDate date) { return result; } + // comment 생성 로직 + public CommentResponseDto createComment(User user, CommentRequestDto commentRequestDto){ + validateUserId(user); + + Comment comment = new Comment(user, commentRequestDto.getDate(), commentRequestDto.getContent()); + Comment savedComment = commentRepository.save(comment); + + return new CommentResponseDto(savedComment.getId(), savedComment.getDate(), savedComment.getContent()); + } + + @Transactional + // comment 수정 로직 + public CommentResponseDto updateComment (User user, LocalDate date, CommentRequestDto commentRequestDto){ + validateUserId(user); + Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) + .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); + + // 날짜 변경 처리 + if (commentRequestDto.getDate() != null){ + comment.setDate(commentRequestDto.getDate()); + } + + // 내용 변경 처리 + if (commentRequestDto.getContent() != null){ + comment.setContent(commentRequestDto.getContent()); + } + + Comment updatedComment = commentRepository.save(comment); + return new CommentResponseDto(updatedComment.getId(), updatedComment.getDate(), updatedComment.getContent()); + } + + + // 특정 유저 comment 조회 로직 + public CommentResponseDto getUserComment(User user, LocalDate date) { + validateUserId(user); + + Comment comment = commentRepository.findCommentByUserIdAndDateIs(user, date) + .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND_ERROR")); + + return new CommentResponseDto(comment.getId(), comment.getDate(), comment.getContent()); + } // 투두 이름 유효성 검사 메서드 private void validateTimetableName(String timetableName) { @@ -330,5 +327,4 @@ private boolean isSameSchedule(Timetable dailyEntry, Timetable weeklyEntry) { dailyEntry.getColor().equals(weeklyEntry.getColor()) && Objects.equals(dailyEntry.getMemo(), weeklyEntry.getMemo()); } - -} +} \ No newline at end of file From e3f31c75d5c838443710583541e51a306aac8100 Mon Sep 17 00:00:00 2001 From: honeybears Date: Thu, 23 May 2024 23:27:37 +0900 Subject: [PATCH 10/10] Fix : UserController -> PREMINUM Error --- src/main/java/com/umc/mada/user/service/UserService.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/umc/mada/user/service/UserService.java b/src/main/java/com/umc/mada/user/service/UserService.java index 1a4ce78..d01a944 100644 --- a/src/main/java/com/umc/mada/user/service/UserService.java +++ b/src/main/java/com/umc/mada/user/service/UserService.java @@ -13,6 +13,7 @@ import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; +import javax.transaction.Transactional; import java.util.HashMap; import java.util.List; import java.util.Map;