Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 멤버 도메인 연동 #187

Merged
merged 2 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package com.pgms.apibooking.common.exception;

import com.pgms.coredomain.domain.common.BookingErrorCode;
import com.pgms.coredomain.domain.common.BaseErrorCode;

import lombok.Getter;

@Getter
public class BookingException extends RuntimeException {

private final BookingErrorCode errorCode;
private final BaseErrorCode errorCode;

public BookingException(BookingErrorCode errorCode) {
public BookingException(BaseErrorCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ public class BookingExceptionHandler extends ResponseEntityExceptionHandler {
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
HttpStatusCode statusCode, WebRequest request) {
if (ex instanceof BindException) {
BookingErrorCode errorCode = BookingErrorCode.INVALID_INPUT_VALUE;
ErrorResponse response = new ErrorResponse(errorCode.getCode(), errorCode.getMessage());
ErrorResponse response = BookingErrorCode.INVALID_INPUT_VALUE.getErrorResponse();

((BindException)ex).getBindingResult().getAllErrors().forEach(e -> {
String fieldName = ((FieldError)e).getField();
Expand All @@ -42,16 +41,14 @@ protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object bo

log.error(ex.getMessage(), ex);

BookingErrorCode errorCode = BookingErrorCode.INTERNAL_SERVER_ERROR;
ErrorResponse response = new ErrorResponse(errorCode.getCode(), errorCode.getMessage());
ErrorResponse response = BookingErrorCode.INTERNAL_SERVER_ERROR.getErrorResponse();
return ResponseEntity.internalServerError().body(response);
}

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
BookingErrorCode errorCode = BookingErrorCode.INVALID_INPUT_VALUE;
ErrorResponse response = new ErrorResponse(errorCode.getCode(), errorCode.getMessage());
ErrorResponse response = BookingErrorCode.INVALID_INPUT_VALUE.getErrorResponse();
return ResponseEntity.badRequest().body(response);
}

Expand All @@ -61,13 +58,13 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotV
BindingResult bindingResult = ex.getBindingResult();
String errorMessage = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
log.warn("Validation Failed: {}", errorMessage);
ErrorResponse response = new ErrorResponse(BookingErrorCode.INVALID_INPUT_VALUE.getCode(), errorMessage);
ErrorResponse response = BookingErrorCode.INVALID_INPUT_VALUE.getErrorResponse();
return ResponseEntity.status(status).body(response);
}

@ExceptionHandler(BookingException.class)
protected ResponseEntity<ErrorResponse> handleBookingException(BookingException ex) {
ErrorResponse response = new ErrorResponse(ex.getErrorCode().getCode(), ex.getErrorCode().getMessage());
ErrorResponse response = ex.getErrorCode().getErrorResponse();
log.warn("Booking Exception Occurred : {}", response.getErrorMessage());
return ResponseEntity.status(ex.getErrorCode().getStatus()).body(response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public class BookingController {
public ResponseEntity<ApiResponse<BookingCreateResponse>> createBooking(
//@CurrentAccount Long memberId,
@RequestBody @Valid BookingCreateRequest request,
HttpServletRequest httpRequest) {
HttpServletRequest httpRequest
) {
BookingCreateResponse createdBooking = bookingService.createBooking(request, 1L); //TODO: 인증된 memberId 지정
ApiResponse<BookingCreateResponse> response = ApiResponse.ok(createdBooking);
URI location = UriComponentsBuilder
Expand All @@ -53,7 +54,8 @@ public ResponseEntity<ApiResponse<BookingCreateResponse>> createBooking(
public ResponseEntity<Void> cancelBooking(
//@CurrentAccount Long memberId,
@PathVariable String id,
@RequestBody @Valid BookingCancelRequest request) {
@RequestBody @Valid BookingCancelRequest request
) {
bookingService.cancelBooking(id, request, 1L); //TODO: 인증된 memberId 지정
return ResponseEntity.ok().build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.pgms.apibooking.domain.booking.service;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

import org.springframework.data.domain.PageRequest;
Expand All @@ -13,9 +12,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pgms.coredomain.domain.common.BookingErrorCode;
import com.pgms.apibooking.common.exception.BookingException;
import com.pgms.coresecurity.security.jwt.booking.BookingAuthToken;
import com.pgms.apibooking.config.TossPaymentConfig;
import com.pgms.apibooking.domain.booking.dto.request.BookingCancelRequest;
import com.pgms.apibooking.domain.booking.dto.request.BookingCreateRequest;
Expand All @@ -39,13 +36,16 @@
import com.pgms.coredomain.domain.booking.Ticket;
import com.pgms.coredomain.domain.booking.repository.BookingRepository;
import com.pgms.coredomain.domain.booking.repository.TicketRepository;
import com.pgms.coredomain.domain.common.BookingErrorCode;
import com.pgms.coredomain.domain.common.MemberErrorCode;
import com.pgms.coredomain.domain.event.EventSeat;
import com.pgms.coredomain.domain.event.EventSeatStatus;
import com.pgms.coredomain.domain.event.EventTime;
import com.pgms.coredomain.domain.event.repository.EventSeatRepository;
import com.pgms.coredomain.domain.event.repository.EventTimeRepository;
import com.pgms.coredomain.domain.member.Member;
import com.pgms.coredomain.domain.member.repository.MemberRepository;
import com.pgms.coresecurity.security.jwt.booking.BookingAuthToken;

import lombok.RequiredArgsConstructor;

Expand Down Expand Up @@ -138,10 +138,8 @@ public PageResponse<BookingsGetResponse> getBookings(
BookingSearchCondition searchCondition,
Long memberId
) {
Member member = getMemberById(memberId);

Pageable pageable = PageRequest.of(pageCondition.getPage() - 1, pageCondition.getSize());
searchCondition.updateMemberId(member.getId());
searchCondition.updateMemberId(memberId);

List<BookingsGetResponse> bookings = bookingQuerydslRepository.findAll(searchCondition, pageable)
.stream()
Expand All @@ -155,12 +153,10 @@ public PageResponse<BookingsGetResponse> getBookings(

@Transactional(readOnly = true)
public BookingGetResponse getBooking(String id, Long memberId) {
Member member = getMemberById(memberId);

Booking booking = bookingRepository.findBookingInfoById(id)
.orElseThrow(() -> new BookingException(BookingErrorCode.BOOKING_NOT_FOUND));

if (!booking.isSameBooker(member.getId())) {
if (!booking.isSameBooker(memberId)) {
throw new BookingException(BookingErrorCode.FORBIDDEN);
}

Expand Down Expand Up @@ -213,9 +209,8 @@ private void validateRefundReceiveAccount(PaymentMethod paymentMethod,
}

private Member getMemberById(Long memberId) {
System.out.println("member id get " + memberId);
return memberRepository.findById(memberId)
.orElseThrow(() -> new NoSuchElementException("Member not found"));
.orElseThrow(() -> new BookingException(MemberErrorCode.MEMBER_NOT_FOUND));
}

private String getCurrentSessionId() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.pgms.apibooking.domain.seat.dto.response.AreaResponse;
import com.pgms.apibooking.domain.seat.service.SeatService;
import com.pgms.coredomain.response.ApiResponse;
import com.pgms.coresecurity.security.resolver.CurrentAccount;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand All @@ -32,14 +33,14 @@ public ResponseEntity<ApiResponse<List<AreaResponse>>> getSeats(@ModelAttribute
}

@PostMapping("/{seatId}/select")
public ResponseEntity<Void> selectSeat(@PathVariable Long seatId) {
seatService.selectSeat(seatId);
public ResponseEntity<Void> selectSeat(@PathVariable Long seatId, @CurrentAccount Long memberId) {
seatService.selectSeat(seatId, memberId);
return ResponseEntity.ok().build();
}

@PostMapping("/{seatId}/deselect")
public ResponseEntity<Void> deselectSeat(@PathVariable Long seatId) {
seatService.deselectSeat(seatId);
public ResponseEntity<Void> deselectSeat(@PathVariable Long seatId, @CurrentAccount Long memberId) {
seatService.deselectSeat(seatId, memberId);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.pgms.apibooking.domain.seat.service;

import java.time.Duration;
import java.util.Optional;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
Expand All @@ -17,6 +18,15 @@ class SeatLockService { //TODO: 레디스 레포지토리 분리

private final RedisTemplate<String, String> redisTemplate;

Optional<Long> getSelectorId(Long seatId) {
String key = generateSeatLockKey(seatId);
String value = redisTemplate.opsForValue().get(key);
if (value == null) {
return Optional.empty();
}
return Optional.of(extractMemberId(value));
}

boolean isSeatLocked(Long seatId) {
return redisTemplate.opsForValue().get(generateSeatLockKey(seatId)) != null;
}
Expand All @@ -39,4 +49,8 @@ private String generateSeatLockKey(Long seatId) {
private String generateSeatLockValue(Long memberId) {
return SEAT_LOCK_CACHE_VALUE_PREFIX + memberId;
}

private Long extractMemberId(String value) {
return Long.parseLong(value.replace(SEAT_LOCK_CACHE_VALUE_PREFIX, ""));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -37,9 +38,7 @@ public List<AreaResponse> getSeats(SeatsGetRequest request) {
.toList();
}

public void selectSeat(Long seatId) {
Long memberId = 0L; //TODO: 인증된 memberId 지정

public void selectSeat(Long seatId, Long memberId) {
if (seatLockService.isSeatLocked(seatId)) {
throw new BookingException(BookingErrorCode.SEAT_BEING_BOOKED);
}
Expand All @@ -54,19 +53,29 @@ public void selectSeat(Long seatId) {
seatLockService.lockSeat(seatId, memberId);
}

public void deselectSeat(Long seatId) {
Long memberId = 0L; //TODO: 인증된 memberId 지정

//TODO: lock 걸어둔 멤버에게 요청이 들어왔는지 검증 후, 아래 로직을 수행한다
public void deselectSeat(Long seatId, Long memberId) {
Optional<Long> selectorIdOpt = seatLockService.getSelectorId(seatId);

EventSeat seat = getSeat(seatId);
if(selectorIdOpt.isEmpty()) {
updateSeatStatusToAvailable(seatId);
throw new BookingException(BookingErrorCode.SEAT_SELECTION_EXPIRED);
}

if (!selectorIdOpt.get().equals(memberId)) {
throw new BookingException(BookingErrorCode.SEAT_SELECTED_BY_ANOTHER_MEMBER);
}

seat.updateStatus(EventSeatStatus.AVAILABLE);
updateSeatStatusToAvailable(seatId);
seatLockService.unlockSeat(seatId);
}

private EventSeat getSeat(Long seatId) {
return eventSeatRepository.findById(seatId)
.orElseThrow(() -> new BookingException(BookingErrorCode.SEAT_NOT_FOUND));
}

private void updateSeatStatusToAvailable(Long seatId) {
EventSeat seat = getSeat(seatId);
seat.updateStatus(EventSeatStatus.AVAILABLE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public enum BookingErrorCode implements BaseErrorCode{
SEAT_NOT_FOUND(HttpStatus.BAD_REQUEST, "SEAT_NOT_FOUND", "존재하지 않는 좌석입니다."),
SEAT_BEING_BOOKED(HttpStatus.BAD_REQUEST, "SEAT_BEING_BOOKED", "예매중인 좌석입니다."),
SEAT_ALREADY_BOOKED(HttpStatus.BAD_REQUEST, "SEAT_ALREADY_BOOKED", "예매된 좌석입니다."),
SEAT_SELECTED_BY_ANOTHER_MEMBER(HttpStatus.BAD_REQUEST, "SEAT_SELECTED_BY_ANOTHER_MEMBER", "다른 회원이 선택한 좌석입니다."),
SEAT_SELECTION_EXPIRED(HttpStatus.BAD_REQUEST, "SEAT_SELECTION_EXPIRED", "좌석 선택 시간이 만료되었습니다."),

TIME_NOT_FOUND(HttpStatus.BAD_REQUEST, "TIME_NOT_FOUND", "존재하지 않는 공연 회차입니다."),
UNBOOKABLE_EVENT(HttpStatus.BAD_REQUEST, "UNBOOKABLE_EVENT", "현재 예매가 불가능한 공연입니다."),
Expand Down