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