Compare commits
45 Commits
feature/cr
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd59423238 | ||
|
|
fb5c34b520 | ||
|
|
12a23667b6 | ||
|
|
45b73509d2 | ||
|
|
22c4fd900b | ||
|
|
1b9dab4a4a | ||
|
|
50bc3b97dc | ||
|
|
4005dad9ac | ||
|
|
43674f8f66 | ||
|
|
d80a370232 | ||
|
|
12f1d6b9be | ||
|
|
db5e8272b6 | ||
|
|
9780a84609 | ||
|
|
7283eeb5d3 | ||
|
|
0521b85dd9 | ||
|
|
b836598be3 | ||
|
|
0173fc92ed | ||
|
|
73cc0241d3 | ||
|
|
720c495b51 | ||
|
|
bd7b761636 | ||
|
|
c9c4201920 | ||
|
|
16eed0cbed | ||
|
|
8d5f179647 | ||
|
|
fca765e9c3 | ||
|
|
3ea3b88b1f | ||
|
|
09cb4a3767 | ||
|
|
648638860c | ||
|
|
6f14c96931 | ||
|
|
e009c2786c | ||
|
|
cb79ec5e57 | ||
|
|
d0af7e4444 | ||
|
|
ab32f435b1 | ||
|
|
a5cc6f2513 | ||
|
|
9ddfc24d2f | ||
|
|
8d9a86df64 | ||
|
|
69fe793afa | ||
|
|
928958dd45 | ||
|
|
a235983475 | ||
|
|
183e61188e | ||
|
|
d5eac621ca | ||
|
|
270edc20b5 | ||
|
|
2b249e3be9 | ||
|
|
0c26555665 | ||
|
|
9f70ee0ed9 | ||
|
|
38365de76c |
9
.idea/Ticketing.iml
generated
Normal file
9
.idea/Ticketing.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Ticketing.iml" filepath="$PROJECT_DIR$/.idea/Ticketing.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
10
.idea/runConfigurations.xml
generated
Normal file
10
.idea/runConfigurations.xml
generated
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RunConfigurationProducerService">
|
||||
<option name="ignoredProducers">
|
||||
<set>
|
||||
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
|
||||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
33
.idea/workspace.xml
generated
Normal file
33
.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="2a93e153-a90c-44db-b1da-6c4424693422" name="Changes" comment="" />
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="ProjectId" id="29uM8tIDp7UqdPYE3auX216NPaN" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent">
|
||||
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
|
||||
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
|
||||
</component>
|
||||
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="2a93e153-a90c-44db-b1da-6c4424693422" name="Changes" comment="" />
|
||||
<created>1653958362269</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1653958362269</updated>
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
</project>
|
||||
59
README.md
59
README.md
@@ -1,5 +1,5 @@
|
||||
# 🍿 Ticketing
|
||||
영화 예매 서비스
|
||||
영화 예매 사이트를 대용량 트래픽에 대응할 수 있도록 설계.
|
||||
|
||||
<br/>
|
||||
|
||||
@@ -8,32 +8,59 @@
|
||||
- 기획 및 설계 : 22.04.13 ~
|
||||
- 프로젝트 구현 :
|
||||
|
||||
<br/>
|
||||
|
||||
<br/><br/>
|
||||
## 🎯 프로젝트 주요 관심사
|
||||
- OOP(객체 지향 프로그래밍)의 장점을 최대한 활용
|
||||
- 테스트 코드를 통한 믿을 수 있는 코드 작성
|
||||
- 대용량 트래픽을 고려한 확장 가능한 설계 및 성능 튜닝
|
||||
- 코드리뷰를 통해 코드 품질 향상
|
||||
- 코드 컨벤션 준수하여 코드 통일성 유지
|
||||
|
||||
## 🎯 프로젝트 목표
|
||||
<br/>
|
||||
|
||||
## 🛠 기술스택
|
||||
- Java 11
|
||||
- Spring Boot 2.6.7 (당시 최신 GA 버전)
|
||||
- Gradle Kotlin DSL
|
||||
- Spring Security
|
||||
- Junit 5
|
||||
- Hibernate / SpringJPA
|
||||
- MySQL 8.0
|
||||
- Redis
|
||||
|
||||
<br/><br/>
|
||||
<br/>
|
||||
|
||||
## Wiki
|
||||
- [Git Branch 전략](https://github.com/f-lab-edu/Ticketing/wiki#-git-branch-%EC%A0%84%EB%9E%B5)
|
||||
- [Code Convention](https://github.com/f-lab-edu/Ticketing/wiki#-code-convention)
|
||||
- [패키지 구조](https://github.com/f-lab-edu/Ticketing/wiki#-%ED%8C%A8%ED%82%A4%EC%A7%80-%EA%B5%AC%EC%A1%B0)
|
||||
- [Use Case](https://github.com/f-lab-edu/Ticketing/wiki/Use-Case)
|
||||
- [Prototype](https://github.com/f-lab-edu/Ticketing/wiki/Prototype)
|
||||
- [Issue Posting](https://github.com/f-lab-edu/Ticketing/wiki/Issue-Posting)
|
||||
|
||||
<br/>
|
||||
|
||||
## 🧩 ERD
|
||||
|
||||
``` mermaid
|
||||
erDiagram
|
||||
MOVIE ||--o{ MOVIE_TIMES : ""
|
||||
MOVIE ||--o{ MOVIE_TIME : ""
|
||||
MOVIE {
|
||||
bigint id PK "영화 ID"
|
||||
varchar title "영화제목"
|
||||
int running_time "러닝타임"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
THEATER ||--o{ MOVIE_TIMES : ""
|
||||
THEATER ||--o{ MOVIE_TIME : ""
|
||||
THEATER ||--|{ SEAT : ""
|
||||
THEATER {
|
||||
bigint id PK "상영관 ID"
|
||||
int theater_number "상영관 번호"
|
||||
int seat_count "좌석수"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
@@ -43,56 +70,58 @@ erDiagram
|
||||
bigint theater_id FK "상영관 ID"
|
||||
int column "열"
|
||||
int row "행"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
MOVIE_TIMES ||--o{ TICKET : ""
|
||||
MOVIE_TIMES {
|
||||
MOVIE_TIME ||--o{ TICKET : ""
|
||||
MOVIE_TIME {
|
||||
bigint id PK "상영시간표 ID"
|
||||
bigint movie_id FK "영화 ID"
|
||||
bigint theater_id FK "상영관 ID"
|
||||
date running_date "상영 날짜"
|
||||
int round "회차"
|
||||
time start_at "시작 시간"
|
||||
time end_at "종료 시간"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
TICKET {
|
||||
bigint id PK "티켓 ID"
|
||||
bigint seat_id FK "좌석 ID"
|
||||
bigint movie_times_id FK "상영시간표 ID"
|
||||
bigint payment_id FK "결제 ID"
|
||||
bigint movie_time_id FK "상영시간표 ID"
|
||||
bigint payment_id "결제 ID"
|
||||
varchar status "상태 - 구매가능/예약진행중/판매완료"
|
||||
int ticket_price "가격"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "등록일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
TICKET }|--|| PAYMENT : ""
|
||||
PAYMENT {
|
||||
bigint id PK "결제 ID"
|
||||
bigint user_id FK "유저ID"
|
||||
bigint user_alternate_id "유저 대체ID"
|
||||
varchar movie_title "영화제목"
|
||||
varchar type "결제 타입 - 예) 네이버페이, 카카오페이"
|
||||
varchar status "상태 - 완료/환불/실패"
|
||||
varchar failed_message "실패사유 - 컬럼명을 알아보기 쉬운가?"
|
||||
varchar payment_number "예매번호"
|
||||
int total_price "결제 금액"
|
||||
datetime deleted_at "삭제일시"
|
||||
datetime created_at "결제일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
USER ||--o{ PAYMENT : ""
|
||||
USER {
|
||||
bigint id "회원"
|
||||
bigint alternate_id "대체ID"
|
||||
varchar name "이름"
|
||||
varchar email "이메일"
|
||||
varchar password "비밀번호"
|
||||
varchar grade "등급 - 고객/임직원"
|
||||
varchar phone "휴대폰 번호"
|
||||
boolean is_deleted "탈퇴여부"
|
||||
datetime deleted_at "탈퇴일시"
|
||||
datetime created_at "가입일시"
|
||||
datetime updated_at "수정일시"
|
||||
}
|
||||
```
|
||||
|
||||
<br/><br/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## 작업 내용
|
||||
## 작업 분류
|
||||
- [ ] 기능 추가
|
||||
- [ ] 코드 수정
|
||||
- [ ] 환경 설정
|
||||
@@ -30,4 +30,3 @@
|
||||
- [ ] 구현 사항에 대한 테스트를 완료했습니다.
|
||||
- [ ] 의도한 내용 이외에 다른 코드에는 변경 사항이 없는지 확인했습니다.
|
||||
- [ ] 코드 스타일을 적용하여 팀 코딩 컨벤션에 맞게 작성했습니다.
|
||||
- [ ] 팀원 모두 구현 내용 및 코드에 대해 이해하고 있습니다.
|
||||
@@ -23,17 +23,22 @@ repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")
|
||||
implementation("org.springframework.boot:spring-boot-starter-log4j2")
|
||||
implementation("com.lmax:disruptor:3.4.2")
|
||||
implementation("org.projectlombok:lombok:1.18.24")
|
||||
implementation("io.springfox:springfox-boot-starter:3.0.0")
|
||||
implementation("io.springfox:springfox-swagger-ui:3.0.0")
|
||||
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")
|
||||
implementation("com.lmax:disruptor:3.4.4")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.11.5")
|
||||
implementation("com.googlecode.json-simple:json-simple:1.1.1")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-redis")
|
||||
implementation("com.google.code.findbugs:jsr305:3.0.2")
|
||||
|
||||
modules {
|
||||
module("org.springframework.boot:spring-boot-starter-logging") {
|
||||
@@ -43,8 +48,12 @@ dependencies {
|
||||
|
||||
compileOnly("org.projectlombok:lombok")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.5")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.5")
|
||||
annotationProcessor("org.projectlombok:lombok")
|
||||
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
|
||||
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
}
|
||||
@@ -52,3 +61,28 @@ dependencies {
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
create("intTest") {
|
||||
compileClasspath += sourceSets.main.get().output
|
||||
runtimeClasspath += sourceSets.main.get().output
|
||||
}
|
||||
}
|
||||
|
||||
val intTestImplementation by configurations.getting {
|
||||
extendsFrom(configurations.implementation.get())
|
||||
}
|
||||
|
||||
configurations["intTestRuntimeOnly"].extendsFrom(configurations.runtimeOnly.get())
|
||||
configurations["intTestImplementation"].extendsFrom(configurations.testImplementation.get())
|
||||
|
||||
val integrationTest = task<Test>("integrationTest") {
|
||||
description = "Runs integration tests."
|
||||
group = "verification"
|
||||
|
||||
testClassesDirs = sourceSets["intTest"].output.classesDirs
|
||||
classpath = sourceSets["intTest"].runtimeClasspath
|
||||
shouldRunAfter("test")
|
||||
}
|
||||
|
||||
tasks.check { dependsOn(integrationTest) }
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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 RefreshRedisRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
refreshRedisRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 조회기능")
|
||||
void saveAndFind() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
|
||||
// when
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken findRefreshToken = refreshRedisRepository.findById(refreshToken.getId()).get();
|
||||
assertAll(
|
||||
() -> assertThat(findRefreshToken.getEmail()).isEqualTo("ticketing@gmail.com")
|
||||
, () -> assertThat(findRefreshToken.getToken()).isEqualTo("refreshToken")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 이메일 조회")
|
||||
void saveAndFindByEmail() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
|
||||
// when
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken findRefreshToken = refreshRedisRepository.findByEmail(refreshToken.getEmail()).get();
|
||||
assertAll(
|
||||
() -> assertThat(findRefreshToken.getEmail()).isEqualTo("ticketing@gmail.com")
|
||||
, () -> assertThat(findRefreshToken.getToken()).isEqualTo("refreshToken")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 수정기능")
|
||||
void saveAndSave() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
Long id = refreshToken.getId();
|
||||
|
||||
// when
|
||||
RefreshToken savedRefreshToken = refreshRedisRepository.findById(id).get();
|
||||
savedRefreshToken.changeToken("refreshToken2");
|
||||
refreshRedisRepository.save(savedRefreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken lastSavedRefreshToken = refreshRedisRepository.findById(id).get();
|
||||
assertThat(lastSavedRefreshToken.getToken()).isEqualTo("refreshToken2");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
public class MovieTest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import java.util.Optional;
|
||||
import javax.transaction.Transactional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.Rollback;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class MovieRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
MovieRepository movieRepository;
|
||||
|
||||
@Order(1)
|
||||
@Test
|
||||
@Rollback(value = false)
|
||||
@DisplayName("Movie Repository Test - saving movie")
|
||||
void shouldAbleToSaveMovie() {
|
||||
// given
|
||||
Movie movie = new Movie("범죄도시 2", 106L);
|
||||
|
||||
// when
|
||||
Movie savedMovie = movieRepository.save(movie);
|
||||
|
||||
// then
|
||||
assertEquals(movie.getTitle(), savedMovie.getTitle());
|
||||
}
|
||||
|
||||
@Order(2)
|
||||
@Test
|
||||
@DisplayName("Movie Repository Test - finding movie with title")
|
||||
void ShouldAbleToFindMovieWithTitle() {
|
||||
// given, when
|
||||
Optional<Movie> optionalMovie = movieRepository.findByTitle("범죄도시 2");
|
||||
|
||||
// then
|
||||
assertTrue(optionalMovie.isPresent());
|
||||
}
|
||||
|
||||
@Order(3)
|
||||
@Test
|
||||
@DisplayName("Movie Repository Test - finding movie that doesn't exist")
|
||||
void ShouldNotAbleToFindMovie() {
|
||||
// given, when
|
||||
Optional<Movie> optionalMovie = movieRepository.findByTitle("존재하지 않는 영화");
|
||||
|
||||
// then
|
||||
assertFalse(optionalMovie.isPresent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
public class MovieTimesRepositoryTest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
public class SeatRepositoryTest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import javax.transaction.Transactional;
|
||||
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
|
||||
@Transactional
|
||||
public class TheaterRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
TheaterRepository theaterRepository;
|
||||
|
||||
@Test
|
||||
@DisplayName("Theater Repository Test - saving theater")
|
||||
void ShouldAbleToSaveTheater() {
|
||||
// given
|
||||
Theater theater = new Theater(1);
|
||||
|
||||
// when
|
||||
Theater savedTheater = theaterRepository.save(theater);
|
||||
|
||||
// then
|
||||
assertEquals(theater.getTheaterNumber(), savedTheater.getTheaterNumber());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
public class TicketRepositoryTest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@SpringBootTest
|
||||
public class TMDBServiceImplTest {
|
||||
|
||||
@Value("${tmdb.api-key}")
|
||||
private String apiKey;
|
||||
|
||||
@Value("${tmdb.read-access-token}")
|
||||
private String readAccessToken;
|
||||
|
||||
@Autowired
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
@DisplayName("TMDB Service Test - Get [Now Playing] movies")
|
||||
void shouldAbleToGetMovieList() throws Exception {
|
||||
// given
|
||||
assertNotNull(apiKey);
|
||||
assertNotNull(readAccessToken);
|
||||
|
||||
ArrayList<Charset> acceptCharset = new ArrayList<>();
|
||||
acceptCharset.add(StandardCharsets.UTF_8);
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAcceptCharset(acceptCharset);
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setBearerAuth(readAccessToken);
|
||||
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("api_key", apiKey);
|
||||
params.put("language", "ko");
|
||||
|
||||
HttpEntity<?> request = new HttpEntity<>(headers);
|
||||
|
||||
// when
|
||||
ResponseEntity<?> response = restTemplate.exchange(
|
||||
"https://api.themoviedb.org/3/movie/now_playing?" + mapToUrlParam(params),
|
||||
HttpMethod.GET,
|
||||
request,
|
||||
String.class
|
||||
);
|
||||
|
||||
// JSONParser parser = new JSONParser();
|
||||
// Object obj = parser.parse(String.valueOf(response));
|
||||
// Object results = ((JSONObject) obj).get("results");
|
||||
//
|
||||
// ArrayList<String> movieList = new ArrayList<>();
|
||||
//
|
||||
// ArrayList<JSONObject> jsonMovieList = new ArrayList<>();
|
||||
|
||||
// then
|
||||
assertTrue(response.getStatusCode().is2xxSuccessful());
|
||||
}
|
||||
|
||||
private static String mapToUrlParam(Map<String, String> params) {
|
||||
StringBuffer paramData = new StringBuffer();
|
||||
|
||||
for (Map.Entry<String, String> param : params.entrySet()) {
|
||||
if (paramData.length() != 0) {
|
||||
paramData.append('&');
|
||||
}
|
||||
|
||||
paramData.append(param.getKey());
|
||||
paramData.append('=');
|
||||
paramData.append(param.getValue());
|
||||
}
|
||||
|
||||
return paramData.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
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;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
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.SignUpRequest;
|
||||
import com.ticketing.server.user.service.interfaces.UserService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.http.MediaType;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
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
|
||||
@Transactional
|
||||
class AuthControllerTest {
|
||||
|
||||
private static final String LOGIN_URL = "/api/auth/token";
|
||||
private static final String REGISTER_URL = "/api/users";
|
||||
private static final String USER_EMAIL = "ticketing@gmail.com";
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext context;
|
||||
|
||||
@Autowired
|
||||
UserService userService;
|
||||
|
||||
@Autowired
|
||||
PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
MockMvc mvc;
|
||||
|
||||
@Test
|
||||
@DisplayName("로그인 인증 성공")
|
||||
void loginSuccess() throws Exception {
|
||||
// given
|
||||
LoginRequest request = new LoginRequest(USER_EMAIL, "qwe123");
|
||||
|
||||
// when
|
||||
ResultActions actions = mvc.perform(post(LOGIN_URL)
|
||||
.content(asJsonString(request))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
// then
|
||||
actions.andDo(print())
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("로그인 패스워드 인증 실패")
|
||||
void loginPasswordFail() throws Exception {
|
||||
// given
|
||||
LoginRequest request = new LoginRequest(USER_EMAIL, "qwe1234");
|
||||
|
||||
// when
|
||||
ResultActions actions = mvc.perform(post(LOGIN_URL)
|
||||
.content(asJsonString(request))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
// then
|
||||
actions.andDo(print())
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
|
||||
SignUpRequest signUpRequest = new SignUpRequest("ticketing", USER_EMAIL, "qwe123", "010-1234-5678");
|
||||
|
||||
mvc.perform(post(REGISTER_URL)
|
||||
.content(asJsonString(signUpRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
refreshRedisRepository.deleteAll();
|
||||
}
|
||||
|
||||
private String asJsonString(Object object) throws JsonProcessingException {
|
||||
return objectMapper.writeValueAsString(object);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UserControllerTest {
|
||||
|
||||
}
|
||||
37
server/src/intTest/resources/application.yml
Normal file
37
server/src/intTest/resources/application.yml
Normal file
@@ -0,0 +1,37 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/ticketing_test?serverTimezone=Asia/Seoul&characterEncoding=UTF-8
|
||||
username: ENC(LowN1n4w0Ep/DqLD8+q5Bq6AXM4b8e3V)
|
||||
password: ENC(OMvGcpZLpggFTiGNkqNe66Zq/SmJXF6o)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
show_sql: true
|
||||
format_sql: true
|
||||
hibernate:
|
||||
ddl-auto: create
|
||||
|
||||
mvc:
|
||||
pathmatch:
|
||||
matching-strategy: ant_path_matcher
|
||||
|
||||
jasypt:
|
||||
encryptor:
|
||||
bean: jasyptStringEncryptor
|
||||
|
||||
jwt:
|
||||
access-header: Authorization
|
||||
refresh-header: REFRESH_TOKEN
|
||||
prefix: Bearer
|
||||
secret-key: Zi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXktZi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXkK
|
||||
access-token-validity-in-seconds: 60
|
||||
refresh-token-validity-in-seconds: 259200
|
||||
|
||||
tmdb:
|
||||
api-key: 0d1503b6dcbfe1c514299b5564c649b8
|
||||
read-access-token: eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwZDE1MDNiNmRjYmZlMWM1MTQyOTliNTU2NGM2NDliOCIsInN1YiI6IjYyOWYwODRlNzI2ZmIxMTA2NDA4MjI2NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.rs8KZea8QLyashILiggWFx2s46lgUtzo-xSWoDgE58A
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.ticketing.server;
|
||||
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
|
||||
@EnableJpaAuditing
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties(JwtProperties.class)
|
||||
public class ServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.time.Duration;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.BufferingClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
|
||||
return restTemplateBuilder
|
||||
.requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
|
||||
.setConnectTimeout(Duration.ofMillis(5000)) // connection-timeout
|
||||
.setReadTimeout(Duration.ofMillis(5000)) // read-timeout
|
||||
.additionalMessageConverters(new StringHttpMessageConverter(Charset.forName("UTF-8")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
|
||||
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
|
||||
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
|
||||
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
|
||||
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.StringUtils;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiKey;
|
||||
import springfox.documentation.service.AuthorizationScope;
|
||||
import springfox.documentation.service.SecurityReference;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger.web.UiConfiguration;
|
||||
import springfox.documentation.swagger.web.UiConfigurationBuilder;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class SwaggerConfig {
|
||||
|
||||
@Bean
|
||||
public Docket api() {
|
||||
return new Docket(DocumentationType.OAS_30).useDefaultResponseMessages(false).select()
|
||||
.apis(RequestHandlerSelectors.any()).paths(PathSelectors.ant("/api/**")).build()
|
||||
.securityContexts(Arrays.asList(securityContext()))
|
||||
.securitySchemes(Arrays.asList(apiKey()));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
|
||||
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
|
||||
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
|
||||
allEndpoints.addAll(webEndpoints);
|
||||
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
|
||||
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
|
||||
String basePath = webEndpointProperties.getBasePath();
|
||||
EndpointMapping endpointMapping = new EndpointMapping(basePath);
|
||||
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
|
||||
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
|
||||
}
|
||||
|
||||
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
|
||||
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
|
||||
}
|
||||
|
||||
private ApiKey apiKey() {
|
||||
return new ApiKey(SECURITY_SCHEMA_NAME, "Authorization", "header");
|
||||
}
|
||||
|
||||
private SecurityContext securityContext() {
|
||||
return SecurityContext.builder().securityReferences(defaultAuth()).build();
|
||||
}
|
||||
|
||||
public static final String SECURITY_SCHEMA_NAME = "Authorization";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL = "global";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL_DESC = "accessEverything";
|
||||
|
||||
private List<SecurityReference> defaultAuth() {
|
||||
AuthorizationScope authorizationScope = new AuthorizationScope(AUTHORIZATION_SCOPE_GLOBAL,
|
||||
AUTHORIZATION_SCOPE_GLOBAL_DESC);
|
||||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||
authorizationScopes[0] = authorizationScope;
|
||||
return Arrays.asList(new SecurityReference(SECURITY_SCHEMA_NAME, authorizationScopes));
|
||||
}
|
||||
|
||||
@Bean
|
||||
UiConfiguration uiConfig() {
|
||||
return UiConfigurationBuilder.builder()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors().disable()
|
||||
.csrf().disable()
|
||||
.formLogin().disable()
|
||||
.headers().frameOptions().disable();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -19,13 +19,15 @@ public abstract class AbstractEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
protected Long id;
|
||||
|
||||
@Column(nullable = false, updatable = false)
|
||||
@CreatedDate
|
||||
private LocalDateTime createdAt;
|
||||
protected LocalDateTime createdAt;
|
||||
|
||||
@LastModifiedDate
|
||||
private LocalDateTime updatedAt;
|
||||
protected LocalDateTime updatedAt;
|
||||
|
||||
protected LocalDateTime deletedAt;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.ticketing.server.global.exception;
|
||||
|
||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||
import static org.springframework.http.HttpStatus.CONFLICT;
|
||||
import static org.springframework.http.HttpStatus.FORBIDDEN;
|
||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ErrorCode {
|
||||
|
||||
/* 400 BAD_REQUEST : 잘못된 요청 */
|
||||
MISMATCH_PASSWORD(BAD_REQUEST, "비밀번호가 일치하지 않습니다."),
|
||||
TOKEN_TYPE(BAD_REQUEST, "토큰 타입이 올바르지 않습니다."),
|
||||
UNAVAILABLE_REFRESH_TOKEN(BAD_REQUEST, "사용할 수 없는 토큰 입니다."),
|
||||
UNABLE_CHANGE_GRADE(BAD_REQUEST, "동일한 등급으로 변경할 수 없습니다."),
|
||||
|
||||
/* 403 FORBIDDEN : 접근 권한 제한 */
|
||||
VALID_USER_ID(FORBIDDEN, "해당 정보에 접근 권한이 존재하지 않습니다."),
|
||||
|
||||
/* 404 NOT_FOUND : Resource 를 찾을 수 없음 */
|
||||
USER_NOT_FOUND(NOT_FOUND, "해당 유저 정보를 찾을 수 없습니다."),
|
||||
EMAIL_NOT_FOUND(NOT_FOUND, "해당 이메일을 찾을 수 없습니다."),
|
||||
MOVIE_NOT_FOUND(NOT_FOUND, "해당 제목의 영화를 찾을 수 없습니다."),
|
||||
REFRESH_TOKEN_NOT_FOUND(NOT_FOUND, "리프레쉬 토큰을 찾을 수 없습니다."),
|
||||
PAYMENT_ID_NOT_FOUND(NOT_FOUND, "결제정보를 찾을 수 없습니다."),
|
||||
THEATER_NOT_FOUND(NOT_FOUND, "상영관 정보를 찾을 수 없습니다."),
|
||||
|
||||
/* 409 CONFLICT : Resource 의 현재 상태와 충돌. 보통 중복된 데이터 존재 */
|
||||
DUPLICATE_EMAIL(CONFLICT, "이메일이 이미 존재합니다."),
|
||||
DUPLICATE_PAYMENT(CONFLICT, "해당 좌석은 현재 판매된 좌석입니다."),
|
||||
DUPLICATE_MOVIE(CONFLICT, "해당 영화 정보가 이미 존재합니다."),
|
||||
DUPLICATE_MOVIE_TIME(CONFLICT, "해당 영화 시간표 정보가 이미 존재합니다."),
|
||||
DELETED_EMAIL(CONFLICT, "이미 삭제된 이메일 입니다."),
|
||||
DELETED_MOVIE(CONFLICT, "이미 삭제된 영화 입니다.");
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
private final String detail;
|
||||
|
||||
/* 400 BAD_REQUEST : 잘못된 요청 */
|
||||
public static TicketingException throwMismatchPassword() {
|
||||
throw new TicketingException(MISMATCH_PASSWORD);
|
||||
}
|
||||
|
||||
public static TicketingException throwTokenType() {
|
||||
throw new TicketingException(TOKEN_TYPE);
|
||||
}
|
||||
|
||||
public static TicketingException throwUnavailableRefreshToken() {
|
||||
throw new TicketingException(UNAVAILABLE_REFRESH_TOKEN);
|
||||
}
|
||||
|
||||
public static TicketingException throwUnableChangeGrade() {
|
||||
throw new TicketingException(UNABLE_CHANGE_GRADE);
|
||||
}
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
public static TicketingException throwMovieNotFound() {
|
||||
throw new TicketingException(MOVIE_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwRefreshTokenNotFound() {
|
||||
throw new TicketingException(REFRESH_TOKEN_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwPaymentIdNotFound() {
|
||||
throw new TicketingException(PAYMENT_ID_NOT_FOUND);
|
||||
}
|
||||
|
||||
public static TicketingException throwTheaterNotFound() {
|
||||
throw new TicketingException(THEATER_NOT_FOUND);
|
||||
}
|
||||
|
||||
/* 409 CONFLICT : Resource 의 현재 상태와 충돌. 보통 중복된 데이터 존재 */
|
||||
public static TicketingException throwDuplicateEmail() {
|
||||
throw new TicketingException(DUPLICATE_EMAIL);
|
||||
}
|
||||
|
||||
public static TicketingException throwDuplicatePayment() {
|
||||
throw new TicketingException(DUPLICATE_PAYMENT);
|
||||
}
|
||||
|
||||
public static TicketingException throwDuplicateMovie() {
|
||||
throw new TicketingException(DUPLICATE_MOVIE);
|
||||
}
|
||||
|
||||
public static TicketingException throwDuplicateMovieTime() {
|
||||
throw new TicketingException(DUPLICATE_MOVIE_TIME);
|
||||
}
|
||||
|
||||
public static TicketingException throwDeletedEmail() {
|
||||
throw new TicketingException(DELETED_EMAIL);
|
||||
}
|
||||
|
||||
public static TicketingException throwDeletedMovie() {
|
||||
throw new TicketingException(DELETED_MOVIE);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ticketing.server.global.exception;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
@Getter
|
||||
@EqualsAndHashCode
|
||||
public class ErrorResponse {
|
||||
|
||||
private final HttpStatus status;
|
||||
private final String message;
|
||||
private final List<String> errors;
|
||||
|
||||
public ErrorResponse(HttpStatus status, String message, List<String> errors) {
|
||||
this.status = status;
|
||||
this.message = message;
|
||||
this.errors = errors;
|
||||
}
|
||||
|
||||
public ErrorResponse(HttpStatus status, String message, String error) {
|
||||
this.status = status;
|
||||
this.message = message;
|
||||
this.errors = List.of(error);
|
||||
}
|
||||
|
||||
public static ErrorResponse toErrorResponse(ErrorCode errorCode) {
|
||||
return new ErrorResponse(
|
||||
errorCode.getHttpStatus(),
|
||||
errorCode.name(),
|
||||
errorCode.getDetail());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package com.ticketing.server.global.exception;
|
||||
|
||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||
import static org.springframework.http.HttpStatus.FORBIDDEN;
|
||||
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED;
|
||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
|
||||
import static org.springframework.http.HttpStatus.UNSUPPORTED_MEDIA_TYPE;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.TypeMismatchException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
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.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.validation.ObjectError;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.support.MissingServletRequestPartException;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
/* 400 START */
|
||||
|
||||
/**
|
||||
* Valid 유효성 검사 실패
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleMethodArgumentNotValid(
|
||||
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("MethodArgumentNotValidException :: ", ex);
|
||||
|
||||
List<String> errors = generateErrors(ex);
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), errors);
|
||||
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/***
|
||||
* ModelAttribute 으로 binding error 발생
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleBindException(
|
||||
BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("BindException :: ", ex);
|
||||
|
||||
List<String> errors = generateErrors(ex);
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), errors);
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 잘못된 유형으로 Bean 속성 설정
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleTypeMismatch(
|
||||
TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("TypeMismatchException :: ", ex);
|
||||
|
||||
String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), error);
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* multipart/form-data 요청 실패
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleMissingServletRequestPart(
|
||||
MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("MissingServletRequestPartException :: ", ex);
|
||||
|
||||
String error = ex.getRequestPartName() + " part is missing";
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), error);
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 필수 인수 누락
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleMissingServletRequestParameter(
|
||||
MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("MissingServletRequestParameterException :: ", ex);
|
||||
|
||||
String error = ex.getParameterName() + " parameter is missing";
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), error);
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인수가 예상한 형식이 아닐 시
|
||||
*/
|
||||
@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
|
||||
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex) {
|
||||
log.error("MethodArgumentTypeMismatchException :: ", ex);
|
||||
|
||||
String error = ex.getName() + " should be of type " + Objects.requireNonNull(ex.getRequiredType()).getName();
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), error);
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 제약 조건 위반
|
||||
*/
|
||||
@ExceptionHandler(value = ConstraintViolationException.class)
|
||||
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex) {
|
||||
log.error("ConstraintViolationException :: ", ex);
|
||||
|
||||
List<String> errors = new ArrayList<>();
|
||||
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
|
||||
errors.add(violation.getRootBeanClass().getName() + " " + violation.getPropertyPath() + ": " + violation.getMessage());
|
||||
}
|
||||
|
||||
ErrorResponse response = new ErrorResponse(BAD_REQUEST, ex.getLocalizedMessage(), errors);
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/* 400 END */
|
||||
|
||||
/**
|
||||
* 404 발생
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleNoHandlerFoundException(
|
||||
NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("NoHandlerFoundException :: ", ex);
|
||||
|
||||
String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();
|
||||
ErrorResponse response = new ErrorResponse(NOT_FOUND, ex.getLocalizedMessage(), error);
|
||||
return ResponseEntity.status(response.getStatus()).headers(headers).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지원하지 않는 HTTP 메서드로 요청 405
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(
|
||||
HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("HttpRequestMethodNotSupportedException :: ", ex);
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(ex.getMethod());
|
||||
builder.append(" method is not supported for this request. Supported methods are ");
|
||||
|
||||
Set<HttpMethod> supportedHttpMethods = ex.getSupportedHttpMethods();
|
||||
if (supportedHttpMethods != null) {
|
||||
supportedHttpMethods.forEach(t -> builder.append(t).append(" "));
|
||||
}
|
||||
|
||||
ErrorResponse response = new ErrorResponse(METHOD_NOT_ALLOWED, ex.getLocalizedMessage(), builder.toString());
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지원되지 않는 미디어 유형으로 요청 415
|
||||
*/
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
|
||||
HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
|
||||
log.error("HttpMediaTypeNotSupportedException :: ", ex);
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(ex.getContentType());
|
||||
builder.append(" media type is not supported. Supported media types are ");
|
||||
ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(" "));
|
||||
|
||||
ErrorResponse response = new ErrorResponse(UNSUPPORTED_MEDIA_TYPE, ex.getLocalizedMessage(), builder.substring(0, builder.length() - 2));
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 핸들러 없는 모든 예외 500
|
||||
*/
|
||||
@ExceptionHandler(value = Exception.class)
|
||||
protected ResponseEntity<Object> handleAll(Exception ex) {
|
||||
log.error("Exception :: ", ex);
|
||||
|
||||
ErrorResponse response = new ErrorResponse(INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "오류가 발생했습니다.");
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 접근 권한이 없을 때
|
||||
*/
|
||||
@ExceptionHandler(value = AccessDeniedException.class)
|
||||
protected ResponseEntity<ErrorResponse> handleAccessDeniedException(Exception ex) {
|
||||
log.error("AccessDeniedException :: ", ex);
|
||||
|
||||
ErrorResponse response = new ErrorResponse(FORBIDDEN, ex.getLocalizedMessage(), "접근 권한이 없습니다.");
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 정보가 없을 때
|
||||
*/
|
||||
@ExceptionHandler(value = AuthenticationException.class)
|
||||
protected ResponseEntity<ErrorResponse> handleAuthenticationException(Exception ex) {
|
||||
log.error("AuthenticationException :: ", ex);
|
||||
|
||||
ErrorResponse response = new ErrorResponse(UNAUTHORIZED, ex.getLocalizedMessage(), "로그인 후 이용하실 수 있습니다.");
|
||||
return ResponseEntity.status(response.getStatus()).headers(new HttpHeaders()).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 예외 발생 시
|
||||
*/
|
||||
@ExceptionHandler(value = TicketingException.class)
|
||||
protected ResponseEntity<ErrorResponse> ticketingException(TicketingException ex) {
|
||||
log.error("TicketingException :: ", ex);
|
||||
|
||||
ErrorCode errorCode = ex.getErrorCode();
|
||||
return ResponseEntity.status(errorCode.getHttpStatus()).body(ErrorResponse.toErrorResponse(errorCode));
|
||||
}
|
||||
|
||||
private List<String> generateErrors(BindException ex) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
|
||||
|
||||
for (ObjectError error : allErrors) {
|
||||
errors.add(error.getDefaultMessage());
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.ticketing.server.global.exception;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class TicketingException extends RuntimeException {
|
||||
|
||||
private final ErrorCode errorCode;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ticketing.server.global.factory;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Properties;
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.env.PropertiesPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.support.EncodedResource;
|
||||
import org.springframework.core.io.support.PropertySourceFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
||||
|
||||
@Override
|
||||
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) {
|
||||
Properties yamlProperties = loadYamlProperties(resource);
|
||||
String sourceName = StringUtils.hasText(name) ? name : resource.getResource().getFilename();
|
||||
return new PropertiesPropertySource(Objects.requireNonNull(sourceName), Objects.requireNonNull(yamlProperties));
|
||||
}
|
||||
|
||||
private Properties loadYamlProperties(EncodedResource resource) {
|
||||
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
||||
factory.setResources(resource.getResource());
|
||||
return factory.getObject();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
@Configuration
|
||||
@EnableRedisRepositories
|
||||
public class RedisConfig {
|
||||
|
||||
@Value("${spring.redis.host}")
|
||||
private String host;
|
||||
|
||||
@Value("${spring.redis.port}")
|
||||
private int port;
|
||||
|
||||
@Bean
|
||||
public RedisConnectionFactory redisConnectionFactory() {
|
||||
return new LettuceConnectionFactory(host, port);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate() {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory());
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new StringRedisSerializer());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
return new JpaTransactionManager();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface RefreshRedisRepository extends CrudRepository<RefreshToken, Long> {
|
||||
|
||||
Optional<RefreshToken> findByEmail(String email);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.redis.core.RedisHash;
|
||||
import org.springframework.data.redis.core.index.Indexed;
|
||||
|
||||
@Getter
|
||||
@RedisHash("RefreshToken")
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class RefreshToken {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
@Column(name = "refresh_token_id")
|
||||
private Long id;
|
||||
|
||||
@Indexed
|
||||
private String email;
|
||||
private String token;
|
||||
|
||||
public RefreshToken(String email, String token) {
|
||||
this.email = email;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public void changeToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ticketing.server.global.security;
|
||||
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.AccessDecisionManager;
|
||||
import org.springframework.security.access.AccessDecisionVoter;
|
||||
import org.springframework.security.access.annotation.Jsr250Voter;
|
||||
import org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice;
|
||||
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
|
||||
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
|
||||
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter;
|
||||
import org.springframework.security.access.vote.AffirmativeBased;
|
||||
import org.springframework.security.access.vote.AuthenticatedVoter;
|
||||
import org.springframework.security.access.vote.RoleHierarchyVoter;
|
||||
import org.springframework.security.access.vote.RoleVoter;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
|
||||
@EnableGlobalMethodSecurity(
|
||||
securedEnabled = true,
|
||||
jsr250Enabled = true,
|
||||
prePostEnabled = true
|
||||
)
|
||||
@Configuration
|
||||
public class RoleConfig extends GlobalMethodSecurityConfiguration {
|
||||
|
||||
@Override
|
||||
protected AccessDecisionManager accessDecisionManager() {
|
||||
List<AccessDecisionVoter<?>> decisionVoters = new ArrayList<>();
|
||||
ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
|
||||
expressionAdvice.setExpressionHandler(getExpressionHandler());
|
||||
decisionVoters.add(new PreInvocationAuthorizationAdviceVoter(expressionAdvice));
|
||||
decisionVoters.add(new Jsr250Voter());
|
||||
|
||||
decisionVoters.add(new RoleVoter());
|
||||
decisionVoters.add(roleHierarchyVoter());
|
||||
decisionVoters.add(new AuthenticatedVoter());
|
||||
return new AffirmativeBased(decisionVoters);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RoleHierarchyVoter roleHierarchyVoter() {
|
||||
return new RoleHierarchyVoter(roleHierarchy());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RoleHierarchy roleHierarchy() {
|
||||
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
|
||||
roleHierarchy.setHierarchy(UserGrade.getRoleHierarchy());
|
||||
return roleHierarchy;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ticketing.server.global.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public class SecurityUtil {
|
||||
|
||||
private SecurityUtil() {
|
||||
}
|
||||
|
||||
public static String getCurrentUserEmail() {
|
||||
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null || authentication.getName() == null) {
|
||||
throw new IllegalStateException("Security Context 에 인증 정보가 없습니다.");
|
||||
}
|
||||
|
||||
return authentication.getName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ticketing.server.global.security;
|
||||
|
||||
import com.ticketing.server.global.security.jwt.JwtFilter;
|
||||
import com.ticketing.server.global.security.jwt.JwtSecurityConfig;
|
||||
import com.ticketing.server.global.security.jwt.handle.JwtAccessDeniedHandler;
|
||||
import com.ticketing.server.global.security.jwt.handle.JwtAuthenticationEntryPoint;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
private final JwtFilter jwtFilter;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
|
||||
http
|
||||
.csrf().disable()
|
||||
.exceptionHandling()
|
||||
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||
|
||||
.and()
|
||||
.headers()
|
||||
.frameOptions()
|
||||
.sameOrigin()
|
||||
|
||||
// 시큐리티는 기본적으로 세션을 사용하지만, jwt 을 위해 세션을 Stateless 로 설정
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers(HttpMethod.POST, "/api/auth/token").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/api/auth/refresh").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/api/users").permitAll()
|
||||
.antMatchers(HttpMethod.GET,"/api/movies").permitAll()
|
||||
.antMatchers("/api/movieTimes/**").permitAll()
|
||||
.antMatchers("/l7check").permitAll()
|
||||
.antMatchers("/actuator/**").permitAll()
|
||||
.antMatchers("/api/v3/", "/swagger-ui/**", "/swagger/", "/swagger-resources/**", "/v3/api-docs").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.apply(new JwtSecurityConfig(jwtFilter));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class JwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtProvider tokenProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
|
||||
public JwtFilter(JwtProperties jwtProperties, JwtProvider tokenProvider) {
|
||||
this.jwtProperties = jwtProperties;
|
||||
this.tokenProvider = tokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
String jwt = resolveToken(request);
|
||||
|
||||
// 토큰이 정상이면 Authentication 을 가져와서 SecurityContext 에 저장
|
||||
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
|
||||
Authentication authentication = tokenProvider.getAuthentication(jwt);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String bearerToken = request.getHeader(jwtProperties.getAccessHeader());
|
||||
if (StringUtils.hasText(bearerToken) && jwtProperties.hasTokenStartsWith(bearerToken)) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
|
||||
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.ConstructorBinding;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@ConstructorBinding
|
||||
@ConfigurationProperties(value = "jwt")
|
||||
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||
public class JwtProperties {
|
||||
|
||||
private final String accessHeader;
|
||||
private final String refreshHeader;
|
||||
private final String prefix;
|
||||
private final String secretKey;
|
||||
private final Integer accessTokenValidityInSeconds;
|
||||
private final Integer refreshTokenValidityInSeconds;
|
||||
|
||||
public boolean hasTokenStartsWith(String token) {
|
||||
return token.startsWith(prefix);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
|
||||
import com.ticketing.server.user.service.dto.TokenDTO;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import java.security.Key;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class JwtProvider {
|
||||
|
||||
private static final String AUTHORITIES_KEY = "auth";
|
||||
private static final String AUTHORITIES_DELIMITER = ",";
|
||||
|
||||
private final Key key;
|
||||
private final String prefix;
|
||||
private final long accessTokenValidityInMilliseconds;
|
||||
private final long refreshTokenValidityInMilliseconds;
|
||||
|
||||
public JwtProvider(JwtProperties jwtProperties) {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getSecretKey());
|
||||
this.key = Keys.hmacShaKeyFor(keyBytes);
|
||||
|
||||
this.prefix = jwtProperties.getPrefix();
|
||||
this.accessTokenValidityInMilliseconds = jwtProperties.getAccessTokenValidityInSeconds() * 1000L;
|
||||
this.refreshTokenValidityInMilliseconds = jwtProperties.getRefreshTokenValidityInSeconds() * 1000L;
|
||||
}
|
||||
|
||||
public TokenDTO generateTokenDto(Authentication authentication) {
|
||||
String accessToken = createAccessToken(authentication);
|
||||
String refreshToken = createRefreshToken(authentication);
|
||||
long expiresIn = accessTokenValidityInMilliseconds / 1000L;
|
||||
|
||||
return new TokenDTO(accessToken, refreshToken, prefix, expiresIn);
|
||||
}
|
||||
|
||||
private String createAccessToken(Authentication authentication) {
|
||||
// 만료시간 계산
|
||||
long now = (new Date()).getTime();
|
||||
Date accessTokenExpiresIn = new Date(now + this.accessTokenValidityInMilliseconds);
|
||||
|
||||
return createToken(authentication, accessTokenExpiresIn);
|
||||
}
|
||||
|
||||
private String createRefreshToken(Authentication authentication) {
|
||||
// 만료시간 계산
|
||||
long now = (new Date()).getTime();
|
||||
Date refreshTokenExpiresIn = new Date(now + this.refreshTokenValidityInMilliseconds);
|
||||
|
||||
return createToken(authentication, refreshTokenExpiresIn);
|
||||
}
|
||||
|
||||
private String createToken(Authentication authentication, Date expiration) {
|
||||
// 권한 정보 가져오기
|
||||
String authorities = generateStringToAuthorities(authentication);
|
||||
|
||||
// JWT 생성
|
||||
return Jwts.builder()
|
||||
.setSubject(authentication.getName()) // email
|
||||
.claim(AUTHORITIES_KEY, authorities) // payload
|
||||
.setExpiration(expiration) // 만료일
|
||||
.signWith(key, SignatureAlgorithm.HS512) // 서명 키 값
|
||||
.compact();
|
||||
}
|
||||
|
||||
private String generateStringToAuthorities(Authentication authentication) {
|
||||
StringJoiner authorities = new StringJoiner(AUTHORITIES_DELIMITER);
|
||||
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
|
||||
String roleName = makeRoleName(grantedAuthority.getAuthority());
|
||||
authorities.add(roleName);
|
||||
}
|
||||
return authorities.toString();
|
||||
}
|
||||
|
||||
private String makeRoleName(String role) {
|
||||
return "ROLE_" + role.toUpperCase();
|
||||
}
|
||||
|
||||
public Authentication getAuthentication(String token) {
|
||||
// 토큰 복호화
|
||||
Claims claims = parseClaims(token);
|
||||
|
||||
// 권한조회
|
||||
List<SimpleGrantedAuthority> authorities =
|
||||
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(AUTHORITIES_DELIMITER))
|
||||
.map(SimpleGrantedAuthority::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
UserDetails principal = new User(claims.getSubject(), "", authorities);
|
||||
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
parseClaims(token);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Claims parseClaims(String token) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class JwtSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity builder) {
|
||||
builder.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ticketing.server.global.security.jwt.handle;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
|
||||
@Component("JwtAccessDeniedHandler")
|
||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
private final HandlerExceptionResolver resolver;
|
||||
|
||||
public JwtAccessDeniedHandler(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
|
||||
this.resolver = resolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||
resolver.resolveException(request, response, null, accessDeniedException);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ticketing.server.global.security.jwt.handle;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
|
||||
@Component("JwtAuthenticationEntryPoint")
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
private final HandlerExceptionResolver resolver;
|
||||
|
||||
public JwtAuthenticationEntryPoint(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
|
||||
this.resolver = resolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
|
||||
resolver.resolveException(request, response, null, authException);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ticketing.server.global.validator.constraints;
|
||||
|
||||
import com.ticketing.server.global.validator.constraintvalidators.FieldsValueNotMatchValidator;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@Constraint(validatedBy = FieldsValueNotMatchValidator.class)
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface FieldsValueNotMatch {
|
||||
|
||||
String message() default "validation.password.not.change";
|
||||
|
||||
String field();
|
||||
|
||||
String fieldMatch();
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ticketing.server.global.validator.constraintvalidators;
|
||||
|
||||
import com.ticketing.server.global.validator.constraints.FieldsValueNotMatch;
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import org.springframework.beans.BeanWrapperImpl;
|
||||
|
||||
public class FieldsValueNotMatchValidator implements ConstraintValidator<FieldsValueNotMatch, Object> {
|
||||
|
||||
private String field;
|
||||
private String fieldMatch;
|
||||
|
||||
public void initialize(FieldsValueNotMatch constraintAnnotation) {
|
||||
this.field = constraintAnnotation.field();
|
||||
this.fieldMatch = constraintAnnotation.fieldMatch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(Object value, ConstraintValidatorContext context) {
|
||||
Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
|
||||
Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);
|
||||
|
||||
if (fieldValue != null) {
|
||||
return !fieldValue.equals(fieldMatchValue);
|
||||
} else {
|
||||
return fieldMatchValue != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,73 @@
|
||||
package com.ticketing.server.movie.application;
|
||||
|
||||
import static com.ticketing.server.user.domain.UserGrade.ROLES.STAFF;
|
||||
|
||||
import com.ticketing.server.movie.application.request.MovieDeleteRequest;
|
||||
import com.ticketing.server.movie.application.request.MovieRegisterRequest;
|
||||
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.RegisteredMovieDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import javax.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/movies")
|
||||
@Api(value = "Movie API", tags = {"Movie"})
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieController {
|
||||
|
||||
private final MovieService movieService;
|
||||
|
||||
@PostMapping()
|
||||
@ApiOperation(value = "영화 정보 등록")
|
||||
@Secured(STAFF)
|
||||
public ResponseEntity<MovieInfoResponse> registerMovie(@RequestBody @Valid MovieRegisterRequest request) {
|
||||
RegisteredMovieDTO registeredMovieDto =
|
||||
movieService.registerMovie(request.getTitle(), request.getRunningTime());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
registeredMovieDto.toResponse()
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping()
|
||||
@ApiOperation(value = "영화 목록 조회")
|
||||
public ResponseEntity<MovieListResponse> getMovies() {
|
||||
MovieListDTO movieListDto = movieService.getMovies();
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
movieListDto.toResponse()
|
||||
);
|
||||
}
|
||||
|
||||
@DeleteMapping()
|
||||
@ApiOperation(value = "영화 정보 삭제")
|
||||
@Secured(STAFF)
|
||||
public ResponseEntity<MovieDeleteResponse> deleteMovie(@RequestBody @Valid MovieDeleteRequest request) {
|
||||
DeletedMovieDTO deletedMovieDto = movieService.deleteMovie(request.getId());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
deletedMovieDto.toResponse()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.ticketing.server.movie.application;
|
||||
|
||||
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.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 javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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
|
||||
@RequestMapping("/api/movieTimes")
|
||||
@Api(value = "MovieTime API", tags = {"Movie Time"})
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieTimeController {
|
||||
|
||||
private final MovieTimeService movieTimeService;
|
||||
|
||||
@PostMapping
|
||||
@ApiOperation(value = "영화 시간표 등록")
|
||||
@Secured(STAFF)
|
||||
public ResponseEntity<MovieTimeInfoResponse> registerMovieTime(
|
||||
@RequestBody @Valid MovieTimeRegisterRequest movieTimeRegisterRequest) {
|
||||
RegisteredMovieTimeDTO registeredMovieTimeDto = movieTimeService.registerMovieTime(
|
||||
movieTimeRegisterRequest.toMovieTimeRegisterDTO()
|
||||
);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
registeredMovieTimeDto.toResponse()
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@ApiOperation(value = "영화 시간표 조회")
|
||||
@Validated
|
||||
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);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
movieTimeListDto.toResponse()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.ticketing.server.movie.application;
|
||||
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class MovieTimesController {
|
||||
|
||||
}
|
||||
@@ -1,8 +1,30 @@
|
||||
package com.ticketing.server.movie.application;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/tickets")
|
||||
@Validated
|
||||
public class TicketController {
|
||||
|
||||
private final TicketService ticketService;
|
||||
|
||||
@GetMapping("payments/{paymentId}")
|
||||
public ResponseEntity<TicketDetailsResponse> findTicketsByPaymentId(@PathVariable("paymentId") @NotNull Long paymentId) {
|
||||
TicketDetailsDTO tickets = ticketService.findTicketsByPaymentId(paymentId);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(tickets.toResponse());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ticketing.server.movie.application.request;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MovieDeleteRequest {
|
||||
|
||||
@NotNull(message = "{validation.not.null.id}")
|
||||
private Long id;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.ticketing.server.movie.application.request;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.MovieRegisterDTO;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieRegisterRequest {
|
||||
|
||||
@NotEmpty(message = "{validation.not.empty.title}")
|
||||
private String title;
|
||||
|
||||
@NotNull(message = "{validation.not.null.runningTime}")
|
||||
private Long runningTime;
|
||||
|
||||
public MovieRegisterDTO toMovieRegisterDTO() {
|
||||
return new MovieRegisterDTO(title, runningTime);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ticketing.server.movie.application.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeRegisterDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeRegisterRequest {
|
||||
|
||||
@NotNull(message = "{validation.not.null.movieId}")
|
||||
private Long movieId;
|
||||
|
||||
@NotNull(message = "{validation.not.null.theaterNumber}")
|
||||
private Integer theaterNumber;
|
||||
|
||||
@NotNull(message = "{validation.not.null.round}")
|
||||
private Integer round;
|
||||
|
||||
private LocalDateTime startAt;
|
||||
|
||||
public MovieTimeRegisterDTO toMovieTimeRegisterDTO() {
|
||||
return new MovieTimeRegisterDTO(movieId, theaterNumber, round, startAt);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieDeleteResponse {
|
||||
|
||||
private final Long id;
|
||||
|
||||
private final String title;
|
||||
|
||||
private final LocalDateTime deletedAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieInfoResponse {
|
||||
|
||||
@ApiModelProperty(value = "영화 ID")
|
||||
private Long movieId;
|
||||
|
||||
@ApiModelProperty(value = "영화 제목")
|
||||
private String title;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieListResponse {
|
||||
|
||||
@ApiModelProperty(value = "영화 제목")
|
||||
private List<MovieDTO> movieDtos;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeInfoResponse {
|
||||
|
||||
@ApiModelProperty(value = "영화 시간표 ID")
|
||||
private Long movieTimeId;
|
||||
|
||||
@ApiModelProperty(value = "상영관 번호")
|
||||
private Integer theaterNumber;
|
||||
|
||||
@ApiModelProperty(value = "회차")
|
||||
private Integer round;
|
||||
|
||||
@ApiModelProperty(value = "시작 시간")
|
||||
private LocalDateTime startAt;
|
||||
|
||||
@ApiModelProperty(value = "종료 시간")
|
||||
private LocalDateTime endAt;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import java.util.List;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeListResponse {
|
||||
|
||||
@ApiModelProperty(value = "영화 시간표 정보")
|
||||
private List<MovieTimeDTO> movieTimeDtos;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class TicketDetailsResponse {
|
||||
|
||||
private final List<TicketDetailDTO> ticketDetails;
|
||||
|
||||
public TicketDetailsResponse(List<TicketDetailDTO> ticketDetails) {
|
||||
this.ticketDetails = ticketDetails;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +1,46 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.movie.service.dto.MovieDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import javax.persistence.Entity;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@AllArgsConstructor
|
||||
public class Movie extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
private String title;
|
||||
|
||||
@NotNull
|
||||
private Integer runningTime;
|
||||
private Long runningTime;
|
||||
|
||||
Movie(Long id, String title, Long runningTime) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.runningTime = runningTime;
|
||||
}
|
||||
|
||||
public Movie delete() {
|
||||
if (deletedAt != null) {
|
||||
throw ErrorCode.throwDeletedMovie();
|
||||
}
|
||||
|
||||
deletedAt = LocalDateTime.now();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MovieDTO toMovieDTO() {
|
||||
return new MovieDTO(this.id, this.title);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.movie.service.dto.MovieTimeDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class MovieTime extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "movie_id", referencedColumnName = "id", updatable = false)
|
||||
private Movie movie;
|
||||
|
||||
@NotNull
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "theater_id", referencedColumnName = "id", updatable = false)
|
||||
private Theater theater;
|
||||
|
||||
@NotNull
|
||||
private Integer round;
|
||||
|
||||
@NotNull
|
||||
private LocalDateTime startAt;
|
||||
|
||||
@NotNull
|
||||
private LocalDateTime endAt;
|
||||
|
||||
@OneToMany(mappedBy = "movieTime", cascade = CascadeType.ALL)
|
||||
private List<Ticket> tickets = new ArrayList<>();
|
||||
|
||||
public MovieTime(Movie movie, Theater theater, int round, LocalDateTime startAt) {
|
||||
this.movie = movie;
|
||||
this.theater = theater;
|
||||
this.round = round;
|
||||
this.startAt = startAt;
|
||||
this.endAt = generateEndAt(startAt);
|
||||
}
|
||||
|
||||
MovieTime(Long id, Movie movie, Theater theater, int round, LocalDateTime startAt) {
|
||||
this.id = id;
|
||||
this.movie = movie;
|
||||
this.theater = theater;
|
||||
this.round = round;
|
||||
this.startAt = startAt;
|
||||
this.endAt = generateEndAt(startAt);
|
||||
}
|
||||
|
||||
private LocalDateTime generateEndAt(LocalDateTime startAt) {
|
||||
Long runningTime = movie.getRunningTime();
|
||||
return startAt.plusMinutes(runningTime);
|
||||
}
|
||||
|
||||
public String getMovieTitle() {
|
||||
return this.movie.getTitle();
|
||||
}
|
||||
|
||||
public List<Seat> getSeats() {
|
||||
return this.theater.getSeats();
|
||||
}
|
||||
|
||||
public MovieTimeDTO toMovieTimeDTO() {
|
||||
return new MovieTimeDTO(
|
||||
this.id, this.theater.getTheaterNumber(), this.round, this.startAt, this.endAt);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
public class MovieTimes extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "movie_id", referencedColumnName = "id", updatable = false)
|
||||
private Movie movie;
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "theater_id", referencedColumnName = "id", updatable = false)
|
||||
private Theater theater;
|
||||
|
||||
@NotNull
|
||||
private LocalDate runningDate;
|
||||
|
||||
@NotNull
|
||||
private Integer round;
|
||||
|
||||
@NotNull
|
||||
private LocalDateTime startAt;
|
||||
|
||||
@NotNull
|
||||
private LocalDateTime endAt;
|
||||
|
||||
}
|
||||
@@ -2,17 +2,21 @@ package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class Seat extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "theater_id", referencedColumnName = "id", updatable = false)
|
||||
private Theater theater;
|
||||
|
||||
@@ -22,4 +26,26 @@ public class Seat extends AbstractEntity {
|
||||
@NotNull
|
||||
private Integer seatRow;
|
||||
|
||||
public Seat(Integer seatColumn, Integer seatRow, Theater theater) {
|
||||
this.seatColumn = seatColumn;
|
||||
this.seatRow = seatRow;
|
||||
setTheater(theater);
|
||||
}
|
||||
|
||||
Seat(Long id, int column, int row, Theater theater) {
|
||||
this.id = id;
|
||||
this.seatColumn = column;
|
||||
this.seatRow = row;
|
||||
setTheater(theater);
|
||||
}
|
||||
|
||||
private void setTheater(Theater theater) {
|
||||
this.theater = theater;
|
||||
theater.addSeat(this);
|
||||
}
|
||||
|
||||
public Integer getTheaterNumber() {
|
||||
return this.theater.getTheaterNumber();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,17 +1,38 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class Theater extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
private Integer theaterNumber;
|
||||
|
||||
private Integer seatCount;
|
||||
@OneToMany(mappedBy = "theater", cascade = CascadeType.ALL)
|
||||
private List<Seat> seats = new ArrayList<>();
|
||||
|
||||
Theater(Long id, Integer theaterNumber) {
|
||||
this.id = id;
|
||||
this.theaterNumber = theaterNumber;
|
||||
}
|
||||
|
||||
public Theater(Integer theaterNumber) {
|
||||
this.theaterNumber = theaterNumber;
|
||||
}
|
||||
|
||||
public void addSeat(Seat seat) {
|
||||
seats.add(seat);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,35 +1,89 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.payment.domain.Payment;
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import java.time.LocalDateTime;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
import javax.persistence.Enumerated;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class Ticket extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "seat_id", referencedColumnName = "id", updatable = false)
|
||||
private Seat seat;
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "movie_times_id", referencedColumnName = "id", updatable = false)
|
||||
private MovieTimes movieTimes;
|
||||
private MovieTime movieTime;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "payment_id", referencedColumnName = "id", updatable = false)
|
||||
private Payment payment;
|
||||
private Long paymentId;
|
||||
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private TicketStatus status;
|
||||
|
||||
@NotNull
|
||||
private Integer ticketPrice;
|
||||
|
||||
public Ticket(Seat seat, MovieTime movieTime, Integer ticketPrice) {
|
||||
this.seat = seat;
|
||||
this.movieTime = movieTime;
|
||||
this.ticketPrice = ticketPrice;
|
||||
this.status = TicketStatus.SALE;
|
||||
}
|
||||
|
||||
Ticket(Long id, Seat seat, MovieTime movieTime, Integer ticketPrice) {
|
||||
this.id = id;
|
||||
this.seat = seat;
|
||||
this.movieTime = movieTime;
|
||||
this.ticketPrice = ticketPrice;
|
||||
this.status = TicketStatus.SALE;
|
||||
}
|
||||
|
||||
public Integer getColumn() {
|
||||
return this.seat.getSeatColumn();
|
||||
}
|
||||
|
||||
public Integer getRow() {
|
||||
return this.seat.getSeatRow();
|
||||
}
|
||||
|
||||
public LocalDateTime getStartAt() {
|
||||
return this.movieTime.getStartAt();
|
||||
}
|
||||
|
||||
public LocalDateTime getEndAt() {
|
||||
return this.movieTime.getEndAt();
|
||||
}
|
||||
|
||||
public Integer getTheaterNumber() {
|
||||
return this.seat.getTheaterNumber();
|
||||
}
|
||||
|
||||
public String getMovieTitle() {
|
||||
return this.movieTime.getMovieTitle();
|
||||
}
|
||||
|
||||
public void registerPayment(Long id) {
|
||||
if (this.paymentId != null) {
|
||||
throw ErrorCode.throwDuplicatePayment();
|
||||
}
|
||||
|
||||
this.paymentId = id;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import lombok.Getter;
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum TicketStatus {
|
||||
|
||||
SALE("판매가능"),
|
||||
SCHEDULED("환불"),
|
||||
SOLD("판매완료");
|
||||
|
||||
@@ -1,10 +1,29 @@
|
||||
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;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface MovieRepository extends JpaRepository<Movie, Long> {
|
||||
|
||||
Optional<Movie> findByTitle(String title);
|
||||
|
||||
Optional<Movie> findByIdAndDeletedAtNull(Long id);
|
||||
|
||||
@Query(value = "SELECT m "
|
||||
+ "FROM Movie m "
|
||||
+ "WHERE title = :title "
|
||||
+ "AND deleted_at IS NULL")
|
||||
Optional<Movie> findValidMovieWithTitle(String title);
|
||||
|
||||
@Query(value = "SELECT * "
|
||||
+ "FROM movie "
|
||||
+ "WHERE deleted_at IS NULL", nativeQuery = true)
|
||||
List<Movie> findValidMovies();
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface MovieTimeRepository extends JpaRepository<MovieTime, Long> {
|
||||
|
||||
Optional<MovieTime> findByMovieAndTheaterAndRoundAndDeletedAtNull(Movie movie, Theater theater, Integer round);
|
||||
|
||||
@Query(value = "SELECT mt "
|
||||
+ "FROM MovieTime mt "
|
||||
+ "JOIN FETCH mt.movie "
|
||||
+ "WHERE mt.movie = :movie "
|
||||
+ "AND mt.startAt BETWEEN :startOfDay AND :endOfDay ")
|
||||
List<MovieTime> findValidMovieTimes(Movie movie, LocalDateTime startOfDay, LocalDateTime endOfDay);
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.MovieTimes;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface MovieTimesRepository extends JpaRepository<MovieTimes, Long> {
|
||||
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface TheaterRepository extends JpaRepository<Theater, Long> {
|
||||
|
||||
Optional<Theater> findByTheaterNumber(Integer theaterNumber);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface TicketRepository extends JpaRepository<Ticket, Long> {
|
||||
|
||||
@Query(
|
||||
value =
|
||||
"SELECT t "
|
||||
+ "FROM Ticket t "
|
||||
+ "JOIN FETCH t.movieTime mt "
|
||||
+ "JOIN FETCH t.seat s "
|
||||
+ "JOIN FETCH s.theater th "
|
||||
+ "WHERE t.paymentId = :paymentId "
|
||||
)
|
||||
List<Ticket> findTicketFetchJoinByPaymentId(@Param("paymentId") Long paymentId);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,9 +1,62 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
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;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieServiceImpl implements MovieService {
|
||||
|
||||
private final MovieRepository movieRepository;
|
||||
|
||||
@Override
|
||||
public RegisteredMovieDTO registerMovie(String title, Long runningTime) {
|
||||
Optional<Movie> movie = movieRepository.findValidMovieWithTitle(title);
|
||||
|
||||
if(movie.isEmpty()) {
|
||||
Movie newMovie = movieRepository.save(
|
||||
new Movie(title, runningTime)
|
||||
);
|
||||
|
||||
return new RegisteredMovieDTO(newMovie);
|
||||
}
|
||||
|
||||
throw ErrorCode.throwDuplicateMovie();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MovieListDTO getMovies() {
|
||||
List<Movie> movies = movieRepository.findValidMovies();
|
||||
|
||||
List<MovieDTO> movieDtos = movies.stream()
|
||||
.map(movie -> movie.toMovieDTO())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new MovieListDTO(movieDtos);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public DeletedMovieDTO deleteMovie(Long id) {
|
||||
Movie movie = movieRepository.findByIdAndDeletedAtNull(id)
|
||||
.orElseThrow(ErrorCode::throwMovieNotFound);
|
||||
|
||||
Movie deletedMovie = movie.delete();
|
||||
|
||||
return new DeletedMovieDTO(deletedMovie);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
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.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;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieTimeServiceImpl implements MovieTimeService {
|
||||
|
||||
private final MovieRepository movieRepository;
|
||||
|
||||
private final TheaterRepository theaterRepository;
|
||||
|
||||
private final MovieTimeRepository movieTimeRepository;
|
||||
|
||||
@Override
|
||||
public RegisteredMovieTimeDTO registerMovieTime(@Valid MovieTimeRegisterDTO movieTimeRegisterDto) {
|
||||
Movie movie = findMovieById(movieTimeRegisterDto.getMovieId());
|
||||
Theater theater = findTheaterByNumber(movieTimeRegisterDto.getTheaterNumber());
|
||||
int round = movieTimeRegisterDto.getRound();
|
||||
|
||||
Optional<MovieTime> movieTime =
|
||||
movieTimeRepository.findByMovieAndTheaterAndRoundAndDeletedAtNull(movie, theater, round);
|
||||
|
||||
if(movieTime.isEmpty()) {
|
||||
MovieTime newMovieTime = movieTimeRepository.save(
|
||||
new MovieTime(movie, theater, round, movieTimeRegisterDto.getStartAt())
|
||||
);
|
||||
|
||||
return new RegisteredMovieTimeDTO(newMovieTime);
|
||||
}
|
||||
|
||||
throw ErrorCode.throwDuplicateMovieTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MovieTimeListDTO getMovieTimes(Long movieId, LocalDate runningDate) {
|
||||
Movie movie = findMovieById(movieId);
|
||||
|
||||
LocalDateTime startOfDay = runningDate.atStartOfDay().plusHours(6);
|
||||
LocalDateTime endOfDay = startOfDay.plusDays(1);
|
||||
|
||||
List<MovieTime> movieTimes = movieTimeRepository.findValidMovieTimes(movie, startOfDay, endOfDay);
|
||||
|
||||
List<MovieTimeDTO> movieTimeDtos = movieTimes.stream()
|
||||
.map(movieTime -> movieTime.toMovieTimeDTO())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new MovieTimeListDTO(movieTimeDtos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Movie findMovieById(Long movieId) {
|
||||
Movie movie = movieRepository.findByIdAndDeletedAtNull(movieId)
|
||||
.orElseThrow(ErrorCode::throwMovieNotFound);
|
||||
|
||||
return movie;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Theater findTheaterByNumber(Integer theaterNumber) {
|
||||
Theater theater = theaterRepository.findByTheaterNumber(theaterNumber)
|
||||
.orElseThrow(ErrorCode::throwTheaterNotFound);
|
||||
|
||||
return theater;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.movie.service.interfaces.MovieTimesService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class MovieTimesServiceImpl implements MovieTimesService {
|
||||
|
||||
}
|
||||
@@ -1,9 +1,40 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.movie.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
@Validated
|
||||
@Slf4j
|
||||
public class TicketServiceImpl implements TicketService {
|
||||
|
||||
private final TicketRepository ticketRepository;
|
||||
|
||||
@Override
|
||||
public TicketDetailsDTO findTicketsByPaymentId(@NotNull Long paymentId) {
|
||||
List<TicketDetailDTO> ticketDetails = ticketRepository.findTicketFetchJoinByPaymentId(paymentId)
|
||||
.stream()
|
||||
.map(TicketDetailDTO::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (ticketDetails.isEmpty()) {
|
||||
throw ErrorCode.throwPaymentIdNotFound();
|
||||
}
|
||||
|
||||
return new TicketDetailsDTO(ticketDetails);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieDeleteResponse;
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class DeletedMovieDTO {
|
||||
|
||||
private final Long id;
|
||||
|
||||
private final String title;
|
||||
|
||||
private final LocalDateTime deletedAt;
|
||||
|
||||
public DeletedMovieDTO(Movie movie) {
|
||||
this(
|
||||
movie.getId(),
|
||||
movie.getTitle(),
|
||||
movie.getDeletedAt()
|
||||
);
|
||||
}
|
||||
|
||||
public MovieDeleteResponse toResponse() {
|
||||
return new MovieDeleteResponse(id, title, deletedAt);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieDTO {
|
||||
|
||||
private Long movieId;
|
||||
|
||||
private String title;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MovieRegisterDTO {
|
||||
|
||||
@NotEmpty(message = "{validation.not.empty.title}")
|
||||
private String title;
|
||||
|
||||
@NotNull(message = "{validation.not.null.runningTime}")
|
||||
private Long runningTime;
|
||||
|
||||
public Movie toMovie() {
|
||||
return new Movie(this.title, this.runningTime);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeDTO {
|
||||
|
||||
private Long movieTimeId;
|
||||
|
||||
private Integer theaterNumber;
|
||||
|
||||
private Integer round;
|
||||
|
||||
private LocalDateTime startAt;
|
||||
|
||||
private LocalDateTime endAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class MovieTimeRegisterDTO {
|
||||
|
||||
@NotNull(message = "{validation.not.null.movieId}")
|
||||
private Long movieId;
|
||||
|
||||
@NotNull(message = "{validation.not.null.theaterNumber}")
|
||||
private Integer theaterNumber;
|
||||
|
||||
@NotNull(message = "{validation.not.null.round}")
|
||||
private Integer round;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Seoul")
|
||||
private LocalDateTime startAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieInfoResponse;
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class RegisteredMovieDTO {
|
||||
|
||||
private final Long id;
|
||||
|
||||
private final String title;
|
||||
|
||||
public RegisteredMovieDTO(Movie movie) {
|
||||
this(
|
||||
movie.getId(),
|
||||
movie.getTitle()
|
||||
);
|
||||
}
|
||||
|
||||
public MovieInfoResponse toResponse() {
|
||||
return new MovieInfoResponse(id, title);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieTimeInfoResponse;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class RegisteredMovieTimeDTO {
|
||||
|
||||
private final Long movieTimeId;
|
||||
|
||||
private final Integer theaterNumber;
|
||||
|
||||
private final Integer round;
|
||||
|
||||
private final LocalDateTime startAt;
|
||||
|
||||
private final LocalDateTime endAt;
|
||||
|
||||
public RegisteredMovieTimeDTO(MovieTime movieTime) {
|
||||
this(
|
||||
movieTime.getId(),
|
||||
movieTime.getTheater().getTheaterNumber(),
|
||||
movieTime.getRound(),
|
||||
movieTime.getStartAt(),
|
||||
movieTime.getEndAt()
|
||||
);
|
||||
}
|
||||
|
||||
public MovieTimeInfoResponse toResponse() {
|
||||
return new MovieTimeInfoResponse(movieTimeId, theaterNumber, round, startAt, endAt);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
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.RegisteredMovieDTO;
|
||||
|
||||
public interface MovieService {
|
||||
|
||||
RegisteredMovieDTO registerMovie(String title, Long runningTime);
|
||||
|
||||
MovieListDTO getMovies();
|
||||
|
||||
DeletedMovieDTO deleteMovie(Long id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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.MovieTimeRegisterDTO;
|
||||
import com.ticketing.server.movie.service.dto.RegisteredMovieTimeDTO;
|
||||
import java.time.LocalDate;
|
||||
import javax.validation.Valid;
|
||||
|
||||
public interface MovieTimeService {
|
||||
|
||||
RegisteredMovieTimeDTO registerMovieTime(@Valid MovieTimeRegisterDTO movieTimeRegisterDto);
|
||||
|
||||
MovieTimeListDTO getMovieTimes(Long movieId, LocalDate runningDate);
|
||||
|
||||
Movie findMovieById(Long movieId);
|
||||
|
||||
Theater findTheaterByNumber(Integer theaterNumber);
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
public interface MovieTimesService {
|
||||
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public interface TicketService {
|
||||
|
||||
TicketDetailsDTO findTicketsByPaymentId(@NotNull Long paymentId);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ticketing.server.movie.setup;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Profile(value = {"local"})
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class MovieSetupController {
|
||||
|
||||
private final MovieSetupService movieSetupService;
|
||||
|
||||
@PostConstruct
|
||||
public void setup() {
|
||||
movieSetupService.init();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.ticketing.server.movie.setup;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.MovieTime;
|
||||
import com.ticketing.server.movie.domain.Seat;
|
||||
import com.ticketing.server.movie.domain.Theater;
|
||||
import com.ticketing.server.movie.domain.Ticket;
|
||||
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.domain.repository.TicketRepository;
|
||||
import com.ticketing.server.payment.domain.Payment;
|
||||
import com.ticketing.server.payment.domain.PaymentStatus;
|
||||
import com.ticketing.server.payment.domain.PaymentType;
|
||||
import com.ticketing.server.payment.domain.repository.PaymentRepository;
|
||||
import com.ticketing.server.payment.service.dto.CreatePaymentDTO;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class
|
||||
MovieSetupService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final MovieRepository movieRepository;
|
||||
private final MovieTimeRepository movieTimeRepository;
|
||||
private final TheaterRepository theaterRepository;
|
||||
private final TicketRepository ticketRepository;
|
||||
private final PaymentRepository paymentRepository;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Transactional
|
||||
public void init() {
|
||||
initMovie();
|
||||
initTheater();
|
||||
initMovieTime();
|
||||
initTicket();
|
||||
initPayment();
|
||||
}
|
||||
|
||||
private void initMovie() {
|
||||
List<Movie> movies = Arrays.asList(
|
||||
new Movie("탑건: 매버릭", 130L),
|
||||
new Movie("헤어질 결심", 138L),
|
||||
new Movie("마녀2", 137L),
|
||||
new Movie("범죄도시2", 106L),
|
||||
new Movie("버즈 라이트이어", 105L)
|
||||
);
|
||||
|
||||
movieRepository.saveAll(movies);
|
||||
}
|
||||
|
||||
private void initTheater() {
|
||||
List<Theater> theaters = Arrays.asList(
|
||||
new Theater(1),
|
||||
new Theater(2)
|
||||
);
|
||||
|
||||
for (Theater theater : theaters) {
|
||||
for (int col = 1; col <= 2; col++) {
|
||||
for (int row = 1; row <= 10; row++) {
|
||||
new Seat(col, row, theater);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
theaterRepository.saveAll(theaters);
|
||||
}
|
||||
|
||||
private void initMovieTime() {
|
||||
List<Movie> movies = movieRepository.findAll();
|
||||
List<Theater> theaters = theaterRepository.findAll();
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
List<MovieTime> movieTimes = new ArrayList<>();
|
||||
for (Theater theater : theaters) {
|
||||
movieTimes.add(new MovieTime(movies.get(0), theater, 1, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 8, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(0), theater, 3, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 12, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(1), theater, 2, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 10, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(2), theater, 4, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 14, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(0), theater, 5, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 16, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(3), theater, 6, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 18, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(0), theater, 7, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 21, 0)));
|
||||
movieTimes.add(new MovieTime(movies.get(4), theater, 8, LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 23, 0)));
|
||||
}
|
||||
|
||||
movieTimeRepository.saveAll(movieTimes);
|
||||
}
|
||||
|
||||
private void initTicket() {
|
||||
List<MovieTime> movieTimes = movieTimeRepository.findAll();
|
||||
|
||||
List<Ticket> tickets = new ArrayList<>();
|
||||
Integer ticketPrice = 15_000;
|
||||
for (MovieTime movieTime : movieTimes) {
|
||||
for (Seat seat : movieTime.getSeats()) {
|
||||
tickets.add(new Ticket(seat, movieTime, ticketPrice));
|
||||
}
|
||||
}
|
||||
|
||||
ticketRepository.saveAll(tickets);
|
||||
}
|
||||
|
||||
private void initPayment() {
|
||||
User user = userRepository.save(new User(123L, "김동효", "kdhyo98@gmail.com", passwordEncoder.encode("123123"), UserGrade.USER, "010-1234-5678"));
|
||||
|
||||
List<Ticket> tickets = ticketRepository.findAll();
|
||||
Ticket ticket = tickets.get(0);
|
||||
String title = ticket.getMovieTime().getMovie().getTitle();
|
||||
CreatePaymentDTO createPaymentDto = new CreatePaymentDTO(user.getAlternateId(), title, PaymentType.KAKAO_PAY, PaymentStatus.COMPLETED, "2022-0710-4142", 30_000);
|
||||
Payment payment = createPaymentDto.toEntity();
|
||||
|
||||
paymentRepository.save(payment);
|
||||
|
||||
ticket.registerPayment(payment.getId());
|
||||
tickets.get(1).registerPayment(payment.getId());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.ticketing.server.payment.api;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public interface MovieClient {
|
||||
|
||||
TicketDetailsResponse getTicketsByPaymentId(@NotNull Long paymentId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.ticketing.server.payment.api;
|
||||
|
||||
import com.ticketing.server.payment.api.dto.response.UserDetailResponse;
|
||||
|
||||
public interface UserClient {
|
||||
|
||||
UserDetailResponse detail();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ticketing.server.payment.api.dto.response;
|
||||
|
||||
import com.ticketing.server.payment.domain.Payment;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.service.dto.UserDetailDTO;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class UserDetailResponse {
|
||||
|
||||
private final Long userAlternateId;
|
||||
private final String name;
|
||||
private final String email;
|
||||
private final UserGrade grade;
|
||||
private final String phone;
|
||||
|
||||
public UserDetailResponse(UserDetailDTO userDetailDto) {
|
||||
this(
|
||||
userDetailDto.getAlternateId(),
|
||||
userDetailDto.getName(),
|
||||
userDetailDto.getEmail(),
|
||||
userDetailDto.getGrade(),
|
||||
userDetailDto.getPhone()
|
||||
);
|
||||
}
|
||||
|
||||
public boolean hasUserAlternateId(Payment payment) {
|
||||
return userAlternateId.equals(payment.getUserAlternateId());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticketing.server.payment.api.impl;
|
||||
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.movie.service.dto.TicketDetailsDTO;
|
||||
import com.ticketing.server.movie.service.interfaces.TicketService;
|
||||
import com.ticketing.server.payment.api.MovieClient;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class MovieClientImpl implements MovieClient {
|
||||
|
||||
private final TicketService ticketService;
|
||||
|
||||
@Override
|
||||
public TicketDetailsResponse getTicketsByPaymentId(@NotNull Long paymentId) {
|
||||
TicketDetailsDTO ticketDetails = ticketService.findTicketsByPaymentId(paymentId);
|
||||
return ticketDetails.toResponse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ticketing.server.payment.api.impl;
|
||||
|
||||
import com.ticketing.server.payment.api.UserClient;
|
||||
import com.ticketing.server.payment.api.dto.response.UserDetailResponse;
|
||||
import com.ticketing.server.user.service.dto.UserDetailDTO;
|
||||
import com.ticketing.server.user.service.interfaces.UserService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserClientImpl implements UserClient {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@Override
|
||||
public UserDetailResponse detail() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
UserDetails details = (UserDetails) authentication.getPrincipal();
|
||||
|
||||
UserDetailDTO userDetail = userService.findDetailByEmail(details.getUsername());
|
||||
return new UserDetailResponse(userDetail);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,47 @@
|
||||
package com.ticketing.server.payment.application;
|
||||
|
||||
import com.ticketing.server.payment.application.response.PaymentDetailResponse;
|
||||
import com.ticketing.server.payment.application.response.SimplePaymentsResponse;
|
||||
import com.ticketing.server.payment.service.dto.PaymentDetailDTO;
|
||||
import com.ticketing.server.payment.service.dto.SimplePaymentsDTO;
|
||||
import com.ticketing.server.payment.service.interfaces.PaymentApisService;
|
||||
import com.ticketing.server.payment.service.interfaces.PaymentService;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/payments")
|
||||
@Validated
|
||||
public class PaymentController {
|
||||
|
||||
private final PaymentApisService paymentApisService;
|
||||
private final PaymentService paymentService;
|
||||
|
||||
@GetMapping
|
||||
@Secured(UserGrade.ROLES.USER)
|
||||
public ResponseEntity<SimplePaymentsResponse> simplePayments(@NotNull Long userAlternateId) {
|
||||
SimplePaymentsDTO simplePayments = paymentService.findSimplePayments(userAlternateId);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(simplePayments.toResponse());
|
||||
}
|
||||
|
||||
@GetMapping("/detail")
|
||||
@Secured(UserGrade.ROLES.USER)
|
||||
public ResponseEntity<PaymentDetailResponse> detail(@NotNull Long paymentId) {
|
||||
PaymentDetailDTO paymentDetail = paymentApisService.findPaymentDetail(paymentId);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(paymentDetail.toResponse());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ticketing.server.payment.application.response;
|
||||
|
||||
import com.ticketing.server.payment.service.dto.TicketDetailDTO;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class PaymentDetailResponse {
|
||||
|
||||
private Long paymentId;
|
||||
private String movieTitle;
|
||||
private String paymentNumber;
|
||||
private Integer totalPrice;
|
||||
private LocalDateTime createdAt;
|
||||
private List<TicketDetailDTO> tickets;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ticketing.server.payment.application.response;
|
||||
|
||||
import com.ticketing.server.payment.service.dto.SimplePaymentDTO;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class SimplePaymentsResponse {
|
||||
|
||||
private final Long userAlternateId;
|
||||
private final List<SimplePaymentDTO> payments;
|
||||
|
||||
}
|
||||
@@ -1,38 +1,67 @@
|
||||
package com.ticketing.server.payment.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
import javax.persistence.Enumerated;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class Payment extends AbstractEntity {
|
||||
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", referencedColumnName = "id", updatable = false)
|
||||
private User user;
|
||||
@Column(name = "user_alternate_id", nullable = false)
|
||||
private Long userAlternateId;
|
||||
|
||||
@NotEmpty
|
||||
@Column(name = "movie_title", nullable = false)
|
||||
private String movieTitle;
|
||||
|
||||
@NotNull
|
||||
@Column(name = "type", nullable = false)
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
private PaymentType type;
|
||||
|
||||
@NotNull
|
||||
@Column(name = "status", nullable = false)
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
private PaymentStatus status;
|
||||
|
||||
@Column(name = "failed_message")
|
||||
private String failedMessage;
|
||||
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
@Column(name = "payment_number", nullable = false)
|
||||
private String paymentNumber;
|
||||
|
||||
@NotNull
|
||||
@Column(name = "total_price", nullable = false)
|
||||
private Integer totalPrice;
|
||||
|
||||
public Payment(Long userAlternateId, String movieTitle, PaymentType type, PaymentStatus status, String paymentNumber, Integer totalPrice) {
|
||||
this.userAlternateId = userAlternateId;
|
||||
this.movieTitle = movieTitle;
|
||||
this.type = type;
|
||||
this.status = status;
|
||||
this.paymentNumber = paymentNumber;
|
||||
this.totalPrice = totalPrice;
|
||||
}
|
||||
|
||||
Payment(Long id, Long userAlternateId, String movieTitle, PaymentType type, PaymentStatus status, String paymentNumber, Integer totalPrice) {
|
||||
this.id = id;
|
||||
this.userAlternateId = userAlternateId;
|
||||
this.movieTitle = movieTitle;
|
||||
this.type = type;
|
||||
this.status = status;
|
||||
this.paymentNumber = paymentNumber;
|
||||
this.totalPrice = totalPrice;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package com.ticketing.server.payment.domain.repository;
|
||||
|
||||
import com.ticketing.server.payment.domain.Payment;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface PaymentRepository extends JpaRepository<Payment, Long> {
|
||||
|
||||
List<Payment> findByUserAlternateId(Long userId);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ticketing.server.payment.service;
|
||||
|
||||
import com.ticketing.server.global.exception.ErrorCode;
|
||||
import com.ticketing.server.movie.application.response.TicketDetailsResponse;
|
||||
import com.ticketing.server.payment.api.MovieClient;
|
||||
import com.ticketing.server.payment.api.UserClient;
|
||||
import com.ticketing.server.payment.api.dto.response.UserDetailResponse;
|
||||
import com.ticketing.server.payment.domain.Payment;
|
||||
import com.ticketing.server.payment.domain.repository.PaymentRepository;
|
||||
import com.ticketing.server.payment.service.dto.PaymentDetailDTO;
|
||||
import com.ticketing.server.payment.service.interfaces.PaymentApisService;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
@Validated
|
||||
@Slf4j
|
||||
public class PaymentApisServiceImpl implements PaymentApisService {
|
||||
|
||||
private final PaymentRepository paymentRepository;
|
||||
private final MovieClient movieClient;
|
||||
private final UserClient userClient;
|
||||
|
||||
@Override
|
||||
public PaymentDetailDTO findPaymentDetail(@NotNull Long paymentId) {
|
||||
Payment payment = paymentRepository.findById(paymentId)
|
||||
.orElseThrow(ErrorCode::throwPaymentIdNotFound);
|
||||
|
||||
UserDetailResponse userDetail = userClient.detail();
|
||||
if (!userDetail.hasUserAlternateId(payment)) {
|
||||
throw ErrorCode.throwValidUserId();
|
||||
}
|
||||
|
||||
TicketDetailsResponse tickets = movieClient.getTicketsByPaymentId(payment.getId());
|
||||
return new PaymentDetailDTO(payment, tickets);
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user