Skip to content

Commit

Permalink
[REFACTOR] MyTeam&Board 부분 클린코딩 적용(#189) (#193)
Browse files Browse the repository at this point in the history
* ♻️refactor: 사용자 차단 시, 차단 객체는 Dto가 아닌 Entity에서 처리되도록 static 메서드로 대체(#189)

* ♻️refactor: 클린코딩 적용(#189)
  • Loading branch information
600gramSik authored Sep 12, 2024
1 parent 3903d4a commit 8f973da
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 108 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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;

}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -11,7 +9,6 @@
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
Expand All @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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) {
Expand All @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand All @@ -74,4 +56,39 @@ public void deallocatePosition(Long teamId, Long memberId, User user) {
} else
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE);
}
}

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));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,4 @@ public List<GetTeamResponseDto.TeamList> 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<TacticPositionDetail> 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);
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand All @@ -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) {

// 팀 리더 검증
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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", "매치 일정이 존재하지 않습니다."),
Expand Down

0 comments on commit 8f973da

Please sign in to comment.