Skip to content

Commit

Permalink
✨ [FEAT] #82: 아이덴티티 변경 API (#91)
Browse files Browse the repository at this point in the history
* feat: 아이덴티티 변경 api 구현

* chore: 존재하지 않는 키워드 요청 에러처리

* chore: JPA 메서드 이름 기반 쿼리로 수정

* chore: Update MemberServiceImpl.java
  • Loading branch information
oneeee822 authored Jan 25, 2025
1 parent bb3c335 commit 5eba954
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public enum ErrorStatus {
IDENTITY_ALREADY_SET(HttpStatus.BAD_REQUEST, "MEMBER4003", "아이덴티티 키워드는 최초 1회만 설정 가능합니다."),
INVALID_CATEGORY(HttpStatus.BAD_REQUEST, "MEMBER4004", "존재하지 않는 카테고리입니다."),
INVALID_IDENTITY_MAPPING(HttpStatus.BAD_REQUEST, "MEMBER4005", "카테고리와 키워드가 일치하지 않습니다."),
NO_CHANGES_IN_KEYWORDS(HttpStatus.BAD_REQUEST, "MEMBER4006", "선택된 키워드에 변경사항이 없습니다."),
NOT_EXISTS_KEYWORD(HttpStatus.BAD_REQUEST, "MEMBER4007", "존재하지 않는 키워드입니다."),

// 버블 관련 애러
BUBBLE_NOT_FOUND(HttpStatus.BAD_REQUEST, "BUBBLE4001", "버블을 찾을 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,13 @@ public ResponseEntity<ApiResponse> getIdentityKeywords(@AuthenticationPrincipal
MemberResponseDto.IdentityKeywordsResultDto result = memberService.getIdentityKeywords(userPrincipal);
return ApiResponse.onSuccess(SuccessStatus._OK, result);
}

@PatchMapping("/identity")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<ApiResponse> updateIdentityTest(
@AuthenticationPrincipal CustomUserPrincipal userPrincipal,
@RequestBody @Valid MemberRequestDto.IdentityTestSaveDto request) {
MemberResponseDto.IdentityTestSaveResultDto result = memberService.updateIdentityTest(userPrincipal, request);
return ApiResponse.onSuccess(SuccessStatus._OK, result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@ public interface MemberKeywordRepository extends JpaRepository<MemberKeyword, Lo
boolean existsByMember_MemberIdAndKeyword_Category(Long memberId, String category);

boolean existsByMember_MemberIdAndKeyword_KeywordId(Long memberId, Integer keywordId);

List<MemberKeyword> findByMember_MemberIdAndKeywordCategory(Long memberId, String category);

void deleteByMember_MemberIdAndKeywordCategory(Long memberId, String category);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ public interface MemberService {
ResponseEntity<ApiResponse> refreshAccessToken(String token);
MemberResponseDto.IdentityTestSaveResultDto saveIdentityTest(CustomUserPrincipal userPrincipal, MemberRequestDto.IdentityTestSaveDto request);
MemberResponseDto.IdentityKeywordsResultDto getIdentityKeywords(CustomUserPrincipal userPrincipal);
MemberResponseDto.IdentityTestSaveResultDto updateIdentityTest(CustomUserPrincipal userPrincipal, MemberRequestDto.IdentityTestSaveDto request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,14 @@
import com.edison.project.global.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.edison.project.domain.member.entity.Member;

import java.util.Objects;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import java.util.*;
import java.util.stream.Collectors;

import static com.edison.project.common.status.SuccessStatus._OK;
Expand Down Expand Up @@ -291,5 +286,74 @@ public MemberResponseDto.IdentityKeywordsResultDto getIdentityKeywords(CustomUse
.build();
}

@Override
@Transactional
public MemberResponseDto.IdentityTestSaveResultDto updateIdentityTest(CustomUserPrincipal userPrincipal, MemberRequestDto.IdentityTestSaveDto request) {
if (userPrincipal == null) {
throw new GeneralException(ErrorStatus.LOGIN_REQUIRED);
}

// 사용자 인증 확인
Member member = memberRepository.findById(userPrincipal.getMemberId())
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));

// 존재하지 않는 카테고리 검증
String category = request.getCategory();
List<String> validCategories = List.of("CATEGORY1", "CATEGORY2", "CATEGORY3", "CATEGORY4");
if (!validCategories.contains(category)) {
throw new GeneralException(ErrorStatus.INVALID_CATEGORY);
}

// 카테고리-키워드 맵핑 검증
List<Keywords> keywords = keywordsRepository.findAllById(request.getKeywords());
if (!keywords.stream().allMatch(keyword -> category.equals(keyword.getCategory()))) {
throw new GeneralException(ErrorStatus.INVALID_IDENTITY_MAPPING);
}

// 요청된 키워드 ID를 가져옵니다.
List<Integer> requestedKeywordIds = request.getKeywords();

// 데이터베이스에서 해당 카테고리에 속하는 모든 키워드 ID를 조회합니다.
List<Integer> validKeywordIds = keywordsRepository.findAllByCategory(request.getCategory()).stream()
.map(Keywords::getKeywordId)
.collect(Collectors.toList());

// 요청된 키워드 ID 중에서 존재하지 않는 키워드 ID를 필터링합니다.
List<Integer> invalidKeywordIds = requestedKeywordIds.stream()
.filter(keywordId -> !validKeywordIds.contains(keywordId))
.collect(Collectors.toList());

// 존재하지 않는 키워드가 있다면 에러를 throw 합니다.
if (!invalidKeywordIds.isEmpty()) {
throw new GeneralException(ErrorStatus.NOT_EXISTS_KEYWORD);
}

List<MemberKeyword> existingMemberKeywords = memberKeywordRepository.findByMember_MemberIdAndKeywordCategory(member.getMemberId(), request.getCategory());
List<Integer> existingKeywordIds = existingMemberKeywords.stream()
.map(memberKeyword -> memberKeyword.getKeyword().getKeywordId())
.collect(Collectors.toList());

// 이전 키워드와 비교하여 동일한지 확인
if (new HashSet<>(existingKeywordIds).equals(new HashSet<>(request.getKeywords()))) {
throw new GeneralException(ErrorStatus.NO_CHANGES_IN_KEYWORDS);
}

memberKeywordRepository.deleteByMember_MemberIdAndKeywordCategory(member.getMemberId(), category);


List<MemberKeyword> memberKeywords = keywords.stream()
.map(keyword -> MemberKeyword.builder()
.member(member)
.keyword(keyword)
.build())
.collect(Collectors.toList());
memberKeywordRepository.saveAll(memberKeywords);

return MemberResponseDto.IdentityTestSaveResultDto.builder()
.category(category)
.keywords(request.getKeywords())
.build();
}


}

0 comments on commit 5eba954

Please sign in to comment.