| 1 | import { DateTime, IANAZone } from 'luxon'; |
| 2 | import { prisma } |
| 3 | import { FlightAwareService } |
| 4 | import { RedisService } |
| 5 | |
| 6 | import { |
| 7 | BadRequestException, |
| 8 | HttpException, |
| 9 | HttpStatus, |
| 10 | Injectable, |
| 11 | InternalServerErrorException, |
| 12 | NotFoundException, |
| 13 | UnauthorizedException, |
| 14 | } from '@nestjs/common'; |
| 15 | import { ConfigService } |
| 16 | import { createId } |
| 17 | import { CreateFlightBookingDTO } |
| 18 | import { GetFlightSearchDTO } |
| 19 | import { GetFlightTrackDTO } |
| 20 | import { GetFlightDTO } |
| 21 | import type { UpdateFlightBookingDTO |
| 22 | import { |
| 23 | AircraftEntity, |
| 24 | FlightCandidateEntity, |
| 25 | FlightSearchResponseEntity, |
| 26 | } from './entities/flight.entity'; |
| 27 | |
| 28 | const TIMEZONE_ABBREV_TO_IANA: Record |
| 29 | UTC: 'UTC', |
| 30 | GMT: 'Etc/UTC', |
| 31 | BST: 'Europe/London', |
| 32 | CET: 'Europe/Berlin', |
| 33 | CEST: 'Europe/Berlin', |
| 34 | EET: 'Europe/Athens', |
| 35 | EEST: 'Europe/Athens', |
| 36 | IST: 'Asia/Kolkata', |
| 37 | PKT: 'Asia/Karachi', |
| 38 | MSK: 'Europe/Moscow', |
| 39 | AST: 'America/Halifax', |
| 40 | ADT: 'America/Halifax', |
| 41 | EST: 'America/New_York', |
| 42 | EDT: 'America/New_York', |
| 43 | CST: 'America/Chicago', |
| 44 | CDT: 'America/Chicago', |
| 45 | MST: 'America/Denver', |
| 46 | MDT: 'America/Denver', |
| 47 | PST: 'America/Los_Angeles', |
| 48 | PDT: 'America/Los_Angeles', |
| 49 | AKST: 'America/Anchorage', |
| 50 | AKDT: 'America/Anchorage', |
| 51 | HST: 'Pacific/Honolulu', |
| 52 | JST: 'Asia/Tokyo', |
| 53 | KST: 'Asia/Seoul', |
| 54 | AEST: 'Australia/Sydney', |
| 55 | AEDT: 'Australia/Sydney', |
| 56 | ACST: 'Australia/Adelaide', |
| 57 | ACDT: 'Australia/Adelaide', |
| 58 | AWST: 'Australia/Perth', |
| 59 | }; |
| 60 | |
| 61 | const ALT_CHANGE_FROM_CODE: Record |
| 62 | C: 'Climb', |
| 63 | D: 'Descend', |
| 64 | '-': 'None', |
| 65 | }; |
| 66 | const ALT_CHANGE_TO_CODE: Record |
| 67 | Climb: 'C', |
| 68 | Descend: 'D', |
| 69 | None: '-', |
| 70 | }; |
| 71 | |
| 72 | type UpdateType |
| 73 | | 'Projected' |
| 74 | | 'Oceanic' |
| 75 | | 'Radar' |
| 76 | | 'ADSB' |
| 77 | | 'Multilateration' |
| 78 | | 'Datalink' |
| 79 | | 'Surface_And_Near_Surface' |
| 80 | | 'Spaced_Based' |
| 81 | | 'Virtual_Event' |
| 82 | |
| 83 | const UPDATE_TYPE_FROM_CODE: Record |
| 84 | P: 'Projected', |
| 85 | O: 'Oceanic', |
| 86 | Z: 'Radar', |
| 87 | A: 'ADSB', |
| 88 | M: 'Multilateration', |
| 89 | D: 'Datalink', |
| 90 | X: 'Surface_And_Near_Surface', |
| 91 | S: 'Spaced_Based', |
| 92 | V: 'Virtual_Event', |
| 93 | }; |
| 94 | type AirportConditions |
| 95 | delays: any |
| 96 | forecast: any |
| 97 | observation: any |
| 98 | }; |
| 99 | |
| 100 | const EMPTY_CONDITIONS: AirportConditions |
| 101 | delays: null, |
| 102 | forecast: null, |
| 103 | observation: null, |
| 104 | }; |
| 105 | |
| 106 | const UPDATE_TYPE_TO_CODE: Record |
| 107 | Projected: 'P', |
| 108 | Oceanic: 'O', |
| 109 | Radar: 'Z', |
| 110 | ADSB: 'A', |
| 111 | Multilateration: 'M', |
| 112 | Datalink: 'D', |
| 113 | Surface_And_Near_Surface: 'X', |
| 114 | Spaced_Based: 'S', |
| 115 | Virtual_Event: 'V', |
| 116 | }; |
| 117 | |
| 118 | function resolveIanaZone(tz: |
| 119 | if (tz && |
| 120 | const mapped = |
| 121 | if (mapped && |
| 122 | return 'UTC'; |
| 123 | } |
| 124 | |
| 125 | function parseDateInTimezone( |
| 126 | dateString: string, |
| 127 | timezone: string, |
| 128 | ): { startOfDayUtc: |
| 129 | if (dateString.split |
| 130 | throw new BadRequestException( |
| 131 | } |
| 132 | const zone = |
| 133 | const start = |
| 134 | const end = |
| 135 | return { startOfDayUtc: |
| 136 | } |
| 137 | |
| 138 | function normalizeAircraftFromDb(aircraft: |
| 139 | return { |
| 140 | modeS: aircraft.hexIcao |
| 141 | age: aircraft.age |
| 142 | image: aircraft.image |
| 143 | attribution: aircraft.attribution |
| 144 | isFreighter: aircraft.isFreighter |
| 145 | model: aircraft.typeName |
| 146 | registration: aircraft.reg |
| 147 | aircraft_id: aircraft.aircraft_id |
| 148 | deliveryDate: aircraft.deliveryDate |
| 149 | firstFlightDate: aircraft.firstFlightDate |
| 150 | payload: aircraft.payload |
| 151 | registrations: (aircraft.registrations |
| 152 | id: r.id |
| 153 | reg: r.reg |
| 154 | active: r.active |
| 155 | hexIcao: r.hexIcao |
| 156 | airlineName: r.airlineName |
| 157 | registrationDate: r.registrationDate |
| 158 | })), |
| 159 | } satisfies AircraftEntity; |
| 160 | } |
| 161 | |
| 162 | function normalizeAircraftFromStored( |
| 163 | stored: any |
| 164 | ): AircraftEntity | |
| 165 | if (!stored) |
| 166 | return { |
| 167 | modeS: stored.modeS |
| 168 | age: (stored.ageYears |
| 169 | image: stored.image |
| 170 | attribution: |
| 171 | stored.attribution ?? |
| 172 | isFreighter: stored.isFreighter |
| 173 | model: stored.typeName |
| 174 | registration: stored.reg |
| 175 | aircraft_id: stored.aircraft_id |
| 176 | payload: stored.payload |
| 177 | deliveryDate: stored.deliveryDate |
| 178 | firstFlightDate: stored.firstFlightDate |
| 179 | } as AircraftEntity; |
| 180 | } |
| 181 | |
| 182 | async function lookupAirline( |
| 183 | if (!iata && |
| 184 | return prisma.airline |
| 185 | where: { |
| 186 | OR: [ |
| 187 | iata ? { iata |
| 188 | icao ? { icao |
| 189 | ].filter(Boolean) |
| 190 | }, |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | function mergeAirline(stored: |
| 195 | if (!db) |
| 196 | return { name: |
| 197 | } |
| 198 | |
| 199 | async function lookupAirport( |
| 200 | if (!iata && |
| 201 | return prisma.airport |
| 202 | where: { |
| 203 | OR: [ |
| 204 | iata ? { iataCode |
| 205 | icao ? { OR |
| 206 | ].filter(Boolean) |
| 207 | }, |
| 208 | }); |
| 209 | } |
| 210 | |
| 211 | function buildFlightAwareDataPayload(faFlight |
| 212 | const d = |
| 213 | return { |
| 214 | ident: faFlight.ident |
| 215 | identIcao: faFlight.ident_icao |
| 216 | identIata: faFlight.ident_iata |
| 217 | actualRunwayOff: faFlight.actual_runway_off |
| 218 | actualRunwayOn: faFlight.actual_runway_on |
| 219 | operator: faFlight.operator |
| 220 | operatorIcao: faFlight.operator_icao |
| 221 | operatorIata: faFlight.operator_iata |
| 222 | flightNumber: faFlight.flight_number |
| 223 | registration: faFlight.registration |
| 224 | atcIdent: faFlight.atc_ident |
| 225 | inboundFaFlightId: faFlight.inbound_fa_flight_id |
| 226 | codesharesIata: faFlight.codeshares_iata |
| 227 | codesharesIcao: faFlight.codeshares |
| 228 | departureDelay: faFlight.departure_delay |
| 229 | arrivalDelay: faFlight.arrival_delay |
| 230 | filedEte: faFlight.filed_ete |
| 231 | progressPercent: faFlight.progress_percent |
| 232 | status: faFlight.status |
| 233 | aircraftType: faFlight.aircraft_type |
| 234 | routeDistance: faFlight.route_distance |
| 235 | filedAirspeed: faFlight.filed_airspeed |
| 236 | filedAltitude: faFlight.filed_altitude |
| 237 | route: faFlight.route |
| 238 | baggageClaim: faFlight.baggage_claim |
| 239 | seatsCabinBusiness: faFlight.seats_cabin_business |
| 240 | seatsCabinCoach: faFlight.seats_cabin_coach |
| 241 | seatsCabinFirst: faFlight.seats_cabin_first |
| 242 | gateOrigin: faFlight.gate_origin |
| 243 | gateDestination: faFlight.gate_destination |
| 244 | terminalOrigin: faFlight.terminal_origin |
| 245 | terminalDestination: faFlight.terminal_destination |
| 246 | scheduledOut: d(faFlight |
| 247 | estimatedOut: d(faFlight |
| 248 | actualOut: d(faFlight |
| 249 | scheduledOff: d(faFlight |
| 250 | estimatedOff: d(faFlight |
| 251 | actualOff: d(faFlight |
| 252 | scheduledOn: d(faFlight |
| 253 | estimatedOn: d(faFlight |
| 254 | actualOn: d(faFlight |
| 255 | scheduledIn: d(faFlight |
| 256 | estimatedIn: d(faFlight |
| 257 | actualIn: d(faFlight |
| 258 | foresightPredictionsAvailable: |
| 259 | faFlight.foresight_predictions_available ?? |
| 260 | blocked: faFlight.blocked |
| 261 | diverted: faFlight.diverted |
| 262 | cancelled: faFlight.cancelled |
| 263 | positionOnly: faFlight.position_only |
| 264 | originCode: faFlight?.origin |
| 265 | originCodeIcao: faFlight?.origin |
| 266 | originCodeIata: faFlight?.origin |
| 267 | originCodeLid: faFlight?.origin |
| 268 | originTimezone: faFlight?.origin |
| 269 | originName: faFlight?.origin |
| 270 | originCity: faFlight?.origin |
| 271 | destinationCode: faFlight?.destination |
| 272 | destinationCodeIcao: faFlight?.destination |
| 273 | destinationCodeIata: faFlight?.destination |
| 274 | destinationCodeLid: faFlight?.destination |
| 275 | destinationTimezone: faFlight?.destination |
| 276 | destinationName: faFlight?.destination |
| 277 | destinationCity: faFlight?.destination |
| 278 | flightId, |
| 279 | }; |
| 280 | } |
| 281 | |
| 282 | function buildFlightData( |
| 283 | faFlight: any, |
| 284 | userId: string, |
| 285 | searchDate: Date |
| 286 | dbAirline: any, |
| 287 | depAirport: any, |
| 288 | arrAirport: any, |
| 289 | departureConditions: AirportConditions |
| 290 | arrivalConditions: AirportConditions |
| 291 | ) { |
| 292 | return { |
| 293 | userId, |
| 294 | flightNo: faFlight.ident |
| 295 | callSign: faFlight.ident |
| 296 | aircraft: { |
| 297 | registration: faFlight.registration |
| 298 | type: faFlight.aircraft_type |
| 299 | }, |
| 300 | airline: { |
| 301 | name: |
| 302 | dbAirline?.name ?? |
| 303 | faFlight.operator ?? |
| 304 | faFlight.operator_iata ?? |
| 305 | 'Unknown', |
| 306 | iata: dbAirline?.iata |
| 307 | icao: dbAirline?.icao |
| 308 | image: dbAirline?.image |
| 309 | }, |
| 310 | arrival: { |
| 311 | airport: { |
| 312 | icao: faFlight.destination |
| 313 | iata: faFlight.destination |
| 314 | name: faFlight.destination |
| 315 | municipalityName: faFlight.destination |
| 316 | location: { |
| 317 | lat: arrAirport ? |
| 318 | lon: arrAirport ? |
| 319 | }, |
| 320 | countryCode: faFlight.destination |
| 321 | timeZone: faFlight.destination |
| 322 | shortName: faFlight?.destination |
| 323 | conditions: arrivalConditions, |
| 324 | }, |
| 325 | scheduledTime: { |
| 326 | utc: faFlight.scheduled_on |
| 327 | local: faFlight.scheduled_on |
| 328 | }, |
| 329 | revisedTime: faFlight.estimated_on |
| 330 | ? { utc: faFlight |
| 331 | : null, |
| 332 | actualTime: faFlight.actual_on |
| 333 | ? { utc: faFlight |
| 334 | : null, |
| 335 | terminal: faFlight.terminal_destination |
| 336 | gate: faFlight.gate_destination |
| 337 | }, |
| 338 | cargo: false, |
| 339 | date: faFlight.scheduled_out |
| 340 | departure: { |
| 341 | airport: { |
| 342 | shortName: faFlight?.origin |
| 343 | icao: faFlight.origin |
| 344 | iata: faFlight.origin |
| 345 | name: faFlight.origin |
| 346 | municipalityName: faFlight.origin |
| 347 | location: { |
| 348 | lat: depAirport ? |
| 349 | lon: depAirport ? |
| 350 | }, |
| 351 | countryCode: faFlight.origin |
| 352 | timeZone: faFlight.origin |
| 353 | conditions: departureConditions, |
| 354 | }, |
| 355 | scheduledTime: { |
| 356 | utc: faFlight.scheduled_out |
| 357 | local: faFlight.scheduled_out |
| 358 | }, |
| 359 | revisedTime: faFlight.estimated_out |
| 360 | ? { utc: faFlight |
| 361 | : null, |
| 362 | actualTime: faFlight.actual_out |
| 363 | ? { utc: faFlight |
| 364 | : null, |
| 365 | terminal: faFlight.terminal_origin |
| 366 | gate: faFlight.gate_origin |
| 367 | }, |
| 368 | }; |
| 369 | } |
| 370 | |
| 371 | @Injectable() |
| 372 | export class FlightService |
| 373 | private redis: |
| 374 | |
| 375 | constructor( |
| 376 | private readonly configService |
| 377 | private readonly flightAwareService |
| 378 | private readonly redisService |
| 379 | ) { |
| 380 | this.redis = |
| 381 | } |
| 382 | |
| 383 | /** Get a faFlight via Redis cache (by fa_flight_id) or FlightAware API. */ |
| 384 | private async getFaFlightById |
| 385 | const cacheKey = |
| 386 | if (this.redis |
| 387 | try { |
| 388 | const cached = |
| 389 | if (cached) { |
| 390 | console.log(`Retrieved flight |
| 391 | return JSON.parse |
| 392 | } |
| 393 | } catch (error) |
| 394 | console.warn('Failed to read flight from Redis cache: |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | console.log(`Cache miss for |
| 399 | const response = |
| 400 | if (!response || |
| 401 | const faFlight = |
| 402 | |
| 403 | if (this.redis |
| 404 | try { |
| 405 | await this.redis |
| 406 | console.log(`Cached flight |
| 407 | } catch (error) |
| 408 | console.warn('Failed to cache flight in Redis: |
| 409 | } |
| 410 | } |
| 411 | return faFlight; |
| 412 | } |
| 413 | |
| 414 | /** Resolve the FlightAware flight to operate on, given the request shape. */ |
| 415 | private async resolveFaFlight |
| 416 | faFlightId?: string |
| 417 | forceUpdate?: boolean |
| 418 | existingFlight: any |
| 419 | iata?: string |
| 420 | icao?: string |
| 421 | searchDate: Date |
| 422 | nextDate: Date |
| 423 | }): Promise |
| 424 | const { faFlightId, |
| 425 | |
| 426 | if (faFlightId) { |
| 427 | const record = |
| 428 | where: { |
| 429 | OR: [ |
| 430 | { flightAwareData: { faFlightId |
| 431 | { id: faFlightId |
| 432 | { |
| 433 | flightAwareData:{ |
| 434 | id:faFlightId, |
| 435 | } |
| 436 | } |
| 437 | ], |
| 438 | }, |
| 439 | include: { flightAwareData: true |
| 440 | }); |
| 441 | const resolvedId = |
| 442 | console.log(`Fetching specific flight using fa_flight_id |
| 443 | const faFlight = |
| 444 | if (!faFlight) |
| 445 | throw new BadRequestException( |
| 446 | 'Unable to fetch flight information with the provided flight ID.', |
| 447 | ); |
| 448 | } |
| 449 | return faFlight; |
| 450 | } |
| 451 | |
| 452 | if (forceUpdate && |
| 453 | const id = |
| 454 | console.log(`Force update: Using existing fa_flight_id |
| 455 | const response = |
| 456 | if (!response || |
| 457 | throw new BadRequestException( |
| 458 | 'Unable to fetch flight information. Please make sure the flight number is correct.', |
| 459 | ); |
| 460 | } |
| 461 | return response.flights |
| 462 | } |
| 463 | |
| 464 | const ident = |
| 465 | if (!ident) |
| 466 | const response = |
| 467 | if (!response || |
| 468 | throw new BadRequestException( |
| 469 | 'Unable to fetch flight information. Please make sure the flight number is correct.', |
| 470 | ); |
| 471 | } |
| 472 | let faFlight = |
| 473 | if (response.flights |
| 474 | const matched = |
| 475 | const d = |
| 476 | ? new Date( |
| 477 | : f.scheduled_off |
| 478 | ? new Date( |
| 479 | : null; |
| 480 | return d ? |
| 481 | }); |
| 482 | if (matched) { |
| 483 | faFlight = matched; |
| 484 | console.log(`Matched FlightAware flight by date: |
| 485 | } else { |
| 486 | console.log(`No date match found, using first flight: |
| 487 | } |
| 488 | } |
| 489 | return faFlight; |
| 490 | } |
| 491 | |
| 492 | /** Extract a usable AeroAPI airport identifier (prefer ICAO, then IATA, then raw code). */ |
| 493 | private extractAirportId(airport |
| 494 | return airport?.code_icao |
| 495 | } |
| 496 | |
| 497 | /** Fetch delays, forecast, and latest observation for an airport, in parallel. */ |
| 498 | private async getAirportConditions |
| 499 | const [delays, |
| 500 | this.flightAwareService.getAirportDelays |
| 501 | this.flightAwareService.getAirportWeatherForecast |
| 502 | this.flightAwareService.getAirportLatestObservation |
| 503 | ]); |
| 504 | const val = |
| 505 | r.status === |
| 506 | return { |
| 507 | delays: val(delays |
| 508 | forecast: val(forecast |
| 509 | observation: val(observation |
| 510 | }; |
| 511 | } |
| 512 | |
| 513 | /** Resolve (find or create) the aircraft record for a flight. */ |
| 514 | private async resolveAircraft |
| 515 | registration: string |
| 516 | faFlight: any, |
| 517 | newFlight: any, |
| 518 | ): Promise<AircraftEntity |
| 519 | if (!registration) |
| 520 | return { |
| 521 | ...(newFlight.aircraft |
| 522 | registration: faFlight.registration |
| 523 | model: faFlight.aircraft_type |
| 524 | }; |
| 525 | } |
| 526 | |
| 527 | const existing = |
| 528 | where: { reg: registration |
| 529 | include: { registrations: true |
| 530 | }); |
| 531 | if (existing) return |
| 532 | |
| 533 | const apiKey = |
| 534 | if (!apiKey) |
| 535 | return { |
| 536 | ...(newFlight.aircraft |
| 537 | registration, |
| 538 | model: faFlight.aircraft_type |
| 539 | }; |
| 540 | } |
| 541 | |
| 542 | try { |
| 543 | const res = |
| 544 | `https://aerodatabox.p.rapidapi.com/aircrafts/reg/${registration}?withImage=true&withRegistrations=true` |
| 545 | { |
| 546 | headers: { |
| 547 | 'X-RapidAPI-Key': apiKey, |
| 548 | 'X-RapidAPI-Host': 'aerodatabox.p.rapidapi.com', |
| 549 | }, |
| 550 | }, |
| 551 | ); |
| 552 | if (!res.ok |
| 553 | const json = |
| 554 | |
| 555 | const aircraft = |
| 556 | data: { |
| 557 | aircraft_id: String(json |
| 558 | payload: json, |
| 559 | reg: json.reg |
| 560 | hexIcao: json.hexIcao |
| 561 | modelCode: json.modelCode |
| 562 | firstFlightDate: json.firstFlightDate |
| 563 | ? new Date( |
| 564 | : null, |
| 565 | deliveryDate: json.deliveryDate |
| 566 | ? new Date( |
| 567 | : null, |
| 568 | typeName: json.typeName |
| 569 | isFreighter: json.isFreighter |
| 570 | age: json.ageYears |
| 571 | image: json?.image |
| 572 | attribution: json?.image |
| 573 | ? `${json.image |
| 574 | : null, |
| 575 | registrations: json.registrations |
| 576 | ? { |
| 577 | createMany: { |
| 578 | data: json.registrations |
| 579 | id: `registration_${createId |
| 580 | active: data.active |
| 581 | reg: data.reg |
| 582 | airlineName: data.airlineName |
| 583 | registrationDate: data.registrationDate |
| 584 | ? new Date( |
| 585 | : null, |
| 586 | hexIcao: data.hexIcao |
| 587 | })), |
| 588 | skipDuplicates: true, |
| 589 | }, |
| 590 | } |
| 591 | : undefined, |
| 592 | }, |
| 593 | include: { registrations: true |
| 594 | }); |
| 595 | console.log(`Fetched aircraft data from AeroDataBox for |
| 596 | return normalizeAircraftFromDb(aircraft |
| 597 | } catch (error) |
| 598 | console.error('Error fetching from AeroDataBox: |
| 599 | |
| 600 | let planespotterImage: |
| 601 | let planespotterAttribution: |
| 602 | try { |
| 603 | const psRes = |
| 604 | `https://api.planespotters.net/pub/photos/reg/${registration}`, |
| 605 | ); |
| 606 | if (psRes.ok |
| 607 | const data = |
| 608 | if (data.photos |
| 609 | planespotterImage = data. |
| 610 | planespotterAttribution = `Photo by ${ |
| 611 | } |
| 612 | } |
| 613 | } catch (e) |
| 614 | console.error('Error fetching from Planespotters: |
| 615 | } |
| 616 | |
| 617 | const aircraft = |
| 618 | data: { |
| 619 | aircraft_id: `aircraft_${createId |
| 620 | reg: registration, |
| 621 | hexIcao: '', |
| 622 | typeName: faFlight.aircraft_type |
| 623 | modelCode: faFlight.aircraft_type |
| 624 | isFreighter: false, |
| 625 | age: 0, |
| 626 | image: planespotterImage, |
| 627 | attribution: planespotterAttribution, |
| 628 | payload: {}, |
| 629 | }, |
| 630 | }); |
| 631 | return { |
| 632 | modeS: aircraft.hexIcao |
| 633 | age: aircraft.age |
| 634 | image: aircraft.image |
| 635 | attribution: aircraft.attribution |
| 636 | isFreighter: aircraft.isFreighter |
| 637 | model: aircraft.typeName |
| 638 | registration: aircraft.reg |
| 639 | aircraft_id: aircraft.aircraft_id |
| 640 | deliveryDate: aircraft.deliveryDate |
| 641 | firstFlightDate: aircraft.firstFlightDate |
| 642 | payload: aircraft.payload |
| 643 | } satisfies AircraftEntity; |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | async getFlight( |
| 648 | { iata, icao |
| 649 | userId: string, |
| 650 | ) { |
| 651 | const dateToUse = |
| 652 | const { startOfDayUtc: |
| 653 | parseDateInTimezone(dateToUse, timezone |
| 654 | |
| 655 | const existingFlight = |
| 656 | where: { |
| 657 | OR: [ |
| 658 | { callSign: iata |
| 659 | { flightNo: iata |
| 660 | { callSign: icao |
| 661 | { flightNo: icao |
| 662 | ], |
| 663 | date: { gte: searchDate |
| 664 | }, |
| 665 | orderBy: { createdAt: ' |
| 666 | include: { |
| 667 | greatCircleDistance: true, |
| 668 | flightAwareData: true, |
| 669 | bookings: { where: { |
| 670 | }, |
| 671 | }); |
| 672 | |
| 673 | // Cached path: return existing flight without hitting FlightAware |
| 674 | if (!forceUpdate && |
| 675 | return this.buildExistingFlightResponse |
| 676 | } |
| 677 | |
| 678 | try { |
| 679 | const faFlight = |
| 680 | faFlightId, |
| 681 | forceUpdate, |
| 682 | existingFlight, |
| 683 | iata, |
| 684 | icao, |
| 685 | searchDate, |
| 686 | nextDate, |
| 687 | }); |
| 688 | |
| 689 | const arrivalAirportId = |
| 690 | const departureAirportId = |
| 691 | if (!arrivalAirportId) |
| 692 | throw new BadRequestException( |
| 693 | } |
| 694 | |
| 695 | // Kick off airport-conditions fetches in parallel with DB lookups below. |
| 696 | const conditionsPromise = |
| 697 | departureAirportId |
| 698 | ? this.getAirportConditions( |
| 699 | : Promise.resolve( |
| 700 | this.getAirportConditions(arrivalAirportId |
| 701 | ]); |
| 702 | |
| 703 | const greatCircleDistance = |
| 704 | ? { |
| 705 | meter: Math.round |
| 706 | km: (faFlight.route_distance |
| 707 | mile: (faFlight.route_distance |
| 708 | nm: faFlight.route_distance |
| 709 | feet: Math.round |
| 710 | } |
| 711 | : null; |
| 712 | |
| 713 | const dbAirline = |
| 714 | faFlight.operator_iata ?? |
| 715 | faFlight.operator_icao ?? |
| 716 | ); |
| 717 | const [depAirport, |
| 718 | lookupAirport( |
| 719 | faFlight.origin?.code_iata |
| 720 | faFlight.origin?.code_icao |
| 721 | ), |
| 722 | lookupAirport( |
| 723 | faFlight.destination?.code_iata |
| 724 | faFlight.destination?.code_icao |
| 725 | ), |
| 726 | ]); |
| 727 | |
| 728 | const [departureConditions, |
| 729 | |
| 730 | const flightData = |
| 731 | faFlight, |
| 732 | userId, |
| 733 | searchDate, |
| 734 | dbAirline, |
| 735 | depAirport, |
| 736 | arrAirport, |
| 737 | departureConditions, |
| 738 | arrivalConditions, |
| 739 | ); |
| 740 | |
| 741 | const newFlight = |
| 742 | forceUpdate && existingFlight |
| 743 | ? await prisma. |
| 744 | where: { id: existingFlight |
| 745 | data: flightData, |
| 746 | include: { greatCircleDistance: true |
| 747 | }) |
| 748 | : await prisma. |
| 749 | data: { ...flightData |
| 750 | include: { greatCircleDistance: true |
| 751 | }); |
| 752 | |
| 753 | if (greatCircleDistance) { |
| 754 | await prisma.greatCircleDistance |
| 755 | where: { flightId: newFlight |
| 756 | update: greatCircleDistance, |
| 757 | create: { ...greatCircleDistance |
| 758 | }); |
| 759 | } |
| 760 | console.log( |
| 761 | forceUpdate && existingFlight |
| 762 | ? `Updated flight from FlightAware: ${faFlight. |
| 763 | : `Created flight from FlightAware: ${faFlight. |
| 764 | ); |
| 765 | |
| 766 | const faPayload = |
| 767 | if (forceUpdate && |
| 768 | await prisma.flightAwareData |
| 769 | where: { id: existingFlight |
| 770 | data: faPayload, |
| 771 | }); |
| 772 | } else { |
| 773 | const found = |
| 774 | where: { faFlightId: faFlight |
| 775 | }); |
| 776 | if (found) { |
| 777 | await prisma.flightAwareData |
| 778 | where: { id: found |
| 779 | data: faPayload, |
| 780 | }); |
| 781 | } else { |
| 782 | await prisma.flightAwareData |
| 783 | data: { faFlightId: faFlight |
| 784 | }); |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | const normalizedAircraft = |
| 789 | faFlight.registration, |
| 790 | faFlight, |
| 791 | newFlight, |
| 792 | ); |
| 793 | |
| 794 | const flightWithAwareData = |
| 795 | where: { id: newFlight |
| 796 | include: { |
| 797 | greatCircleDistance: true, |
| 798 | flightAwareData: { omit: { |
| 799 | bookings: { where: { |
| 800 | }, |
| 801 | }); |
| 802 | |
| 803 | const storedAirline = |
| 804 | const dbAirlineFinal = |
| 805 | storedAirline?.iata, |
| 806 | storedAirline?.icao, |
| 807 | ); |
| 808 | const mergedAirline = |
| 809 | |
| 810 | if (flightWithAwareData && |
| 811 | return { |
| 812 | ...flightWithAwareData, |
| 813 | airline: mergedAirline, |
| 814 | aircraft: normalizedAircraft, |
| 815 | bookings: flightWithAwareData.bookings |
| 816 | }; |
| 817 | } |
| 818 | return flightWithAwareData |
| 819 | ? { |
| 820 | ...flightWithAwareData, |
| 821 | airline: mergedAirline, |
| 822 | bookings: flightWithAwareData.bookings |
| 823 | } |
| 824 | : { ...newFlight |
| 825 | } catch (error) |
| 826 | if ( |
| 827 | error instanceof UnauthorizedException |
| 828 | error instanceof BadRequestException |
| 829 | ) { |
| 830 | throw error; |
| 831 | } |
| 832 | console.error('Error fetching flight data: |
| 833 | throw new InternalServerErrorException( |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | /** Build the response for the cached (existing-flight, no forceUpdate) path. */ |
| 838 | private async buildExistingFlightResponse |
| 839 | const stored = |
| 840 | let aircraft: |
| 841 | if (stored) { |
| 842 | const hex = |
| 843 | const reg = |
| 844 | if (hex) { |
| 845 | aircraft = await |
| 846 | where: { hexIcao: hex |
| 847 | include: { registrations: true |
| 848 | }); |
| 849 | } |
| 850 | if (!aircraft && |
| 851 | aircraft = await |
| 852 | where: { reg |
| 853 | include: { registrations: true |
| 854 | }); |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | const storedAirline = |
| 859 | const dbAirline = |
| 860 | storedAirline?.iata, |
| 861 | storedAirline?.icao, |
| 862 | ); |
| 863 | |
| 864 | return { |
| 865 | ...existingFlight, |
| 866 | airline: mergeAirline(storedAirline |
| 867 | aircraft: aircraft |
| 868 | ? normalizeAircraftFromDb(aircraft) |
| 869 | : normalizeAircraftFromStored(stored) |
| 870 | bookings: existingFlight.bookings |
| 871 | }; |
| 872 | } |
| 873 | |
| 874 | async searchFlights( |
| 875 | { iata, icao |
| 876 | userId: string, |
| 877 | ): Promise<FlightSearchResponseEntity |
| 878 | let searchDate: |
| 879 | let nextDate: |
| 880 | if (date) { |
| 881 | const parsed = |
| 882 | searchDate = parsed. |
| 883 | nextDate = parsed. |
| 884 | } |
| 885 | |
| 886 | try { |
| 887 | const ident = |
| 888 | if (!ident) |
| 889 | |
| 890 | const response = |
| 891 | if (!response || |
| 892 | return { flights: |
| 893 | } |
| 894 | |
| 895 | let filtered = |
| 896 | if (searchDate && |
| 897 | filtered = response. |
| 898 | const d = |
| 899 | ? new Date( |
| 900 | : f.scheduled_off |
| 901 | ? new Date( |
| 902 | : null; |
| 903 | return d ? |
| 904 | }); |
| 905 | } |
| 906 | |
| 907 | // Cache by fa_flight_id so getFlight can hit Redis instead of FA API |
| 908 | if (this.redis |
| 909 | try { |
| 910 | for (const f |
| 911 | await this.redis |
| 912 | `flightaware:flight:by_id:${f.fa_flight_id |
| 913 | 3600, |
| 914 | JSON.stringify(f |
| 915 | ); |
| 916 | } |
| 917 | console.log( |
| 918 | `Cached ${filtered.length} |
| 919 | ); |
| 920 | } catch (error) |
| 921 | console.warn('Failed to cache flights in Redis: |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | // Batch-resolve airlines from DB |
| 926 | const iatas = |
| 927 | const icaos = |
| 928 | filtered.forEach((f |
| 929 | if (f.operator_iata |
| 930 | if (f.operator_icao |
| 931 | }); |
| 932 | const airlineByIata = |
| 933 | const airlineByIcao = |
| 934 | if (iatas.size |
| 935 | const dbAirlines = |
| 936 | where: { |
| 937 | OR: [ |
| 938 | iatas.size ? |
| 939 | icaos.size ? |
| 940 | ].filter(Boolean) |
| 941 | }, |
| 942 | }); |
| 943 | for (const a |
| 944 | if (a.iata |
| 945 | if (a.icao |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | const flights: |
| 950 | const dbAirline = |
| 951 | (f.operator_iata && |
| 952 | (f.operator_icao && |
| 953 | null; |
| 954 | return { |
| 955 | faFlightId: f.fa_flight_id |
| 956 | ident: f.ident |
| 957 | origin: { |
| 958 | code: f.origin |
| 959 | codeIata: f.origin |
| 960 | codeIcao: f.origin |
| 961 | name: f.origin |
| 962 | city: f.origin |
| 963 | }, |
| 964 | destination: { |
| 965 | code: f.destination |
| 966 | codeIata: f.destination |
| 967 | codeIcao: f.destination |
| 968 | name: f.destination |
| 969 | city: f.destination |
| 970 | }, |
| 971 | scheduledOut: f.scheduled_out |
| 972 | scheduledOff: f.scheduled_off |
| 973 | status: f.status |
| 974 | airline: { |
| 975 | name: |
| 976 | dbAirline?.name ?? |
| 977 | f.operator ?? |
| 978 | f.operator_iata ?? |
| 979 | f.operator_icao ?? |
| 980 | 'Unknown', |
| 981 | iata: dbAirline?.iata |
| 982 | icao: dbAirline?.icao |
| 983 | image: dbAirline?.image |
| 984 | }, |
| 985 | }; |
| 986 | }); |
| 987 | |
| 988 | return { flights, |
| 989 | } catch (error) |
| 990 | if (error instanceof |
| 991 | console.error( |
| 992 | 'Error searching flights from FlightAware, falling back to database:', |
| 993 | error, |
| 994 | ); |
| 995 | return this.searchFlightsDbFallback |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | private async searchFlightsDbFallback |
| 1000 | iata: string |
| 1001 | icao: string |
| 1002 | userId: string, |
| 1003 | searchDate: Date |
| 1004 | nextDate: Date |
| 1005 | ): Promise<FlightSearchResponseEntity |
| 1006 | const where: |
| 1007 | OR: [ |
| 1008 | { callSign: { equals: |
| 1009 | { flightNo: { equals: |
| 1010 | ...(icao |
| 1011 | ? [ |
| 1012 | { callSign: { equals: |
| 1013 | { flightNo: { equals: |
| 1014 | ] |
| 1015 | : []), |
| 1016 | ], |
| 1017 | userId, |
| 1018 | }; |
| 1019 | if (searchDate && |
| 1020 | |
| 1021 | const dbFlights = |
| 1022 | where, |
| 1023 | include: { flightAwareData: true |
| 1024 | orderBy: { date: ' |
| 1025 | }); |
| 1026 | if (dbFlights.length |
| 1027 | throw new InternalServerErrorException( |
| 1028 | } |
| 1029 | |
| 1030 | const flights: |
| 1031 | const dep = |
| 1032 | const arr = |
| 1033 | const airline = |
| 1034 | const fa = |
| 1035 | return { |
| 1036 | faFlightId: fa?.faFlightId |
| 1037 | ident: fa?.ident |
| 1038 | origin: { |
| 1039 | code: dep?.airport |
| 1040 | codeIata: dep?.airport |
| 1041 | codeIcao: dep?.airport |
| 1042 | name: dep?.airport |
| 1043 | city: dep?.airport |
| 1044 | }, |
| 1045 | destination: { |
| 1046 | code: arr?.airport |
| 1047 | codeIata: arr?.airport |
| 1048 | codeIcao: arr?.airport |
| 1049 | name: arr?.airport |
| 1050 | city: arr?.airport |
| 1051 | }, |
| 1052 | scheduledOut: fa?.scheduledOut |
| 1053 | scheduledOff: fa?.scheduledOff |
| 1054 | status: fa?.status |
| 1055 | airline: { |
| 1056 | name: airline?.name |
| 1057 | iata: airline?.iata |
| 1058 | icao: airline?.icao |
| 1059 | image: airline?.image |
| 1060 | }, |
| 1061 | }; |
| 1062 | }); |
| 1063 | return { flights, |
| 1064 | } |
| 1065 | |
| 1066 | async getFlightTrack( |
| 1067 | { iata, icao |
| 1068 | userId: string, |
| 1069 | ) { |
| 1070 | const dateToUse = |
| 1071 | const { startOfDayUtc: |
| 1072 | parseDateInTimezone(dateToUse, timezone |
| 1073 | |
| 1074 | const existingFlight = |
| 1075 | where: { |
| 1076 | OR: [ |
| 1077 | { callSign: { equals: |
| 1078 | { flightNo: { equals: |
| 1079 | { callSign: { equals: |
| 1080 | { flightNo: { equals: |
| 1081 | ], |
| 1082 | userId, |
| 1083 | date: { gte: searchDate |
| 1084 | }, |
| 1085 | orderBy: { createdAt: ' |
| 1086 | include: { flightAwareData: true |
| 1087 | }); |
| 1088 | if (!existingFlight) |
| 1089 | throw new HttpException( |
| 1090 | } |
| 1091 | if (!existingFlight.flightAwareData |
| 1092 | throw new HttpException( |
| 1093 | 'FlightAware data not available for this flight', |
| 1094 | HttpStatus.NOT_FOUND, |
| 1095 | ); |
| 1096 | } |
| 1097 | |
| 1098 | const faFlightId = |
| 1099 | const cacheKey = |
| 1100 | const cacheTTL = |
| 1101 | |
| 1102 | const fa = |
| 1103 | const landingTime = |
| 1104 | const isFlightConcluded = |
| 1105 | ? (Date.now |
| 1106 | : false; |
| 1107 | |
| 1108 | // Concluded + complete data already persisted: serve from DB |
| 1109 | if (isFlightConcluded && |
| 1110 | console.log( |
| 1111 | `Flight ${faFlightId} has concluded and all positions are fetched. Returning database data.` |
| 1112 | ); |
| 1113 | const positions = |
| 1114 | where: { flightId: existingFlight |
| 1115 | orderBy: { timestamp: ' |
| 1116 | }); |
| 1117 | if (positions.length |
| 1118 | console.log( |
| 1119 | `FlightTrack: Returning ${positions.length} |
| 1120 | ); |
| 1121 | let actualDistance: |
| 1122 | if (positions.length |
| 1123 | const a = |
| 1124 | const b = |
| 1125 | const R = |
| 1126 | const dLat = |
| 1127 | const dLon = |
| 1128 | const x = |
| 1129 | Math.sin(dLat |
| 1130 | Math.cos((Number |
| 1131 | Math.cos((Number |
| 1132 | Math.sin(dLon |
| 1133 | actualDistance = R |
| 1134 | } |
| 1135 | return { |
| 1136 | actual_distance: actualDistance, |
| 1137 | positions: positions.map |
| 1138 | fa_flight_id: faFlightId, |
| 1139 | altitude: p.altitude |
| 1140 | altitude_change: ALT_CHANGE_TO_CODE[p |
| 1141 | groundspeed: p.groundSpeed |
| 1142 | heading: p.heading |
| 1143 | latitude: Number(p |
| 1144 | longitude: Number(p |
| 1145 | timestamp: p.timestamp |
| 1146 | update_type: UPDATE_TYPE_TO_CODE[p |
| 1147 | })), |
| 1148 | }; |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | const shouldSkipCache = |
| 1153 | isFlightConcluded && !existingFlight |
| 1154 | if (shouldSkipCache) { |
| 1155 | console.log( |
| 1156 | `Flight ${faFlightId} has concluded but positions not fully fetched. Fetching complete track data from FlightAware.` |
| 1157 | ); |
| 1158 | } |
| 1159 | |
| 1160 | if (!shouldSkipCache && |
| 1161 | try { |
| 1162 | const cached = |
| 1163 | if (cached) { |
| 1164 | console.log( |
| 1165 | `FlightTrack: Returning cached data for ${faFlightId} from application cache` |
| 1166 | ); |
| 1167 | return JSON.parse |
| 1168 | } |
| 1169 | } catch (error) |
| 1170 | console.warn('Redis cache read error in flight service: |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | console.log( |
| 1175 | `FlightTrack: Fetching ${isFlightConcluded ? |
| 1176 | ); |
| 1177 | const trackData = |
| 1178 | if (!trackData || |
| 1179 | throw new InternalServerErrorException( |
| 1180 | } |
| 1181 | |
| 1182 | await prisma.$transaction |
| 1183 | async (tx) |
| 1184 | for (const pos |
| 1185 | const id = |
| 1186 | const data = |
| 1187 | altitude: pos.altitude |
| 1188 | altitudeChange: ALT_CHANGE_FROM_CODE[pos |
| 1189 | groundSpeed: pos.groundspeed |
| 1190 | heading: pos.heading |
| 1191 | latitude: pos.latitude |
| 1192 | longitude: pos.longitude |
| 1193 | timestamp: new Date |
| 1194 | updatedType: UPDATE_TYPE_FROM_CODE[pos |
| 1195 | }; |
| 1196 | await tx.flightPositions |
| 1197 | where: { id |
| 1198 | update: data, |
| 1199 | create: { id, |
| 1200 | }); |
| 1201 | } |
| 1202 | if (isFlightConcluded) { |
| 1203 | await tx.flight |
| 1204 | where: { id: existingFlight |
| 1205 | data: { allFlightPositionsFetched: true |
| 1206 | }); |
| 1207 | console.log( |
| 1208 | `FlightTrack: Marked all positions as fetched for concluded flight ${faFlightId}`, |
| 1209 | ); |
| 1210 | } |
| 1211 | }, |
| 1212 | { timeout: 60000 }, |
| 1213 | ); |
| 1214 | |
| 1215 | const responseData = |
| 1216 | actual_distance: trackData.actual_distance |
| 1217 | positions: trackData.positions |
| 1218 | fa_flight_id: pos.fa_flight_id |
| 1219 | altitude: pos.altitude |
| 1220 | altitude_change: pos.altitude_change |
| 1221 | groundspeed: pos.groundspeed |
| 1222 | heading: pos.heading |
| 1223 | latitude: pos.latitude |
| 1224 | longitude: pos.longitude |
| 1225 | timestamp: pos.timestamp |
| 1226 | update_type: pos.update_type |
| 1227 | })), |
| 1228 | }; |
| 1229 | |
| 1230 | if (!isFlightConcluded && |
| 1231 | try { |
| 1232 | await this.redis |
| 1233 | console.log( |
| 1234 | `FlightTrack: Cached track data for ${faFlightId} for ${ |
| 1235 | ); |
| 1236 | } catch (error) |
| 1237 | console.warn('Redis cache write error in flight service: |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | return responseData; |
| 1242 | } |
| 1243 | |
| 1244 | async createFlightBooking(dto |
| 1245 | const flight = |
| 1246 | where: { id: dto |
| 1247 | }); |
| 1248 | if (!flight) |
| 1249 | throw new BadRequestException( |
| 1250 | 'Flight not found or does not belong to the user', |
| 1251 | ); |
| 1252 | } |
| 1253 | const existing = |
| 1254 | where: { flightId: dto |
| 1255 | }); |
| 1256 | if (existing) { |
| 1257 | throw new BadRequestException( |
| 1258 | 'A booking already exists for this flight. Use update endpoint to modify it.', |
| 1259 | ); |
| 1260 | } |
| 1261 | return prisma.flightBooking |
| 1262 | data: { |
| 1263 | flightId: dto.flightId |
| 1264 | userId, |
| 1265 | bookingCode: dto.bookingCode |
| 1266 | seatNumber: dto.seatNumber |
| 1267 | seatType: dto.seatType |
| 1268 | seatingClass: dto.seatingClass |
| 1269 | reason: dto.reason |
| 1270 | notes: dto.notes |
| 1271 | }, |
| 1272 | }); |
| 1273 | } |
| 1274 | |
| 1275 | async updateFlightBooking( |
| 1276 | bookingId: string, |
| 1277 | dto: UpdateFlightBookingDTO |
| 1278 | userId: string, |
| 1279 | ) { |
| 1280 | const existing = |
| 1281 | where: { id: bookingId |
| 1282 | }); |
| 1283 | if (!existing) |
| 1284 | throw new NotFoundException( |
| 1285 | 'Booking not found or does not belong to the user', |
| 1286 | ); |
| 1287 | } |
| 1288 | const data: |
| 1289 | const nullIfEmpty = |
| 1290 | if (dto.bookingCode |
| 1291 | if (dto.seatNumber |
| 1292 | if (dto.seatType |
| 1293 | if (dto.seatingClass |
| 1294 | if (dto.reason |
| 1295 | if (dto.notes |
| 1296 | |
| 1297 | return prisma.flightBooking |
| 1298 | } |
| 1299 | |
| 1300 | async getFlightBooking(bookingId |
| 1301 | const booking = |
| 1302 | where: { id: bookingId |
| 1303 | }); |
| 1304 | if (!booking) |
| 1305 | throw new NotFoundException( |
| 1306 | 'Booking not found or does not belong to the user', |
| 1307 | ); |
| 1308 | } |
| 1309 | return booking; |
| 1310 | } |
| 1311 | |
| 1312 | async getFlightBookingsByFlightId(flightId |
| 1313 | const flight = |
| 1314 | where: { id: flightId |
| 1315 | }); |
| 1316 | if (!flight) |
| 1317 | throw new BadRequestException( |
| 1318 | 'Flight not found or does not belong to the user', |
| 1319 | ); |
| 1320 | } |
| 1321 | return prisma.flightBooking |
| 1322 | where: { flightId, |
| 1323 | orderBy: { createdAt: ' |
| 1324 | }); |
| 1325 | } |
| 1326 | |
| 1327 | async deleteFlightBooking(bookingId |
| 1328 | const existing = |
| 1329 | where: { id: bookingId |
| 1330 | }); |
| 1331 | if (!existing) |
| 1332 | throw new NotFoundException( |
| 1333 | 'Booking not found or does not belong to the user', |
| 1334 | ); |
| 1335 | } |
| 1336 | await prisma.flightBooking |
| 1337 | return { message: |
| 1338 | } |
| 1339 | } |