| 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 { UpdateFlightBookingDTO } |
| 22 | import { |
| 23 | AircraftEntity, |
| 24 | FlightCandidateEntity, |
| 25 | FlightSearchResponseEntity, |
| 26 | } from './entities/flight.entity'; |
| 27 | |
| 28 | @Injectable() |
| 29 | export class FlightService |
| 30 | private redis: |
| 31 | |
| 32 | constructor( |
| 33 | private readonly configService |
| 34 | private readonly flightAwareService |
| 35 | private readonly redisService |
| 36 | ) { |
| 37 | this.redis = |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Converts a date string (e.g., "2025-11-04") interpreted as midnight in the user's timezone |
| 42 | * to UTC Date objects for database queries |
| 43 | */ |
| 44 | private parseDateInTimezone( |
| 45 | dateString: string, |
| 46 | timezone: string, |
| 47 | ): { |
| 48 | startOfDayUtc: Date |
| 49 | endOfDayUtc: Date |
| 50 | } { |
| 51 | // Validate date format (YYYY-MM-DD) |
| 52 | const dateParts = |
| 53 | if (dateParts.length |
| 54 | throw new BadRequestException( |
| 55 | } |
| 56 | |
| 57 | // Map common abbreviations to representative IANA zones (handles DST correctly) |
| 58 | const mapAbbrevToIana = |
| 59 | const A = |
| 60 | const table: |
| 61 | UTC: 'UTC', |
| 62 | GMT: 'Etc/UTC', |
| 63 | BST: 'Europe/London', |
| 64 | CET: 'Europe/Berlin', |
| 65 | CEST: 'Europe/Berlin', |
| 66 | EET: 'Europe/Athens', |
| 67 | EEST: 'Europe/Athens', |
| 68 | IST: 'Asia/Kolkata', // |
| 69 | PKT: 'Asia/Karachi', |
| 70 | MSK: 'Europe/Moscow', |
| 71 | AST: 'America/Halifax', |
| 72 | ADT: 'America/Halifax', |
| 73 | EST: 'America/New_York', |
| 74 | EDT: 'America/New_York', |
| 75 | CST: 'America/Chicago', |
| 76 | CDT: 'America/Chicago', |
| 77 | MST: 'America/Denver', |
| 78 | MDT: 'America/Denver', |
| 79 | PST: 'America/Los_Angeles', |
| 80 | PDT: 'America/Los_Angeles', |
| 81 | AKST: 'America/Anchorage', |
| 82 | AKDT: 'America/Anchorage', |
| 83 | HST: 'Pacific/Honolulu', |
| 84 | JST: 'Asia/Tokyo', |
| 85 | KST: 'Asia/Seoul', |
| 86 | AEST: 'Australia/Sydney', |
| 87 | AEDT: 'Australia/Sydney', |
| 88 | ACST: 'Australia/Adelaide', |
| 89 | ACDT: 'Australia/Adelaide', |
| 90 | AWST: 'Australia/Perth', |
| 91 | }; |
| 92 | return table[A |
| 93 | }; |
| 94 | |
| 95 | // Resolve a Luxon zone: prefer valid IANA; otherwise use mapping for abbreviations; fallback UTC |
| 96 | const resolveZone = |
| 97 | if (tz && |
| 98 | const mapped = |
| 99 | if (mapped && |
| 100 | return 'UTC'; |
| 101 | }; |
| 102 | |
| 103 | const zone = |
| 104 | const start = |
| 105 | const end = |
| 106 | |
| 107 | return { |
| 108 | startOfDayUtc: start.toJSDate |
| 109 | endOfDayUtc: end.toJSDate |
| 110 | }; |
| 111 | } |
| 112 | |
| 113 | async getFlight( |
| 114 | { iata, icao |
| 115 | userId: string, |
| 116 | ) { |
| 117 | // Parse date with timezone consideration |
| 118 | const dateToUse = |
| 119 | const { startOfDayUtc: |
| 120 | this.parseDateInTimezone(dateToUse |
| 121 | |
| 122 | const existingFlight = |
| 123 | where: { |
| 124 | OR: [ |
| 125 | { callSign: iata |
| 126 | { flightNo: iata |
| 127 | { callSign: icao |
| 128 | { flightNo: icao |
| 129 | ], |
| 130 | date: { |
| 131 | gte: searchDate, |
| 132 | lt: nextDate, |
| 133 | }, |
| 134 | }, |
| 135 | orderBy: { |
| 136 | createdAt: 'desc', |
| 137 | }, |
| 138 | include: { |
| 139 | greatCircleDistance: true, |
| 140 | flightAwareData: true, |
| 141 | bookings: { |
| 142 | where: { |
| 143 | userId, |
| 144 | }, |
| 145 | orderBy: { |
| 146 | createdAt: 'desc', |
| 147 | }, |
| 148 | }, |
| 149 | }, |
| 150 | }); |
| 151 | |
| 152 | // If forceUpdate is not specified and flight exists, return it |
| 153 | if (!forceUpdate && |
| 154 | let aircraft: |
| 155 | if (existingFlight?.aircraft |
| 156 | const stored = |
| 157 | const hexCandidate: |
| 158 | stored?.modeS ?? |
| 159 | const regCandidate: |
| 160 | stored?.reg ?? |
| 161 | if (hexCandidate) { |
| 162 | aircraft = await |
| 163 | where: { hexIcao: hexCandidate |
| 164 | include: { registrations: true |
| 165 | }); |
| 166 | } |
| 167 | if (!aircraft && |
| 168 | aircraft = await |
| 169 | where: { reg: regCandidate |
| 170 | include: { registrations: true |
| 171 | }); |
| 172 | } |
| 173 | } |
| 174 | const stored = |
| 175 | const normalizedFromStored: |
| 176 | ? ({ |
| 177 | modeS: stored.modeS |
| 178 | age: (stored.ageYears |
| 179 | image: stored.image |
| 180 | attribution: |
| 181 | stored.attribution ?? |
| 182 | isFreighter: stored.isFreighter |
| 183 | model: stored.typeName |
| 184 | registration: |
| 185 | stored.reg ?? |
| 186 | aircraft_id: stored.aircraft_id |
| 187 | payload: stored.payload |
| 188 | deliveryDate: |
| 189 | stored.deliveryDate ?? |
| 190 | (stored.deliveryDate |
| 191 | ? new Date( |
| 192 | : undefined), |
| 193 | firstFlightDate: |
| 194 | stored.firstFlightDate ?? |
| 195 | (stored.firstFlightDate |
| 196 | ? new Date( |
| 197 | : undefined), |
| 198 | } as AircraftEntity) |
| 199 | : undefined; |
| 200 | |
| 201 | // Query airline from DB to get correct name and image |
| 202 | const storedAirline = |
| 203 | const airlineIata = |
| 204 | const airlineIcao = |
| 205 | |
| 206 | const dbAirline = |
| 207 | where: { |
| 208 | OR: [ |
| 209 | airlineIata ? { iata |
| 210 | airlineIcao ? { icao |
| 211 | ].filter(Boolean) |
| 212 | }, |
| 213 | }); |
| 214 | |
| 215 | // Merge airline data: prefer DB, fallback to stored |
| 216 | const mergedAirline = |
| 217 | ? { |
| 218 | name: dbAirline.name |
| 219 | iata: dbAirline.iata |
| 220 | icao: dbAirline.icao |
| 221 | image: dbAirline.image |
| 222 | } |
| 223 | : storedAirline; |
| 224 | |
| 225 | return { |
| 226 | ...existingFlight, |
| 227 | airline: mergedAirline, |
| 228 | aircraft: aircraft |
| 229 | ? ({ |
| 230 | modeS: aircraft.hexIcao |
| 231 | age: aircraft.age |
| 232 | image: aircraft.image |
| 233 | attribution: aircraft.attribution |
| 234 | isFreighter: aircraft.isFreighter |
| 235 | model: aircraft.typeName |
| 236 | registration: aircraft.reg |
| 237 | aircraft_id: aircraft.aircraft_id |
| 238 | deliveryDate: aircraft.deliveryDate |
| 239 | firstFlightDate: aircraft.firstFlightDate |
| 240 | payload: aircraft.payload |
| 241 | registrations: (aircraft.registrations |
| 242 | id: r.id |
| 243 | reg: r.reg |
| 244 | active: r.active |
| 245 | hexIcao: r.hexIcao |
| 246 | airlineName: r.airlineName |
| 247 | registrationDate: r.registrationDate |
| 248 | })), |
| 249 | } satisfies AircraftEntity) |
| 250 | : normalizedFromStored, |
| 251 | bookings: existingFlight.bookings |
| 252 | }; |
| 253 | } |
| 254 | |
| 255 | // Fetch flight data from FlightAware API only |
| 256 | try { |
| 257 | let flightAwareResponse: |
| 258 | let faFlight: |
| 259 | |
| 260 | // If faFlightId is provided, try to get from Redis cache first to avoid API call |
| 261 | if (faFlightId) { |
| 262 | const record = |
| 263 | where: { |
| 264 | OR: [ |
| 265 | { |
| 266 | flightAwareData: { |
| 267 | faFlightId, |
| 268 | }, |
| 269 | }, |
| 270 | { |
| 271 | id: faFlightId, // |
| 272 | }, |
| 273 | ], |
| 274 | }, |
| 275 | include: { |
| 276 | flightAwareData: true, |
| 277 | }, |
| 278 | }); |
| 279 | |
| 280 | console.log( |
| 281 | `Fetching specific flight using fa_flight_id ${record?.flightAwareData |
| 282 | ); |
| 283 | |
| 284 | // Try to get from Redis cache first (cached from searchFlights) |
| 285 | let cachedFlight: |
| 286 | if (this.redis |
| 287 | try { |
| 288 | const flightCacheKey = |
| 289 | const cached = |
| 290 | if (cached) { |
| 291 | cachedFlight = JSON. |
| 292 | console.log( |
| 293 | `Retrieved flight ${record?.flightAwareData |
| 294 | ); |
| 295 | } |
| 296 | } catch (error) |
| 297 | console.warn('Failed to read flight from Redis cache: |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | if (cachedFlight) { |
| 302 | // Use cached flight data |
| 303 | faFlight = cachedFlight; |
| 304 | // Create a FlightAwareResponse-like structure for compatibility |
| 305 | flightAwareResponse = { |
| 306 | flights: [cachedFlight], |
| 307 | links: {}, |
| 308 | num_pages: 1, |
| 309 | }; |
| 310 | } else { |
| 311 | // Cache miss - fetch from FlightAware API |
| 312 | console.log( |
| 313 | `Cache miss for ${record?.flightAwareData |
| 314 | ); |
| 315 | flightAwareResponse = |
| 316 | await this.flightAwareService |
| 317 | |
| 318 | if (!flightAwareResponse || |
| 319 | throw new BadRequestException( |
| 320 | 'Unable to fetch flight information with the provided flight ID.', |
| 321 | ); |
| 322 | } |
| 323 | |
| 324 | // When using fa_flight_id, we get exactly 1 flight in the array |
| 325 | faFlight = flightAwareResponse. |
| 326 | |
| 327 | // Cache it for future use (cache miss scenario) |
| 328 | if (this.redis |
| 329 | try { |
| 330 | const flightCacheKey = |
| 331 | await this.redis |
| 332 | flightCacheKey, |
| 333 | 3600, |
| 334 | JSON.stringify(faFlight |
| 335 | ); |
| 336 | console.log( |
| 337 | `Cached flight ${record?.flightAwareData |
| 338 | ); |
| 339 | } catch (error) |
| 340 | console.warn('Failed to cache flight in Redis: |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } else if (forceUpdate |
| 345 | // If forceUpdate is true and we have an existing flight with fa_flight_id, use that |
| 346 | const existingFaFlightId = |
| 347 | console.log( |
| 348 | `Force update: Using existing fa_flight_id ${existingFaFlightId} to fetch from FlightAware` |
| 349 | ); |
| 350 | flightAwareResponse = |
| 351 | await this.flightAwareService |
| 352 | existingFaFlightId, |
| 353 | ); |
| 354 | |
| 355 | if (!flightAwareResponse || |
| 356 | throw new BadRequestException( |
| 357 | 'Unable to fetch flight information. Please make sure the flight number is correct.', |
| 358 | ); |
| 359 | } |
| 360 | |
| 361 | // When using fa_flight_id, we get exactly 1 flight in the array |
| 362 | faFlight = flightAwareResponse. |
| 363 | } else { |
| 364 | // Normal flow: use iata/icao identifier |
| 365 | const flightAwareIdent = |
| 366 | if (!flightAwareIdent) |
| 367 | throw new BadRequestException( |
| 368 | } |
| 369 | |
| 370 | flightAwareResponse = |
| 371 | await this.flightAwareService |
| 372 | |
| 373 | if (!flightAwareResponse || |
| 374 | throw new BadRequestException( |
| 375 | 'Unable to fetch flight information. Please make sure the flight number is correct.', |
| 376 | ); |
| 377 | } |
| 378 | |
| 379 | // Use the first flight or try to match by date |
| 380 | faFlight = flightAwareResponse. |
| 381 | |
| 382 | // Try to find a flight matching the search date |
| 383 | if (flightAwareResponse.flights |
| 384 | const matchedFlight = |
| 385 | const flightDate = |
| 386 | ? new Date( |
| 387 | : flight.scheduled_off |
| 388 | ? new Date( |
| 389 | : null; |
| 390 | |
| 391 | if (flightDate) { |
| 392 | // Check if flight date falls within the UTC date range for the user's timezone date |
| 393 | return flightDate >= |
| 394 | } |
| 395 | return false; |
| 396 | }); |
| 397 | |
| 398 | if (matchedFlight) { |
| 399 | faFlight = matchedFlight; |
| 400 | console.log( |
| 401 | `Matched FlightAware flight by date: ${faFlight.fa_flight_id |
| 402 | ); |
| 403 | } else { |
| 404 | console.log( |
| 405 | `No date match found, using first flight: ${faFlight.fa_flight_id |
| 406 | ); |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // Calculate great circle distance (approximate) |
| 412 | const greatCircleDistance = |
| 413 | ? { |
| 414 | meter: Math.round |
| 415 | km: (faFlight.route_distance |
| 416 | mile: (faFlight.route_distance |
| 417 | nm: faFlight.route_distance |
| 418 | feet: Math.round |
| 419 | } |
| 420 | : null; |
| 421 | |
| 422 | // Resolve airline from DB using IATA/ICAO |
| 423 | const airlineIata = |
| 424 | const airlineIcao = |
| 425 | |
| 426 | const dbAirline = |
| 427 | where: { |
| 428 | OR: [ |
| 429 | airlineIata ? { iata |
| 430 | airlineIcao ? { icao |
| 431 | ].filter(Boolean) |
| 432 | }, |
| 433 | }); |
| 434 | |
| 435 | // Resolve airport coordinates from DB using IATA/ICAO |
| 436 | const depIata = |
| 437 | const depIcao = |
| 438 | faFlight.origin?.code_icao |
| 439 | const arrIata = |
| 440 | const arrIcao = |
| 441 | faFlight.destination?.code_icao |
| 442 | faFlight.destination?.code |
| 443 | undefined; |
| 444 | |
| 445 | const [depAirport, |
| 446 | prisma.airport.findFirst |
| 447 | where: { |
| 448 | OR: [ |
| 449 | depIata ? { iataCode |
| 450 | depIcao |
| 451 | ? { OR: [{ |
| 452 | : undefined, |
| 453 | ].filter(Boolean) |
| 454 | }, |
| 455 | }), |
| 456 | prisma.airport.findFirst |
| 457 | where: { |
| 458 | OR: [ |
| 459 | arrIata ? { iataCode |
| 460 | arrIcao |
| 461 | ? { OR: [{ |
| 462 | : undefined, |
| 463 | ].filter(Boolean) |
| 464 | }, |
| 465 | }), |
| 466 | ]); |
| 467 | |
| 468 | const flightData = |
| 469 | userId, |
| 470 | flightNo: faFlight.ident |
| 471 | callSign: faFlight.ident |
| 472 | aircraft: { |
| 473 | registration: faFlight.registration |
| 474 | type: faFlight.aircraft_type |
| 475 | }, |
| 476 | airline: { |
| 477 | name: |
| 478 | dbAirline?.name ?? |
| 479 | faFlight.operator ?? |
| 480 | faFlight.operator_iata ?? |
| 481 | 'Unknown', |
| 482 | iata: dbAirline?.iata |
| 483 | icao: dbAirline?.icao |
| 484 | image: dbAirline?.image |
| 485 | }, |
| 486 | arrival: { |
| 487 | airport: { |
| 488 | icao: faFlight.destination |
| 489 | iata: faFlight.destination |
| 490 | name: faFlight.destination |
| 491 | municipalityName: faFlight.destination |
| 492 | location: { |
| 493 | lat: arrAirport ? |
| 494 | lon: arrAirport ? |
| 495 | }, |
| 496 | countryCode: |
| 497 | faFlight.destination?.code_icao |
| 498 | timeZone: faFlight.destination |
| 499 | shortName: faFlight?.destination |
| 500 | }, |
| 501 | scheduledTime: { |
| 502 | utc: faFlight.scheduled_on |
| 503 | local: faFlight.scheduled_on |
| 504 | }, |
| 505 | revisedTime: faFlight.estimated_on |
| 506 | ? { |
| 507 | utc: faFlight.estimated_on |
| 508 | local: faFlight.estimated_on |
| 509 | } |
| 510 | : null, |
| 511 | actualTime: faFlight.actual_on |
| 512 | ? { |
| 513 | utc: faFlight.actual_on |
| 514 | local: faFlight.actual_on |
| 515 | } |
| 516 | : null, |
| 517 | terminal: faFlight.terminal_destination |
| 518 | gate: faFlight.gate_destination |
| 519 | }, |
| 520 | cargo: false, |
| 521 | date: faFlight.scheduled_out |
| 522 | ? new Date( |
| 523 | : searchDate, |
| 524 | departure: { |
| 525 | airport: { |
| 526 | shortName: faFlight?.origin |
| 527 | icao: faFlight.origin |
| 528 | iata: faFlight.origin |
| 529 | name: faFlight.origin |
| 530 | municipalityName: faFlight.origin |
| 531 | location: { |
| 532 | lat: depAirport ? |
| 533 | lon: depAirport ? |
| 534 | }, |
| 535 | countryCode: faFlight.origin |
| 536 | timeZone: faFlight.origin |
| 537 | }, |
| 538 | scheduledTime: { |
| 539 | utc: faFlight.scheduled_out |
| 540 | local: faFlight.scheduled_out |
| 541 | }, |
| 542 | revisedTime: faFlight.estimated_out |
| 543 | ? { |
| 544 | utc: faFlight.estimated_out |
| 545 | local: faFlight.estimated_out |
| 546 | } |
| 547 | : null, |
| 548 | actualTime: faFlight.actual_out |
| 549 | ? { |
| 550 | utc: faFlight.actual_out |
| 551 | local: faFlight.actual_out |
| 552 | } |
| 553 | : null, |
| 554 | terminal: faFlight.terminal_origin |
| 555 | gate: faFlight.gate_origin |
| 556 | }, |
| 557 | }; |
| 558 | |
| 559 | // Update existing flight if forceUpdate is true, otherwise create new |
| 560 | const newFlight = |
| 561 | forceUpdate && existingFlight |
| 562 | ? await prisma. |
| 563 | where: { id: existingFlight |
| 564 | data: flightData, |
| 565 | include: { |
| 566 | greatCircleDistance: true, |
| 567 | }, |
| 568 | }) |
| 569 | : await prisma. |
| 570 | data: { |
| 571 | ...flightData, |
| 572 | id: `flight_${createId |
| 573 | }, |
| 574 | include: { |
| 575 | greatCircleDistance: true, |
| 576 | }, |
| 577 | }); |
| 578 | |
| 579 | // Handle greatCircleDistance separately (upsert) |
| 580 | if (greatCircleDistance) { |
| 581 | await prisma.greatCircleDistance |
| 582 | where: { flightId: newFlight |
| 583 | update: greatCircleDistance, |
| 584 | create: { |
| 585 | ...greatCircleDistance, |
| 586 | flightId: newFlight.id |
| 587 | }, |
| 588 | }); |
| 589 | } |
| 590 | |
| 591 | console.log( |
| 592 | forceUpdate && existingFlight |
| 593 | ? `Updated flight from FlightAware: ${faFlight. |
| 594 | : `Created flight from FlightAware: ${faFlight. |
| 595 | ); |
| 596 | |
| 597 | // Upsert FlightAwareData (update if exists, create if not) |
| 598 | const flightAwareDataPayload = |
| 599 | ident: faFlight.ident |
| 600 | identIcao: faFlight.ident_icao |
| 601 | identIata: faFlight.ident_iata |
| 602 | actualRunwayOff: faFlight.actual_runway_off |
| 603 | actualRunwayOn: faFlight.actual_runway_on |
| 604 | operator: faFlight.operator |
| 605 | operatorIcao: faFlight.operator_icao |
| 606 | operatorIata: faFlight.operator_iata |
| 607 | flightNumber: faFlight.flight_number |
| 608 | registration: faFlight.registration |
| 609 | atcIdent: faFlight.atc_ident |
| 610 | inboundFaFlightId: faFlight.inbound_fa_flight_id |
| 611 | codesharesIata: faFlight.codeshares_iata |
| 612 | codesharesIcao: faFlight.codeshares |
| 613 | departureDelay: faFlight.departure_delay |
| 614 | arrivalDelay: faFlight.arrival_delay |
| 615 | filedEte: faFlight.filed_ete |
| 616 | progressPercent: faFlight.progress_percent |
| 617 | status: faFlight.status |
| 618 | aircraftType: faFlight.aircraft_type |
| 619 | routeDistance: faFlight.route_distance |
| 620 | filedAirspeed: faFlight.filed_airspeed |
| 621 | filedAltitude: faFlight.filed_altitude |
| 622 | route: faFlight.route |
| 623 | baggageClaim: faFlight.baggage_claim |
| 624 | seatsCabinBusiness: faFlight.seats_cabin_business |
| 625 | seatsCabinCoach: faFlight.seats_cabin_coach |
| 626 | seatsCabinFirst: faFlight.seats_cabin_first |
| 627 | gateOrigin: faFlight.gate_origin |
| 628 | gateDestination: faFlight.gate_destination |
| 629 | terminalOrigin: faFlight.terminal_origin |
| 630 | terminalDestination: faFlight.terminal_destination |
| 631 | scheduledOut: faFlight.scheduled_out |
| 632 | ? new Date( |
| 633 | : null, |
| 634 | estimatedOut: faFlight.estimated_out |
| 635 | ? new Date( |
| 636 | : null, |
| 637 | actualOut: faFlight.actual_out |
| 638 | scheduledOff: faFlight.scheduled_off |
| 639 | ? new Date( |
| 640 | : null, |
| 641 | estimatedOff: faFlight.estimated_off |
| 642 | ? new Date( |
| 643 | : null, |
| 644 | actualOff: faFlight.actual_off |
| 645 | scheduledOn: faFlight.scheduled_on |
| 646 | ? new Date( |
| 647 | : null, |
| 648 | estimatedOn: faFlight.estimated_on |
| 649 | ? new Date( |
| 650 | : null, |
| 651 | actualOn: faFlight.actual_on |
| 652 | scheduledIn: faFlight.scheduled_in |
| 653 | ? new Date( |
| 654 | : null, |
| 655 | estimatedIn: faFlight.estimated_in |
| 656 | ? new Date( |
| 657 | : null, |
| 658 | actualIn: faFlight.actual_in |
| 659 | foresightPredictionsAvailable: |
| 660 | faFlight.foresight_predictions_available ?? |
| 661 | blocked: faFlight.blocked |
| 662 | diverted: faFlight.diverted |
| 663 | cancelled: faFlight.cancelled |
| 664 | positionOnly: faFlight.position_only |
| 665 | originCode: faFlight?.origin |
| 666 | originCodeIcao: faFlight?.origin |
| 667 | originCodeIata: faFlight?.origin |
| 668 | originCodeLid: faFlight?.origin |
| 669 | originTimezone: faFlight?.origin |
| 670 | originName: faFlight?.origin |
| 671 | originCity: faFlight?.origin |
| 672 | destinationCode: faFlight?.destination |
| 673 | destinationCodeIcao: faFlight?.destination |
| 674 | destinationCodeIata: faFlight?.destination |
| 675 | destinationCodeLid: faFlight?.destination |
| 676 | destinationTimezone: faFlight?.destination |
| 677 | destinationName: faFlight?.destination |
| 678 | destinationCity: faFlight?.destination |
| 679 | flightId: newFlight.id |
| 680 | }; |
| 681 | |
| 682 | // Update or create FlightAwareData |
| 683 | // If forceUpdate is true and we have an existing flight, we know FlightAwareData exists |
| 684 | if (forceUpdate && |
| 685 | // Update existing FlightAwareData to avoid unique constraint failure |
| 686 | await prisma.flightAwareData |
| 687 | where: { id: existingFlight |
| 688 | data: flightAwareDataPayload, |
| 689 | }); |
| 690 | } else { |
| 691 | // Check if FlightAwareData exists, then update or create |
| 692 | const existingFlightAwareData = |
| 693 | where: { faFlightId: faFlight |
| 694 | }); |
| 695 | |
| 696 | if (existingFlightAwareData) { |
| 697 | await prisma.flightAwareData |
| 698 | where: { id: existingFlightAwareData |
| 699 | data: flightAwareDataPayload, |
| 700 | }); |
| 701 | } else { |
| 702 | await prisma.flightAwareData |
| 703 | data: { |
| 704 | faFlightId: faFlight.fa_flight_id |
| 705 | ...flightAwareDataPayload, |
| 706 | }, |
| 707 | }); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | // Handle aircraft information using AeroDataBox |
| 712 | let normalizedAircraft: |
| 713 | const registration = |
| 714 | const apiKey = |
| 715 | |
| 716 | if (registration) { |
| 717 | // Check if aircraft already exists in database |
| 718 | let aircraft: |
| 719 | where: { |
| 720 | reg: registration, |
| 721 | }, |
| 722 | include: { registrations: true |
| 723 | }); |
| 724 | |
| 725 | if (aircraft) { |
| 726 | normalizedAircraft = { |
| 727 | modeS: aircraft.hexIcao |
| 728 | age: aircraft.age |
| 729 | image: aircraft.image |
| 730 | attribution: aircraft.attribution |
| 731 | isFreighter: aircraft.isFreighter |
| 732 | model: aircraft.typeName |
| 733 | registration: aircraft.reg |
| 734 | aircraft_id: aircraft.aircraft_id |
| 735 | deliveryDate: aircraft.deliveryDate |
| 736 | firstFlightDate: aircraft.firstFlightDate |
| 737 | payload: aircraft.payload |
| 738 | registrations: (aircraft.registrations |
| 739 | id: r.id |
| 740 | reg: r.reg |
| 741 | active: r.active |
| 742 | hexIcao: r.hexIcao |
| 743 | airlineName: r.airlineName |
| 744 | registrationDate: r.registrationDate |
| 745 | })), |
| 746 | } satisfies AircraftEntity; |
| 747 | } else if (apiKey |
| 748 | // Fetch aircraft details from AeroDataBox |
| 749 | try { |
| 750 | const aeroDataBoxRes = |
| 751 | `https://aerodatabox.p.rapidapi.com/aircrafts/reg/${registration}?withImage=true&withRegistrations=true` |
| 752 | { |
| 753 | headers: { |
| 754 | 'X-RapidAPI-Key': apiKey, |
| 755 | 'X-RapidAPI-Host': 'aerodatabox.p.rapidapi.com', |
| 756 | }, |
| 757 | }, |
| 758 | ); |
| 759 | |
| 760 | if (aeroDataBoxRes.ok |
| 761 | const json = |
| 762 | |
| 763 | // Create aircraft record with AeroDataBox data |
| 764 | aircraft = await |
| 765 | data: { |
| 766 | aircraft_id: String(json |
| 767 | payload: json, |
| 768 | reg: json.reg |
| 769 | hexIcao: json.hexIcao |
| 770 | modelCode: json.modelCode |
| 771 | firstFlightDate: json.firstFlightDate |
| 772 | ? new Date( |
| 773 | : null, |
| 774 | deliveryDate: json.deliveryDate |
| 775 | ? new Date( |
| 776 | : null, |
| 777 | typeName: json.typeName |
| 778 | isFreighter: json.isFreighter |
| 779 | age: json.ageYears |
| 780 | image: json?.image |
| 781 | attribution: json?.image |
| 782 | ? `${json.image |
| 783 | : null, |
| 784 | registrations: json.registrations |
| 785 | ? { |
| 786 | createMany: { |
| 787 | data: json.registrations |
| 788 | id: `registration_${createId |
| 789 | active: data.active |
| 790 | reg: data.reg |
| 791 | airlineName: data.airlineName |
| 792 | registrationDate: data.registrationDate |
| 793 | ? new Date( |
| 794 | : null, |
| 795 | hexIcao: data.hexIcao |
| 796 | })), |
| 797 | skipDuplicates: true, |
| 798 | }, |
| 799 | } |
| 800 | : undefined, |
| 801 | }, |
| 802 | include: { registrations: true |
| 803 | }); |
| 804 | |
| 805 | normalizedAircraft = { |
| 806 | modeS: aircraft.hexIcao |
| 807 | age: aircraft.age |
| 808 | image: aircraft.image |
| 809 | attribution: aircraft.attribution |
| 810 | isFreighter: aircraft.isFreighter |
| 811 | model: aircraft.typeName |
| 812 | registration: aircraft.reg |
| 813 | aircraft_id: aircraft.aircraft_id |
| 814 | deliveryDate: aircraft.deliveryDate |
| 815 | firstFlightDate: aircraft.firstFlightDate |
| 816 | payload: aircraft.payload |
| 817 | registrations: (aircraft.registrations |
| 818 | id: r.id |
| 819 | reg: r.reg |
| 820 | active: r.active |
| 821 | hexIcao: r.hexIcao |
| 822 | airlineName: r.airlineName |
| 823 | registrationDate: r.registrationDate |
| 824 | })), |
| 825 | } satisfies AircraftEntity; |
| 826 | |
| 827 | console.log( |
| 828 | `Fetched aircraft data from AeroDataBox for ${registration}`, |
| 829 | ); |
| 830 | } else { |
| 831 | throw new Error( |
| 832 | } |
| 833 | } catch (error) |
| 834 | console.error('Error fetching from AeroDataBox: |
| 835 | |
| 836 | // Fallback to Planespotters for image only |
| 837 | let planespotterImage: |
| 838 | let planespotterAttribution: |
| 839 | |
| 840 | try { |
| 841 | const planespotterRes = |
| 842 | `https://api.planespotters.net/pub/photos/reg/${registration}`, |
| 843 | ); |
| 844 | if (planespotterRes.ok |
| 845 | const planespotterData = |
| 846 | if ( |
| 847 | planespotterData.photos && |
| 848 | planespotterData.photos.length |
| 849 | ) { |
| 850 | planespotterImage = |
| 851 | planespotterData.photos[0] |
| 852 | planespotterAttribution = `Photo by ${ |
| 853 | } |
| 854 | } |
| 855 | } catch (e) |
| 856 | console.error('Error fetching from Planespotters: |
| 857 | } |
| 858 | |
| 859 | // Create minimal aircraft record with Planespotters image |
| 860 | aircraft = await |
| 861 | data: { |
| 862 | aircraft_id: `aircraft_${createId |
| 863 | reg: registration, |
| 864 | hexIcao: '', |
| 865 | typeName: faFlight.aircraft_type |
| 866 | modelCode: faFlight.aircraft_type |
| 867 | isFreighter: false, |
| 868 | age: 0, |
| 869 | image: planespotterImage, |
| 870 | attribution: planespotterAttribution, |
| 871 | payload: {}, |
| 872 | }, |
| 873 | }); |
| 874 | |
| 875 | normalizedAircraft = { |
| 876 | modeS: aircraft.hexIcao |
| 877 | age: aircraft.age |
| 878 | image: aircraft.image |
| 879 | attribution: aircraft.attribution |
| 880 | isFreighter: aircraft.isFreighter |
| 881 | model: aircraft.typeName |
| 882 | registration: aircraft.reg |
| 883 | aircraft_id: aircraft.aircraft_id |
| 884 | deliveryDate: aircraft.deliveryDate |
| 885 | firstFlightDate: aircraft.firstFlightDate |
| 886 | payload: aircraft.payload |
| 887 | } satisfies AircraftEntity; |
| 888 | } |
| 889 | } else { |
| 890 | // No API key, create minimal record |
| 891 | normalizedAircraft = { |
| 892 | //@ts-expect-error |
| 893 | ...newFlight.aircraft |
| 894 | registration: registration, |
| 895 | model: faFlight.aircraft_type |
| 896 | }; |
| 897 | } |
| 898 | } else { |
| 899 | // No registration available, use basic aircraft info from flight data |
| 900 | normalizedAircraft = { |
| 901 | //@ts-expect-error |
| 902 | ...newFlight.aircraft |
| 903 | registration: faFlight.registration |
| 904 | model: faFlight.aircraft_type |
| 905 | }; |
| 906 | } |
| 907 | |
| 908 | // Reload flight with FlightAware data to include it in response |
| 909 | const flightWithAwareData = |
| 910 | where: { id: newFlight |
| 911 | include: { |
| 912 | greatCircleDistance: true, |
| 913 | flightAwareData: { |
| 914 | omit: { |
| 915 | faFlightId: true, |
| 916 | }, |
| 917 | }, |
| 918 | bookings: { |
| 919 | where: { |
| 920 | userId, |
| 921 | }, |
| 922 | orderBy: { |
| 923 | createdAt: 'desc', |
| 924 | }, |
| 925 | }, |
| 926 | }, |
| 927 | }); |
| 928 | |
| 929 | // Query airline from DB to get correct name and image |
| 930 | const storedAirlineFinal = |
| 931 | const airlineIataFinal = |
| 932 | const airlineIcaoFinal = |
| 933 | |
| 934 | const dbAirlineFinal = |
| 935 | where: { |
| 936 | OR: [ |
| 937 | airlineIataFinal ? { iata |
| 938 | airlineIcaoFinal ? { icao |
| 939 | ].filter(Boolean) |
| 940 | }, |
| 941 | }); |
| 942 | |
| 943 | // Merge airline data: prefer DB, fallback to stored |
| 944 | const mergedAirlineFinal = |
| 945 | ? { |
| 946 | name: dbAirlineFinal.name |
| 947 | iata: dbAirlineFinal.iata |
| 948 | icao: dbAirlineFinal.icao |
| 949 | image: dbAirlineFinal.image |
| 950 | } |
| 951 | : storedAirlineFinal; |
| 952 | |
| 953 | // Preserve the normalized aircraft data in the response |
| 954 | if (flightWithAwareData && |
| 955 | return { |
| 956 | ...flightWithAwareData, |
| 957 | airline: mergedAirlineFinal, |
| 958 | aircraft: normalizedAircraft, |
| 959 | bookings: flightWithAwareData.bookings |
| 960 | }; |
| 961 | } |
| 962 | |
| 963 | return flightWithAwareData |
| 964 | ? { |
| 965 | ...flightWithAwareData, |
| 966 | airline: mergedAirlineFinal, |
| 967 | bookings: flightWithAwareData.bookings |
| 968 | } |
| 969 | : { |
| 970 | ...newFlight, |
| 971 | bookings: [], |
| 972 | }; |
| 973 | } catch (error) |
| 974 | if ( |
| 975 | error instanceof UnauthorizedException |
| 976 | error instanceof BadRequestException |
| 977 | ) { |
| 978 | throw error; |
| 979 | } |
| 980 | console.error('Error fetching flight data: |
| 981 | throw new InternalServerErrorException( |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | async searchFlights( |
| 986 | { iata, icao |
| 987 | userId: string, |
| 988 | ): Promise<FlightSearchResponseEntity |
| 989 | // Parse date with timezone consideration if provided |
| 990 | let searchDate: |
| 991 | let nextDate: |
| 992 | |
| 993 | if (date) { |
| 994 | const { startOfDayUtc, |
| 995 | date, |
| 996 | timezone, |
| 997 | ); |
| 998 | searchDate = startOfDayUtc; |
| 999 | nextDate = endOfDayUtc; |
| 1000 | } |
| 1001 | |
| 1002 | // Fetch flights from FlightAware API |
| 1003 | try { |
| 1004 | const flightAwareIdent = |
| 1005 | if (!flightAwareIdent) |
| 1006 | throw new BadRequestException( |
| 1007 | } |
| 1008 | |
| 1009 | const flightAwareResponse = |
| 1010 | await this.flightAwareService |
| 1011 | |
| 1012 | if (!flightAwareResponse || |
| 1013 | return { |
| 1014 | flights: [], |
| 1015 | count: 0, |
| 1016 | }; |
| 1017 | } |
| 1018 | |
| 1019 | // Filter flights by date if provided |
| 1020 | let filteredFlights = |
| 1021 | if (searchDate && |
| 1022 | filteredFlights = flightAwareResponse. |
| 1023 | const flightDate = |
| 1024 | ? new Date( |
| 1025 | : flight.scheduled_off |
| 1026 | ? new Date( |
| 1027 | : null; |
| 1028 | |
| 1029 | if (flightDate) { |
| 1030 | return flightDate >= |
| 1031 | } |
| 1032 | return false; |
| 1033 | }); |
| 1034 | } |
| 1035 | |
| 1036 | // Cache individual flights by faFlightId in Redis for later retrieval |
| 1037 | // This avoids making a second API call when user selects a flight |
| 1038 | // Use a distinct cache key prefix to avoid conflicts with FlightAware service cache |
| 1039 | if (this.redis |
| 1040 | try { |
| 1041 | for (const faFlight |
| 1042 | const flightCacheKey = |
| 1043 | // Cache for 1 hour (3600 seconds) - FlightAware data is relatively stable |
| 1044 | await this.redis |
| 1045 | flightCacheKey, |
| 1046 | 3600, |
| 1047 | JSON.stringify(faFlight |
| 1048 | ); |
| 1049 | } |
| 1050 | console.log( |
| 1051 | `Cached ${filteredFlights.length} |
| 1052 | ); |
| 1053 | } catch (error) |
| 1054 | console.warn('Failed to cache flights in Redis: |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | // Collect unique airline IATA/ICAO codes to query database in batch |
| 1059 | const airlineCodes = |
| 1060 | filteredFlights.forEach((faFlight |
| 1061 | if (faFlight.operator_iata |
| 1062 | airlineCodes.add(`iata: |
| 1063 | } |
| 1064 | if (faFlight.operator_icao |
| 1065 | airlineCodes.add(`icao: |
| 1066 | } |
| 1067 | }); |
| 1068 | |
| 1069 | // Query airlines from database in batch |
| 1070 | const airlineMap = |
| 1071 | if (airlineCodes.size |
| 1072 | const airlineIatas = |
| 1073 | .filter((code) |
| 1074 | .map((code) |
| 1075 | const airlineIcaos = |
| 1076 | .filter((code) |
| 1077 | .map((code) |
| 1078 | |
| 1079 | const dbAirlines = |
| 1080 | where: { |
| 1081 | OR: [ |
| 1082 | airlineIatas.length > 0 |
| 1083 | ? { iata: { |
| 1084 | : undefined, |
| 1085 | airlineIcaos.length > 0 |
| 1086 | ? { icao: { |
| 1087 | : undefined, |
| 1088 | ].filter(Boolean) |
| 1089 | }, |
| 1090 | }); |
| 1091 | |
| 1092 | // Create a map for quick lookup: IATA/ICAO -> airline record |
| 1093 | dbAirlines.forEach((airline |
| 1094 | if (airline.iata |
| 1095 | airlineMap.set(`iata: |
| 1096 | } |
| 1097 | if (airline.icao |
| 1098 | airlineMap.set(`icao: |
| 1099 | } |
| 1100 | }); |
| 1101 | } |
| 1102 | |
| 1103 | // Map FlightAware flights to FlightCandidateEntity |
| 1104 | const flightCandidates: |
| 1105 | (faFlight: any |
| 1106 | // Resolve airline from database or fallback to FlightAware data |
| 1107 | const airlineIata = |
| 1108 | const airlineIcao = |
| 1109 | |
| 1110 | // Try to get airline from database |
| 1111 | const dbAirline = |
| 1112 | airlineIata && airlineMap. |
| 1113 | ? airlineMap.get( |
| 1114 | : airlineIcao && airlineMap |
| 1115 | ? airlineMap.get( |
| 1116 | : null; |
| 1117 | |
| 1118 | // Use DB airline data if available, otherwise fallback to FlightAware data |
| 1119 | const airlineName = |
| 1120 | ? dbAirline.name |
| 1121 | : (faFlight.operator |
| 1122 | faFlight.operator_iata ?? |
| 1123 | faFlight.operator_icao ?? |
| 1124 | 'Unknown'); |
| 1125 | |
| 1126 | return { |
| 1127 | faFlightId: faFlight.fa_flight_id |
| 1128 | ident: faFlight.ident |
| 1129 | origin: { |
| 1130 | code: faFlight.origin |
| 1131 | codeIata: faFlight.origin |
| 1132 | codeIcao: faFlight.origin |
| 1133 | name: faFlight.origin |
| 1134 | city: faFlight.origin |
| 1135 | }, |
| 1136 | destination: { |
| 1137 | code: faFlight.destination |
| 1138 | codeIata: faFlight.destination |
| 1139 | codeIcao: |
| 1140 | faFlight.destination?.code_icao |
| 1141 | name: faFlight.destination |
| 1142 | city: faFlight.destination |
| 1143 | }, |
| 1144 | scheduledOut: faFlight.scheduled_out |
| 1145 | ? new Date( |
| 1146 | : undefined, |
| 1147 | scheduledOff: faFlight.scheduled_off |
| 1148 | ? new Date( |
| 1149 | : undefined, |
| 1150 | status: faFlight.status |
| 1151 | airline: { |
| 1152 | name: airlineName, |
| 1153 | iata: dbAirline?.iata |
| 1154 | icao: dbAirline?.icao |
| 1155 | image: dbAirline?.image |
| 1156 | }, |
| 1157 | }; |
| 1158 | }, |
| 1159 | ); |
| 1160 | |
| 1161 | return { |
| 1162 | flights: flightCandidates, |
| 1163 | count: flightCandidates.length, |
| 1164 | }; |
| 1165 | } catch (error) |
| 1166 | if (error instanceof |
| 1167 | throw error; |
| 1168 | } |
| 1169 | console.error('Error searching flights from FlightAware, falling back to database: |
| 1170 | |
| 1171 | // Fallback: try to return matching flights from the database |
| 1172 | const flightAwareIdent = |
| 1173 | const dbWhere: |
| 1174 | OR: [ |
| 1175 | { callSign: { equals: |
| 1176 | { flightNo: { equals: |
| 1177 | ...(icao |
| 1178 | ? [ |
| 1179 | { callSign: { equals: |
| 1180 | { flightNo: { equals: |
| 1181 | ] |
| 1182 | : []), |
| 1183 | ], |
| 1184 | userId, |
| 1185 | }; |
| 1186 | |
| 1187 | if (searchDate && |
| 1188 | dbWhere.date = |
| 1189 | } |
| 1190 | |
| 1191 | const dbFlights = |
| 1192 | where: dbWhere, |
| 1193 | include: { flightAwareData: true |
| 1194 | orderBy: { date: ' |
| 1195 | }); |
| 1196 | |
| 1197 | if (dbFlights.length |
| 1198 | throw new InternalServerErrorException( |
| 1199 | } |
| 1200 | |
| 1201 | const flightCandidates: |
| 1202 | (flight) => |
| 1203 | const dep = |
| 1204 | const arr = |
| 1205 | const airlineData = |
| 1206 | const fa = |
| 1207 | |
| 1208 | return { |
| 1209 | faFlightId: fa?.faFlightId |
| 1210 | ident: fa?.ident |
| 1211 | origin: { |
| 1212 | code: dep?.airport |
| 1213 | codeIata: dep?.airport |
| 1214 | codeIcao: dep?.airport |
| 1215 | name: dep?.airport |
| 1216 | city: dep?.airport |
| 1217 | }, |
| 1218 | destination: { |
| 1219 | code: arr?.airport |
| 1220 | codeIata: arr?.airport |
| 1221 | codeIcao: arr?.airport |
| 1222 | name: arr?.airport |
| 1223 | city: arr?.airport |
| 1224 | }, |
| 1225 | scheduledOut: fa?.scheduledOut |
| 1226 | scheduledOff: fa?.scheduledOff |
| 1227 | status: fa?.status |
| 1228 | airline: { |
| 1229 | name: airlineData?.name |
| 1230 | iata: airlineData?.iata |
| 1231 | icao: airlineData?.icao |
| 1232 | image: airlineData?.image |
| 1233 | }, |
| 1234 | }; |
| 1235 | }, |
| 1236 | ); |
| 1237 | |
| 1238 | return { |
| 1239 | flights: flightCandidates, |
| 1240 | count: flightCandidates.length, |
| 1241 | }; |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | async getFlightTrack( |
| 1246 | { iata, icao |
| 1247 | userId: string, |
| 1248 | ) { |
| 1249 | const dateToUse = |
| 1250 | const tz = |
| 1251 | const { startOfDayUtc: |
| 1252 | this.parseDateInTimezone(dateToUse |
| 1253 | |
| 1254 | const existingFlight = |
| 1255 | where: { |
| 1256 | OR: [ |
| 1257 | { callSign: { equals: |
| 1258 | { flightNo: { equals: |
| 1259 | { callSign: { equals: |
| 1260 | { flightNo: { equals: |
| 1261 | ], |
| 1262 | userId, |
| 1263 | date: { |
| 1264 | gte: searchDate, |
| 1265 | lte: nextDate, |
| 1266 | }, |
| 1267 | }, |
| 1268 | orderBy: { |
| 1269 | createdAt: 'desc', |
| 1270 | }, |
| 1271 | include: { |
| 1272 | flightAwareData: true, |
| 1273 | }, |
| 1274 | }); |
| 1275 | if (!existingFlight) |
| 1276 | throw new HttpException( |
| 1277 | 'Flight not found in database', |
| 1278 | HttpStatus.NOT_FOUND, |
| 1279 | ); |
| 1280 | } |
| 1281 | |
| 1282 | if (!existingFlight.flightAwareData |
| 1283 | throw new HttpException( |
| 1284 | 'FlightAware data not available for this flight', |
| 1285 | HttpStatus.NOT_FOUND, |
| 1286 | ); |
| 1287 | } |
| 1288 | |
| 1289 | const faFlightId = |
| 1290 | const cacheKey = |
| 1291 | const cacheTTL = |
| 1292 | |
| 1293 | // Check if flight has concluded (landed more than 2 hours ago) |
| 1294 | const flightAwareData = |
| 1295 | const hasLanded = |
| 1296 | flightAwareData.actualOn || |
| 1297 | flightAwareData.actualIn || |
| 1298 | flightAwareData.estimatedOn; |
| 1299 | |
| 1300 | let isFlightConcluded = |
| 1301 | if (hasLanded) { |
| 1302 | const landingTimeValue = |
| 1303 | flightAwareData.actualOn || |
| 1304 | flightAwareData.actualIn || |
| 1305 | flightAwareData.estimatedOn; |
| 1306 | const landingTime = |
| 1307 | const now = |
| 1308 | const hoursSinceLanding = |
| 1309 | (now.getTime() |
| 1310 | |
| 1311 | // Consider flight concluded if it landed more than 2 hours ago |
| 1312 | isFlightConcluded = hoursSinceLanding |
| 1313 | } |
| 1314 | |
| 1315 | // If flight is concluded and all positions are fetched, return database data |
| 1316 | if (isFlightConcluded && |
| 1317 | console.log( |
| 1318 | `Flight ${faFlightId} has concluded and all positions are fetched. Returning database data.` |
| 1319 | ); |
| 1320 | |
| 1321 | const existingPositions = |
| 1322 | where: { |
| 1323 | flightId: existingFlight.id |
| 1324 | }, |
| 1325 | orderBy: { |
| 1326 | timestamp: 'asc', |
| 1327 | }, |
| 1328 | }); |
| 1329 | |
| 1330 | if (existingPositions.length |
| 1331 | console.log( |
| 1332 | `FlightTrack: Returning ${existingPositions.length} |
| 1333 | ); |
| 1334 | |
| 1335 | // Calculate actual distance if available |
| 1336 | let actualDistance = |
| 1337 | if (existingPositions.length |
| 1338 | // Simple distance calculation (you could improve this) |
| 1339 | const first = |
| 1340 | const last = |
| 1341 | const R = |
| 1342 | const firstLat = |
| 1343 | const firstLon = |
| 1344 | const lastLat = |
| 1345 | const lastLon = |
| 1346 | const dLat = |
| 1347 | const dLon = |
| 1348 | const a = |
| 1349 | Math.sin(dLat |
| 1350 | Math.cos((firstLat |
| 1351 | Math.cos((lastLat |
| 1352 | Math.sin(dLon |
| 1353 | Math.sin(dLon |
| 1354 | const c = |
| 1355 | actualDistance = R |
| 1356 | } |
| 1357 | |
| 1358 | return { |
| 1359 | actual_distance: actualDistance, |
| 1360 | positions: existingPositions.map |
| 1361 | fa_flight_id: faFlightId, |
| 1362 | altitude: pos.altitude |
| 1363 | altitude_change: |
| 1364 | pos.altitudeChange === |
| 1365 | ? 'C' |
| 1366 | : pos.altitudeChange |
| 1367 | ? 'D' |
| 1368 | : '-', |
| 1369 | groundspeed: pos.groundSpeed |
| 1370 | heading: pos.heading |
| 1371 | // Prisma Decimal values get stringified; ensure numbers in API response |
| 1372 | latitude: Number(pos |
| 1373 | longitude: Number(pos |
| 1374 | timestamp: pos.timestamp |
| 1375 | update_type: |
| 1376 | pos.updatedType === |
| 1377 | ? 'P' |
| 1378 | : pos.updatedType |
| 1379 | ? 'O' |
| 1380 | : pos.updatedType |
| 1381 | ? 'Z' |
| 1382 | : pos.updatedType |
| 1383 | ? 'A' |
| 1384 | : pos.updatedType |
| 1385 | ? 'M' |
| 1386 | : pos.updatedType |
| 1387 | ? 'D' |
| 1388 | : pos.updatedType |
| 1389 | ? 'X' |
| 1390 | : pos.updatedType |
| 1391 | ? 'S' |
| 1392 | : pos.updatedType |
| 1393 | ? 'V' |
| 1394 | : null, |
| 1395 | })), |
| 1396 | }; |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | // If flight is concluded but positions aren't all fetched, fetch from API |
| 1401 | const shouldSkipCache = |
| 1402 | isFlightConcluded && !existingFlight |
| 1403 | |
| 1404 | if (shouldSkipCache) { |
| 1405 | console.log( |
| 1406 | `Flight ${faFlightId} has concluded but positions not fully fetched. Fetching complete track data from FlightAware.` |
| 1407 | ); |
| 1408 | } |
| 1409 | |
| 1410 | // Check Redis cache first for active flights (skip cache for concluded flights that need refetch) |
| 1411 | if (!shouldSkipCache) |
| 1412 | try { |
| 1413 | if (this.redis |
| 1414 | const cached = |
| 1415 | if (cached) { |
| 1416 | console.log( |
| 1417 | `FlightTrack: Returning cached data for ${faFlightId} from application cache` |
| 1418 | ); |
| 1419 | return JSON.parse |
| 1420 | } |
| 1421 | } |
| 1422 | } catch (error) |
| 1423 | console.warn('Redis cache read error in flight service: |
| 1424 | } |
| 1425 | } |
| 1426 | |
| 1427 | // Fetch track data from FlightAware API |
| 1428 | console.log( |
| 1429 | `FlightTrack: Fetching ${isFlightConcluded ? |
| 1430 | ); |
| 1431 | const trackData = |
| 1432 | |
| 1433 | if (!trackData || |
| 1434 | throw new InternalServerErrorException( |
| 1435 | 'Failed to fetch flight track data', |
| 1436 | ); |
| 1437 | } |
| 1438 | |
| 1439 | // Map altitude_change from API format to Prisma enum |
| 1440 | const mapAltitudeChange = |
| 1441 | change: string, |
| 1442 | ): 'Climb' | |
| 1443 | switch (change) { |
| 1444 | case 'C': |
| 1445 | return 'Climb'; |
| 1446 | case 'D': |
| 1447 | return 'Descend'; |
| 1448 | case '-': |
| 1449 | default: |
| 1450 | return 'None'; |
| 1451 | } |
| 1452 | }; |
| 1453 | |
| 1454 | // Map update_type from API format to Prisma enum |
| 1455 | const mapUpdateType = |
| 1456 | type: string, |
| 1457 | ): |
| 1458 | | 'Projected' |
| 1459 | | 'Oceanic' |
| 1460 | | 'Radar' |
| 1461 | | 'ADSB' |
| 1462 | | 'Multilateration' |
| 1463 | | 'Datalink' |
| 1464 | | 'Surface_And_Near_Surface' |
| 1465 | | 'Spaced_Based' |
| 1466 | | 'Virtual_Event' => |
| 1467 | switch (type) { |
| 1468 | case 'P': |
| 1469 | return 'Projected'; |
| 1470 | case 'O': |
| 1471 | return 'Oceanic'; |
| 1472 | case 'Z': |
| 1473 | return 'Radar'; |
| 1474 | case 'A': |
| 1475 | return 'ADSB'; |
| 1476 | case 'M': |
| 1477 | return 'Multilateration'; |
| 1478 | case 'D': |
| 1479 | return 'Datalink'; |
| 1480 | case 'X': |
| 1481 | return 'Surface_And_Near_Surface'; |
| 1482 | case 'S': |
| 1483 | return 'Spaced_Based'; |
| 1484 | case 'V': |
| 1485 | return 'Virtual_Event'; |
| 1486 | default: |
| 1487 | return 'ADSB'; |
| 1488 | } |
| 1489 | }; |
| 1490 | |
| 1491 | // UPSERT positions in the database |
| 1492 | // Use a transaction to ensure atomicity |
| 1493 | await prisma.$transaction |
| 1494 | async (tx) |
| 1495 | for (const pos |
| 1496 | const positionId = |
| 1497 | |
| 1498 | await tx.flightPositions |
| 1499 | where: { |
| 1500 | id: positionId, |
| 1501 | }, |
| 1502 | update: { |
| 1503 | altitude: pos.altitude |
| 1504 | altitudeChange: mapAltitudeChange(pos |
| 1505 | groundSpeed: pos.groundspeed |
| 1506 | heading: pos.heading |
| 1507 | latitude: pos.latitude |
| 1508 | longitude: pos.longitude |
| 1509 | timestamp: new Date |
| 1510 | updatedType: mapUpdateType(pos |
| 1511 | }, |
| 1512 | create: { |
| 1513 | id: positionId, |
| 1514 | altitude: pos.altitude |
| 1515 | altitudeChange: mapAltitudeChange(pos |
| 1516 | groundSpeed: pos.groundspeed |
| 1517 | heading: pos.heading |
| 1518 | latitude: pos.latitude |
| 1519 | longitude: pos.longitude |
| 1520 | timestamp: new Date |
| 1521 | updatedType: mapUpdateType(pos |
| 1522 | flightId: existingFlight.id |
| 1523 | }, |
| 1524 | }); |
| 1525 | } |
| 1526 | |
| 1527 | // If flight is concluded, mark all positions as fetched |
| 1528 | if (isFlightConcluded) { |
| 1529 | await tx.flight |
| 1530 | where: { id: existingFlight |
| 1531 | data: { allFlightPositionsFetched: true |
| 1532 | }); |
| 1533 | console.log( |
| 1534 | `FlightTrack: Marked all positions as fetched for concluded flight ${faFlightId}`, |
| 1535 | ); |
| 1536 | } |
| 1537 | }, |
| 1538 | { timeout: 60000 }, |
| 1539 | ); |
| 1540 | |
| 1541 | // Prepare response data |
| 1542 | const responseData = |
| 1543 | actual_distance: trackData.actual_distance |
| 1544 | positions: trackData.positions |
| 1545 | fa_flight_id: pos.fa_flight_id |
| 1546 | altitude: pos.altitude |
| 1547 | altitude_change: pos.altitude_change |
| 1548 | groundspeed: pos.groundspeed |
| 1549 | heading: pos.heading |
| 1550 | latitude: pos.latitude |
| 1551 | longitude: pos.longitude |
| 1552 | timestamp: pos.timestamp |
| 1553 | update_type: pos.update_type |
| 1554 | })), |
| 1555 | }; |
| 1556 | |
| 1557 | // Cache the response in Redis for 30 seconds (skip caching for concluded flights) |
| 1558 | // Concluded flights are already persisted in the database and don't need caching |
| 1559 | if (!isFlightConcluded) |
| 1560 | try { |
| 1561 | if (this.redis |
| 1562 | await this.redis |
| 1563 | cacheKey, |
| 1564 | cacheTTL, |
| 1565 | JSON.stringify(responseData |
| 1566 | ); |
| 1567 | console.log( |
| 1568 | `FlightTrack: Cached track data for ${faFlightId} for ${ |
| 1569 | ); |
| 1570 | } |
| 1571 | } catch (error) |
| 1572 | console.warn('Redis cache write error in flight service: |
| 1573 | } |
| 1574 | } |
| 1575 | |
| 1576 | return responseData; |
| 1577 | } |
| 1578 | |
| 1579 | async createFlightBooking( |
| 1580 | createBookingDto: CreateFlightBookingDTO |
| 1581 | userId: string, |
| 1582 | ) { |
| 1583 | // Verify that the flight exists and belongs to the user |
| 1584 | const flight = |
| 1585 | where: { |
| 1586 | id: createBookingDto.flightId |
| 1587 | userId, |
| 1588 | }, |
| 1589 | }); |
| 1590 | |
| 1591 | if (!flight) |
| 1592 | throw new BadRequestException( |
| 1593 | 'Flight not found or does not belong to the user', |
| 1594 | ); |
| 1595 | } |
| 1596 | |
| 1597 | // Check if booking already exists for this flight and user |
| 1598 | const existingBooking = |
| 1599 | where: { |
| 1600 | flightId: createBookingDto.flightId |
| 1601 | userId, |
| 1602 | }, |
| 1603 | }); |
| 1604 | |
| 1605 | if (existingBooking) { |
| 1606 | throw new BadRequestException( |
| 1607 | 'A booking already exists for this flight. Use update endpoint to modify it.', |
| 1608 | ); |
| 1609 | } |
| 1610 | |
| 1611 | // Create the booking |
| 1612 | const booking = |
| 1613 | data: { |
| 1614 | flightId: createBookingDto.flightId |
| 1615 | userId, |
| 1616 | bookingCode: createBookingDto.bookingCode |
| 1617 | seatNumber: createBookingDto.seatNumber |
| 1618 | seatType: createBookingDto.seatType |
| 1619 | seatingClass: createBookingDto.seatingClass |
| 1620 | reason: createBookingDto.reason |
| 1621 | notes: createBookingDto.notes |
| 1622 | }, |
| 1623 | }); |
| 1624 | |
| 1625 | return booking; |
| 1626 | } |
| 1627 | |
| 1628 | async updateFlightBooking( |
| 1629 | bookingId: string, |
| 1630 | updateBookingDto: UpdateFlightBookingDTO |
| 1631 | userId: string, |
| 1632 | ) { |
| 1633 | // Verify that the booking exists and belongs to the user |
| 1634 | const existingBooking = |
| 1635 | where: { |
| 1636 | id: bookingId, |
| 1637 | userId, |
| 1638 | }, |
| 1639 | }); |
| 1640 | |
| 1641 | if (!existingBooking) |
| 1642 | throw new NotFoundException( |
| 1643 | 'Booking not found or does not belong to the user', |
| 1644 | ); |
| 1645 | } |
| 1646 | |
| 1647 | // Build update data object, only including fields that are provided |
| 1648 | // If a field is explicitly set to null, we'll set it to null in the database |
| 1649 | // If undefined, the field won't be updated (partial update) |
| 1650 | const updateData: |
| 1651 | if (updateBookingDto.bookingCode |
| 1652 | // Convert empty strings to null for consistency |
| 1653 | updateData.bookingCode = |
| 1654 | updateBookingDto.bookingCode === |
| 1655 | ? null |
| 1656 | : updateBookingDto.bookingCode; |
| 1657 | } |
| 1658 | if (updateBookingDto.seatNumber |
| 1659 | updateData.seatNumber = |
| 1660 | updateBookingDto.seatNumber === |
| 1661 | } |
| 1662 | if (updateBookingDto.seatType |
| 1663 | updateData.seatType = |
| 1664 | } |
| 1665 | if (updateBookingDto.seatingClass |
| 1666 | updateData.seatingClass = |
| 1667 | } |
| 1668 | if (updateBookingDto.reason |
| 1669 | updateData.reason = |
| 1670 | } |
| 1671 | if (updateBookingDto.notes |
| 1672 | updateData.notes = |
| 1673 | updateBookingDto.notes === |
| 1674 | } |
| 1675 | |
| 1676 | // Update the booking |
| 1677 | const updatedBooking = |
| 1678 | where: { |
| 1679 | id: bookingId, |
| 1680 | }, |
| 1681 | data: updateData, |
| 1682 | }); |
| 1683 | |
| 1684 | return updatedBooking; |
| 1685 | } |
| 1686 | |
| 1687 | async getFlightBooking(bookingId |
| 1688 | const booking = |
| 1689 | where: { |
| 1690 | id: bookingId, |
| 1691 | userId, |
| 1692 | }, |
| 1693 | }); |
| 1694 | |
| 1695 | if (!booking) |
| 1696 | throw new NotFoundException( |
| 1697 | 'Booking not found or does not belong to the user', |
| 1698 | ); |
| 1699 | } |
| 1700 | |
| 1701 | return booking; |
| 1702 | } |
| 1703 | |
| 1704 | async getFlightBookingsByFlightId(flightId |
| 1705 | // Verify that the flight belongs to the user |
| 1706 | const flight = |
| 1707 | where: { |
| 1708 | id: flightId, |
| 1709 | userId, |
| 1710 | }, |
| 1711 | }); |
| 1712 | |
| 1713 | if (!flight) |
| 1714 | throw new BadRequestException( |
| 1715 | 'Flight not found or does not belong to the user', |
| 1716 | ); |
| 1717 | } |
| 1718 | |
| 1719 | const bookings = |
| 1720 | where: { |
| 1721 | flightId, |
| 1722 | userId, |
| 1723 | }, |
| 1724 | orderBy: { |
| 1725 | createdAt: 'desc', |
| 1726 | }, |
| 1727 | }); |
| 1728 | |
| 1729 | return bookings; |
| 1730 | } |
| 1731 | |
| 1732 | async deleteFlightBooking(bookingId |
| 1733 | // Verify that the booking exists and belongs to the user |
| 1734 | const existingBooking = |
| 1735 | where: { |
| 1736 | id: bookingId, |
| 1737 | userId, |
| 1738 | }, |
| 1739 | }); |
| 1740 | |
| 1741 | if (!existingBooking) |
| 1742 | throw new NotFoundException( |
| 1743 | 'Booking not found or does not belong to the user', |
| 1744 | ); |
| 1745 | } |
| 1746 | |
| 1747 | await prisma.flightBooking |
| 1748 | where: { |
| 1749 | id: bookingId, |
| 1750 | }, |
| 1751 | }); |
| 1752 | |
| 1753 | return { message: |
| 1754 | } |
| 1755 | } |