Skip to content
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
Expand Up @@ -2,6 +2,9 @@

import com.restless.ticketing.application.dto.TicketSeatInfo;
import com.restless.ticketing.application.TicketSeatQueryService;
import com.restless.ticketing.application.TicketReservationQueryService;
import com.restless.ticketing.application.dto.TicketBookingAvailability;
import com.restless.auth.LoginMember;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -16,6 +19,12 @@
public class TicketSeatController {

private final TicketSeatQueryService ticketSeatQueryService;
private final TicketReservationQueryService reservationQueries;

@GetMapping("/{performanceId}/booking-availability")
public TicketBookingAvailability availability(@LoginMember Long userId, @PathVariable Long performanceId) {
return reservationQueries.getAvailability(userId, performanceId);
}

@GetMapping("/{performanceId}/seats")
public List<TicketSeatInfo> getSeats(@PathVariable("performanceId") Long performanceId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import com.restless.ticketing.domain.TicketReservationStatus;
import com.restless.ticketing.infrastructure.SeatHoldRepository;
import com.restless.ticketing.infrastructure.TicketReservationRepository;
import com.restless.ticketing.infrastructure.TicketPurchaseLimitRepository;
import com.restless.concert.application.ConcertQueryService;
import com.restless.ticketing.application.dto.TicketBookingAvailability;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
Expand All @@ -32,6 +35,20 @@ public class TicketReservationQueryService {
private final TicketReservationRepository ticketReservationRepository;
private final SeatHoldRepository seatHoldRepository;
private final JdbcTemplate jdbc;
private final TicketPurchaseLimitRepository purchaseLimits;
private final ConcertQueryService concerts;

public TicketBookingAvailability getAvailability(Long userId, Long performanceId) {
validateUser(userId);
if (performanceId == null || performanceId <= 0) throw new BusinessException(ErrorCode.INVALID_REQUEST);
int maximum = concerts.getBookingPerformance(performanceId).maxTicketsPerUser();
var limit = purchaseLimits.findFirstByUserIdAndPerformanceId(userId, performanceId);
int confirmed = limit.map(com.restless.ticketing.domain.TicketPurchaseLimit::getConfirmedCount).orElse(0);
int reserved = limit.map(com.restless.ticketing.domain.TicketPurchaseLimit::getReservedCount).orElse(0);
var active = getActive(userId).stream().filter(r -> r.performanceId().equals(performanceId)).findFirst().orElse(null);
return new TicketBookingAvailability(maximum, confirmed, reserved,
Math.max(0, maximum - confirmed - reserved), active);
}

public TicketReservationDetail getDetail(Long userId, Long reservationId) {
validateUser(userId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.restless.ticketing.application.dto;

/** 조회 시점의 한도와 활성 예약. 선점 시에는 서버가 다시 검증한다. */
public record TicketBookingAvailability(int maximum, int confirmed, int reserved, int remaining,
TicketReservationDetail activeReservation) { }
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface TicketPurchaseLimitRepository extends JpaRepository<TicketPurch

@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<TicketPurchaseLimit> findByUserIdAndPerformanceId(Long userId, Long performanceId);

Optional<TicketPurchaseLimit> findFirstByUserIdAndPerformanceId(Long userId, Long performanceId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,30 @@ void expiredReservationReleasesAllSeatsWithoutRecreationOrReleasingNewOwner() {
assertStoredReservation(next, 1);
}

@Test
@DisplayName("회차별 구매 한도는 본인 확정·선점 수량과 활성 예약을 조회한다")
void bookingAvailabilityShowsOwnCountsAndActiveReservation() throws Exception {
String path = "/api/performances/{id}/booking-availability";
mockMvc.perform(get(path, fixture.performanceId())).andExpect(status().isUnauthorized());
mockMvc.perform(get(path, fixture.performanceId()).with(jwt().jwt(t -> t.subject(fixture.firstUserId().toString()))))
.andExpect(status().isOk()).andExpect(jsonPath("$.maximum").value(3))
.andExpect(jsonPath("$.remaining").value(3)).andExpect(jsonPath("$.activeReservation").doesNotExist());
jdbc.update("INSERT INTO ticket_purchase_limits (user_id, performance_id, reserved_count, confirmed_count) VALUES (?, ?, 0, 2)", fixture.firstUserId(), fixture.performanceId());
mockMvc.perform(get(path, fixture.performanceId()).with(jwt().jwt(t -> t.subject(fixture.firstUserId().toString()))))
.andExpect(status().isOk()).andExpect(jsonPath("$.confirmed").value(2))
.andExpect(jsonPath("$.remaining").value(1)).andExpect(jsonPath("$.activeReservation").doesNotExist());
TicketReservationInfo own = reserve(fixture.firstUserId(), "availability", List.of(seat(0)));
mockMvc.perform(get(path, fixture.performanceId()).with(jwt().jwt(t -> t.subject(fixture.firstUserId().toString()))))
.andExpect(status().isOk()).andExpect(jsonPath("$.confirmed").value(2))
.andExpect(jsonPath("$.reserved").value(1)).andExpect(jsonPath("$.remaining").value(0))
.andExpect(jsonPath("$.activeReservation.reservationId").value(own.reservationId()));
mockMvc.perform(get(path, fixture.performanceId()).with(jwt().jwt(t -> t.subject(fixture.secondUserId().toString()))))
.andExpect(status().isOk()).andExpect(jsonPath("$.remaining").value(3))
.andExpect(jsonPath("$.activeReservation").doesNotExist());
mockMvc.perform(get(path, Long.MAX_VALUE).with(jwt().jwt(t -> t.subject(fixture.firstUserId().toString()))))
.andExpect(status().isNotFound());
}

@ParameterizedTest(name = "{displayName} [{0}]")
@EnumSource(value = TicketReservationStatus.class, names = {"HELD", "PAYMENT_PENDING", "RECONCILING"})
@DisplayName("기한 전 HELD와 결제 진행·결과 확인 중 예약은 최초 선점 기한만으로 반환하지 않는다")
Expand Down
6 changes: 6 additions & 0 deletions docs/contracts/api/ticketing.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ Long으로 변환할 수 없는 performanceId는 `400 INVALID_REQUEST`로 응답

## 좌석 선점

### 본인 회차별 구매 한도 조회

`GET /api/performances/{performanceId}/booking-availability`는 로그인 회원의 해당 회차 구매 현황을 반환한다. `maximum`은 회차당 한도, `confirmed`는 확정 수량, `reserved`는 선점 수량, `remaining`은 `max(0, maximum - confirmed - reserved)`이다. `activeReservation`은 해당 회차의 HELD·PAYMENT_PENDING·RECONCILING 본인 예약 상세 또는 null이다. 예약이 없는 최초 사용자도 수량 0으로 조회하며, 타인의 수량은 공개하지 않는다. 회차가 없으면 404, 비로그인은 401이다.

조회 결과는 조회 시점의 안내이며 좌석을 확보하지 않는다. 다른 요청이 수량을 변경할 수 있으므로 실제 선점 시 서버는 기존 구매 관리 행 잠금 아래 한도와 활성 예약을 다시 확인한다. HELD는 기존 checkout 또는 취소로 이어가며, PAYMENT_PENDING·RECONCILING은 결제 확인으로 안내한다. 결제 진행 후에는 선점 취소 API를 사용할 수 없다.

로그인 필수다. 회원 ID는 본문에서 받지 않고 `@LoginMember`로 인증된 토큰에서 추출한다.
`performanceId`와 `seatIds`는 양수여야 하며 좌석 목록은 비어 있거나 중복될 수 없다.
`seatIds`는 물리 좌석 ID가 아닌 조회 응답의 판매 좌석 `seatId`다.
Expand Down
Loading