Compare commits
13 Commits
feature/pa
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ee6a30ded | ||
|
|
d3d8403a4b | ||
|
|
657c9e7f7d | ||
|
|
c5b779fda7 | ||
|
|
b7057cfc73 | ||
|
|
42a00d20d0 | ||
|
|
b3842d93b4 | ||
|
|
58bed5565f | ||
|
|
28874b1b1c | ||
|
|
656e5e25e8 | ||
|
|
f1382597de | ||
|
|
a2cfd7ab15 | ||
|
|
61f6636653 |
@@ -91,7 +91,7 @@ erDiagram
|
||||
bigint seat_id FK "좌석 ID"
|
||||
bigint movie_time_id FK "상영시간표 ID"
|
||||
bigint payment_id "결제 ID"
|
||||
varchar status "상태 - 구매가능/예약진행중/판매완료"
|
||||
varchar status "상태 - 판매가능/예약/"
|
||||
int ticket_price "가격"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
@@ -101,10 +101,11 @@ erDiagram
|
||||
PAYMENT {
|
||||
bigint id PK "결제 ID"
|
||||
bigint user_alternate_id "유저 대체ID"
|
||||
varchar tid "카카오페이 결제고유번호"
|
||||
varchar movie_title "영화제목"
|
||||
varchar type "결제 타입 - 예) 네이버페이, 카카오페이"
|
||||
varchar status "상태 - 완료/환불/실패"
|
||||
varchar failed_message "실패사유 - 컬럼명을 알아보기 쉬운가?"
|
||||
varchar status "상태 - 완료/환불"
|
||||
varchar failed_message "실패사유"
|
||||
varchar payment_number "예매번호"
|
||||
int total_price "결제 금액"
|
||||
datetime deleted_at "삭제일시"
|
||||
|
||||
1
server/.gitignore
vendored
1
server/.gitignore
vendored
@@ -6,6 +6,7 @@
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
HELP.md
|
||||
bin/**
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
|
||||
12
server/Dockerfile
Normal file
12
server/Dockerfile
Normal file
@@ -0,0 +1,12 @@
|
||||
FROM openjdk:11-jre-slim
|
||||
|
||||
ENV APP_HOME=/usr/app/
|
||||
|
||||
WORKDIR $APP_HOME
|
||||
|
||||
COPY build/libs/server-0.0.1-SNAPSHOT.jar application.jar
|
||||
|
||||
EXPOSE 8443
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["java", "-jar", "application.jar"]
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import org.springframework.security.test.context.support.WithSecurityContext;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@WithSecurityContext(factory = WithAuthUserSecurityContextFactory.class)
|
||||
public @interface WithAuthUser {
|
||||
|
||||
String email();
|
||||
|
||||
String role();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.test.context.support.WithSecurityContextFactory;
|
||||
|
||||
public class WithAuthUserSecurityContextFactory implements WithSecurityContextFactory<WithAuthUser> {
|
||||
|
||||
@Override
|
||||
public SecurityContext createSecurityContext(WithAuthUser annotation) {
|
||||
String email = annotation.email();
|
||||
String role = annotation.role();
|
||||
List<SimpleGrantedAuthority> authorities = List.of(new SimpleGrantedAuthority(role));
|
||||
|
||||
User authUser = new User(email, "", authorities);
|
||||
UsernamePasswordAuthenticationToken token =
|
||||
new UsernamePasswordAuthenticationToken(authUser, "", authorities);
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
context.setAuthentication(token);
|
||||
return context;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ticketing.server.movie.aop;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class TicketLockAspectTest {
|
||||
|
||||
@Autowired
|
||||
private TicketLockAspect ticketLockAspect;
|
||||
|
||||
@Test
|
||||
@DisplayName("티켓 lock 동시성 체크")
|
||||
@SuppressWarnings({"java:S5960"})
|
||||
void ticketMultiThread() throws InterruptedException {
|
||||
// given
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch latch = new CountDownLatch(2);
|
||||
|
||||
List<String> lockIds = List.of("TicketLock:1", "TicketLock:2", "TicketLock:3");
|
||||
AtomicBoolean result1 = new AtomicBoolean(Boolean.TRUE);
|
||||
AtomicBoolean result2 = new AtomicBoolean(Boolean.TRUE);
|
||||
|
||||
// when
|
||||
executorService.execute(() -> {
|
||||
result1.set(ticketLockAspect.isEveryTicketIdLock(lockIds));
|
||||
latch.countDown();
|
||||
});
|
||||
|
||||
executorService.execute(() -> {
|
||||
result2.set(ticketLockAspect.isEveryTicketIdLock(List.of("TicketLock:1")));
|
||||
latch.countDown();
|
||||
});
|
||||
|
||||
latch.await();
|
||||
|
||||
// then
|
||||
Long unlockCount = ticketLockAspect.ticketIdsUnlock(lockIds);
|
||||
|
||||
assertAll(
|
||||
() -> assertThat(result1).isNotEqualTo(result2),
|
||||
() -> assertThat(unlockCount > 0).isTrue()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
@@ -9,8 +11,11 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.user.application.request.LoginRequest;
|
||||
import com.ticketing.server.user.application.request.RefreshRequest;
|
||||
import com.ticketing.server.user.application.request.SignUpRequest;
|
||||
import com.ticketing.server.user.application.response.TokenResponse;
|
||||
import com.ticketing.server.user.service.interfaces.UserService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
@@ -30,8 +35,12 @@ import org.springframework.web.context.WebApplicationContext;
|
||||
class AuthControllerTest {
|
||||
|
||||
private static final String LOGIN_URL = "/api/auth/token";
|
||||
private static final String REFRESH_URL = "/api/auth/refresh";
|
||||
private static final String LOGOUT_URL = "/api/auth/logout";
|
||||
private static final String REGISTER_URL = "/api/users";
|
||||
|
||||
private static final String USER_EMAIL = "ticketing@gmail.com";
|
||||
private static final String USER_PW = "qwe123";
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext context;
|
||||
@@ -54,7 +63,7 @@ class AuthControllerTest {
|
||||
@DisplayName("로그인 인증 성공")
|
||||
void loginSuccess() throws Exception {
|
||||
// given
|
||||
LoginRequest request = new LoginRequest(USER_EMAIL, "qwe123");
|
||||
LoginRequest request = new LoginRequest(USER_EMAIL, USER_PW);
|
||||
|
||||
// when
|
||||
ResultActions actions = mvc.perform(post(LOGIN_URL)
|
||||
@@ -82,6 +91,69 @@ class AuthControllerTest {
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("리프레쉬 토큰 발급 성공")
|
||||
void refreshTokenSuccess() throws Exception {
|
||||
// given
|
||||
LoginRequest loginRequest = new LoginRequest(USER_EMAIL, USER_PW);
|
||||
|
||||
// when
|
||||
// 로그인
|
||||
String loginResponseBody = mvc.perform(post(LOGIN_URL)
|
||||
.content(asJsonString(loginRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
TokenResponse loginResponse = objectMapper.readValue(loginResponseBody, TokenResponse.class);
|
||||
RefreshRequest refreshRequest = new RefreshRequest(loginResponse.getRefreshToken());
|
||||
|
||||
// 토큰재발급
|
||||
String refreshResponseBody = mvc.perform(post(REFRESH_URL)
|
||||
.content(asJsonString(refreshRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
TokenResponse refreshBody = objectMapper.readValue(refreshResponseBody, TokenResponse.class);
|
||||
|
||||
// then
|
||||
assertAll(
|
||||
() -> assertThat(refreshBody.getAccessToken()).isNotEmpty(),
|
||||
() -> assertThat(refreshBody.getRefreshToken()).isNotEmpty(),
|
||||
() -> assertThat(loginResponse.getTokenType()).isEqualTo(refreshBody.getTokenType()),
|
||||
() -> assertThat(loginResponse.getExpiresIn()).isEqualTo(refreshBody.getExpiresIn())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("로그아웃 성공")
|
||||
void logoutSuccess() throws Exception {
|
||||
// given
|
||||
LoginRequest loginRequest = new LoginRequest(USER_EMAIL, USER_PW);
|
||||
|
||||
// 로그인
|
||||
String loginResponseBody = mvc.perform(post(LOGIN_URL)
|
||||
.content(asJsonString(loginRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
TokenResponse loginResponse = objectMapper.readValue(loginResponseBody, TokenResponse.class);
|
||||
String authorization = loginResponse.getTokenType() + " " + loginResponse.getAccessToken();
|
||||
|
||||
// 로그아웃
|
||||
ResultActions actions = mvc.perform(post(LOGOUT_URL)
|
||||
.header("Authorization", authorization));
|
||||
|
||||
// then
|
||||
actions.andDo(print())
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
mvc = MockMvcBuilders
|
||||
@@ -89,7 +161,7 @@ class AuthControllerTest {
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
|
||||
SignUpRequest signUpRequest = new SignUpRequest("ticketing", USER_EMAIL, "qwe123", "010-1234-5678");
|
||||
SignUpRequest signUpRequest = new SignUpRequest("ticketing", USER_EMAIL, USER_PW, "010-1234-5678");
|
||||
|
||||
mvc.perform(post(REGISTER_URL)
|
||||
.content(asJsonString(signUpRequest))
|
||||
@@ -102,6 +174,7 @@ class AuthControllerTest {
|
||||
}
|
||||
|
||||
private String asJsonString(Object object) throws JsonProcessingException {
|
||||
|
||||
return objectMapper.writeValueAsString(object);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,241 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.springframework.http.MediaType.APPLICATION_JSON;
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ticketing.server.global.config.WithAuthUser;
|
||||
import com.ticketing.server.user.application.request.LoginRequest;
|
||||
import com.ticketing.server.user.application.request.SignUpRequest;
|
||||
import com.ticketing.server.user.application.request.UserChangeGradeRequest;
|
||||
import com.ticketing.server.user.application.request.UserChangePasswordRequest;
|
||||
import com.ticketing.server.user.application.request.UserDeleteRequest;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.domain.UserGrade.ROLES;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
@Transactional
|
||||
class UserControllerTest {
|
||||
|
||||
private static final String LOGIN_URL = "/api/auth/token";
|
||||
|
||||
private static final String BASICS_URL = "/api/users";
|
||||
private static final String DETAILS_URL = "/api/users/details";
|
||||
private static final String CHANGE_PASSWORD_URL = "/api/users/password";
|
||||
private static final String CHANGE_GRADE_URL = "/api/users/grade";
|
||||
|
||||
private static final String NAME = "$.name";
|
||||
private static final String EMAIL = "$.email";
|
||||
private static final String GRADE = "$.grade";
|
||||
private static final String PHONE = "$.phone";
|
||||
private static final String BEFORE_GRADE = "$.beforeGrade";
|
||||
private static final String AFTER_GRADE = "$.afterGrade";
|
||||
|
||||
private static final String USER_EMAIL = "testemail@ticketing.com";
|
||||
private static final String USER_PW = "qwe123";
|
||||
private static final String USER_NAME = "김철수";
|
||||
private static final String USER_PHONE = "010-1234-5678";
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
ObjectMapper mapper;
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext context;
|
||||
|
||||
MockMvc mvc;
|
||||
|
||||
SignUpRequest signUpRequest;
|
||||
|
||||
@Test
|
||||
@DisplayName("회원가입 성공")
|
||||
void registerSuccess() throws Exception {
|
||||
// given
|
||||
// when
|
||||
ResultActions resultActions = mvc.perform(
|
||||
post(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(APPLICATION_JSON))
|
||||
.andExpect(jsonPath(NAME).value(USER_NAME))
|
||||
.andExpect(jsonPath(EMAIL).value(USER_EMAIL));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 정보 조회")
|
||||
@WithAuthUser(email = USER_EMAIL, role = ROLES.USER)
|
||||
void detailsSuccess() throws Exception {
|
||||
// given
|
||||
mvc.perform(
|
||||
post(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// when
|
||||
ResultActions resultActions = mvc.perform(
|
||||
get(DETAILS_URL)
|
||||
.content(mapper.writeValueAsString(signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(APPLICATION_JSON))
|
||||
.andExpect(jsonPath(NAME).value(USER_NAME))
|
||||
.andExpect(jsonPath(EMAIL).value(USER_EMAIL))
|
||||
.andExpect(jsonPath(GRADE).value(UserGrade.USER.name()))
|
||||
.andExpect(jsonPath(PHONE).value(USER_PHONE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 탈퇴 성공")
|
||||
@WithAuthUser(email = USER_EMAIL, role = ROLES.USER)
|
||||
void deleteUserSuccess() throws Exception {
|
||||
// given
|
||||
UserDeleteRequest deleteRequest = new UserDeleteRequest(USER_EMAIL, USER_PW);
|
||||
LoginRequest loginRequest = new LoginRequest(USER_EMAIL, USER_PW);
|
||||
mvc.perform(
|
||||
post(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// when
|
||||
|
||||
// 1. 회원 탈퇴 진행
|
||||
mvc.perform(
|
||||
delete(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(deleteRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// 2. 탈퇴된 계정 로그인
|
||||
ResultActions resultActions = mvc.perform(post(LOGIN_URL)
|
||||
.content(mapper.writeValueAsString(loginRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비밀번호 변경 성공")
|
||||
@WithAuthUser(email = USER_EMAIL, role = ROLES.USER)
|
||||
void changePasswordSuccess() throws Exception {
|
||||
// given
|
||||
UserChangePasswordRequest changePasswordRequest = new UserChangePasswordRequest(USER_PW, "qwe1234");
|
||||
LoginRequest loginRequest = new LoginRequest(USER_EMAIL, USER_PW);
|
||||
mvc.perform(
|
||||
post(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(this.signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// when
|
||||
|
||||
// 1. 패스워드 변경
|
||||
mvc.perform(
|
||||
put(CHANGE_PASSWORD_URL)
|
||||
.content(mapper.writeValueAsString(changePasswordRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
)
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// 2. 변경 전 계정으로 로그인
|
||||
ResultActions resultActions = mvc.perform(post(LOGIN_URL)
|
||||
.content(mapper.writeValueAsString(loginRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 등급 변경")
|
||||
@WithAuthUser(email = "admin@ticketing.com", role = ROLES.ADMIN)
|
||||
void changeGradeSuccess() throws Exception {
|
||||
// given
|
||||
UserChangeGradeRequest changeGradeRequest = new UserChangeGradeRequest(USER_EMAIL, UserGrade.STAFF);
|
||||
mvc.perform(
|
||||
post(BASICS_URL)
|
||||
.content(mapper.writeValueAsString(signUpRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// when
|
||||
ResultActions resultActions = mvc.perform(
|
||||
post(CHANGE_GRADE_URL)
|
||||
.content(mapper.writeValueAsString(changeGradeRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(APPLICATION_JSON))
|
||||
.andExpect(jsonPath(EMAIL).value(USER_EMAIL))
|
||||
.andExpect(jsonPath(BEFORE_GRADE).value(UserGrade.USER.name()))
|
||||
.andExpect(jsonPath(AFTER_GRADE).value(UserGrade.STAFF.name()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 등급 변경 실패 - 권한 등급이 낮을 경우")
|
||||
@WithAuthUser(email = "staff@ticketing.com", role = ROLES.STAFF)
|
||||
void changeGradeFail() throws Exception {
|
||||
// given
|
||||
UserChangeGradeRequest changeGradeRequest = new UserChangeGradeRequest(USER_EMAIL, UserGrade.STAFF);
|
||||
|
||||
// when
|
||||
ResultActions resultActions = mvc.perform(
|
||||
post(CHANGE_GRADE_URL)
|
||||
.content(mapper.writeValueAsString(changeGradeRequest))
|
||||
.contentType(APPLICATION_JSON)
|
||||
);
|
||||
|
||||
// then
|
||||
resultActions
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
|
||||
signUpRequest = new SignUpRequest(USER_NAME, USER_EMAIL, USER_PW, USER_PHONE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ spring:
|
||||
pathmatch:
|
||||
matching-strategy: ant_path_matcher
|
||||
|
||||
config:
|
||||
import: "optional:configserver:"
|
||||
|
||||
jasypt:
|
||||
encryptor:
|
||||
bean: jasyptStringEncryptor
|
||||
|
||||
@@ -5,7 +5,6 @@ import static org.springframework.http.HttpStatus.CONFLICT;
|
||||
import static org.springframework.http.HttpStatus.FORBIDDEN;
|
||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||
|
||||
import com.ticketing.server.global.redis.PaymentCache;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -24,8 +23,11 @@ public enum ErrorCode {
|
||||
BAD_REQUEST_PAYMENT_COMPLETE(BAD_REQUEST, "처리할 결제 정보가 존재하지 않습니다."),
|
||||
BAD_REQUEST_PAYMENT_READY(BAD_REQUEST, "이미 진행 중인 결제가 존재합니다."),
|
||||
BAD_REQUEST_PAYMENT_CANCEL(BAD_REQUEST, "취소할 티켓이 존재하지 않습니다."),
|
||||
BAD_REQUEST_TICKET_RESERVATION(BAD_REQUEST, "이미 다른 고객이 예약 진행 중인 좌석이 존재합니다."),
|
||||
BAD_REQUEST_TICKET_SOLD(BAD_REQUEST, "이미 환불 진행 중 입니다."),
|
||||
NOT_REFUNDABLE_TIME(BAD_REQUEST, "환불이 가능한 시간이 지났습니다."),
|
||||
NOT_REFUNDABLE_SEAT(BAD_REQUEST, "환불할 수 있는 좌석이 아닙니다."),
|
||||
EMPTY_TICKET_ID(BAD_REQUEST, "티켓 정보가 존재하지 않습니다."),
|
||||
|
||||
/* 403 FORBIDDEN : 접근 권한 제한 */
|
||||
VALID_USER_ID(FORBIDDEN, "해당 정보에 접근 권한이 존재하지 않습니다."),
|
||||
@@ -48,7 +50,7 @@ public enum ErrorCode {
|
||||
DELETED_MOVIE(CONFLICT, "이미 삭제된 영화 입니다.");
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
private String detail;
|
||||
private final String detail;
|
||||
|
||||
/* 400 BAD_REQUEST : 잘못된 요청 */
|
||||
public static TicketingException throwMismatchPassword() {
|
||||
@@ -67,14 +69,6 @@ public enum ErrorCode {
|
||||
throw new TicketingException(UNABLE_CHANGE_GRADE);
|
||||
}
|
||||
|
||||
public static TicketingException throwInvalidTicketId() {
|
||||
throw new TicketingException(INVALID_TICKET_ID);
|
||||
}
|
||||
|
||||
public static TicketingException throwBadRequestMovieTime() {
|
||||
throw new TicketingException(BAD_REQUEST_MOVIE_TIME);
|
||||
}
|
||||
|
||||
public static TicketingException throwBadRequestPaymentComplete() {
|
||||
throw new TicketingException(BAD_REQUEST_PAYMENT_COMPLETE);
|
||||
}
|
||||
@@ -83,27 +77,12 @@ public enum ErrorCode {
|
||||
throw new TicketingException(BAD_REQUEST_PAYMENT_READY);
|
||||
}
|
||||
|
||||
public static TicketingException throwBadRequestPaymentCancel() {
|
||||
throw new TicketingException(BAD_REQUEST_PAYMENT_CANCEL);
|
||||
}
|
||||
|
||||
public static TicketingException throwNotRefundableTime() {
|
||||
throw new TicketingException(NOT_REFUNDABLE_TIME);
|
||||
}
|
||||
|
||||
public static TicketingException throwNotRefundableSeat() {
|
||||
throw new TicketingException(NOT_REFUNDABLE_SEAT);
|
||||
}
|
||||
|
||||
/* 403 FORBIDDEN : 접근 권한 제한 */
|
||||
public static TicketingException throwValidUserId() {
|
||||
throw new TicketingException(VALID_USER_ID);
|
||||
}
|
||||
|
||||
/* 404 NOT_FOUND : Resource 를 찾을 수 없음 */
|
||||
public static TicketingException throwUserNotFound() {
|
||||
throw new TicketingException(USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwEmailNotFound() {
|
||||
throw new TicketingException(EMAIL_NOT_FOUND);
|
||||
@@ -113,10 +92,6 @@ public enum ErrorCode {
|
||||
throw new TicketingException(MOVIE_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwMovieTimeNotFound() {
|
||||
throw new TicketingException(MOVIE_TIME_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwRefreshTokenNotFound() {
|
||||
throw new TicketingException(REFRESH_TOKEN_NOT_FOUND);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.ObjectError;
|
||||
@@ -211,6 +212,17 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이메일이 존재하지 않을 경우
|
||||
*/
|
||||
@ExceptionHandler(value = BadCredentialsException.class)
|
||||
protected ResponseEntity<ErrorResponse> handleBadCredentialsException(BadCredentialsException ex) {
|
||||
log.error("BadCredentialsException :: ", ex);
|
||||
|
||||
ErrorResponse response = new ErrorResponse(UNAUTHORIZED, ex.getLocalizedMessage(), "아이디 혹은 패스워드가 일치하지 않습니다.");
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 정보가 없을 때
|
||||
*/
|
||||
|
||||
@@ -28,8 +28,9 @@ public class RefreshToken {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public void changeToken(String token) {
|
||||
public RefreshToken changeToken(String token) {
|
||||
this.token = token;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ public class JwtProvider {
|
||||
|
||||
private static final String AUTHORITIES_KEY = "auth";
|
||||
private static final String AUTHORITIES_DELIMITER = ",";
|
||||
private static final String ROLE = "ROLE_";
|
||||
|
||||
private final Key key;
|
||||
private final String prefix;
|
||||
@@ -89,7 +90,7 @@ public class JwtProvider {
|
||||
}
|
||||
|
||||
private String makeRoleName(String role) {
|
||||
return "ROLE_" + role.toUpperCase();
|
||||
return role.contains(ROLE) ? role.toUpperCase() : ROLE + role.toUpperCase();
|
||||
}
|
||||
|
||||
public Authentication getAuthentication(String token) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ticketing.server.movie.aop;
|
||||
|
||||
import static com.ticketing.server.movie.domain.TicketLock.LOCK_VALUE;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.service.dto.TicketIdsDTO;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Aspect
|
||||
@RequiredArgsConstructor
|
||||
public class TicketLockAspect {
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Around("execution(* com.ticketing.server.movie.service.TicketLockService.*(..))")
|
||||
public Object ticketLock(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
List<String> ticketLockIds = getTicketLockIds(joinPoint);
|
||||
|
||||
try {
|
||||
if (!isEveryTicketIdLock(ticketLockIds)) {
|
||||
throw new TicketingException(ErrorCode.BAD_REQUEST_TICKET_SOLD);
|
||||
}
|
||||
|
||||
return joinPoint.proceed();
|
||||
} finally {
|
||||
ticketIdsUnlock(ticketLockIds);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean isEveryTicketIdLock(List<String> ids) {
|
||||
for (String id : ids) {
|
||||
if (Boolean.FALSE.equals(redisTemplate.opsForValue().setIfAbsent(id, LOCK_VALUE.getValue(), 5, TimeUnit.MINUTES))) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
protected Long ticketIdsUnlock(List<String> ids) {
|
||||
return redisTemplate.delete(ids);
|
||||
}
|
||||
|
||||
private List<String> getTicketLockIds(ProceedingJoinPoint joinPoint) {
|
||||
for (Object arg : joinPoint.getArgs()) {
|
||||
if (arg instanceof TicketIdsDTO) {
|
||||
TicketIdsDTO ids = (TicketIdsDTO) arg;
|
||||
return ids.makeTicketLockIds();
|
||||
}
|
||||
}
|
||||
|
||||
throw new TicketingException(ErrorCode.EMPTY_TICKET_ID);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -8,11 +8,12 @@ import com.ticketing.server.movie.application.response.MovieDeleteResponse;
|
||||
import com.ticketing.server.movie.application.response.MovieListResponse;
|
||||
import com.ticketing.server.movie.application.response.MovieInfoResponse;
|
||||
import com.ticketing.server.movie.service.dto.DeletedMovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieListDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -51,11 +52,11 @@ public class MovieController {
|
||||
@GetMapping()
|
||||
@ApiOperation(value = "영화 목록 조회")
|
||||
public ResponseEntity<MovieListResponse> getMovies() {
|
||||
MovieListDTO movieListDto = movieService.getMovies();
|
||||
List<MovieDTO> movieDtos = movieService.getMovies();
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
movieListDto.toResponse()
|
||||
new MovieListResponse(movieDtos)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,13 +5,14 @@ import static com.ticketing.server.user.domain.UserGrade.ROLES.STAFF;
|
||||
import com.ticketing.server.movie.application.request.MovieTimeRegisterRequest;
|
||||
import com.ticketing.server.movie.application.response.MovieTimeInfoResponse;
|
||||
import com.ticketing.server.movie.application.response.MovieTimeListResponse;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeListDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieTimeService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -58,11 +59,11 @@ public class MovieTimeController {
|
||||
public ResponseEntity<MovieTimeListResponse> getMovieTimes(
|
||||
@ApiParam(value = "영화 ID", required = true) @RequestParam @NotNull Long movieId,
|
||||
@ApiParam(value = "상영 날짜", required = true) @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate runningDate) {
|
||||
MovieTimeListDTO movieTimeListDto = movieTimeService.getMovieTimes(movieId, runningDate);
|
||||
List<MovieTimeDTO> movieTimeDtos = movieTimeService.getMovieTimes(movieId, runningDate);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
movieTimeListDto.toResponse()
|
||||
new MovieTimeListResponse(movieTimeDtos)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,11 @@ import static com.ticketing.server.user.domain.UserGrade.ROLES.USER;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.movie.application.response.TicketListResponse;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketListDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -32,11 +33,11 @@ public class TicketController {
|
||||
@Secured(USER)
|
||||
public ResponseEntity<TicketListResponse> getTickets(
|
||||
@ApiParam(value = "영화 시간표 ID", required = true) @RequestParam @NotNull Long movieTimeId) {
|
||||
TicketListDTO ticketListDto = ticketService.getTickets(movieTimeId);
|
||||
List<TicketDTO> tickets = ticketService.getTickets(movieTimeId);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
ticketListDto.toResponse()
|
||||
new TicketListResponse(tickets)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,11 +45,11 @@ public class TicketController {
|
||||
@Secured(USER)
|
||||
public ResponseEntity<TicketDetailsResponse> findTicketsByPaymentId(
|
||||
@PathVariable("paymentId") @NotNull Long paymentId) {
|
||||
TicketDetailsDTO tickets = ticketService.findTicketsByPaymentId(paymentId);
|
||||
List<TicketDetailDTO> tickets = ticketService.findTicketsByPaymentId(paymentId);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
tickets.toResponse()
|
||||
new TicketDetailsResponse(tickets)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import static com.ticketing.server.global.exception.ErrorCode.BAD_REQUEST_PAYMENT_CANCEL;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.DUPLICATE_PAYMENT;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.NOT_REFUNDABLE_SEAT;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.NOT_REFUNDABLE_TIME;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import javax.persistence.Entity;
|
||||
@@ -56,7 +62,7 @@ public class Ticket extends AbstractEntity {
|
||||
|
||||
public Ticket makeReservation() {
|
||||
if (!TicketStatus.SALE.equals(status)) {
|
||||
throw ErrorCode.throwDuplicatePayment();
|
||||
throw new TicketingException(DUPLICATE_PAYMENT);
|
||||
}
|
||||
|
||||
status = TicketStatus.RESERVATION;
|
||||
@@ -65,7 +71,7 @@ public class Ticket extends AbstractEntity {
|
||||
|
||||
public Ticket makeSold(Long paymentId) {
|
||||
if (TicketStatus.SOLD.equals(status)) {
|
||||
throw ErrorCode.throwDuplicatePayment();
|
||||
throw new TicketingException(DUPLICATE_PAYMENT);
|
||||
}
|
||||
|
||||
status = TicketStatus.SOLD;
|
||||
@@ -75,7 +81,7 @@ public class Ticket extends AbstractEntity {
|
||||
|
||||
public Ticket cancel() {
|
||||
if (!TicketStatus.RESERVATION.equals(status)) {
|
||||
throw ErrorCode.throwBadRequestPaymentCancel();
|
||||
throw new TicketingException(BAD_REQUEST_PAYMENT_CANCEL);
|
||||
}
|
||||
|
||||
status = TicketStatus.SALE;
|
||||
@@ -86,7 +92,7 @@ public class Ticket extends AbstractEntity {
|
||||
public Ticket refund(LocalDateTime dateTime) {
|
||||
long seconds = ChronoUnit.SECONDS.between(dateTime, getStartAt());
|
||||
if (600L > seconds) {
|
||||
throw ErrorCode.throwNotRefundableTime();
|
||||
throw new TicketingException(NOT_REFUNDABLE_TIME);
|
||||
}
|
||||
|
||||
return refund();
|
||||
@@ -94,7 +100,7 @@ public class Ticket extends AbstractEntity {
|
||||
|
||||
public Ticket refund() {
|
||||
if (!TicketStatus.SOLD.equals(status)) {
|
||||
throw ErrorCode.throwNotRefundableSeat();
|
||||
throw new TicketingException(NOT_REFUNDABLE_SEAT);
|
||||
}
|
||||
|
||||
status = TicketStatus.SALE;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum TicketLock {
|
||||
|
||||
LOCK_KEY("TicketLock"),
|
||||
LOCK_VALUE("lock");
|
||||
|
||||
private final String value;
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
@@ -17,8 +16,8 @@ public interface MovieRepository extends JpaRepository<Movie, Long> {
|
||||
|
||||
@Query(value = "SELECT m "
|
||||
+ "FROM Movie m "
|
||||
+ "WHERE title = :title "
|
||||
+ "AND deleted_at IS NULL")
|
||||
+ "WHERE m.title = :title "
|
||||
+ "AND m.deletedAt IS NULL")
|
||||
Optional<Movie> findValidMovieWithTitle(String title);
|
||||
|
||||
@Query(value = "SELECT * "
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.service.dto.DeletedMovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieListDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieService;
|
||||
import java.util.List;
|
||||
@@ -39,14 +38,12 @@ public class MovieServiceImpl implements MovieService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MovieListDTO getMovies() {
|
||||
public List<MovieDTO> getMovies() {
|
||||
List<Movie> movies = movieRepository.findValidMovies();
|
||||
|
||||
List<MovieDTO> movieDtos = movies.stream()
|
||||
return movies.stream()
|
||||
.map(movie -> movie.toMovieDTO())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new MovieListDTO(movieDtos);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -8,9 +8,7 @@ import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.domain.repository.MovieTimeRepository;
|
||||
import com.ticketing.server.movie.domain.repository.TheaterRepository;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeListDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeRegisterDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieTimeService;
|
||||
import java.time.LocalDate;
|
||||
@@ -56,7 +54,7 @@ public class MovieTimeServiceImpl implements MovieTimeService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MovieTimeListDTO getMovieTimes(Long movieId, LocalDate runningDate) {
|
||||
public List<MovieTimeDTO> getMovieTimes(Long movieId, LocalDate runningDate) {
|
||||
Movie movie = findMovieById(movieId);
|
||||
|
||||
LocalDateTime startOfDay = runningDate.atStartOfDay().plusHours(6);
|
||||
@@ -64,11 +62,9 @@ public class MovieTimeServiceImpl implements MovieTimeService {
|
||||
|
||||
List<MovieTime> movieTimes = movieTimeRepository.findValidMovieTimes(movie, startOfDay, endOfDay);
|
||||
|
||||
List<MovieTimeDTO> movieTimeDtos = movieTimes.stream()
|
||||
return movieTimes.stream()
|
||||
.map(movieTime -> movieTime.toMovieTimeDTO())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new MovieTimeListDTO(movieTimeDtos);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static com.ticketing.server.global.exception.ErrorCode.BAD_REQUEST_MOVIE_TIME;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.INVALID_TICKET_ID;
|
||||
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.movie.service.dto.TicketIdsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketSoldDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsSoldDTO;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class TicketLockService {
|
||||
|
||||
private final TicketRepository ticketRepository;
|
||||
|
||||
public TicketsReservationDTO ticketReservation(@Valid TicketIdsDTO ticketIdsDto) {
|
||||
List<Ticket> tickets = getTicketsByInTicketIds(ticketIdsDto.getTicketIds());
|
||||
|
||||
Long firstMovieTimeId = firstMovieTimeId(tickets);
|
||||
List<TicketReservationDTO> reservationDtoList = tickets.stream()
|
||||
.map(Ticket::makeReservation)
|
||||
.filter(ticket -> firstMovieTimeId.equals(ticket.getMovieTimeId()))
|
||||
.map(TicketReservationDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (tickets.size() != reservationDtoList.size()) {
|
||||
throw new TicketingException(BAD_REQUEST_MOVIE_TIME);
|
||||
}
|
||||
|
||||
return new TicketsReservationDTO(firstMovieTitle(tickets), reservationDtoList);
|
||||
}
|
||||
|
||||
public TicketsSoldDTO ticketSold(@NotNull Long paymentId, @Valid TicketIdsDTO ticketIdsDto) {
|
||||
List<Ticket> tickets = getTicketsByInTicketIds(ticketIdsDto.getTicketIds());
|
||||
|
||||
List<TicketSoldDTO> soldDtoList = tickets.stream()
|
||||
.map(ticket -> ticket.makeSold(paymentId))
|
||||
.map(TicketSoldDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new TicketsSoldDTO(paymentId, soldDtoList);
|
||||
}
|
||||
|
||||
private List<Ticket> getTicketsByInTicketIds(List<Long> ticketIds) {
|
||||
List<Ticket> tickets = ticketRepository.findTicketFetchJoinByTicketIds(ticketIds);
|
||||
|
||||
if (tickets.size() != ticketIds.size()) {
|
||||
throw new TicketingException(INVALID_TICKET_ID);
|
||||
}
|
||||
|
||||
return tickets;
|
||||
}
|
||||
|
||||
private Long firstMovieTimeId(List<Ticket> tickets) {
|
||||
Ticket ticket = tickets.get(0);
|
||||
return ticket.getMovieTimeId();
|
||||
}
|
||||
|
||||
private String firstMovieTitle(List<Ticket> tickets) {
|
||||
Ticket ticket = tickets.get(0);
|
||||
return ticket.getMovieTitle();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +1,24 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import com.ticketing.server.movie.domain.repository.MovieTimeRepository;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.INVALID_TICKET_ID;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.MOVIE_TIME_NOT_FOUND;
|
||||
import static com.ticketing.server.global.exception.ErrorCode.PAYMENT_ID_NOT_FOUND;
|
||||
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.global.validator.constraints.NotEmptyCollection;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.domain.repository.MovieTimeRepository;
|
||||
import com.ticketing.server.movie.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.movie.service.dto.TicketDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketListDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketIdsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketSoldDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsCancelDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsSoldDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.constraints.NotNull;
|
||||
@@ -38,66 +36,44 @@ import org.springframework.validation.annotation.Validated;
|
||||
public class TicketServiceImpl implements TicketService {
|
||||
|
||||
private final TicketRepository ticketRepository;
|
||||
|
||||
private final MovieTimeRepository movieTimeRepository;
|
||||
private final TicketLockService ticketLockService;
|
||||
|
||||
@Override
|
||||
public TicketListDTO getTickets(@NotNull Long movieTimeId) {
|
||||
public List<TicketDTO> getTickets(@NotNull Long movieTimeId) {
|
||||
MovieTime movieTime = movieTimeRepository.findById(movieTimeId)
|
||||
.orElseThrow(ErrorCode::throwMovieTimeNotFound);
|
||||
.orElseThrow(() -> new TicketingException(MOVIE_TIME_NOT_FOUND));
|
||||
|
||||
List<TicketDTO> tickets = ticketRepository.findValidTickets(movieTime)
|
||||
return ticketRepository.findValidTickets(movieTime)
|
||||
.stream()
|
||||
.map(TicketDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new TicketListDTO(tickets);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TicketDetailsDTO findTicketsByPaymentId(@NotNull Long paymentId) {
|
||||
public List<TicketDetailDTO> findTicketsByPaymentId(@NotNull Long paymentId) {
|
||||
List<TicketDetailDTO> ticketDetails = ticketRepository.findTicketFetchJoinByPaymentId(paymentId)
|
||||
.stream()
|
||||
.map(TicketDetailDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (ticketDetails.isEmpty()) {
|
||||
throw ErrorCode.throwPaymentIdNotFound();
|
||||
throw new TicketingException(PAYMENT_ID_NOT_FOUND);
|
||||
}
|
||||
|
||||
return new TicketDetailsDTO(ticketDetails);
|
||||
return ticketDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TicketsReservationDTO ticketReservation(@NotEmptyCollection List<Long> ticketIds) {
|
||||
List<Ticket> tickets = getTicketsByInTicketIds(ticketIds);
|
||||
|
||||
Long firstMovieTimeId = firstMovieTimeId(tickets);
|
||||
List<TicketReservationDTO> reservationDtoList = tickets.stream()
|
||||
.map(Ticket::makeReservation)
|
||||
.filter(ticket -> firstMovieTimeId.equals(ticket.getMovieTimeId()))
|
||||
.map(TicketReservationDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (ticketIds.size() != reservationDtoList.size()) {
|
||||
throw ErrorCode.throwBadRequestMovieTime();
|
||||
}
|
||||
|
||||
return new TicketsReservationDTO(firstMovieTitle(tickets), reservationDtoList);
|
||||
return ticketLockService.ticketReservation(new TicketIdsDTO(ticketIds));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TicketsSoldDTO ticketSold(@NotNull Long paymentId, @NotEmptyCollection List<Long> ticketIds) {
|
||||
List<Ticket> tickets = getTicketsByInTicketIds(ticketIds);
|
||||
|
||||
List<TicketSoldDTO> soldDtoList = tickets.stream()
|
||||
.map(ticket -> ticket.makeSold(paymentId))
|
||||
.map(TicketSoldDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new TicketsSoldDTO(paymentId, soldDtoList);
|
||||
return ticketLockService.ticketSold(paymentId, new TicketIdsDTO(ticketIds));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -106,40 +82,28 @@ public class TicketServiceImpl implements TicketService {
|
||||
List<Ticket> tickets = getTicketsByInTicketIds(ticketIds);
|
||||
tickets.forEach(Ticket::cancel);
|
||||
|
||||
return new TicketsCancelDTO(ticketIds);
|
||||
return new TicketsCancelDTO(tickets);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TicketsRefundDTO ticketsRefund(@NotNull Long paymentId, UnaryOperator<Ticket> refund) {
|
||||
public List<TicketRefundDTO> ticketsRefund(@NotNull Long paymentId, UnaryOperator<Ticket> refund) {
|
||||
List<Ticket> tickets = ticketRepository.findTicketFetchJoinByPaymentId(paymentId);
|
||||
|
||||
List<TicketRefundDTO> refundDtoList = tickets.stream()
|
||||
return tickets.stream()
|
||||
.map(refund)
|
||||
.map(TicketRefundDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new TicketsRefundDTO(refundDtoList);
|
||||
}
|
||||
|
||||
private List<Ticket> getTicketsByInTicketIds(List<Long> ticketIds) {
|
||||
List<Ticket> tickets = ticketRepository.findTicketFetchJoinByTicketIds(ticketIds);
|
||||
|
||||
if (tickets.size() != ticketIds.size()) {
|
||||
throw ErrorCode.throwInvalidTicketId();
|
||||
throw new TicketingException(INVALID_TICKET_ID);
|
||||
}
|
||||
|
||||
return tickets;
|
||||
}
|
||||
|
||||
private Long firstMovieTimeId(List<Ticket> tickets) {
|
||||
Ticket ticket = tickets.get(0);
|
||||
return ticket.getMovieTimeId();
|
||||
}
|
||||
|
||||
private String firstMovieTitle(List<Ticket> tickets) {
|
||||
Ticket ticket = tickets.get(0);
|
||||
return ticket.getMovieTitle();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieListResponse;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieListDTO {
|
||||
|
||||
private final List<MovieDTO> movieDtos;
|
||||
|
||||
public MovieListResponse toResponse() {
|
||||
return new MovieListResponse(movieDtos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieTimeListResponse;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeListDTO {
|
||||
|
||||
private final List<MovieTimeDTO> movieTimeDtos;
|
||||
|
||||
public MovieTimeListResponse toResponse() {
|
||||
return new MovieTimeListResponse(movieTimeDtos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketDetailsDTO {
|
||||
|
||||
private final List<TicketDetailDTO> ticketDetails;
|
||||
|
||||
public TicketDetailsResponse toResponse() {
|
||||
return new TicketDetailsResponse(ticketDetails);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import static com.ticketing.server.movie.domain.TicketLock.LOCK_KEY;
|
||||
|
||||
import com.ticketing.server.global.validator.constraints.NotEmptyCollection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketIdsDTO {
|
||||
|
||||
@NotEmptyCollection
|
||||
private List<Long> ticketIds;
|
||||
|
||||
public List<String> makeTicketLockIds() {
|
||||
return ticketIds.stream()
|
||||
.map(id -> LOCK_KEY.getValue() + ":" + id)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketListResponse;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketListDTO {
|
||||
|
||||
private final List<TicketDTO> ticketDtos;
|
||||
|
||||
public TicketListResponse toResponse() {
|
||||
return new TicketListResponse(ticketDtos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +1,22 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketCancelResponse;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketsCancelDTO {
|
||||
|
||||
private final List<Long> ticketIds;
|
||||
|
||||
public TicketsCancelDTO(List<Ticket> tickets) {
|
||||
ticketIds = tickets.stream()
|
||||
.map(Ticket::getId)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public TicketCancelResponse toResponse() {
|
||||
return new TicketCancelResponse(ticketIds);
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketsRefundDTO {
|
||||
|
||||
private List<TicketRefundDTO> tickets;
|
||||
|
||||
public TicketsRefundResponse toResponse() {
|
||||
return new TicketsRefundResponse(tickets);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.DeletedMovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieListDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieDTO;
|
||||
import java.util.List;
|
||||
|
||||
public interface MovieService {
|
||||
|
||||
RegisteredMovieDTO registerMovie(String title, Long runningTime);
|
||||
|
||||
MovieListDTO getMovies();
|
||||
List<MovieDTO> getMovies();
|
||||
|
||||
DeletedMovieDTO deleteMovie(Long id);
|
||||
}
|
||||
|
||||
@@ -2,17 +2,18 @@ package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeListDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeRegisterDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieTimeDTO;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
|
||||
public interface MovieTimeService {
|
||||
|
||||
RegisteredMovieTimeDTO registerMovieTime(@Valid MovieTimeRegisterDTO movieTimeRegisterDto);
|
||||
|
||||
MovieTimeListDTO getMovieTimes(Long movieId, LocalDate runningDate);
|
||||
List<MovieTimeDTO> getMovieTimes(Long movieId, LocalDate runningDate);
|
||||
|
||||
Movie findMovieById(Long movieId);
|
||||
|
||||
|
||||
@@ -2,21 +2,23 @@ package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
import com.ticketing.server.global.validator.constraints.NotEmptyCollection;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketListDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketIdsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsCancelDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsSoldDTO;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.util.List;
|
||||
import java.util.function.UnaryOperator;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public interface TicketService {
|
||||
|
||||
TicketListDTO getTickets(@NotNull Long movieTimeId);
|
||||
List<TicketDTO> getTickets(@NotNull Long movieTimeId);
|
||||
|
||||
TicketDetailsDTO findTicketsByPaymentId(@NotNull Long paymentId);
|
||||
List<TicketDetailDTO> findTicketsByPaymentId(@NotNull Long paymentId);
|
||||
|
||||
TicketsReservationDTO ticketReservation(@NotEmptyCollection List<Long> ticketIds);
|
||||
|
||||
@@ -24,6 +26,6 @@ public interface TicketService {
|
||||
|
||||
TicketsCancelDTO ticketCancel(@NotEmptyCollection List<Long> ticketIds);
|
||||
|
||||
TicketsRefundDTO ticketsRefund(@NotNull Long paymentId, UnaryOperator<Ticket> refund);
|
||||
List<TicketRefundDTO> ticketsRefund(@NotNull Long paymentId, UnaryOperator<Ticket> refund);
|
||||
|
||||
}
|
||||
|
||||
@@ -8,15 +8,16 @@ import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.movie.application.response.TicketReservationResponse;
|
||||
import com.ticketing.server.movie.application.response.TicketSoldResponse;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsCancelDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsRefundDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsRefundResponse;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsSoldDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import com.ticketing.server.payment.api.MovieClient;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -31,8 +32,8 @@ public class MovieClientImpl implements MovieClient {
|
||||
|
||||
@Override
|
||||
public TicketDetailsResponse getTicketsByPaymentId(@NotNull Long paymentId) {
|
||||
TicketDetailsDTO ticketDetails = ticketService.findTicketsByPaymentId(paymentId);
|
||||
return ticketDetails.toResponse();
|
||||
List<TicketDetailDTO> ticketDetails = ticketService.findTicketsByPaymentId(paymentId);
|
||||
return new TicketDetailsResponse(ticketDetails);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,14 +56,14 @@ public class MovieClientImpl implements MovieClient {
|
||||
|
||||
@Override
|
||||
public TicketsRefundResponse ticketRefundByDateTime(TicketsRefundRequest request, LocalDateTime dateTime) {
|
||||
TicketsRefundDTO ticketsRefundDto = ticketService.ticketsRefund(request.getPaymentId(), ticket -> ticket.refund(dateTime));
|
||||
return ticketsRefundDto.toResponse();
|
||||
List<TicketRefundDTO> ticketRefundDTOS = ticketService.ticketsRefund(request.getPaymentId(), ticket -> ticket.refund(dateTime));
|
||||
return new TicketsRefundResponse(ticketRefundDTOS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TicketsRefundResponse ticketRefund(TicketsRefundRequest request) {
|
||||
TicketsRefundDTO ticketsRefundDto = ticketService.ticketsRefund(request.getPaymentId(), Ticket::refund);
|
||||
return ticketsRefundDto.toResponse();
|
||||
List<TicketRefundDTO> ticketRefundDtos = ticketService.ticketsRefund(request.getPaymentId(), Ticket::refund);
|
||||
return new TicketsRefundResponse(ticketRefundDtos);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
import com.ticketing.server.user.application.request.LoginRequest;
|
||||
import com.ticketing.server.user.application.request.RefreshRequest;
|
||||
import com.ticketing.server.user.application.response.LogoutResponse;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import com.ticketing.server.user.application.response.TokenResponse;
|
||||
import com.ticketing.server.user.service.dto.DeleteRefreshTokenDTO;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import com.ticketing.server.user.service.interfaces.AuthenticationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -16,7 +17,6 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
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
|
||||
@@ -37,8 +37,8 @@ public class AuthController {
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public ResponseEntity<TokenResponse> refreshToken(@RequestParam("refreshToken") String refreshToken) {
|
||||
TokenDTO tokenDto = authenticationService.reissueTokenDto(refreshToken);
|
||||
public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) {
|
||||
TokenDTO tokenDto = authenticationService.reissueTokenDto(request.getRefreshToken());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.headers(getHttpHeaders())
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ticketing.server.user.application.request;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RefreshRequest {
|
||||
|
||||
private String refreshToken;
|
||||
|
||||
}
|
||||
@@ -4,9 +4,13 @@ import com.ticketing.server.user.domain.UserGrade;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class UserChangeGradeRequest {
|
||||
|
||||
@NotEmpty(message = "{validation.not.empty.email}")
|
||||
|
||||
@@ -2,14 +2,16 @@ package com.ticketing.server.user.application.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TokenResponse {
|
||||
|
||||
private final String accessToken;
|
||||
private final String refreshToken;
|
||||
private final String tokenType;
|
||||
private final long expiresIn;
|
||||
private String accessToken;
|
||||
private String refreshToken;
|
||||
private String tokenType;
|
||||
private long expiresIn;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.ticketing.server.user.application.response;
|
||||
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.service.dto.UserDetailDTO;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
|
||||
@@ -3,10 +3,9 @@ package com.ticketing.server.user.service;
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.global.redis.RefreshToken;
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.security.jwt.JwtProvider;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import com.ticketing.server.user.service.dto.DeleteRefreshTokenDTO;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import com.ticketing.server.user.service.interfaces.AuthenticationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
@@ -14,7 +13,6 @@ import org.springframework.security.config.annotation.authentication.builders.Au
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -23,7 +21,6 @@ public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
private final RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
private final JwtProvider jwtProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final AuthenticationManagerBuilder authenticationManagerBuilder;
|
||||
|
||||
@Override
|
||||
@@ -40,8 +37,14 @@ public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
// refresh 토큰이 있으면 수정, 없으면 생성
|
||||
refreshRedisRepository.findByEmail(email)
|
||||
.ifPresentOrElse(
|
||||
tokenEntity -> tokenEntity.changeToken(tokenDto.getRefreshToken()),
|
||||
() -> refreshRedisRepository.save(new RefreshToken(email, tokenDto.getRefreshToken()))
|
||||
tokenEntity -> refreshRedisRepository.save(
|
||||
tokenEntity.changeToken(
|
||||
tokenDto.getRefreshToken()
|
||||
)
|
||||
),
|
||||
() -> refreshRedisRepository.save(
|
||||
new RefreshToken(email, tokenDto.getRefreshToken())
|
||||
)
|
||||
);
|
||||
|
||||
return tokenDto;
|
||||
@@ -49,9 +52,7 @@ public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TokenDTO reissueTokenDto(String bearerRefreshToken) {
|
||||
String refreshToken = resolveToken(bearerRefreshToken);
|
||||
|
||||
public TokenDTO reissueTokenDto(String refreshToken) {
|
||||
// 토큰 검증
|
||||
jwtProvider.validateToken(refreshToken);
|
||||
|
||||
@@ -61,7 +62,7 @@ public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
RefreshToken findTokenEntity = refreshRedisRepository.findByEmail(authentication.getName())
|
||||
.orElseThrow(ErrorCode::throwRefreshTokenNotFound);
|
||||
|
||||
// redis 토큰과 input 토큰이 일치한지 확인
|
||||
// input 토큰이 최신 토큰이 아닐 경우 예외 처리
|
||||
if (!refreshToken.equals(findTokenEntity.getToken())) {
|
||||
throw ErrorCode.throwUnavailableRefreshToken();
|
||||
}
|
||||
@@ -88,11 +89,4 @@ public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
);
|
||||
}
|
||||
|
||||
private String resolveToken(String bearerToken) {
|
||||
if (StringUtils.hasText(bearerToken) && jwtProperties.hasTokenStartsWith(bearerToken)) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
throw ErrorCode.throwTokenType();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.ticketing.server.user.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
import java.util.Collections;
|
||||
@@ -21,7 +20,7 @@ public class CustomUserDetailsService implements UserDetailsService {
|
||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||
return userRepository.findByEmailAndDeletedAtNull(email)
|
||||
.map(this::createUserDetails)
|
||||
.orElseThrow(ErrorCode::throwEmailNotFound);
|
||||
.orElseThrow(() -> new UsernameNotFoundException(email));
|
||||
}
|
||||
|
||||
private UserDetails createUserDetails(User user) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
server:
|
||||
port: 8443
|
||||
address: 0.0.0.0
|
||||
|
||||
http:
|
||||
port: 8080
|
||||
|
||||
ssl:
|
||||
key-store: classpath:keystore/ticketing.p12
|
||||
key-store-password: ENC(OMvGcpZLpggFTiGNkqNe66Zq/SmJXF6o)
|
||||
key-store-type: PKCS12
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://ticketing-db/ticketing?serverTimezone=Asia/Seoul&characterEncoding=UTF-8
|
||||
username: ENC(LowN1n4w0Ep/DqLD8+q5Bq6AXM4b8e3V)
|
||||
password: ENC(OMvGcpZLpggFTiGNkqNe66Zq/SmJXF6o)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
show_sql: true
|
||||
format_sql: true
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
|
||||
redis:
|
||||
host: 172.18.0.3
|
||||
port: 6379
|
||||
|
||||
BIN
server/src/main/resources/keystore/ticketing.p12
Normal file
BIN
server/src/main/resources/keystore/ticketing.p12
Normal file
Binary file not shown.
@@ -0,0 +1,120 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.domain.UserGrade.ROLES;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import javax.servlet.ServletException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@EnableConfigurationProperties(value = JwtProperties.class)
|
||||
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||
class JwtFilterTest {
|
||||
|
||||
@Autowired
|
||||
private JwtProperties jwtProperties;
|
||||
|
||||
private MockHttpServletRequest mockRequest;
|
||||
private MockHttpServletResponse mockResponse;
|
||||
private MockFilterChain mockFilterChain;
|
||||
|
||||
private JwtFilter jwtFilter;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
mockRequest = new MockHttpServletRequest();
|
||||
mockResponse = new MockHttpServletResponse();
|
||||
mockFilterChain = new MockFilterChain();
|
||||
|
||||
JwtProvider jwtProvider = new JwtProvider(jwtProperties);
|
||||
jwtFilter = new JwtFilter(jwtProperties, jwtProvider);
|
||||
|
||||
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(UserGrade.USER.name());
|
||||
Collection<SimpleGrantedAuthority> authorities = Collections.singleton(grantedAuthority);
|
||||
User user = new User(
|
||||
"kdhyo98@gmail.com",
|
||||
"",
|
||||
authorities
|
||||
);
|
||||
TokenDTO tokenDto = jwtProvider.generateTokenDto(new UsernamePasswordAuthenticationToken(user, null, authorities));
|
||||
mockRequest.addHeader("Authorization", "Bearer " + tokenDto.getAccessToken());
|
||||
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@DisplayName("Header 정보가 올바르지 않을 경우")
|
||||
@ValueSource(strings = {"Bearer tokenTest", "Bearer", "BearertokenTest"})
|
||||
void validateToken(String authorization) {
|
||||
// given
|
||||
mockRequest.removeHeader("Authorization");
|
||||
mockRequest.addHeader("Authorization", authorization);
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> jwtFilter.doFilterInternal(mockRequest, mockResponse, mockFilterChain))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다음 필터 실행")
|
||||
void continuesToNextFilter() throws ServletException, IOException {
|
||||
// given
|
||||
MockFilterChain mockFilterChainSpy = spy(this.mockFilterChain);
|
||||
|
||||
// when
|
||||
jwtFilter.doFilter(mockRequest, mockResponse, mockFilterChainSpy);
|
||||
|
||||
// then
|
||||
verify(mockFilterChainSpy, times(1)).doFilter(mockRequest, mockResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("setAuthentication 데이터 확인")
|
||||
void setsAuthenticationInSecurityContext() throws ServletException, IOException {
|
||||
// given
|
||||
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(ROLES.USER);
|
||||
Collection<GrantedAuthority> authorities = Collections.singleton(grantedAuthority);
|
||||
|
||||
// when
|
||||
jwtFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
|
||||
|
||||
// then
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
User principal = (User) authentication.getPrincipal();
|
||||
assertAll(
|
||||
() -> assertThat(principal.getUsername()).isEqualTo("kdhyo98@gmail.com"),
|
||||
() -> assertThat(principal.getAuthorities()).isEqualTo(authorities)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ticketing.server.movie.aop;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class TicketLockAspectTest {
|
||||
|
||||
}
|
||||
@@ -1,15 +1,22 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.service.dto.DeletedMovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieListDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieDTO;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.hibernate.sql.Delete;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -21,9 +28,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
public class MovieServiceImplTest {
|
||||
|
||||
Movie movie;
|
||||
MovieDTO movieDto;
|
||||
List<Movie> movies = new ArrayList<>();
|
||||
List<MovieDTO> movieDTOS = new ArrayList<>();
|
||||
|
||||
@Mock
|
||||
MovieRepository movieRepository;
|
||||
@@ -39,10 +44,10 @@ public class MovieServiceImplTest {
|
||||
.thenReturn(Collections.emptyList());
|
||||
|
||||
// when
|
||||
MovieListDTO movieListDto = movieService.getMovies();
|
||||
List<MovieDTO> movieDtos = movieService.getMovies();
|
||||
|
||||
// then
|
||||
assertTrue(movieListDto.getMovieDtos().isEmpty());
|
||||
assertTrue(movieDtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -55,11 +60,80 @@ public class MovieServiceImplTest {
|
||||
when(movieRepository.findValidMovies())
|
||||
.thenReturn(movies);
|
||||
|
||||
// when
|
||||
MovieListDTO movieListDto = movieService.getMovies();
|
||||
// when
|
||||
List<MovieDTO> movieDtos = movieService.getMovies();
|
||||
|
||||
// then
|
||||
assertTrue(!movieListDto.getMovieDtos().isEmpty());
|
||||
// then
|
||||
assertTrue(!movieDtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - register movie")
|
||||
void shouldAbleToRegisterMovie() {
|
||||
// given
|
||||
String title = "추가할 영화 제목";
|
||||
movie = new Movie(title, 100L);
|
||||
|
||||
when(movieRepository.findValidMovieWithTitle(title))
|
||||
.thenReturn(Optional.empty());
|
||||
when(movieRepository.save(any()))
|
||||
.thenReturn(movie);
|
||||
|
||||
// when
|
||||
RegisteredMovieDTO registeredMovieDto =
|
||||
movieService.registerMovie(title, movie.getRunningTime());
|
||||
|
||||
// then
|
||||
assertThat(registeredMovieDto).isNotNull();
|
||||
assertTrue(registeredMovieDto.getTitle().equals(title));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - register movie when there is same movie already")
|
||||
void shouldThrowExceptionWhenRegistering() {
|
||||
// given
|
||||
String title = "이미 중복된 영화 제목";
|
||||
|
||||
Movie movie = new Movie(title, 100L);
|
||||
|
||||
when(movieRepository.findValidMovieWithTitle(title))
|
||||
.thenReturn(Optional.of(movie));
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> movieService.registerMovie(title, 100L))
|
||||
.isInstanceOf(TicketingException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - delete movie")
|
||||
void shouldAbleToDeleteMovie() {
|
||||
// given
|
||||
Movie movie = new Movie("삭제할 영화 제목", 100L);
|
||||
|
||||
when(movieRepository.findByIdAndDeletedAtNull(1L))
|
||||
.thenReturn(Optional.of(movie));
|
||||
|
||||
// when
|
||||
DeletedMovieDTO deletedMovieDto =
|
||||
movieService.deleteMovie(1L);
|
||||
|
||||
// then
|
||||
assertTrue(deletedMovieDto.getTitle().equals("삭제할 영화 제목"));
|
||||
assertThat(deletedMovieDto.getDeletedAt()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - delete movie when there is no such movie")
|
||||
void shouldThrowExceptionWhenDeleting() {
|
||||
// given
|
||||
when(movieRepository.findByIdAndDeletedAtNull(1L))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> movieService.deleteMovie(1L))
|
||||
.isInstanceOf(TicketingException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.domain.repository.MovieTimeRepository;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeListDTO;
|
||||
import com.ticketing.server.movie.domain.repository.TheaterRepository;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeRegisterDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieTimeDTO;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
@@ -27,11 +35,15 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
public class MovieTimeServiceImplTest {
|
||||
|
||||
String title = "범죄도시2";
|
||||
LocalDateTime startAt = LocalDateTime.now();
|
||||
List<MovieTime> movieTimes = new ArrayList<>();
|
||||
|
||||
@Mock
|
||||
MovieRepository movieRepository;
|
||||
|
||||
@Mock
|
||||
TheaterRepository theaterRepository;
|
||||
|
||||
@Mock
|
||||
MovieTimeRepository movieTimeRepository;
|
||||
|
||||
@@ -39,7 +51,7 @@ public class MovieTimeServiceImplTest {
|
||||
MovieTimeServiceImpl movieTimeService;
|
||||
|
||||
@Test
|
||||
@DisplayName("MovieTime Service Test - get empty list when there are no valid movie times")
|
||||
@DisplayName("MovieTime Service Test - get empty list when there is no valid movie time")
|
||||
void shouldGetEmptyList() {
|
||||
// given
|
||||
Movie movie = new Movie(title, 106L);
|
||||
@@ -51,10 +63,10 @@ public class MovieTimeServiceImplTest {
|
||||
.thenReturn(Collections.emptyList());
|
||||
|
||||
// when
|
||||
MovieTimeListDTO movieTimeListDto = movieTimeService.getMovieTimes(any(), LocalDate.now());
|
||||
List<MovieTimeDTO> movieTimeDtos = movieTimeService.getMovieTimes(any(), LocalDate.now());
|
||||
|
||||
// then
|
||||
assertTrue(movieTimeListDto.getMovieTimeDtos().isEmpty());
|
||||
assertTrue(movieTimeDtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -76,10 +88,82 @@ public class MovieTimeServiceImplTest {
|
||||
.thenReturn(movieTimes);
|
||||
|
||||
// when
|
||||
MovieTimeListDTO movieTimeListDto = movieTimeService.getMovieTimes(any(), LocalDate.of(2022, 07, 01));
|
||||
List<MovieTimeDTO> movieTimeDtos = movieTimeService.getMovieTimes(any(), LocalDate.of(2022, 07, 01));
|
||||
|
||||
// then
|
||||
assertTrue(!movieTimeListDto.getMovieTimeDtos().isEmpty());
|
||||
assertTrue(!movieTimeDtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MovieTime Service Test - register movie time")
|
||||
void shouldAbleToRegisterMovieTime() {
|
||||
// given
|
||||
Movie movie = new Movie(title, 100L);
|
||||
Theater theater = new Theater(1);
|
||||
MovieTime movieTime = new MovieTime(movie, theater, 1, startAt);
|
||||
|
||||
when(movieRepository.findByIdAndDeletedAtNull(anyLong()))
|
||||
.thenReturn(Optional.of(movie));
|
||||
|
||||
when(theaterRepository.findByTheaterNumber(anyInt()))
|
||||
.thenReturn(Optional.of(theater));
|
||||
|
||||
when(movieTimeRepository.findByMovieAndTheaterAndRoundAndDeletedAtNull(any(), any(), anyInt()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
when(movieTimeRepository.save(any()))
|
||||
.thenReturn(movieTime);
|
||||
|
||||
// when
|
||||
RegisteredMovieTimeDTO registeredMovieTimeDto =
|
||||
movieTimeService.registerMovieTime(
|
||||
new MovieTimeRegisterDTO(1L, 1, 1, startAt)
|
||||
);
|
||||
|
||||
// then
|
||||
assertThat(registeredMovieTimeDto).isNotNull();
|
||||
assertTrue(registeredMovieTimeDto.getTheaterNumber() == 1);
|
||||
assertTrue(registeredMovieTimeDto.getStartAt() == startAt);
|
||||
assertTrue(registeredMovieTimeDto.getRound() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MovieTime Service Test - register movie time when there is same movie time already")
|
||||
void shouldThrowExceptionWhenRegisteringDuplicateMovieTime() {
|
||||
// given
|
||||
Movie movie = new Movie(title, 100L);
|
||||
Theater theater = new Theater(1);
|
||||
MovieTime movieTime = new MovieTime(movie, theater, 1, startAt);
|
||||
MovieTimeRegisterDTO movieTimeRegisterDto = new MovieTimeRegisterDTO(1L, 1, 1, startAt);
|
||||
|
||||
when(movieRepository.findByIdAndDeletedAtNull(anyLong()))
|
||||
.thenReturn(Optional.of(movie));
|
||||
|
||||
when(theaterRepository.findByTheaterNumber(anyInt()))
|
||||
.thenReturn(Optional.of(theater));
|
||||
|
||||
when(movieTimeRepository.findByMovieAndTheaterAndRoundAndDeletedAtNull(any(), any(), anyInt()))
|
||||
.thenReturn(Optional.of(movieTime));
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> movieTimeService.registerMovieTime(movieTimeRegisterDto))
|
||||
.isInstanceOf(TicketingException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MovieTime Service Test - register movie time when there is no such movie")
|
||||
void shouldThrowExceptionWhenRegisteringMovieTimeWithNoSuchMovie() {
|
||||
// given
|
||||
Theater theater = new Theater(1);
|
||||
MovieTimeRegisterDTO movieTimeRegisterDto = new MovieTimeRegisterDTO(1L, 1, 1, startAt);
|
||||
|
||||
when(movieRepository.findByIdAndDeletedAtNull(1L))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> movieTimeService.registerMovieTime(movieTimeRegisterDto))
|
||||
.isInstanceOf(TicketingException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static com.ticketing.server.movie.domain.TicketTest.setupTickets;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.movie.service.dto.TicketIdsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TicketLockServiceTest {
|
||||
|
||||
@Mock
|
||||
TicketRepository ticketRepository;
|
||||
|
||||
@InjectMocks
|
||||
TicketLockService ticketLockService;
|
||||
|
||||
@Test
|
||||
@DisplayName("티켓목록 예약으로 변경 시 조회된 갯수랑 다른 경우")
|
||||
void ticketReservationFail() {
|
||||
// given
|
||||
List<Ticket> tickets = setupTickets();
|
||||
List<Ticket> list = List.of(tickets.get(0), tickets.get(1), tickets.get(2));
|
||||
List<Long> ids = List.of(0L, 1L, 2L, 10000L);
|
||||
TicketIdsDTO ticketIdsDto = new TicketIdsDTO(ids);
|
||||
|
||||
when(ticketRepository.findTicketFetchJoinByTicketIds(ids)).thenReturn(list);
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> ticketLockService.ticketReservation(ticketIdsDto))
|
||||
.isInstanceOf(TicketingException.class)
|
||||
.extracting("errorCode")
|
||||
.isEqualTo(ErrorCode.INVALID_TICKET_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("티켓목록 예약으로 변경 완료")
|
||||
void ticketReservationSuccess() {
|
||||
// given
|
||||
List<Ticket> tickets = setupTickets();
|
||||
List<Ticket> list = List.of(tickets.get(0), tickets.get(1), tickets.get(2));
|
||||
List<Long> ids = List.of(0L, 1L, 2L);
|
||||
TicketIdsDTO ticketIdsDto = new TicketIdsDTO(ids);
|
||||
|
||||
when(ticketRepository.findTicketFetchJoinByTicketIds(ids)).thenReturn(list);
|
||||
|
||||
// when
|
||||
TicketsReservationDTO ticketReservationsDto = ticketLockService.ticketReservation(ticketIdsDto);
|
||||
|
||||
// then
|
||||
assertThat(ticketReservationsDto.getTicketReservationDtoList()).hasSize(3);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.global.exception.TicketingException;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import com.ticketing.server.movie.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.dto.TicketsReservationDTO;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -53,8 +51,7 @@ class TicketServiceImplTest {
|
||||
when(ticketRepository.findTicketFetchJoinByPaymentId(1L)).thenReturn(List.of(tickets.get(0)));
|
||||
|
||||
// when
|
||||
TicketDetailsDTO ticketDetailDto = ticketService.findTicketsByPaymentId(1L);
|
||||
List<TicketDetailDTO> ticketDetails = ticketDetailDto.getTicketDetails();
|
||||
List<TicketDetailDTO> ticketDetails = ticketService.findTicketsByPaymentId(1L);
|
||||
|
||||
// then
|
||||
assertAll(
|
||||
@@ -63,39 +60,4 @@ class TicketServiceImplTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("티켓목록 예약으로 변경 시 조회된 갯수랑 다른 경우")
|
||||
void ticketReservationFail() {
|
||||
// given
|
||||
List<Ticket> tickets = setupTickets();
|
||||
List<Ticket> list = List.of(tickets.get(0), tickets.get(1), tickets.get(2));
|
||||
List<Long> ids = List.of(0L, 1L, 2L, 10000L);
|
||||
|
||||
when(ticketRepository.findTicketFetchJoinByTicketIds(ids)).thenReturn(list);
|
||||
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> ticketService.ticketReservation(ids))
|
||||
.isInstanceOf(TicketingException.class)
|
||||
.extracting("errorCode")
|
||||
.isEqualTo(ErrorCode.INVALID_TICKET_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("티켓목록 예약으로 변경 완료")
|
||||
void ticketReservationSuccess() {
|
||||
// given
|
||||
List<Ticket> tickets = setupTickets();
|
||||
List<Ticket> list = List.of(tickets.get(0), tickets.get(1), tickets.get(2));
|
||||
List<Long> ids = List.of(0L, 1L, 2L);
|
||||
|
||||
when(ticketRepository.findTicketFetchJoinByTicketIds(ids)).thenReturn(list);
|
||||
|
||||
// when
|
||||
TicketsReservationDTO ticketReservationsDto = ticketService.ticketReservation(ids);
|
||||
|
||||
// then
|
||||
assertThat(ticketReservationsDto.getTicketReservationDtoList()).hasSize(3);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.global.redis.RefreshToken;
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.security.jwt.JwtProvider;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -62,7 +62,7 @@ class AuthenticationServiceImplTest {
|
||||
@DisplayName("토큰 재발급 성공")
|
||||
void reissueAccessToken() {
|
||||
// given
|
||||
String refreshToken = "Bearer eyJhbGciOiJIUzUxMiJ9";
|
||||
String refreshToken = "eyJhbGciOiJIUzUxMiJ9";
|
||||
when(jwtProvider.validateToken(any())).thenReturn(true);
|
||||
when(jwtProvider.getAuthentication(any())).thenReturn(authenticationToken);
|
||||
when(jwtProvider.generateTokenDto(any())).thenReturn(useJwtProvider.generateTokenDto(authenticationToken));
|
||||
|
||||
Reference in New Issue
Block a user