Skip to content

Commit

Permalink
🐛 fix: 그룹 일부 삭제 시 롤링페이퍼를 소유하고 있다면 오류가 발생하던 문제 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
woosung1223 committed Oct 2, 2024
1 parent 42e0faf commit ffb6b39
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 22 deletions.
55 changes: 37 additions & 18 deletions src/main/java/slvtwn/khu/toyouserver/application/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -76,9 +77,7 @@ private List<UserResponse> findUsersWithSpecificGroup(User user, String search,
public void updateUser(Long userId, UserUpdateRequest request) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ToyouException(ResponseType.USER_NOT_FOUND));

changeUserGroupsIfChanged(request, user);

user.updateInfo(request.name(), request.birthday(), request.introduction(), request.imageUrl());
createBirthdayEvents(user);
}
Expand All @@ -87,37 +86,57 @@ private void changeUserGroupsIfChanged(UserUpdateRequest request, User user) {
List<Group> requestGroups = findGroupsFromRequest(request);
List<Group> userGroups = findGroupsFromUser(user);

if (!requestGroups.equals(userGroups)) {
replaceUserGroups(user, request.groups());
if (isGroupUpdatedNeeded(requestGroups, userGroups)) {
List<Group> removedGroups = findRemoveGroups(requestGroups, userGroups);
List<Group> newGroups = findNewGroups(requestGroups, userGroups);
deleteRollingPaperAndMembers(user, removedGroups);
saveMembersWithNewGroups(user, newGroups);
}
}

private void deleteRollingPaperAndMembers(User user, List<Group> removedGroups) {
List<Member> members = memberRepository.findByUser(user);

rollingPaperRepository.deleteAllByMemberIn(members);
memberRepository.deleteByUserAndGroupIn(user, removedGroups);
}

private List<Group> findGroupsFromRequest(UserUpdateRequest request) {
return request.groups().stream()
.map(each -> groupRepository.findById(each.id())
.orElseThrow(() -> new ToyouException(ResponseType.BAD_REQUEST)))
.toList();
List<Long> groupIds = request.groups().stream()
.map(GroupRequest::id)
.collect(Collectors.toList());

return groupRepository.findAllByIdIn(groupIds);
}

private List<Group> findGroupsFromUser(User user) {
return memberRepository.findByUser(user).stream()
.map(Member::getGroup)
.toList();
.collect(Collectors.toList());
}

private void replaceUserGroups(User user, List<GroupRequest> groupRequests) {
List<Member> members = memberRepository.findByUser(user);
private boolean isGroupUpdatedNeeded(List<Group> requestGroups, List<Group> userGroups) {
if (requestGroups.size() > userGroups.size()) {
return true;
}
userGroups.removeAll(requestGroups);
return !userGroups.isEmpty();
}

rollingPaperRepository.deleteAllByMemberIn(members);
memberRepository.deleteAll(members);
private List<Group> findRemoveGroups(List<Group> requestGroups, List<Group> userGroups) {
return userGroups.stream()
.filter(each -> !requestGroups.contains(each))
.toList();
}

saveMembersWithNewGroups(user, groupRequests);
private List<Group> findNewGroups(List<Group> requestGroups, List<Group> userGroups) {
return requestGroups.stream()
.filter(each -> !userGroups.contains(each))
.toList();
}

private void saveMembersWithNewGroups(User user, List<GroupRequest> groupRequests) {
List<Member> newMembers = groupRequests.stream()
.map(each -> groupRepository.findById(each.id())
.orElseThrow(() -> new ToyouException(ResponseType.BAD_REQUEST)))
private void saveMembersWithNewGroups(User user, List<Group> groups) {
List<Member> newMembers = groups.stream()
.map(each -> new Member(user, each))
.map(memberRepository::save)
.toList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
public interface GroupRepository extends JpaRepository<Group, Long> {

List<Group> findTop30ByNameLike(String keyword);
List<Group> findAllByIdIn(List<Long> groupIds);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ public interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> findByGroupAndUserNameLike(Group group, String pattern);

Optional<Member> findByUserIdAndGroupId(Long userId, Long groupId);

void deleteByUserAndGroupIn(User user, List<Group> group);
}
130 changes: 126 additions & 4 deletions src/test/java/slvtwn/khu/toyouserver/application/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.persistence.PersistenceContext;
import java.time.LocalDate;
import java.util.List;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
Expand All @@ -14,6 +15,7 @@
import org.springframework.transaction.annotation.Transactional;
import slvtwn.khu.toyouserver.domain.Group;
import slvtwn.khu.toyouserver.domain.Member;
import slvtwn.khu.toyouserver.domain.RollingPaper;
import slvtwn.khu.toyouserver.domain.User;
import slvtwn.khu.toyouserver.dto.GroupRequest;
import slvtwn.khu.toyouserver.dto.UserResponse;
Expand Down Expand Up @@ -80,7 +82,7 @@ class UserServiceTest {
}

@Test
void 유저_정보를_업데이트_할_수_있다() {
void 유저_정보_업데이트_시_새로_그룹을_추가할_수_있다() {
// given
User user = new User("name", LocalDate.now(), "introduction", "profile_picture", null);
Group group1 = new Group("name");
Expand All @@ -102,9 +104,129 @@ class UserServiceTest {

// then
User expectedUser = new User(request.name(), request.birthday(), request.introduction(), request.imageUrl(), null);
List<Member> userRelatedMembers = entityManager.createQuery("select m from Member m where user = :user")
.setParameter("user", user)
.getResultList();

SoftAssertions.assertSoftly(softly -> {
softly.assertThat(user)
.usingRecursiveComparison()
.ignoringFields("id", "createdDate", "lastModifiedDate")
.isEqualTo(expectedUser);

softly.assertThat(userRelatedMembers)
.extracting(Member::getGroup)
.containsExactlyInAnyOrder(group1, group2);
});
}

@Test
void 유저_정보_업데이트_시_그룹을_대체할_수_있다() {
// given
User user = new User("name", LocalDate.now(), "introduction", "profile_picture", null);
Group group1 = new Group("name");
Group group2 = new Group("name");
Member member = new Member(user, group1);

entityManager.persist(user);
entityManager.persist(group1);
entityManager.persist(group2);
entityManager.persist(member);

UserUpdateRequest request = new UserUpdateRequest(user.getId(), LocalDate.now().plusDays(1),
"new_name", "new_introduction", "new_image_url", List.of(
new GroupRequest(group2.getId(), group2.getName())));

// when
userService.updateUser(user.getId(), request);

// then
User expectedUser = new User(request.name(), request.birthday(), request.introduction(), request.imageUrl(), null);
List<Member> userRelatedMembers = entityManager.createQuery("select m from Member m where user = :user")
.setParameter("user", user)
.getResultList();

SoftAssertions.assertSoftly(softly -> {
softly.assertThat(user)
.usingRecursiveComparison()
.ignoringFields("id", "createdDate", "lastModifiedDate")
.isEqualTo(expectedUser);

softly.assertThat(userRelatedMembers)
.extracting(Member::getGroup)
.containsExactlyInAnyOrder(group2);
});
}

@Test
void 유저_정보_업데이트_시_그룹을_삭제할_수_있다() {
// given
User user = new User("name", LocalDate.now(), "introduction", "profile_picture", null);
Group group1 = new Group("name");
Group group2 = new Group("name");
Member member1 = new Member(user, group1);
Member member2 = new Member(user, group2);

entityManager.persist(user);
entityManager.persist(group1);
entityManager.persist(group2);
entityManager.persist(member1);
entityManager.persist(member2);

UserUpdateRequest request = new UserUpdateRequest(user.getId(), LocalDate.now().plusDays(1),
"new_name", "new_introduction", "new_image_url", List.of());

// when
userService.updateUser(user.getId(), request);

// then
User expectedUser = new User(request.name(), request.birthday(), request.introduction(), request.imageUrl(), null);
List<Member> userRelatedMembers = entityManager.createQuery("select m from Member m where user = :user")
.setParameter("user", user)
.getResultList();

SoftAssertions.assertSoftly(softly -> {
softly.assertThat(user)
.usingRecursiveComparison()
.ignoringFields("id", "createdDate", "lastModifiedDate")
.isEqualTo(expectedUser);

softly.assertThat(userRelatedMembers)
.hasSize(0);
});
}

@Test
void 유저_정보_업데이트_시_그룹을_삭제하면_관련_롤링페이퍼도_삭제된다() {
// given
User user = new User("name", LocalDate.now(), "introduction", "profile_picture", null);
Group group = new Group("name");
Member member = new Member(user, group);
RollingPaper rollingPaper = new RollingPaper("image_url", "title", "content",
null, member, null);

entityManager.persist(user);
entityManager.persist(group);
entityManager.persist(member);
entityManager.persist(rollingPaper);

UserUpdateRequest request = new UserUpdateRequest(user.getId(), LocalDate.now().plusDays(1),
"new_name", "new_introduction", "new_image_url", List.of());

// when
userService.updateUser(user.getId(), request);

// then
User expectedUser = new User(request.name(), request.birthday(), request.introduction(), request.imageUrl(), null);

SoftAssertions.assertSoftly(softly -> {
softly.assertThat(user)
.usingRecursiveComparison()
.ignoringFields("id", "createdDate", "lastModifiedDate")
.isEqualTo(expectedUser);

assertThat(user).usingRecursiveComparison()
.ignoringFields("id", "createdDate", "lastModifiedDate")
.isEqualTo(expectedUser);
softly.assertThat(entityManager.contains(rollingPaper))
.isFalse();
});
}
}

0 comments on commit ffb6b39

Please sign in to comment.