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

Refactor: 메소드 배치 변경 #164

Merged
merged 2 commits into from
May 18, 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
44 changes: 20 additions & 24 deletions src/main/java/cotato/csquiz/service/KingMemberService.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,13 @@ public List<KingMember> calculateKingMember(Education education) {
.toList();
}

@Transactional
public void saveKingMembers(List<KingMember> kingMembers) {
kingMemberRepository.saveAll(kingMembers);
}

@Transactional
public void saveWinnerIfKingMemberIsOne(Education education) {
List<KingMember> kingMembers = kingMemberRepository.findAllByEducation(education);
if (kingMembers.size() == 1) {
Member findMember = memberRepository.findById(kingMembers.get(0).getMemberId())
.orElseThrow(() -> new EntityNotFoundException("해당 멤버를 찾을 수 없습니다."));
saveWinner(findMember.getId(), education);
}
}

private List<Member> findKingMembersFromEducation(Education education) {
List<Quiz> quizzes = quizRepository.findAllByEducationId(education.getId());
List<Scorer> scorersInEducation = findScorersFromQuizzes(quizzes);

return findKingMembers(scorersInEducation);
}

private List<Scorer> findScorersFromQuizzes(List<Quiz> quizzes) {
return quizzes.stream()
.flatMap(tempQuiz -> scorerRepository.findAllByQuizId(tempQuiz.getId()).stream())
List<Long> quizIds = quizRepository.findAllByEducationId(education.getId()).stream()
.map(Quiz::getId)
.toList();
List<Scorer> scorers = scorerRepository.findAllByQuizIdsInQuery(quizIds);

return findKingMembers(scorers);
}

