Skip to content

Commit

Permalink
Merge pull request #84 from PLADI-ALM/feat/PDS-63-getResources
Browse files Browse the repository at this point in the history
[PDS-63/feat] 관리자 자원 목록 조회 API
  • Loading branch information
sojungpp authored Oct 14, 2023
2 parents 6f66102 + 9575a10 commit 901b713
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static BookingRes toDto(ResourceBooking resourceBooking) {
return BookingRes.builder()
.id(resourceBooking.getResourceBookingId())
.name(resourceBooking.getResource().getName())
.detailInfo(resourceBooking.getResource().getCategory().getValue())
.detailInfo(resourceBooking.getResource().getResourceCategory().getName())
.startDateTime(DateTimeUtil.dateToString(resourceBooking.getStartDate()))
.endDateTime(DateTimeUtil.dateToString(resourceBooking.getEndDate()))
.status(resourceBooking.getStatus().getValue())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,16 @@ private static void checkRole(Role role, User user, User target) {
if (!user.equals(target)) throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
break;
case ADMIN:
if (!target.getRole().equals(Role.ADMIN)) throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
checkAdminRole(target);
break;
}
}

// 관리자 권환 확인
private static void checkAdminRole(User user) {
if (!user.checkRole(Role.ADMIN)) throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
}

