Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/main/java/com/example/triptalk/TriptalkApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableJpaAuditing
@EnableScheduling
@SpringBootApplication
public class TriptalkApplication {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.triptalk.domain.tripPlan.controller;

import com.example.triptalk.domain.tripPlan.dto.FlightResponse;
import com.example.triptalk.domain.tripPlan.service.FlightService;
import com.example.triptalk.global.apiPayload.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/flights")
@RequiredArgsConstructor
@Tag(name = "항공권 API", description = "추천 항공권 조회 (매주 업데이트)")
public class FlightController {

private final FlightService flightService;

@GetMapping
@Operation(
summary = "추천 항공권 조회",
description = """
**다양한 인기 노선의 항공권을 조회합니다.**

### 📅 데이터 업데이트
- 매주 월요일 새벽 3시 자동 업데이트
- 항상 7일 후 출발 항공권 제공
- 총 60개 이상 노선 (노선당 최대 3개)
- Amadeus API 실시간 가격 정보 (매주 업데이트)
- 자동 환율 변환 (EUR, USD 등 → KRW)

### 🌍 제공 노선
- **국내선**: 김포-제주, 인천-제주, 김포-부산, 인천-부산, 김포-대구 등
- **일본**: 도쿄, 오사카, 후쿠오카, 삿포로, 오키나와 등
- **중국**: 상하이, 베이징, 광저우, 선전, 시안 등
- **동남아**: 방콕, 싱가포르, 다낭, 발리, 세부, 푸켓 등
- **미주**: 뉴욕, LA, 샌프란시스코, 시애틀, 괌, 하와이 등
- **유럽**: 런던, 파리, 로마, 바르셀로나, 이스탄불 등
- **오세아니아**: 시드니, 멜버른, 오클랜드 등

### 📊 응답 데이터
- `flightList`: 항공권 목록 (최대 10개씩 페이징)
- `id`: 항공권 ID
- `originName`: 출발지 한국어명 (예: 김포, 인천)
- `destinationName`: 도착지 한국어명 (예: 제주, 나리타)
- `airlineName`: 항공사명 + 편명 (예: 대한항공 KE1019)
- `price`: 가격 (원화, KRW) - 모든 통화 자동 변환
- `departureDate/arrivalDate`: 출발/도착 날짜
- `isOutbound` : 출발편 여부 (true: 출발편, false: 귀국편)

"""
)
public ApiResponse<FlightResponse.FlightListResultDTO> getFlights(
@Parameter(description = "커서 ID (다음 페이지 ID, 처음 요청 시 null)", example = "null")
@RequestParam(required = false) Long cursorId
) {
FlightResponse.FlightListResultDTO response = flightService.getFlights(cursorId);
return ApiResponse.onSuccess(response);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package com.example.triptalk.domain.tripPlan.converter;

import com.example.triptalk.domain.tripPlan.dto.AmadeusResponse;
import com.example.triptalk.domain.tripPlan.entity.Flight;
import com.example.triptalk.domain.tripPlan.util.CountryImageMapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class AmadeusConverter {

/**
* Amadeus FlightOffer를 Flight 엔티티로 변환
* @param flightOffer Amadeus API 응답
* @param isOutbound true: 출발편, false: 귀환편
* @param tempId 임시 ID (사용되지 않음, DB 저장 시 자동 생성)
* @return Flight 엔티티
*/
public static Flight toFlight(
AmadeusResponse.FlightOffer flightOffer,
Boolean isOutbound,
Long tempId
) {
// 첫 번째 여정 정보 추출 (출발편 또는 귀환편)
AmadeusResponse.Itinerary itinerary = flightOffer.getItineraries()[isOutbound ? 0 : 1];
AmadeusResponse.Segment firstSegment = itinerary.getSegments()[0];
AmadeusResponse.Segment lastSegment = itinerary.getSegments()[itinerary.getSegments().length - 1];
Comment on lines +25 to +28
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

배열 접근 시 예외 발생 가능성

itineraries 배열이 비어있거나 isOutbound가 false일 때 itinerary가 1개만 있으면 ArrayIndexOutOfBoundsException이 발생합니다. 또한 segments 배열이 비어있을 경우에도 예외가 발생할 수 있습니다.

+        if (flightOffer.getItineraries() == null || flightOffer.getItineraries().length == 0) {
+            throw new IllegalArgumentException("Flight offer has no itineraries");
+        }
+        int itineraryIndex = isOutbound ? 0 : Math.min(1, flightOffer.getItineraries().length - 1);
         // 첫 번째 여정 정보 추출 (출발편 또는 귀환편)
-        AmadeusResponse.Itinerary itinerary = flightOffer.getItineraries()[isOutbound ? 0 : 1];
+        AmadeusResponse.Itinerary itinerary = flightOffer.getItineraries()[itineraryIndex];
+        if (itinerary.getSegments() == null || itinerary.getSegments().length == 0) {
+            throw new IllegalArgumentException("Itinerary has no segments");
+        }
         AmadeusResponse.Segment firstSegment = itinerary.getSegments()[0];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 첫 번째 여정 정보 추출 (출발편 또는 귀환편)
AmadeusResponse.Itinerary itinerary = flightOffer.getItineraries()[isOutbound ? 0 : 1];
AmadeusResponse.Segment firstSegment = itinerary.getSegments()[0];
AmadeusResponse.Segment lastSegment = itinerary.getSegments()[itinerary.getSegments().length - 1];
if (flightOffer.getItineraries() == null || flightOffer.getItineraries().length == 0) {
throw new IllegalArgumentException("Flight offer has no itineraries");
}
int itineraryIndex = isOutbound ? 0 : Math.min(1, flightOffer.getItineraries().length - 1);
// 첫 번째 여정 정보 추출 (출발편 또는 귀환편)
AmadeusResponse.Itinerary itinerary = flightOffer.getItineraries()[itineraryIndex];
if (itinerary.getSegments() == null || itinerary.getSegments().length == 0) {
throw new IllegalArgumentException("Itinerary has no segments");
}
AmadeusResponse.Segment firstSegment = itinerary.getSegments()[0];
AmadeusResponse.Segment lastSegment = itinerary.getSegments()[itinerary.getSegments().length - 1];


// 출발/도착 시간에서 날짜 추출
LocalDate departureDate = parseDateTime(firstSegment.getDeparture().getAt()).toLocalDate();
LocalDate arrivalDate = parseDateTime(lastSegment.getArrival().getAt()).toLocalDate();

// 출발지/도착지
String origin = firstSegment.getDeparture().getIataCode();
String destination = lastSegment.getArrival().getIataCode();

// 항공사 정보 (carrier code + flight number)
String airlineName = String.format("%s %s",
getAirlineName(firstSegment.getCarrierCode()),
firstSegment.getNumber());

// 가격 변환 (통화에 따라 원화로 변환)
Integer price = convertToKRW(
flightOffer.getPrice().getCurrency(),
Double.parseDouble(flightOffer.getPrice().getTotal())
);

// 이미지 URL (도착지 기준)
String imageUrl = CountryImageMapper.getImageUrl(destination);

// DB 저장 시 ID는 자동 생성됨
return Flight.builder()
.origin(origin)
.destination(destination)
.airlineName(airlineName)
.price(price)
.departureDate(departureDate)
.arrivalDate(arrivalDate)
.imageUrl(imageUrl)
.isOutbound(isOutbound)
.build();
}

/**
* 통화를 원화(KRW)로 변환
* @param currency 원본 통화 코드
* @param amount 금액
* @return 원화로 변환된 금액
*/
private static Integer convertToKRW(String currency, Double amount) {
// 환율 (2025년 12월 기준 대략적인 값)
double exchangeRate = switch (currency.toUpperCase()) {
case "KRW" -> 1.0;
case "USD" -> 1350.0; // 1 USD = 1,350 KRW
case "EUR" -> 1450.0; // 1 EUR = 1,450 KRW
case "JPY" -> 9.0; // 1 JPY = 9 KRW
case "CNY" -> 190.0; // 1 CNY = 190 KRW
case "THB" -> 40.0; // 1 THB = 40 KRW
case "SGD" -> 1000.0; // 1 SGD = 1,000 KRW
case "HKD" -> 175.0; // 1 HKD = 175 KRW
case "GBP" -> 1700.0; // 1 GBP = 1,700 KRW
case "AUD" -> 900.0; // 1 AUD = 900 KRW
default -> 1350.0; // 기본값: USD 환율
};

return (int) (amount * exchangeRate);
}

/**
* ISO 8601 형식의 날짜/시간 문자열을 LocalDateTime으로 파싱
* @param dateTimeStr "2025-12-10T07:30:00" 형식
* @return LocalDateTime
*/
private static LocalDateTime parseDateTime(String dateTimeStr) {
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}

/**
* IATA 항공사 코드를 항공사 이름으로 변환
* @param carrierCode IATA 2자리 코드 (예: KE, OZ, 7C)
* @return 항공사 이름
*/
private static String getAirlineName(String carrierCode) {
return switch (carrierCode) {
case "KE" -> "대한항공";
case "OZ" -> "아시아나항공";
case "7C" -> "제주항공";
case "LJ" -> "진에어";
case "TW" -> "티웨이항공";
case "RS" -> "에어서울";
case "BX" -> "에어부산";
case "ZE" -> "이스타항공";
case "4V" -> "플라이강원";
case "NH" -> "전일본공수";
case "JL" -> "일본항공";
case "CZ" -> "중국남방항공";
case "MU" -> "중국동방항공";
case "CA" -> "중국국제항공";
case "TG" -> "타이항공";
case "SQ" -> "싱가포르항공";
case "VN" -> "베트남항공";
case "PR" -> "필리핀항공";
case "AF" -> "에어프랑스";
case "LH" -> "루프트한자";
case "BA" -> "영국항공";
case "UA" -> "유나이티드항공";
case "AA" -> "아메리칸항공";
case "DL" -> "델타항공";
default -> carrierCode; // 매핑되지 않은 경우 코드 그대로 반환
};
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.triptalk.domain.tripPlan.converter;

import com.example.triptalk.domain.tripPlan.dto.FlightResponse;
import com.example.triptalk.domain.tripPlan.entity.Flight;
import com.example.triptalk.domain.tripPlan.util.AirportNameMapper;
import org.springframework.data.domain.Slice;

import java.util.List;

public class FlightConverter {

/**
* Flight 엔티티를 FlightDTO로 변환
*/
public static FlightResponse.FlightDTO toFlightDTO(Flight flight) {
return FlightResponse.FlightDTO.builder()
.id(flight.getId())
.originName(AirportNameMapper.getAirportName(flight.getOrigin()))
.destinationName(AirportNameMapper.getAirportName(flight.getDestination()))
.airlineName(flight.getAirlineName())
.price(flight.getPrice())
.departureDate(flight.getDepartureDate())
.arrivalDate(flight.getArrivalDate())
.imageUrl(flight.getImageUrl())
.isOutbound(flight.getIsOutbound())
.build();
}

/**
* Slice<Flight>을 FlightListResultDTO로 변환
*/
public static FlightResponse.FlightListResultDTO toFlightListResultDTO(Slice<Flight> slice) {
List<FlightResponse.FlightDTO> flightList = slice.getContent().stream()
.map(FlightConverter::toFlightDTO)
.toList();

// 다음 커서 ID는 마지막 항목의 ID
Long nextCursorId = flightList.isEmpty() ?
null :
flightList.getLast().getId();

return FlightResponse.FlightListResultDTO.builder()
.flightList(flightList)
.flightListSize(flightList.size())
.isFirst(slice.isFirst())
.hasNext(slice.hasNext())
.nextCursorId(nextCursorId)
.build();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.example.triptalk.domain.tripPlan.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;

import java.util.List;

public class AmadeusResponse {

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class AccessToken {
@JsonProperty("access_token")
private String accessToken;

@JsonProperty("token_type")
private String tokenType;

@JsonProperty("expires_in")
private Integer expiresIn;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class FlightOffersResponse {
private List<FlightOffer> data;
private Object meta; // 메타 정보 (필요시 파싱)
private Object dictionaries; // 딕셔너리 정보 (필요시 파싱)
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class FlightOffer {
private String id;
private String type;
private Itinerary[] itineraries;
private Price price;
private List<String> validatingAirlineCodes;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Itinerary {
private Segment[] segments;
private String duration;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Segment {
private Departure departure;
private Arrival arrival;
private String carrierCode;
private String number;
private Aircraft aircraft;
private String duration;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Departure {
private String iataCode;
private String at; // 2025-12-10T07:30:00
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Arrival {
private String iataCode;
private String at; // 2025-12-10T08:35:00
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Aircraft {
private String code;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Price {
private String currency;
private String total;
private String base;
}
}

Loading
Loading