Skip to content

Commit

Permalink
Merge pull request #39 from Likelion-YeungNam-Univ/feat/#32—challenge…
Browse files Browse the repository at this point in the history
…-participant

챌린지 count 및 ranking 수정
  • Loading branch information
jjjjjinseo authored Jul 31, 2024
2 parents 4dfdea6 + abb7e11 commit 0dc0163
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ public class ChallengeParticipantController {

@GetMapping("/today-challenges") // 현재 로그인한 유저의 챌린지 참가 정보 조회
public ResponseEntity<List<ChallengeParticipantDTO>> getMyChallenges(HttpServletRequest request) {

// JWT 토큰에서 사용자 ID 추출
String token = jwtUtil.resolveToken(request);
Long userId = jwtUtil.getUserId(token.substring(7));
Long userId = jwtUtil.getUserId(token.substring(7)); // "Bearer "를 제외한 부분

// 사용자 ID를 이용하여 챌린지 참가 정보 조회
List<ChallengeParticipantDTO> challengeParticipants = challengeParticipantService.getUserChallenges(userId);

// 조회된 챌린지 참가 정보를 응답으로 반환
return ResponseEntity.ok(challengeParticipants);
}

Expand Down Expand Up @@ -78,6 +81,4 @@ public ResponseEntity<List<ChallengeRankingDto>> getChallengeRankings(HttpServle
return ResponseEntity.ok(rankings);
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class ChallengeParticipantDTO {
private String challengeContent;
private boolean isCompleted;
private LocalDate challengeCompletedDate;
private Long successCount; // 친구들의 성공 카운트 추가

public static ChallengeParticipantDTO fromEntity(ChallengeParticipant challengeParticipant) {
return ChallengeParticipantDTO.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.example.beginnerfitbe.challengeparticipant.repository;

import com.example.beginnerfitbe.challengeparticipant.domain.ChallengeParticipant;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
Expand All @@ -17,4 +19,9 @@ public interface ChallengeParticipantRepository extends JpaRepository<ChallengeP
long countByUserIdAndIsCompletedTrueAndChallengeCompletedDate(Long userId, LocalDate date);
boolean existsByChallengeCompletedDate(LocalDate date);

// 친구들의 성공 카운트를 위한 메소드 추가
@Query("SELECT COUNT(cp) FROM ChallengeParticipant cp WHERE cp.challenge.challengeId = :challengeId AND cp.user.id IN :userIds AND cp.isCompleted = true")
long countByChallengeIdAndUserIdIn(@Param("challengeId") Long challengeId, @Param("userIds") List<Long> userIds);


}
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,78 @@ public class ChallengeParticipantService {
@Transactional(readOnly = true)
public List<ChallengeParticipantDTO> getUserChallenges(Long userId) {


// 현재 날짜
LocalDate currentDate = LocalDate.now();

// userId와 현재 날짜로 ChallengeParticipant 리스트 반환
List<ChallengeParticipant> participants = challengeParticipantRepository.findByUserIdAndChallengeCompletedDate(userId, currentDate);

// DTO로 변환하여 반환
return participants.stream()
.map(ChallengeParticipantDTO::fromEntity)
List<Friend> acceptedFriendRequests = friendRepository.findByReceiverIdAndIsAcceptedTrue(userId);
List<Long> receiverIds = friendRepository.findReceiverIdsBySenderId(userId);
List<User> receivers = userRepository.findAllById(receiverIds);

List<OtherUserDto> acceptedRequestsDtos = acceptedFriendRequests.stream()
.map(friend -> {
User sender = friend.getSender();
return new OtherUserDto(
sender.getId(),
sender.getEmail(),
sender.getName(),
sender.getHeight(),
sender.getWeight(),
sender.getTargetWeight(),
sender.getDate(),
sender.getTargetDate(),
sender.getExerciseTime(),
sender.getExerciseGoals(),
sender.getConcernedAreas(),
sender.getExerciseIntensity(),
sender.getProfileUrl()
);
})
.collect(Collectors.toList());

for (User receiver : receivers) {
acceptedRequestsDtos.add(new OtherUserDto(
receiver.getId(),
receiver.getEmail(),
receiver.getName(),
receiver.getHeight(),
receiver.getWeight(),
receiver.getTargetWeight(),
receiver.getDate(),
receiver.getTargetDate(),
receiver.getExerciseTime(),
receiver.getExerciseGoals(),
receiver.getConcernedAreas(),
receiver.getExerciseIntensity(),
receiver.getProfileUrl()
));
}

List<Long> friendIds = acceptedRequestsDtos.stream()
.map(OtherUserDto::getId)
.collect(Collectors.toList());

// ID 리스트 출력
System.out.println("Friend IDs: " + friendIds);

// 친구들의 성공 카운트를 위한 결과 리스트
List<ChallengeParticipantDTO> challengeParticipantDTOs = new ArrayList<>();

for (ChallengeParticipant participant : participants) {
Long challengeId = participant.getChallenge().getChallengeId();

// 해당 챌린지에 대해 친구들의 성공 카운트
long successCount = challengeParticipantRepository.countByChallengeIdAndUserIdIn(challengeId, friendIds);

// DTO 변환 후 성공 카운트 설정
ChallengeParticipantDTO dto = ChallengeParticipantDTO.fromEntity(participant);
dto.setSuccessCount(successCount); // 성공 카운트 추가
challengeParticipantDTOs.add(dto);
}

return challengeParticipantDTOs;
}

public void completeChallenge(Long userId, Long challengeId) {
Expand Down Expand Up @@ -155,12 +216,6 @@ public List<ChallengeRankingDto> getChallengeRankings(Long userId) {
));
}

// 랭크 매기기
rankings.sort((r1, r2) -> Integer.compare(r2.getCompletedCount(), r1.getCompletedCount()));
for (int i = 0; i < rankings.size(); i++) {
rankings.get(i).setRank(i + 1); // 순위는 1부터 시작
}

// 로그인한 사용자의 완료된 챌린지 수를 랭크에 포함
rankings.add(new ChallengeRankingDto(
userId,
Expand All @@ -170,12 +225,23 @@ public List<ChallengeRankingDto> getChallengeRankings(Long userId) {
0 // 초기 랭크는 0으로 설정
));

// 전체 리스트 다시 정렬
// 랭크 매기기
rankings.sort((r1, r2) -> Integer.compare(r2.getCompletedCount(), r1.getCompletedCount()));

int rank = 1; // 현재 랭크
for (int i = 0; i < rankings.size(); i++) {
rankings.get(i).setRank(i + 1);
// 첫 번째 사용자이거나 이전 사용자와 완료된 수가 다른 경우
if (i == 0 || rankings.get(i).getCompletedCount() != rankings.get(i - 1).getCompletedCount()) {
rankings.get(i).setRank(rank); // 현재 랭크 부여
rank++; // 다음 랭크로 증가
} else {
// 이전 사용자와 완료된 수가 같으면 같은 랭크 부여
rankings.get(i).setRank(rank - 1); // 이전 랭크 유지
}
}

return rankings;
}


}

0 comments on commit 0dc0163

Please sign in to comment.