diff --git a/.github/workflows/deploy_dev.yml b/.github/workflows/deploy_dev.yml index f3245f187..8f28feadc 100644 --- a/.github/workflows/deploy_dev.yml +++ b/.github/workflows/deploy_dev.yml @@ -2,7 +2,7 @@ name: Deploy Keeper Development Server on: push: - branches: [develop] + branches: [ develop ] jobs: deploy_development: diff --git a/.github/workflows/deploy_prod.yml b/.github/workflows/deploy_prod.yml index 829868647..c97b3681d 100644 --- a/.github/workflows/deploy_prod.yml +++ b/.github/workflows/deploy_prod.yml @@ -2,7 +2,7 @@ name: Deploy Keeper Production Server on: push: - branches: [master] + branches: [ master ] jobs: deploy_production: diff --git a/README.md b/README.md index 605ad6b0a..dcf37fa4b 100644 --- a/README.md +++ b/README.md @@ -17,15 +17,15 @@ KEEPER 홈페이지 백엔드 서버입니다. # 📝 링크 -| 이름 | 링크 | -|----------------------|------------------------------------------------------------------------------------------------------------------| -| 운영 홈페이지 | [keeper.or.kr](https://keeper.or.kr) | -| 개발 홈페이지 | [dev.keeper.or.kr](https://dev.keeper.or.kr) | -| API 문서 | [api.keeper.or.kr/docs/keeper.html](https://api.keeper.or.kr/docs/keeper.html) | -| Notion | [Notion Link](https://chip-force-ed0.notion.site/KEEPER-0dbccc3c2374465b8be715cd9d872103?pvs=4) | -| 프론트 Repository | [Homepage-Front-R2](https://github.com/KEEPER31337/Homepage-Front-R2) | -| 인프라 코드 Repository | [Homepage-Infrastructure](https://github.com/KEEPER31337/Homepage-Infrastructure) | -| 데이터베이스 코드 Repository | [Homepage-Database](https://github.com/KEEPER31337/Homepage-Database) | +| 이름 | 링크 | +|----------------------|-------------------------------------------------------------------------------------------------| +| 운영 홈페이지 | [keeper.or.kr](https://keeper.or.kr) | +| 개발 홈페이지 | [dev.keeper.or.kr](https://dev.keeper.or.kr) | +| API 문서 | [api.keeper.or.kr/docs/keeper.html](https://api.keeper.or.kr/docs/keeper.html) | +| Notion | [Notion Link](https://chip-force-ed0.notion.site/KEEPER-0dbccc3c2374465b8be715cd9d872103?pvs=4) | +| 프론트 Repository | [Homepage-Front-R2](https://github.com/KEEPER31337/Homepage-Front-R2) | +| 인프라 코드 Repository | [Homepage-Infrastructure](https://github.com/KEEPER31337/Homepage-Infrastructure) | +| 데이터베이스 코드 Repository | [Homepage-Database](https://github.com/KEEPER31337/Homepage-Database) | # ✨ 도메인 diff --git a/images/logo_neon.svg b/images/logo_neon.svg index 547b56b67..c754cfe05 100644 --- a/images/logo_neon.svg +++ b/images/logo_neon.svg @@ -1,36 +1,37 @@ - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/intellij-java-google-style.xml b/intellij-java-google-style.xml index f3a6743ef..cf29951cf 100644 --- a/intellij-java-google-style.xml +++ b/intellij-java-google-style.xml @@ -2,222 +2,222 @@ - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + - + - - + + - - - + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + - - + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - + + - + - - - + + + - + - - - + + + - - - - + + + + - - - + + + - - + + - - + + - - + + - - - + + + @@ -226,7 +226,7 @@ xmlns:android - + ^$ @@ -237,7 +237,7 @@ xmlns:.* - + ^$ @@ -249,7 +249,7 @@ .*:id - + http://schemas.android.com/apk/res/android @@ -260,7 +260,7 @@ style - + ^$ @@ -271,7 +271,7 @@ .* - + ^$ @@ -283,7 +283,7 @@ .*:.*Style - + http://schemas.android.com/apk/res/android @@ -295,7 +295,7 @@ .*:layout_width - + http://schemas.android.com/apk/res/android @@ -306,7 +306,7 @@ .*:layout_height - + http://schemas.android.com/apk/res/android @@ -317,7 +317,7 @@ .*:layout_weight - + http://schemas.android.com/apk/res/android @@ -328,7 +328,7 @@ .*:layout_margin - + http://schemas.android.com/apk/res/android @@ -339,7 +339,7 @@ .*:layout_marginTop - + http://schemas.android.com/apk/res/android @@ -350,7 +350,7 @@ .*:layout_marginBottom - + http://schemas.android.com/apk/res/android @@ -361,7 +361,7 @@ .*:layout_marginStart - + http://schemas.android.com/apk/res/android @@ -372,7 +372,7 @@ .*:layout_marginEnd - + http://schemas.android.com/apk/res/android @@ -383,7 +383,7 @@ .*:layout_marginLeft - + http://schemas.android.com/apk/res/android @@ -394,7 +394,7 @@ .*:layout_marginRight - + http://schemas.android.com/apk/res/android @@ -405,7 +405,7 @@ .*:layout_.* - + http://schemas.android.com/apk/res/android @@ -417,7 +417,7 @@ .*:padding - + http://schemas.android.com/apk/res/android @@ -428,7 +428,7 @@ .*:paddingTop - + http://schemas.android.com/apk/res/android @@ -439,7 +439,7 @@ .*:paddingBottom - + http://schemas.android.com/apk/res/android @@ -450,7 +450,7 @@ .*:paddingStart - + http://schemas.android.com/apk/res/android @@ -461,7 +461,7 @@ .*:paddingEnd - + http://schemas.android.com/apk/res/android @@ -472,7 +472,7 @@ .*:paddingLeft - + http://schemas.android.com/apk/res/android @@ -483,7 +483,7 @@ .*:paddingRight - + http://schemas.android.com/apk/res/android @@ -537,62 +537,62 @@ - - - - - - - - - - - - + + + + + + + + + + + + - - - + + + - - - - - - - - - + + + + + + + + + - - - - - - + + + + + + - - + + - - - - - - - - - - - + + + + + + + + + + + - - + + diff --git a/src/main/java/com/keeper/homepage/domain/about/api/StaticWriteController.java b/src/main/java/com/keeper/homepage/domain/about/api/StaticWriteController.java index de70ff84d..11019022d 100644 --- a/src/main/java/com/keeper/homepage/domain/about/api/StaticWriteController.java +++ b/src/main/java/com/keeper/homepage/domain/about/api/StaticWriteController.java @@ -27,7 +27,8 @@ public ResponseEntity getAllTypes() { } @GetMapping("/titles/types/{type}") - public ResponseEntity getTitleByType(@PathVariable @NotNull String type) { + public ResponseEntity getTitleByType( + @PathVariable @NotNull String type) { StaticWriteTitleResponse response = staticWriteService.getTitleByType(type); return ResponseEntity.status(HttpStatus.OK) .body(response); diff --git a/src/main/java/com/keeper/homepage/domain/about/application/StaticWriteService.java b/src/main/java/com/keeper/homepage/domain/about/application/StaticWriteService.java index 06858cc82..34dc6c3a8 100644 --- a/src/main/java/com/keeper/homepage/domain/about/application/StaticWriteService.java +++ b/src/main/java/com/keeper/homepage/domain/about/application/StaticWriteService.java @@ -24,7 +24,8 @@ public StaticWriteTitleTypeResponse getAllTypes() { } public StaticWriteTitleResponse getTitleByType(String type) { - StaticWriteTitle staticWriteTitle = staticWriteTitleRepository.findByStaticWriteTitleType(StaticWriteTitleType.fromCode(type)) + StaticWriteTitle staticWriteTitle = staticWriteTitleRepository.findByStaticWriteTitleType( + StaticWriteTitleType.fromCode(type)) .orElseThrow(() -> new BusinessException(type, "type", TITLE_TYPE_NOT_FOUND)); return StaticWriteTitleResponse.from(staticWriteTitle); } diff --git a/src/main/java/com/keeper/homepage/domain/about/dto/response/StaticWriteSubTitleImageResponse.java b/src/main/java/com/keeper/homepage/domain/about/dto/response/StaticWriteSubTitleImageResponse.java index 9aa9ad3eb..806dcbb99 100644 --- a/src/main/java/com/keeper/homepage/domain/about/dto/response/StaticWriteSubTitleImageResponse.java +++ b/src/main/java/com/keeper/homepage/domain/about/dto/response/StaticWriteSubTitleImageResponse.java @@ -25,7 +25,8 @@ public static StaticWriteSubTitleImageResponse from(StaticWriteSubtitleImage sub return StaticWriteSubTitleImageResponse.builder() .id(subtitleImage.getId()) .subtitle(subtitleImage.getSubtitle()) - .thumbnailPath(subtitleImage.getThumbnail() != null ? subtitleImage.getThumbnail().getPath() : null) + .thumbnailPath( + subtitleImage.getThumbnail() != null ? subtitleImage.getThumbnail().getPath() : null) .displayOrder(subtitleImage.getDisplayOrder()) .staticWriteContents(subtitleImage.getStaticWriteContents().stream() .map(StaticWriteContentResponse::from) diff --git a/src/main/java/com/keeper/homepage/domain/attendance/application/AttendanceService.java b/src/main/java/com/keeper/homepage/domain/attendance/application/AttendanceService.java index 0db3450c8..648f7d6cd 100644 --- a/src/main/java/com/keeper/homepage/domain/attendance/application/AttendanceService.java +++ b/src/main/java/com/keeper/homepage/domain/attendance/application/AttendanceService.java @@ -84,7 +84,8 @@ private int getRankPoint(int rank) { } private int getContinuousDay(Member member, LocalDate now) { - Attendance yesterdayAttendance = attendanceRepository.findByMemberAndDate(member, now.minusDays(1)) + Attendance yesterdayAttendance = attendanceRepository.findByMemberAndDate(member, + now.minusDays(1)) .orElse(null); if (yesterdayAttendance == null) { return 1; diff --git a/src/main/java/com/keeper/homepage/domain/attendance/dao/AttendanceRepository.java b/src/main/java/com/keeper/homepage/domain/attendance/dao/AttendanceRepository.java index 30935e5dd..fc511e8e4 100644 --- a/src/main/java/com/keeper/homepage/domain/attendance/dao/AttendanceRepository.java +++ b/src/main/java/com/keeper/homepage/domain/attendance/dao/AttendanceRepository.java @@ -26,6 +26,7 @@ public interface AttendanceRepository extends JpaRepository { @Query("SELECT a FROM Attendance a " + "WHERE a.member = :member " + "AND a.date >= :localDate") - List findAllRecent(@Param("member") Member member, @Param("localDate") LocalDate localDate); + List findAllRecent(@Param("member") Member member, + @Param("localDate") LocalDate localDate); } diff --git a/src/main/java/com/keeper/homepage/domain/auth/api/SignInController.java b/src/main/java/com/keeper/homepage/domain/auth/api/SignInController.java index 894755b95..bb6f93f8a 100644 --- a/src/main/java/com/keeper/homepage/domain/auth/api/SignInController.java +++ b/src/main/java/com/keeper/homepage/domain/auth/api/SignInController.java @@ -50,14 +50,17 @@ public ResponseEntity findLoginId(@RequestBody @Email FindLoginIdRequest r @PostMapping("/send-password-change-auth-code") public ResponseEntity sendPasswordChangeAuthCode( @RequestBody @Valid MemberIdAndEmailRequest request) { - int expiredSeconds = signInService.sendPasswordChangeAuthCode(EmailAddress.from(request.getEmail()), + int expiredSeconds = signInService.sendPasswordChangeAuthCode( + EmailAddress.from(request.getEmail()), LoginId.from(request.getLoginId())); return ResponseEntity.ok(EmailAuthResponse.from(expiredSeconds)); } @GetMapping("/check-auth-code") - public ResponseEntity checkAuthCode(String email, String loginId, String authCode) { - boolean isAuth = signInService.isAuthenticated(EmailAddress.from(email), LoginId.from(loginId), authCode); + public ResponseEntity checkAuthCode(String email, String loginId, + String authCode) { + boolean isAuth = signInService.isAuthenticated(EmailAddress.from(email), LoginId.from(loginId), + authCode); return ResponseEntity.ok(CheckAuthCodeResponse.from(isAuth)); } @@ -65,7 +68,8 @@ public ResponseEntity checkAuthCode(String email, String public ResponseEntity changePassword( @RequestBody @Valid ChangePasswordForMissingRequest request) { signInService.changePassword(request.getAuthCode(), - LoginId.from(request.getLoginId()), EmailAddress.from(request.getEmail()), request.getRawPassword()); + LoginId.from(request.getLoginId()), EmailAddress.from(request.getEmail()), + request.getRawPassword()); return ResponseEntity.noContent().build(); } } diff --git a/src/main/java/com/keeper/homepage/domain/auth/application/AuthCookieService.java b/src/main/java/com/keeper/homepage/domain/auth/application/AuthCookieService.java index e71f9286a..3e0000f5c 100644 --- a/src/main/java/com/keeper/homepage/domain/auth/application/AuthCookieService.java +++ b/src/main/java/com/keeper/homepage/domain/auth/application/AuthCookieService.java @@ -18,17 +18,20 @@ public class AuthCookieService { private final JwtTokenProvider jwtTokenProvider; private final RedisUtil redisUtil; - public void setNewCookieInResponse(String authId, String[] roles, String userAgent, HttpServletResponse response) { + public void setNewCookieInResponse(String authId, String[] roles, String userAgent, + HttpServletResponse response) { String newRefreshToken = jwtTokenProvider.createAccessToken(REFRESH_TOKEN, authId, roles); setTokenInCookie(response, newRefreshToken, (int) REFRESH_TOKEN.getExpiredMillis() / 1000, REFRESH_TOKEN.getTokenName()); String newAccessToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, authId, roles); setTokenInCookie(response, newAccessToken, (int) REFRESH_TOKEN.getExpiredMillis() / 1000, ACCESS_TOKEN.getTokenName()); - redisUtil.setDataExpire(JwtTokenProvider.getRefreshTokenKeyForRedis(authId, userAgent), newRefreshToken, REFRESH_TOKEN.getExpiredMillis()); + redisUtil.setDataExpire(JwtTokenProvider.getRefreshTokenKeyForRedis(authId, userAgent), + newRefreshToken, REFRESH_TOKEN.getExpiredMillis()); } - private void setTokenInCookie(HttpServletResponse httpResponse, String token, int expiredSeconds, String cookieName) { + private void setTokenInCookie(HttpServletResponse httpResponse, String token, int expiredSeconds, + String cookieName) { ResponseCookie cookie = ResponseCookie.from(cookieName, token) .path("/") .sameSite("None") diff --git a/src/main/java/com/keeper/homepage/domain/auth/application/SignInService.java b/src/main/java/com/keeper/homepage/domain/auth/application/SignInService.java index d6acea979..7def70e27 100644 --- a/src/main/java/com/keeper/homepage/domain/auth/application/SignInService.java +++ b/src/main/java/com/keeper/homepage/domain/auth/application/SignInService.java @@ -73,8 +73,10 @@ public int sendPasswordChangeAuthCode(EmailAddress email, LoginId loginId) { .orElseThrow(() -> new BusinessException(email.get(), "email", ErrorCode.MEMBER_NOT_FOUND)); String authCode = generateRandomAuthCode(); - redisUtil.setDataExpire(PASSWORD_AUTH_CODE_KEY + member.getId(), authCode, AUTH_CODE_EXPIRE_MILLIS); - mailUtil.sendMail(List.of(email.get()), "KEEPER 비밀번호 변경 인증 코드입니다.", "회원님의 비밀번호 변경 인증 코드: " + authCode); + redisUtil.setDataExpire(PASSWORD_AUTH_CODE_KEY + member.getId(), authCode, + AUTH_CODE_EXPIRE_MILLIS); + mailUtil.sendMail(List.of(email.get()), "KEEPER 비밀번호 변경 인증 코드입니다.", + "회원님의 비밀번호 변경 인증 코드: " + authCode); return AUTH_CODE_EXPIRE_MILLIS / 1000; } @@ -94,12 +96,14 @@ public boolean isAuthenticated(EmailAddress email, LoginId loginId, String reque Member member = memberRepository.findByProfileEmailAddressAndProfileLoginId(email, loginId) .orElseThrow(() -> new BusinessException(email.get(), "email", ErrorCode.MEMBER_NOT_FOUND)); - Optional data = redisUtil.getData(PASSWORD_AUTH_CODE_KEY + member.getId(), String.class); + Optional data = redisUtil.getData(PASSWORD_AUTH_CODE_KEY + member.getId(), + String.class); return data.map(correctAuthCode -> correctAuthCode.equals(requestAuthCode)).orElse(false); } @Transactional - public void changePassword(String authCode, LoginId loginId, EmailAddress email, String rawPassword) { + public void changePassword(String authCode, LoginId loginId, EmailAddress email, + String rawPassword) { if (!isAuthenticated(email, loginId, authCode)) { throw new BusinessException(authCode, "authCode", ErrorCode.AUTH_CODE_MISMATCH); } diff --git a/src/main/java/com/keeper/homepage/domain/comment/application/CommentService.java b/src/main/java/com/keeper/homepage/domain/comment/application/CommentService.java index c46be8ebe..48d4af4a7 100644 --- a/src/main/java/com/keeper/homepage/domain/comment/application/CommentService.java +++ b/src/main/java/com/keeper/homepage/domain/comment/application/CommentService.java @@ -73,7 +73,8 @@ public CommentListResponse getComments(Member member, Long postId) { List commentResponses = comments.stream() .map(comment -> { if (post.isCategory(익명게시판)) { - return CommentResponse.of(comment, ANONYMOUS_NAME, null, member.isLike(comment), member.isDislike(comment)); + return CommentResponse.of(comment, ANONYMOUS_NAME, null, member.isLike(comment), + member.isDislike(comment)); } return CommentResponse.from(comment, member.isLike(comment), member.isDislike(comment)); }) diff --git a/src/main/java/com/keeper/homepage/domain/comment/dao/CommentRepository.java b/src/main/java/com/keeper/homepage/domain/comment/dao/CommentRepository.java index 7e36e969a..5aed76aee 100644 --- a/src/main/java/com/keeper/homepage/domain/comment/dao/CommentRepository.java +++ b/src/main/java/com/keeper/homepage/domain/comment/dao/CommentRepository.java @@ -13,5 +13,6 @@ public interface CommentRepository extends JpaRepository { @Query("UPDATE Comment c " + "SET c.member = :virtualMember " + "WHERE c.member = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); } diff --git a/src/main/java/com/keeper/homepage/domain/comment/dto/response/CommentResponse.java b/src/main/java/com/keeper/homepage/domain/comment/dto/response/CommentResponse.java index fee45453c..7c474e9d5 100644 --- a/src/main/java/com/keeper/homepage/domain/comment/dto/response/CommentResponse.java +++ b/src/main/java/com/keeper/homepage/domain/comment/dto/response/CommentResponse.java @@ -42,7 +42,8 @@ public static CommentResponse from(Comment comment, boolean isLike, boolean isDi .build(); } - public static CommentResponse of(Comment comment, String writerName, String writerThumbnailPath, boolean isLike, + public static CommentResponse of(Comment comment, String writerName, String writerThumbnailPath, + boolean isLike, boolean isDislike) { return CommentResponse.builder() .commentId(comment.getId()) diff --git a/src/main/java/com/keeper/homepage/domain/ctf/api/CtfContestController.java b/src/main/java/com/keeper/homepage/domain/ctf/api/CtfContestController.java index d260574cc..b3034fb04 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/api/CtfContestController.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/api/CtfContestController.java @@ -49,7 +49,8 @@ public ResponseEntity updateContest( @PathVariable long contestId, @RequestBody @Valid UpdateContestRequest request ) { - ctfContestService.updateContest(contestId, request.getName(), request.getDescription(), request.isJoinable()); + ctfContestService.updateContest(contestId, request.getName(), request.getDescription(), + request.isJoinable()); return ResponseEntity.status(HttpStatus.CREATED) .build(); } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/api/CtfTeamController.java b/src/main/java/com/keeper/homepage/domain/ctf/api/CtfTeamController.java index f95e7719f..4c064f684 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/api/CtfTeamController.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/api/CtfTeamController.java @@ -39,7 +39,8 @@ public ResponseEntity createTeam( @LoginMember Member member, @RequestBody @Valid CreateTeamRequest request ) { - ctfTeamService.createTeam(member, request.getName(), request.getDescription(), request.getContestId()); + ctfTeamService.createTeam(member, request.getName(), request.getDescription(), + request.getContestId()); return ResponseEntity.status(HttpStatus.CREATED) .build(); } @@ -69,7 +70,8 @@ public ResponseEntity> getTeams( @RequestParam(defaultValue = "0") @PositiveOrZero int page, @RequestParam(defaultValue = "10") @PositiveOrZero int size ) { - return ResponseEntity.ok(ctfTeamService.getTeams(contestId, search, PageRequest.of(page, size))); + return ResponseEntity.ok( + ctfTeamService.getTeams(contestId, search, PageRequest.of(page, size))); } @PostMapping("/{teamId}/members/{memberId}") diff --git a/src/main/java/com/keeper/homepage/domain/ctf/application/CtfTeamService.java b/src/main/java/com/keeper/homepage/domain/ctf/application/CtfTeamService.java index 6f6d63872..87e394d9f 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/application/CtfTeamService.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/application/CtfTeamService.java @@ -71,7 +71,8 @@ public CtfTeamDetailResponse getTeam(long teamId) { public Page getTeams(long contestId, String search, Pageable pageable) { CtfContest contest = ctfContestFindService.findJoinableById(contestId); - return ctfTeamRepository.findAllByCtfContestAndNameIgnoreCaseContaining(contest, search, pageable) + return ctfTeamRepository.findAllByCtfContestAndNameIgnoreCaseContaining(contest, search, + pageable) .map(CtfTeamResponse::from); } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/converter/CtfChallengeCategoryTypeConverter.java b/src/main/java/com/keeper/homepage/domain/ctf/converter/CtfChallengeCategoryTypeConverter.java index eb6c3090f..27af78537 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/converter/CtfChallengeCategoryTypeConverter.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/converter/CtfChallengeCategoryTypeConverter.java @@ -7,7 +7,8 @@ @Converter @Slf4j -public class CtfChallengeCategoryTypeConverter implements AttributeConverter { +public class CtfChallengeCategoryTypeConverter implements + AttributeConverter { @Override public String convertToDatabaseColumn(CtfChallengeCategoryType type) { diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/CtfContestRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/CtfContestRepository.java index 96697a9d7..442897678 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/CtfContestRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/CtfContestRepository.java @@ -22,6 +22,7 @@ public interface CtfContestRepository extends JpaRepository { @Query("UPDATE CtfContest c " + "SET c.creator = :virtualMember " + "WHERE c.creator = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasCtfChallengeCategoryRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasCtfChallengeCategoryRepository.java index 2567efdc7..63aaa09a1 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasCtfChallengeCategoryRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasCtfChallengeCategoryRepository.java @@ -3,6 +3,7 @@ import com.keeper.homepage.domain.ctf.entity.challenge.CtfChallengeHasCtfChallengeCategory; import org.springframework.data.jpa.repository.JpaRepository; -public interface CtfChallengeHasCtfChallengeCategoryRepository extends JpaRepository { +public interface CtfChallengeHasCtfChallengeCategoryRepository extends + JpaRepository { } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasFileRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasFileRepository.java index 553dc7455..ed91cbc58 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasFileRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeHasFileRepository.java @@ -4,6 +4,7 @@ import com.keeper.homepage.domain.ctf.entity.challenge.CtfChallengeHasFilePK; import org.springframework.data.jpa.repository.JpaRepository; -public interface CtfChallengeHasFileRepository extends JpaRepository { +public interface CtfChallengeHasFileRepository extends + JpaRepository { } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeRepository.java index fc696b267..38ab1968a 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/challenge/CtfChallengeRepository.java @@ -13,6 +13,7 @@ public interface CtfChallengeRepository extends JpaRepository { +public interface CtfDynamicChallengeInfoRepository extends + JpaRepository { } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamHasMemberRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamHasMemberRepository.java index c18f21757..5f543d8ed 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamHasMemberRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamHasMemberRepository.java @@ -4,6 +4,7 @@ import com.keeper.homepage.domain.ctf.entity.team.CtfTeamHasMemberPK; import org.springframework.data.jpa.repository.JpaRepository; -public interface CtfTeamHasMemberRepository extends JpaRepository { +public interface CtfTeamHasMemberRepository extends + JpaRepository { } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamRepository.java b/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamRepository.java index 1fc16f269..bb33dccee 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamRepository.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/dao/team/CtfTeamRepository.java @@ -15,12 +15,14 @@ public interface CtfTeamRepository extends JpaRepository { Optional findByIdAndIdNot(long teamId, long virtualId); - Page findAllByCtfContestAndNameIgnoreCaseContaining(CtfContest ctfContest, String search, Pageable pageable); + Page findAllByCtfContestAndNameIgnoreCaseContaining(CtfContest ctfContest, String search, + Pageable pageable); @Modifying @Query("UPDATE CtfTeam c " + "SET c.creator = :virtualMember " + "WHERE c.creator = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/entity/CtfSubmitLog.java b/src/main/java/com/keeper/homepage/domain/ctf/entity/CtfSubmitLog.java index 2c7838dcc..05f047e08 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/entity/CtfSubmitLog.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/entity/CtfSubmitLog.java @@ -65,7 +65,8 @@ public class CtfSubmitLog { private CtfContest ctfContest; @Builder - private CtfSubmitLog(LocalDateTime submitTime, String flagSubmitted, Boolean isCorrect, String teamName, + private CtfSubmitLog(LocalDateTime submitTime, String flagSubmitted, Boolean isCorrect, + String teamName, String submitterLoginId, String submitterRealName, String challengeName, String contestName, CtfContest ctfContest) { this.submitTime = submitTime; diff --git a/src/main/java/com/keeper/homepage/domain/ctf/entity/challenge/CtfChallengeHasCtfChallengeCategory.java b/src/main/java/com/keeper/homepage/domain/ctf/entity/challenge/CtfChallengeHasCtfChallengeCategory.java index 71dbf72be..494434c89 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/entity/challenge/CtfChallengeHasCtfChallengeCategory.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/entity/challenge/CtfChallengeHasCtfChallengeCategory.java @@ -37,7 +37,8 @@ public class CtfChallengeHasCtfChallengeCategory { private CtfChallengeCategory ctfChallengeCategory; @Builder - private CtfChallengeHasCtfChallengeCategory(CtfChallenge ctfChallenge, CtfChallengeCategory ctfChallengeCategory) { + private CtfChallengeHasCtfChallengeCategory(CtfChallenge ctfChallenge, + CtfChallengeCategory ctfChallengeCategory) { this.ctfChallenge = ctfChallenge; this.ctfChallengeCategory = ctfChallengeCategory; } diff --git a/src/main/java/com/keeper/homepage/domain/ctf/entity/team/CtfTeam.java b/src/main/java/com/keeper/homepage/domain/ctf/entity/team/CtfTeam.java index e35f74be7..d610deb45 100644 --- a/src/main/java/com/keeper/homepage/domain/ctf/entity/team/CtfTeam.java +++ b/src/main/java/com/keeper/homepage/domain/ctf/entity/team/CtfTeam.java @@ -67,7 +67,8 @@ public class CtfTeam extends BaseEntity { private final Set ctfTeamHasMembers = new HashSet<>(); @Builder - private CtfTeam(String name, String description, Member creator, Integer score, CtfContest ctfContest, + private CtfTeam(String name, String description, Member creator, Integer score, + CtfContest ctfContest, LocalDateTime lastSolveTime) { this.name = name; this.description = description; diff --git a/src/main/java/com/keeper/homepage/domain/election/api/AdminElectionController.java b/src/main/java/com/keeper/homepage/domain/election/api/AdminElectionController.java index 863cdc55e..b6bc35c5e 100644 --- a/src/main/java/com/keeper/homepage/domain/election/api/AdminElectionController.java +++ b/src/main/java/com/keeper/homepage/domain/election/api/AdminElectionController.java @@ -42,7 +42,8 @@ public class AdminElectionController { public ResponseEntity createElection( @LoginMember Member member, @RequestBody @Valid ElectionCreateRequest request) { - adminElectionService.createElection(member, request.getName(), request.getDescription(), request.getIsAvailable()); + adminElectionService.createElection(member, request.getName(), request.getDescription(), + request.getIsAvailable()); return ResponseEntity.status(HttpStatus.CREATED).build(); } @@ -75,7 +76,8 @@ public ResponseEntity registerCandidate( @RequestBody @Valid ElectionCandidateRegisterRequest request, @PathVariable long electionId, @PathVariable long candidateId) { - adminElectionService.registerCandidate(request.getDescription(), request.getMemberJobId(), electionId, candidateId); + adminElectionService.registerCandidate(request.getDescription(), request.getMemberJobId(), + electionId, candidateId); return ResponseEntity.status(HttpStatus.CREATED).build(); } diff --git a/src/main/java/com/keeper/homepage/domain/election/application/AdminElectionService.java b/src/main/java/com/keeper/homepage/domain/election/application/AdminElectionService.java index 36f1bcae9..8f22fbae0 100644 --- a/src/main/java/com/keeper/homepage/domain/election/application/AdminElectionService.java +++ b/src/main/java/com/keeper/homepage/domain/election/application/AdminElectionService.java @@ -64,7 +64,8 @@ public void deleteElection(long electionId) { } @Transactional - public void updateElection(long electionId, String name, String description, Boolean isAvailable) { + public void updateElection(long electionId, String name, String description, + Boolean isAvailable) { Election election = validElectionFindService.findById(electionId); election.update(name, description, isAvailable); @@ -77,7 +78,8 @@ public Page getElections(Pageable pageable) { } @Transactional - public void registerCandidate(String description, Long memberJobId, long electionId, long candidateId) { + public void registerCandidate(String description, Long memberJobId, long electionId, + long candidateId) { Election election = validElectionFindService.findById(electionId); Member member = memberFindService.findById(candidateId); MemberJob memberJob = validCandidateService.findJobById(memberJobId); @@ -92,7 +94,8 @@ public void registerCandidate(String description, Long memberJobId, long electio } @Transactional - public void registerCandidates(List candidateIds, String description, Long memberJobId, long electionId) { + public void registerCandidates(List candidateIds, String description, Long memberJobId, + long electionId) { for (Long candidateId : candidateIds) { registerCandidate(description, memberJobId, electionId, candidateId); } @@ -103,7 +106,8 @@ public void deleteCandidate(long electionId, long candidateId) { ElectionCandidate electionCandidate = validCandidateService.findById(candidateId); Election election = validElectionFindService.findById(electionId); if (election.isAvailable()) { - throw new BusinessException(electionId, "electionId", ErrorCode.ELECTION_CANDIDATE_CANNOT_DELETE); + throw new BusinessException(electionId, "electionId", + ErrorCode.ELECTION_CANDIDATE_CANNOT_DELETE); } electionCandidateRepository.delete(electionCandidate); diff --git a/src/main/java/com/keeper/homepage/domain/election/application/convenience/ValidCandidateService.java b/src/main/java/com/keeper/homepage/domain/election/application/convenience/ValidCandidateService.java index 36cc28ba9..5e7314dde 100644 --- a/src/main/java/com/keeper/homepage/domain/election/application/convenience/ValidCandidateService.java +++ b/src/main/java/com/keeper/homepage/domain/election/application/convenience/ValidCandidateService.java @@ -24,7 +24,8 @@ public class ValidCandidateService { private static final long VIRTUAL_ELECTION_CANDIDATE_ID = 1; - private static final List VALID_CANDIDATE_JOB_IDS = Arrays.asList(ROLE_회장.getId(), ROLE_부회장.getId(), + private static final List VALID_CANDIDATE_JOB_IDS = Arrays.asList(ROLE_회장.getId(), + ROLE_부회장.getId(), ROLE_총무.getId()); private final ElectionCandidateRepository electionCandidateRepository; @@ -32,7 +33,8 @@ public class ValidCandidateService { public ElectionCandidate findById(long candidateId) { return electionCandidateRepository.findByIdAndIdNot(candidateId, VIRTUAL_ELECTION_CANDIDATE_ID) - .orElseThrow(() -> new BusinessException(candidateId, "candidateId", ELECTION_CANDIDATE_NOT_FOUND)); + .orElseThrow( + () -> new BusinessException(candidateId, "candidateId", ELECTION_CANDIDATE_NOT_FOUND)); } public MemberJob findJobById(long memberJobId) { diff --git a/src/main/java/com/keeper/homepage/domain/election/dao/ElectionRepository.java b/src/main/java/com/keeper/homepage/domain/election/dao/ElectionRepository.java index 4bf837c0f..8ee489475 100644 --- a/src/main/java/com/keeper/homepage/domain/election/dao/ElectionRepository.java +++ b/src/main/java/com/keeper/homepage/domain/election/dao/ElectionRepository.java @@ -20,6 +20,7 @@ public interface ElectionRepository extends JpaRepository { @Query("UPDATE Election e " + "SET e.member = :virtualMember " + "WHERE e.member = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); } diff --git a/src/main/java/com/keeper/homepage/domain/election/dao/ElectionVoterRepository.java b/src/main/java/com/keeper/homepage/domain/election/dao/ElectionVoterRepository.java index 60e6dd578..3ddaae730 100644 --- a/src/main/java/com/keeper/homepage/domain/election/dao/ElectionVoterRepository.java +++ b/src/main/java/com/keeper/homepage/domain/election/dao/ElectionVoterRepository.java @@ -9,7 +9,8 @@ public interface ElectionVoterRepository extends JpaRepository { - Optional findByMemberAndElectionAndIsVoted(Member member, Election election, Boolean isVoted); + Optional findByMemberAndElectionAndIsVoted(Member member, Election election, + Boolean isVoted); void deleteAllByElection(Election election); diff --git a/src/main/java/com/keeper/homepage/domain/game/api/GameController.kt b/src/main/java/com/keeper/homepage/domain/game/api/GameController.kt index 94ff089f8..af0c0f785 100644 --- a/src/main/java/com/keeper/homepage/domain/game/api/GameController.kt +++ b/src/main/java/com/keeper/homepage/domain/game/api/GameController.kt @@ -15,8 +15,8 @@ import org.springframework.web.bind.annotation.* @RequestMapping("/game") @RestController class GameController( - private val baseballService: BaseballService, - private val gameService: GameService + private val baseballService: BaseballService, + private val gameService: GameService ) { @GetMapping("/rank") fun getGameRank(): ResponseEntity> { @@ -41,8 +41,8 @@ class GameController( @PostMapping("/baseball/start") fun baseballStart( - @LoginMember requestMember: Member, - @RequestBody @Valid request: BaseballStartRequest + @LoginMember requestMember: Member, + @RequestBody @Valid request: BaseballStartRequest ): ResponseEntity { val baseballResponse = baseballService.start(requestMember, request.bettingPoint) return ResponseEntity.ok(baseballResponse) @@ -50,8 +50,8 @@ class GameController( @PostMapping("/baseball/guess") fun baseballGuess( - @LoginMember requestMember: Member, - @RequestBody @Valid request: BaseballGuessRequest + @LoginMember requestMember: Member, + @RequestBody @Valid request: BaseballGuessRequest ): ResponseEntity { val baseballResponse = baseballService.guess(requestMember, request.guessNumber) return ResponseEntity.ok(baseballResponse) @@ -59,7 +59,7 @@ class GameController( @GetMapping("/baseball/result") fun getBaseballResult( - @LoginMember requestMember: Member + @LoginMember requestMember: Member ): ResponseEntity { val baseballResponse = baseballService.getResult(requestMember) return ResponseEntity.ok(baseballResponse) diff --git a/src/main/java/com/keeper/homepage/domain/game/application/BaseballService.kt b/src/main/java/com/keeper/homepage/domain/game/application/BaseballService.kt index b55dad1ae..e9ed158ed 100644 --- a/src/main/java/com/keeper/homepage/domain/game/application/BaseballService.kt +++ b/src/main/java/com/keeper/homepage/domain/game/application/BaseballService.kt @@ -19,7 +19,7 @@ import org.springframework.transaction.annotation.Transactional const val REDIS_KEY_PREFIX = "baseball_" const val GUESS_NUMBER_LENGTH = 4 const val TRY_COUNT = 9 -const val MAX_BETTING_POINT = 5000L +const val MAX_BETTING_POINT = 3000L const val MIN_BETTING_POINT = 1000L const val BETTING_POINT_MESSAGE = "야구 게임 베팅" const val EARN_POINT_MESSAGE = "야구 게임 획득" @@ -27,17 +27,17 @@ const val EARN_POINT_MESSAGE = "야구 게임 획득" @Service @Transactional(readOnly = true) class BaseballService( - val redisUtil: RedisUtil, - val gameFindService: GameFindService + val redisUtil: RedisUtil, + val gameFindService: GameFindService ) { fun getBaseballGameInfoByMember(): BaseballInfoByMemberResponse = - BaseballInfoByMemberResponse( - guessNumberLength = GUESS_NUMBER_LENGTH, - tryCount = TRY_COUNT, - maxBettingPoint = MAX_BETTING_POINT, - minBettingPoint = MIN_BETTING_POINT, - maxPlayTime = BASEBALL_MAX_PLAYTIME, - ) + BaseballInfoByMemberResponse( + guessNumberLength = GUESS_NUMBER_LENGTH, + tryCount = TRY_COUNT, + maxBettingPoint = MAX_BETTING_POINT, + minBettingPoint = MIN_BETTING_POINT, + maxPlayTime = BASEBALL_MAX_PLAYTIME, + ) @Transactional fun getStatus(requestMember: Member): Pair { @@ -66,6 +66,11 @@ class BaseballService( if (bettingPoint <= 0) { throw BusinessException(requestMember.id, "memberId", ErrorCode.POINT_MUST_BE_POSITIVE) } + if(bettingPoint !in 1000..3000) { + throw BusinessException(requestMember.id, "memberId", ErrorCode.INVALID_GAME_POINT) + } + + if (requestMember.point < bettingPoint) { throw BusinessException(requestMember.id, "memberId", ErrorCode.NOT_ENOUGH_POINT) } @@ -75,9 +80,9 @@ class BaseballService( game.baseball.increaseBaseballTimes() val baseballResultEntity = BaseballResultEntity( - correctNumber = generateDistinctRandomNumber(GUESS_NUMBER_LENGTH), - bettingPoint = bettingPoint, - earnablePoint = bettingPoint * 2 // TODO: 포인트 획득 전략 정해지면 다시 구현 (우선 처음엔 베팅포인트 * 2) + correctNumber = generateDistinctRandomNumber(GUESS_NUMBER_LENGTH), + bettingPoint = bettingPoint, + earnablePoint = bettingPoint * 2 // TODO: 포인트 획득 전략 정해지면 다시 구현 (우선 처음엔 베팅포인트 * 2) ) saveBaseballResultInRedis(requestMember.id, baseballResultEntity, game.baseball.baseballPerDay) return BaseballResponse(emptyList(), bettingPoint, baseballResultEntity.earnablePoint, SECOND_PER_GAME) @@ -85,42 +90,42 @@ class BaseballService( private fun isAlreadyPlayedAllOfThem(member: Member): Boolean { return gameFindService.findByMemberOrInit(member) - .baseball - .isAlreadyPlayedAllOfThem + .baseball + .isAlreadyPlayedAllOfThem } private fun generateDistinctRandomNumber(length: Int): String { return (0..9).shuffled() - .take(length) - .joinToString(separator = "") + .take(length) + .joinToString(separator = "") } fun saveBaseballResultInRedis( - requestMemberId: Long, - baseballResultEntity: BaseballResultEntity, - baseballPerDay: Int + requestMemberId: Long, + baseballResultEntity: BaseballResultEntity, + baseballPerDay: Int ) { redisUtil.setDataExpire( - REDIS_KEY_PREFIX + requestMemberId.toString() + "_" + baseballPerDay, - baseballResultEntity, - RedisUtil.toMidNight() + REDIS_KEY_PREFIX + requestMemberId.toString() + "_" + baseballPerDay, + baseballResultEntity, + RedisUtil.toMidNight() ) // 다음날 자정에 redis data expired } @Transactional fun guess( - requestMember: Member, - guessNumber: String + requestMember: Member, + guessNumber: String ): BaseballResponse { val gameEntity = gameFindService.findByMemberOrInit(requestMember) val baseballResultEntity = getBaseballResultInRedis(requestMember, gameEntity) if (baseballResultEntity.isEnd()) { return BaseballResponse( - convertBaseballResult(baseballResultEntity.results), - baseballResultEntity.bettingPoint, - gameEntity.baseball.baseballDayPoint, - 0 + convertBaseballResult(baseballResultEntity.results), + baseballResultEntity.bettingPoint, + gameEntity.baseball.baseballDayPoint, + 0 ) } @@ -130,15 +135,15 @@ class BaseballService( val earnablePoint = baseballResultEntity.earnablePoint if (baseballResultEntity.isEnd()) { - requestMember.addPoint(earnablePoint, EARN_POINT_MESSAGE) - gameEntity.baseball.baseballDayPoint = earnablePoint + requestMember.addPoint(earnablePoint*2, EARN_POINT_MESSAGE) + gameEntity.baseball.baseballDayPoint = earnablePoint*2 } return BaseballResponse( - convertBaseballResult(baseballResultEntity.results), - baseballResultEntity.bettingPoint, - earnablePoint, - 0 + convertBaseballResult(baseballResultEntity.results), + baseballResultEntity.bettingPoint, + earnablePoint, + 0 ) } @@ -152,10 +157,10 @@ class BaseballService( if (baseballResultEntity.isEnd()) { return BaseballResponse( - convertBaseballResult(baseballResultEntity.results), - baseballResultEntity.bettingPoint, - baseballResultEntity.earnablePoint, - 0 + convertBaseballResult(baseballResultEntity.results), + baseballResultEntity.bettingPoint, + baseballResultEntity.earnablePoint, + 0 ) } @@ -163,10 +168,10 @@ class BaseballService( saveBaseballResultInRedis(requestMember.id, baseballResultEntity, gameEntity.baseball.baseballPerDay) return BaseballResponse( - convertBaseballResult(baseballResultEntity.results), - baseballResultEntity.bettingPoint, - baseballResultEntity.earnablePoint, - remainedSeconds + convertBaseballResult(baseballResultEntity.results), + baseballResultEntity.bettingPoint, + baseballResultEntity.earnablePoint, + remainedSeconds ) } @@ -176,8 +181,8 @@ class BaseballService( private fun getBaseballResultInRedis(requestMember: Member, gameEntity: Game): BaseballResultEntity { return redisUtil.getData( - REDIS_KEY_PREFIX + requestMember.id.toString() + "_" + gameEntity.baseball.baseballPerDay, - BaseballResultEntity::class.java + REDIS_KEY_PREFIX + requestMember.id.toString() + "_" + gameEntity.baseball.baseballPerDay, + BaseballResultEntity::class.java ).orElseThrow { throw BusinessException(requestMember.id, "memberId", ErrorCode.NOT_PLAYED_YET) } } diff --git a/src/main/java/com/keeper/homepage/domain/game/application/GameFindService.kt b/src/main/java/com/keeper/homepage/domain/game/application/GameFindService.kt index bb63e5543..4acd2f5a2 100644 --- a/src/main/java/com/keeper/homepage/domain/game/application/GameFindService.kt +++ b/src/main/java/com/keeper/homepage/domain/game/application/GameFindService.kt @@ -13,7 +13,7 @@ class GameFindService(private val gameRepository: GameRepository) { fun findByMemberOrInit(member: Member): Game { return gameRepository.findByMemberAndPlayDate(member, LocalDate.now()) - .orElseGet { initWhenNotExistGameMemberInfo(member) } + .orElseGet { initWhenNotExistGameMemberInfo(member) } } fun findAllByPlayDate(playDate: LocalDate): List { diff --git a/src/main/java/com/keeper/homepage/domain/game/application/GameService.kt b/src/main/java/com/keeper/homepage/domain/game/application/GameService.kt index 38686d0f0..d2732f3c3 100644 --- a/src/main/java/com/keeper/homepage/domain/game/application/GameService.kt +++ b/src/main/java/com/keeper/homepage/domain/game/application/GameService.kt @@ -11,18 +11,18 @@ import java.time.LocalDate const val MAX_RANK_COUNT = 4 fun List.safeSubList(fromIndex: Int, toIndex: Int): List = - this.subList(fromIndex.coerceAtLeast(0), toIndex.coerceAtMost(this.size)) + this.subList(fromIndex.coerceAtLeast(0), toIndex.coerceAtMost(this.size)) @Service @Transactional(readOnly = true) class GameService( - val gameFindService: GameFindService + val gameFindService: GameFindService ) { fun getGameRanks(): List { return gameFindService.findAllByPlayDate(LocalDate.now()) - .sortedWith(compareBy({ -getTodayEarnedPoint(it) }, { it.lastPlayTime })) - .safeSubList(0, MAX_RANK_COUNT) - .mapIndexed { rank, game -> GameRankResponse(rank + 1, game.member, getTodayEarnedPoint(game)) } + .sortedWith(compareBy({ -getTodayEarnedPoint(it) }, { it.lastPlayTime })) + .safeSubList(0, MAX_RANK_COUNT) + .mapIndexed { rank, game -> GameRankResponse(rank + 1, game.member, getTodayEarnedPoint(game)) } } private fun getTodayEarnedPoint(game: Game): Int { @@ -34,8 +34,8 @@ class GameService( val todayTotalEarnedPoint = gameEntity.lotto.lottoDayPoint + gameEntity.dice.diceDayPoint + gameEntity.roulette.rouletteDayPoint + gameEntity.baseball.baseballDayPoint return GameInfoByMemberResponse( - todayTotalEarnedPoint = todayTotalEarnedPoint, - currentMemberPoint = requestMember.point + todayTotalEarnedPoint = todayTotalEarnedPoint, + currentMemberPoint = requestMember.point ) } } diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballGuessRequest.kt b/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballGuessRequest.kt index 2e2d2b05a..74f9af46d 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballGuessRequest.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballGuessRequest.kt @@ -4,6 +4,6 @@ import com.keeper.homepage.domain.game.application.GUESS_NUMBER_LENGTH import org.hibernate.validator.constraints.Length data class BaseballGuessRequest( - @field:Length(min = GUESS_NUMBER_LENGTH, max = GUESS_NUMBER_LENGTH) - val guessNumber: String, + @field:Length(min = GUESS_NUMBER_LENGTH, max = GUESS_NUMBER_LENGTH) + val guessNumber: String, ) diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballStartRequest.kt b/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballStartRequest.kt index 86ab5700b..1e58bf34b 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballStartRequest.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/req/BaseballStartRequest.kt @@ -7,8 +7,8 @@ import jakarta.validation.constraints.Min import jakarta.validation.constraints.Positive data class BaseballStartRequest( - @field:Positive - @field:Max(MAX_BETTING_POINT) - @field:Min(MIN_BETTING_POINT) - val bettingPoint: Int, + @field:Positive + @field:Max(MAX_BETTING_POINT) + @field:Min(MIN_BETTING_POINT) + val bettingPoint: Int, ) diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballInfoByMemberResponse.kt b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballInfoByMemberResponse.kt index 5c6057af9..cd749de89 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballInfoByMemberResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballInfoByMemberResponse.kt @@ -1,9 +1,9 @@ package com.keeper.homepage.domain.game.dto.res data class BaseballInfoByMemberResponse( - val guessNumberLength: Int, - val tryCount: Int, - val maxBettingPoint: Long, - val minBettingPoint: Long, - val maxPlayTime: Int, + val guessNumberLength: Int, + val tryCount: Int, + val maxBettingPoint: Long, + val minBettingPoint: Long, + val maxPlayTime: Int, ) diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballResponse.kt b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballResponse.kt index 534ad8d78..2fd9be24f 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballResponse.kt @@ -3,16 +3,16 @@ package com.keeper.homepage.domain.game.dto.res import com.keeper.homepage.domain.game.entity.redis.BaseballResultEntity data class BaseballResponse( - val results: List, - val bettingPoint: Int, - val earnablePoint: Int, - val remainedSecond: Int, // millis 단위는 버림. + val results: List, + val bettingPoint: Int, + val earnablePoint: Int, + val remainedSecond: Int, // millis 단위는 버림. ) { data class GuessResultResponse(val guessNumber: String, val strike: Int, val ball: Int) { constructor(guessResultEntity: BaseballResultEntity.GuessResultEntity) : this( - guessNumber = guessResultEntity.guessNumber, - strike = guessResultEntity.strike, - ball = guessResultEntity.ball, + guessNumber = guessResultEntity.guessNumber, + strike = guessResultEntity.strike, + ball = guessResultEntity.ball, ) } } diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballStatusResponse.kt b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballStatusResponse.kt index 17941cc3c..0296804c7 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballStatusResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/res/BaseballStatusResponse.kt @@ -1,8 +1,8 @@ package com.keeper.homepage.domain.game.dto.res data class BaseballStatusResponse( - val status: BaseballStatus, - val baseballPerDay: Int, + val status: BaseballStatus, + val baseballPerDay: Int, ) enum class BaseballStatus { diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/res/GameInfoByMemberResponse.kt b/src/main/java/com/keeper/homepage/domain/game/dto/res/GameInfoByMemberResponse.kt index b2c4dab0b..4b93c21b9 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/res/GameInfoByMemberResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/res/GameInfoByMemberResponse.kt @@ -1,6 +1,6 @@ package com.keeper.homepage.domain.game.dto.res data class GameInfoByMemberResponse( - val todayTotalEarnedPoint: Int, - val currentMemberPoint: Int, + val todayTotalEarnedPoint: Int, + val currentMemberPoint: Int, ) diff --git a/src/main/java/com/keeper/homepage/domain/game/dto/res/GameRankResponse.kt b/src/main/java/com/keeper/homepage/domain/game/dto/res/GameRankResponse.kt index 7a404df2b..3edd4e046 100644 --- a/src/main/java/com/keeper/homepage/domain/game/dto/res/GameRankResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/game/dto/res/GameRankResponse.kt @@ -3,19 +3,19 @@ package com.keeper.homepage.domain.game.dto.res import com.keeper.homepage.domain.member.entity.Member data class GameRankResponse( - val rank: Int, - val realName: String, - val generation: String, - val todayEarnedPoint: Int, - val thumbnailPath: String?, - val memberId: Long, + val rank: Int, + val realName: String, + val generation: String, + val todayEarnedPoint: Int, + val thumbnailPath: String?, + val memberId: Long, ) { constructor(rank: Int, member: Member, todayEarnedPoint: Int) : this( - rank = rank, - realName = member.realName, - generation = member.generation.toString(), - todayEarnedPoint = todayEarnedPoint, - thumbnailPath = member.thumbnailPath, - memberId = member.id, + rank = rank, + realName = member.realName, + generation = member.generation.toString(), + todayEarnedPoint = todayEarnedPoint, + thumbnailPath = member.thumbnailPath, + memberId = member.id, ) } diff --git a/src/main/java/com/keeper/homepage/domain/game/entity/Game.java b/src/main/java/com/keeper/homepage/domain/game/entity/Game.java index 5d268193b..74184e9f8 100644 --- a/src/main/java/com/keeper/homepage/domain/game/entity/Game.java +++ b/src/main/java/com/keeper/homepage/domain/game/entity/Game.java @@ -58,7 +58,8 @@ public class Game { @Embedded private Baseball baseball; - public Game(Long id, Member member, LocalDate playDate, LocalDateTime lastPlayTime, Dice dice, Lotto lotto, Roulette roulette, + public Game(Long id, Member member, LocalDate playDate, LocalDateTime lastPlayTime, Dice dice, + Lotto lotto, Roulette roulette, Baseball baseball) { this.id = id; this.member = member; diff --git a/src/main/java/com/keeper/homepage/domain/game/entity/redis/BaseballResultEntity.kt b/src/main/java/com/keeper/homepage/domain/game/entity/redis/BaseballResultEntity.kt index 19dbb7870..b3fa3e6e7 100644 --- a/src/main/java/com/keeper/homepage/domain/game/entity/redis/BaseballResultEntity.kt +++ b/src/main/java/com/keeper/homepage/domain/game/entity/redis/BaseballResultEntity.kt @@ -8,10 +8,10 @@ import java.time.LocalDateTime const val SECOND_PER_GAME = 30 // 시간제한: 30s class BaseballResultEntity( - val correctNumber: String, - val bettingPoint: Int, - val results: MutableList = mutableListOf(), - var earnablePoint: Int, + val correctNumber: String, + val bettingPoint: Int, + val results: MutableList = mutableListOf(), + var earnablePoint: Int, ) { var lastGuessTime: LocalDateTime = LocalDateTime.now() diff --git a/src/main/java/com/keeper/homepage/domain/game/support/BaseballSupport.kt b/src/main/java/com/keeper/homepage/domain/game/support/BaseballSupport.kt index 74066e04f..3ec42420d 100644 --- a/src/main/java/com/keeper/homepage/domain/game/support/BaseballSupport.kt +++ b/src/main/java/com/keeper/homepage/domain/game/support/BaseballSupport.kt @@ -10,8 +10,8 @@ import java.time.ZoneOffset.UTC class BaseballSupport { companion object { fun getPassedGameCount( - playedRoundCount: Int, - lastGuessTime: LocalDateTime, + playedRoundCount: Int, + lastGuessTime: LocalDateTime, ): Pair { val now = LocalDateTime.now() val passedSecond = now.toEpochSecond(UTC) - lastGuessTime.toEpochSecond(UTC) @@ -26,8 +26,8 @@ class BaseballSupport { } fun guessAndGetResult( - correctNumber: String, - guessNumber: String + correctNumber: String, + guessNumber: String ): BaseballResultEntity.GuessResultEntity { if (guessNumber.length != GUESS_NUMBER_LENGTH) { return BaseballResultEntity.GuessResultEntity(guessNumber, 0, 0) diff --git a/src/main/java/com/keeper/homepage/domain/library/api/BookManageController.kt b/src/main/java/com/keeper/homepage/domain/library/api/BookManageController.kt index de97e5fc6..26a625f10 100644 --- a/src/main/java/com/keeper/homepage/domain/library/api/BookManageController.kt +++ b/src/main/java/com/keeper/homepage/domain/library/api/BookManageController.kt @@ -31,35 +31,35 @@ const val GET_BOOKS_DEFAULT_SIZE = 10 @RestController @Secured("ROLE_회장", "ROLE_부회장", "ROLE_사서") class BookManageController( - private val bookManageService: BookManageService + private val bookManageService: BookManageService ) { @GetMapping fun getBooks( - @RequestParam(required = false, defaultValue = "") search: String, - @RequestParam(required = false, defaultValue = "ALL") searchType: BookSearchType, - @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, - @RequestParam(defaultValue = GET_BOOKS_DEFAULT_SIZE.toString()) @Min(GET_BOOKS_MIN_SIZE) @Max(GET_BOOKS_MAX_SIZE) @NotNull size: Int, + @RequestParam(required = false, defaultValue = "") search: String, + @RequestParam(required = false, defaultValue = "ALL") searchType: BookSearchType, + @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, + @RequestParam(defaultValue = GET_BOOKS_DEFAULT_SIZE.toString()) @Min(GET_BOOKS_MIN_SIZE) @Max(GET_BOOKS_MAX_SIZE) @NotNull size: Int, ): ResponseEntity> { return ResponseEntity.ok( - bookManageService.getBooks(search, searchType, PageRequest.of(page, size)) - .map(::BookDetailResponse) + bookManageService.getBooks(search, searchType, PageRequest.of(page, size)) + .map(::BookDetailResponse) ) } @PostMapping(consumes = [MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE]) fun addBook( - @RequestPart @Valid bookMetaData: BookRequest, - @RequestPart thumbnail: MultipartFile?, + @RequestPart @Valid bookMetaData: BookRequest, + @RequestPart thumbnail: MultipartFile?, ): ResponseEntity { val addedBookId = bookManageService.addBook( - bookMetaData.title!!, - bookMetaData.author!!, - bookMetaData.totalQuantity!!, - bookMetaData.bookDepartment!!, - thumbnail, + bookMetaData.title!!, + bookMetaData.author!!, + bookMetaData.totalQuantity!!, + bookMetaData.bookDepartment!!, + thumbnail, ) return ResponseEntity.created(URI.create("/books/${addedBookId}")) - .build() + .build() } @DeleteMapping("/{bookId}") @@ -70,27 +70,27 @@ class BookManageController( @PutMapping("/{bookId}") fun modifyBook( - @PathVariable bookId: Long, - @RequestBody @Valid request: ModifyBookRequest + @PathVariable bookId: Long, + @RequestBody @Valid request: ModifyBookRequest ): ResponseEntity { bookManageService.modifyBook( - bookId, - request.title!!, - request.author!!, - request.totalQuantity!!, - request.bookDepartment!!, + bookId, + request.title!!, + request.author!!, + request.totalQuantity!!, + request.bookDepartment!!, ) return ResponseEntity.noContent().build() } @PatchMapping("/{bookId}/thumbnail") fun modifyBookThumbnail( - @PathVariable bookId: Long, - @ModelAttribute thumbnail: MultipartFile? + @PathVariable bookId: Long, + @ModelAttribute thumbnail: MultipartFile? ): ResponseEntity { bookManageService.modifyBookThumbnail( - bookId, - thumbnail + bookId, + thumbnail ) return ResponseEntity.noContent().build() } diff --git a/src/main/java/com/keeper/homepage/domain/library/api/BorrowManageController.kt b/src/main/java/com/keeper/homepage/domain/library/api/BorrowManageController.kt index a3812f2f2..c01bb8313 100644 --- a/src/main/java/com/keeper/homepage/domain/library/api/BorrowManageController.kt +++ b/src/main/java/com/keeper/homepage/domain/library/api/BorrowManageController.kt @@ -25,14 +25,14 @@ const val DEFAULT_SIZE = 10 @RestController @Secured("ROLE_회장", "ROLE_부회장", "ROLE_사서") class BorrowManageController( - private val borrowManageService: BorrowManageService + private val borrowManageService: BorrowManageService ) { @GetMapping fun getBorrowRequests( - @RequestParam(defaultValue = "") search: String, - @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, - @RequestParam(defaultValue = DEFAULT_SIZE.toString()) @Min(MIN_SIZE) @Max(MAX_SIZE) @NotNull size: Int, - @RequestParam status: BorrowStatusDto? + @RequestParam(defaultValue = "") search: String, + @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, + @RequestParam(defaultValue = DEFAULT_SIZE.toString()) @Min(MIN_SIZE) @Max(MAX_SIZE) @NotNull size: Int, + @RequestParam status: BorrowStatusDto? ): ResponseEntity> { val borrowRequests = borrowManageService.getBorrow(search, PageRequest.of(page, size), status) return ResponseEntity.ok(borrowRequests) @@ -64,10 +64,10 @@ class BorrowManageController( @GetMapping("/logs") fun getBorrowLogs( - @RequestParam(defaultValue = "") search: String, - @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, - @RequestParam(defaultValue = DEFAULT_SIZE.toString()) @Min(MIN_SIZE) @Max(MAX_SIZE) @NotNull size: Int, - @RequestParam searchType: BookBorrowLog.LogType?, + @RequestParam(defaultValue = "") search: String, + @RequestParam(defaultValue = "0") @PositiveOrZero @NotNull page: Int, + @RequestParam(defaultValue = DEFAULT_SIZE.toString()) @Min(MIN_SIZE) @Max(MAX_SIZE) @NotNull size: Int, + @RequestParam searchType: BookBorrowLog.LogType?, ): ResponseEntity> { val borrowLogs = borrowManageService.getBorrowLogs(search, PageRequest.of(page, size), searchType) return ResponseEntity.ok(borrowLogs) diff --git a/src/main/java/com/keeper/homepage/domain/library/application/BookManageService.kt b/src/main/java/com/keeper/homepage/domain/library/application/BookManageService.kt index 583c3e1f0..c4b2c888b 100644 --- a/src/main/java/com/keeper/homepage/domain/library/application/BookManageService.kt +++ b/src/main/java/com/keeper/homepage/domain/library/application/BookManageService.kt @@ -17,13 +17,13 @@ import org.springframework.web.multipart.MultipartFile import java.util.function.Function fun BookRepository.getBookById(bookId: Long) = this.findById(bookId) - .orElseThrow { throw BusinessException(bookId, "bookId", ErrorCode.BOOK_NOT_FOUND) } + .orElseThrow { throw BusinessException(bookId, "bookId", ErrorCode.BOOK_NOT_FOUND) } @Service @Transactional(readOnly = true) class BookManageService( - val bookRepository: BookRepository, - val thumbnailUtil: ThumbnailUtil + val bookRepository: BookRepository, + val thumbnailUtil: ThumbnailUtil ) { fun getBooks(search: String, searchType: BookSearchType, pageable: PageRequest): Page { return when (searchType) { @@ -35,20 +35,20 @@ class BookManageService( @Transactional fun addBook( - title: String, - author: String, - totalQuantity: Long, - bookDepartment: BookDepartment.BookDepartmentType, - thumbnail: MultipartFile? + title: String, + author: String, + totalQuantity: Long, + bookDepartment: BookDepartment.BookDepartmentType, + thumbnail: MultipartFile? ): Long = bookRepository.save( - Book( - title, - author, - BookDepartment.getBookDepartmentBy(bookDepartment), - totalQuantity, - thumbnailUtil.saveThumbnail(thumbnail) - .orElse(null) - ) + Book( + title, + author, + BookDepartment.getBookDepartmentBy(bookDepartment), + totalQuantity, + thumbnailUtil.saveThumbnail(thumbnail) + .orElse(null) + ) ).id @Transactional @@ -64,25 +64,25 @@ class BookManageService( @Transactional fun modifyBook( - bookId: Long, - title: String, - author: String, - totalQuantity: Long, - bookDepartment: BookDepartment.BookDepartmentType, + bookId: Long, + title: String, + author: String, + totalQuantity: Long, + bookDepartment: BookDepartment.BookDepartmentType, ) = bookRepository.getBookById(bookId) - .updateBook( - title, - author, - BookDepartment.getBookDepartmentBy(bookDepartment), - totalQuantity - ) + .updateBook( + title, + author, + BookDepartment.getBookDepartmentBy(bookDepartment), + totalQuantity + ) @Transactional fun modifyBookThumbnail(bookId: Long, thumbnail: MultipartFile?) { bookRepository.getBookById(bookId).thumbnail = thumbnailUtil.saveThumbnail(thumbnail) - .orElse(null) + .orElse(null) } fun getBookDetail(bookId: Long): BookDetailResponse = - BookDetailResponse(bookRepository.getBookById(bookId)) + BookDetailResponse(bookRepository.getBookById(bookId)) } diff --git a/src/main/java/com/keeper/homepage/domain/library/application/BookService.java b/src/main/java/com/keeper/homepage/domain/library/application/BookService.java index a5c447cf0..3183cc798 100644 --- a/src/main/java/com/keeper/homepage/domain/library/application/BookService.java +++ b/src/main/java/com/keeper/homepage/domain/library/application/BookService.java @@ -53,7 +53,8 @@ public class BookService { public static final long MAX_BORROWING_COUNT = 2; public static final long RENEWAL_WAITING_PERIOD = 3; - public Page getBooks(Member member, @NotNull BookSearchType searchType, String search, + public Page getBooks(Member member, @NotNull BookSearchType searchType, + String search, PageRequest pageable) { boolean isUnderLimit = member.getCountWaitOrInBorrowing() < MAX_BORROWING_COUNT; @@ -62,8 +63,9 @@ public Page getBooks(Member member, @NotNull BookSearchType search .map(book -> BookResponse.of(book, canBorrow(member, book) && isUnderLimit)); case TITLE -> bookRepository.findAllByTitleIgnoreCaseContainingOrderByIdDesc(search, pageable) .map(book -> BookResponse.of(book, canBorrow(member, book) && isUnderLimit)); - case AUTHOR -> bookRepository.findAllByAuthorIgnoreCaseContainingOrderByIdDesc(search, pageable) - .map(book -> BookResponse.of(book, canBorrow(member, book) && isUnderLimit)); + case AUTHOR -> + bookRepository.findAllByAuthorIgnoreCaseContainingOrderByIdDesc(search, pageable) + .map(book -> BookResponse.of(book, canBorrow(member, book) && isUnderLimit)); default -> throw new BusinessException(searchType, "searchType", BOOK_SEARCH_TYPE_NOT_FOUND); }; } @@ -92,14 +94,16 @@ public void requestBorrow(Member member, long bookId) { private void checkCountInBorrowing(Member member) { long countWaitOrInBorrowing = member.getCountWaitOrInBorrowing(); if (countWaitOrInBorrowing >= MAX_BORROWING_COUNT) { - throw new BusinessException(countWaitOrInBorrowing, "countWaitOrInBorrowing", BOOK_BORROWING_COUNT_OVER); + throw new BusinessException(countWaitOrInBorrowing, "countWaitOrInBorrowing", + BOOK_BORROWING_COUNT_OVER); } } private void checkCurrentQuantity(Book book) { Long currentQuantity = book.getCurrentQuantity(); if (currentQuantity == 0L) { - throw new BusinessException(currentQuantity, "currentQuantity", BOOK_CURRENT_QUANTITY_IS_ZERO); + throw new BusinessException(currentQuantity, "currentQuantity", + BOOK_CURRENT_QUANTITY_IS_ZERO); } } @@ -107,7 +111,8 @@ private void checkBorrowRequestAlready(Member member, Book book) { Optional borrowInfo = bookBorrowInfoRepository .findByMemberAndBookAndInBorrowingOrWait(member, book); if (borrowInfo.isPresent()) { - throw new BusinessException(borrowInfo.get().getId(), "bookBorrowInfoId", BORROW_REQUEST_ALREADY); + throw new BusinessException(borrowInfo.get().getId(), "bookBorrowInfoId", + BORROW_REQUEST_ALREADY); } } @@ -124,7 +129,8 @@ private void validateRenewalByReturnedDate(BookBorrowLog borrowLog) { long daysBetween = ChronoUnit.DAYS.between(returnedDate, currentDate); if (daysBetween <= RENEWAL_WAITING_PERIOD) { - throw new BusinessException(returnedDate, "checkEligibilityForRenewal", BORROW_RENEWAL_ELIGIBILITY_NOT_MET); + throw new BusinessException(returnedDate, "checkEligibilityForRenewal", + BORROW_RENEWAL_ELIGIBILITY_NOT_MET); } } diff --git a/src/main/java/com/keeper/homepage/domain/library/application/BorrowManageService.kt b/src/main/java/com/keeper/homepage/domain/library/application/BorrowManageService.kt index d62d58b5f..47be7fbee 100644 --- a/src/main/java/com/keeper/homepage/domain/library/application/BorrowManageService.kt +++ b/src/main/java/com/keeper/homepage/domain/library/application/BorrowManageService.kt @@ -18,21 +18,21 @@ import org.springframework.transaction.annotation.Transactional import java.time.LocalDateTime fun BookBorrowInfoRepository.getBorrowById(borrowId: Long) = this.findById(borrowId) - .orElseThrow { throw BusinessException(borrowId, "borrowId", ErrorCode.BORROW_NOT_FOUND) } + .orElseThrow { throw BusinessException(borrowId, "borrowId", ErrorCode.BORROW_NOT_FOUND) } @Service @Transactional(readOnly = true) class BorrowManageService( - val borrowInfoRepository: BookBorrowInfoRepository, - val borrowLogRepository: BookBorrowLogRepository, + val borrowInfoRepository: BookBorrowInfoRepository, + val borrowLogRepository: BookBorrowLogRepository, ) { fun getBorrow(search: String, pageable: Pageable, borrowStatusDto: BorrowStatusDto?): Page { if (borrowStatusDto == null) { return borrowInfoRepository.findAll(pageable) - .map(::BorrowDetailResponse) + .map(::BorrowDetailResponse) } return borrowStatusDto.getBorrowInfo(search, borrowInfoRepository, pageable) - .map(::BorrowDetailResponse) + .map(::BorrowDetailResponse) } @Transactional @@ -82,9 +82,9 @@ class BorrowManageService( } fun getBorrowLogs( - search: String, - pageable: PageRequest, - searchType: LogType? + search: String, + pageable: PageRequest, + searchType: LogType? ): Page { return when (searchType) { null, LogType.전체 -> borrowLogRepository.findAll(search, pageable) @@ -92,9 +92,9 @@ class BorrowManageService( LogType.반납대기, LogType.반납완료, LogType.대출반려 -> borrowLogRepository.findAllByStatus( - searchType.name, - search, - pageable + searchType.name, + search, + pageable ) }.map(::BorrowLogResponse) } diff --git a/src/main/java/com/keeper/homepage/domain/library/converter/BookSearchTypeConverter.kt b/src/main/java/com/keeper/homepage/domain/library/converter/BookSearchTypeConverter.kt index e949705b8..960e7cb36 100644 --- a/src/main/java/com/keeper/homepage/domain/library/converter/BookSearchTypeConverter.kt +++ b/src/main/java/com/keeper/homepage/domain/library/converter/BookSearchTypeConverter.kt @@ -7,8 +7,8 @@ import java.util.* class BookSearchTypeConverter : Converter { override fun convert(source: String): BookSearchType { return Arrays.stream(BookSearchType.values()) - .filter { bookSearchType: BookSearchType -> bookSearchType.type == source.lowercase() } - .findFirst() - .get() + .filter { bookSearchType: BookSearchType -> bookSearchType.type == source.lowercase() } + .findFirst() + .get() } } diff --git a/src/main/java/com/keeper/homepage/domain/library/dao/BookBorrowInfoRepository.java b/src/main/java/com/keeper/homepage/domain/library/dao/BookBorrowInfoRepository.java index bb2a380b9..83eccb496 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dao/BookBorrowInfoRepository.java +++ b/src/main/java/com/keeper/homepage/domain/library/dao/BookBorrowInfoRepository.java @@ -52,7 +52,8 @@ Page findAllByTwoBorrowStatus(@Param("statusId1") long borrowSta Optional findByMemberAndBookAndInBorrowingOrWait(@Param("member") Member member, @Param("book") Book book); - Optional findByMemberAndBookAndBorrowStatus(Member member, Book book, BookBorrowStatus borrowStatus); + Optional findByMemberAndBookAndBorrowStatus(Member member, Book book, + BookBorrowStatus borrowStatus); @Query(value = "SELECT borrow " + "FROM BookBorrowInfo borrow " @@ -60,6 +61,7 @@ Optional findByMemberAndBookAndInBorrowingOrWait(@Param("member" + "OR borrow.borrowStatus.id = 3 " // 대출 중 + "OR borrow.borrowStatus.id = 4) " // 반납 대기 + "AND borrow.member = :member ") - Page findAllByMemberAndInBorrowingOrWait(@Param("member") Member member, Pageable pageable); + Page findAllByMemberAndInBorrowingOrWait(@Param("member") Member member, + Pageable pageable); } diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/req/BookRequest.kt b/src/main/java/com/keeper/homepage/domain/library/dto/req/BookRequest.kt index ca4983279..969c1cd9c 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/req/BookRequest.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/req/BookRequest.kt @@ -12,18 +12,18 @@ const val MAX_AUTHOR_LENGTH = 30 const val MAX_TOTAL_QUANTITY_LENGTH = 20L data class BookRequest( - @field:NotNull - @field:Length(min = 1, max = MAX_TITLE_LENGTH) - val title: String?, + @field:NotNull + @field:Length(min = 1, max = MAX_TITLE_LENGTH) + val title: String?, - @field:NotNull - @field:Length(min = 1, max = MAX_AUTHOR_LENGTH) - val author: String?, + @field:NotNull + @field:Length(min = 1, max = MAX_AUTHOR_LENGTH) + val author: String?, - @field:NotNull - @field:Max(MAX_TOTAL_QUANTITY_LENGTH) @field:Min(1) - val totalQuantity: Long?, + @field:NotNull + @field:Max(MAX_TOTAL_QUANTITY_LENGTH) @field:Min(1) + val totalQuantity: Long?, - @field:NotNull - val bookDepartment: BookDepartment.BookDepartmentType?, + @field:NotNull + val bookDepartment: BookDepartment.BookDepartmentType?, ) diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/req/BorrowStatusDto.kt b/src/main/java/com/keeper/homepage/domain/library/dto/req/BorrowStatusDto.kt index f89d61846..58b7ad0ce 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/req/BorrowStatusDto.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/req/BorrowStatusDto.kt @@ -12,43 +12,43 @@ import java.time.LocalDateTime enum class BorrowStatusDto(val status: String) { REQUESTS("requests") { override fun getBorrowInfo( - search: String, - repository: BookBorrowInfoRepository, - pageable: Pageable + search: String, + repository: BookBorrowInfoRepository, + pageable: Pageable ) = repository.findAllByBorrowStatus(getBookBorrowStatusBy(대출대기).id, search, pageable)!! }, WILL_RETURN("willreturn") { override fun getBorrowInfo( - search: String, - repository: BookBorrowInfoRepository, - pageable: Pageable + search: String, + repository: BookBorrowInfoRepository, + pageable: Pageable ) = repository.findAllByBorrowStatus(getBookBorrowStatusBy(반납대기).id, search, pageable)!! }, REQUESTS_OR_WILL_RETURN("requests_or_willreturn") { override fun getBorrowInfo( - search: String, - repository: BookBorrowInfoRepository, - pageable: Pageable + search: String, + repository: BookBorrowInfoRepository, + pageable: Pageable ) = repository.findAllByTwoBorrowStatus( - getBookBorrowStatusBy(대출대기).id, - getBookBorrowStatusBy(반납대기).id, - search, - pageable + getBookBorrowStatusBy(대출대기).id, + getBookBorrowStatusBy(반납대기).id, + search, + pageable )!! }, OVERDUE("overdue") { override fun getBorrowInfo( - search: String, - repository: BookBorrowInfoRepository, - pageable: Pageable + search: String, + repository: BookBorrowInfoRepository, + pageable: Pageable ) = repository.findAllOverDue(LocalDateTime.now(), pageable)!! }; fun isMatch(status: String) = this.status == status abstract fun getBorrowInfo( - search: String, - repository: BookBorrowInfoRepository, - pageable: Pageable + search: String, + repository: BookBorrowInfoRepository, + pageable: Pageable ): Page } diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/req/ModifyBookRequest.kt b/src/main/java/com/keeper/homepage/domain/library/dto/req/ModifyBookRequest.kt index 816659b4b..4b04e4b98 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/req/ModifyBookRequest.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/req/ModifyBookRequest.kt @@ -7,18 +7,18 @@ import jakarta.validation.constraints.NotNull import org.hibernate.validator.constraints.Length data class ModifyBookRequest( - @field:NotNull - @field:Length(min = 1, max = MAX_TITLE_LENGTH) - val title: String?, + @field:NotNull + @field:Length(min = 1, max = MAX_TITLE_LENGTH) + val title: String?, - @field:NotNull - @field:Length(min = 1, max = MAX_AUTHOR_LENGTH) - val author: String?, + @field:NotNull + @field:Length(min = 1, max = MAX_AUTHOR_LENGTH) + val author: String?, - @field:NotNull - @field:Max(MAX_TOTAL_QUANTITY_LENGTH) @field:Min(1) - val totalQuantity: Long?, + @field:NotNull + @field:Max(MAX_TOTAL_QUANTITY_LENGTH) @field:Min(1) + val totalQuantity: Long?, - @field:NotNull - val bookDepartment: BookDepartment.BookDepartmentType?, + @field:NotNull + val bookDepartment: BookDepartment.BookDepartmentType?, ) diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BookDetailResponse.kt b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BookDetailResponse.kt index 06631f39c..f87ca5ecf 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BookDetailResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BookDetailResponse.kt @@ -3,25 +3,25 @@ package com.keeper.homepage.domain.library.dto.resp import com.keeper.homepage.domain.library.entity.Book data class BookDetailResponse( - val bookId: Long, - val title: String, - val author: String, - val bookDepartment: String, - val totalQuantity: Long, - val currentQuantity: Long, - val thumbnailPath: String?, - val borrowInfos: List + val bookId: Long, + val title: String, + val author: String, + val bookDepartment: String, + val totalQuantity: Long, + val currentQuantity: Long, + val thumbnailPath: String?, + val borrowInfos: List ) { constructor(book: Book) : this( - bookId = book.id, - title = book.title, - author = book.author, - bookDepartment = book.bookDepartment.type.name, - totalQuantity = book.totalQuantity, - currentQuantity = book.currentQuantity, - thumbnailPath = book.thumbnailPath, - borrowInfos = book.bookBorrowInfos - .filter { borrowInfo -> borrowInfo.isInBorrowing } - .map(::BorrowDetailResponse), + bookId = book.id, + title = book.title, + author = book.author, + bookDepartment = book.bookDepartment.type.name, + totalQuantity = book.totalQuantity, + currentQuantity = book.currentQuantity, + thumbnailPath = book.thumbnailPath, + borrowInfos = book.bookBorrowInfos + .filter { borrowInfo -> borrowInfo.isInBorrowing } + .map(::BorrowDetailResponse), ) } diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowDetailResponse.kt b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowDetailResponse.kt index 513e6312f..469d069c0 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowDetailResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowDetailResponse.kt @@ -7,35 +7,35 @@ import java.time.LocalDateTime const val RESPONSE_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss" data class BorrowDetailResponse( - val borrowInfoId: Long, - val bookId: Long, - val bookTitle: String, - val author: String, - val totalQuantity: Long, - val currentQuantity: Long, - val borrowerId: Long, - val borrowerRealName: String, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val requestDatetime: LocalDateTime?, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val borrowDateTime: LocalDateTime?, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val expiredDateTime: LocalDateTime?, - val status: String + val borrowInfoId: Long, + val bookId: Long, + val bookTitle: String, + val author: String, + val totalQuantity: Long, + val currentQuantity: Long, + val borrowerId: Long, + val borrowerRealName: String, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val requestDatetime: LocalDateTime?, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val borrowDateTime: LocalDateTime?, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val expiredDateTime: LocalDateTime?, + val status: String ) { constructor(borrowInfo: BookBorrowInfo) : this( - borrowInfoId = borrowInfo.id, - bookId = borrowInfo.book.id, - bookTitle = borrowInfo.book.title, - author = borrowInfo.book.author, - totalQuantity = borrowInfo.book.totalQuantity, - currentQuantity = borrowInfo.book.currentQuantity, - borrowerId = borrowInfo.member.id, - borrowerRealName = borrowInfo.member.realName, - requestDatetime = borrowInfo.lastRequestDate, - borrowDateTime = borrowInfo.borrowDate, - expiredDateTime = borrowInfo.expireDate, - status = borrowInfo.borrowStatus.type.name, + borrowInfoId = borrowInfo.id, + bookId = borrowInfo.book.id, + bookTitle = borrowInfo.book.title, + author = borrowInfo.book.author, + totalQuantity = borrowInfo.book.totalQuantity, + currentQuantity = borrowInfo.book.currentQuantity, + borrowerId = borrowInfo.member.id, + borrowerRealName = borrowInfo.member.realName, + requestDatetime = borrowInfo.lastRequestDate, + borrowDateTime = borrowInfo.borrowDate, + expiredDateTime = borrowInfo.expireDate, + status = borrowInfo.borrowStatus.type.name, ) } diff --git a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowLogResponse.kt b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowLogResponse.kt index 70de41a79..d0f41a9df 100644 --- a/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowLogResponse.kt +++ b/src/main/java/com/keeper/homepage/domain/library/dto/resp/BorrowLogResponse.kt @@ -5,34 +5,34 @@ import com.keeper.homepage.domain.library.entity.BookBorrowLog import java.time.LocalDateTime data class BorrowLogResponse( - val borrowInfoId: Long, - val bookId: Long, - val bookTitle: String, - val author: String, - val borrowerId: Long, - val borrowerRealName: String, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val borrowDateTime: LocalDateTime?, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val expireDateTime: LocalDateTime?, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val returnDateTime: LocalDateTime?, - @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) - val rejectDateTime: LocalDateTime?, - val status: String + val borrowInfoId: Long, + val bookId: Long, + val bookTitle: String, + val author: String, + val borrowerId: Long, + val borrowerRealName: String, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val borrowDateTime: LocalDateTime?, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val expireDateTime: LocalDateTime?, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val returnDateTime: LocalDateTime?, + @JsonFormat(pattern = RESPONSE_DATETIME_FORMAT) + val rejectDateTime: LocalDateTime?, + val status: String ) { constructor(log: BookBorrowLog) : this( - borrowInfoId = log.borrowId, - bookId = log.bookId, - bookTitle = log.bookTitle, - author = log.bookAuthor, - borrowerId = log.memberId, - borrowerRealName = log.memberRealName, - borrowDateTime = log.borrowDate, - expireDateTime = log.expireDate, - returnDateTime = log.returnDate, - rejectDateTime = log.rejectDate, - status = log.borrowStatus, + borrowInfoId = log.borrowId, + bookId = log.bookId, + bookTitle = log.bookTitle, + author = log.bookAuthor, + borrowerId = log.memberId, + borrowerRealName = log.memberRealName, + borrowDateTime = log.borrowDate, + expireDateTime = log.expireDate, + returnDateTime = log.returnDate, + rejectDateTime = log.rejectDate, + status = log.borrowStatus, ) } diff --git a/src/main/java/com/keeper/homepage/domain/member/api/MemberController.java b/src/main/java/com/keeper/homepage/domain/member/api/MemberController.java index 5e3c4b53e..3b6f634cf 100644 --- a/src/main/java/com/keeper/homepage/domain/member/api/MemberController.java +++ b/src/main/java/com/keeper/homepage/domain/member/api/MemberController.java @@ -76,7 +76,8 @@ public ResponseEntity> getPointRanks( @RequestParam(defaultValue = "0") @PositiveOrZero int page, @RequestParam(defaultValue = "10") @PositiveOrZero int size ) { - Page response = memberService.getPointRanking(PageRequest.of(page, size)); + Page response = memberService.getPointRanking( + PageRequest.of(page, size)); return ResponseEntity.ok(response); } diff --git a/src/main/java/com/keeper/homepage/domain/member/application/MemberService.java b/src/main/java/com/keeper/homepage/domain/member/application/MemberService.java index d6fabb112..904ce2d19 100644 --- a/src/main/java/com/keeper/homepage/domain/member/application/MemberService.java +++ b/src/main/java/com/keeper/homepage/domain/member/application/MemberService.java @@ -102,7 +102,8 @@ public void deleteMember(Member member, String rawPassword) { private void checkBorrowedBook(Member member) { if (member.hasAnyBorrowBooks()) { - throw new BusinessException(member.getBookBorrowInfos(), "memberBorrowInfos", MEMBER_BOOK_NOT_EMPTY); + throw new BusinessException(member.getBookBorrowInfos(), "memberBorrowInfos", + MEMBER_BOOK_NOT_EMPTY); } } diff --git a/src/main/java/com/keeper/homepage/domain/member/application/convenience/MemberFindService.java b/src/main/java/com/keeper/homepage/domain/member/application/convenience/MemberFindService.java index 1d0c1c548..843df1345 100644 --- a/src/main/java/com/keeper/homepage/domain/member/application/convenience/MemberFindService.java +++ b/src/main/java/com/keeper/homepage/domain/member/application/convenience/MemberFindService.java @@ -49,6 +49,7 @@ public List findAllRegular() { } public Page findAllRegular(Pageable pageable) { - return memberRepository.findAllByMemberTypeAndIdNot(getMemberTypeBy(정회원), VIRTUAL_MEMBER_ID, pageable); + return memberRepository.findAllByMemberTypeAndIdNot(getMemberTypeBy(정회원), VIRTUAL_MEMBER_ID, + pageable); } } diff --git a/src/main/java/com/keeper/homepage/domain/member/dao/comment/MemberHasCommentDislikeRepository.java b/src/main/java/com/keeper/homepage/domain/member/dao/comment/MemberHasCommentDislikeRepository.java index 8c7578a4e..3b7396b9a 100644 --- a/src/main/java/com/keeper/homepage/domain/member/dao/comment/MemberHasCommentDislikeRepository.java +++ b/src/main/java/com/keeper/homepage/domain/member/dao/comment/MemberHasCommentDislikeRepository.java @@ -6,7 +6,8 @@ import com.keeper.homepage.domain.post.entity.Post; import org.springframework.data.jpa.repository.JpaRepository; -public interface MemberHasCommentDislikeRepository extends JpaRepository { +public interface MemberHasCommentDislikeRepository extends + JpaRepository { void deleteAllByComment(Comment comment); diff --git a/src/main/java/com/keeper/homepage/domain/member/dto/response/profile/MemberProfileResponse.java b/src/main/java/com/keeper/homepage/domain/member/dto/response/profile/MemberProfileResponse.java index 519236583..ecb4950f5 100644 --- a/src/main/java/com/keeper/homepage/domain/member/dto/response/profile/MemberProfileResponse.java +++ b/src/main/java/com/keeper/homepage/domain/member/dto/response/profile/MemberProfileResponse.java @@ -51,7 +51,8 @@ public static MemberProfileResponse of(Member member, Member me) { } private static String getStudentIdIfMine(Member member, Member me) { - return Objects.equals(member.getId(), me.getId()) ? member.getProfile().getStudentId().get() : "default"; + return Objects.equals(member.getId(), me.getId()) ? member.getProfile().getStudentId().get() + : "default"; } private static List getFollower(Member member) { diff --git a/src/main/java/com/keeper/homepage/domain/member/entity/Member.java b/src/main/java/com/keeper/homepage/domain/member/entity/Member.java index 1f72e81ad..032f61179 100644 --- a/src/main/java/com/keeper/homepage/domain/member/entity/Member.java +++ b/src/main/java/com/keeper/homepage/domain/member/entity/Member.java @@ -399,7 +399,8 @@ public long getCountWaitOrInBorrowing() { public boolean hasTeam(CtfContest contest) { return ctfTeamHasMembers.stream() - .anyMatch(ctfTeamHasMember -> ctfTeamHasMember.getCtfTeam().getCtfContest().equals(contest)); + .anyMatch( + ctfTeamHasMember -> ctfTeamHasMember.getCtfTeam().getCtfContest().equals(contest)); } public boolean isJoin(CtfTeam ctfTeam) { diff --git a/src/main/java/com/keeper/homepage/domain/member/entity/embedded/Profile.java b/src/main/java/com/keeper/homepage/domain/member/entity/embedded/Profile.java index c943d60e5..e0b3ece86 100644 --- a/src/main/java/com/keeper/homepage/domain/member/entity/embedded/Profile.java +++ b/src/main/java/com/keeper/homepage/domain/member/entity/embedded/Profile.java @@ -42,7 +42,8 @@ public class Profile { private Thumbnail thumbnail; @Builder - private Profile(LoginId loginId, EmailAddress emailAddress, Password password, RealName realName, LocalDate birthday, + private Profile(LoginId loginId, EmailAddress emailAddress, Password password, RealName realName, + LocalDate birthday, StudentId studentId, Thumbnail thumbnail) { this.loginId = loginId; this.emailAddress = emailAddress; diff --git a/src/main/java/com/keeper/homepage/domain/merit/api/MeritController.java b/src/main/java/com/keeper/homepage/domain/merit/api/MeritController.java index a62f4fa12..38ae94a23 100644 --- a/src/main/java/com/keeper/homepage/domain/merit/api/MeritController.java +++ b/src/main/java/com/keeper/homepage/domain/merit/api/MeritController.java @@ -54,7 +54,8 @@ public ResponseEntity> searchMeritLogList( @RequestParam(defaultValue = "10") @PositiveOrZero @Max(30) int size ) { return ResponseEntity - .ok(meritLogService.findAllByMeritType(PageRequest.of(page, size, Sort.by("time").descending()), meritType) + .ok(meritLogService.findAllByMeritType( + PageRequest.of(page, size, Sort.by("time").descending()), meritType) .map(SearchMeritLogListResponse::from)); } diff --git a/src/main/java/com/keeper/homepage/domain/merit/dao/MeritLogRepository.java b/src/main/java/com/keeper/homepage/domain/merit/dao/MeritLogRepository.java index 8e9047e8b..6507470f1 100644 --- a/src/main/java/com/keeper/homepage/domain/merit/dao/MeritLogRepository.java +++ b/src/main/java/com/keeper/homepage/domain/merit/dao/MeritLogRepository.java @@ -19,9 +19,12 @@ public interface MeritLogRepository extends JpaRepository { long countByMemberId(long memberId); @Query( - "SELECT NEW com.keeper.homepage.domain.merit.dto.response.MeritLogsGroupByMemberResponse(m.memberId, m.memberRealName, m.memberGeneration, " + - "CAST(SUM(CASE WHEN m.meritType.isMerit = true THEN m.meritType.merit ELSE 0 END) AS INTEGER), " + - "CAST(SUM(CASE WHEN m.meritType.isMerit = false THEN m.meritType.merit ELSE 0 END) AS INTEGER)) " + + "SELECT NEW com.keeper.homepage.domain.merit.dto.response.MeritLogsGroupByMemberResponse(m.memberId, m.memberRealName, m.memberGeneration, " + + + "CAST(SUM(CASE WHEN m.meritType.isMerit = true THEN m.meritType.merit ELSE 0 END) AS INTEGER), " + + + "CAST(SUM(CASE WHEN m.meritType.isMerit = false THEN m.meritType.merit ELSE 0 END) AS INTEGER)) " + + "FROM MeritLog m GROUP BY m.memberId, m.memberRealName, m.memberGeneration") Page findAllTotalMeritLogs(Pageable pageable); diff --git a/src/main/java/com/keeper/homepage/domain/point/api/PointController.java b/src/main/java/com/keeper/homepage/domain/point/api/PointController.java index 18023473a..f3117dc33 100644 --- a/src/main/java/com/keeper/homepage/domain/point/api/PointController.java +++ b/src/main/java/com/keeper/homepage/domain/point/api/PointController.java @@ -52,7 +52,8 @@ public ResponseEntity> findAllPointLogs( @LoginMember Member member ) { return ResponseEntity.ok( - pointLogService.findAllPointLogs(PageRequest.of(page, size, Sort.by(DESC, "time")), member.getId()) + pointLogService.findAllPointLogs(PageRequest.of(page, size, Sort.by(DESC, "time")), + member.getId()) .map(FindAllPointLogResponse::from) ); } diff --git a/src/main/java/com/keeper/homepage/domain/point/entity/PointLog.java b/src/main/java/com/keeper/homepage/domain/point/entity/PointLog.java index ae05d6622..6c089eacd 100644 --- a/src/main/java/com/keeper/homepage/domain/point/entity/PointLog.java +++ b/src/main/java/com/keeper/homepage/domain/point/entity/PointLog.java @@ -51,7 +51,8 @@ public class PointLog { private Boolean isSpent; @Builder - private PointLog(LocalDateTime time, Member member, Integer point, String detail, Member presented, Boolean isSpent) { + private PointLog(LocalDateTime time, Member member, Integer point, String detail, + Member presented, Boolean isSpent) { this.time = time; this.member = member; this.point = point; diff --git a/src/main/java/com/keeper/homepage/domain/post/api/PostController.java b/src/main/java/com/keeper/homepage/domain/post/api/PostController.java index dfd2f09a9..4515e36e3 100644 --- a/src/main/java/com/keeper/homepage/domain/post/api/PostController.java +++ b/src/main/java/com/keeper/homepage/domain/post/api/PostController.java @@ -190,7 +190,8 @@ public ResponseEntity> getPosts( @RequestParam(defaultValue = "0") @PositiveOrZero int page, @RequestParam(defaultValue = "10") @PositiveOrZero int size ) { - return ResponseEntity.ok(postService.getPosts(categoryId, searchType, search, PageRequest.of(page, size))); + return ResponseEntity.ok( + postService.getPosts(categoryId, searchType, search, PageRequest.of(page, size))); } @GetMapping("/recent") diff --git a/src/main/java/com/keeper/homepage/domain/post/application/PostService.java b/src/main/java/com/keeper/homepage/domain/post/application/PostService.java index bfb5c1065..766c01d96 100644 --- a/src/main/java/com/keeper/homepage/domain/post/application/PostService.java +++ b/src/main/java/com/keeper/homepage/domain/post/application/PostService.java @@ -72,7 +72,8 @@ public class PostService { private static final int RECENT_POSTING_COUNT = 10; @Transactional - public Long create(Post post, Long categoryId, MultipartFile thumbnail, List multipartFiles) { + public Long create(Post post, Long categoryId, MultipartFile thumbnail, + List multipartFiles) { if (post.isSecret()) { checkPassword(post.getPassword()); } @@ -322,7 +323,8 @@ public void deletePostFile(Member member, long postId, List fileIds) { }); } - public Page getPosts(long categoryId, String searchType, String search, PageRequest pageable) { + public Page getPosts(long categoryId, String searchType, String search, + PageRequest pageable) { Category category = categoryFindService.findById(categoryId); if (searchType == null) { return postRepository.findAllRecentByCategory(category, pageable) diff --git a/src/main/java/com/keeper/homepage/domain/post/application/convenience/CategoryFindService.java b/src/main/java/com/keeper/homepage/domain/post/application/convenience/CategoryFindService.java index aa53f80c1..be3453479 100644 --- a/src/main/java/com/keeper/homepage/domain/post/application/convenience/CategoryFindService.java +++ b/src/main/java/com/keeper/homepage/domain/post/application/convenience/CategoryFindService.java @@ -19,6 +19,7 @@ public class CategoryFindService { public Category findById(long categoryId) { return categoryRepository.findByIdAndIdNot(categoryId, VIRTUAL_CATEGORY_ID) - .orElseThrow(() -> new BusinessException(categoryId, "categoryId", POST_CATEGORY_NOT_FOUND)); + .orElseThrow( + () -> new BusinessException(categoryId, "categoryId", POST_CATEGORY_NOT_FOUND)); } } diff --git a/src/main/java/com/keeper/homepage/domain/post/dao/PostRepository.java b/src/main/java/com/keeper/homepage/domain/post/dao/PostRepository.java index fc3b5bee2..8ef671fb6 100644 --- a/src/main/java/com/keeper/homepage/domain/post/dao/PostRepository.java +++ b/src/main/java/com/keeper/homepage/domain/post/dao/PostRepository.java @@ -64,7 +64,8 @@ public interface PostRepository extends JpaRepository { + "AND p.isTemp = false " + "AND LOWER(p.title) LIKE LOWER(concat('%', :search, '%')) " + "ORDER BY p.registerTime DESC") - Page findAllRecentByCategoryAndTitle(@Param("category") Category category, @Param("search") String search, + Page findAllRecentByCategoryAndTitle(@Param("category") Category category, + @Param("search") String search, Pageable pageable); /** @@ -80,7 +81,8 @@ Page findAllRecentByCategoryAndTitle(@Param("category") Category category, + "AND p.isTemp = false " + "AND LOWER(p.content) LIKE LOWER(concat('%', :search, '%')) " + "ORDER BY p.registerTime DESC") - Page findAllRecentByCategoryAndContent(@Param("category") Category category, @Param("search") String search, + Page findAllRecentByCategoryAndContent(@Param("category") Category category, + @Param("search") String search, Pageable pageable); /** @@ -113,7 +115,8 @@ Page findAllRecentByCategoryAndTitleOrContent(@Param("category") Category + "AND p.isTemp = false " + "AND LOWER(p.member.profile.realName) LIKE LOWER(concat('%', :search, '%')) " + "ORDER BY p.registerTime DESC") - Page findAllRecentByCategoryAndWriter(@Param("category") Category category, @Param("search") String search, + Page findAllRecentByCategoryAndWriter(@Param("category") Category category, + @Param("search") String search, Pageable pageable); /** @@ -125,7 +128,8 @@ Page findAllRecentByCategoryAndWriter(@Param("category") Category category @Query("SELECT p FROM Post p " + "WHERE p.isTemp = false " + "AND p.registerTime BETWEEN :startDate AND :endDate") - List findAllTrend(@Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate); + List findAllTrend(@Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate); @Query("SELECT p FROM Post p " @@ -142,7 +146,8 @@ Page findAllRecentByCategoryAndWriter(@Param("category") Category category + "AND p.isTemp = false " + "ORDER BY p.id DESC " + "LIMIT 1") - Optional findPreviousPost(@Param("postId") Long postId, @Param("category") Category category); + Optional findPreviousPost(@Param("postId") Long postId, + @Param("category") Category category); Page findAllByMemberAndIsTempFalse(Member member, Pageable pageable); @@ -152,7 +157,8 @@ Page findAllRecentByCategoryAndWriter(@Param("category") Category category @Query("UPDATE Post p " + "SET p.member = :virtualMember " + "WHERE p.member = :member AND p.isTemp = false ") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); void deleteAllByMemberAndIsTempTrue(Member member); } diff --git a/src/main/java/com/keeper/homepage/domain/post/dto/response/PostDetailResponse.java b/src/main/java/com/keeper/homepage/domain/post/dto/response/PostDetailResponse.java index 4afdecdf2..502b8edb6 100644 --- a/src/main/java/com/keeper/homepage/domain/post/dto/response/PostDetailResponse.java +++ b/src/main/java/com/keeper/homepage/domain/post/dto/response/PostDetailResponse.java @@ -43,7 +43,8 @@ public class PostDetailResponse { private AdjacentPostResponse previousPost; private AdjacentPostResponse nextPost; - public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike, Post previousPost, Post nextPost) { + public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike, + Post previousPost, Post nextPost) { return PostDetailResponse.builder() .categoryId(post.getCategory().getId()) .categoryName(post.getCategory().getType().toString()) @@ -70,7 +71,8 @@ public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike .build(); } - public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike, boolean isRead, Post previousPost, + public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike, boolean isRead, + Post previousPost, Post nextPost) { return PostDetailResponse.builder() .categoryId(post.getCategory().getId()) @@ -99,7 +101,8 @@ public static PostDetailResponse of(Post post, boolean isLike, boolean isDislike .build(); } - public static PostDetailResponse of(Post post, String writerName, boolean isLike, boolean isDislike, + public static PostDetailResponse of(Post post, String writerName, boolean isLike, + boolean isDislike, Post previousPost, Post nextPost) { return PostDetailResponse.builder() .categoryId(post.getCategory().getId()) diff --git a/src/main/java/com/keeper/homepage/domain/post/entity/Post.java b/src/main/java/com/keeper/homepage/domain/post/entity/Post.java index 44eeba628..1146219e9 100644 --- a/src/main/java/com/keeper/homepage/domain/post/entity/Post.java +++ b/src/main/java/com/keeper/homepage/domain/post/entity/Post.java @@ -107,8 +107,10 @@ public class Post extends BaseEntity { private final Set postDislikes = new HashSet<>(); @Builder - private Post(String title, String content, Member member, Integer visitCount, String ipAddress, Boolean allowComment, - Boolean isNotice, Boolean isSecret, Boolean isTemp, String password, Category category, Thumbnail thumbnail) { + private Post(String title, String content, Member member, Integer visitCount, String ipAddress, + Boolean allowComment, + Boolean isNotice, Boolean isSecret, Boolean isTemp, String password, Category category, + Thumbnail thumbnail) { this.title = title; this.content = content; this.member = member; diff --git a/src/main/java/com/keeper/homepage/domain/seminar/README.md b/src/main/java/com/keeper/homepage/domain/seminar/README.md index 7a957c027..8759b3481 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/README.md +++ b/src/main/java/com/keeper/homepage/domain/seminar/README.md @@ -4,9 +4,11 @@ `validCloseTime` 메서드에 의해 입력 값이 `null`인지 체크하고 있습니다. -`Optional`을 사용하여 유연하게 코드를 작성할 수 있다고 생각이 들겠지만, 현재 프로그램이 동작되는 구조는 세미나가 생성되었을 때 마감 시간(`attendanceCloseTime`, `latenessCloseTime`) 값은 `null`인 상태로 생성되고 세미나 시작 기능에서 마감 시간을 설정하고 있습니다. +`Optional`을 사용하여 유연하게 코드를 작성할 수 있다고 생각이 들겠지만, 현재 프로그램이 동작되는 구조는 세미나가 생성되었을 때 마감 +시간(`attendanceCloseTime`, `latenessCloseTime`) 값은 `null`인 상태로 생성되고 세미나 시작 기능에서 마감 시간을 설정하고 있습니다. -이때 `validCloseTime` 메서드가 동작하는데 둘 다 `null`일 때는 세미나가 시작되지 않았음을 표현할 수 있고, 둘 중에 하나만 `null`일 때는 시간 검증 로직에서 오류가 발생하기 때문에 비정상적인 값이라고 판단되어 예외 처리를 하였습니다. +이때 `validCloseTime` 메서드가 동작하는데 둘 다 `null`일 때는 세미나가 시작되지 않았음을 표현할 수 있고, 둘 중에 하나만 `null`일 때는 시간 검증 +로직에서 오류가 발생하기 때문에 비정상적인 값이라고 판단되어 예외 처리를 하였습니다. 최종적으로 `validCloseTime`에 의해 검증이 끝난 후 세미나가 시작됩니다. @@ -14,13 +16,16 @@ ### `SeminarRepository`의 `findByAvailableCloseTime` 동작 방식 -`attendanceCloseTime`과 `latenessCloseTime`이 `null`이 아니고 지각 마감 시간(`latenessCloseTime`)이 현재 시간보다 이전인 세미나만 가져오는 기능입니다. +`attendanceCloseTime`과 `latenessCloseTime`이 `null`이 아니고 지각 마감 시간(`latenessCloseTime`)이 현재 시간보다 이전인 +세미나만 가져오는 기능입니다. -DB에 저장된 `virtual_seminar`는 마감 시간들이 `null`이 아닌 과거 시간이 들어있으므로 단순히 시간만 확인하면 됩니다. (`virtual_seminar`는 과거로 인식하기 때문에 조회 대상이 아닙니다.) +DB에 저장된 `virtual_seminar`는 마감 시간들이 `null`이 아닌 과거 시간이 들어있으므로 단순히 시간만 확인하면 됩니다. (`virtual_seminar`는 +과거로 인식하기 때문에 조회 대상이 아닙니다.) ### `SeminarControllerTest`의 `이용 가능한 세미나 조회 테스트`에서 API를 사용하지 않는 테스트가 있는 이유 -`현재 시간이 지각 마감 시간을 지난 경우 조회 가능한 세미나가 존재하지 않는다.`를 테스트할 때 과거 시간으로 저장된 세미나를 생성해야 하는데, `Controller`에서 과거 시간의 입력을 막아놨기 때문에 `SeminarRepository`로 생성하였습니다. +`현재 시간이 지각 마감 시간을 지난 경우 조회 가능한 세미나가 존재하지 않는다.`를 테스트할 때 과거 시간으로 저장된 세미나를 생성해야 하는데, `Controller`에서 과거 +시간의 입력을 막아놨기 때문에 `SeminarRepository`로 생성하였습니다. ### `SeminarControllerTest`의 `세미나 조회 테스트`에서 모든 데이터를 검증하지 않는 이유 diff --git a/src/main/java/com/keeper/homepage/domain/seminar/api/SeminarController.java b/src/main/java/com/keeper/homepage/domain/seminar/api/SeminarController.java index edd32cbc4..91a5aa8cc 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/api/SeminarController.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/api/SeminarController.java @@ -48,7 +48,8 @@ public ResponseEntity startSeminar( @PathVariable long seminarId, @Valid @RequestBody SeminarStartRequest request ) { - SeminarAttendanceCodeResponse response = seminarService.start(member, seminarId, request.attendanceCloseTime(), + SeminarAttendanceCodeResponse response = seminarService.start(member, seminarId, + request.attendanceCloseTime(), request.latenessCloseTime()); return ResponseEntity.status(HttpStatus.OK).body(response); } diff --git a/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceService.java b/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceService.java index 1a58b7497..f318fd64b 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceService.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceService.java @@ -47,7 +47,8 @@ public class SeminarAttendanceService { private static final int ONE_HOUR = 60 * 60; @Transactional - public SeminarAttendanceResponse attendance(Long seminarId, Member member, String attendanceCode) { + public SeminarAttendanceResponse attendance(Long seminarId, Member member, + String attendanceCode) { Seminar seminar = validSeminarFindService.findById(seminarId); SeminarAttendance seminarAttendance = getSeminarAttendance(seminar, member); @@ -71,13 +72,15 @@ private SeminarAttendance getSeminarAttendance(Seminar seminar, Member member) { .build()); } return attendanceRepository.findBySeminarAndMember(seminar, member) - .orElseThrow(() -> new BusinessException(member.getRealName(), "member", SEMINAR_ATTENDANCE_UNABLE)); + .orElseThrow( + () -> new BusinessException(member.getRealName(), "member", SEMINAR_ATTENDANCE_UNABLE)); } private void checkAttemptNumberLimit(String key) { int attemptNumber = redisUtil.increaseAndGetWithExpire(key, ONE_HOUR).intValue(); if (attemptNumber > MAX_ATTEMPT_COUNT) { - throw new BusinessException(attemptNumber, "attemptNumber", SEMINAR_ATTENDANCE_ATTEMPT_NOT_AVAILABLE); + throw new BusinessException(attemptNumber, "attemptNumber", + SEMINAR_ATTENDANCE_ATTEMPT_NOT_AVAILABLE); } } @@ -86,21 +89,25 @@ private void checkAttendanceCode(Seminar seminar, String attendanceCode, String if (!seminarAttendanceCode.equals(attendanceCode)) { String attemptNumber = redisUtil.getData(key, String.class).orElseThrow(); - throw new BusinessException(attemptNumber, "attemptNumber", SEMINAR_ATTENDANCE_CODE_NOT_AVAILABLE); + throw new BusinessException(attemptNumber, "attemptNumber", + SEMINAR_ATTENDANCE_CODE_NOT_AVAILABLE); } } private void checkDuplicateAttendance(SeminarAttendance seminarAttendance) { if (seminarAttendance.getSeminarAttendanceStatus().getType() != BEFORE_ATTENDANCE) { - throw new BusinessException(seminarAttendance.getSeminarAttendanceStatus(), "attendanceStatus", + throw new BusinessException(seminarAttendance.getSeminarAttendanceStatus(), + "attendanceStatus", SEMINAR_ATTENDANCE_DUPLICATE); } } @Transactional - public void changeStatus(long attendanceId, SeminarAttendanceStatusType statusType, String excuse) { + public void changeStatus(long attendanceId, SeminarAttendanceStatusType statusType, + String excuse) { SeminarAttendance seminarAttendance = attendanceRepository.findById(attendanceId) - .orElseThrow(() -> new BusinessException(attendanceId, "attendanceId", SEMINAR_ATTENDANCE_NOT_FOUND)); + .orElseThrow(() -> new BusinessException(attendanceId, "attendanceId", + SEMINAR_ATTENDANCE_NOT_FOUND)); if (statusType == LATENESS || statusType == PERSONAL) { seminarAttendance.changeStatus(statusType, excuse); return; @@ -121,7 +128,8 @@ public Page getAttendances(Pageable pageable) { LocalDate semesterFirstDate = SemesterUtil.getSemesterFirstDate(now); return regulars.map(member -> { - var seminarAttendances = attendanceRepository.findAllRecentByMember(member.getId(), semesterFirstDate); + var seminarAttendances = attendanceRepository.findAllRecentByMember(member.getId(), + semesterFirstDate); return SeminarAttendanceManageResponse.of(member, seminarAttendances); }); } diff --git a/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarService.java b/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarService.java index 78b0d1846..11ac2ff51 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarService.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/application/SeminarService.java @@ -78,7 +78,8 @@ private String randomAttendanceCode() { } @Transactional - public SeminarAttendanceCodeResponse start(Member starter, Long seminarId, LocalDateTime attendanceCloseTime, + public SeminarAttendanceCodeResponse start(Member starter, Long seminarId, + LocalDateTime attendanceCloseTime, LocalDateTime latenessCloseTime) { checkValidCloseTime(attendanceCloseTime, latenessCloseTime); @@ -89,7 +90,8 @@ public SeminarAttendanceCodeResponse start(Member starter, Long seminarId, Local return new SeminarAttendanceCodeResponse(seminar.getAttendanceCode()); } - private void checkValidCloseTime(LocalDateTime attendanceCloseTime, LocalDateTime latenessCloseTime) { + private void checkValidCloseTime(LocalDateTime attendanceCloseTime, + LocalDateTime latenessCloseTime) { if (attendanceCloseTime == null && latenessCloseTime == null) { return; } @@ -110,7 +112,8 @@ private static void requireNonNull(T obj, String fieldName, ErrorCode errorC } private void attendanceStarter(Seminar seminar, Member member) { - Optional seminarAttendance = seminarAttendanceRepository.findBySeminarAndMember(seminar, + Optional seminarAttendance = seminarAttendanceRepository.findBySeminarAndMember( + seminar, member); if (seminarAttendance.isPresent()) { SeminarAttendance attendance = seminarAttendance.get(); @@ -133,7 +136,8 @@ public void delete(long seminarId) { public SeminarDetailResponse findById(Member member, long seminarId) { Seminar seminar = validSeminarFindService.findById(seminarId); - var seminarAttendanceStatusType = seminarAttendanceRepository.findBySeminarAndMember(seminar, member) + var seminarAttendanceStatusType = seminarAttendanceRepository.findBySeminarAndMember(seminar, + member) .orElse(SeminarAttendance.builder() .seminarAttendanceStatus(getSeminarAttendanceStatusBy(BEFORE_ATTENDANCE)) .build()) diff --git a/src/main/java/com/keeper/homepage/domain/seminar/application/convenience/ValidSeminarFindService.java b/src/main/java/com/keeper/homepage/domain/seminar/application/convenience/ValidSeminarFindService.java index f6b48eb7b..8f170da86 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/application/convenience/ValidSeminarFindService.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/application/convenience/ValidSeminarFindService.java @@ -21,7 +21,8 @@ public class ValidSeminarFindService { private final SeminarRepository seminarRepository; public List findAll() { - return seminarRepository.findAllByIdIsNot(VIRTUAL_SEMINAR_ID, Sort.by(Sort.Direction.DESC, "openTime")).stream() + return seminarRepository.findAllByIdIsNot(VIRTUAL_SEMINAR_ID, + Sort.by(Sort.Direction.DESC, "openTime")).stream() .map(SeminarResponse::from) .toList(); } diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceExcuseRepository.java b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceExcuseRepository.java index 810cc495e..18aa147c8 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceExcuseRepository.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceExcuseRepository.java @@ -5,7 +5,8 @@ import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; -public interface SeminarAttendanceExcuseRepository extends JpaRepository { +public interface SeminarAttendanceExcuseRepository extends + JpaRepository { Optional findAllBySeminarAttendance(SeminarAttendance seminarAttendance); diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepository.java b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepository.java index 020e44c1a..92b936c72 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepository.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepository.java @@ -3,6 +3,7 @@ import com.keeper.homepage.domain.seminar.entity.SeminarAttendanceStatus; import org.springframework.data.jpa.repository.JpaRepository; -public interface SeminarAttendanceStatusRepository extends JpaRepository { +public interface SeminarAttendanceStatusRepository extends + JpaRepository { } diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarRepository.java b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarRepository.java index fbd821cb9..58aa942bb 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarRepository.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dao/SeminarRepository.java @@ -28,7 +28,8 @@ public interface SeminarRepository extends JpaRepository { + "AND DATE(s.openTime) >= :localDate " + "ORDER BY s.openTime ASC " + "LIMIT 1") - Optional findByAvailable(@Param("dateTime") LocalDateTime dateTime, @Param("localDate") LocalDate localDate); + Optional findByAvailable(@Param("dateTime") LocalDateTime dateTime, + @Param("localDate") LocalDate localDate); @Query("SELECT s FROM Seminar s " + "WHERE s.id <> 1 " // virtual seminar data 제외 @@ -52,7 +53,8 @@ public interface SeminarRepository extends JpaRepository { @Query("UPDATE Seminar s " + "SET s.starter = :virtualMember " + "WHERE s.starter = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); @Query("SELECT s FROM Seminar s " + "WHERE DATE(s.openTime) >= :localDate " diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dto/request/SeminarAttendanceStatusRequest.java b/src/main/java/com/keeper/homepage/domain/seminar/dto/request/SeminarAttendanceStatusRequest.java index 671bf0871..00d9108c0 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dto/request/SeminarAttendanceStatusRequest.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dto/request/SeminarAttendanceStatusRequest.java @@ -13,4 +13,5 @@ public record SeminarAttendanceStatusRequest( @NotNull(message = "출석 상태를 선택해주세요.") SeminarAttendanceStatusType statusType ) { + } diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarAttendanceManageResponse.java b/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarAttendanceManageResponse.java index 512086957..159be0d8b 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarAttendanceManageResponse.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarAttendanceManageResponse.java @@ -30,12 +30,14 @@ public class SeminarAttendanceManageResponse { private long totalAbsence; private long totalPersonal; - public static SeminarAttendanceManageResponse of(Member member, List seminarAttendances) { + public static SeminarAttendanceManageResponse of(Member member, + List seminarAttendances) { return SeminarAttendanceManageResponse.builder() .memberId(member.getId()) .memberName(member.getRealName()) .generation(member.getGeneration()) - .attendances(seminarAttendances.stream().map(SeminarAttendanceDetailResponse::from).toList()) + .attendances( + seminarAttendances.stream().map(SeminarAttendanceDetailResponse::from).toList()) .totalAttendance(seminarAttendances.stream() .filter(seminarAttendance -> seminarAttendance.isStatus(ATTENDANCE)) .count()) diff --git a/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarDetailResponse.java b/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarDetailResponse.java index 8e4627840..8b0ba4228 100644 --- a/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarDetailResponse.java +++ b/src/main/java/com/keeper/homepage/domain/seminar/dto/response/SeminarDetailResponse.java @@ -23,7 +23,8 @@ public class SeminarDetailResponse { private String attendanceCode; private Long starterId; - public static SeminarDetailResponse from(Seminar seminar, SeminarAttendanceStatusType seminarAttendanceStatusType) { + public static SeminarDetailResponse from(Seminar seminar, + SeminarAttendanceStatusType seminarAttendanceStatusType) { return SeminarDetailResponse.builder() .id(seminar.getId()) .name(seminar.getName()) diff --git a/src/main/java/com/keeper/homepage/domain/study/application/StudyService.java b/src/main/java/com/keeper/homepage/domain/study/application/StudyService.java index a13658d49..11f05f127 100644 --- a/src/main/java/com/keeper/homepage/domain/study/application/StudyService.java +++ b/src/main/java/com/keeper/homepage/domain/study/application/StudyService.java @@ -37,7 +37,8 @@ public class StudyService { private final MemberFindService memberFindService; @Transactional - public void create(Member headMember, Study study, List memberIds, MultipartFile thumbnail) { + public void create(Member headMember, Study study, List memberIds, + MultipartFile thumbnail) { checkLink(study); saveStudyThumbnail(study, thumbnail); diff --git a/src/main/java/com/keeper/homepage/domain/study/dao/StudyRepository.java b/src/main/java/com/keeper/homepage/domain/study/dao/StudyRepository.java index 314dbd4d0..3daefe859 100644 --- a/src/main/java/com/keeper/homepage/domain/study/dao/StudyRepository.java +++ b/src/main/java/com/keeper/homepage/domain/study/dao/StudyRepository.java @@ -16,6 +16,7 @@ public interface StudyRepository extends JpaRepository { @Query("UPDATE Study s " + "SET s.headMember = :virtualMember " + "WHERE s.headMember = :member") - void updateVirtualMember(@Param("member") Member member, @Param("virtualMember") Member virtualMember); + void updateVirtualMember(@Param("member") Member member, + @Param("virtualMember") Member virtualMember); } diff --git a/src/main/java/com/keeper/homepage/domain/study/entity/Study.java b/src/main/java/com/keeper/homepage/domain/study/entity/Study.java index 4ecfca55f..24e1b8255 100644 --- a/src/main/java/com/keeper/homepage/domain/study/entity/Study.java +++ b/src/main/java/com/keeper/homepage/domain/study/entity/Study.java @@ -78,7 +78,8 @@ public class Study extends BaseEntity { private final Set studyMembers = new HashSet<>(); @Builder - private Study(String title, String information, Integer year, Integer season, Link link, Thumbnail thumbnail, + private Study(String title, String information, Integer year, Integer season, Link link, + Thumbnail thumbnail, Member headMember) { this.title = title; this.information = information; diff --git a/src/main/java/com/keeper/homepage/domain/survey/entity/Survey.java b/src/main/java/com/keeper/homepage/domain/survey/entity/Survey.java index 43db7efe3..a470f3a26 100644 --- a/src/main/java/com/keeper/homepage/domain/survey/entity/Survey.java +++ b/src/main/java/com/keeper/homepage/domain/survey/entity/Survey.java @@ -52,7 +52,8 @@ public Boolean isVisible() { } @Builder - private Survey(LocalDateTime openTime, LocalDateTime closeTime, String name, String description, Boolean isVisible) { + private Survey(LocalDateTime openTime, LocalDateTime closeTime, String name, String description, + Boolean isVisible) { this.openTime = openTime; this.closeTime = closeTime; this.name = name; diff --git a/src/main/java/com/keeper/homepage/domain/survey/entity/SurveyMemberReply.java b/src/main/java/com/keeper/homepage/domain/survey/entity/SurveyMemberReply.java index 8c3969a5e..035a4c1a7 100644 --- a/src/main/java/com/keeper/homepage/domain/survey/entity/SurveyMemberReply.java +++ b/src/main/java/com/keeper/homepage/domain/survey/entity/SurveyMemberReply.java @@ -49,7 +49,8 @@ public class SurveyMemberReply { private SurveyReplyExcuse replyExcuse; @Builder - private SurveyMemberReply(Member member, Survey survey, SurveyReply reply, LocalDateTime replyTime) { + private SurveyMemberReply(Member member, Survey survey, SurveyReply reply, + LocalDateTime replyTime) { this.member = member; this.survey = survey; this.reply = reply; diff --git a/src/main/java/com/keeper/homepage/global/config/interceptor/AttendanceInterceptor.java b/src/main/java/com/keeper/homepage/global/config/interceptor/AttendanceInterceptor.java index 121a0a600..a219216c3 100644 --- a/src/main/java/com/keeper/homepage/global/config/interceptor/AttendanceInterceptor.java +++ b/src/main/java/com/keeper/homepage/global/config/interceptor/AttendanceInterceptor.java @@ -20,7 +20,8 @@ public class AttendanceInterceptor implements HandlerInterceptor { private final RedisUtil redisUtil; @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { diff --git a/src/main/java/com/keeper/homepage/global/config/p6spy/PrettySqlFormat.java b/src/main/java/com/keeper/homepage/global/config/p6spy/PrettySqlFormat.java index 8e8574d92..5eee881de 100644 --- a/src/main/java/com/keeper/homepage/global/config/p6spy/PrettySqlFormat.java +++ b/src/main/java/com/keeper/homepage/global/config/p6spy/PrettySqlFormat.java @@ -11,28 +11,30 @@ @Configuration public class PrettySqlFormat implements MessageFormattingStrategy { - @PostConstruct - public void setLogMessageFormat() { - P6SpyOptions.getActiveInstance().setLogMessageFormat(this.getClass().getName()); - } + @PostConstruct + public void setLogMessageFormat() { + P6SpyOptions.getActiveInstance().setLogMessageFormat(this.getClass().getName()); + } - @Override - public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { - sql = formatSql(category, sql); - return "[%s] | %d ms | %s".formatted(category, elapsed, formatSql(category, sql)); - } + @Override + public String formatMessage(int connectionId, String now, long elapsed, String category, + String prepared, String sql, String url) { + sql = formatSql(category, sql); + return "[%s] | %d ms | %s".formatted(category, elapsed, formatSql(category, sql)); + } - private String formatSql(String category, String sql) { - if (sql != null && !sql.trim().isEmpty() && Category.STATEMENT.getName().equals(category)) { - String trimmedSQL = sql.trim().toLowerCase(Locale.ROOT); - if (trimmedSQL.startsWith("create") || trimmedSQL.startsWith("alter") || trimmedSQL.startsWith("comment")) { - sql = FormatStyle.DDL.getFormatter().format(sql); - } else { - sql = FormatStyle.BASIC.getFormatter().format(sql); - } - return sql; - } - return sql; + private String formatSql(String category, String sql) { + if (sql != null && !sql.trim().isEmpty() && Category.STATEMENT.getName().equals(category)) { + String trimmedSQL = sql.trim().toLowerCase(Locale.ROOT); + if (trimmedSQL.startsWith("create") || trimmedSQL.startsWith("alter") + || trimmedSQL.startsWith("comment")) { + sql = FormatStyle.DDL.getFormatter().format(sql); + } else { + sql = FormatStyle.BASIC.getFormatter().format(sql); + } + return sql; } + return sql; + } } diff --git a/src/main/java/com/keeper/homepage/global/config/password/PasswordFactory.java b/src/main/java/com/keeper/homepage/global/config/password/PasswordFactory.java index e57d87ce2..2d92fa744 100644 --- a/src/main/java/com/keeper/homepage/global/config/password/PasswordFactory.java +++ b/src/main/java/com/keeper/homepage/global/config/password/PasswordFactory.java @@ -32,7 +32,8 @@ public boolean matches(CharSequence rawPassword, String encodedPassword) { || matchesWithMD5(rawPassword.toString(), encodedPassword); } - private boolean isMatchInDelegatingPasswordEncoder(CharSequence rawPassword, String encodedPassword) { + private boolean isMatchInDelegatingPasswordEncoder(CharSequence rawPassword, + String encodedPassword) { try { return createDelegatingPasswordEncoder().matches(rawPassword, encodedPassword); } catch (Exception ignore) { diff --git a/src/main/java/com/keeper/homepage/global/config/security/JwtTokenProvider.java b/src/main/java/com/keeper/homepage/global/config/security/JwtTokenProvider.java index 0bfc8d036..d09bb47fd 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/JwtTokenProvider.java +++ b/src/main/java/com/keeper/homepage/global/config/security/JwtTokenProvider.java @@ -44,7 +44,8 @@ public class JwtTokenProvider { final Key secretKey; public static String getRefreshTokenKeyForRedis(String authId, String userAgent) { - String encodedUserAgent = Base64.getEncoder().encodeToString((userAgent == null ? "" : userAgent).getBytes()); + String encodedUserAgent = Base64.getEncoder() + .encodeToString((userAgent == null ? "" : userAgent).getBytes()); return "refreshToken:" + authId + ":" + encodedUserAgent; } diff --git a/src/main/java/com/keeper/homepage/global/config/security/filter/RefreshTokenFilter.java b/src/main/java/com/keeper/homepage/global/config/security/filter/RefreshTokenFilter.java index e18049203..6f0d37ddc 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/filter/RefreshTokenFilter.java +++ b/src/main/java/com/keeper/homepage/global/config/security/filter/RefreshTokenFilter.java @@ -26,25 +26,29 @@ @Component public class RefreshTokenFilter extends GenericFilterBean { - private final JwtTokenProvider jwtTokenProvider; - private final JwtTokenConditionFactory jwtTokenConditionFactory; - private final AuthCookieService authCookieService; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) - throws IOException, ServletException { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - final var accessTokenDto = jwtTokenProvider.tryCheckTokenValid(httpRequest, ACCESS_TOKEN); - final var refreshTokenDto = jwtTokenProvider.tryCheckTokenValid(httpRequest, REFRESH_TOKEN); - List jwtTokenConditions = jwtTokenConditionFactory.createJwtTokenConditions(); - - jwtTokenConditions.stream() - .filter(jwtTokenCondition -> jwtTokenCondition.isSatisfiedBy(accessTokenDto, refreshTokenDto, httpRequest)) - .findFirst() - .ifPresentOrElse(jwtTokenCondition -> jwtTokenCondition.setJwtToken(accessTokenDto, refreshTokenDto, httpRequest, httpResponse), - () -> authCookieService.setCookieExpired(httpResponse)); - - filterChain.doFilter(request, response); - } + private final JwtTokenProvider jwtTokenProvider; + private final JwtTokenConditionFactory jwtTokenConditionFactory; + private final AuthCookieService authCookieService; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) + throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + final var accessTokenDto = jwtTokenProvider.tryCheckTokenValid(httpRequest, ACCESS_TOKEN); + final var refreshTokenDto = jwtTokenProvider.tryCheckTokenValid(httpRequest, REFRESH_TOKEN); + List jwtTokenConditions = jwtTokenConditionFactory.createJwtTokenConditions(); + + jwtTokenConditions.stream() + .filter( + jwtTokenCondition -> jwtTokenCondition.isSatisfiedBy(accessTokenDto, refreshTokenDto, + httpRequest)) + .findFirst() + .ifPresentOrElse( + jwtTokenCondition -> jwtTokenCondition.setJwtToken(accessTokenDto, refreshTokenDto, + httpRequest, httpResponse), + () -> authCookieService.setCookieExpired(httpResponse)); + + filterChain.doFilter(request, response); + } } diff --git a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/AccessTokenReissueCondition.java b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/AccessTokenReissueCondition.java index bf372228a..cbf861c80 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/AccessTokenReissueCondition.java +++ b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/AccessTokenReissueCondition.java @@ -17,33 +17,36 @@ @RequiredArgsConstructor public class AccessTokenReissueCondition implements JwtTokenCondition { - private final AuthCookieService authCookieService; - private final JwtTokenProvider jwtTokenProvider; - private final RedisUtil redisUtil; - - @Override - public boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, - TokenValidationResultDto refreshTokenDto, - HttpServletRequest httpRequest) { - return isTokenExpired(accessTokenDto) && - isTokenValid(refreshTokenDto) && - isTokenInRedis(refreshTokenDto, httpRequest.getHeader(USER_AGENT)); - } - - @Override - public void setJwtToken(TokenValidationResultDto accessTokenDto, TokenValidationResultDto refreshTokenDto, - HttpServletRequest httpRequest, HttpServletResponse httpResponse) { - setAuthentication(jwtTokenProvider, refreshTokenDto); - - String authId = String.valueOf(jwtTokenProvider.getAuthId(refreshTokenDto.getToken())); - String[] roles = jwtTokenProvider.getRoles(refreshTokenDto.getToken()); - authCookieService.setNewCookieInResponse(authId, roles, httpRequest.getHeader(USER_AGENT), httpResponse); - } - - private boolean isTokenInRedis(TokenValidationResultDto refreshTokenDto, String userAgent) { - long authId = jwtTokenProvider.getAuthId(refreshTokenDto.getToken()); - String refreshTokenKey = JwtTokenProvider.getRefreshTokenKeyForRedis(String.valueOf(authId), userAgent); - Optional tokenInRedis = redisUtil.getData(refreshTokenKey, String.class); - return tokenInRedis.isPresent() && tokenInRedis.get().equals(refreshTokenDto.getToken()); - } + private final AuthCookieService authCookieService; + private final JwtTokenProvider jwtTokenProvider; + private final RedisUtil redisUtil; + + @Override + public boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest httpRequest) { + return isTokenExpired(accessTokenDto) && + isTokenValid(refreshTokenDto) && + isTokenInRedis(refreshTokenDto, httpRequest.getHeader(USER_AGENT)); + } + + @Override + public void setJwtToken(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest httpRequest, HttpServletResponse httpResponse) { + setAuthentication(jwtTokenProvider, refreshTokenDto); + + String authId = String.valueOf(jwtTokenProvider.getAuthId(refreshTokenDto.getToken())); + String[] roles = jwtTokenProvider.getRoles(refreshTokenDto.getToken()); + authCookieService.setNewCookieInResponse(authId, roles, httpRequest.getHeader(USER_AGENT), + httpResponse); + } + + private boolean isTokenInRedis(TokenValidationResultDto refreshTokenDto, String userAgent) { + long authId = jwtTokenProvider.getAuthId(refreshTokenDto.getToken()); + String refreshTokenKey = JwtTokenProvider.getRefreshTokenKeyForRedis(String.valueOf(authId), + userAgent); + Optional tokenInRedis = redisUtil.getData(refreshTokenKey, String.class); + return tokenInRedis.isPresent() && tokenInRedis.get().equals(refreshTokenDto.getToken()); + } } diff --git a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenCondition.java b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenCondition.java index d6a86190c..cac1eb276 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenCondition.java +++ b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenCondition.java @@ -11,25 +11,26 @@ public interface JwtTokenCondition { - boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, - TokenValidationResultDto refreshTokenDto, - HttpServletRequest httpRequest); - - void setJwtToken(TokenValidationResultDto accessTokenDto, TokenValidationResultDto refreshTokenDto, - HttpServletRequest request, HttpServletResponse response); - - default void setAuthentication(JwtTokenProvider jwtTokenProvider, - TokenValidationResultDto jwtTokenDto) { - SecurityContextHolder.getContext() - .setAuthentication(jwtTokenProvider.getAuthentication(jwtTokenDto.getToken())); - } - - default boolean isTokenValid(TokenValidationResultDto jwtTokenDto) { - return jwtTokenDto.getResultType() == VALID; - } - - default boolean isTokenExpired(TokenValidationResultDto jwtTokenDto) { - return jwtTokenDto.getResultType() == EXPIRED; - } + boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest httpRequest); + + void setJwtToken(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest request, HttpServletResponse response); + + default void setAuthentication(JwtTokenProvider jwtTokenProvider, + TokenValidationResultDto jwtTokenDto) { + SecurityContextHolder.getContext() + .setAuthentication(jwtTokenProvider.getAuthentication(jwtTokenDto.getToken())); + } + + default boolean isTokenValid(TokenValidationResultDto jwtTokenDto) { + return jwtTokenDto.getResultType() == VALID; + } + + default boolean isTokenExpired(TokenValidationResultDto jwtTokenDto) { + return jwtTokenDto.getResultType() == EXPIRED; + } } diff --git a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenConditionFactory.java b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenConditionFactory.java index 658709aa2..e9f728b02 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenConditionFactory.java +++ b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenConditionFactory.java @@ -9,10 +9,10 @@ @RequiredArgsConstructor public class JwtTokenConditionFactory { - private final JwtTokenValidCondition jwtTokenValidCondition; - private final AccessTokenReissueCondition accessTokenReissueCondition; + private final JwtTokenValidCondition jwtTokenValidCondition; + private final AccessTokenReissueCondition accessTokenReissueCondition; - public List createJwtTokenConditions() { - return List.of(jwtTokenValidCondition, accessTokenReissueCondition); - } + public List createJwtTokenConditions() { + return List.of(jwtTokenValidCondition, accessTokenReissueCondition); + } } diff --git a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenValidCondition.java b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenValidCondition.java index b7321d54a..e9fdf4cc0 100644 --- a/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenValidCondition.java +++ b/src/main/java/com/keeper/homepage/global/config/security/filter/token_condition/JwtTokenValidCondition.java @@ -11,17 +11,19 @@ @RequiredArgsConstructor public class JwtTokenValidCondition implements JwtTokenCondition { - private final JwtTokenProvider jwtTokenProvider; + private final JwtTokenProvider jwtTokenProvider; - @Override - public boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, TokenValidationResultDto refreshTokenDto, - HttpServletRequest httpRequest) { - return accessTokenDto.isValid(); - } + @Override + public boolean isSatisfiedBy(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest httpRequest) { + return accessTokenDto.isValid(); + } - @Override - public void setJwtToken(TokenValidationResultDto accessTokenDto, TokenValidationResultDto refreshTokenDto, - HttpServletRequest request, HttpServletResponse response) { - setAuthentication(jwtTokenProvider, accessTokenDto); - } + @Override + public void setJwtToken(TokenValidationResultDto accessTokenDto, + TokenValidationResultDto refreshTokenDto, + HttpServletRequest request, HttpServletResponse response) { + setAuthentication(jwtTokenProvider, accessTokenDto); + } } diff --git a/src/main/java/com/keeper/homepage/global/config/web/WebMvcConfiguration.java b/src/main/java/com/keeper/homepage/global/config/web/WebMvcConfiguration.java index f46992688..eb1b8ef20 100644 --- a/src/main/java/com/keeper/homepage/global/config/web/WebMvcConfiguration.java +++ b/src/main/java/com/keeper/homepage/global/config/web/WebMvcConfiguration.java @@ -25,7 +25,8 @@ public class WebMvcConfiguration implements WebMvcConfigurer { private final LoginMemberArgumentResolver loginMemberArgumentResolver; private final AttendanceInterceptor attendanceInterceptor; - private static final String[] ATTENDANCE_PATH = {"/posts/trend", "/members/point-rank", "/attendances/point"}; + private static final String[] ATTENDANCE_PATH = {"/posts/trend", "/members/point-rank", + "/attendances/point"}; @Override public void addArgumentResolvers(List resolvers) { diff --git a/src/main/java/com/keeper/homepage/global/error/ErrorCode.java b/src/main/java/com/keeper/homepage/global/error/ErrorCode.java index 7f57a78d4..bc451b945 100644 --- a/src/main/java/com/keeper/homepage/global/error/ErrorCode.java +++ b/src/main/java/com/keeper/homepage/global/error/ErrorCode.java @@ -33,7 +33,8 @@ public enum ErrorCode { SEMINAR_TIME_NOT_AVAILABLE("올바르지 않은 시간 값입니다", HttpStatus.BAD_REQUEST), SEMINAR_ATTENDANCE_NOT_FOUND("해당 세미나 출석을 찾을 수 없습니다.", HttpStatus.NOT_FOUND), SEMINAR_ATTENDANCE_CODE_NOT_AVAILABLE("올바르지 않은 출석 코드입니다.", HttpStatus.BAD_REQUEST), - SEMINAR_ATTENDANCE_ATTEMPT_NOT_AVAILABLE("출석코드 입력 가능 횟수를 초과하여 출석이 불가능합니다.", HttpStatus.BAD_REQUEST), + SEMINAR_ATTENDANCE_ATTEMPT_NOT_AVAILABLE("출석코드 입력 가능 횟수를 초과하여 출석이 불가능합니다.", + HttpStatus.BAD_REQUEST), SEMINAR_ATTENDANCE_DUPLICATE("이미 출석을 완료한 계정입니다.", HttpStatus.CONFLICT), SEMINAR_ATTENDANCE_UNABLE("정회원이 아닌 회원은 출석이 불가합니다.", HttpStatus.BAD_REQUEST), // POST @@ -57,7 +58,8 @@ public enum ErrorCode { BOOK_DELETE_FAILED_IN_BORROWING("누군가가 책을 빌리고 있어 책을 삭제할 수 없습니다.", HttpStatus.BAD_REQUEST), BOOK_CANNOT_BORROW("책을 빌릴 수 없습니다.", HttpStatus.BAD_REQUEST), BOOK_CANNOT_RETURN_EXCEED_TOTAL_QUANTITY("전체 수량을 초과하여 책을 반납할 수 없습니다.", HttpStatus.BAD_REQUEST), - BOOK_CANNOT_UPDATE_EXCEED_CURRENT_QUANTITY("현재 대여중인 수량보다 적은 수량으로 변경할 수 없습니다.", HttpStatus.BAD_REQUEST), + BOOK_CANNOT_UPDATE_EXCEED_CURRENT_QUANTITY("현재 대여중인 수량보다 적은 수량으로 변경할 수 없습니다.", + HttpStatus.BAD_REQUEST), BOOK_SEARCH_TYPE_NOT_FOUND("올바르지 않은 검색 타입입니다.", HttpStatus.BAD_REQUEST), BOOK_BORROWING_COUNT_OVER("대출 신청 가능 수량을 초과했습니다.", HttpStatus.BAD_REQUEST), BOOK_CURRENT_QUANTITY_IS_ZERO("현재 수량이 없는 책은 대출 신청이 불가합니다.", HttpStatus.BAD_REQUEST), @@ -82,6 +84,7 @@ public enum ErrorCode { NOT_ENOUGH_POINT("베팅 포인트는 보유한 포인트보다 많을 수 없습니다.", HttpStatus.BAD_REQUEST), POINT_MUST_BE_POSITIVE("베팅 포인트는 양수여야 합니다.", HttpStatus.BAD_REQUEST), NOT_PLAYED_YET("아직 게임을 시작하지 않았습니다.", HttpStatus.BAD_REQUEST), + INVALID_GAME_POINT("1000점에서 3000점 사이의 베팅 포인트를 입력하여야 합니다.", HttpStatus.BAD_REQUEST), // FILE FILE_NOT_FOUND("해당 파일은 존재하지 않습니다.", HttpStatus.BAD_REQUEST), // ATTENDANCE diff --git a/src/main/java/com/keeper/homepage/global/error/ExceptionAdvice.java b/src/main/java/com/keeper/homepage/global/error/ExceptionAdvice.java index 25b5f6264..fba2f8b99 100644 --- a/src/main/java/com/keeper/homepage/global/error/ExceptionAdvice.java +++ b/src/main/java/com/keeper/homepage/global/error/ExceptionAdvice.java @@ -31,7 +31,8 @@ public ResponseEntity accessDeniedException(AccessDeniedException } @ExceptionHandler(ConstraintViolationException.class) - public ResponseEntity constraintViolationException(ConstraintViolationException e) { + public ResponseEntity constraintViolationException( + ConstraintViolationException e) { return ResponseEntity.badRequest() .body(ErrorResponse.from(e.getMessage())); } diff --git a/src/main/java/com/keeper/homepage/global/util/aop/PreparedStatementProxyHandler.java b/src/main/java/com/keeper/homepage/global/util/aop/PreparedStatementProxyHandler.java index 92b237d27..b9f6eb375 100644 --- a/src/main/java/com/keeper/homepage/global/util/aop/PreparedStatementProxyHandler.java +++ b/src/main/java/com/keeper/homepage/global/util/aop/PreparedStatementProxyHandler.java @@ -13,7 +13,7 @@ public class PreparedStatementProxyHandler implements private static final List JDBC_QUERY_METHOD = List.of("executeQuery", "execute", "executeUpdate"); - + private final Object preparedStatement; private final ApiStatistic apiStatistic; diff --git a/src/main/java/com/keeper/homepage/global/util/semester/SemesterUtil.java b/src/main/java/com/keeper/homepage/global/util/semester/SemesterUtil.java index 1a78c8afd..f384abf3a 100644 --- a/src/main/java/com/keeper/homepage/global/util/semester/SemesterUtil.java +++ b/src/main/java/com/keeper/homepage/global/util/semester/SemesterUtil.java @@ -20,7 +20,8 @@ public class SemesterUtil { private static final List FIRST_SEMESTER = List.of(MARCH, APRIL, MAY, JUNE, JULY, AUGUST); - private static final List SECOND_SEMESTER = List.of(SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, JANUARY, FEBRUARY); + private static final List SECOND_SEMESTER = List.of(SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, + JANUARY, FEBRUARY); public static LocalDate getSemesterFirstDate(LocalDate now) { if (FIRST_SEMESTER.contains(now.getMonth())) { diff --git a/src/main/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidator.java b/src/main/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidator.java index dcddb282a..418adca70 100644 --- a/src/main/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidator.java +++ b/src/main/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidator.java @@ -7,7 +7,8 @@ class ThumbnailServerValidator { - public static void checkInvalidImageFile(byte[] fileData, String originalFilename) throws IOException { + public static void checkInvalidImageFile(byte[] fileData, String originalFilename) + throws IOException { if (isNotImageFile(fileData)) { throw new IllegalArgumentException("파일이 이미지가 아닙니다. 파일 이름: " + originalFilename); } diff --git a/src/test/java/com/keeper/homepage/domain/auth/api/SignOutControllerTest.java b/src/test/java/com/keeper/homepage/domain/auth/api/SignOutControllerTest.java index d788f6910..9fb37bf5d 100644 --- a/src/test/java/com/keeper/homepage/domain/auth/api/SignOutControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/auth/api/SignOutControllerTest.java @@ -26,36 +26,36 @@ class SignOutControllerTest extends IntegrationTest { - @Nested - @DisplayName("로그아웃 테스트") - class SignOut { + @Nested + @DisplayName("로그아웃 테스트") + class SignOut { - private Member member; + private Member member; - @BeforeEach - void setupMember() { - member = memberTestHelper.generate(); - } + @BeforeEach + void setupMember() { + member = memberTestHelper.generate(); + } - @Test - @DisplayName("유효한 요청이면 로그아웃이 성공해야 한다.") - void should_successfullySignOut_when_validRequest() throws Exception { - Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN.getTokenName(), - jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원)); - Cookie refreshTokenCookie = new Cookie(REFRESH_TOKEN.getTokenName(), - jwtTokenProvider.createAccessToken(REFRESH_TOKEN, member.getId(), ROLE_회원)); - callSignOutApi(accessTokenCookie, refreshTokenCookie) - .andExpect(status().isNoContent()) - .andExpect(cookie().maxAge(ACCESS_TOKEN.getTokenName(), 0)) - .andExpect(cookie().maxAge(REFRESH_TOKEN.getTokenName(), 0)) - .andDo(document("sign-out", - requestCookies( - cookieWithName(ACCESS_TOKEN.getTokenName()).description("ACCESS TOKEN"), - cookieWithName(REFRESH_TOKEN.getTokenName()).description("REFRESH TOKEN") - ))); + @Test + @DisplayName("유효한 요청이면 로그아웃이 성공해야 한다.") + void should_successfullySignOut_when_validRequest() throws Exception { + Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN.getTokenName(), + jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원)); + Cookie refreshTokenCookie = new Cookie(REFRESH_TOKEN.getTokenName(), + jwtTokenProvider.createAccessToken(REFRESH_TOKEN, member.getId(), ROLE_회원)); + callSignOutApi(accessTokenCookie, refreshTokenCookie) + .andExpect(status().isNoContent()) + .andExpect(cookie().maxAge(ACCESS_TOKEN.getTokenName(), 0)) + .andExpect(cookie().maxAge(REFRESH_TOKEN.getTokenName(), 0)) + .andDo(document("sign-out", + requestCookies( + cookieWithName(ACCESS_TOKEN.getTokenName()).description("ACCESS TOKEN"), + cookieWithName(REFRESH_TOKEN.getTokenName()).description("REFRESH TOKEN") + ))); - assertThat(redisUtil.getData(String.valueOf(member.getId()), String.class)).isEmpty(); - } + assertThat(redisUtil.getData(String.valueOf(member.getId()), String.class)).isEmpty(); + } // @Test // @Disabled @@ -75,10 +75,11 @@ void should_successfullySignOut_when_validRequest() throws Exception { // .andExpect(cookie().maxAge(REFRESH_TOKEN.getTokenName(), 0)); // } - @NotNull - private ResultActions callSignOutApi(Cookie accessTokenCookie, Cookie refreshTokenCookie) throws Exception { - return mockMvc.perform(post("/sign-out") - .cookie(accessTokenCookie, refreshTokenCookie)); - } + @NotNull + private ResultActions callSignOutApi(Cookie accessTokenCookie, Cookie refreshTokenCookie) + throws Exception { + return mockMvc.perform(post("/sign-out") + .cookie(accessTokenCookie, refreshTokenCookie)); } + } } diff --git a/src/test/java/com/keeper/homepage/domain/auth/api/test/AuthTestControllerTest.java b/src/test/java/com/keeper/homepage/domain/auth/api/test/AuthTestControllerTest.java index 658a6fe82..7464a9936 100644 --- a/src/test/java/com/keeper/homepage/domain/auth/api/test/AuthTestControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/auth/api/test/AuthTestControllerTest.java @@ -180,7 +180,8 @@ class Exist { @BeforeEach void setupRefreshToken() { - redisUtil.setDataExpire(JwtTokenProvider.getRefreshTokenKeyForRedis("0", null), refreshToken, REFRESH_TOKEN.getExpiredMillis()); + redisUtil.setDataExpire(JwtTokenProvider.getRefreshTokenKeyForRedis("0", null), + refreshToken, REFRESH_TOKEN.getExpiredMillis()); } // @Test diff --git a/src/test/java/com/keeper/homepage/domain/comment/api/CommentApiTestHelper.java b/src/test/java/com/keeper/homepage/domain/comment/api/CommentApiTestHelper.java index 56e9148de..28fc59f11 100644 --- a/src/test/java/com/keeper/homepage/domain/comment/api/CommentApiTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/comment/api/CommentApiTestHelper.java @@ -14,7 +14,8 @@ public class CommentApiTestHelper extends IntegrationTest { - ResultActions callCreateCommentApi(String memberToken, CommentCreateRequest request) throws Exception { + ResultActions callCreateCommentApi(String memberToken, CommentCreateRequest request) + throws Exception { return mockMvc.perform(post("/comments") .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken)) .content(asJsonString(request)) diff --git a/src/test/java/com/keeper/homepage/domain/ctf/api/CtfTeamControllerTest.java b/src/test/java/com/keeper/homepage/domain/ctf/api/CtfTeamControllerTest.java index b213f830e..7ba7af3a0 100644 --- a/src/test/java/com/keeper/homepage/domain/ctf/api/CtfTeamControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/ctf/api/CtfTeamControllerTest.java @@ -204,10 +204,11 @@ class CtfTeamJoinAndLeaveTest { .contestId(ctfContest.getId()) .build(); - mockMvc.perform(post("/ctf/teams/{teamId}/members/{memberId}", ctfTeam.getId(), member.getId()) - .content(asJsonString(request)) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken)) - .contentType(MediaType.APPLICATION_JSON)) + mockMvc.perform( + post("/ctf/teams/{teamId}/members/{memberId}", ctfTeam.getId(), member.getId()) + .content(asJsonString(request)) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andDo(document("join-ctf-team", requestCookies( @@ -230,8 +231,9 @@ class CtfTeamJoinAndLeaveTest { CtfTeam ctfTeam = ctfTeamTestHelper.generate(); member.join(ctfTeam); - mockMvc.perform(delete("/ctf/teams/{teamId}/members/{memberId}", ctfTeam.getId(), member.getId()) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken))) + mockMvc.perform( + delete("/ctf/teams/{teamId}/members/{memberId}", ctfTeam.getId(), member.getId()) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken))) .andExpect(status().isNoContent()) .andDo(document("leave-ctf-team", requestCookies( diff --git a/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeCategoryRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeCategoryRepositoryTest.java index 69574b4a6..0f3892c15 100644 --- a/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeCategoryRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeCategoryRepositoryTest.java @@ -21,7 +21,8 @@ class CtfChallengeCategoryTest { @DisplayName("CtfChallengeCategoryType Enum에 DB의 모든 데이터가 있어야 한다.") public void CtfChallengeCategoryType_Enum에_DB의_모든_데이터가_있어야_한다() throws Exception { List ctfChallengeCategories = ctfChallengeCategoryRepository.findAll(); - List ctfChallengeCategoryTypes = Arrays.stream(CtfChallengeCategoryType.values()) + List ctfChallengeCategoryTypes = Arrays.stream( + CtfChallengeCategoryType.values()) .map(CtfChallengeCategory::getCtfChallengeCategoryBy) .toList(); diff --git a/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeRepositoryTest.java index d4991a4f3..96eb809f3 100644 --- a/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/ctf/dao/CtfChallengeRepositoryTest.java @@ -42,7 +42,8 @@ class CtfChallengeTypeTest { CtfChallenge findChallenge = ctfChallengeRepository.getReferenceById(ctfChallenge.getId()); assertThat(findChallenge.getCtfDynamicChallengeInfo()).isNotNull(); - assertThat(findChallenge.getCtfDynamicChallengeInfo().getCtfChallenge()).isEqualTo(findChallenge); + assertThat(findChallenge.getCtfDynamicChallengeInfo().getCtfChallenge()).isEqualTo( + findChallenge); assertThat(findChallenge.getCtfDynamicChallengeInfo().getMinScore()).isEqualTo(500); assertThat(findChallenge.getCtfDynamicChallengeInfo().getMaxScore()).isEqualTo(1000); } @@ -54,7 +55,8 @@ class CtfChallengeTypeTest { .type(STANDARD) .build(); - assertThatThrownBy(() -> ctfChallenge.setCtfDynamicChallengeInfo(CtfDynamicChallengeInfo.builder().build())) + assertThatThrownBy( + () -> ctfChallenge.setCtfDynamicChallengeInfo(CtfDynamicChallengeInfo.builder().build())) .isInstanceOf(IllegalStateException.class); } } diff --git a/src/test/java/com/keeper/homepage/domain/election/api/AdminElectionApiTestHelper.java b/src/test/java/com/keeper/homepage/domain/election/api/AdminElectionApiTestHelper.java index 9fa9bc604..5bf0055dc 100644 --- a/src/test/java/com/keeper/homepage/domain/election/api/AdminElectionApiTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/election/api/AdminElectionApiTestHelper.java @@ -21,7 +21,8 @@ public class AdminElectionApiTestHelper extends IntegrationTest { - ResultActions callCreateElectionApi(String adminToken, ElectionCreateRequest request) throws Exception { + ResultActions callCreateElectionApi(String adminToken, ElectionCreateRequest request) + throws Exception { return mockMvc.perform(post("/admin/elections") .content(asJsonString(request)) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken)) @@ -33,7 +34,8 @@ ResultActions callDeleteElectionApi(String adminToken, long electionId) throws E .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))); } - ResultActions callUpdateElectionApi(String adminToken, long electionId, ElectionUpdateRequest request) + ResultActions callUpdateElectionApi(String adminToken, long electionId, + ElectionUpdateRequest request) throws Exception { return mockMvc.perform(put("/admin/elections/{electionId}", electionId) .content(asJsonString(request)) @@ -56,15 +58,18 @@ FieldDescriptor[] getElectionResponse() { } - ResultActions callRegisterCandidateApi(String adminToken, ElectionCandidateRegisterRequest request, long electionId, + ResultActions callRegisterCandidateApi(String adminToken, + ElectionCandidateRegisterRequest request, long electionId, long candidateId) throws Exception { - return mockMvc.perform(post("/admin/elections/{electionId}/candidates/{candidateId}", electionId, candidateId) - .content(asJsonString(request)) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken)) - .contentType(MediaType.APPLICATION_JSON)); + return mockMvc.perform( + post("/admin/elections/{electionId}/candidates/{candidateId}", electionId, candidateId) + .content(asJsonString(request)) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken)) + .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callRegisterCandidatesApi(String adminToken, ElectionCandidatesRegisterRequest request, long electionId) + ResultActions callRegisterCandidatesApi(String adminToken, + ElectionCandidatesRegisterRequest request, long electionId) throws Exception { return mockMvc.perform(post("/admin/elections/{electionId}/candidates", electionId) .content(asJsonString(request)) @@ -72,12 +77,15 @@ ResultActions callRegisterCandidatesApi(String adminToken, ElectionCandidatesReg .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callDeleteCandidateApi(String adminToken, long electionId, long candidateId) throws Exception { - return mockMvc.perform(delete("/admin/elections/{electionId}/candidates/{candidateId}", electionId, candidateId) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))); + ResultActions callDeleteCandidateApi(String adminToken, long electionId, long candidateId) + throws Exception { + return mockMvc.perform( + delete("/admin/elections/{electionId}/candidates/{candidateId}", electionId, candidateId) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))); } - ResultActions callRegisterVotersApi(String adminToken, ElectionVotersRequest request, long electionId) + ResultActions callRegisterVotersApi(String adminToken, ElectionVotersRequest request, + long electionId) throws Exception { return mockMvc.perform(post("/admin/elections/{electionId}/voters", electionId) .content(asJsonString(request)) @@ -85,7 +93,8 @@ ResultActions callRegisterVotersApi(String adminToken, ElectionVotersRequest req .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callDeleteVotersApi(String adminToken, ElectionVotersRequest request, long electionId) + ResultActions callDeleteVotersApi(String adminToken, ElectionVotersRequest request, + long electionId) throws Exception { return mockMvc.perform(delete("/admin/elections/{electionId}/voters", electionId) .content(asJsonString(request)) diff --git a/src/test/java/com/keeper/homepage/domain/election/api/AdminTestElectionControllerTest.java b/src/test/java/com/keeper/homepage/domain/election/api/AdminTestElectionControllerTest.java index afa5fab48..734e783a3 100644 --- a/src/test/java/com/keeper/homepage/domain/election/api/AdminTestElectionControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/election/api/AdminTestElectionControllerTest.java @@ -262,7 +262,8 @@ class CandidateRegisterAndDeleteTest { .memberJobId(memberJobId) .build(); - Set> violations = validator.validate(request); + Set> violations = validator.validate( + request); assertEquals(1, violations.size()); } @@ -275,7 +276,8 @@ class CandidateRegisterAndDeleteTest { long memberJobId = ROLE_회장.getId(); MemberJob memberJob = memberJobRepository.findById(memberJobId).orElseThrow(); Election election = electionTestHelper.builder().isAvailable(false).build(); - ElectionCandidate electionCandidate = electionCandidateTestHelper.builder(memberJob).election(election).build(); + ElectionCandidate electionCandidate = electionCandidateTestHelper.builder(memberJob) + .election(election).build(); long electionId = electionCandidate.getElection().getId(); long candidateId = electionCandidate.getId(); @@ -337,7 +339,8 @@ class VoterRegisterAndDeleteTest { Election election = electionTestHelper.builder().isAvailable(false).build(); long electionId = election.getId(); List voterIds = IntStream.range(0, 5) - .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build().getMember().getId()) + .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build() + .getMember().getId()) .collect(toList()); ElectionVotersRequest request = ElectionVotersRequest.builder() diff --git a/src/test/java/com/keeper/homepage/domain/election/application/AdminElectionServiceTest.java b/src/test/java/com/keeper/homepage/domain/election/application/AdminElectionServiceTest.java index 2d375f20d..7988aaeb1 100644 --- a/src/test/java/com/keeper/homepage/domain/election/application/AdminElectionServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/election/application/AdminElectionServiceTest.java @@ -91,7 +91,8 @@ void setUp() { em.flush(); em.clear(); - ElectionCandidate savedCandidate = electionCandidateRepository.findById(electionCandidate.getId()).orElseThrow(); + ElectionCandidate savedCandidate = electionCandidateRepository.findById( + electionCandidate.getId()).orElseThrow(); assertEquals(electionCandidate.getDescription(), savedCandidate.getDescription()); assertThat(savedCandidate.getMemberJob().getType()).isEqualTo(ROLE_회장); @@ -106,7 +107,8 @@ void setUp() { memberJob = memberJobRepository.findById(improperMemberJobType.getId()).orElseThrow(); assertThrows(BusinessException.class, - () -> adminElectionService.registerCandidate(electionCandidate.getDescription(), memberJob.getId(), + () -> adminElectionService.registerCandidate(electionCandidate.getDescription(), + memberJob.getId(), electionId, candidateId), ELECTION_CANDIDATE_CANNOT_REGISTER.getMessage()); } @@ -121,7 +123,8 @@ void setUp() { .collect(toList()); electionCandidateRepository.deleteAll(); - adminElectionService.registerCandidates(candidateIds, electionCandidate.getDescription(), memberJob.getId(), + adminElectionService.registerCandidates(candidateIds, electionCandidate.getDescription(), + memberJob.getId(), electionId); em.flush(); @@ -136,7 +139,8 @@ void setUp() { @DisplayName("후보자 삭제에 성공한다.") public void 후보자_삭제에_성공한다() throws Exception { Election election = electionTestHelper.builder().isAvailable(false).build(); - ElectionCandidate electionCandidate = electionCandidateTestHelper.builder(memberJob).election(election).build(); + ElectionCandidate electionCandidate = electionCandidateTestHelper.builder(memberJob) + .election(election).build(); long electionId = electionCandidate.getElection().getId(); long candidateId = electionCandidate.getId(); adminElectionService.deleteCandidate(electionId, candidateId); @@ -153,7 +157,8 @@ void setUp() { long electionId = electionCandidate.getElection().getId(); long notExistCandidateId = 10; - assertThrows(BusinessException.class, () -> adminElectionService.deleteCandidate(electionId, notExistCandidateId), + assertThrows(BusinessException.class, + () -> adminElectionService.deleteCandidate(electionId, notExistCandidateId), ELECTION_CANDIDATE_NOT_FOUND.getMessage()); } @@ -166,8 +171,9 @@ void setUp() { .isAvailable(true) .build(); - assertThrows(BusinessException.class, () -> adminElectionService.deleteCandidate(election.getId(), - electionCandidate.getId()), ELECTION_CANDIDATE_CANNOT_DELETE.getMessage()); + assertThrows(BusinessException.class, + () -> adminElectionService.deleteCandidate(election.getId(), + electionCandidate.getId()), ELECTION_CANDIDATE_CANNOT_DELETE.getMessage()); } } @@ -199,7 +205,8 @@ class VoterRegisterAndDeleteTest { public void 투표자_다중_삭제에_성공한다() throws Exception { Election election = electionTestHelper.builder().isAvailable(false).build(); List voterIds = IntStream.range(0, 5) - .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build().getMember().getId()) + .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build() + .getMember().getId()) .collect(toList()); adminElectionService.deleteVoters(voterIds, election.getId()); @@ -220,7 +227,8 @@ class VoterRegisterAndDeleteTest { .mapToObj(electionVoter -> memberTestHelper.generate().getId()) .collect(toList()); - assertThrows(BusinessException.class, () -> adminElectionService.deleteVoters(voterIds, election.getId()), + assertThrows(BusinessException.class, + () -> adminElectionService.deleteVoters(voterIds, election.getId()), ELECTION_VOTER_NOT_FOUND.getMessage()); } @@ -234,10 +242,12 @@ class VoterRegisterAndDeleteTest { .build(); List voterIds = IntStream.range(0, 5) - .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build().getMember().getId()) + .mapToObj(electionVoter -> electionVoterTestHelper.builder().election(election).build() + .getMember().getId()) .collect(toList()); - assertThrows(BusinessException.class, () -> adminElectionService.deleteVoters(voterIds, election.getId()), + assertThrows(BusinessException.class, + () -> adminElectionService.deleteVoters(voterIds, election.getId()), ELECTION_VOTER_CANNOT_DELETE.getMessage()); } diff --git a/src/test/java/com/keeper/homepage/domain/game/api/GameApiTestHelper.kt b/src/test/java/com/keeper/homepage/domain/game/api/GameApiTestHelper.kt index fd4682505..5fed7dd76 100644 --- a/src/test/java/com/keeper/homepage/domain/game/api/GameApiTestHelper.kt +++ b/src/test/java/com/keeper/homepage/domain/game/api/GameApiTestHelper.kt @@ -34,65 +34,65 @@ class GameApiTestHelper : IntegrationTest() { } fun callGetGameRank( - accessCookies: Array = playerCookies + accessCookies: Array = playerCookies ): ResultActions { return mockMvc.perform( - get("$GAME_URL/rank") - .cookie(*accessCookies) + get("$GAME_URL/rank") + .cookie(*accessCookies) ) } fun callGetMyGameInfo( - accessCookies: Array = playerCookies + accessCookies: Array = playerCookies ): ResultActions { return mockMvc.perform( - get("$GAME_URL/my-info") - .cookie(*accessCookies) + get("$GAME_URL/my-info") + .cookie(*accessCookies) ) } fun callBaseballGameInfo( - accessCookies: Array = playerCookies + accessCookies: Array = playerCookies ): ResultActions { return mockMvc.perform( - get("$GAME_URL/baseball/game-info") - .cookie(*accessCookies) + get("$GAME_URL/baseball/game-info") + .cookie(*accessCookies) ) } fun callBaseballGetStatus( - accessCookies: Array = playerCookies + accessCookies: Array = playerCookies ): ResultActions { return mockMvc.perform( - get("$GAME_URL/baseball/status") - .cookie(*accessCookies) + get("$GAME_URL/baseball/status") + .cookie(*accessCookies) ) } fun callBaseballStart( - bettingPoint: Int, - accessCookies: Array = playerCookies + bettingPoint: Int, + accessCookies: Array = playerCookies ): ResultActions { return mockMvc.perform( - post("$GAME_URL/baseball/start") - .content(asJsonString(BaseballStartRequest(bettingPoint))) - .contentType(APPLICATION_JSON) - .cookie(*accessCookies) + post("$GAME_URL/baseball/start") + .content(asJsonString(BaseballStartRequest(bettingPoint))) + .contentType(APPLICATION_JSON) + .cookie(*accessCookies) ) } fun callBaseballGuess( - guessNumbers: List, - correctNumber: String, - bettingPoint: Int, - results: MutableList = mutableListOf(), - earnablePoint: Int = 1000, - accessCookies: Array = playerCookies + guessNumbers: List, + correctNumber: String, + bettingPoint: Int, + results: MutableList = mutableListOf(), + earnablePoint: Int = 1000, + accessCookies: Array = playerCookies ): ResultActions { baseballService.saveBaseballResultInRedis( - player.id, - BaseballResultEntity(correctNumber, bettingPoint, results, earnablePoint), - 0, + player.id, + BaseballResultEntity(correctNumber, bettingPoint, results, earnablePoint), + 0, ) for (guessNumber in guessNumbers.subList(0, guessNumbers.size - 1)) { callBaseballGuess(guessNumber, accessCookies) @@ -102,31 +102,31 @@ class GameApiTestHelper : IntegrationTest() { private fun callBaseballGuess(guessNumber: String, accessCookies: Array): ResultActions { return mockMvc.perform( - post("$GAME_URL/baseball/guess") - .content(asJsonString(BaseballGuessRequest(guessNumber))) - .contentType(APPLICATION_JSON) - .cookie(*accessCookies)) + post("$GAME_URL/baseball/guess") + .content(asJsonString(BaseballGuessRequest(guessNumber))) + .contentType(APPLICATION_JSON) + .cookie(*accessCookies)) } fun callGetBaseballResult( - results: MutableList = mutableListOf(), - earnablePoint: Int = 1000, - accessCookies: Array = playerCookies + results: MutableList = mutableListOf(), + earnablePoint: Int = 1000, + accessCookies: Array = playerCookies ): ResultActions { baseballService.saveBaseballResultInRedis( - player.id, - BaseballResultEntity("1234", 1000, results, earnablePoint), - 1, + player.id, + BaseballResultEntity("1234", 1000, results, earnablePoint), + 1, ) return mockMvc.perform( - get("$GAME_URL/baseball/result") - .cookie(*accessCookies) + get("$GAME_URL/baseball/result") + .cookie(*accessCookies) ) } fun gameStart() { gameFindService.findByMemberOrInit(player) - .baseball - .increaseBaseballTimes() + .baseball + .increaseBaseballTimes() } } diff --git a/src/test/java/com/keeper/homepage/domain/game/api/GameControllerTest.kt b/src/test/java/com/keeper/homepage/domain/game/api/GameControllerTest.kt index 10da98164..065cf6174 100644 --- a/src/test/java/com/keeper/homepage/domain/game/api/GameControllerTest.kt +++ b/src/test/java/com/keeper/homepage/domain/game/api/GameControllerTest.kt @@ -27,20 +27,20 @@ class GameControllerTest : GameApiTestHelper() { @Test fun `나의 게임 관련 정보를 불러온다`() { callGetMyGameInfo() - .andExpect(status().isOk) - .andDo( - document( - "get-my-game-info", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - responseFields( - fieldWithPath("todayTotalEarnedPoint").description("오늘 게임으로 얻은 총 포인트"), - fieldWithPath("currentMemberPoint").description("현재 멤버 보유 포인트"), - ) + .andExpect(status().isOk) + .andDo( + document( + "get-my-game-info", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + responseFields( + fieldWithPath("todayTotalEarnedPoint").description("오늘 게임으로 얻은 총 포인트"), + fieldWithPath("currentMemberPoint").description("현재 멤버 보유 포인트"), + ) + ) ) - ) } @Test @@ -48,24 +48,24 @@ class GameControllerTest : GameApiTestHelper() { (1..2).forEach { _ -> gameTestHelper.generate() } callGetGameRank() - .andExpect(status().isOk) - .andDo( - document( - "game-rank", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - responseFields( - fieldWithPath("[].rank").description("순위 (1~${MAX_RANK_COUNT})"), - fieldWithPath("[].realName").description("실명"), - fieldWithPath("[].generation").description("기수"), - fieldWithPath("[].todayEarnedPoint").description("오늘 얻은 포인트"), - fieldWithPath("[].thumbnailPath").description("프로필 이미지 url (상대경로)"), - fieldWithPath("[].memberId").description("회원 id") - ) + .andExpect(status().isOk) + .andDo( + document( + "game-rank", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + responseFields( + fieldWithPath("[].rank").description("순위 (1~${MAX_RANK_COUNT})"), + fieldWithPath("[].realName").description("실명"), + fieldWithPath("[].generation").description("기수"), + fieldWithPath("[].todayEarnedPoint").description("오늘 얻은 포인트"), + fieldWithPath("[].thumbnailPath").description("프로필 이미지 url (상대경로)"), + fieldWithPath("[].memberId").description("회원 id") + ) + ) ) - ) } } @@ -75,107 +75,107 @@ class GameControllerTest : GameApiTestHelper() { @Test fun `야구게임 정보를 불러온다`() { callBaseballGameInfo() - .andExpect(status().isOk) - .andExpect(jsonPath("$.guessNumberLength").value(4)) - .andExpect(jsonPath("$.tryCount").value(9)) - .andExpect(jsonPath("$.maxBettingPoint").value(5000L)) - .andExpect(jsonPath("$.minBettingPoint").value(1000L)) - .andDo( - document( - "baseball-game-info", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - responseFields( - fieldWithPath("guessNumberLength").description("추측할 숫자 길이"), - fieldWithPath("tryCount").description("라운드 수"), - fieldWithPath("maxBettingPoint").description("최대 베팅 포인트"), - fieldWithPath("minBettingPoint").description("최소 베팅 포인트"), - fieldWithPath("maxPlayTime").description("최대 플레이 가능 횟수"), - ) + .andExpect(status().isOk) + .andExpect(jsonPath("$.guessNumberLength").value(4)) + .andExpect(jsonPath("$.tryCount").value(9)) + .andExpect(jsonPath("$.maxBettingPoint").value(5000L)) + .andExpect(jsonPath("$.minBettingPoint").value(1000L)) + .andDo( + document( + "baseball-game-info", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + responseFields( + fieldWithPath("guessNumberLength").description("추측할 숫자 길이"), + fieldWithPath("tryCount").description("라운드 수"), + fieldWithPath("maxBettingPoint").description("최대 베팅 포인트"), + fieldWithPath("minBettingPoint").description("최소 베팅 포인트"), + fieldWithPath("maxPlayTime").description("최대 플레이 가능 횟수"), + ) + ) ) - ) } @Test fun `야구게임을 오늘 안했으면 NOT_START가 나와야 한다`() { callBaseballGetStatus() - .andDo(MockMvcResultHandlers.print()) - .andExpect(status().isOk) - .andExpect(jsonPath("$.status").value("NOT_START")) - .andDo( - document( - "baseball-get-status", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - responseFields( - fieldWithPath("status").description( - BaseballStatus.values().map { it.name } + " 중 하나로 내려갑니다." - ), - fieldWithPath("baseballPerDay").description("현재 야구게임 플레이 횟수 (시작을 안했으면 0, 했으면 1 이상)"), - ) + .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk) + .andExpect(jsonPath("$.status").value("NOT_START")) + .andDo( + document( + "baseball-get-status", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + responseFields( + fieldWithPath("status").description( + BaseballStatus.values().map { it.name } + " 중 하나로 내려갑니다." + ), + fieldWithPath("baseballPerDay").description("현재 야구게임 플레이 횟수 (시작을 안했으면 0, 했으면 1 이상)"), + ) + ) ) - ) } @Test fun `야구게임을 시작했으면 PLAYING이 나와야 한다`() { gameStart() baseballService.saveBaseballResultInRedis( - player.id, - BaseballResultEntity( - "1234", - 1000, - mutableListOf(), - 2000 - ), - 1, + player.id, + BaseballResultEntity( + "1234", + 1000, + mutableListOf(), + 2000 + ), + 1, ) callBaseballGetStatus() - .andExpect(status().isOk) - .andExpect(jsonPath("$.status").value("PLAYING")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.status").value("PLAYING")) } @Test fun `야구게임을 시작했고, 9판 모두 했으면 END가 나와야 한다`() { gameStart() baseballService.saveBaseballResultInRedis( - player.id, - BaseballResultEntity( - "1234", - 1000, - mutableListOf(null, null, null, null, null, null, null, null, null), - 2000 - ), - 1, + player.id, + BaseballResultEntity( + "1234", + 1000, + mutableListOf(null, null, null, null, null, null, null, null, null), + 2000 + ), + 1, ) callBaseballGetStatus() - .andExpect(status().isOk) - .andExpect(jsonPath("$.status").value("END")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.status").value("END")) } @Test fun `야구게임을 시작했고, 4strike를 했으면 END가 나와야 한다`() { gameStart() baseballService.saveBaseballResultInRedis( - player.id, - BaseballResultEntity( - "1234", - 1000, - mutableListOf(null, null, GuessResultEntity("1234", 4, 0)), - 2000 - ), - 1, + player.id, + BaseballResultEntity( + "1234", + 1000, + mutableListOf(null, null, GuessResultEntity("1234", 4, 0)), + 2000 + ), + 1, ) callBaseballGetStatus() - .andExpect(status().isOk) - .andExpect(jsonPath("$.status").value("END")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.status").value("END")) } @Test @@ -185,13 +185,13 @@ class GameControllerTest : GameApiTestHelper() { em.clear() val result = callBaseballStart(1000) - .andExpect(status().isOk) + .andExpect(status().isOk) val baseball = gameFindService.findByMemberOrInit(player).baseball assertThat(baseball.baseballPerDay).isEqualTo(1) // 게임을 시작하면 play count가 증가한다. val data = redisUtil.getData( - REDIS_KEY_PREFIX + player.id.toString() + "_" + baseball.baseballPerDay, - BaseballResultEntity::class.java + REDIS_KEY_PREFIX + player.id.toString() + "_" + baseball.baseballPerDay, + BaseballResultEntity::class.java ) assertThat(data).isNotEmpty assertThat(data.get().correctNumber).hasSize(4) @@ -201,22 +201,22 @@ class GameControllerTest : GameApiTestHelper() { assertThat(data.get().lastGuessTime).isBefore(LocalDateTime.now()) result.andDo( - document( - "baseball-start", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - requestFields( - fieldWithPath("bettingPoint").description("베팅을 할 포인트 (${MIN_BETTING_POINT}이상 ${MAX_BETTING_POINT}이하)"), - ), - responseFields( - fieldWithPath("results").description("start API에선 빈 배열로 내려갑니다."), - fieldWithPath("earnablePoint").description("처음 할당된 획득할 포인트"), - fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), - fieldWithPath("remainedSecond").description("이번 라운드 남은 초. 이 API에선 항상 ${SECOND_PER_GAME}으로 반환됩니다."), + document( + "baseball-start", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + requestFields( + fieldWithPath("bettingPoint").description("베팅을 할 포인트 (${MIN_BETTING_POINT}이상 ${MAX_BETTING_POINT}이하)"), + ), + responseFields( + fieldWithPath("results").description("start API에선 빈 배열로 내려갑니다."), + fieldWithPath("earnablePoint").description("처음 할당된 획득할 포인트"), + fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), + fieldWithPath("remainedSecond").description("이번 라운드 남은 초. 이 API에선 항상 ${SECOND_PER_GAME}으로 반환됩니다."), + ) ) - ) ) } @@ -225,12 +225,12 @@ class GameControllerTest : GameApiTestHelper() { player.addPoint(1000) memberRepository.save(player) callBaseballStart(1001) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) callBaseballStart(2000) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) @Suppress("INTEGER_OVERFLOW") callBaseballStart(Int.MAX_VALUE + 1) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } @Test @@ -238,11 +238,11 @@ class GameControllerTest : GameApiTestHelper() { player.addPoint(1000) memberRepository.save(player) callBaseballStart(-1000) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) callBaseballStart(0) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) callBaseballStart(9) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } @Test @@ -250,52 +250,52 @@ class GameControllerTest : GameApiTestHelper() { player.addPoint(1000) memberRepository.save(player) callBaseballStart(2000) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } @Test fun `valid한 request면 guess는 성공해야 한다`() { val result = callBaseballGuess( - guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, - results = mutableListOf( - GuessResultEntity("1357", 0, 0), - GuessResultEntity("2468", 2, 2), - GuessResultEntity("7890", 3, 0) - ) + guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, + results = mutableListOf( + GuessResultEntity("1357", 0, 0), + GuessResultEntity("2468", 2, 2), + GuessResultEntity("7890", 3, 0) + ) ).andExpect(status().isOk) - .andExpect(jsonPath("$.results").isArray) - .andExpect(jsonPath("$.results[0]").exists()) - .andExpect(jsonPath("$.earnablePoint").isNumber) + .andExpect(jsonPath("$.results").isArray) + .andExpect(jsonPath("$.results[0]").exists()) + .andExpect(jsonPath("$.earnablePoint").isNumber) result.andDo( - document( - "baseball-guess", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - requestFields( - fieldWithPath("guessNumber").description("추측한 숫자 (반드시 ${GUESS_NUMBER_LENGTH}자 여야 합니다)"), - ), - responseFields( - fieldWithPath("results").description("타임아웃난 round는 null"), - fieldWithPath("results[].guessNumber").description("해당 라운드에 사용자가 입력한 추측 숫자"), - fieldWithPath("results[].strike").description("strike"), - fieldWithPath("results[].ball").description("ball"), - fieldWithPath("earnablePoint").description("획득한 포인트 (마지막 게임이 아니면 0)"), - fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), - fieldWithPath("remainedSecond").description("이번 라운드 남은 초. 이 API에선 항상 0으로 반환됩니다."), - ), - ) + document( + "baseball-guess", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + requestFields( + fieldWithPath("guessNumber").description("추측한 숫자 (반드시 ${GUESS_NUMBER_LENGTH}자 여야 합니다)"), + ), + responseFields( + fieldWithPath("results").description("타임아웃난 round는 null"), + fieldWithPath("results[].guessNumber").description("해당 라운드에 사용자가 입력한 추측 숫자"), + fieldWithPath("results[].strike").description("strike"), + fieldWithPath("results[].ball").description("ball"), + fieldWithPath("earnablePoint").description("획득한 포인트 (마지막 게임이 아니면 0)"), + fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), + fieldWithPath("remainedSecond").description("이번 라운드 남은 초. 이 API에선 항상 0으로 반환됩니다."), + ), + ) ) } @Test fun `guessNumber가 4자가 아니면 guess는 실패한다`() { callBaseballGuess(guessNumbers = listOf("123"), correctNumber = "1234", bettingPoint = 1000) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) callBaseballGuess(guessNumbers = listOf("12345"), correctNumber = "1234", bettingPoint = 1000) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } @Test @@ -304,11 +304,11 @@ class GameControllerTest : GameApiTestHelper() { val earnablePoint = 3000 callBaseballGuess( - guessNumbers = listOf("3456", "4567", "5678"), - correctNumber = "5678", - bettingPoint = 1000, - earnablePoint = earnablePoint, - results = mutableListOf(GuessResultEntity("1234", 2, 2), null, GuessResultEntity("2345", 3, 0)) + guessNumbers = listOf("3456", "4567", "5678"), + correctNumber = "5678", + bettingPoint = 1000, + earnablePoint = earnablePoint, + results = mutableListOf(GuessResultEntity("1234", 2, 2), null, GuessResultEntity("2345", 3, 0)) ).andExpect(status().isOk) assertThat(beforePlayerPoint + 2430).isEqualTo(player.point) // 초기 3000 포인트에서 2번 틀렸다고 가정 @@ -319,8 +319,8 @@ class GameControllerTest : GameApiTestHelper() { val beforePlayerPoint = player.point callBaseballGuess( - guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, - results = mutableListOf(GuessResultEntity("1234", 2, 2), null, GuessResultEntity("5678", 4, 0)) + guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, + results = mutableListOf(GuessResultEntity("1234", 2, 2), null, GuessResultEntity("5678", 4, 0)) ).andExpect(status().isOk) assertThat(beforePlayerPoint).isEqualTo(player.point) @@ -331,11 +331,11 @@ class GameControllerTest : GameApiTestHelper() { val beforePlayerPoint = player.point callBaseballGuess( - guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, - results = mutableListOf( - GuessResultEntity("1234", 2, 2), null, GuessResultEntity("5678", 4, 0), - null, null, null, null, null, null - ) + guessNumbers = listOf("1234"), correctNumber = "1234", bettingPoint = 1000, + results = mutableListOf( + GuessResultEntity("1234", 2, 2), null, GuessResultEntity("5678", 4, 0), + null, null, null, null, null, null + ) ).andExpect(status().isOk) assertThat(beforePlayerPoint).isEqualTo(player.point) @@ -346,58 +346,58 @@ class GameControllerTest : GameApiTestHelper() { gameStart() callGetBaseballResult( - results = mutableListOf( - GuessResultEntity("1234", 2, 2), - null, GuessResultEntity("3456", 1, 0), - null, null, GuessResultEntity("5678", 3, 0) - ) + results = mutableListOf( + GuessResultEntity("1234", 2, 2), + null, GuessResultEntity("3456", 1, 0), + null, null, GuessResultEntity("5678", 3, 0) + ) ).andDo(MockMvcResultHandlers.print()) - .andExpect(status().isOk) - .andExpect( - jsonPath("$.results[0]").value( - linkedMapOf( - "guessNumber" to "1234", - "strike" to 2, - "ball" to 2 - ) + .andExpect(status().isOk) + .andExpect( + jsonPath("$.results[0]").value( + linkedMapOf( + "guessNumber" to "1234", + "strike" to 2, + "ball" to 2 + ) + ) ) - ) - .andExpect(jsonPath("$.results[1]").value(null)) - .andExpect( - jsonPath("$.results[2]").value( - linkedMapOf( - "guessNumber" to "3456", - "strike" to 1, - "ball" to 0 - ) + .andExpect(jsonPath("$.results[1]").value(null)) + .andExpect( + jsonPath("$.results[2]").value( + linkedMapOf( + "guessNumber" to "3456", + "strike" to 1, + "ball" to 0 + ) + ) ) - ) - .andExpect(jsonPath("$.results[3]").value(null)) - .andExpect(jsonPath("$.results[4]").value(null)) - .andExpect( - jsonPath("$.results[5]").value( - linkedMapOf( - "guessNumber" to "5678", - "strike" to 3, - "ball" to 0 - ) + .andExpect(jsonPath("$.results[3]").value(null)) + .andExpect(jsonPath("$.results[4]").value(null)) + .andExpect( + jsonPath("$.results[5]").value( + linkedMapOf( + "guessNumber" to "5678", + "strike" to 3, + "ball" to 0 + ) + ) ) - ) - .andDo( - document( - "get-baseball-results", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") - ), - responseFields( - subsectionWithPath("results").description("타임아웃난 round는 null"), - fieldWithPath("earnablePoint").description("획득한 포인트 (오늘 끝낸 게임이 아니면 0)"), - fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), - fieldWithPath("remainedSecond").description("이번 라운드 남은 초. ms 단위는 버림해서 내려갑니다."), - ), + .andDo( + document( + "get-baseball-results", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN") + ), + responseFields( + subsectionWithPath("results").description("타임아웃난 round는 null"), + fieldWithPath("earnablePoint").description("획득한 포인트 (오늘 끝낸 게임이 아니면 0)"), + fieldWithPath("bettingPoint").description("게임 시작 베팅 포인트"), + fieldWithPath("remainedSecond").description("이번 라운드 남은 초. ms 단위는 버림해서 내려갑니다."), + ), + ) ) - ) } } } diff --git a/src/test/java/com/keeper/homepage/domain/game/application/GameServiceTest.kt b/src/test/java/com/keeper/homepage/domain/game/application/GameServiceTest.kt index e6af22f65..dd2aafa0e 100644 --- a/src/test/java/com/keeper/homepage/domain/game/application/GameServiceTest.kt +++ b/src/test/java/com/keeper/homepage/domain/game/application/GameServiceTest.kt @@ -13,14 +13,14 @@ import java.time.LocalDate import java.time.LocalDateTime fun GameTestHelper.generate( - member: Member, - baseballDayPoint: Int, - lastPlayTime: LocalDateTime = LocalDateTime.now() + member: Member, + baseballDayPoint: Int, + lastPlayTime: LocalDateTime = LocalDateTime.now() ): Game { return this.builder().member(member) - .baseball(Baseball.from(1, baseballDayPoint)) - .lastPlayTime(lastPlayTime) - .build() + .baseball(Baseball.from(1, baseballDayPoint)) + .lastPlayTime(lastPlayTime) + .build() } class GameServiceTest : IntegrationTest() { @@ -36,16 +36,16 @@ class GameServiceTest : IntegrationTest() { val game5 = gameTestHelper.generate(members[4], 500, now) val game6 = gameTestHelper.generate(members[5], 0, now) given(gameFindService.findAllByPlayDate(LocalDate.now())) - .willReturn(listOf(game1, game2, game3, game4, game5, game6)) + .willReturn(listOf(game1, game2, game3, game4, game5, game6)) val gameRanks = gameService.getGameRanks() assertThat(gameRanks).hasSize(4) assertThat(gameRanks).containsExactly( - GameRankResponse(1, members[3], 2000), - GameRankResponse(2, members[1], 1500), - GameRankResponse(3, members[2], 1500), - GameRankResponse(4, members[0], 1000), + GameRankResponse(1, members[3], 2000), + GameRankResponse(2, members[1], 1500), + GameRankResponse(3, members[2], 1500), + GameRankResponse(4, members[0], 1000), ) } } diff --git a/src/test/java/com/keeper/homepage/domain/game/support/BaseballSupportTest.kt b/src/test/java/com/keeper/homepage/domain/game/support/BaseballSupportTest.kt index 4a7319b85..5ccce0131 100644 --- a/src/test/java/com/keeper/homepage/domain/game/support/BaseballSupportTest.kt +++ b/src/test/java/com/keeper/homepage/domain/game/support/BaseballSupportTest.kt @@ -80,10 +80,10 @@ class BaseballSupportTest { @ParameterizedTest @MethodSource fun `같은 숫자면 ball, 같은 위치이면 strike를 올려야 한다`( - correctNumber: String, - guessNumber: String, - expectedStrike: Int, - expectedBall: Int + correctNumber: String, + guessNumber: String, + expectedStrike: Int, + expectedBall: Int ) { val result = BaseballSupport.guessAndGetResult(correctNumber, guessNumber) assertThat(result.strike).isEqualTo(expectedStrike) @@ -91,14 +91,14 @@ class BaseballSupportTest { } fun `같은 숫자면 ball, 같은 위치이면 strike를 올려야 한다`() = Stream.of( - Arguments.arguments("1234", "1234", 4, 0), - Arguments.arguments("1234", "1256", 2, 0), - Arguments.arguments("1234", "4321", 0, 4), - Arguments.arguments("1234", "1432", 2, 2), - Arguments.arguments("1234", "9328", 0, 2), - Arguments.arguments("1234", "1423", 1, 3), - Arguments.arguments("1234", "5678", 0, 0), - Arguments.arguments("1234", "1567", 1, 0), + Arguments.arguments("1234", "1234", 4, 0), + Arguments.arguments("1234", "1256", 2, 0), + Arguments.arguments("1234", "4321", 0, 4), + Arguments.arguments("1234", "1432", 2, 2), + Arguments.arguments("1234", "9328", 0, 2), + Arguments.arguments("1234", "1423", 1, 3), + Arguments.arguments("1234", "5678", 0, 0), + Arguments.arguments("1234", "1567", 1, 0), ) @Test diff --git a/src/test/java/com/keeper/homepage/domain/library/BookTestHelper.java b/src/test/java/com/keeper/homepage/domain/library/BookTestHelper.java index 6121e80d7..2830e2add 100644 --- a/src/test/java/com/keeper/homepage/domain/library/BookTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/library/BookTestHelper.java @@ -69,7 +69,8 @@ public Book build() { return bookRepository.save(Book.builder() .title(title != null ? title : "도서 제목") .author(author != null ? author : "도서 저자") - .bookDepartment(bookDepartment != null ? bookDepartment : BookDepartment.getBookDepartmentBy(ETC)) + .bookDepartment( + bookDepartment != null ? bookDepartment : BookDepartment.getBookDepartmentBy(ETC)) .totalQuantity(totalQuantity != null ? totalQuantity : 1) .thumbnail(thumbnail) .build()); diff --git a/src/test/java/com/keeper/homepage/domain/library/api/BookControllerTest.java b/src/test/java/com/keeper/homepage/domain/library/api/BookControllerTest.java index 978cafc71..954dc7c81 100644 --- a/src/test/java/com/keeper/homepage/domain/library/api/BookControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/library/api/BookControllerTest.java @@ -131,7 +131,8 @@ class CancelRequestBorrow { .andExpect(status().isNoContent()) .andDo(document("cancel-book-borrow", requestCookies( - cookieWithName(ACCESS_TOKEN.getTokenName()).description("ACCESS TOKEN %s".formatted(securedValue)) + cookieWithName(ACCESS_TOKEN.getTokenName()).description( + "ACCESS TOKEN %s".formatted(securedValue)) ), pathParameters( parameterWithName("borrowId").description("대출 신청 취소하고자 하는 도서대여 ID") @@ -234,7 +235,8 @@ class CancelRequestReturn { .andExpect(status().isNoContent()) .andDo(document("cancel-book-return", requestCookies( - cookieWithName(ACCESS_TOKEN.getTokenName()).description("ACCESS TOKEN %s".formatted(securedValue)) + cookieWithName(ACCESS_TOKEN.getTokenName()).description( + "ACCESS TOKEN %s".formatted(securedValue)) ), pathParameters( parameterWithName("borrowId").description("도서 대출 내역 ID") diff --git a/src/test/java/com/keeper/homepage/domain/library/api/BookManageApiTestHelper.kt b/src/test/java/com/keeper/homepage/domain/library/api/BookManageApiTestHelper.kt index c60a30d75..79d9199bc 100644 --- a/src/test/java/com/keeper/homepage/domain/library/api/BookManageApiTestHelper.kt +++ b/src/test/java/com/keeper/homepage/domain/library/api/BookManageApiTestHelper.kt @@ -33,55 +33,55 @@ import java.time.LocalDateTime const val BOOK_URL = "/manage/books" fun field( - path: String, - description: String, - optional: Boolean = false + path: String, + description: String, + optional: Boolean = false ) = if (optional) { PayloadDocumentation.fieldWithPath(path) - .description(description) - .optional() + .description(description) + .optional() } else { PayloadDocumentation.fieldWithPath(path) - .description(description) + .description(description) } fun pageHelper(vararg fieldDescriptors: FieldDescriptor): Array = - arrayOf( - *listHelper("content", *fieldDescriptors), - field("empty", "가져오는 페이지가 비어 있는 지"), - field("first", "첫 페이지인지"), - field("last", "마지막 페이지인지"), - field("number", "페이지 number (0부터 시작)"), - field("numberOfElements", "현재 페이지의 데이터 개수"), - PayloadDocumentation.subsectionWithPath("pageable").description("페이지에 대한 부가 정보"), - field("sort.empty", "정렬 기준이 비어 있는 지"), - field("sort.sorted", "정렬이 되었는지"), - field("sort.unsorted", "정렬이 되지 않았는지"), - field("totalPages", "총 페이지 수"), - field("totalElements", "총 데이터 개수"), - field("size", "한 페이지당 데이터 개수") - ) + arrayOf( + *listHelper("content", *fieldDescriptors), + field("empty", "가져오는 페이지가 비어 있는 지"), + field("first", "첫 페이지인지"), + field("last", "마지막 페이지인지"), + field("number", "페이지 number (0부터 시작)"), + field("numberOfElements", "현재 페이지의 데이터 개수"), + PayloadDocumentation.subsectionWithPath("pageable").description("페이지에 대한 부가 정보"), + field("sort.empty", "정렬 기준이 비어 있는 지"), + field("sort.sorted", "정렬이 되었는지"), + field("sort.unsorted", "정렬이 되지 않았는지"), + field("totalPages", "총 페이지 수"), + field("totalElements", "총 데이터 개수"), + field("size", "한 페이지당 데이터 개수") + ) fun listHelper(objectName: String, vararg fieldDescriptors: FieldDescriptor): Array = - fieldDescriptors.map { field("${objectName}[].${it.path}", it.description.toString(), it.isOptional) } - .toTypedArray() + fieldDescriptors.map { field("${objectName}[].${it.path}", it.description.toString(), it.isOptional) } + .toTypedArray() fun multiValueMapOf( - vararg pairs: Pair + vararg pairs: Pair ): MultiValueMap = LinkedMultiValueMap().apply { setAll(mapOf(*pairs)) } fun BookBorrowInfoTestHelper.generate( - borrowStatus: BookBorrowStatus.BookBorrowStatusType, - book: Book, - expiredDate: LocalDateTime = LocalDateTime.now().plusWeeks(2), + borrowStatus: BookBorrowStatus.BookBorrowStatusType, + book: Book, + expiredDate: LocalDateTime = LocalDateTime.now().plusWeeks(2), ): BookBorrowInfo { return this.builder() - .book(book) - .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(borrowStatus)) - .expireDate(expiredDate) - .build() + .book(book) + .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(borrowStatus)) + .expireDate(expiredDate) + .build() } class BookManageApiTestHelper : IntegrationTest() { @@ -98,162 +98,162 @@ class BookManageApiTestHelper : IntegrationTest() { } fun callGetBooksApi( - params: MultiValueMap = multiValueMapOf( - "search" to "", - "page" to "0", - "size" to "10", - ), - accessCookies: Array = bookManagerCookies, + params: MultiValueMap = multiValueMapOf( + "search" to "", + "page" to "0", + "size" to "10", + ), + accessCookies: Array = bookManagerCookies, ): ResultActions { return mockMvc.perform( - get(BOOK_URL) - .queryParams(params) - .cookie(*accessCookies) + get(BOOK_URL) + .queryParams(params) + .cookie(*accessCookies) ) } fun callAddBookApi( - request: BookRequest = BookRequest( - title = "삶의 목적을 찾는 45가지 방법", - author = "ChatGPT", - totalQuantity = 10, - bookDepartment = BookDepartmentType.DOCUMENT - ), - accessCookies: Array = bookManagerCookies, - hasThumbnail: Boolean = false, - isMocking: Boolean = false, + request: BookRequest = BookRequest( + title = "삶의 목적을 찾는 45가지 방법", + author = "ChatGPT", + totalQuantity = 10, + bookDepartment = BookDepartmentType.DOCUMENT + ), + accessCookies: Array = bookManagerCookies, + hasThumbnail: Boolean = false, + isMocking: Boolean = false, ): ResultActions { if (isMocking) { every { bookManageService.addBook(any(), any(), any(), any(), any()) } returns 1L } val mockPart = MockPart( - "bookMetaData", - asJsonString(request).toByteArray(StandardCharsets.UTF_8) + "bookMetaData", + asJsonString(request).toByteArray(StandardCharsets.UTF_8) ) mockPart.headers.contentType = MediaType.APPLICATION_JSON return if (hasThumbnail) { mockMvc.perform( - multipart(BOOK_URL) - .file(thumbnailTestHelper.smallThumbnailFile) - .part(mockPart) - .cookie(*accessCookies) - .contentType(MediaType.MULTIPART_FORM_DATA) + multipart(BOOK_URL) + .file(thumbnailTestHelper.smallThumbnailFile) + .part(mockPart) + .cookie(*accessCookies) + .contentType(MediaType.MULTIPART_FORM_DATA) ).andDo(MockMvcResultHandlers.print()) } else { mockMvc.perform( - multipart(BOOK_URL) - .part(mockPart) - .cookie(*accessCookies) - .contentType(MediaType.MULTIPART_FORM_DATA) + multipart(BOOK_URL) + .part(mockPart) + .cookie(*accessCookies) + .contentType(MediaType.MULTIPART_FORM_DATA) ).andDo(MockMvcResultHandlers.print()) } } fun callDeleteBookApi( - accessCookies: Array = bookManagerCookies, - isMocking: Boolean = false, + accessCookies: Array = bookManagerCookies, + isMocking: Boolean = false, ): ResultActions { var bookId = 0L if (isMocking) { every { bookManageService.deleteBook(any()) } just Runs } else { bookId = bookManageService.addBook( - "삶의 목적을 찾는 45가지 방법", - "ChatGPT", - 10, - BookDepartmentType.DOCUMENT, - null + "삶의 목적을 찾는 45가지 방법", + "ChatGPT", + 10, + BookDepartmentType.DOCUMENT, + null ) } return mockMvc.perform( - delete("${BOOK_URL}/{bookId}", bookId) - .cookie(*accessCookies) + delete("${BOOK_URL}/{bookId}", bookId) + .cookie(*accessCookies) ) } fun callModifyBookApi( - content: ModifyBookRequest = ModifyBookRequest( - title = "삶의 목적을 찾는 45가지 방법", - author = "ChatGPT", - totalQuantity = 10, - bookDepartment = BookDepartmentType.DOCUMENT - ), - bookId: Long, - accessCookies: Array = bookManagerCookies, + content: ModifyBookRequest = ModifyBookRequest( + title = "삶의 목적을 찾는 45가지 방법", + author = "ChatGPT", + totalQuantity = 10, + bookDepartment = BookDepartmentType.DOCUMENT + ), + bookId: Long, + accessCookies: Array = bookManagerCookies, ): ResultActions = - mockMvc.perform( - put("${BOOK_URL}/{bookId}", bookId) - .content(asJsonString(content)) - .cookie(*accessCookies) - .contentType(MediaType.APPLICATION_JSON_VALUE) - ) + mockMvc.perform( + put("${BOOK_URL}/{bookId}", bookId) + .content(asJsonString(content)) + .cookie(*accessCookies) + .contentType(MediaType.APPLICATION_JSON_VALUE) + ) fun callModifyBookThumbnailApi(bookId: Long): ResultActions = - mockMvc.perform( - multipart("${BOOK_URL}/{bookId}/thumbnail", bookId) - .file(thumbnailTestHelper.smallThumbnailFile) - .with { request -> - request.method = "PATCH" - request - } - .cookie(*bookManagerCookies) - .contentType(MediaType.MULTIPART_FORM_DATA) - ) + mockMvc.perform( + multipart("${BOOK_URL}/{bookId}/thumbnail", bookId) + .file(thumbnailTestHelper.smallThumbnailFile) + .with { request -> + request.method = "PATCH" + request + } + .cookie(*bookManagerCookies) + .contentType(MediaType.MULTIPART_FORM_DATA) + ) fun callGetBookDetailApi( - bookId: Long, - accessCookies: Array = bookManagerCookies, + bookId: Long, + accessCookies: Array = bookManagerCookies, ): ResultActions = mockMvc.perform( - get("${BOOK_URL}/{bookId}", bookId) - .cookie(*accessCookies) + get("${BOOK_URL}/{bookId}", bookId) + .cookie(*accessCookies) ) fun getBorrowDetailResponseDocs(): Array { return arrayOf( - field("borrowInfoId", "대출 정보 ID"), - field("bookId", "대출할 책의 ID"), - field("bookTitle", "대출할 책의 제목"), - field("author", "대출할 책의 저자"), - field("totalQuantity", "대출할 책의 전체 수량"), - field("currentQuantity", "대출할 책의 남은 수량"), - field("borrowerId", "대출자의 ID"), - field("borrowerRealName", "대출자의 실명"), - field("requestDatetime", "대출 요청을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), - field("borrowDateTime", "대출 승인을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), - field("expiredDateTime", "반납 예정 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), - field( - "status", "대출의 현재 상태\r\n\r\n${BookBorrowStatus.BookBorrowStatusType.getAllList()}" - ), + field("borrowInfoId", "대출 정보 ID"), + field("bookId", "대출할 책의 ID"), + field("bookTitle", "대출할 책의 제목"), + field("author", "대출할 책의 저자"), + field("totalQuantity", "대출할 책의 전체 수량"), + field("currentQuantity", "대출할 책의 남은 수량"), + field("borrowerId", "대출자의 ID"), + field("borrowerRealName", "대출자의 실명"), + field("requestDatetime", "대출 요청을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), + field("borrowDateTime", "대출 승인을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), + field("expiredDateTime", "반납 예정 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), + field( + "status", "대출의 현재 상태\r\n\r\n${BookBorrowStatus.BookBorrowStatusType.getAllList()}" + ), ) } fun getBookDetailResponseDocs(): Array { return arrayOf( - field("bookId", "책 ID"), - field("thumbnailPath", "책 썸네일 주소"), - field("title", "책 이름"), - field("author", "책 저자"), - field("currentQuantity", "책 현재 수량"), - field("totalQuantity", "책 전체 수량"), - field("bookDepartment", "책 카테고리"), - *listHelper("borrowInfos", *getBorrowDetailResponseDocs()), + field("bookId", "책 ID"), + field("thumbnailPath", "책 썸네일 주소"), + field("title", "책 이름"), + field("author", "책 저자"), + field("currentQuantity", "책 현재 수량"), + field("totalQuantity", "책 전체 수량"), + field("bookDepartment", "책 카테고리"), + *listHelper("borrowInfos", *getBorrowDetailResponseDocs()), ) } fun getBorrowLogResponseDocs(): Array { return arrayOf( - field("borrowInfoId", "대출 정보 ID (대출 로그 id는 아닙니다)"), - field("bookId", "대출한 책의 ID"), - field("bookTitle", "대출한 책의 제목"), - field("author", "대출한 책의 저자"), - field("borrowerId", "대출한 유저의 Id"), - field("borrowerRealName", "대출한 유저의 실명"), - field("borrowDateTime", "대출을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), - field("expireDateTime", "반납 예정 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), - field("returnDateTime", "반납 승인을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)").optional(), - field("rejectDateTime", "반납 반려를 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)").optional(), - field("status", "로그가 찍힐 때의 대출 상태. 종류: ${LogType.values().map(LogType::name).joinToString()}"), + field("borrowInfoId", "대출 정보 ID (대출 로그 id는 아닙니다)"), + field("bookId", "대출한 책의 ID"), + field("bookTitle", "대출한 책의 제목"), + field("author", "대출한 책의 저자"), + field("borrowerId", "대출한 유저의 Id"), + field("borrowerRealName", "대출한 유저의 실명"), + field("borrowDateTime", "대출을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), + field("expireDateTime", "반납 예정 시간 (양식: $RESPONSE_DATETIME_FORMAT)"), + field("returnDateTime", "반납 승인을 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)").optional(), + field("rejectDateTime", "반납 반려를 한 시간 (양식: $RESPONSE_DATETIME_FORMAT)").optional(), + field("status", "로그가 찍힐 때의 대출 상태. 종류: ${LogType.values().map(LogType::name).joinToString()}"), ) } } diff --git a/src/test/java/com/keeper/homepage/domain/library/api/BookManageControllerTest.kt b/src/test/java/com/keeper/homepage/domain/library/api/BookManageControllerTest.kt index 98b713b9b..6880fa274 100644 --- a/src/test/java/com/keeper/homepage/domain/library/api/BookManageControllerTest.kt +++ b/src/test/java/com/keeper/homepage/domain/library/api/BookManageControllerTest.kt @@ -42,10 +42,10 @@ import java.util.stream.Stream const val HALF_NANOSECOND = 500000000 fun LocalDateTime.formatting(format: String) = - if (this.nano > HALF_NANOSECOND) - this.plusSeconds(1).format(DateTimeFormatter.ofPattern(format)) - else - this.format(DateTimeFormatter.ofPattern(format)) + if (this.nano > HALF_NANOSECOND) + this.plusSeconds(1).format(DateTimeFormatter.ofPattern(format)) + else + this.format(DateTimeFormatter.ofPattern(format)) class BookManageControllerTest : BookManageApiTestHelper() { @@ -67,10 +67,10 @@ class BookManageControllerTest : BookManageApiTestHelper() { bookBorrowInfoTestHelper.generate(borrowStatus = 대출반려, book = bookList[bookCount - 1]) bookBorrowInfoTestHelper.generate(borrowStatus = 반납완료, book = bookList[bookCount - 1]) validParams = multiValueMapOf( - "search" to "", - "page" to "0", - "size" to "3", - "searchType" to "all", + "search" to "", + "page" to "0", + "size" to "3", + "searchType" to "all", ) } @@ -78,51 +78,51 @@ class BookManageControllerTest : BookManageApiTestHelper() { fun `유효한 요청이면 관리자 책 목록 가져오기는 성공해야 한다`() { val securedValue = getSecuredValue(BookManageController::class.java, "getBooks") callGetBooksApi(validParams).andDo(MockMvcResultHandlers.print()) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].bookId").value(bookList[3].id)) - .andExpect(jsonPath("$.content[0].title").value(bookList[3].title)) - .andExpect(jsonPath("$.content[0].author").value(bookList[3].author)) - .andExpect(jsonPath("$.content[0].totalQuantity").value(bookList[3].totalQuantity)) - .andExpect(jsonPath("$.content[0].currentQuantity").value(bookList[3].currentQuantity)) - .andExpect(jsonPath("$.content[0].bookDepartment").value(bookList[3].bookDepartment.type.name)) - .andExpect(jsonPath("$.content[0].thumbnailPath").value(bookList[3].thumbnailPath)) - .andExpect(jsonPath("$.content[0].borrowInfos[0].borrowInfoId").value(borrowList[3].id)) - .andExpect(jsonPath("$.content[1].borrowInfos[0].borrowInfoId").value(borrowList[2].id)) - .andExpect(jsonPath("$.content[2].borrowInfos[0].borrowInfoId").value(borrowList[1].id)) - .andExpect(jsonPath("$.content[0].borrowInfos.length()").value(2)) - .andExpect(jsonPath("$.content[1].borrowInfos.length()").value(1)) - .andExpect(jsonPath("$.content[2].borrowInfos.length()").value(1)) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("3")) - .andExpect(jsonPath("$.totalPages").value("2")) - .andDo( - document( - "manager-get-books", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - queryParameters( - parameterWithName("page").description("페이지 (양수여야 합니다.)") - .optional(), - parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") - .optional(), - parameterWithName("search").description("책의 제목이나 저자를 검색합니다. (만약 빈 값으로 보낼 경우 책 관련 정보를 모두 가져옵니다.)") - .optional(), - parameterWithName("searchType").description("검색 타입") - .attributes( - Attributes.Attribute( - "format", - "title: 제목, author: 저자, all: 제목 + 저자, null : 전체 도서 목록 조회" + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].bookId").value(bookList[3].id)) + .andExpect(jsonPath("$.content[0].title").value(bookList[3].title)) + .andExpect(jsonPath("$.content[0].author").value(bookList[3].author)) + .andExpect(jsonPath("$.content[0].totalQuantity").value(bookList[3].totalQuantity)) + .andExpect(jsonPath("$.content[0].currentQuantity").value(bookList[3].currentQuantity)) + .andExpect(jsonPath("$.content[0].bookDepartment").value(bookList[3].bookDepartment.type.name)) + .andExpect(jsonPath("$.content[0].thumbnailPath").value(bookList[3].thumbnailPath)) + .andExpect(jsonPath("$.content[0].borrowInfos[0].borrowInfoId").value(borrowList[3].id)) + .andExpect(jsonPath("$.content[1].borrowInfos[0].borrowInfoId").value(borrowList[2].id)) + .andExpect(jsonPath("$.content[2].borrowInfos[0].borrowInfoId").value(borrowList[1].id)) + .andExpect(jsonPath("$.content[0].borrowInfos.length()").value(2)) + .andExpect(jsonPath("$.content[1].borrowInfos.length()").value(1)) + .andExpect(jsonPath("$.content[2].borrowInfos.length()").value(1)) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("3")) + .andExpect(jsonPath("$.totalPages").value("2")) + .andDo( + document( + "manager-get-books", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + queryParameters( + parameterWithName("page").description("페이지 (양수여야 합니다.)") + .optional(), + parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") + .optional(), + parameterWithName("search").description("책의 제목이나 저자를 검색합니다. (만약 빈 값으로 보낼 경우 책 관련 정보를 모두 가져옵니다.)") + .optional(), + parameterWithName("searchType").description("검색 타입") + .attributes( + Attributes.Attribute( + "format", + "title: 제목, author: 저자, all: 제목 + 저자, null : 전체 도서 목록 조회" + ) + ) + .optional(), + ), + responseFields( + *pageHelper(*getBookDetailResponseDocs()) ) - ) - .optional(), - ), - responseFields( - *pageHelper(*getBookDetailResponseDocs()) - ) + ) ) - ) } } @@ -131,53 +131,53 @@ class BookManageControllerTest : BookManageApiTestHelper() { inner class `책 추가` { private val validRequest = BookRequest( - title = "삶의 목적을 찾는 45가지 방법", - author = "ChatGPT", - totalQuantity = 10, - bookDepartment = BookDepartmentType.DOCUMENT + title = "삶의 목적을 찾는 45가지 방법", + author = "ChatGPT", + totalQuantity = 10, + bookDepartment = BookDepartmentType.DOCUMENT ) @Test fun `유효한 요청이면 책 등록은 성공해야 한다`() { val securedValue = getSecuredValue(BookManageController::class.java, "addBook") callAddBookApi(hasThumbnail = true) - .andExpect(status().isCreated) - .andDo( - document( - "assign-book", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - requestPartFields( - "bookMetaData", - fieldWithPath("title").description("책 제목 (최대 ${MAX_TITLE_LENGTH}자)"), - fieldWithPath("author").description("저자 (최대 ${MAX_AUTHOR_LENGTH}자)"), - fieldWithPath("bookDepartment") - .attributes( - key("format") - .value( - BookDepartmentType.values().map(BookDepartmentType::getName).joinToString() - ) - ).description("책 카테고리"), - fieldWithPath("totalQuantity").description("책 수량 (1권 이상 ${MAX_TOTAL_QUANTITY_LENGTH}권 이하)"), - ), - requestParts( - partWithName("bookMetaData").description("책 정보"), - partWithName("thumbnail").description("책의 썸네일") - .optional(), - ), - responseHeaders( - headerWithName(HttpHeaders.LOCATION).description("생성된 책의 URI") - ) + .andExpect(status().isCreated) + .andDo( + document( + "assign-book", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + requestPartFields( + "bookMetaData", + fieldWithPath("title").description("책 제목 (최대 ${MAX_TITLE_LENGTH}자)"), + fieldWithPath("author").description("저자 (최대 ${MAX_AUTHOR_LENGTH}자)"), + fieldWithPath("bookDepartment") + .attributes( + key("format") + .value( + BookDepartmentType.values().map(BookDepartmentType::getName).joinToString() + ) + ).description("책 카테고리"), + fieldWithPath("totalQuantity").description("책 수량 (1권 이상 ${MAX_TOTAL_QUANTITY_LENGTH}권 이하)"), + ), + requestParts( + partWithName("bookMetaData").description("책 정보"), + partWithName("thumbnail").description("책의 썸네일") + .optional(), + ), + responseHeaders( + headerWithName(HttpHeaders.LOCATION).description("생성된 책의 URI") + ) + ) ) - ) } @Test fun `썸네일이 없어도 책 등록은 성공해야 한다`() { callAddBookApi() - .andExpect(status().isCreated) + .andExpect(status().isCreated) } @ParameterizedTest @@ -188,19 +188,19 @@ class BookManageControllerTest : BookManageApiTestHelper() { property.isAccessible = true property.set(invalidRequest, invalidValue) callAddBookApi(request = invalidRequest) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } fun `유효하지 않은 요청의 책 등록은 실패해야 한다`(): Stream { return Stream.of( - Arguments.arguments("title", ""), - Arguments.arguments("title", null), - Arguments.arguments("author", ""), - Arguments.arguments("author", null), - Arguments.arguments("totalQuantity", -1L), - Arguments.arguments("totalQuantity", 0L), - Arguments.arguments("totalQuantity", 21L), - Arguments.arguments("bookDepartment", null), + Arguments.arguments("title", ""), + Arguments.arguments("title", null), + Arguments.arguments("author", ""), + Arguments.arguments("author", null), + Arguments.arguments("totalQuantity", -1L), + Arguments.arguments("totalQuantity", 0L), + Arguments.arguments("totalQuantity", 21L), + Arguments.arguments("bookDepartment", null), ) } @@ -210,7 +210,7 @@ class BookManageControllerTest : BookManageApiTestHelper() { member.assignJob(MemberJob.MemberJobType.ROLE_회원) callAddBookApi(accessCookies = memberTestHelper.getTokenCookies(member)) - .andExpect(status().isForbidden) + .andExpect(status().isForbidden) } } @@ -222,19 +222,19 @@ class BookManageControllerTest : BookManageApiTestHelper() { fun `유효한 요청이면 책 삭제는 성공해야 한다`() { val securedValue = getSecuredValue(BookManageController::class.java, "deleteBook") callDeleteBookApi() - .andExpect(status().isNoContent) - .andDo( - document( - "delete-book", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("bookId").description("책 id") - ) + .andExpect(status().isNoContent) + .andDo( + document( + "delete-book", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("bookId").description("책 id") + ) + ) ) - ) } @Test @@ -243,7 +243,7 @@ class BookManageControllerTest : BookManageApiTestHelper() { member.assignJob(MemberJob.MemberJobType.ROLE_회원) callDeleteBookApi(accessCookies = memberTestHelper.getTokenCookies(member)) - .andExpect(status().isForbidden) + .andExpect(status().isForbidden) } } @@ -256,62 +256,62 @@ class BookManageControllerTest : BookManageApiTestHelper() { @BeforeEach fun generateNewBook() { book = bookTestHelper.builder() - .thumbnail(thumbnailTestHelper.generateThumbnail()) - .build() + .thumbnail(thumbnailTestHelper.generateThumbnail()) + .build() } @Test fun `유효한 요청이면 책 수정은 성공해야 한다`() { val securedValue = getSecuredValue(BookManageController::class.java, "addBook") callModifyBookApi(bookId = book.id) - .andExpect(status().isNoContent) - .andDo( - document( - "modify-book", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("bookId").description("책 id") - ), - requestFields( - field("title", "책 제목 (최대 ${MAX_TITLE_LENGTH}자)"), - field("author", "저자 (최대 ${MAX_AUTHOR_LENGTH}자)"), - field("bookDepartment", "책 카테고리") - .attributes( - key("format") - .value( - BookDepartmentType.values().map(BookDepartmentType::getName).joinToString() - ) - ), - field("totalQuantity", "책 수량 (1권 이상 ${MAX_TOTAL_QUANTITY_LENGTH}권 이하)"), - ), + .andExpect(status().isNoContent) + .andDo( + document( + "modify-book", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("bookId").description("책 id") + ), + requestFields( + field("title", "책 제목 (최대 ${MAX_TITLE_LENGTH}자)"), + field("author", "저자 (최대 ${MAX_AUTHOR_LENGTH}자)"), + field("bookDepartment", "책 카테고리") + .attributes( + key("format") + .value( + BookDepartmentType.values().map(BookDepartmentType::getName).joinToString() + ) + ), + field("totalQuantity", "책 수량 (1권 이상 ${MAX_TOTAL_QUANTITY_LENGTH}권 이하)"), + ), + ) ) - ) } @Test fun `유효한 요청이면 책 썸네일 수정은 성공해야 한다`() { val securedValue = getSecuredValue(BookManageController::class.java, "addBook") callModifyBookThumbnailApi(bookId = book.id) - .andExpect(status().isNoContent) - .andDo( - document( - "modify-book-thumbnail", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("bookId").description("책 id") - ), - requestParts( - partWithName("thumbnail").description("책의 썸네일 (null 값으로 보낼 경우 기본 썸네일로 지정됩니다.)") - .optional(), - ) + .andExpect(status().isNoContent) + .andDo( + document( + "modify-book-thumbnail", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("bookId").description("책 id") + ), + requestParts( + partWithName("thumbnail").description("책의 썸네일 (null 값으로 보낼 경우 기본 썸네일로 지정됩니다.)") + .optional(), + ) + ) ) - ) } @Test @@ -320,7 +320,7 @@ class BookManageControllerTest : BookManageApiTestHelper() { member.assignJob(MemberJob.MemberJobType.ROLE_회원) callModifyBookApi(bookId = book.id, accessCookies = memberTestHelper.getTokenCookies(member)) - .andExpect(status().isForbidden) + .andExpect(status().isForbidden) } } @@ -335,23 +335,23 @@ class BookManageControllerTest : BookManageApiTestHelper() { @BeforeEach fun generateNewBook() { book = bookTestHelper.builder() - .totalQuantity(3) - .currentQuantity(3) - .thumbnail(thumbnailTestHelper.generateThumbnail()) - .build() + .totalQuantity(3) + .currentQuantity(3) + .thumbnail(thumbnailTestHelper.generateThumbnail()) + .build() borrowList = listOf( - bookBorrowInfoTestHelper.builder() - .book(book) - .borrowStatus(getBookBorrowStatusBy(대출중)) - .build(), - bookBorrowInfoTestHelper.builder() - .book(book) - .borrowStatus(getBookBorrowStatusBy(반납대기)) - .build(), - bookBorrowInfoTestHelper.builder() - .book(book) - .borrowStatus(getBookBorrowStatusBy(반납완료)) - .build(), + bookBorrowInfoTestHelper.builder() + .book(book) + .borrowStatus(getBookBorrowStatusBy(대출중)) + .build(), + bookBorrowInfoTestHelper.builder() + .book(book) + .borrowStatus(getBookBorrowStatusBy(반납대기)) + .build(), + bookBorrowInfoTestHelper.builder() + .book(book) + .borrowStatus(getBookBorrowStatusBy(반납완료)) + .build(), ) } @@ -361,40 +361,40 @@ class BookManageControllerTest : BookManageApiTestHelper() { em.clear() val securedValue = getSecuredValue(BookManageController::class.java, "getBookDetail") callGetBookDetailApi(bookId = book.id) - .andExpect(status().isOk) - .andExpect(jsonPath("$.bookId").value(book.id)) - .andExpect(jsonPath("$.title").value(book.title)) - .andExpect(jsonPath("$.author").value(book.author)) - .andExpect(jsonPath("$.totalQuantity").value(book.totalQuantity)) - .andExpect(jsonPath("$.currentQuantity").value(book.currentQuantity)) - .andExpect(jsonPath("$.bookDepartment").value(book.bookDepartment.type.name)) - .andExpect(jsonPath("$.totalQuantity").value(3)) - .andExpect(jsonPath("$.currentQuantity").value(1)) - .andExpect(jsonPath("$.thumbnailPath").value(book.thumbnail.path)) - .andExpect(jsonPath("$.borrowInfos[0].borrowInfoId").value(borrowList[0].id)) - .andExpect(jsonPath("$.borrowInfos[0].bookId").value(borrowList[0].book.id)) - .andExpect(jsonPath("$.borrowInfos[0].bookTitle").value(borrowList[0].book.title)) - .andExpect(jsonPath("$.borrowInfos[0].author").value(borrowList[0].book.author)) - .andExpect(jsonPath("$.borrowInfos[0].borrowerId").value(borrowList[0].member.id)) - .andExpect( - jsonPath("$.borrowInfos[0].borrowerRealName") - .value(borrowList[0].member.realName) - ) - .andDo( - document( - "get-book-detail", - requestCookies( - cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("bookId").description("책 id") - ), - responseFields( - *getBookDetailResponseDocs() - ), + .andExpect(status().isOk) + .andExpect(jsonPath("$.bookId").value(book.id)) + .andExpect(jsonPath("$.title").value(book.title)) + .andExpect(jsonPath("$.author").value(book.author)) + .andExpect(jsonPath("$.totalQuantity").value(book.totalQuantity)) + .andExpect(jsonPath("$.currentQuantity").value(book.currentQuantity)) + .andExpect(jsonPath("$.bookDepartment").value(book.bookDepartment.type.name)) + .andExpect(jsonPath("$.totalQuantity").value(3)) + .andExpect(jsonPath("$.currentQuantity").value(1)) + .andExpect(jsonPath("$.thumbnailPath").value(book.thumbnail.path)) + .andExpect(jsonPath("$.borrowInfos[0].borrowInfoId").value(borrowList[0].id)) + .andExpect(jsonPath("$.borrowInfos[0].bookId").value(borrowList[0].book.id)) + .andExpect(jsonPath("$.borrowInfos[0].bookTitle").value(borrowList[0].book.title)) + .andExpect(jsonPath("$.borrowInfos[0].author").value(borrowList[0].book.author)) + .andExpect(jsonPath("$.borrowInfos[0].borrowerId").value(borrowList[0].member.id)) + .andExpect( + jsonPath("$.borrowInfos[0].borrowerRealName") + .value(borrowList[0].member.realName) + ) + .andDo( + document( + "get-book-detail", + requestCookies( + cookieWithName(ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("bookId").description("책 id") + ), + responseFields( + *getBookDetailResponseDocs() + ), + ) ) - ) } } } diff --git a/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageApiTestHelper.kt b/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageApiTestHelper.kt index 36cdb6dbb..7f526b52d 100644 --- a/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageApiTestHelper.kt +++ b/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageApiTestHelper.kt @@ -14,58 +14,58 @@ const val BORROW_URL = "/manage/borrow-infos" class BorrowManageApiTestHelper : BookManageApiTestHelper() { fun callGetBorrowApi( - params: MultiValueMap = LinkedMultiValueMap(), - borrowStatus: BorrowStatusDto?, - accessCookies: Array = bookManagerCookies, + params: MultiValueMap = LinkedMultiValueMap(), + borrowStatus: BorrowStatusDto?, + accessCookies: Array = bookManagerCookies, ): ResultActions = mockMvc.perform( - get(BORROW_URL) - .params(params) - .param("status", borrowStatus?.status) - .cookie(*accessCookies) + get(BORROW_URL) + .params(params) + .param("status", borrowStatus?.status) + .cookie(*accessCookies) ) fun callApproveBorrowApi( - borrowId: Long, - accessCookies: Array = bookManagerCookies + borrowId: Long, + accessCookies: Array = bookManagerCookies ): ResultActions = mockMvc.perform( - post("${BORROW_URL}/{borrowId}/requests-approve", borrowId) - .cookie(*accessCookies) + post("${BORROW_URL}/{borrowId}/requests-approve", borrowId) + .cookie(*accessCookies) ) fun callDenyBorrowApi( - borrowId: Long, - accessCookies: Array = bookManagerCookies + borrowId: Long, + accessCookies: Array = bookManagerCookies ): ResultActions = mockMvc.perform( - post("${BORROW_URL}/{borrowId}/requests-deny", borrowId) - .cookie(*accessCookies) + post("${BORROW_URL}/{borrowId}/requests-deny", borrowId) + .cookie(*accessCookies) ) fun callApproveReturnApi( - borrowId: Long, - accessCookies: Array = bookManagerCookies + borrowId: Long, + accessCookies: Array = bookManagerCookies ): ResultActions = mockMvc.perform( - post("${BORROW_URL}/{borrowId}/return-approve", borrowId) - .cookie(*accessCookies) + post("${BORROW_URL}/{borrowId}/return-approve", borrowId) + .cookie(*accessCookies) ) fun callDenyReturnApi( - borrowId: Long, - accessCookies: Array = bookManagerCookies + borrowId: Long, + accessCookies: Array = bookManagerCookies ): ResultActions = mockMvc.perform( - post("${BORROW_URL}/{borrowId}/return-deny", borrowId) - .cookie(*accessCookies) + post("${BORROW_URL}/{borrowId}/return-deny", borrowId) + .cookie(*accessCookies) ) fun callGetBorrowLogApi( - params: MultiValueMap = LinkedMultiValueMap(), - searchType: LogType? = null, - search: String? = null, - accessCookies: Array = bookManagerCookies, + params: MultiValueMap = LinkedMultiValueMap(), + searchType: LogType? = null, + search: String? = null, + accessCookies: Array = bookManagerCookies, ): ResultActions = mockMvc.perform( - get("${BORROW_URL}/logs") - .params(params) - .param("searchType", searchType?.name) - .param("search", search) - .cookie(*accessCookies) + get("${BORROW_URL}/logs") + .params(params) + .param("searchType", searchType?.name) + .param("search", search) + .cookie(*accessCookies) ) } diff --git a/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageControllerTest.kt b/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageControllerTest.kt index 4ded5b642..75c439437 100644 --- a/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageControllerTest.kt +++ b/src/test/java/com/keeper/homepage/domain/library/api/BorrowManageControllerTest.kt @@ -41,93 +41,93 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { @Test fun `유효한 요청이면 책 대여 정보 가져오기는 성공해야 한다`() { val securedValue = - getSecuredValue(BorrowManageController::class.java, "getBorrowRequests") + getSecuredValue(BorrowManageController::class.java, "getBorrowRequests") callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "3"), - borrowStatus = BorrowStatusDto.REQUESTS + params = multiValueMapOf("page" to "0", "size" to "3"), + borrowStatus = BorrowStatusDto.REQUESTS ) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) - .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) - .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) - .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) - .andExpect(jsonPath("$.content[0].totalQuantity").value(borrowInfoList[0].book.totalQuantity)) - .andExpect(jsonPath("$.content[0].currentQuantity").value(borrowInfoList[0].book.currentQuantity)) - .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) - .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("3")) - .andExpect(jsonPath("$.totalPages").value("7")) - .andDo( - document( - "get-borrow-infos", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - queryParameters( - parameterWithName("page").description("페이지 (양수여야 합니다.)") - .optional(), - parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") - .optional(), - parameterWithName("search").description("검색 키워드. 도서명, 저자, 실명에서 검색해옵니다.") - .optional(), - parameterWithName("status") - .attributes( - key("format").value( - BorrowStatusDto.values().map(BorrowStatusDto::status).joinToString() + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) + .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) + .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) + .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) + .andExpect(jsonPath("$.content[0].totalQuantity").value(borrowInfoList[0].book.totalQuantity)) + .andExpect(jsonPath("$.content[0].currentQuantity").value(borrowInfoList[0].book.currentQuantity)) + .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) + .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("3")) + .andExpect(jsonPath("$.totalPages").value("7")) + .andDo( + document( + "get-borrow-infos", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + queryParameters( + parameterWithName("page").description("페이지 (양수여야 합니다.)") + .optional(), + parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") + .optional(), + parameterWithName("search").description("검색 키워드. 도서명, 저자, 실명에서 검색해옵니다.") + .optional(), + parameterWithName("status") + .attributes( + key("format").value( + BorrowStatusDto.values().map(BorrowStatusDto::status).joinToString() + ) + ).description("만약 빈 값으로 보낼 경우 대출 관련 정보를 모두 가져옵니다.") + .optional() + ), + responseFields( + *pageHelper(*getBorrowDetailResponseDocs()) ) - ).description("만약 빈 값으로 보낼 경우 대출 관련 정보를 모두 가져옵니다.") - .optional() - ), - responseFields( - *pageHelper(*getBorrowDetailResponseDocs()) - ) + ) ) - ) } @Test fun `페이지와 사이즈에 해당하는 대여 목록을 가져와야 한다`() { callGetBorrowApi( - params = multiValueMapOf("page" to "1", "size" to "5"), - borrowStatus = BorrowStatusDto.REQUESTS + params = multiValueMapOf("page" to "1", "size" to "5"), + borrowStatus = BorrowStatusDto.REQUESTS ) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[5].id)) - .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[5].book.id)) - .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[5].book.title)) - .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[5].book.author)) - .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[5].member.id)) - .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[5].member.realName)) - .andExpect(jsonPath("$.number").value("1")) - .andExpect(jsonPath("$.size").value("5")) - .andExpect(jsonPath("$.totalPages").value("4")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[5].id)) + .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[5].book.id)) + .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[5].book.title)) + .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[5].book.author)) + .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[5].member.id)) + .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[5].member.realName)) + .andExpect(jsonPath("$.number").value("1")) + .andExpect(jsonPath("$.size").value("5")) + .andExpect(jsonPath("$.totalPages").value("4")) } @Test fun `페이지와 사이즈가 인자로 오지 않아도 default 결과를 반환해야 한다`() { callGetBorrowApi(borrowStatus = BorrowStatusDto.REQUESTS) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) - .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) - .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) - .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) - .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) - .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("10")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) + .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) + .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) + .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) + .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) + .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("10")) + .andExpect(jsonPath("$.totalPages").value("2")) } @ParameterizedTest @CsvSource("-1, 10", "0, -1", "0, 2", "0, 101") fun `올바르지 않은 요청은 실패해야 한다`(page: String, size: String) { callGetBorrowApi( - params = multiValueMapOf("page" to page, "size" to size), - borrowStatus = BorrowStatusDto.REQUESTS + params = multiValueMapOf("page" to page, "size" to size), + borrowStatus = BorrowStatusDto.REQUESTS ) - .andExpect(status().isBadRequest) + .andExpect(status().isBadRequest) } @Test @@ -136,11 +136,11 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..3).map { bookBorrowInfoTestHelper.generate(대출중, bookTestHelper.generate()) } (1..3).map { bookBorrowInfoTestHelper.generate(반납대기, bookTestHelper.generate()) } callGetBorrowApi(borrowStatus = null) - .andExpect(status().isOk) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("10")) - .andExpect(jsonPath("$.totalPages").value("3")) - .andExpect(jsonPath("$.totalElements").value("29")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("10")) + .andExpect(jsonPath("$.totalPages").value("3")) + .andExpect(jsonPath("$.totalElements").value("29")) } @Test @@ -149,16 +149,16 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..3).map { bookBorrowInfoTestHelper.generate(대출중, bookTestHelper.generate()) } (1..3).map { bookBorrowInfoTestHelper.generate(반납대기, bookTestHelper.generate()) } callGetBorrowApi(borrowStatus = BorrowStatusDto.REQUESTS) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) - .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) - .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) - .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) - .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) - .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("10")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) + .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) + .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) + .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) + .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) + .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("10")) + .andExpect(jsonPath("$.totalPages").value("2")) } @Test @@ -167,17 +167,17 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..3).map { bookBorrowInfoTestHelper.generate(대출중, bookTestHelper.generate()) } (1..3).map { bookBorrowInfoTestHelper.generate(반납대기, bookTestHelper.generate()) } callGetBorrowApi(borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) - .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) - .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) - .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) - .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) - .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("10")) - .andExpect(jsonPath("$.totalPages").value("3")) - .andExpect(jsonPath("$.totalElements").value("23")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].borrowInfoId").value(borrowInfoList[0].id)) + .andExpect(jsonPath("$.content[0].bookId").value(borrowInfoList[0].book.id)) + .andExpect(jsonPath("$.content[0].bookTitle").value(borrowInfoList[0].book.title)) + .andExpect(jsonPath("$.content[0].author").value(borrowInfoList[0].book.author)) + .andExpect(jsonPath("$.content[0].borrowerId").value(borrowInfoList[0].member.id)) + .andExpect(jsonPath("$.content[0].borrowerRealName").value(borrowInfoList[0].member.realName)) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("10")) + .andExpect(jsonPath("$.totalPages").value("3")) + .andExpect(jsonPath("$.totalElements").value("23")) } @Test @@ -197,13 +197,13 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { generateBorrowInfoByTitle(대출중, "나다") // X generateBorrowInfoByTitle(반납완료, "나다") // X callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), - borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN + params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), + borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN ).andExpect(status().isOk) - .andExpect(jsonPath("$.totalElements").value("8")) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("5")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(jsonPath("$.totalElements").value("8")) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("5")) + .andExpect(jsonPath("$.totalPages").value("2")) } @Test @@ -223,13 +223,13 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { generateBorrowInfoByAuthor(대출중, "나다") // X generateBorrowInfoByAuthor(반납완료, "나다") // X callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), - borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN + params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), + borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN ).andExpect(status().isOk) - .andExpect(jsonPath("$.totalElements").value("8")) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("5")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(jsonPath("$.totalElements").value("8")) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("5")) + .andExpect(jsonPath("$.totalPages").value("2")) } @Test @@ -249,13 +249,13 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { generateBorrowInfoByMemberRealName(대출중, "나다") // X generateBorrowInfoByMemberRealName(반납완료, "나다") // X callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), - borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN + params = multiValueMapOf("page" to "0", "size" to "5", "search" to searchKeyword), + borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN ).andExpect(status().isOk) - .andExpect(jsonPath("$.totalElements").value("8")) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("5")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(jsonPath("$.totalElements").value("8")) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("5")) + .andExpect(jsonPath("$.totalPages").value("2")) } @Test @@ -264,9 +264,9 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..3).map { bookBorrowInfoTestHelper.generate(대출중, bookTestHelper.generate()) } (1..3).map { bookBorrowInfoTestHelper.generate(반납대기, bookTestHelper.generate()) } callGetBorrowApi(borrowStatus = BorrowStatusDto.REQUESTS_OR_WILL_RETURN).andExpect(status().isOk) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("10")) - .andExpect(jsonPath("$.totalPages").value("3")) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("10")) + .andExpect(jsonPath("$.totalPages").value("3")) } @Test @@ -275,14 +275,14 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..4).map { bookBorrowInfoTestHelper.generate(대출중, bookTestHelper.generate()) } (1..8).map { bookBorrowInfoTestHelper.generate(반납대기, bookTestHelper.generate()) } callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "3"), - borrowStatus = BorrowStatusDto.WILL_RETURN + params = multiValueMapOf("page" to "0", "size" to "3"), + borrowStatus = BorrowStatusDto.WILL_RETURN ) - .andExpect(status().isOk) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("3")) - .andExpect(jsonPath("$.totalPages").value("3")) - .andExpect(jsonPath("$.totalElements").value("8")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("3")) + .andExpect(jsonPath("$.totalPages").value("3")) + .andExpect(jsonPath("$.totalElements").value("8")) } @Test @@ -292,69 +292,69 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { (1..2).map { bookBorrowInfoTestHelper.generate(대출반려, bookTestHelper.generate()) } (1..4).map { bookBorrowInfoTestHelper.generate( - 대출중, - bookTestHelper.generate(), - LocalDateTime.now().minusDays(1) + 대출중, + bookTestHelper.generate(), + LocalDateTime.now().minusDays(1) ) } (1..8).map { bookBorrowInfoTestHelper.generate( - 반납대기, - bookTestHelper.generate(), - LocalDateTime.now().minusDays(1) + 반납대기, + bookTestHelper.generate(), + LocalDateTime.now().minusDays(1) ) } callGetBorrowApi( - params = multiValueMapOf("page" to "0", "size" to "5"), - borrowStatus = BorrowStatusDto.OVERDUE + params = multiValueMapOf("page" to "0", "size" to "5"), + borrowStatus = BorrowStatusDto.OVERDUE ) - .andExpect(status().isOk) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("5")) - .andExpect(jsonPath("$.totalElements").value("12")) - .andExpect(jsonPath("$.totalPages").value("3")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("5")) + .andExpect(jsonPath("$.totalElements").value("12")) + .andExpect(jsonPath("$.totalPages").value("3")) } private fun generateBorrowInfoByTitle( - type: BookBorrowStatus.BookBorrowStatusType, - title: String + type: BookBorrowStatus.BookBorrowStatusType, + title: String ): BookBorrowInfo { return bookBorrowInfoTestHelper.builder() - .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) - .book( - bookTestHelper.builder() - .title(title) - .build() - ) - .build() + .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) + .book( + bookTestHelper.builder() + .title(title) + .build() + ) + .build() } private fun generateBorrowInfoByAuthor( - type: BookBorrowStatus.BookBorrowStatusType, - author: String + type: BookBorrowStatus.BookBorrowStatusType, + author: String ): BookBorrowInfo { return bookBorrowInfoTestHelper.builder() - .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) - .book( - bookTestHelper.builder() - .author(author) - .build() - ) - .build() + .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) + .book( + bookTestHelper.builder() + .author(author) + .build() + ) + .build() } private fun generateBorrowInfoByMemberRealName( - type: BookBorrowStatus.BookBorrowStatusType, - name: String + type: BookBorrowStatus.BookBorrowStatusType, + name: String ): BookBorrowInfo { return bookBorrowInfoTestHelper.builder() - .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) - .member( - memberTestHelper.builder() - .realName(RealName.from(name)) - .build() - ) - .build() + .borrowStatus(BookBorrowStatus.getBookBorrowStatusBy(type)) + .member( + memberTestHelper.builder() + .realName(RealName.from(name)) + .build() + ) + .build() } } @@ -374,19 +374,19 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { val beforeBorrowingQuantity = borrowInfo.book.countInBorrowing val securedValue = getSecuredValue(BorrowManageController::class.java, "approveBorrow") callApproveBorrowApi(borrowInfo.id) - .andExpect(status().isNoContent) - .andDo( - document( - "borrow-requests-approve", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("borrowId").description("대출 ID") - ) + .andExpect(status().isNoContent) + .andDo( + document( + "borrow-requests-approve", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("borrowId").description("대출 ID") + ) + ) ) - ) borrowInfo.borrowStatus.type shouldBe 대출중 borrowInfo.book.countInBorrowing shouldBe beforeBorrowingQuantity + 1 } @@ -411,19 +411,19 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { fun `유효한 요청이면 책 대여 거절이 성공해야 한다`() { val securedValue = getSecuredValue(BorrowManageController::class.java, "denyBorrow") callDenyBorrowApi(borrowInfo.id) - .andExpect(status().isNoContent) - .andDo( - document( - "borrow-requests-deny", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("borrowId").description("대출 ID") - ) + .andExpect(status().isNoContent) + .andDo( + document( + "borrow-requests-deny", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("borrowId").description("대출 ID") + ) + ) ) - ) } @Test @@ -458,19 +458,19 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { val beforeBorrowingQuantity = borrowInfo.book.countInBorrowing val securedValue = getSecuredValue(BorrowManageController::class.java, "approveReturn") callApproveReturnApi(borrowInfo.id) - .andExpect(status().isNoContent) - .andDo( - document( - "borrow-return-approve", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("borrowId").description("대출 ID") - ) + .andExpect(status().isNoContent) + .andDo( + document( + "borrow-return-approve", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("borrowId").description("대출 ID") + ) + ) ) - ) borrowInfo.borrowStatus.type shouldBe 반납완료 borrowInfo.book.countInBorrowing shouldBe beforeBorrowingQuantity - 1 } @@ -494,19 +494,19 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { fun `유효한 요청이면 책 반납 거절이 성공해야 한다`() { val securedValue = getSecuredValue(BorrowManageController::class.java, "denyReturn") callDenyReturnApi(borrowInfo.id) - .andExpect(status().isNoContent) - .andDo( - document( - "borrow-return-deny", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - pathParameters( - parameterWithName("borrowId").description("대출 ID") - ) + .andExpect(status().isNoContent) + .andDo( + document( + "borrow-return-deny", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + pathParameters( + parameterWithName("borrowId").description("대출 ID") + ) + ) ) - ) borrowInfo.borrowStatus.type shouldBe 대출중 } } @@ -530,12 +530,12 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { @BeforeEach fun setBorrowInfo() { borrowLogList = listOf( - borrowLogTestHelper.builder().borrowStatus(LogType.대출중.name).build(), - borrowLogTestHelper.builder().rejectDate(LocalDateTime.now()) - .borrowStatus(LogType.대출반려.name).build(), - borrowLogTestHelper.builder().borrowStatus(LogType.반납대기.name).build(), - borrowLogTestHelper.builder().returnDate(LocalDateTime.now()) - .borrowStatus(LogType.반납완료.name).build(), + borrowLogTestHelper.builder().borrowStatus(LogType.대출중.name).build(), + borrowLogTestHelper.builder().rejectDate(LocalDateTime.now()) + .borrowStatus(LogType.대출반려.name).build(), + borrowLogTestHelper.builder().borrowStatus(LogType.반납대기.name).build(), + borrowLogTestHelper.builder().returnDate(LocalDateTime.now()) + .borrowStatus(LogType.반납완료.name).build(), ) } @@ -543,62 +543,62 @@ class BorrowManageControllerTest : BorrowManageApiTestHelper() { fun `유효한 요청이면 책 대출 현황 로그 조회는 성공해야 한다`() { val securedValue = getSecuredValue(BorrowManageController::class.java, "getBorrowLogs") callGetBorrowLogApi( - params = multiValueMapOf( - "page" to "0", - "size" to "3" - ), + params = multiValueMapOf( + "page" to "0", + "size" to "3" + ), ).andDo(MockMvcResultHandlers.print()) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].status").value("반납완료")) - .andExpect(jsonPath("$.content[1].status").value("반납대기")) - .andExpect(jsonPath("$.content[2].status").value("대출반려")) - .andExpect(jsonPath("$.number").value("0")) - .andExpect(jsonPath("$.size").value("3")) - .andExpect(jsonPath("$.totalPages").value("2")) - .andDo( - document( - "get-borrow-logs", - requestCookies( - cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), - cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") - ), - queryParameters( - parameterWithName("page").description("페이지 (양수여야 합니다.)") - .optional(), - parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") - .optional(), - parameterWithName("search").description("검색 키워드. 도서명, 저자, 실명에서 검색해옵니다.") - .optional(), - parameterWithName("searchType") - .attributes( - key("format").value(LogType.values().map(LogType::name).joinToString()) - ).description("만약 null로 보낼 경우 대출 관련 정보를 모두 가져옵니다.") - .optional() - ), - responseFields( - *pageHelper(*getBorrowLogResponseDocs()) - ) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].status").value("반납완료")) + .andExpect(jsonPath("$.content[1].status").value("반납대기")) + .andExpect(jsonPath("$.content[2].status").value("대출반려")) + .andExpect(jsonPath("$.number").value("0")) + .andExpect(jsonPath("$.size").value("3")) + .andExpect(jsonPath("$.totalPages").value("2")) + .andDo( + document( + "get-borrow-logs", + requestCookies( + cookieWithName(JwtType.ACCESS_TOKEN.tokenName).description("ACCESS TOKEN ${securedValue}"), + cookieWithName(JwtType.REFRESH_TOKEN.tokenName).description("REFRESH TOKEN ${securedValue}") + ), + queryParameters( + parameterWithName("page").description("페이지 (양수여야 합니다.)") + .optional(), + parameterWithName("size").description("한 페이지당 불러올 개수 (default: ${DEFAULT_SIZE}) 최대: ${MAX_SIZE} 최소: ${MIN_SIZE}") + .optional(), + parameterWithName("search").description("검색 키워드. 도서명, 저자, 실명에서 검색해옵니다.") + .optional(), + parameterWithName("searchType") + .attributes( + key("format").value(LogType.values().map(LogType::name).joinToString()) + ).description("만약 null로 보낼 경우 대출 관련 정보를 모두 가져옵니다.") + .optional() + ), + responseFields( + *pageHelper(*getBorrowLogResponseDocs()) + ) + ) ) - ) callGetBorrowLogApi(params = multiValueMapOf("page" to "1", "size" to "3")) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content[0].status").value("대출중")) - .andExpect(jsonPath("$.number").value("1")) - .andExpect(jsonPath("$.size").value("3")) - .andExpect(jsonPath("$.totalPages").value("2")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content[0].status").value("대출중")) + .andExpect(jsonPath("$.number").value("1")) + .andExpect(jsonPath("$.size").value("3")) + .andExpect(jsonPath("$.totalPages").value("2")) } @Test fun `전체 책 대출 현황 로그 조회는 성공해야 한다`() { callGetBorrowLogApi(searchType = LogType.전체) - .andExpect(status().isOk) - .andExpect(jsonPath("$.content.length()").value("4")) - .andExpect(jsonPath("$.content[0].status").value("반납완료")) - .andExpect(jsonPath("$.content[1].status").value("반납대기")) - .andExpect(jsonPath("$.content[2].status").value("대출반려")) - .andExpect(jsonPath("$.content[3].status").value("대출중")) + .andExpect(status().isOk) + .andExpect(jsonPath("$.content.length()").value("4")) + .andExpect(jsonPath("$.content[0].status").value("반납완료")) + .andExpect(jsonPath("$.content[1].status").value("반납대기")) + .andExpect(jsonPath("$.content[2].status").value("대출반려")) + .andExpect(jsonPath("$.content[3].status").value("대출중")) } } } diff --git a/src/test/java/com/keeper/homepage/domain/library/application/BookManageServiceTest.kt b/src/test/java/com/keeper/homepage/domain/library/application/BookManageServiceTest.kt index 9504d948d..81e2e2d93 100644 --- a/src/test/java/com/keeper/homepage/domain/library/application/BookManageServiceTest.kt +++ b/src/test/java/com/keeper/homepage/domain/library/application/BookManageServiceTest.kt @@ -20,18 +20,18 @@ import org.junit.jupiter.api.Test import java.time.LocalDateTime fun BookBorrowInfoTestHelper.generate( - member: Member, - book: Book, - bookBorrowStatusType: BookBorrowStatusType + member: Member, + book: Book, + bookBorrowStatusType: BookBorrowStatusType ): BookBorrowInfo { val now = LocalDateTime.now() return this.builder() - .book(book) - .member(member) - .borrowDate(now) - .expireDate(now.plusWeeks(2)) - .borrowStatus(getBookBorrowStatusBy(bookBorrowStatusType)) - .build() + .book(book) + .member(member) + .borrowDate(now) + .expireDate(now.plusWeeks(2)) + .borrowStatus(getBookBorrowStatusBy(bookBorrowStatusType)) + .build() } class BookManageServiceTest : IntegrationTest() { @@ -113,27 +113,27 @@ class BookManageServiceTest : IntegrationTest() { fun `현재 대여중인 권 수 이하의 책 수량 수정은 실패해야 한다`() { val bookCount = 2L val book = bookTestHelper.builder() - .totalQuantity(bookCount) - .currentQuantity(bookCount) - .thumbnail(thumbnailTestHelper.generateThumbnail()) - .build() + .totalQuantity(bookCount) + .currentQuantity(bookCount) + .thumbnail(thumbnailTestHelper.generateThumbnail()) + .build() val member = memberTestHelper.generate() (1..bookCount).map { // 모든 책 대여 bookBorrowInfoTestHelper.builder() - .book(book) - .member(member) - .borrowStatus(getBookBorrowStatusBy(BookBorrowStatusType.대출중)) - .build() + .book(book) + .member(member) + .borrowStatus(getBookBorrowStatusBy(BookBorrowStatusType.대출중)) + .build() } val exception = shouldThrow { bookManageService.modifyBook( - book.id, - book.title + "_", - book.author + "_", - bookCount - 1, - BookDepartment.BookDepartmentType.ETC, + book.id, + book.title + "_", + book.author + "_", + bookCount - 1, + BookDepartment.BookDepartmentType.ETC, ) } diff --git a/src/test/java/com/keeper/homepage/domain/library/application/BookServiceTest.java b/src/test/java/com/keeper/homepage/domain/library/application/BookServiceTest.java index b7446f6f2..04f608cb7 100644 --- a/src/test/java/com/keeper/homepage/domain/library/application/BookServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/library/application/BookServiceTest.java @@ -45,7 +45,8 @@ void setUp() { @Test @DisplayName("현재수량이 0이 아니고, 회원이 빌린 책의 개수가 5권 미만이면 도서 대여 가능 응답을 해야 한다.") public void 현재수량이_0이_아니고_회원이_빌린_책의_개수가_5권_미만이면_도서_대여_가능_응답을_해야_한다() { - Page books = bookService.getBooks(member, BookSearchType.ALL, "", PageRequest.of(0, 5)); + Page books = bookService.getBooks(member, BookSearchType.ALL, "", + PageRequest.of(0, 5)); assertThat(books.getContent().get(0).isCanBorrow()).isTrue(); } @@ -56,7 +57,8 @@ void setUp() { bookBorrowInfoTestHelper.builder().book(book).borrowStatus(getBookBorrowStatusBy(대출중)) .build(); - Page books = bookService.getBooks(member, BookSearchType.ALL, "", PageRequest.of(0, 5)); + Page books = bookService.getBooks(member, BookSearchType.ALL, "", + PageRequest.of(0, 5)); assertThat(books.getContent().get(0).isCanBorrow()).isFalse(); } @@ -74,7 +76,8 @@ void setUp() { em.clear(); member = memberRepository.findById(member.getId()).get(); - Page books = bookService.getBooks(member, BookSearchType.ALL, "", PageRequest.of(0, 5)); + Page books = bookService.getBooks(member, BookSearchType.ALL, "", + PageRequest.of(0, 5)); assertThat(books.getContent().get(0).isCanBorrow()).isFalse(); } @@ -99,7 +102,8 @@ void setUp() { em.clear(); member = memberRepository.findById(member.getId()).get(); - Page books = bookService.getBooks(member, BookSearchType.ALL, "", PageRequest.of(0, 5)); + Page books = bookService.getBooks(member, BookSearchType.ALL, "", + PageRequest.of(0, 5)); assertThat(books.getContent().get(0).isCanBorrow()).isFalse(); assertThat(books.getContent().get(1).isCanBorrow()).isFalse(); @@ -124,7 +128,8 @@ void setUp() { @DisplayName("도서 대출중인 권수가 2권 이하면 도서 대출은 성공해야 한다.") public void 도서_대출중인_권수가_2권_이하면_도서_대출은_성공해야_한다() { assertDoesNotThrow(() -> bookService.requestBorrow(member, book.getId())); - assertThat(bookBorrowInfoRepository.findByMemberAndBookAndInBorrowingOrWait(member, book)).isNotEmpty(); + assertThat(bookBorrowInfoRepository.findByMemberAndBookAndInBorrowingOrWait(member, + book)).isNotEmpty(); } @Test @@ -298,7 +303,8 @@ void setUp() { public void 대출_내역이_없다면_도서_반납_요청이_실패해야_한다() { long notExistBorrowId = 5; - assertThrows(BusinessException.class, () -> bookService.requestReturn(member, notExistBorrowId)); + assertThrows(BusinessException.class, + () -> bookService.requestReturn(member, notExistBorrowId)); } @Test diff --git a/src/test/java/com/keeper/homepage/domain/library/dao/BookRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/library/dao/BookRepositoryTest.java index 58f735dc5..def1af7ad 100644 --- a/src/test/java/com/keeper/homepage/domain/library/dao/BookRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/library/dao/BookRepositoryTest.java @@ -98,7 +98,8 @@ void should_processDefault_when_EmptyBookBorrowInfoValue() { em.flush(); em.clear(); - BookBorrowInfo findBorrowInfo = bookBorrowInfoRepository.findById(borrowInfo.getId()).orElseThrow(); + BookBorrowInfo findBorrowInfo = bookBorrowInfoRepository.findById(borrowInfo.getId()) + .orElseThrow(); assertThat(findBorrowInfo.getBorrowDate()).isBefore(LocalDateTime.now()); } diff --git a/src/test/java/com/keeper/homepage/domain/member/api/MemberControllerTest.java b/src/test/java/com/keeper/homepage/domain/member/api/MemberControllerTest.java index 4ac706415..fded22c03 100644 --- a/src/test/java/com/keeper/homepage/domain/member/api/MemberControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/member/api/MemberControllerTest.java @@ -337,16 +337,21 @@ void setUp() throws IOException { member = memberTestHelper.generate(); otherMember = memberTestHelper.generate(); memberToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원); - otherMemberToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, otherMember.getId(), ROLE_회원); + otherMemberToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, otherMember.getId(), + ROLE_회원); } @Test @DisplayName("회원 프로필 조회를 성공해야 한다") void 회원_프로필_조회를_성공해야_한다() throws Exception { - memberService.follow(member, memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); - memberService.follow(member, memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); - memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), member.getId()); - memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), member.getId()); + memberService.follow(member, + memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); + memberService.follow(member, + memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); + memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), + member.getId()); + memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), + member.getId()); String securedValue = getSecuredValue(MemberController.class, "getMemberProfile"); @@ -376,8 +381,10 @@ void setUp() throws IOException { @Test @DisplayName("다른 회원의 프로필을 조회할 때는 학번이 노출되면 안된다.") public void 다른_회원의_프로필_조회할_때는_학번이_노출되면_안된다() throws Exception { - memberService.follow(member, memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); - memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), member.getId()); + memberService.follow(member, + memberTestHelper.builder().realName(RealName.from("일일")).build().getId()); + memberService.follow(memberTestHelper.builder().realName(RealName.from("삼삼")).build(), + member.getId()); em.flush(); em.clear(); @@ -406,7 +413,8 @@ void setUp() { otherMember = memberTestHelper.generate(); admin = memberTestHelper.generate(); memberToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원); - adminToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원, ROLE_회장); + adminToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원, + ROLE_회장); typeId = 3L; } @@ -553,7 +561,8 @@ void setUp() { .build(); memberToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원); admin = memberTestHelper.builder().build(); - adminToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원, ROLE_회장); + adminToken = jwtTokenProvider.createAccessToken(ACCESS_TOKEN, member.getId(), ROLE_회원, + ROLE_회장); } @Test diff --git a/src/test/java/com/keeper/homepage/domain/member/api/MemberJobControllerTest.java b/src/test/java/com/keeper/homepage/domain/member/api/MemberJobControllerTest.java index ad3c2768b..71d82a72c 100644 --- a/src/test/java/com/keeper/homepage/domain/member/api/MemberJobControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/member/api/MemberJobControllerTest.java @@ -84,8 +84,9 @@ void setUp() { public void 유효한_요청일_경우_임원_직책_추가는_성공해야_한다() throws Exception { String securedValue = getSecuredValue(MemberJobController.class, "addMemberExecutiveJob"); - mockMvc.perform(post("/members/{memberId}/executive-jobs/{jobId}", member.getId(), ROLE_부회장.getId()) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))) + mockMvc.perform( + post("/members/{memberId}/executive-jobs/{jobId}", member.getId(), ROLE_부회장.getId()) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))) .andExpect(status().isCreated()) .andDo(document("add-member-executive-job", requestCookies( @@ -103,8 +104,9 @@ void setUp() { public void 유효한_요청일_경우_임원_직책_삭제는_성공해야_한다() throws Exception { String securedValue = getSecuredValue(MemberJobController.class, "deleteMemberExecutiveJob"); - mockMvc.perform(delete("/members/{memberId}/executive-jobs/{jobId}", member.getId(), ROLE_부회장.getId()) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))) + mockMvc.perform( + delete("/members/{memberId}/executive-jobs/{jobId}", member.getId(), ROLE_부회장.getId()) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminToken))) .andExpect(status().isNoContent()) .andDo(document("delete-member-executive-job", requestCookies( diff --git a/src/test/java/com/keeper/homepage/domain/member/application/MemberProfileServiceTest.java b/src/test/java/com/keeper/homepage/domain/member/application/MemberProfileServiceTest.java index 47d2f7ef6..02d766cea 100644 --- a/src/test/java/com/keeper/homepage/domain/member/application/MemberProfileServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/member/application/MemberProfileServiceTest.java @@ -109,7 +109,8 @@ void setUp() throws IOException { em.clear(); Member updatedMember = memberFindService.findById(memberId); - assertThat(updatedMember.getProfile().getEmailAddress().get()).isEqualTo(EmailAddress.from(randomEmail).get()); + assertThat(updatedMember.getProfile().getEmailAddress().get()).isEqualTo( + EmailAddress.from(randomEmail).get()); } @Test diff --git a/src/test/java/com/keeper/homepage/domain/member/application/MemberServiceTest.java b/src/test/java/com/keeper/homepage/domain/member/application/MemberServiceTest.java index 5c9e35995..6f5023e95 100644 --- a/src/test/java/com/keeper/homepage/domain/member/application/MemberServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/member/application/MemberServiceTest.java @@ -254,7 +254,8 @@ void setUp() { .attendTime(LocalDateTime.now()) .build()).getId();// O Long replyId = surveyMemberReplyTestHelper.builder().member(member).build().getId();// O - ElectionCandidate electionCandidate = electionCandidateTestHelper.builder(getMemberJobBy(ROLE_회장)).member(member) + ElectionCandidate electionCandidate = electionCandidateTestHelper.builder( + getMemberJobBy(ROLE_회장)).member(member) .build(); // O electionVoterTestHelper.builder().member(member).build(); // O electionChartLogRepository.save(ElectionChartLog.builder() diff --git a/src/test/java/com/keeper/homepage/domain/merit/api/MeritControllerTest.java b/src/test/java/com/keeper/homepage/domain/merit/api/MeritControllerTest.java index 8dcf7683e..311524a45 100644 --- a/src/test/java/com/keeper/homepage/domain/merit/api/MeritControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/merit/api/MeritControllerTest.java @@ -277,40 +277,40 @@ void setUp() throws IOException { @DisplayName("벌점 목록 조회를 성공해야 한다.") void 벌점_목록_조회를_성공해야_한다() throws Exception { meritLogTestHelper.builder() - .memberId(member.getId()) - .meritType(meritTypeHelper.builder().merit(3).isMerit(true).build()) - .build(); + .memberId(member.getId()) + .meritType(meritTypeHelper.builder().merit(3).isMerit(true).build()) + .build(); meritLogTestHelper.builder() - .memberId(member.getId()) - .meritType(meritTypeHelper.builder().merit(-3).isMerit(false).build()) - .build(); + .memberId(member.getId()) + .meritType(meritTypeHelper.builder().merit(-3).isMerit(false).build()) + .build(); mockMvc.perform(get("/merits") - .param("meritType", "DEMERIT") - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminAccessToken))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content[0].isMerit").value("false")); + .param("meritType", "DEMERIT") + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminAccessToken))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].isMerit").value("false")); } @Test @DisplayName("상점 목록 조회를 성공해야 한다.") void 상점_목록_조회를_성공해야_한다() throws Exception { meritLogTestHelper.builder() - .memberId(member.getId()) - .meritType(meritTypeHelper.builder().merit(-3).isMerit(false).build()) - .build(); + .memberId(member.getId()) + .meritType(meritTypeHelper.builder().merit(-3).isMerit(false).build()) + .build(); meritLogTestHelper.builder() - .memberId(member.getId()) - .meritType(meritTypeHelper.builder().merit(3).isMerit(true).build()) - .build(); + .memberId(member.getId()) + .meritType(meritTypeHelper.builder().merit(3).isMerit(true).build()) + .build(); mockMvc.perform(get("/merits") - .param("meritType", "MERIT") - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminAccessToken))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content[0].isMerit").value("true")); + .param("meritType", "MERIT") + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), adminAccessToken))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].isMerit").value("true")); } @Test diff --git a/src/test/java/com/keeper/homepage/domain/merit/application/MeritLogServiceTest.java b/src/test/java/com/keeper/homepage/domain/merit/application/MeritLogServiceTest.java index c35e7266b..f3003f5e7 100644 --- a/src/test/java/com/keeper/homepage/domain/merit/application/MeritLogServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/merit/application/MeritLogServiceTest.java @@ -71,8 +71,10 @@ class MeritLogTest { em.flush(); em.clear(); - Page meritLogs = meritLogService.findAllByMeritType(PageRequest.of(0, 10), MERIT_TYPE); - Page demeritLogs = meritLogService.findAllByMeritType(PageRequest.of(0, 10), DEMERIT_TYPE); + Page meritLogs = meritLogService.findAllByMeritType(PageRequest.of(0, 10), + MERIT_TYPE); + Page demeritLogs = meritLogService.findAllByMeritType(PageRequest.of(0, 10), + DEMERIT_TYPE); Page allLogs = meritLogService.findAllByMeritType(PageRequest.of(0, 10), ALL_TYPE); assertThat(meritLogs diff --git a/src/test/java/com/keeper/homepage/domain/merit/dao/MeritLogRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/merit/dao/MeritLogRepositoryTest.java index 1fad5f4fa..c7c95e1e7 100644 --- a/src/test/java/com/keeper/homepage/domain/merit/dao/MeritLogRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/merit/dao/MeritLogRepositoryTest.java @@ -67,6 +67,7 @@ class GetTotalMeritLogsTest { private MeritType meritType, demeritType; private Member member, otherMember; + @BeforeEach void setUp() { meritType = meritTypeHelper.builder().merit(5).isMerit(true).build(); diff --git a/src/test/java/com/keeper/homepage/domain/point/application/PointLogServiceTest.java b/src/test/java/com/keeper/homepage/domain/point/application/PointLogServiceTest.java index 89c7e925b..a00a50b1f 100644 --- a/src/test/java/com/keeper/homepage/domain/point/application/PointLogServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/point/application/PointLogServiceTest.java @@ -37,7 +37,8 @@ void setUp() { em.flush(); em.clear(); - Page findPointLogPages = pointLogService.findAllPointLogs(PageRequest.of(0, 10), giver.getId()); + Page findPointLogPages = pointLogService.findAllPointLogs(PageRequest.of(0, 10), + giver.getId()); assertThat(findPointLogPages .map(PointLog::getId) diff --git a/src/test/java/com/keeper/homepage/domain/post/api/PostApiTestHelper.java b/src/test/java/com/keeper/homepage/domain/post/api/PostApiTestHelper.java index 0de41c381..832237bf0 100644 --- a/src/test/java/com/keeper/homepage/domain/post/api/PostApiTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/post/api/PostApiTestHelper.java @@ -21,7 +21,8 @@ public class PostApiTestHelper extends IntegrationTest { - ResultActions callCreatePostApiWithFile(String accessToken, MockMultipartFile file, MockPart mockPart) + ResultActions callCreatePostApiWithFile(String accessToken, MockMultipartFile file, + MockPart mockPart) throws Exception { return mockMvc.perform(multipart("/posts") .file(file) @@ -70,7 +71,8 @@ ResultActions callUpdatePostApi(String accessToken, long postId, PostUpdateReque .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callUpdatePostThumbnail(String accessToken, long postId, MockMultipartFile thumbnail) + ResultActions callUpdatePostThumbnail(String accessToken, long postId, + MockMultipartFile thumbnail) throws Exception { return mockMvc.perform(multipart("/posts/{postId}/thumbnail", postId) .file(thumbnail) @@ -130,7 +132,8 @@ ResultActions callAddPostFilesApi(String accessToken, long postId, MockMultipart .contentType(MediaType.MULTIPART_FORM_DATA)); } - ResultActions callDeletePostFileApi(String accessToken, long postId, PostFileDeleteRequest request) + ResultActions callDeletePostFileApi(String accessToken, long postId, + PostFileDeleteRequest request) throws Exception { return mockMvc.perform(delete("/posts/{postId}/files", postId) .content(asJsonString(request)) @@ -138,7 +141,8 @@ ResultActions callDeletePostFileApi(String accessToken, long postId, PostFileDel .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callGetPostsApi(String memberToken, MultiValueMap params) throws Exception { + ResultActions callGetPostsApi(String memberToken, MultiValueMap params) + throws Exception { return mockMvc.perform(get("/posts") .params(params) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), memberToken))); diff --git a/src/test/java/com/keeper/homepage/domain/post/api/PostControllerTest.java b/src/test/java/com/keeper/homepage/domain/post/api/PostControllerTest.java index b47b51d32..6d223104d 100644 --- a/src/test/java/com/keeper/homepage/domain/post/api/PostControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/post/api/PostControllerTest.java @@ -127,7 +127,8 @@ void should_201CREATED_when_createPostWithThumbnailAndFiles() throws Exception { ), requestPartFields( "request", - fieldWithPath("title").description("게시글 제목을 입력해주세요. (최대 가능 길이 : " + POST_TITLE_LENGTH + ")"), + fieldWithPath("title").description( + "게시글 제목을 입력해주세요. (최대 가능 길이 : " + POST_TITLE_LENGTH + ")"), fieldWithPath("content").description("게시글 내용을 입력해주세요. (임시 저장글이 아닐 경우 필수입니다.)") .optional(), fieldWithPath("allowComment").description("댓글 허용 여부"), @@ -135,7 +136,8 @@ void should_201CREATED_when_createPostWithThumbnailAndFiles() throws Exception { fieldWithPath("isSecret").description("비밀글 여부"), fieldWithPath("isTemp").description("임시 저장글 여부"), fieldWithPath("password") - .description("게시글 비밀번호를 입력해주세요. (최대 가능 길이 : " + POST_PASSWORD_LENGTH + ", 비밀글일 경우 필수값입니다.)") + .description("게시글 비밀번호를 입력해주세요. (최대 가능 길이 : " + POST_PASSWORD_LENGTH + + ", 비밀글일 경우 필수값입니다.)") .optional(), fieldWithPath("categoryId").description("게시글 카테고리를 입력해주세요.") ), @@ -195,7 +197,8 @@ void should_201CREATED_when_createPostWithNoPassword() throws Exception { .isSecret(false) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -215,7 +218,8 @@ public void should_fail_when_secretPostWithoutPassword() throws Exception { .isSecret(true) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -234,7 +238,8 @@ void should_400BadRequest_when_blankTitle() throws Exception { .isSecret(false) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -253,7 +258,8 @@ void should_400BadRequest_when_blankContent() throws Exception { .isSecret(false) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -272,7 +278,8 @@ void should_400BadRequest_when_tooLongTitle() throws Exception { .isSecret(false) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -292,7 +299,8 @@ void should_400BadRequest_when_tooLongPassword() throws Exception { .password("a".repeat(POST_PASSWORD_LENGTH + 1)) .categoryId(category.getId()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -311,7 +319,8 @@ void should_400BadRequest_when_WithoutCategoryId() throws Exception { .isSecret(false) .password("게시글 비밀번호") .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -331,7 +340,8 @@ void should_400BadRequest_when_inValidCategoryId() throws Exception { .password("게시글 비밀번호") .categoryId(-1L) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreatePostApi(memberToken, mockPart) @@ -379,7 +389,8 @@ public void should_success_when_getPost() throws Exception { fieldWithPath("title").description("게시글의 타이틀"), fieldWithPath("writerId").description("게시글 작성자의 ID(익명 게시판일 경우 \"1\")"), fieldWithPath("writerName").description("게시글 작성자의 이름(익명 게시판일 경우 \"익명\")"), - fieldWithPath("writerThumbnailPath").description("게시글 작성자의 썸네일 경로(익명 게시판일 경우 null)"), + fieldWithPath("writerThumbnailPath").description( + "게시글 작성자의 썸네일 경로(익명 게시판일 경우 null)"), fieldWithPath("registerTime").description("게시글 등록 시간"), fieldWithPath("updateTime").description("게시글 수정 시간"), fieldWithPath("visitCount").description("게시글 조회수"), @@ -480,15 +491,17 @@ public void should_success_when_writerIsMe() throws Exception { .description("수정하고자 하는 게시글의 ID") ), requestFields( - fieldWithPath("title").description("게시글 제목을 입력해주세요. (최대 가능 길이 : " + POST_TITLE_LENGTH + ")"), + fieldWithPath("title").description( + "게시글 제목을 입력해주세요. (최대 가능 길이 : " + POST_TITLE_LENGTH + ")"), fieldWithPath("content").description("게시글 내용을 입력해주세요. (임시 저장글이 아닐 경우 필수입니다.)") .optional(), fieldWithPath("allowComment").description("댓글 허용 여부"), fieldWithPath("isNotice").description("공지글 여부"), fieldWithPath("isSecret").description("비밀글 여부"), fieldWithPath("isTemp").description("임시 저장글 여부"), - fieldWithPath("password").description("게시글 비밀번호를 입력해주세요. (최대 가능 길이 : " + POST_PASSWORD_LENGTH - + ", 비밀글일 경우 필수값입니다.)") + fieldWithPath("password").description( + "게시글 비밀번호를 입력해주세요. (최대 가능 길이 : " + POST_PASSWORD_LENGTH + + ", 비밀글일 경우 필수값입니다.)") .optional() ), responseHeaders( @@ -646,7 +659,8 @@ void setUp() { fieldWithPath("posts[].title").description("게시글 제목"), fieldWithPath("posts[].writerId").description("게시글 작성자 ID"), fieldWithPath("posts[].writerName").description("게시글 작성자 실명"), - fieldWithPath("posts[].writerThumbnailPath").description("게시글 작성자 썸네일 주소").optional(), + fieldWithPath("posts[].writerThumbnailPath").description("게시글 작성자 썸네일 주소") + .optional(), fieldWithPath("posts[].visitCount").description("게시글 조회수"), fieldWithPath("posts[].commentCount").description("게시글 댓글 개수"), fieldWithPath("posts[].isSecret").description("게시글 비밀글 여부"), @@ -949,7 +963,8 @@ class DownloadFile { mockMvc.perform(get("/posts/{postId}/files/{fileId}", postId, file.getId()) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), otherToken))) .andExpect(status().isOk()) - .andExpect(header().string(CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")) + .andExpect(header().string(CONTENT_DISPOSITION, + "attachment; filename=\"" + file.getFileName() + "\"")) .andDo(document("download-post-file", requestCookies( cookieWithName(ACCESS_TOKEN.getTokenName()) @@ -973,8 +988,9 @@ class DownloadFile { em.clear(); FileEntity file = postHasFileRepository.findByPost(post).get().getFile(); - MvcResult mvcResult = mockMvc.perform(get("/posts/{postId}/files/{fileId}", postId, file.getId()) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), otherToken))) + MvcResult mvcResult = mockMvc.perform( + get("/posts/{postId}/files/{fileId}", postId, file.getId()) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), otherToken))) .andExpect(status().isBadRequest()) .andReturn(); @@ -1018,8 +1034,9 @@ class DownloadFile { em.clear(); FileEntity file = postHasFileRepository.findByPost(otherPost).get().getFile(); - MvcResult mvcResult = mockMvc.perform(get("/posts/{postId}/files/{fileId}", postId, file.getId()) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), otherToken))) + MvcResult mvcResult = mockMvc.perform( + get("/posts/{postId}/files/{fileId}", postId, file.getId()) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), otherToken))) .andExpect(status().isBadRequest()) .andReturn(); diff --git a/src/test/java/com/keeper/homepage/domain/post/application/PostServiceTest.java b/src/test/java/com/keeper/homepage/domain/post/application/PostServiceTest.java index 7c3c81058..c8139b13d 100644 --- a/src/test/java/com/keeper/homepage/domain/post/application/PostServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/post/application/PostServiceTest.java @@ -544,10 +544,13 @@ void setUp() { Long postId1 = postTestHelper.builder().category(category).isTemp(true).build().getId(); Long postId2 = postTestHelper.builder().category(category).isNotice(true).build().getId(); - Page posts = postService.getPosts(category.getId(), null, null, PageRequest.of(0, 10)); + Page posts = postService.getPosts(category.getId(), null, null, + PageRequest.of(0, 10)); - assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).doesNotContain(postId1); - assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).doesNotContain(postId2); + assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).doesNotContain( + postId1); + assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).doesNotContain( + postId2); } @Test @@ -555,7 +558,8 @@ void setUp() { public void 제목_검색은_대소문자_구분_없이_조회되어야_한다() throws Exception { postTestHelper.builder().category(category).title("ABCD").build(); - Page posts = postService.getPosts(category.getId(), "title", "abc", PageRequest.of(0, 10)); + Page posts = postService.getPosts(category.getId(), "title", "abc", + PageRequest.of(0, 10)); assertThat(posts.getContent().stream().map(PostResponse::getTitle).toList()).contains("ABCD"); } @@ -565,7 +569,8 @@ void setUp() { public void 내용_검색은_대소문자_구분_없이_조회되어야_한다() throws Exception { Long postId = postTestHelper.builder().category(category).content("ABCD").build().getId(); - Page posts = postService.getPosts(category.getId(), "content", "abc", PageRequest.of(0, 10)); + Page posts = postService.getPosts(category.getId(), "content", "abc", + PageRequest.of(0, 10)); assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).contains(postId); } @@ -576,7 +581,8 @@ void setUp() { Long postId1 = postTestHelper.builder().category(category).title("ABCD").build().getId(); Long postId2 = postTestHelper.builder().category(category).content("BCD").build().getId(); - Page posts = postService.getPosts(category.getId(), "title+content", "bc", PageRequest.of(0, 10)); + Page posts = postService.getPosts(category.getId(), "title+content", "bc", + PageRequest.of(0, 10)); assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).contains(postId1); assertThat(posts.getContent().stream().map(PostResponse::getId).toList()).contains(postId2); diff --git a/src/test/java/com/keeper/homepage/domain/seminar/SeminarAttendanceTestHelper.java b/src/test/java/com/keeper/homepage/domain/seminar/SeminarAttendanceTestHelper.java index f578b68fc..c5009ad0c 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/SeminarAttendanceTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/SeminarAttendanceTestHelper.java @@ -49,7 +49,8 @@ public SeminarAttendanceBuilder member(Member member) { return this; } - public SeminarAttendanceBuilder seminarAttendanceStatus(SeminarAttendanceStatus seminarAttendanceStatus) { + public SeminarAttendanceBuilder seminarAttendanceStatus( + SeminarAttendanceStatus seminarAttendanceStatus) { this.seminarAttendanceStatus = seminarAttendanceStatus; return this; } diff --git a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarApiTestHelper.java b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarApiTestHelper.java index d23ece553..f2cf8b965 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarApiTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarApiTestHelper.java @@ -77,7 +77,8 @@ ResultActions deleteSeminarUsingApi(String token, Long seminarId) throws Excepti .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), token))); } - ResultActions attendanceSeminarUsingApi(String token, Long seminarId, SeminarAttendanceCodeRequest request) + ResultActions attendanceSeminarUsingApi(String token, Long seminarId, + SeminarAttendanceCodeRequest request) throws Exception { return mockMvc.perform(patch("/seminars/{seminarId}/attendances", seminarId) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), token)) @@ -85,14 +86,16 @@ ResultActions attendanceSeminarUsingApi(String token, Long seminarId, SeminarAtt .content(objectMapper.writeValueAsString(request))); } - ResultActions attendanceSeminarUsingApi(String token, Long seminarId, String strJson) throws Exception { + ResultActions attendanceSeminarUsingApi(String token, Long seminarId, String strJson) + throws Exception { return mockMvc.perform(patch("/seminars/{seminarId}/attendances", seminarId) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), token)) .contentType(MediaType.APPLICATION_JSON) .content(strJson)); } - ResultActions changeAttendanceStatusUsingApi(String token, long attendanceId, SeminarAttendanceStatusRequest request) + ResultActions changeAttendanceStatusUsingApi(String token, long attendanceId, + SeminarAttendanceStatusRequest request) throws Exception { return mockMvc.perform(patch("/seminars/attendances/{attendanceId}", attendanceId) .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), token)) diff --git a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarAttendanceControllerTest.java b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarAttendanceControllerTest.java index 67efa9c16..3d1dc550d 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarAttendanceControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarAttendanceControllerTest.java @@ -196,7 +196,8 @@ class SeminarAttendanceStatusTest { @Test @DisplayName("세미나 출석 상태를 변경한다.") public void should_success_when_changeSeminarAttendanceStatus() throws Exception { - String securedValue = getSecuredValue(SeminarAttendanceController.class, "changeAttendanceStatus"); + String securedValue = getSecuredValue(SeminarAttendanceController.class, + "changeAttendanceStatus"); SeminarAttendance seminarAttendance = seminarAttendanceTestHelper.generate(); @@ -229,7 +230,8 @@ public void should_success_when_emptyExcuse(String excuse) throws Exception { String strJson = """ {"excuse":%s, "statusType":"LATENESS"}"""; SeminarAttendance seminarAttendance = seminarAttendanceTestHelper.generate(); - changeAttendanceStatusUsingApi(adminToken, seminarAttendance.getId(), strJson.formatted(excuse)).andExpect( + changeAttendanceStatusUsingApi(adminToken, seminarAttendance.getId(), + strJson.formatted(excuse)).andExpect( status().isNoContent()); } @@ -241,7 +243,8 @@ public void should_fail_when_invalidValue(String statusType) throws Exception { String strJson = """ {"excuse":"", "statusType": %s}"""; SeminarAttendance seminarAttendance = seminarAttendanceTestHelper.generate(); - changeAttendanceStatusUsingApi(adminToken, seminarAttendance.getId(), strJson.formatted(statusType)).andExpect( + changeAttendanceStatusUsingApi(adminToken, seminarAttendance.getId(), + strJson.formatted(statusType)).andExpect( status().isBadRequest()); } } @@ -257,10 +260,12 @@ class GetSeminarAttendanceTest { // given Long seminarId = seminarService.save(LocalDate.now()).id(); Member admin = memberRepository.findById(adminId).orElseThrow(); - String attendanceCode = seminarService.start(admin, seminarId, LocalDateTime.now().minusMinutes(5), + String attendanceCode = seminarService.start(admin, seminarId, + LocalDateTime.now().minusMinutes(5), LocalDateTime.now().plusMinutes(5)).attendanceCode(); Member user = memberRepository.findById(userId).orElseThrow(); - Long attendanceId = seminarAttendanceService.attendance(seminarId, user, attendanceCode).getId(); + Long attendanceId = seminarAttendanceService.attendance(seminarId, user, attendanceCode) + .getId(); em.flush(); em.clear(); @@ -271,16 +276,20 @@ class GetSeminarAttendanceTest { .andExpect(jsonPath("$.content[0].memberId").value(adminId)) .andExpect(jsonPath("$.content[0].memberName").value(admin.getRealName())) .andExpect(jsonPath("$.content[0].generation").value(admin.getGeneration())) - .andExpect(jsonPath("$.content[0].attendances[0].attendanceStatus").value(ATTENDANCE.toString())) + .andExpect( + jsonPath("$.content[0].attendances[0].attendanceStatus").value(ATTENDANCE.toString())) .andExpect(jsonPath("$.content[0].attendances[0].excuse").isEmpty()) - .andExpect(jsonPath("$.content[0].attendances[0].attendDate").value(LocalDate.now().toString())) + .andExpect( + jsonPath("$.content[0].attendances[0].attendDate").value(LocalDate.now().toString())) .andExpect(jsonPath("$.content[1].memberId").value(userId)) .andExpect(jsonPath("$.content[1].memberName").value(user.getRealName())) .andExpect(jsonPath("$.content[1].generation").value(user.getGeneration())) .andExpect(jsonPath("$.content[1].attendances[0].attendanceId").value(attendanceId)) - .andExpect(jsonPath("$.content[1].attendances[0].attendanceStatus").value(LATENESS.toString())) + .andExpect( + jsonPath("$.content[1].attendances[0].attendanceStatus").value(LATENESS.toString())) .andExpect(jsonPath("$.content[1].attendances[0].excuse").isEmpty()) - .andExpect(jsonPath("$.content[1].attendances[0].attendDate").value(LocalDate.now().toString())) + .andExpect( + jsonPath("$.content[1].attendances[0].attendDate").value(LocalDate.now().toString())) .andDo(document("get-seminar-attendances", requestCookies( cookieWithName(ACCESS_TOKEN.getTokenName()) diff --git a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarControllerTest.java b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarControllerTest.java index faa8fc7b4..596961fca 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/api/SeminarControllerTest.java @@ -71,10 +71,12 @@ class SeminarCreateTest { @DisplayName("세미나 생성을 성공한다.") public void should_successCreateSeminar_when_admin() throws Exception { String securedValue = getSecuredValue(SeminarController.class, "createSeminar"); - MvcResult mvcResult = createSeminarUsingApi(adminToken, LocalDate.now()).andExpect(status().isCreated()) + MvcResult mvcResult = createSeminarUsingApi(adminToken, LocalDate.now()).andExpect( + status().isCreated()) .andDo(document("create-seminar", requestCookies( - cookieWithName(ACCESS_TOKEN.getTokenName()).description("ACCESS TOKEN %s".formatted(securedValue))), + cookieWithName(ACCESS_TOKEN.getTokenName()).description( + "ACCESS TOKEN %s".formatted(securedValue))), queryParameters( parameterWithName("openDate").attributes(dateFormat()) .description("세미나 날짜")), @@ -227,7 +229,8 @@ public void should_checkCountSeminar_when_admin() throws Exception { Long latestSeminarId = createSeminarAndGetId(adminToken, LocalDate.now().minusDays(5)); Long recentSeminarId = createSeminarAndGetId(adminToken, LocalDate.now()); Long midSeminarId = createSeminarAndGetId(adminToken, LocalDate.now().minusDays(2)); - startSeminarUsingApi(adminToken, latestSeminarId, seminarStartRequest).andExpect(status().isOk()); + startSeminarUsingApi(adminToken, latestSeminarId, seminarStartRequest).andExpect( + status().isOk()); em.flush(); em.clear(); diff --git a/src/test/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceServiceTest.java b/src/test/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceServiceTest.java index 2480d04fa..060e064fc 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceServiceTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/application/SeminarAttendanceServiceTest.java @@ -37,19 +37,22 @@ class AttemptLimitTest { Member starter = memberTestHelper.generate(); Member member = memberTestHelper.generate(); long seminarId = seminarService.save(LocalDate.now()).id(); - seminarService.start(starter, seminarId, LocalDateTime.now().plusMinutes(5), LocalDateTime.now().plusMinutes(10)); + seminarService.start(starter, seminarId, LocalDateTime.now().plusMinutes(5), + LocalDateTime.now().plusMinutes(10)); Seminar seminar = seminarRepository.findById(seminarId).orElseThrow(); String invalidAttendanceCode = "12345"; for (int i = 0; i < 5; i++) { - assertThatThrownBy(() -> seminarAttendanceService.attendance(seminar.getId(), member, invalidAttendanceCode)) + assertThatThrownBy(() -> seminarAttendanceService.attendance(seminar.getId(), member, + invalidAttendanceCode)) .isInstanceOf(BusinessException.class) .hasMessageContaining(SEMINAR_ATTENDANCE_CODE_NOT_AVAILABLE.getMessage()); } assertThatThrownBy( - () -> seminarAttendanceService.attendance(seminar.getId(), member, seminar.getAttendanceCode())) + () -> seminarAttendanceService.attendance(seminar.getId(), member, + seminar.getAttendanceCode())) .isInstanceOf(BusinessException.class) .hasMessageContaining(SEMINAR_ATTENDANCE_ATTEMPT_NOT_AVAILABLE.getMessage()); } @@ -75,10 +78,12 @@ class ChangeAttendanceStatusTest { em.clear(); //then - SeminarAttendance findSeminarAttendance = seminarAttendanceRepository.findById(seminarAttendanceId).orElseThrow(); + SeminarAttendance findSeminarAttendance = seminarAttendanceRepository.findById( + seminarAttendanceId).orElseThrow(); assertThat(findSeminarAttendance.getSeminarAttendanceStatus().getType()).isEqualTo(LATENESS); assertThat(findSeminarAttendance.getSeminarAttendanceExcuse()).isNotNull(); - assertThat(findSeminarAttendance.getSeminarAttendanceExcuse().getAbsenceExcuse()).isEqualTo(excuse); + assertThat(findSeminarAttendance.getSeminarAttendanceExcuse().getAbsenceExcuse()).isEqualTo( + excuse); } @Test @@ -102,8 +107,10 @@ class ChangeAttendanceStatusTest { em.clear(); //then - SeminarAttendance findSeminarAttendance = seminarAttendanceRepository.findById(seminarAttendanceId).orElseThrow(); - assertThat(findSeminarAttendance.getSeminarAttendanceStatus().getType()).isEqualTo(BEFORE_ATTENDANCE); + SeminarAttendance findSeminarAttendance = seminarAttendanceRepository.findById( + seminarAttendanceId).orElseThrow(); + assertThat(findSeminarAttendance.getSeminarAttendanceStatus().getType()).isEqualTo( + BEFORE_ATTENDANCE); assertThat(findSeminarAttendance.getSeminarAttendanceExcuse()).isNull(); } } @@ -126,7 +133,8 @@ void setUp() { //given member.updateType(getMemberTypeBy(휴면회원)); Long seminarId = seminarService.save(LocalDate.now()).id(); - String attendanceCode = seminarService.start(admin, seminarId, LocalDateTime.now().plusMinutes(5), + String attendanceCode = seminarService.start(admin, seminarId, + LocalDateTime.now().plusMinutes(5), LocalDateTime.now().plusMinutes(10)).attendanceCode(); em.flush(); em.clear(); diff --git a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceRepositoryTest.java index a2e83c9c0..df9cd7a38 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceRepositoryTest.java @@ -56,7 +56,8 @@ void should_check_when_SavedSeminarAttendance() { assertThat(seminarAttendance.getMember().getProfile().getStudentId()).isEqualTo( member.getProfile().getStudentId()); assertThat(seminarAttendance.getSeminar().getId()).isEqualTo(seminar.getId()); - assertThat(seminarAttendance.getSeminar().getAttendanceCode()).isEqualTo(seminar.getAttendanceCode()); + assertThat(seminarAttendance.getSeminar().getAttendanceCode()).isEqualTo( + seminar.getAttendanceCode()); assertThat(seminarAttendance.getSeminar().getName()).isNotNull(); assertThat(seminarAttendance.getSeminarAttendanceStatus().getType()).isEqualTo(statusType); assertThat(seminarAttendance.getAttendTime()).isAfter(now.minusDays(2)); @@ -77,8 +78,10 @@ void should_success_when_saveAttendExcuseSeminar() { seminarAttendance = seminarAttendanceRepository.findById(seminarAttendanceId).orElseThrow(); Long statusId = seminarAttendance.getSeminarAttendanceStatus().getId(); - SeminarAttendanceStatus attendanceStatus = seminarAttendanceStatusRepository.findById(statusId).orElseThrow(); - SeminarAttendanceExcuse attendanceExcuse = seminarAttendanceExcuseRepository.findById(seminarAttendanceId) + SeminarAttendanceStatus attendanceStatus = seminarAttendanceStatusRepository.findById( + statusId).orElseThrow(); + SeminarAttendanceExcuse attendanceExcuse = seminarAttendanceExcuseRepository.findById( + seminarAttendanceId) .orElseThrow(); assertThat(seminarAttendance.getSeminarAttendanceStatus().getType()).isEqualTo(LATENESS); @@ -103,7 +106,8 @@ void should_success_when_modifyAttendExcuseSeminar() { seminarAttendance = seminarAttendanceRepository.findById(seminarAttendanceId).orElseThrow(); seminarAttendance.changeStatus(LATENESS, excuse); - SeminarAttendanceExcuse attendanceExcuse = seminarAttendanceExcuseRepository.findById(seminarAttendanceId) + SeminarAttendanceExcuse attendanceExcuse = seminarAttendanceExcuseRepository.findById( + seminarAttendanceId) .orElseThrow(); assertThat(attendanceExcuse.getAbsenceExcuse()).isEqualTo(excuse); diff --git a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepositoryTest.java index dbe81cd10..54c58e85b 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarAttendanceStatusRepositoryTest.java @@ -45,7 +45,8 @@ private static List getName(List typesList) { .toList(); } - private static List getType(List typesList) { + private static List getType( + List typesList) { return typesList.stream() .map(SeminarAttendanceStatus::getType) .toList(); diff --git a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarRepositoryTest.java index 1d3e81998..ba44f1919 100644 --- a/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/seminar/dao/SeminarRepositoryTest.java @@ -32,8 +32,10 @@ void should_success_when_createSeminar() { Seminar savedSeminar = seminarRepository.findById(seminarId).orElseThrow(); assertThat(savedSeminar.getOpenTime()).isEqualTo(seminarBuild.getOpenTime()); - assertThat(savedSeminar.getAttendanceCloseTime()).isEqualTo(seminarBuild.getAttendanceCloseTime()); - assertThat(savedSeminar.getLatenessCloseTime()).isEqualTo(seminarBuild.getLatenessCloseTime()); + assertThat(savedSeminar.getAttendanceCloseTime()).isEqualTo( + seminarBuild.getAttendanceCloseTime()); + assertThat(savedSeminar.getLatenessCloseTime()).isEqualTo( + seminarBuild.getLatenessCloseTime()); assertThat(savedSeminar.getAttendanceCode()).isEqualTo(seminarBuild.getAttendanceCode()); assertThat(savedSeminar.getName()).isEqualTo(seminarBuild.getName()); } @@ -51,7 +53,7 @@ void should_process_when_EmptyTime() { assertThat(savedSeminar.getRegisterTime()).isAfter(now.minusDays(2)); assertThat(savedSeminar.getUpdateTime()).isAfter(now.minusDays(2)); } - + @Test @DisplayName("세미나 이름을 넣지 않았을 때 TRIGGER가 동작해야 한다.") void should_success_when_EmptySeminarName() { @@ -73,7 +75,7 @@ void should_success_when_deleteSeminar() { assertThat(afterSeminarLength).isEqualTo(beforeSeminarLength - 1); } } - + @Nested @DisplayName("세미나 조회 테스트") class SeminarSearchTest { diff --git a/src/test/java/com/keeper/homepage/domain/study/StudyTestHelper.java b/src/test/java/com/keeper/homepage/domain/study/StudyTestHelper.java index f561c318a..0b96730ec 100644 --- a/src/test/java/com/keeper/homepage/domain/study/StudyTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/study/StudyTestHelper.java @@ -90,7 +90,8 @@ public Study build() { .year(year) .season(season) .link(Link.builder() - .gitLink(gitLink != null ? gitLink : GitLink.from("https://github.com/KEEPER31337/Homepage-Back-R2")) + .gitLink(gitLink != null ? gitLink + : GitLink.from("https://github.com/KEEPER31337/Homepage-Back-R2")) .notionLink(notionLink != null ? notionLink : "https://www.notion.so/Java-Spring") .etcLink(etcLink != null ? etcLink : "etc.com") .build()) diff --git a/src/test/java/com/keeper/homepage/domain/study/api/StudyApiTestHelper.java b/src/test/java/com/keeper/homepage/domain/study/api/StudyApiTestHelper.java index b68dbe822..c68d857b4 100644 --- a/src/test/java/com/keeper/homepage/domain/study/api/StudyApiTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/study/api/StudyApiTestHelper.java @@ -20,7 +20,8 @@ public class StudyApiTestHelper extends IntegrationTest { - ResultActions callCreateStudyApiWithThumbnail(String accessToken, MockMultipartFile thumbnail, MockPart mockPart) + ResultActions callCreateStudyApiWithThumbnail(String accessToken, MockMultipartFile thumbnail, + MockPart mockPart) throws Exception { return mockMvc.perform(multipart(POST, "/studies") .file(thumbnail) @@ -65,16 +66,18 @@ ResultActions callUpdateStudyApi(String accessToken, long studyId, StudyUpdateRe .contentType(MediaType.APPLICATION_JSON)); } - ResultActions callUpdateStudyThumbnailApi(String accessToken, long studyId, MockMultipartFile thumbnail) + ResultActions callUpdateStudyThumbnailApi(String accessToken, long studyId, + MockMultipartFile thumbnail) throws Exception { - return mockMvc.perform(RestDocumentationRequestBuilders.multipart("/studies/{studyId}/thumbnail", studyId) - .file(thumbnail) - .with(request -> { - request.setMethod("PATCH"); - return request; - }) - .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), accessToken)) - .contentType(MediaType.MULTIPART_FORM_DATA)); + return mockMvc.perform( + RestDocumentationRequestBuilders.multipart("/studies/{studyId}/thumbnail", studyId) + .file(thumbnail) + .with(request -> { + request.setMethod("PATCH"); + return request; + }) + .cookie(new Cookie(ACCESS_TOKEN.getTokenName(), accessToken)) + .contentType(MediaType.MULTIPART_FORM_DATA)); } ResultActions callJoinStudyApi(String accessToken, long studyId, long memberId) diff --git a/src/test/java/com/keeper/homepage/domain/study/api/StudyControllerTest.java b/src/test/java/com/keeper/homepage/domain/study/api/StudyControllerTest.java index 599f65180..9553d8085 100644 --- a/src/test/java/com/keeper/homepage/domain/study/api/StudyControllerTest.java +++ b/src/test/java/com/keeper/homepage/domain/study/api/StudyControllerTest.java @@ -76,7 +76,8 @@ class CreateStudy { .memberIds(List.of(other.getId())) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreateStudyApiWithThumbnail(memberToken, thumbnail, mockPart) @@ -84,18 +85,22 @@ class CreateStudy { .andDo(document("create-study", requestCookies( cookieWithName(ACCESS_TOKEN.getTokenName()) - .description("ACCESS TOKEN %s".formatted(securedValue) + " 스터디 생성자는 스터디장이 됩니다.") + .description( + "ACCESS TOKEN %s".formatted(securedValue) + " 스터디 생성자는 스터디장이 됩니다.") ), requestPartFields( "request", - fieldWithPath("title").description("스터디 이름을 입력해주세요. (최대 가능 길이 : " + STUDY_TITLE_LENGTH + ")"), + fieldWithPath("title").description( + "스터디 이름을 입력해주세요. (최대 가능 길이 : " + STUDY_TITLE_LENGTH + ")"), fieldWithPath("information") .description("스터디 설명을 입력해주세요. (최대 가능 길이 : " + STUDY_INFORMATION_LENGTH + ")") .optional(), fieldWithPath("year").description("스터디 년도를 입력해주세요."), - fieldWithPath("season").attributes(new Attribute("format", "1: 1학기 2: 여름학기 3: 2학기 4: 겨울학기")) + fieldWithPath("season").attributes( + new Attribute("format", "1: 1학기 2: 여름학기 3: 2학기 4: 겨울학기")) .description("스터디 학기를 입력해주세요."), - fieldWithPath("gitLink").attributes(new Attribute("format", "\"https://github.com\"으로 시작")) + fieldWithPath("gitLink").attributes( + new Attribute("format", "\"https://github.com\"으로 시작")) .description("스터디 깃허브 링크를 입력해주세요.").optional(), fieldWithPath("notionLink") .description("스터디 노션 링크를 입력해주세요.").optional(), @@ -125,7 +130,8 @@ class CreateStudy { .memberIds(List.of(other.getId())) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreateStudyApiWithThumbnail(memberToken, thumbnail, mockPart) @@ -144,7 +150,8 @@ class CreateStudy { .memberIds(List.of()) .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreateStudyApiWithThumbnail(memberToken, thumbnail, mockPart) @@ -162,7 +169,8 @@ class CreateStudy { .gitLink("https://github.com/KEEPER31337/Homepage-Back-R2") .build(); - MockPart mockPart = new MockPart("request", asJsonString(request).getBytes(StandardCharsets.UTF_8)); + MockPart mockPart = new MockPart("request", + asJsonString(request).getBytes(StandardCharsets.UTF_8)); mockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON); callCreateStudyApiWithThumbnail(memberToken, thumbnail, mockPart) @@ -289,7 +297,8 @@ class UpdateStudy { .year(2023) .season(2) .gitLink("https://github.com/KEEPER31337/Homepage-Back-R2") - .notionLink("https://www.notion.so/KEEPER-NEW-HOMEPAGE-PROJECT-c4fd631881d84e4daa6fa14404ac6173?pvs=4") + .notionLink( + "https://www.notion.so/KEEPER-NEW-HOMEPAGE-PROJECT-c4fd631881d84e4daa6fa14404ac6173?pvs=4") .etcLink("https://plato.pusan.ac.kr/") .etcTitle("plato") .memberIds(List.of(other.getId())) diff --git a/src/test/java/com/keeper/homepage/domain/survey/SurveyMemberReplyTestHelper.java b/src/test/java/com/keeper/homepage/domain/survey/SurveyMemberReplyTestHelper.java index 95a81888e..1e663a636 100644 --- a/src/test/java/com/keeper/homepage/domain/survey/SurveyMemberReplyTestHelper.java +++ b/src/test/java/com/keeper/homepage/domain/survey/SurveyMemberReplyTestHelper.java @@ -67,7 +67,8 @@ public SurveyMemberReply build() { return surveyMemberReplyRepository.save(SurveyMemberReply.builder() .member(member != null ? member : memberTestHelper.generate()) .survey(survey != null ? survey : surveyTestHelper.generate()) - .reply(reply != null ? reply : surveyReplyRepository.findById(ACTIVITY.getId()).orElseThrow()) + .reply(reply != null ? reply + : surveyReplyRepository.findById(ACTIVITY.getId()).orElseThrow()) .replyTime(replyTime) .build()); } diff --git a/src/test/java/com/keeper/homepage/domain/survey/dao/SurveyMemberReplyRepositoryTest.java b/src/test/java/com/keeper/homepage/domain/survey/dao/SurveyMemberReplyRepositoryTest.java index bb267e9a3..9f83c664f 100644 --- a/src/test/java/com/keeper/homepage/domain/survey/dao/SurveyMemberReplyRepositoryTest.java +++ b/src/test/java/com/keeper/homepage/domain/survey/dao/SurveyMemberReplyRepositoryTest.java @@ -36,7 +36,8 @@ class SurveyMemberReplyTest { public void 활동조사_기타_사유는_활동_조사_응답이_관리한다() throws Exception { em.flush(); em.clear(); - SurveyMemberReply memberReply = surveyMemberReplyRepository.findById(memberReplyId).orElseThrow(); + SurveyMemberReply memberReply = surveyMemberReplyRepository.findById(memberReplyId) + .orElseThrow(); assertThat(memberReply.getReplyExcuse().getRestExcuse()).isEqualTo(excuse.getRestExcuse()); assertThat(surveyReplyExcuseRepository.findById(memberReplyId)).isNotEmpty(); diff --git a/src/test/java/com/keeper/homepage/global/restdocs/RestDocsHelper.java b/src/test/java/com/keeper/homepage/global/restdocs/RestDocsHelper.java index ee42d2ba9..785272b8a 100644 --- a/src/test/java/com/keeper/homepage/global/restdocs/RestDocsHelper.java +++ b/src/test/java/com/keeper/homepage/global/restdocs/RestDocsHelper.java @@ -46,7 +46,8 @@ public static FieldDescriptor field(String path, String description, boolean opt } public static FieldDescriptor[] pageHelper(FieldDescriptor... fieldDescriptors) { - List descriptorList = new ArrayList<>(List.of(listHelper("content", fieldDescriptors))); + List descriptorList = new ArrayList<>( + List.of(listHelper("content", fieldDescriptors))); descriptorList.add(field("empty", "가져오는 페이지가 비어 있는 지")); descriptorList.add(field("first", "첫 페이지인지")); descriptorList.add(field("last", "마지막 페이지인지")); @@ -62,11 +63,13 @@ public static FieldDescriptor[] pageHelper(FieldDescriptor... fieldDescriptors) return descriptorList.toArray(new FieldDescriptor[0]); } - public static FieldDescriptor[] listHelper(String objectName, FieldDescriptor... fieldDescriptors) { + public static FieldDescriptor[] listHelper(String objectName, + FieldDescriptor... fieldDescriptors) { List descriptorList = new ArrayList<>(); for (FieldDescriptor descriptor : fieldDescriptors) { - descriptorList.add(field(objectName + "[]." + descriptor.getPath(), descriptor.getDescription().toString(), - descriptor.isOptional())); + descriptorList.add( + field(objectName + "[]." + descriptor.getPath(), descriptor.getDescription().toString(), + descriptor.isOptional())); } return descriptorList.toArray(new FieldDescriptor[0]); } diff --git a/src/test/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidatorTest.java b/src/test/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidatorTest.java index 5d466b564..b110c8f1d 100644 --- a/src/test/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidatorTest.java +++ b/src/test/java/com/keeper/homepage/global/util/thumbnail/server/ThumbnailServerValidatorTest.java @@ -23,7 +23,8 @@ void should_checkInvalidImageFile_when_notImageFile() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); FileCopyUtils.copy(fakeImageFile.getInputStream(), outputStream); - assertThatThrownBy(() -> checkInvalidImageFile(outputStream.toByteArray(), fakeImageFile.getOriginalFilename())) + assertThatThrownBy(() -> checkInvalidImageFile(outputStream.toByteArray(), + fakeImageFile.getOriginalFilename())) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/src/test/resources/org/springframework/restdocs/templates/query-parameters.snippet b/src/test/resources/org/springframework/restdocs/templates/query-parameters.snippet index c00a84a01..879019029 100644 --- a/src/test/resources/org/springframework/restdocs/templates/query-parameters.snippet +++ b/src/test/resources/org/springframework/restdocs/templates/query-parameters.snippet @@ -1,11 +1,11 @@ -|=== -|파라미터명|필수값|양식|설명 + |=== + |파라미터명|필수값|양식|설명 -{{#parameters}} -|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} -|{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} -|{{#tableCellContent}}{{#format}}{{.}}{{/format}}{{/tableCellContent}} -|{{#tableCellContent}}{{description}}{{/tableCellContent}} -{{/parameters}} + {{#parameters}} + |{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} + |{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} + |{{#tableCellContent}}{{#format}}{{.}}{{/format}}{{/tableCellContent}} + |{{#tableCellContent}}{{description}}{{/tableCellContent}} + {{/parameters}} -|=== + |=== diff --git a/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet b/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet index b554dc7b4..45e6e21c8 100644 --- a/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet +++ b/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet @@ -1,12 +1,12 @@ -|=== -|필드명|타입|필수값|양식|설명 + |=== + |필드명|타입|필수값|양식|설명 -{{#fields}} -|{{#tableCellContent}}`+{{path}}+`{{/tableCellContent}} -|{{#tableCellContent}}`+{{type}}+`{{/tableCellContent}} -|{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} -|{{#tableCellContent}}{{#format}}{{.}}{{/format}}{{/tableCellContent}} -|{{#tableCellContent}}{{description}}{{/tableCellContent}} -{{/fields}} + {{#fields}} + |{{#tableCellContent}}`+{{path}}+`{{/tableCellContent}} + |{{#tableCellContent}}`+{{type}}+`{{/tableCellContent}} + |{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} + |{{#tableCellContent}}{{#format}}{{.}}{{/format}}{{/tableCellContent}} + |{{#tableCellContent}}{{description}}{{/tableCellContent}} + {{/fields}} -|=== + |=== diff --git a/src/test/resources/org/springframework/restdocs/templates/request-parts.snippet b/src/test/resources/org/springframework/restdocs/templates/request-parts.snippet index 38a22a23e..76ef4445c 100644 --- a/src/test/resources/org/springframework/restdocs/templates/request-parts.snippet +++ b/src/test/resources/org/springframework/restdocs/templates/request-parts.snippet @@ -1,10 +1,10 @@ -|=== -|파트명|필수값|설명 + |=== + |파트명|필수값|설명 -{{#requestParts}} -|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} -|{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} -|{{#tableCellContent}}{{description}}{{/tableCellContent}} -{{/requestParts}} + {{#requestParts}} + |{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} + |{{#tableCellContent}}{{^optional}}true{{/optional}}{{/tableCellContent}} + |{{#tableCellContent}}{{description}}{{/tableCellContent}} + {{/requestParts}} -|=== + |===