// 자원 예약 반납 공통 메서드
private void returnBookingResource(ResourceBooking resourceBooking) {
// 사용중 아니라면 -> 사용중 상태에서만 반납이 가능함
Expand Down Expand Up @@ -203,12 +208,6 @@ public Page<AdminBookingRes> getBookingOffices(User user,Pageable pageable) {
return bookings.map(AdminBookingRes::toDto);
}

private void checkAdminRole(User user) {
if (user.getRole() != Role.ADMIN) {
throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
}
}

/**
* 관리자 회의실 예약 개별 조회
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,28 @@

import com.example.pladialmserver.global.resolver.Account;
import com.example.pladialmserver.global.response.ResponseCustom;
import com.example.pladialmserver.resource.dto.response.AdminResourcesRes;
import com.example.pladialmserver.resource.service.ResourceService;
import com.example.pladialmserver.user.entity.User;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "자원 관리자 API")
import java.util.List;

@Api(tags = "관리자 자원 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/resources")
Expand All @@ -28,11 +36,28 @@ public class ResourceAdminController {
*/
@Operation(summary = "자원 카테고리 (차유상)", description = "자원 카테고리를 가져온다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "(S0001)요청에 성공했습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
@ApiResponse(responseCode = "200", description = "(S0001)요청에 성공했습니다."),
@ApiResponse(responseCode = "403", description = "(G0002)접근권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
})
@GetMapping("/category")
public ResponseCustom getResourceCategory(@Account User user) {
return ResponseCustom.OK(resourceService.getResourceCategory(user));
}

/**
* 관리자 자원 목록 조회
*/
@Operation(summary = "관리자 자원 목록 조회 (박소정)", description = "관리자가 자원 목록을 조회 및 검색한다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "(S0001)요청에 성공했습니다."),
@ApiResponse(responseCode = "403", description = "(G0002)접근권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
})
@GetMapping("")
public ResponseCustom<Page<AdminResourcesRes>> getResources(
@Account User user,
@Parameter(description = "(String) 이름 검색어", example = "'MacBook'") @RequestParam(required = false) String keyword,
@PageableDefault(size = 8) Pageable pageable) {
return ResponseCustom.OK(resourceService.getResourcesByAdmin(user, keyword, pageable));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,13 @@ public ResponseCustom<List<String>> getResourceBookedDate(
*/
@Operation(summary = "자원 예약 (박소정)", description = "자원을 예약한다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "(S0001)요청에 성공했습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
@ApiResponse(responseCode = "200", description = "(S0001)요청에 성공했습니다."),
@ApiResponse(responseCode = "400", description = "(B0010)날짜를 모두 입력해주세요. (B0002) 요청사항은 30자 이하로 작성해주세요. (B0003)시작시간보다 끝나는 시간이 더 앞에 있습니다. (B0004)미래의 날짜를 선택해주세요.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
@ApiResponse(responseCode = "404", description = "(R0003)존재하지 않는 자원입니다. (U0001)사용자를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))),
@ApiResponse(responseCode = "409", description = "(B0005)이미 예약되어 있는 시간입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class)))})
@PostMapping("/{resourceId}")
public ResponseCustom bookResource(
@Account User user,
@Parameter(description = "(Long) 자원 Id", example = "1") @PathVariable(name = "resourceId") Long resourceId,
@RequestBody @Valid ResourceReq resourceReq) {

Expand All @@ -114,10 +115,8 @@ public ResponseCustom bookResource(
// 종료일이 시작일 보다 빠른 경우
if (resourceReq.getEndDate().isBefore(resourceReq.getStartDate()))
throw new BaseException(BaseResponseCode.START_TIME_MUST_BE_IN_FRONT);
// TODO 유저 ID 받아오는 로직 추가
Long userId = 1L;

resourceService.bookResource(userId, resourceId, resourceReq);
resourceService.bookResource(user, resourceId, resourceReq);
return ResponseCustom.OK();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class AdminResourceCategoryRes {

public static AdminResourceCategoryRes toDto(List<ResourceCategory> resourceCategories) {
return AdminResourceCategoryRes.builder()
.category(resourceCategories.stream().map(resourceCategory -> resourceCategory.getName()).collect(Collectors.toList()))
.category(resourceCategories.stream().map(ResourceCategory::getName).collect(Collectors.toList()))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static AdminResourceRes toDto(ResourceBooking resourceBooking){
return AdminResourceRes.builder()
.id(resourceBooking.getResourceBookingId())
.name(resourceBooking.getResource().getName())
.category(resourceBooking.getResource().getCategory().getValue())
.category(resourceBooking.getResource().getResourceCategory().getName())
.startDateTime(DateTimeUtil.dateToString(resourceBooking.getStartDate()))
.endDateTime(DateTimeUtil.dateToString(resourceBooking.getEndDate()))
.requester(resourceBooking.getUser().getName())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.pladialmserver.resource.dto.response;

import com.example.pladialmserver.resource.entity.Resource;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class AdminResourcesRes {
@Schema(type = "Long", description = "자원 Id", example = "1")
private Long resourceId;

@Schema(type = "String", description = "자원명", example = "MacBook Pro")
private String name;

@Schema(type = "String", description = "자원 카테고리", example = "전자기기")
private String category;

@Schema(type = "String", description = "자원 설명", example = "맥북프로사줘")
private String description;

public static AdminResourcesRes toDto(Resource resource) {
return AdminResourcesRes.builder()
.resourceId(resource.getResourceId())
.name(resource.getName())
.category(resource.getResourceCategory().getName())
.description(resource.getDescription())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class ResourceDetailRes {
public static ResourceDetailRes toDto(Resource resource) {
return ResourceDetailRes.builder()
.name(resource.getName())
.category(resource.getCategory().getValue())
.category(resource.getResourceCategory().getName())
.description(resource.getDescription())
.imgUrl(AwsS3ImageUrlUtil.toUrl(resource.getImgUrl()))
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public static ResourceRes toDto(Resource resource){
.resourceId(resource.getResourceId())
.imgUrl(AwsS3ImageUrlUtil.toUrl(resource.getImgUrl()))
.name(resource.getName())
.category(resource.getCategory().getValue())
.category(resource.getResourceCategory().getName())
.description(resource.getDescription())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.example.pladialmserver.resource.entity;

import com.example.pladialmserver.equipment.entity.Category;
import com.example.pladialmserver.global.entity.BaseEntity;
import lombok.AccessLevel;
import lombok.Getter;
Expand All @@ -25,9 +24,9 @@ public class Resource extends BaseEntity {
@Size(max = 50)
private String name;

@NotNull
@Enumerated(EnumType.STRING)
private Category category;
@ManyToOne
@JoinColumn(nullable = false, name = "resource_category_id")
private ResourceCategory resourceCategory;

@NotNull
@Size(max = 255)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ public interface ResourceRepository extends JpaRepository<Resource, Long> {
Page<Resource> findAllByResourceIdNotIn(List<Long> resourceIds, Pageable pageable);

Page<Resource> findByNameContaining(String resourceName,Pageable pageable);
Page<Resource> findByNameContainingOrderByName(String resourceName,Pageable pageable);

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import com.example.pladialmserver.global.utils.DateTimeUtil;
import com.example.pladialmserver.resource.dto.request.ResourceReq;
import com.example.pladialmserver.resource.dto.response.AdminResourceCategoryRes;
import com.example.pladialmserver.resource.dto.response.AdminResourceRes;
import com.example.pladialmserver.resource.dto.response.AdminResourcesRes;
import com.example.pladialmserver.resource.dto.response.ResourceDetailRes;
import com.example.pladialmserver.resource.dto.response.ResourceRes;
import com.example.pladialmserver.resource.entity.Resource;
Expand All @@ -31,16 +31,14 @@
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class ResourceService {
private final UserRepository userRepository;
private final ResourceRepository resourceRepository;
private final ResourceBookingRepository resourceBookingRepository;
private final ResourceCategoryRepository resourceCategoryRepository;


// 관리자 권한 확인
private void checkAdminRole(User user) {
if (user.getRole() != Role.ADMIN) {
throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
}
if(!user.checkRole(Role.ADMIN)) throw new BaseException(BaseResponseCode.NO_AUTHENTICATION);
}


Expand Down Expand Up @@ -96,9 +94,7 @@ public List<String> getResourceBookedDate(Long resourceId, String month) {
* 자원 예약
*/
@Transactional
public void bookResource(Long userId, Long resourceId, ResourceReq resourceReq) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new BaseException(BaseResponseCode.USER_NOT_FOUND));
public void bookResource(User user, Long resourceId, ResourceReq resourceReq) {
Resource resource = resourceRepository.findById(resourceId)
.orElseThrow(() -> new BaseException(BaseResponseCode.RESOURCE_NOT_FOUND));

Expand All @@ -108,17 +104,30 @@ public void bookResource(Long userId, Long resourceId, ResourceReq resourceReq)

}

// ===================================================================================================================
// [관리자]
// ===================================================================================================================

/**
* 자원 카테고리
*/
public AdminResourceCategoryRes getResourceCategory(User user) {
//관리자인지 확인
// 관리자 권한 확인
checkAdminRole(user);

List<ResourceCategory> resourceCategories = resourceCategoryRepository.findAll();
return AdminResourceCategoryRes.toDto(resourceCategories);

}


/**
* 관리자 자원 목록 조회
*/
public Page<AdminResourcesRes> getResourcesByAdmin(User user, String keyword, Pageable pageable) {
// 관리자 권한 확인
checkAdminRole(user);
// 자원 조회
Page<Resource> resources = resourceRepository.findByNameContainingOrderByName(keyword, pageable);
return resources.map(AdminResourcesRes::toDto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,8 @@ public static User toEntity(CreateUserReq req, Department department, Position p
.role(Role.getRoleByName(req.getRole()))
.build();
}

public boolean checkRole(Role role) {
return this.role == role;
}
}

0 comments on commit 901b713

Please sign in to comment.