Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Entity 생성, h2 및 JPA 환경설정 #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.gradle
build
.idea
*.yml
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비밀번호를 제외한 정보들은 서비스 운영에 필요하지 않을까요?


2 changes: 2 additions & 0 deletions api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ java {

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Expand Down
18 changes: 18 additions & 0 deletions api/src/main/java/org/onewayticket/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.onewayticket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

/**
* TossPaymentController에서 사용되는 restTemplate
*
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import lombok.RequiredArgsConstructor;
import org.onewayticket.dto.BookingDetailsDto;
import org.onewayticket.dto.BookingRequestDto;
import org.onewayticket.dto.BookingResponseDto;
import org.onewayticket.security.AuthService;
import org.onewayticket.service.BookingService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand All @@ -15,78 +18,65 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/bookings")
public class BookingController {

private final BookingService bookingService;
private final AuthService authService;

// 예약 생성
@PostMapping
public ResponseEntity<BookingDetailsDto> createBooking(@RequestBody BookingRequestDto bookingRequestInfo) {
if (bookingRequestInfo.paymentId() == null || bookingRequestInfo.paymentId().isBlank() || !bookingRequestInfo.paymentId().equals("Confirmed")) {
public ResponseEntity<BookingDetailsDto> createBooking(@RequestBody BookingRequestDto bookingRequestInfo,
@PathVariable String flightId) {

// 결제 정보 검증
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

검증은 어디서 할 것인가?

if (bookingRequestInfo.paymentKey() == null || bookingRequestInfo.paymentKey().isBlank()) {
return ResponseEntity.status(400).build();
}

return ResponseEntity.ok(new BookingDetailsDto("A1234", bookingRequestInfo.bookingName(), bookingRequestInfo.bookingEmail(), bookingRequestInfo.bookingPhoneNumber(),
bookingRequestInfo.flightId(), "ICN", "NRT", LocalDate.of(2023, 12, 1), LocalDate.of(2023, 12, 1), "Jane Doe",
LocalDate.parse(bookingRequestInfo.birthDate()), 25, "Female", "AB123456", "Korean", "12A", "Economy", BigDecimal.valueOf(500), "Confirmed"));
bookingService.createBooking(bookingRequestInfo, flightId);
return ResponseEntity.status(HttpStatus.CREATED).build();

}

@GetMapping
public ResponseEntity<BookingDetailsDto> getBookingDetails(
@RequestParam("bookingId") String bookingId,
@RequestParam("name") String name,
@RequestParam("birthDate") String birthDate) {

// 날짜 유효성 검증
if (!isValidDate(birthDate)) {
return ResponseEntity.badRequest().body(null);
}
public ResponseEntity<BookingResponseDto> getBookingDetails(
@RequestParam("referenceCode") String referenceCode,
@RequestParam("bookingEmail") String bookingEmail) {

// 미리 정의된 예약 정보
BookingDetailsDto bookingDetails = new BookingDetailsDto(
"B1234", "John Doe", "[email protected]", "123456789",
"FL123", "ICN", "NRT", LocalDate.of(2023, 12, 1), LocalDate.of(2023, 12, 1),
name, LocalDate.parse(birthDate), 25, "Female", "AB123456", "Korean", "12A", "Economy",
BigDecimal.valueOf(500), "Confirmed");

BookingDetailsDto bookingDetailsDto = bookingService.getBookingDetails(referenceCode);

// bookingId가 일치하지 않을 경우 예외 처리
if (!bookingDetails.bookingId().equals(bookingId)) {
if (!bookingDetailsDto.referenceCode().equals(referenceCode)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}

return ResponseEntity.ok(bookingDetails);
}
String token = authService.generateToken(referenceCode, bookingEmail);

// record 인스턴스 생성
BookingResponseDto responseDto = new BookingResponseDto(token, bookingDetailsDto);

// DTO 반환
return ResponseEntity.ok(responseDto);

}

// 예약 취소
@DeleteMapping("/{id}")
public ResponseEntity<String> cancelBooking(
@PathVariable String id,
@RequestHeader(value = "Authorization", required = false) String authHeader) {
@RequestHeader(value = "Authorization", required = true) String token) {

// 토큰 검증
if (authHeader == null || !authHeader.equals("Bearer VALID_TOKEN")) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // 메시지 없이 401 반환
try {
bookingService.cancelBooking(id, token);
} catch (Exception e) {
return ResponseEntity.status(400).build();
}

// 200 OK와 함께 예약 ID 반환
return ResponseEntity.ok("Booking with ID " + id + " has been canceled successfully.");
}


// 오늘 이후 날짜이거나 입력 값이 맞는지 확인
private boolean isValidDate(String date) {
try {
LocalDate parsedDate = LocalDate.parse(date); // 기본 포맷 yyyy-MM-dd
return !parsedDate.isAfter(LocalDate.now()); // 오늘 이후 날짜인지 확인
} catch (DateTimeParseException e) {
return false; // 형식이 잘못된 경우 false 반환
}
}


Expand Down
94 changes: 20 additions & 74 deletions api/src/main/java/org/onewayticket/controller/FlightController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,112 +2,58 @@

import lombok.RequiredArgsConstructor;
import org.onewayticket.dto.FlightDto;
import org.onewayticket.service.FlightService;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.NoSuchElementException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/flights")
public class FlightController {
private final FlightService flightService;

@GetMapping("/cheapest")
public ResponseEntity<List<FlightDto>> getCheapestFlights() {
// 더미 데이터 9개 생성
List<FlightDto> flights = List.of(
new FlightDto("FL001", BigDecimal.valueOf(50), LocalDateTime.now(), "ICN", "NRT",
LocalDateTime.now().plusHours(2), LocalDateTime.now().plusHours(4), Duration.ofHours(2)),
new FlightDto("FL002", BigDecimal.valueOf(70), LocalDateTime.now(), "ICN", "HND",
LocalDateTime.now().plusHours(3), LocalDateTime.now().plusHours(5), Duration.ofHours(2)),
new FlightDto("FL003", BigDecimal.valueOf(80), LocalDateTime.now(), "ICN", "KIX",
LocalDateTime.now().plusHours(4), LocalDateTime.now().plusHours(6), Duration.ofHours(2)),
new FlightDto("FL004", BigDecimal.valueOf(100), LocalDateTime.now(), "ICN", "LAX",
LocalDateTime.now().plusHours(5), LocalDateTime.now().plusHours(16), Duration.ofHours(11)),
new FlightDto("FL005", BigDecimal.valueOf(120), LocalDateTime.now(), "ICN", "JFK",
LocalDateTime.now().plusHours(6), LocalDateTime.now().plusHours(20), Duration.ofHours(14)),
new FlightDto("FL006", BigDecimal.valueOf(150), LocalDateTime.now(), "ICN", "CDG",
LocalDateTime.now().plusHours(7), LocalDateTime.now().plusHours(19), Duration.ofHours(12)),
new FlightDto("FL007", BigDecimal.valueOf(200), LocalDateTime.now(), "ICN", "SYD",
LocalDateTime.now().plusHours(8), LocalDateTime.now().plusHours(18), Duration.ofHours(10)),
new FlightDto("FL008", BigDecimal.valueOf(300), LocalDateTime.now(), "ICN", "FRA",
LocalDateTime.now().plusHours(9), LocalDateTime.now().plusHours(22), Duration.ofHours(13)),
new FlightDto("FL009", BigDecimal.valueOf(350), LocalDateTime.now(), "ICN", "SIN",
LocalDateTime.now().plusHours(10), LocalDateTime.now().plusHours(16), Duration.ofHours(6))
);

// 가격 기준으로 정렬 후 상위 9개 반환
return ResponseEntity.ok(flights.stream()
.sorted((f1, f2) -> f1.price().compareTo(f2.price()))
.limit(9)
.toList());
List<FlightDto> flightDtos = flightService.getCheapestFlights();
return ResponseEntity.ok(flightDtos);
}

// 검색결과 보여줄 필터 추가
@GetMapping("/search")
public ResponseEntity<List<FlightDto>> searchFlights(
@RequestParam("departure") String departure,
@RequestParam("origin") String origin,
@RequestParam("destination") String destination,
@RequestParam("departureDate") String departureDate,
@RequestParam("numberOfPassengers") Integer numberOfPassengers,
@RequestParam(value = "sort", defaultValue = "price") String sort) {

// 출발지와 목적지가 같은 경우
if (departure.equalsIgnoreCase(destination)) {
return ResponseEntity.badRequest().body(List.of());
}

// 예제 데이터 생성
List<FlightDto> flights = List.of(
new FlightDto("FL001", BigDecimal.valueOf(50), LocalDateTime.now(), departure, destination,
LocalDateTime.now().plusHours(2), LocalDateTime.now().plusHours(4), Duration.ofHours(2)),
new FlightDto("FL002", BigDecimal.valueOf(70), LocalDateTime.now(), departure, destination,
LocalDateTime.now().plusHours(3), LocalDateTime.now().plusHours(5), Duration.ofHours(2)),
new FlightDto("FL003", BigDecimal.valueOf(120), LocalDateTime.now(), departure, destination,
LocalDateTime.now().plusHours(4), LocalDateTime.now().plusHours(6), Duration.ofHours(2))
);

// 정렬 로직 추가
List<FlightDto> sortedFlights = flights.stream()
.sorted((f1, f2) -> {
switch (sort) {
case "price":
default:
return f1.price().compareTo(f2.price());
case "arrivalTime":
return f1.arrivalTime().compareTo(f2.arrivalTime());
case "flightDuration":
return f1.flightDuration().compareTo(f2.flightDuration());

}
})
.toList();

return ResponseEntity.ok(sortedFlights);
List<FlightDto> flightDtoList = flightService.searchFlights(origin, destination, departureDate, sort);
return ResponseEntity.ok(flightDtoList);
}


@GetMapping("/{flightId}")
public ResponseEntity<FlightDto> getFlightDetails(@PathVariable String flightId) {
if (flightId.length() > 50) { // flightId 유효성 검사
public ResponseEntity<?> getFlightDetails(@PathVariable String flightId) {

// 유효성 검사
if (flightId.length() > 50 || flightId == null || flightId.isBlank()) {
return ResponseEntity.badRequest().build();
}

if ("FL001".equals(flightId)) {
return ResponseEntity.ok(new FlightDto(
"FL001", BigDecimal.valueOf(50), LocalDateTime.now(), "ICN", "NRT",
LocalDateTime.now().plusHours(2), LocalDateTime.now().plusHours(4), Duration.ofHours(2)
));
try {
FlightDto flightDto = flightService.getFlightDetails(flightId);
return ResponseEntity.ok(flightDto);
} catch (NoSuchElementException e) {
// flightId에 해당하는 항공편이 없을 경우 404 Not Found 반환
return ResponseEntity.notFound().build();
}
return ResponseEntity.notFound().build();
}
}



}
Loading