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