private List<Member> findKingMembers(List<Scorer> scorers) {
Expand All @@ -82,6 +63,21 @@ private List<Member> findKingMembers(List<Scorer> scorers) {
.toList();
}

@Transactional
public void saveKingMembers(List<KingMember> kingMembers) {
kingMemberRepository.saveAll(kingMembers);
}

@Transactional
public void saveWinnerIfKingMemberIsOne(Education education) {
List<KingMember> kingMembers = kingMemberRepository.findAllByEducation(education);
if (kingMembers.size() == 1) {
Member findMember = memberRepository.findById(kingMembers.get(0).getMemberId())
.orElseThrow(() -> new EntityNotFoundException("해당 멤버를 찾을 수 없습니다."));
saveWinner(findMember.getId(), education);
}
}

@Transactional
public void saveWinnerIfNoWinnerExist(Quiz quiz) {
Education education = quiz.getEducation();
Expand Down
68 changes: 34 additions & 34 deletions src/main/java/cotato/csquiz/service/MyPageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,29 @@ public HallOfFameResponse findHallOfFame(Long generationId, Long memberId) {
return HallOfFameResponse.of(scorerHallOfFame, answerHallOfFame, myHallOfFameInfo);
}

public MyPageMemberInfoResponse findMemberInfo(Long memberId) {
Member member = findMemberById(memberId);
String originPhoneNumber = encryptService.decryptPhoneNumber(member.getPhoneNumber());
private List<HallOfFameInfo> createScorerHallOfFameByGeneration(Generation generation) {
List<Scorer> scorers = findAllScorersByGeneration(generation);

return MyPageMemberInfoResponse.of(member, originPhoneNumber);
Map<Member, Long> memberScoreMap = scorers.stream()
.collect(Collectors.groupingBy(scorer -> memberService.findById(scorer.getMemberId()),
Collectors.counting()));
List<Map.Entry<Member, Long>> topMemberEntry = sortTopMemberEntry(memberScoreMap);

return topMemberEntry.stream()
.map(entry -> HallOfFameInfo.of(entry.getKey(), entry.getValue()))
.toList();
}

private List<HallOfFameInfo> createRecordsHallOfFameInfoByGeneration(Generation generation) {
List<Record> records = findAllCorrectRecordByGeneration(generation);

Map<Member, Long> countByMember = records.stream()
.collect(Collectors.groupingBy(record -> memberService.findById(record.getMemberId()),
Collectors.counting()));
List<Entry<Member, Long>> sorted5MemberEntry = sortTopMemberEntry(countByMember);
return sorted5MemberEntry.stream()
.map(entry -> HallOfFameInfo.of(entry.getKey(), entry.getValue()))
.toList();
}

private MyHallOfFameInfo createMyHallOfFameInfoByGeneration(Member member, Generation generation) {
Expand All @@ -72,11 +90,6 @@ private MyHallOfFameInfo createMyHallOfFameInfoByGeneration(Member member, Gener
return MyHallOfFameInfo.of(member, scorerCount, answerCount);
}

private Member findMemberById(Long id) {
return memberRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("해당 id를 가진 멤버를 찾을 수 없습니다."));
}

private long countMyScorerByGeneration(Member member, Generation generation) {
List<Scorer> myScorers = findAllScorersByGeneration(generation);
return myScorers.stream()
Expand All @@ -92,31 +105,6 @@ private long countMyAnswerByGeneration(Member member, Generation generation) {
.count();
}

private List<HallOfFameInfo> createRecordsHallOfFameInfoByGeneration(Generation generation) {
List<Record> records = findAllCorrectRecordByGeneration(generation);

Map<Member, Long> countByMember = records.stream()
.collect(Collectors.groupingBy(record -> memberService.findById(record.getMemberId()),
Collectors.counting()));
List<Entry<Member, Long>> sorted5MemberEntry = sortTopMemberEntry(countByMember);
return sorted5MemberEntry.stream()
.map(entry -> HallOfFameInfo.of(entry.getKey(), entry.getValue()))
.toList();
}

private List<HallOfFameInfo> createScorerHallOfFameByGeneration(Generation generation) {
List<Scorer> scorers = findAllScorersByGeneration(generation);

Map<Member, Long> memberScoreMap = scorers.stream()
.collect(Collectors.groupingBy(scorer -> memberService.findById(scorer.getMemberId()),
Collectors.counting()));
List<Map.Entry<Member, Long>> topMemberEntry = sortTopMemberEntry(memberScoreMap);

return topMemberEntry.stream()
.map(entry -> HallOfFameInfo.of(entry.getKey(), entry.getValue()))
.toList();
}

private List<Scorer> findAllScorersByGeneration(final Generation generation) {
List<Long> educationIds = educationRepository.findAllByGenerationId(generation.getId()).stream()
.map(Education::getId)
Expand Down Expand Up @@ -146,4 +134,16 @@ private List<Entry<Member, Long>> sortTopMemberEntry(Map<Member, Long> countByMe
.limit(SHOW_PEOPLE_COUNT)
.toList();
}

public MyPageMemberInfoResponse findMemberInfo(Long memberId) {
Member member = findMemberById(memberId);
String originPhoneNumber = encryptService.decryptPhoneNumber(member.getPhoneNumber());

return MyPageMemberInfoResponse.of(member, originPhoneNumber);
}

private Member findMemberById(Long id) {
return memberRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("해당 id를 가진 멤버를 찾을 수 없습니다."));
}
}
146 changes: 71 additions & 75 deletions src/main/java/cotato/csquiz/service/QuizService.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,19 @@ public void createQuizzes(Long educationId, CreateQuizzesRequest request) throws
}
}

private void checkQuizBefore(Education findEducation) {
if (EducationStatus.BEFORE != findEducation.getStatus()) {
throw new AppException(ErrorCode.EDUCATION_STATUS_NOT_BEFORE);
}
}

private void checkQuizNumbersDistinct(final List<Integer> numbers) {
Set<Integer> distinctNumbers = new HashSet<>(numbers);
if (numbers.size() != distinctNumbers.size()) {
throw new AppException(ErrorCode.QUIZ_NUMBER_DUPLICATED);
}
}

private void deleteAllQuizByEducation(Long educationId) {
List<Long> quizIds = quizRepository.findAllByEducationId(educationId).stream()
.map(Quiz::getId)
Expand All @@ -98,31 +111,32 @@ private void deleteAllQuizByEducation(Long educationId) {
quizRepository.deleteAllByQuizIdsInQuery(quizIds);
}

private void checkQuizNumbersDistinct(final List<Integer> numbers) {
Set<Integer> distinctNumbers = new HashSet<>(numbers);
if (numbers.size() != distinctNumbers.size()) {
throw new AppException(ErrorCode.QUIZ_NUMBER_DUPLICATED);
private void createShortQuiz(Education findEducation, CreateShortQuizRequest request)
throws ImageException {
String imageUrl = null;
if (request.getImage() != null && !request.getImage().isEmpty()) {
imageUrl = s3Uploader.uploadFiles(request.getImage(), QUIZ_BUCKET_DIRECTORY);
}
}

@Transactional
public List<QuizResultInfo> createQuizResults(Long educationId) {
List<Quiz> quizzes = findQuizzesByEducationId(educationId);
ShortQuiz createdShortQuiz = ShortQuiz.builder()
.education(findEducation)
.question(request.getQuestion())
.number(request.getNumber())
.photoUrl(imageUrl)
.appearSecond(generateRandomTime())
.build();
log.info("주관식 문제 생성 완료: 사진 url {}", imageUrl);
quizRepository.save(createdShortQuiz);

return quizzes.stream()
.map(this::createQuizResultInfo)
List<ShortAnswer> shortAnswers = request.getShortAnswers().stream()
.map(CreateShortAnswerRequest::getAnswer)
.map(String::toLowerCase)
.map(String::trim)
.map(answer -> ShortAnswer.of(answer, createdShortQuiz))
.toList();
}

private QuizResultInfo createQuizResultInfo(Quiz quiz) {
Optional<Scorer> mayBeScorer = scorerRepository.findByQuizId(quiz.getId());

if (mayBeScorer.isPresent()) {
Member member = memberService.findById(mayBeScorer.get().getMemberId());
shortAnswerRepository.saveAll(shortAnswers);

return QuizResultInfo.of(quiz, member, memberService.findBackFourNumber(member));
}
return QuizResultInfo.noScorer(quiz);
log.info("주관식 정답 생성 완료: {}개", shortAnswers.size());
}

private void createMultipleQuiz(Education findEducation, CreateMultipleQuizRequest request)
Expand Down Expand Up @@ -160,42 +174,29 @@ private void validateChoiceNumbers(final List<Integer> choiceNumbers) {
}
}

private void createShortQuiz(Education findEducation, CreateShortQuizRequest request)
throws ImageException {
String imageUrl = null;
if (request.getImage() != null && !request.getImage().isEmpty()) {
imageUrl = s3Uploader.uploadFiles(request.getImage(), QUIZ_BUCKET_DIRECTORY);
}

ShortQuiz createdShortQuiz = ShortQuiz.builder()
.education(findEducation)
.question(request.getQuestion())
.number(request.getNumber())
.photoUrl(imageUrl)
.appearSecond(generateRandomTime())
.build();
log.info("주관식 문제 생성 완료: 사진 url {}", imageUrl);
quizRepository.save(createdShortQuiz);
@Transactional
public List<QuizResultInfo> createQuizResults(Long educationId) {
List<Quiz> quizzes = quizRepository.findAllByEducationId(educationId);

List<ShortAnswer> shortAnswers = request.getShortAnswers().stream()
.map(CreateShortAnswerRequest::getAnswer)
.map(String::toLowerCase)
.map(String::trim)
.map(answer -> ShortAnswer.of(answer, createdShortQuiz))
return quizzes.stream()
.map(this::createQuizResultInfo)
.toList();
shortAnswerRepository.saveAll(shortAnswers);

log.info("주관식 정답 생성 완료: {}개", shortAnswers.size());
}

private int generateRandomTime() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
return random.nextInt(QuizService.RANDOM_DELAY_TIME_BOUNDARY);
private QuizResultInfo createQuizResultInfo(Quiz quiz) {
Optional<Scorer> mayBeScorer = scorerRepository.findByQuizId(quiz.getId());

if (mayBeScorer.isPresent()) {
Member member = memberService.findById(mayBeScorer.get().getMemberId());

return QuizResultInfo.of(quiz, member, memberService.findBackFourNumber(member));
}
return QuizResultInfo.noScorer(quiz);
}

@Transactional
public AllQuizzesResponse findAllQuizzesForEducationTeam(Long educationId) {
List<Quiz> quizzes = findQuizzesByEducationId(educationId);
List<Quiz> quizzes = quizRepository.findAllByEducationId(educationId);

List<MultipleQuizResponse> multiples = quizzes.stream()
.filter(quiz -> quiz instanceof MultipleQuiz)
Expand All @@ -212,15 +213,11 @@ public AllQuizzesResponse findAllQuizzesForEducationTeam(Long educationId) {
.build();
}

@Transactional
public AllQuizzesInCsQuizResponse findAllQuizzesForAdminCsQuiz(Long educationId) {
List<Quiz> quizzes = findQuizzesByEducationId(educationId);

List<CsAdminQuizResponse> responses = quizzes.stream()
.map(CsAdminQuizResponse::from)
private MultipleQuizResponse toMultipleQuizResponse(Quiz quiz) {
List<ChoiceResponse> choiceResponses = choiceRepository.findAllByMultipleQuiz((MultipleQuiz) quiz).stream()
.map(ChoiceResponse::forEducation)
.toList();

return AllQuizzesInCsQuizResponse.from(responses);
return MultipleQuizResponse.from(quiz, choiceResponses);
}

private ShortQuizResponse toShortQuizResponse(Quiz quiz) {
Expand All @@ -231,11 +228,15 @@ private ShortQuizResponse toShortQuizResponse(Quiz quiz) {
return ShortQuizResponse.from(quiz, shortAnswerResponses);
}

private MultipleQuizResponse toMultipleQuizResponse(Quiz quiz) {
List<ChoiceResponse> choiceResponses = choiceRepository.findAllByMultipleQuiz((MultipleQuiz) quiz).stream()
.map(ChoiceResponse::forEducation)
@Transactional
public AllQuizzesInCsQuizResponse findAllQuizzesForAdminCsQuiz(Long educationId) {
List<Quiz> quizzes = quizRepository.findAllByEducationId(educationId);

List<CsAdminQuizResponse> responses = quizzes.stream()
.map(CsAdminQuizResponse::from)
.toList();
return MultipleQuizResponse.from(quiz, choiceResponses);

return AllQuizzesInCsQuizResponse.from(responses);
}

@Transactional
Expand Down Expand Up @@ -269,6 +270,13 @@ private List<String> getAnswerList(Quiz quiz) {
return getMultipleQuizAnswer(quiz);
}

private List<String> getShortQuizAnswer(Quiz quiz) {
List<ShortAnswer> shortAnswers = shortAnswerRepository.findAllByShortQuiz((ShortQuiz) quiz);
return shortAnswers.stream()
.map(ShortAnswer::getContent)
.toList();
}

private List<String> getMultipleQuizAnswer(Quiz quiz) {
List<Choice> choices = choiceRepository.findAllByMultipleQuiz((MultipleQuiz) quiz);
return choices.stream()
Expand All @@ -277,13 +285,6 @@ private List<String> getMultipleQuizAnswer(Quiz quiz) {
.toList();
}

private List<String> getShortQuizAnswer(Quiz quiz) {
List<ShortAnswer> shortAnswers = shortAnswerRepository.findAllByShortQuiz((ShortQuiz) quiz);
return shortAnswers.stream()
.map(ShortAnswer::getContent)
.toList();
}

@Transactional
public void addAdditionalAnswer(AddAdditionalAnswerRequest request) {
Quiz quiz = findQuizById(request.quizId());
Expand Down Expand Up @@ -328,18 +329,13 @@ private Quiz findQuizById(Long quizId) {
.orElseThrow(() -> new EntityNotFoundException("해당 퀴즈를 찾을 수 없습니다."));
}

private List<Quiz> findQuizzesByEducationId(Long educationId) {
return quizRepository.findAllByEducationId(educationId);
}

private Education findEducationById(Long educationId) {
return educationRepository.findById(educationId)
.orElseThrow(() -> new EntityNotFoundException("해당 교육 id:" + educationId + " 찾다가 에러 발생했습니다."));
}

private void checkQuizBefore(Education findEducation) {
if (EducationStatus.BEFORE != findEducation.getStatus()) {
throw new AppException(ErrorCode.EDUCATION_STATUS_NOT_BEFORE);
}
private int generateRandomTime() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
return random.nextInt(QuizService.RANDOM_DELAY_TIME_BOUNDARY);
}
}
Loading
Loading