diff --git a/src/main/java/com/capstone/BnagFer/domain/accounts/service/email/EmailService.java b/src/main/java/com/capstone/BnagFer/domain/accounts/service/email/EmailService.java index 88504b91..ba85522f 100644 --- a/src/main/java/com/capstone/BnagFer/domain/accounts/service/email/EmailService.java +++ b/src/main/java/com/capstone/BnagFer/domain/accounts/service/email/EmailService.java @@ -27,7 +27,6 @@ public class EmailService { private final JavaMailSender javaMailSender; private final RedisUtil redisUtil; - private final String ePw = createKey(); private static final String AUTH_CODE_PREFIX = "AuthCode "; @Value("${spring.mail.username}") @@ -36,15 +35,15 @@ public class EmailService { @Value("${spring.mail.smtp.timeout}") private long codeExpTime; - public MimeMessage createMessage(String to) throws MessagingException, UnsupportedEncodingException { - log.info("보내는 대상: " + to); - log.info("인증 번호: " + ePw); + public MimeMessage createMessage(String to, String authCode) throws MessagingException, UnsupportedEncodingException { +// log.info("보내는 대상: " + to); +// log.info("인증 번호: " + authCode); MimeMessage message = javaMailSender.createMimeMessage(); message.addRecipients(MimeMessage.RecipientType.TO, to); // 보낼 대상 message.setSubject("방구석 퍼거슨 인증 코드"); // 메일 제목 - String msg = getString(); + String msg = getString(authCode); message.setText(msg, "utf-8", "html"); //내용, charset타입, subtype message.setFrom(new InternetAddress(id,"bangFer")); @@ -52,12 +51,12 @@ public MimeMessage createMessage(String to) throws MessagingException, Unsupport return message; } - private String getString() { + private String getString(String authCode) { String msg=""; msg += "

이메일 주소 확인

"; msg += "

아래 확인 코드를 화면에서 입력해주세요.

"; msg += "
"; - msg += ePw; + msg += authCode; msg += "
"; return msg; } @@ -75,23 +74,28 @@ public static String createKey() { @Transactional public String sendMessage(String to) throws Exception { - MimeMessage message = createMessage(to); + String authCode = createKey(); + MimeMessage message = createMessage(to, authCode); try { javaMailSender.send(message); } catch (MailException es) { es.printStackTrace(); throw new AccountsExceptionHandler(ErrorCode.UNABLE_TO_SEND_EMAIL); } - redisUtil.save(AUTH_CODE_PREFIX + to, ePw, codeExpTime, TimeUnit.MILLISECONDS); - return ePw; + redisUtil.save(AUTH_CODE_PREFIX + to, authCode, codeExpTime, TimeUnit.MILLISECONDS); + return authCode; } @Transactional public boolean verifyCode(EmailVerifyDto requestDto) { - if (!(redisUtil.hasKey(AUTH_CODE_PREFIX + requestDto.email()))) { + String key = AUTH_CODE_PREFIX + requestDto.email(); + + if (!(redisUtil.hasKey(key))) { throw new CustomException(ErrorCode.CODE_IS_NOT_VALID); } - else if (redisUtil.get(AUTH_CODE_PREFIX + requestDto.email()).toString().equals(requestDto.code())) { + String savedCode = redisUtil.get(key).toString(); + if (savedCode.equals(requestDto.code())) { + redisUtil.delete(key); // 인증 후 삭제 return true; } else { diff --git a/src/main/java/com/capstone/BnagFer/domain/board/dto/request/BoardBlockRequestDto.java b/src/main/java/com/capstone/BnagFer/domain/board/dto/request/BoardBlockRequestDto.java deleted file mode 100644 index 0aff4f8e..00000000 --- a/src/main/java/com/capstone/BnagFer/domain/board/dto/request/BoardBlockRequestDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.capstone.BnagFer.domain.board.dto.request; - -import com.capstone.BnagFer.domain.accounts.entity.User; -import com.capstone.BnagFer.domain.board.entity.BoardBlock; - -public record BoardBlockRequestDto() { - public BoardBlock toEntity(User blockUser, User isBlockedUser) { - return BoardBlock.builder() - .blockUser(blockUser) - .isBlockedUser(isBlockedUser) - .build(); - } -} diff --git a/src/main/java/com/capstone/BnagFer/domain/board/entity/BoardBlock.java b/src/main/java/com/capstone/BnagFer/domain/board/entity/BoardBlock.java index dc112ba9..3649a38a 100644 --- a/src/main/java/com/capstone/BnagFer/domain/board/entity/BoardBlock.java +++ b/src/main/java/com/capstone/BnagFer/domain/board/entity/BoardBlock.java @@ -1,10 +1,10 @@ package com.capstone.BnagFer.domain.board.entity; - import com.capstone.BnagFer.domain.accounts.entity.User; import com.capstone.BnagFer.global.common.BaseEntity; import jakarta.persistence.*; import lombok.*; import java.time.LocalDateTime; + @Entity @Builder @Getter @@ -16,15 +16,21 @@ public class BoardBlock extends BaseEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "board_block_id", nullable = false) private Long id; - @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "block_user_id") private User blockUser; - @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "is_blocked_user_id") private User isBlockedUser; @Column(name = "blocked_at") private LocalDateTime blockedAt; -} + + public static BoardBlock create(User blockUser, User isBlockedUser) { + BoardBlock boardBlock = new BoardBlock(); + boardBlock.blockUser = blockUser; + boardBlock.isBlockedUser = isBlockedUser; + return boardBlock; + + } +} \ No newline at end of file diff --git a/src/main/java/com/capstone/BnagFer/domain/board/service/BoardBlockService.java b/src/main/java/com/capstone/BnagFer/domain/board/service/BoardBlockService.java index 1e579a8d..97e2545a 100644 --- a/src/main/java/com/capstone/BnagFer/domain/board/service/BoardBlockService.java +++ b/src/main/java/com/capstone/BnagFer/domain/board/service/BoardBlockService.java @@ -1,8 +1,6 @@ package com.capstone.BnagFer.domain.board.service; - import com.capstone.BnagFer.domain.accounts.entity.User; import com.capstone.BnagFer.domain.accounts.repository.UserJpaRepository; -import com.capstone.BnagFer.domain.board.dto.request.BoardBlockRequestDto; import com.capstone.BnagFer.domain.board.dto.response.BoardBlockResponseDto; import com.capstone.BnagFer.domain.board.entity.BoardBlock; import com.capstone.BnagFer.domain.board.exception.BoardExceptionHandler; @@ -11,7 +9,6 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @RequiredArgsConstructor @Transactional @@ -20,28 +17,31 @@ public class BoardBlockService { private final UserJpaRepository userRepository; public BoardBlockResponseDto blockUser(User blockUser, Long isBlockedUserId) { - User blockedUser = userRepository.findById(isBlockedUserId) - .orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND)); - if (blockUser.getId().equals(isBlockedUserId)) { - throw new BoardExceptionHandler(ErrorCode.CANNOT_REPORT_YOURSELF); - } - if(boardBlockRepository.existsByBlockUserAndIsBlockedUser(blockUser, blockedUser)){ + User blockedUser = checkIfIsBlocked(isBlockedUserId); + validateSelfAction(blockUser, isBlockedUserId, ErrorCode.CANNOT_REPORT_YOURSELF); + if (boardBlockRepository.existsByBlockUserAndIsBlockedUser(blockUser, blockedUser)) { throw new BoardExceptionHandler(ErrorCode.ALREADY_BLOCKED); } - BoardBlockRequestDto request = new BoardBlockRequestDto(); - BoardBlock boardBlock = request.toEntity(blockUser, blockedUser); + + BoardBlock boardBlock = BoardBlock.create(blockUser, blockedUser); boardBlockRepository.save(boardBlock); return BoardBlockResponseDto.from(boardBlock); } public void unblockUser(User blockUser, Long isBlockedUserId) { - User blockedUser = userRepository.findById(isBlockedUserId) - .orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND)); - if (blockUser.getId().equals(isBlockedUserId)) { - throw new BoardExceptionHandler(ErrorCode.CANNOT_UNBLOCK_YOURSELF); - } + User blockedUser = checkIfIsBlocked(isBlockedUserId); + validateSelfAction(blockUser, isBlockedUserId, ErrorCode.CANNOT_UNBLOCK_YOURSELF); boardBlockRepository.deleteByBlockUserAndIsBlockedUser(blockUser, blockedUser); } + private User checkIfIsBlocked(Long isBlockedUserId) { + return userRepository.findById(isBlockedUserId) + .orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND)); + } -} + private void validateSelfAction(User blockUser, Long isBlockedUserId, ErrorCode errorCode) { + if (blockUser.getId().equals(isBlockedUserId)) { + throw new BoardExceptionHandler(errorCode); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamInviteService.java b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamInviteService.java index 2a87aa31..741aabf4 100644 --- a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamInviteService.java +++ b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamInviteService.java @@ -4,7 +4,6 @@ import com.capstone.BnagFer.domain.accounts.entity.User; import com.capstone.BnagFer.domain.accounts.repository.ProfileJpaRepository; import com.capstone.BnagFer.domain.accounts.service.account.AccountsCommonService; -import com.capstone.BnagFer.domain.notification.event.TeamInviteCreatedEvent; import com.capstone.BnagFer.domain.myteam.dto.request.TeamInviteRequestDto; import com.capstone.BnagFer.domain.myteam.dto.response.TeamInviteResponseDto; import com.capstone.BnagFer.domain.myteam.dto.response.TeamMembersResponseDto; @@ -14,6 +13,7 @@ import com.capstone.BnagFer.domain.myteam.repository.TeamInviteRepository; import com.capstone.BnagFer.domain.myteam.repository.TeamMembersRepository; import com.capstone.BnagFer.domain.myteam.repository.TeamRepository; +import com.capstone.BnagFer.domain.notification.event.TeamInviteCreatedEvent; import com.capstone.BnagFer.global.common.ErrorCode; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationEventPublisher; @@ -33,36 +33,19 @@ public class TeamInviteService { public TeamInviteResponseDto inviteTeamMembers(TeamInviteRequestDto request, User inviter) { Profile profile = profileJpaRepository.findByNickname(request.nickName()); - if(profile==null){ + if (profile == null) { throw new TeamMemberExceptionHandler(ErrorCode.USER_NOT_FOUND); } User invitedUser = profile.getUser(); - //초대가 이루어질 팀을 ID로 찾아오고, 없으면 TEAM_NOT_FOUND 예외를 던진다 + Team team = teamRepository.findById(request.teamId()) .orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND)); - // 방장이 자기 자신을 초대 못하게 하는 예외처리 - if (inviter.getId().equals(invitedUser.getId())) { - throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_INVITE_YOURSELF); - } - - // 초대하려는 사용자가 팀의 리더가 아닌 경우 예외를 던진다 - if (!team.getLeader().getId().equals(inviter.getId())) { - throw new TeamMemberExceptionHandler(ErrorCode.NO_AUTHORIZATION); - } - // 초대받은 사용자가 이미 팀 멤버인지 확인한다 - boolean isAlreadyMember = team.getTeamMembers().stream() - .anyMatch(teamMember -> teamMember.getUser().equals(invitedUser)); - if (isAlreadyMember) { - throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_EXISTS); - } + checkIfAlreadyMember(team, invitedUser); // 초대받은 사용자가 이미 초대되었는지 확인한다 - boolean isAlreadyInvited = teamInviteRepository.existsByTeamAndInvitedUser(team, invitedUser); - if (isAlreadyInvited) { - throw new TeamMemberExceptionHandler(ErrorCode.INVITATION_ALREADY_SENT); - } + checkIfAlreadyInvited(team, invitedUser); // 초대 엔티티를 생성하고 저장한다 TeamInvite teamInvite = request.toEntity(invitedUser, team, inviter); @@ -71,30 +54,28 @@ public TeamInviteResponseDto inviteTeamMembers(TeamInviteRequestDto request, Use // FCM 알림 전송 eventPublisher.publishEvent(new TeamInviteCreatedEvent(savedInvite)); - // 초대 정보를 응답 DTO로 변환하여 반환한다 return TeamInviteResponseDto.from(teamInvite); } + public void kickOutMembers(Long memberId, Long teamId, User user) { TeamMember teamMember = teamMembersRepository.findById(memberId).orElseThrow(() -> new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER)); Team team = teamRepository.findById(teamId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND)); // 프로필 존재 확인 accountsCommonService.checkUserProfile(teamMember.getUser()); - //방장에게만 강퇴 권한 if (team.getLeader().getId().equals(user.getId())) - teamMembersRepository.delete(teamMember); - else throw new TeamMemberExceptionHandler(ErrorCode.NO_AUTHORIZATION); - //방장이 자기 자신을 강퇴 못하게 해주는 예외처리 - if (user.getId().equals(memberId)) { + if (user.getId().equals(memberId)) throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_KICK_OUT_YOURSELF); - } + //이미 강퇴당한 팀원 예외처리 if (teamMember.getId() == null) throw new TeamMemberExceptionHandler(ErrorCode.ALREAY_KICKED_OUT); + + teamMembersRepository.delete(teamMember); } public TeamMembersResponseDto acceptInvite(Long inviteId, User user) { @@ -120,4 +101,19 @@ public void rejectInvite(Long inviteId, User user) { } teamInviteRepository.delete(invite); } + + private void checkIfAlreadyMember(Team team, User invitedUser) { + boolean isAlreadyMember = team.getTeamMembers().stream() + .anyMatch(teamMember -> teamMember.getUser().equals(invitedUser)); + if (isAlreadyMember) { + throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_EXISTS); + } + } + + private void checkIfAlreadyInvited(Team team, User invitedUser) { + boolean isAlreadyInvited = teamInviteRepository.existsByTeamAndInvitedUser(team, invitedUser); + if (isAlreadyInvited) { + throw new TeamMemberExceptionHandler(ErrorCode.INVITATION_ALREADY_SENT); + } + } } diff --git a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamMembersService.java b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamMembersService.java index 1eb5cc1e..a6b74f7b 100644 --- a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamMembersService.java +++ b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamMembersService.java @@ -25,37 +25,19 @@ public class TeamMembersService { private final TeamRepository teamRepository; private final ApplicationEventPublisher eventPublisher; + public TeamMemberPositionResponseDto allocatePosition(TeamMemberPositionRequestDto request, Long teamId, Long memberId, User user) { Team team = teamRepository.findById(teamId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND)); TeamMember teamMember = teamMembersRepository.findById(memberId).orElseThrow(() -> new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER)); - if (!team.getId().equals(teamMember.getTeam().getId())) { - throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER); - } + validateTeamMemberIsInTeam(team, teamMember); + validateLeaderAuthorization(team, user); Position requestedPosition = request.position(); - // 요청한 포지션(requestedPosition)이 이미 다른 멤버에게 할당되어 있는지 확인 - TeamMember existingMemberWithPosition = teamMembersRepository.findByTeamAndPosition(team, requestedPosition); - boolean teamMemberInTeam = teamMembersRepository.existsByTeamAndId(team, memberId); - if (team.getLeader().getId().equals(user.getId())) { - if (teamMemberInTeam) { - if (existingMemberWithPosition == null || !existingMemberWithPosition.equals(teamMember)) { - // 이미 다른 멤버가 요청한 포지션을 가지고 있으면 그 멤버의 포지션을 null로 설정 - if (existingMemberWithPosition != null) { - existingMemberWithPosition.updatePosition(null); - teamMembersRepository.save(existingMemberWithPosition); - } - // 요청한 멤버에게 포지션 할당 - teamMember.updatePosition(requestedPosition); - teamMembersRepository.save(teamMember); - - // FCM 알림 전송 - eventPublisher.publishEvent(new PositionAllocatedEvent(teamMember, requestedPosition)); - } - } else - throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER); - } else - throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE); + TeamMember existingMemberWithPosition = findExistingMemberWithPosition(team, requestedPosition); + + allocateTeamMemberPosition(team, teamMember, existingMemberWithPosition, requestedPosition); + return TeamMemberPositionResponseDto.from(request.toEntity(teamMember)); } @@ -74,4 +56,39 @@ public void deallocatePosition(Long teamId, Long memberId, User user) { } else throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE); } -} \ No newline at end of file + + private void validateTeamMemberIsInTeam(Team team, TeamMember teamMember) { + if (!team.getId().equals(teamMember.getTeam().getId())) { + throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_NOT_IN_TEAM); + } + } + + private void validateLeaderAuthorization(Team team, User user) { + if (!team.getLeader().getId().equals(user.getId())) { + throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE); + } + } + + private TeamMember findExistingMemberWithPosition(Team team, Position requestedPosition) { + return teamMembersRepository.findByTeamAndPosition(team, requestedPosition); + } + + private void allocateTeamMemberPosition(Team team, TeamMember teamMember, TeamMember existingMemberWithPosition, Position requestedPosition) { + boolean teamMemberInTeam = teamMembersRepository.existsByTeamAndId(team, teamMember.getId()); + + if (!teamMemberInTeam) { + throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER); + } + + if (existingMemberWithPosition != null && !existingMemberWithPosition.equals(teamMember)) { + existingMemberWithPosition.updatePosition(null); + teamMembersRepository.save(existingMemberWithPosition); + } + + teamMember.updatePosition(requestedPosition); + teamMembersRepository.save(teamMember); + // FCM 알림 전송 + eventPublisher.publishEvent(new PositionAllocatedEvent(teamMember, requestedPosition)); + } + +} diff --git a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamQueryService.java b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamQueryService.java index 3d018501..c4d8d5f3 100644 --- a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamQueryService.java +++ b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamQueryService.java @@ -49,18 +49,4 @@ public List getMyTeamList(User user) { return teamLists; } - -// public GetTeamResponseDto.getIndividualDetail getIndividualDetail(Long teamId, Long tacticPositionDetailId) { -// -// Team team = teamRepository.findById(teamId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND)); -// TacticPositionDetail tacticPositionDetail = tacticPositionDetailRepository.findById(tacticPositionDetailId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.DETAIL_NOT_FOUND)); -// -// List tacticPositionDetails = team.getTactic().getTacticPositionDetails(); -// TeamMember byTeamAndPosition = teamMembersRepository.findByTeamAndPosition(team, tacticPositionDetail.getPosition()); -// -// if (tacticPositionDetails.contains(tacticPositionDetail)) { -// return GetTeamResponseDto.getIndividualDetail.from(team, tacticPositionDetail, byTeamAndPosition); -// } else -// return GetTeamResponseDto.getIndividualDetail.from(team, tacticPositionDetail, null); -// } } diff --git a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamTacticService.java b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamTacticService.java index fc1a767a..d3ea27fd 100644 --- a/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamTacticService.java +++ b/src/main/java/com/capstone/BnagFer/domain/myteam/service/TeamTacticService.java @@ -31,9 +31,6 @@ public CreateTeamTacticResponseDto changeTactic(Long teamId, Long tacticId, User // 팀 멤버들의 포지션 초기화 resetTeamMemberPositions(team); - // 팀 저장 - teamRepository.save(team); - return CreateTeamTacticResponseDto.from(team, CreateTeamTacticResponseDto.TacticDto.from(tactic)); } @@ -47,12 +44,10 @@ public void deallocateMyTactic(Long teamId, Long tacticId, User user) { } if (team.getTactic() != null && team.getTactic().getTacticId().equals(tacticId)) { team.deleteMyTactic(); - teamRepository.save(team); } else { throw new TacticExceptionHandler(ErrorCode.TACTIC_NOT_FOUND); } } - private void validateAndUpdateTeam(Team team, User user, Tactic tactic) { // 팀 리더 검증 diff --git a/src/main/java/com/capstone/BnagFer/global/common/ErrorCode.java b/src/main/java/com/capstone/BnagFer/global/common/ErrorCode.java index 6177ec13..adbdf5c0 100644 --- a/src/main/java/com/capstone/BnagFer/global/common/ErrorCode.java +++ b/src/main/java/com/capstone/BnagFer/global/common/ErrorCode.java @@ -82,6 +82,7 @@ public enum ErrorCode implements BaseErrorCode { WRONG_INVITATION(HttpStatus.BAD_REQUEST, "TEAMMEMBER416", "자기 자신에게 온 초대가 아닙니다."), INVITATION_ALREADY_SENT(HttpStatus.BAD_REQUEST, "TEAMMEMBER417", "이미 초대가 보내졌습니다."), NOT_A_PENDING_STATUS(HttpStatus.BAD_REQUEST, "TEAMMEMBER418", "이미 초대를 거절했거나 승인한 상태입니다."), + TEAMMEMBER_NOT_IN_TEAM(HttpStatus.BAD_REQUEST, "TEAMMEMBER419", "해당 팀에 해당 팀원이 없습니다."), //CALENDAR_EVENT 관련 에러 MATCH_EVENT_NOT_EXIST(HttpStatus.BAD_REQUEST, "CALENDAREVENT401", "매치 일정이 존재하지 않습니다."),