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