Skip to content

Commit

Permalink
[COZY-30] Role 조회 기능 구현 & 여러 리팩토링
Browse files Browse the repository at this point in the history
* [COZY--30] feat: role 생성, 삭제 기능 구현

* [COZY-30] feat: 데이터 조회 방식 분리  / Role 조회, Rule 조회 따로

* [COZY-30] fix: 에러 해결

* [COZY-30] feat: 기능 로직 수정

* [COZY-30] refac: 인증 어노테이션 적용 & SwaggerApiError 적용

* [COZY-30] feat: Transactional readonly 추가

* [COZY-30] feat: 매일인지 여부 반환 추가
  • Loading branch information
eple0329 authored Aug 14, 2024
1 parent df640f5 commit 8a09099
Show file tree
Hide file tree
Showing 18 changed files with 438 additions and 46 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package com.cozymate.cozymate_server.domain.role.controller;

import com.cozymate.cozymate_server.domain.auth.userDetails.MemberDetails;
import com.cozymate.cozymate_server.domain.role.dto.RoleRequestDto.CreateRoleRequestDto;
import com.cozymate.cozymate_server.domain.role.dto.RoleResponseDto.RoleListDetailResponseDto;
import com.cozymate.cozymate_server.domain.role.service.RoleCommandService;
import com.cozymate.cozymate_server.domain.role.service.RoleQueryService;
import com.cozymate.cozymate_server.global.response.ApiResponse;
import com.cozymate.cozymate_server.global.response.code.status.ErrorStatus;
import com.cozymate.cozymate_server.global.utils.SwaggerApiError;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
public class RoleController {

private final RoleCommandService roleCommandService;
private final RoleQueryService roleQueryService;

@PostMapping("/{roomId}")
@Operation(summary = "[무빗] 특정 방에 role 생성", description = "본인의 룸메라면 Role을 할당할 수 있습니다.")
@SwaggerApiError({ErrorStatus._MATE_OR_ROOM_NOT_FOUND})
public ResponseEntity<ApiResponse<String>> createRole(
@AuthenticationPrincipal MemberDetails memberDetails,
@PathVariable Long roomId,
@Valid @RequestBody CreateRoleRequestDto createRoleRequestDto

) {
roleCommandService.createRole(memberDetails.getMember(), roomId, createRoleRequestDto);
return ResponseEntity.ok(ApiResponse.onSuccess("Role 생성 완료."));
}

@GetMapping("/{roomId}")
@Operation(summary = "[무빗] 특정 방에 role 목록 조회", description = "")
@SwaggerApiError({ErrorStatus._MATE_OR_ROOM_NOT_FOUND})
public ResponseEntity<ApiResponse<RoleListDetailResponseDto>> getRoleList(
@AuthenticationPrincipal MemberDetails memberDetails,
@PathVariable Long roomId
) {

return ResponseEntity.ok(ApiResponse.onSuccess(
roleQueryService.getRole(roomId, memberDetails.getMember())
));
}

@DeleteMapping("{roomId}")
@Operation(summary = "[무빗] 특정 role 삭제", description = "본인의 룸메라면 Role을 삭제할 수 있습니다.")
@SwaggerApiError({ErrorStatus._MATE_OR_ROOM_NOT_FOUND, ErrorStatus._ROLE_NOT_FOUND,
ErrorStatus._ROLE_MATE_MISMATCH})
public ResponseEntity<ApiResponse<String>> deleteRole(
@AuthenticationPrincipal MemberDetails memberDetails,
@PathVariable Long roomId,
@RequestParam Long roleId
) {
roleCommandService.deleteRole(roomId, roleId, memberDetails.getMember());
return ResponseEntity.ok(ApiResponse.onSuccess("Role 삭제 완료"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.cozymate.cozymate_server.domain.role.converter;

import com.cozymate.cozymate_server.domain.mate.Mate;
import com.cozymate.cozymate_server.domain.role.Role;
import com.cozymate.cozymate_server.domain.role.dto.RoleResponseDto.RoleDetailResponseDto;
import com.cozymate.cozymate_server.domain.role.dto.RoleResponseDto.RoleListDetailResponseDto;
import com.cozymate.cozymate_server.domain.role.enums.DayListBitmask;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RoleConverter {

private static final int ALL_DAYS_BITMASK = 127;

public static Role toEntity(Mate mate, String content, int repeatDays) {
return Role.builder()
.mate(mate)
.content(content)
.repeatDays(repeatDays)
.build();
}

// Day List → Bitmask
public static int convertDayListToBitmask(List<DayListBitmask> dayList) {
int bitmask = 0;
for (DayListBitmask dayBitMask : dayList) {
bitmask |= dayBitMask.getValue();
}
return bitmask;
}

// Bitmask → Day List
public static List<DayListBitmask> convertBitmaskToDayList(int bitmask) {
List<DayListBitmask> dayList = new ArrayList<>();
for (DayListBitmask day : DayListBitmask.values()) {
if ((bitmask & day.getValue()) != 0) {
dayList.add(day);
}
}
return dayList;
}

public static RoleDetailResponseDto toRoleDetailResponseDto(Role role) {
return RoleDetailResponseDto.builder()
.id(role.getId())
.content(role.getContent())
.repeatDayList(
convertBitmaskToDayList(role.getRepeatDays()).stream()
.map(DayListBitmask::name)
.toList()
)
.isAllDays(role.getRepeatDays() == ALL_DAYS_BITMASK)
.build();
}

public static RoleListDetailResponseDto toRoleListDetailResponseDto(
List<RoleDetailResponseDto> myRoleList,
Map<String, List<RoleDetailResponseDto>> otherRoleList) {
return RoleListDetailResponseDto.builder()
.myRoleList(myRoleList)
.otherRoleList(otherRoleList)
.build();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.cozymate.cozymate_server.domain.role.dto;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.hibernate.validator.constraints.Length;

public class RoleRequestDto {

@AllArgsConstructor
@Getter
public static class CreateRoleRequestDto {

@NotEmpty
private List<Long> mateIdList;

@Length(min = 1, max = 20)
private String title;

@NotEmpty
@Size(min = 1, max = 7)
private List<String> repeatDayList;

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.cozymate.cozymate_server.domain.role.dto;

import com.cozymate.cozymate_server.domain.mate.Mate;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

public class RoleResponseDto {

@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public static class RoleDetailResponseDto {

private Long id;

private String content;

private List<String> repeatDayList;

private boolean isAllDays;

}

@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public static class RoleListDetailResponseDto {

private List<RoleDetailResponseDto> myRoleList;

private Map<String, List<RoleDetailResponseDto>> otherRoleList;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.cozymate.cozymate_server.domain.role.enums;

import java.util.List;

public enum DayListBitmask {
(1),
(2),
(4),
(8),
(16),
(32),
(64);

private int value;

DayListBitmask(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.cozymate.cozymate_server.domain.role.repository;

import com.cozymate.cozymate_server.domain.role.Role;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface RoleRepository extends JpaRepository<Role, Long> {

List<Role> findAllByMateRoomId(Long roomId);

void deleteByMateId(Long mateId);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.cozymate.cozymate_server.domain.role.service;

import com.cozymate.cozymate_server.domain.mate.Mate;
import com.cozymate.cozymate_server.domain.mate.repository.MateRepository;
import com.cozymate.cozymate_server.domain.member.Member;
import com.cozymate.cozymate_server.domain.role.Role;
import com.cozymate.cozymate_server.domain.role.converter.RoleConverter;
import com.cozymate.cozymate_server.domain.role.dto.RoleRequestDto.CreateRoleRequestDto;
import com.cozymate.cozymate_server.domain.role.enums.DayListBitmask;
import com.cozymate.cozymate_server.domain.role.repository.RoleRepository;
import com.cozymate.cozymate_server.global.response.code.status.ErrorStatus;
import com.cozymate.cozymate_server.global.response.exception.GeneralException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class RoleCommandService {

private final RoleRepository roleRepository;
private final MateRepository mateRepository;


@Transactional
public void createRole(
Member member,
Long roomId,
CreateRoleRequestDto requestDto
) {
// 해당 API를 호출한 사람
Mate mate = mateRepository.findByMemberIdAndRoomId(member.getId(), roomId)
.orElseThrow(() -> new GeneralException(ErrorStatus._MATE_OR_ROOM_NOT_FOUND));

List<DayListBitmask> repeatDayList = requestDto.getRepeatDayList().stream()
.map(DayListBitmask::valueOf).toList();
int repeatDayBitmast = RoleConverter.convertDayListToBitmask(repeatDayList);

// Role의 대상이 되는 사람
requestDto.getMateIdList().forEach(mateId -> {
Mate targerMate = mateRepository.findById(mateId) // TODO: mate를 한번에 가져오는 방식으로 변경해야함
.orElseThrow(() -> new GeneralException(ErrorStatus._MATE_NOT_FOUND));
Role role = RoleConverter.toEntity(targerMate, requestDto.getTitle(), repeatDayBitmast);
roleRepository.save(role);
});
}

public void deleteRole(Long roomId, Long roleId, Member member) {
Mate mate = mateRepository.findByMemberIdAndRoomId(member.getId(), roomId)
.orElseThrow(() -> new GeneralException(ErrorStatus._MATE_OR_ROOM_NOT_FOUND));

Role roleToDelete = roleRepository.findById(roleId)
.orElseThrow(() -> new GeneralException(ErrorStatus._ROLE_NOT_FOUND));

if (Boolean.FALSE.equals(
member.getId().equals(roleToDelete.getMate().getMember().getId())
)) {
throw new GeneralException(ErrorStatus._ROLE_MATE_MISMATCH);
}
roleRepository.delete(roleToDelete);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.cozymate.cozymate_server.domain.role.service;

import com.cozymate.cozymate_server.domain.mate.Mate;
import com.cozymate.cozymate_server.domain.mate.repository.MateRepository;
import com.cozymate.cozymate_server.domain.member.Member;
import com.cozymate.cozymate_server.domain.role.Role;
import com.cozymate.cozymate_server.domain.role.converter.RoleConverter;
import com.cozymate.cozymate_server.domain.role.dto.RoleResponseDto.RoleDetailResponseDto;
import com.cozymate.cozymate_server.domain.role.dto.RoleResponseDto.RoleListDetailResponseDto;
import com.cozymate.cozymate_server.domain.role.repository.RoleRepository;
import com.cozymate.cozymate_server.domain.rule.converter.RuleConverter;
import com.cozymate.cozymate_server.domain.rule.dto.RuleResponseDto.RuleDetailResponseDto;
import com.cozymate.cozymate_server.global.response.code.status.ErrorStatus;
import com.cozymate.cozymate_server.global.response.exception.GeneralException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class RoleQueryService {

private final RoleRepository roleRepository;
private final MateRepository mateRepository;

public RoleListDetailResponseDto getRole(Long roomId, Member member) {
Mate mate = mateRepository.findByMemberIdAndRoomId(member.getId(), roomId)
.orElseThrow(() -> new GeneralException(ErrorStatus._MATE_OR_ROOM_NOT_FOUND));

List<Role> roleList = roleRepository.findAllByMateRoomId(mate.getRoom().getId());
List<RoleDetailResponseDto> myRoleListResponseDto = new ArrayList<>();
Map<String, List<RoleDetailResponseDto>> mateRoleListResponseDto = new HashMap<>();

roleList.forEach(role -> {
if (role.getMate().getId().equals(mate.getId())) {
myRoleListResponseDto.add(RoleConverter.toRoleDetailResponseDto(role));
} else {
String mateName = role.getMate().getMember().getName();
RoleDetailResponseDto roleDto = RoleConverter.toRoleDetailResponseDto(role);
mateRoleListResponseDto.computeIfAbsent(mateName, k -> new ArrayList<>())
.add(roleDto);
}
});

return RoleConverter.toRoleListDetailResponseDto(
myRoleListResponseDto,
mateRoleListResponseDto);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import com.cozymate.cozymate_server.domain.post.repository.PostRepository;
import com.cozymate.cozymate_server.domain.postcomment.PostCommentRepository;
import com.cozymate.cozymate_server.domain.postimage.PostImageRepository;
import com.cozymate.cozymate_server.domain.role.RoleRepository;
import com.cozymate.cozymate_server.domain.role.repository.RoleRepository;
import com.cozymate.cozymate_server.domain.room.Room;
import com.cozymate.cozymate_server.domain.room.converter.RoomConverter;
import com.cozymate.cozymate_server.domain.room.dto.RoomCreateRequest;
Expand Down
Loading

0 comments on commit 8a09099

Please sign in to comment.