Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ [Feat] 피드 반환 수정 #46

Merged
merged 2 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,22 @@ public ResponseEntity<List<GoalDetailResponseDto>> getTodayFeedGoals(HttpSession
@Operation(summary = "단일 목표 상세 조회", description = "단일 목표와 그에 달린 모든 댓글을 조회합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "목표 상세 조회 성공"),
@ApiResponse(responseCode = "401", description = "인증되지 않은 사용자"),
@ApiResponse(responseCode = "404", description = "목표를 찾을 수 없음")
})
@GetMapping("/{goalId}")
public ResponseEntity<GoalDetailResponseDto> getGoalDetailsWithComments(@PathVariable("goalId") Long goalId) {
Optional<GoalDetailResponseDto> goalDetails = goalService.getGoalDetailsWithComments(goalId);
public ResponseEntity<GoalDetailResponseDto> getGoalDetailsWithComments(
@PathVariable("goalId") Long goalId,
HttpSession session) {

Long userId = (Long) session.getAttribute("userId");
if (userId == null) {
return ResponseEntity.status(401).build();
}

Optional<GoalDetailResponseDto> goalDetails = goalService.getGoalDetailsWithComments(goalId, userId);
return goalDetails.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@ public ResponseEntity<GoalDetailResponseDto> getGoalById(@PathVariable("goalId")
if (userId == null) {
return ResponseEntity.status(401).build();
}
Optional<GoalDetailResponseDto> goalDetail = goalService.getGoalDetailsWithComments(goalId);

// isMine
Optional<GoalDetailResponseDto> goalDetail = goalService.getGoalDetailsWithComments(goalId, userId);
return goalDetail.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}



@Operation(summary = "로그인한 사용자의 목표 생성", description = "로그인한 사용자의 새로운 목표를 생성합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "목표 생성 성공"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ public class GoalCommentResponseDto {
private String content;
private LocalDateTime createdAt;
private int emoji;
private boolean isMine;
}

Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ public class GoalDetailResponseDto {
private String nickname;
private LocalDateTime createdAt;
private boolean completed;
private boolean isMine;
private List<GoalCommentResponseDto> comments;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public interface GoalRepository extends JpaRepository<Goal, Long> {
Optional<Goal> findByGoalId(Long goalId);
Optional<Goal> findByGoalIdAndUser(Long goalId, User user);
List<Goal> findByUserInAndCreatedAtBetween(List<User> users, LocalDateTime start, LocalDateTime end);
List<Goal> findByUserAndCreatedAtBetween(User user, LocalDateTime start, LocalDateTime end);


}

Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,22 @@ public GoalCommentResponseDto addComment(Long goalId, Long userId, GoalCommentRe

questService.updateMissionStatus(userId, MissionType.COMMENTED_ON_FRIEND_GOAL);


return new GoalCommentResponseDto(
comment.getCommentId(),
user.getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji()
comment.getEmoji(),
true // 댓글 작성자는 로그인된 사용자이므로 항상 true
);
}


// 댓글 조회
@Transactional
public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId) {
public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId, Long userId) {
User loggedInUser = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));

return goalRepository.findById(goalId)
.map(goal -> {
List<GoalCommentResponseDto> comments = goal.getComments().stream()
Expand All @@ -71,7 +73,8 @@ public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId) {
comment.getUser().getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji()
comment.getEmoji(),
comment.getUser().equals(loggedInUser) // 댓글 작성자와 로그인된 사용자 비교
))
.collect(Collectors.toList());

Expand All @@ -81,12 +84,12 @@ public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId) {
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
goal.getUser().equals(loggedInUser), // 목표 작성자와 로그인된 사용자 비교
comments
);
});
}


// 댓글 삭제
@Transactional
public void deleteComment(Long commentId, Long userId) {
Expand All @@ -100,3 +103,4 @@ public void deleteComment(Long commentId, Long userId) {
goalCommentRepository.deleteById(commentId);
}
}

122 changes: 67 additions & 55 deletions src/main/java/dongguk/osori/domain/goal/service/GoalService.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,17 @@ public class GoalService {

private final GoalRepository goalRepository;
private final UserRepository userRepository;
private final GoalCommentRepository goalCommentRepository;
private final QuestService questService;

// 로그인된 사용자 가져오기
private User getLoggedInUser(Long userId) {
log.debug("Fetching user with ID: {}", userId); // 디버깅용
return userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
}

// 로그인된 사용자의 모든 목표 조회
public List<GoalResponseDto> getUserGoals(Long userId) {
User user = getLoggedInUser(userId);
log.debug("Goals retrieved: {}", user.getGoals()); // 디버깅용
return user.getGoals().stream()
.map(goal -> new GoalResponseDto(goal.getGoalId(), goal.getContent(), goal.getCreatedAt(), goal.isCompleted()))
.collect(Collectors.toList());
Expand Down Expand Up @@ -93,100 +90,115 @@ public Optional<GoalResponseDto> updateGoalCompletionStatus(Long goalId, GoalCom
// 목표 삭제
@Transactional
public String deleteGoal(Long userId, Long goalId) {
log.debug("Deleting goal ID: {} for user ID: {}", goalId, userId); // 디버깅용
Goal goal = goalRepository.findById(goalId)
.orElseThrow(() -> new RuntimeException("존재하지 않는 목표"));

User user = getLoggedInUser(userId);
log.debug("User found: {}, Goal user: {}", user, goal.getUser()); // 디버깅용

if(!user.equals(goal.getUser())) {
log.warn("User mismatch: {} is not the owner of goal ID: {}", userId, goalId); // 디버깅용
return "잘못된 사용자, 삭제 실패";
}
goalRepository.deleteById(goalId); // Goal에서 목표 삭제
log.debug("Goal deleted successfully: {}", goalId); // 디버깅용
goalRepository.deleteById(goalId);
return "목표 삭제 완료";
}

// 피드에서 오늘 날짜의 팔로우한 사람들의 목표 조회
@Transactional
public List<FeedGoalDto> getTodayFeedGoals(Long userId) {
User loggedInUser = getLoggedInUser(userId); // 로그인된 사용자 가져오기
public List<GoalDetailResponseDto> getTodayFeedGoalsAsDetails(Long userId) {
User loggedInUser = getLoggedInUser(userId); // 로그인된 사용자 정보 로드
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
LocalDateTime endOfDay = startOfDay.plusDays(1);

List<User> followingUsers = loggedInUser.getFollowingUsers(); // 팔로우한 사용자 목록 가져오기

// 오늘 날짜에 생성된 팔로우한 사용자의 목표 조회
return goalRepository.findByUserInAndCreatedAtBetween(followingUsers, startOfDay, endOfDay)
.stream()
.map(goal -> new FeedGoalDto(
goal.getGoalId(),
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
goal.getContent(),
goal.getComments().size()
))
.collect(Collectors.toList());
}
// 1. 자신의 목표 조회
List<Goal> myGoals = goalRepository.findByUserAndCreatedAtBetween(loggedInUser, startOfDay, endOfDay);
List<GoalDetailResponseDto> myGoalsDtos = myGoals.stream()
.map(goal -> {
List<GoalCommentResponseDto> comments = goal.getComments().stream()
.map(comment -> new GoalCommentResponseDto(
comment.getCommentId(),
comment.getUser().getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji(),
comment.getUser().getUserId().equals(userId) // 댓글 작성자와 로그인된 사용자 ID 비교
))
.collect(Collectors.toList());

return new GoalDetailResponseDto(
goal.getGoalId(),
goal.getContent(),
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
true, // 내 목표이므로 항상 true
comments
);
})
.collect(Collectors.toList());

@Transactional
public List<GoalDetailResponseDto> getTodayFeedGoalsAsDetails(Long userId) {
User loggedInUser = getLoggedInUser(userId); // 로그인된 사용자 가져오기
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
LocalDateTime endOfDay = startOfDay.plusDays(1);
// 2. 팔로우한 사용자들의 목표 조회
List<User> followingUsers = loggedInUser.getFollowingUsers();
List<Goal> followingGoals = goalRepository.findByUserInAndCreatedAtBetween(followingUsers, startOfDay, endOfDay);
List<GoalDetailResponseDto> followingGoalsDtos = followingGoals.stream()
.map(goal -> {
List<GoalCommentResponseDto> comments = goal.getComments().stream()
.map(comment -> new GoalCommentResponseDto(
comment.getCommentId(),
comment.getUser().getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji(),
comment.getUser().getUserId().equals(userId) // 댓글 작성자와 로그인된 사용자 ID 비교
))
.collect(Collectors.toList());

List<User> followingUsers = loggedInUser.getFollowingUsers(); // 팔로우한 사용자 목록 가져오기

// 오늘 날짜에 생성된 팔로우한 사용자의 목표 조회
return goalRepository.findByUserInAndCreatedAtBetween(followingUsers, startOfDay, endOfDay)
.stream()
.map(goal -> new GoalDetailResponseDto(
goal.getGoalId(),
goal.getContent(),
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
goal.getComments().stream()
.map(comment -> new GoalCommentResponseDto(
comment.getCommentId(),
comment.getUser().getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji()
))
.collect(Collectors.toList())
))
return new GoalDetailResponseDto(
goal.getGoalId(),
goal.getContent(),
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
false, // 팔로우한 사람의 목표이므로 false
comments
);
})
.collect(Collectors.toList());
}

// 3. 결과 리스트 생성: 자신의 목표를 먼저 추가한 후 팔로우한 사람들의 목표 추가
myGoalsDtos.addAll(followingGoalsDtos);
return myGoalsDtos;
}

// Goal ID를 기준으로 목표 상세 조회 (댓글 포함)
@Transactional
public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId) {
public Optional<GoalDetailResponseDto> getGoalDetailsWithComments(Long goalId, Long userId) {
User loggedInUser = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));

return goalRepository.findById(goalId)
.map(goal -> {
// 댓글 리스트 생성
List<GoalCommentResponseDto> comments = goal.getComments().stream()
.map(comment -> new GoalCommentResponseDto(
comment.getCommentId(),
comment.getUser().getNickname(),
comment.getContent(),
comment.getCreatedAt(),
comment.getEmoji()
comment.getEmoji(),
comment.getUser().getUserId().equals(userId) // 작성자와 로그인된 사용자 비교
))
.collect(Collectors.toList());

// 목표 생성
return new GoalDetailResponseDto(
goal.getGoalId(),
goal.getContent(),
goal.getUser().getNickname(),
goal.getCreatedAt(),
goal.isCompleted(),
goal.getUser().getUserId().equals(userId), // 목표 작성자와 로그인된 사용자 비교
comments
);
});
}

}
Loading