| 1 | import { prisma } from 'src/db'; |
| 2 | |
| 3 | import { Injectable } |
| 4 | |
| 5 | import { ProfileStatsResponseEntity } |
| 6 | import { FlightSummaryEntity } |
| 7 | |
| 8 | @Injectable() |
| 9 | export class ProfileService |
| 10 | async getProfileStats(userId |
| 11 | const flights = |
| 12 | include: { |
| 13 | greatCircleDistance: true, |
| 14 | flightAwareData: true, |
| 15 | }, |
| 16 | where: { userId |
| 17 | }); |
| 18 | |
| 19 | if (flights.length |
| 20 | return this.getEmptyStats |
| 21 | } |
| 22 | |
| 23 | // Calculate most flown aircraft using DB typeName |
| 24 | const aircraftCounts = |
| 25 | const aircraftTypeToFlights = |
| 26 | const regs = |
| 27 | const modelCodes = |
| 28 | const candidateTypeNames = |
| 29 | const tailNumbers = |
| 30 | const tailNumberToAircraft = |
| 31 | string, |
| 32 | { typeName: string; |
| 33 | >(); |
| 34 | |
| 35 | flights.forEach((flight |
| 36 | const aircraft = |
| 37 | const fa = |
| 38 | |
| 39 | // Track tail numbers |
| 40 | const tailNumber = |
| 41 | aircraft?.reg || |
| 42 | if (tailNumber) { |
| 43 | tailNumbers.set(tailNumber |
| 44 | } |
| 45 | |
| 46 | if (aircraft?.reg |
| 47 | if (aircraft?.registration |
| 48 | if (aircraft?.modelCode |
| 49 | if (aircraft?.typeName |
| 50 | if (fa?.aircraftType |
| 51 | }); |
| 52 | |
| 53 | const registrations = |
| 54 | ? await prisma. |
| 55 | where: { reg: { |
| 56 | include: { Aircraft: true |
| 57 | }) |
| 58 | : []; |
| 59 | const regToTypeName = |
| 60 | const regToAircraftId = |
| 61 | registrations.forEach((r |
| 62 | if (r.reg |
| 63 | regToTypeName.set(r |
| 64 | if (r.Aircraft |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | // Fetch all aircraft data for images and ages |
| 69 | const allAircraftIds = |
| 70 | const aircraftRows = |
| 71 | modelCodes.size || |
| 72 | ? await prisma. |
| 73 | where: { |
| 74 | OR: [ |
| 75 | modelCodes.size |
| 76 | ? { modelCode: { |
| 77 | : undefined, |
| 78 | candidateTypeNames.size |
| 79 | ? { typeName: { |
| 80 | : undefined, |
| 81 | allAircraftIds.length > 0 |
| 82 | ? { id: { |
| 83 | : undefined, |
| 84 | ].filter(Boolean) |
| 85 | }, |
| 86 | select: { |
| 87 | id: true, |
| 88 | modelCode: true, |
| 89 | typeName: true, |
| 90 | image: true, |
| 91 | age: true, |
| 92 | reg: true, |
| 93 | createdAt: true, |
| 94 | }, |
| 95 | }) |
| 96 | : []; |
| 97 | |
| 98 | const modelCodeToTypeName = |
| 99 | const typeNameToImage = |
| 100 | const regToAge = |
| 101 | const regToImage = |
| 102 | |
| 103 | const now = |
| 104 | |
| 105 | aircraftRows.forEach((a |
| 106 | if (a.modelCode |
| 107 | modelCodeToTypeName.set(a |
| 108 | if (a.image |
| 109 | } |
| 110 | if (a.typeName |
| 111 | typeNameToImage.set(a |
| 112 | } |
| 113 | if (a.reg |
| 114 | // Calculate age offset based on when the record was created |
| 115 | const ageAtCreation = |
| 116 | const yearsSinceCreation = |
| 117 | (now.getTime() |
| 118 | const adjustedAge = |
| 119 | regToAge.set(a |
| 120 | } |
| 121 | if (a.reg |
| 122 | regToImage.set(a |
| 123 | } |
| 124 | }); |
| 125 | |
| 126 | flights.forEach((flight |
| 127 | const aircraft = |
| 128 | const fa = |
| 129 | let typeName = |
| 130 | if (aircraft?.typeName |
| 131 | else if (aircraft?. |
| 132 | typeName = regToTypeName. |
| 133 | else if ( |
| 134 | aircraft?.registration && |
| 135 | regToTypeName.get(aircraft |
| 136 | ) |
| 137 | typeName = regToTypeName. |
| 138 | else if ( |
| 139 | aircraft?.modelCode && |
| 140 | modelCodeToTypeName.get(aircraft |
| 141 | ) |
| 142 | typeName = modelCodeToTypeName. |
| 143 | else if (fa?. |
| 144 | typeName = modelCodeToTypeName. |
| 145 | |
| 146 | if (typeName) { |
| 147 | aircraftCounts.set(typeName |
| 148 | if (!aircraftTypeToFlights.has |
| 149 | aircraftTypeToFlights.set(typeName |
| 150 | } |
| 151 | aircraftTypeToFlights.get(typeName |
| 152 | } |
| 153 | |
| 154 | // Track tail number to aircraft info (for all flights, not just those with typeName) |
| 155 | const tailNumber = |
| 156 | aircraft?.reg || |
| 157 | if (tailNumber && |
| 158 | // Get typeName for this tail number if we don't have it from above |
| 159 | let aircraftTypeName = |
| 160 | if (!aircraftTypeName && |
| 161 | aircraftTypeName = regToTypeName. |
| 162 | } |
| 163 | tailNumberToAircraft.set(tailNumber |
| 164 | typeName: aircraftTypeName || |
| 165 | age: regToAge.get |
| 166 | image: regToImage.get |
| 167 | }); |
| 168 | } |
| 169 | }); |
| 170 | |
| 171 | // Collect unique aircraft ages for median calculation |
| 172 | const uniqueAircraftAges: |
| 173 | tailNumberToAircraft.forEach((info |
| 174 | if (info.age |
| 175 | uniqueAircraftAges.push(info |
| 176 | } |
| 177 | }); |
| 178 | |
| 179 | const mostFlownAircraft = |
| 180 | (a, b) |
| 181 | )[0] || ['', |
| 182 | |
| 183 | // Find most common tail number |
| 184 | const mostCommonTailNumber = |
| 185 | (a, b) |
| 186 | )[0] || ['', |
| 187 | |
| 188 | // Calculate median age (using unique aircraft ages) |
| 189 | let medianAge: |
| 190 | if (uniqueAircraftAges.length |
| 191 | const sortedAges = |
| 192 | const mid = |
| 193 | const calculatedMedian = |
| 194 | sortedAges.length % 2 |
| 195 | ? (sortedAges[mid |
| 196 | : sortedAges[mid] |
| 197 | medianAge = Math. |
| 198 | } |
| 199 | |
| 200 | // Find youngest and oldest aircraft with images |
| 201 | let youngestAircraft: |
| 202 | aircraftName: string |
| 203 | tailNumber: string |
| 204 | age?: number |
| 205 | image?: string |
| 206 | } | undefined |
| 207 | let oldestAircraft: |
| 208 | aircraftName: string |
| 209 | tailNumber: string |
| 210 | age?: number |
| 211 | image?: string |
| 212 | } | undefined |
| 213 | |
| 214 | const aircraftWithAgeAndImage = |
| 215 | .map(([tailNumber |
| 216 | tailNumber, |
| 217 | typeName: info.typeName |
| 218 | age: info.age |
| 219 | image: info.image |
| 220 | })) |
| 221 | .filter((a) |
| 222 | |
| 223 | if (aircraftWithAgeAndImage.length |
| 224 | const sortedByAge = |
| 225 | (a, b) |
| 226 | ); |
| 227 | youngestAircraft = { |
| 228 | aircraftName: sortedByAge[0] |
| 229 | tailNumber: sortedByAge[0] |
| 230 | age: sortedByAge[0] |
| 231 | image: sortedByAge[0] |
| 232 | }; |
| 233 | oldestAircraft = { |
| 234 | aircraftName: sortedByAge[sortedByAge |
| 235 | tailNumber: sortedByAge[sortedByAge |
| 236 | age: sortedByAge[sortedByAge |
| 237 | image: sortedByAge[sortedByAge |
| 238 | }; |
| 239 | } |
| 240 | |
| 241 | // Calculate passport stats |
| 242 | const uniqueAirports = |
| 243 | const uniqueAirlines = |
| 244 | let totalDistanceKm = |
| 245 | let totalDurationMinutes = |
| 246 | |
| 247 | flights.forEach((flight |
| 248 | const departure = |
| 249 | const arrival = |
| 250 | const airline = |
| 251 | |
| 252 | // Track airports |
| 253 | if (departure?.airport |
| 254 | uniqueAirports.add(departure |
| 255 | } |
| 256 | if (departure?.airport |
| 257 | uniqueAirports.add(departure |
| 258 | } |
| 259 | if (arrival?.airport |
| 260 | uniqueAirports.add(arrival |
| 261 | } |
| 262 | if (arrival?.airport |
| 263 | uniqueAirports.add(arrival |
| 264 | } |
| 265 | |
| 266 | // Track airlines |
| 267 | if (airline?.iata |
| 268 | uniqueAirlines.add(airline |
| 269 | } |
| 270 | if (airline?.icao |
| 271 | uniqueAirlines.add(airline |
| 272 | } |
| 273 | |
| 274 | // Sum distance |
| 275 | if (flight.greatCircleDistance |
| 276 | const km = |
| 277 | if (!isNaN(km |
| 278 | totalDistanceKm += km; |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Calculate duration (including delays) |
| 283 | if (flight.flightAwareData |
| 284 | const faData = |
| 285 | let durationMinutes = |
| 286 | |
| 287 | // Use filed ETE if available (in seconds) |
| 288 | if (faData.filedEte |
| 289 | durationMinutes = faData. |
| 290 | } else { |
| 291 | // Calculate from actual times if available |
| 292 | const departureTime = |
| 293 | faData.actualOff || |
| 294 | faData.actualOut || |
| 295 | faData.scheduledOff || |
| 296 | faData.scheduledOut; |
| 297 | const arrivalTime = |
| 298 | faData.actualOn || |
| 299 | faData.actualIn || |
| 300 | faData.scheduledOn || |
| 301 | faData.scheduledIn; |
| 302 | |
| 303 | if (departureTime && |
| 304 | durationMinutes = |
| 305 | (arrivalTime.getTime() |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // Add delays if available (delays are in seconds) |
| 310 | if (faData.departureDelay |
| 311 | durationMinutes += faData. |
| 312 | } |
| 313 | if (faData.arrivalDelay |
| 314 | durationMinutes += faData. |
| 315 | } |
| 316 | |
| 317 | if (durationMinutes > |
| 318 | totalDurationMinutes += durationMinutes; |
| 319 | } |
| 320 | } |
| 321 | }); |
| 322 | |
| 323 | // Find shortest and longest distance flights |
| 324 | const flightsWithDistance = |
| 325 | .map((flight) |
| 326 | flight, |
| 327 | distanceKm: flight.greatCircleDistance |
| 328 | ? Number(flight. |
| 329 | : null, |
| 330 | })) |
| 331 | .filter((f) |
| 332 | |
| 333 | const shortestDistanceFlight = |
| 334 | flightsWithDistance.length > 0 |
| 335 | ? flightsWithDistance.reduce( |
| 336 | curr.distanceKm! < |
| 337 | ) |
| 338 | : null; |
| 339 | |
| 340 | const longestDistanceFlight = |
| 341 | flightsWithDistance.length > 0 |
| 342 | ? flightsWithDistance.reduce( |
| 343 | curr.distanceKm! > |
| 344 | ) |
| 345 | : null; |
| 346 | |
| 347 | // Find shortest and longest duration flights |
| 348 | const flightsWithDuration = |
| 349 | .map((flight) |
| 350 | if (!flight.flightAwareData |
| 351 | |
| 352 | const faData = |
| 353 | let durationMinutes = |
| 354 | |
| 355 | if (faData.filedEte |
| 356 | durationMinutes = faData. |
| 357 | } else { |
| 358 | const departureTime = |
| 359 | faData.actualOff || |
| 360 | faData.actualOut || |
| 361 | faData.scheduledOff || |
| 362 | faData.scheduledOut; |
| 363 | const arrivalTime = |
| 364 | faData.actualOn || |
| 365 | faData.actualIn || |
| 366 | faData.scheduledOn || |
| 367 | faData.scheduledIn; |
| 368 | |
| 369 | if (departureTime && |
| 370 | durationMinutes = |
| 371 | (arrivalTime.getTime() |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | if (faData.departureDelay |
| 376 | durationMinutes += faData. |
| 377 | } |
| 378 | if (faData.arrivalDelay |
| 379 | durationMinutes += faData. |
| 380 | } |
| 381 | |
| 382 | return durationMinutes > |
| 383 | }) |
| 384 | .filter( |
| 385 | (f): f |
| 386 | f !== null, |
| 387 | ); |
| 388 | |
| 389 | const shortestDurationFlight = |
| 390 | flightsWithDuration.length > 0 |
| 391 | ? flightsWithDuration.reduce( |
| 392 | curr.durationMinutes < |
| 393 | ) |
| 394 | : null; |
| 395 | |
| 396 | const longestDurationFlight = |
| 397 | flightsWithDuration.length > 0 |
| 398 | ? flightsWithDuration.reduce( |
| 399 | curr.durationMinutes > |
| 400 | ) |
| 401 | : null; |
| 402 | |
| 403 | // Bulk fetch airlines to enrich images and compute stats |
| 404 | const airlineIatas = |
| 405 | const airlineIcaos = |
| 406 | flights.forEach((flight |
| 407 | const airline = |
| 408 | if (airline?.iata |
| 409 | if (airline?.icao |
| 410 | }); |
| 411 | const airlinesFromDb = |
| 412 | airlineIatas.size || |
| 413 | ? await prisma. |
| 414 | where: { |
| 415 | OR: [ |
| 416 | airlineIatas.size |
| 417 | ? { iata: { |
| 418 | : undefined, |
| 419 | airlineIcaos.size |
| 420 | ? { icao: { |
| 421 | : undefined, |
| 422 | ].filter(Boolean) |
| 423 | }, |
| 424 | select: { iata: true |
| 425 | }) |
| 426 | : []; |
| 427 | const airlineByIata = |
| 428 | const airlineByIcao = |
| 429 | airlinesFromDb.forEach((a |
| 430 | if (a.iata |
| 431 | airlineByIata.set(a |
| 432 | image: a.image |
| 433 | name: a.name |
| 434 | }); |
| 435 | if (a.icao |
| 436 | airlineByIcao.set(a |
| 437 | image: a.image |
| 438 | name: a.name |
| 439 | }); |
| 440 | }); |
| 441 | |
| 442 | // Calculate airline stats |
| 443 | const airlineCounts = |
| 444 | string, |
| 445 | { name: string; |
| 446 | >(); |
| 447 | |
| 448 | flights.forEach((flight |
| 449 | const airline = |
| 450 | const key = |
| 451 | const dbMatch = |
| 452 | (airline?.iata && |
| 453 | (airline?.icao && |
| 454 | undefined; |
| 455 | const existing = |
| 456 | name: dbMatch?.name |
| 457 | iata: airline?.iata |
| 458 | icao: airline?.icao |
| 459 | count: 0, |
| 460 | }; |
| 461 | existing.count++; |
| 462 | airlineCounts.set(key |
| 463 | }); |
| 464 | |
| 465 | const airlines = |
| 466 | .map((airline) |
| 467 | airlineName: airline.name |
| 468 | airlineIata: airline.iata |
| 469 | airlineIcao: airline.icao |
| 470 | image: |
| 471 | (airline.iata && |
| 472 | (airline.icao && |
| 473 | undefined, |
| 474 | flightCount: airline.count |
| 475 | })) |
| 476 | .sort((a, |
| 477 | |
| 478 | // Calculate airport stats (departures) |
| 479 | const airportDepartureCounts = |
| 480 | string, |
| 481 | { code: string; |
| 482 | >(); |
| 483 | |
| 484 | flights.forEach((flight |
| 485 | const departure = |
| 486 | const airportCode = |
| 487 | const airportName = |
| 488 | departure?.airport?.name |
| 489 | |
| 490 | if (airportCode) { |
| 491 | const existing = |
| 492 | code: airportCode, |
| 493 | name: airportName, |
| 494 | count: 0, |
| 495 | }; |
| 496 | existing.count++; |
| 497 | airportDepartureCounts.set(airportCode |
| 498 | } |
| 499 | }); |
| 500 | |
| 501 | const airports = |
| 502 | .map((airport) |
| 503 | airportCode: airport.code |
| 504 | airportName: airport.name |
| 505 | departureCount: airport.count |
| 506 | })) |
| 507 | .sort((a, |
| 508 | |
| 509 | // Calculate top routes |
| 510 | const routeCounts = |
| 511 | |
| 512 | flights.forEach((flight |
| 513 | const departure = |
| 514 | const arrival = |
| 515 | const origin = |
| 516 | const destination = |
| 517 | |
| 518 | if (origin && |
| 519 | const routeKey = |
| 520 | routeCounts.set(routeKey |
| 521 | } |
| 522 | }); |
| 523 | |
| 524 | const topRoutes = |
| 525 | .map(([route |
| 526 | const [origin, |
| 527 | return { origin, |
| 528 | }) |
| 529 | .sort((a, |
| 530 | .slice(0, 10 |
| 531 | |
| 532 | // Transform to lightweight flight summary (no heavy payloads) |
| 533 | const transformFlight = |
| 534 | flight: (typeof |
| 535 | ): FlightSummaryEntity => |
| 536 | const departure = |
| 537 | const arrival = |
| 538 | const airline = |
| 539 | |
| 540 | return { |
| 541 | id: flight.id |
| 542 | flightNo: flight.flightNo |
| 543 | callSign: flight.callSign |
| 544 | airline: { |
| 545 | name: |
| 546 | (airline?.iata && |
| 547 | (airline?.icao && |
| 548 | airline?.name || |
| 549 | '', |
| 550 | iata: airline?.iata |
| 551 | icao: airline?.icao |
| 552 | image: |
| 553 | (airline?.iata && |
| 554 | (airline?.icao && |
| 555 | airline?.image || |
| 556 | undefined, |
| 557 | }, |
| 558 | departureAirportCode: |
| 559 | departure?.airport?.iata |
| 560 | departureAirportName: |
| 561 | departure?.airport?.name |
| 562 | arrivalAirportCode: |
| 563 | arrival?.airport?.iata |
| 564 | arrivalAirportName: |
| 565 | arrival?.airport?.name |
| 566 | date: flight.date |
| 567 | }; |
| 568 | }; |
| 569 | |
| 570 | // Get flights for most flown aircraft |
| 571 | const mostFlownFlights = |
| 572 | mostFlownAircraft[0] && |
| 573 | ? aircraftTypeToFlights.get( |
| 574 | : []; |
| 575 | |
| 576 | return { |
| 577 | mostFlownAircraft: { |
| 578 | aircraftName: mostFlownAircraft[0] |
| 579 | flightCount: mostFlownAircraft[1] |
| 580 | }, |
| 581 | aircraftStats: { |
| 582 | mostFlownAircraftName: mostFlownAircraft[0] |
| 583 | mostFlownAircraftFlightCount: mostFlownAircraft[1] |
| 584 | mostFlownAircraftImage: mostFlownAircraft[0] |
| 585 | ? typeNameToImage.get( |
| 586 | : undefined, |
| 587 | mostFlownAircraftFlights: mostFlownFlights, |
| 588 | mostCommonTailNumber: mostCommonTailNumber[0] |
| 589 | mostCommonTailNumberCount: mostCommonTailNumber[1] |
| 590 | medianAge: medianAge, |
| 591 | youngestAircraft: youngestAircraft, |
| 592 | oldestAircraft: oldestAircraft, |
| 593 | }, |
| 594 | passport: { |
| 595 | totalFlights: flights.length, |
| 596 | totalDistanceKm: Math.round |
| 597 | totalDurationMinutes: Math.round |
| 598 | totalAirports: uniqueAirports.size |
| 599 | totalAirlines: uniqueAirlines.size |
| 600 | }, |
| 601 | shortestDistanceFlight: shortestDistanceFlight |
| 602 | ? { |
| 603 | flight: transformFlight(shortestDistanceFlight |
| 604 | distanceKm: |
| 605 | Math.round(shortestDistanceFlight |
| 606 | } |
| 607 | : { |
| 608 | flight: transformFlight(flights |
| 609 | distanceKm: 0, |
| 610 | }, |
| 611 | longestDistanceFlight: longestDistanceFlight |
| 612 | ? { |
| 613 | flight: transformFlight(longestDistanceFlight |
| 614 | distanceKm: |
| 615 | Math.round(longestDistanceFlight |
| 616 | } |
| 617 | : { |
| 618 | flight: transformFlight(flights |
| 619 | distanceKm: 0, |
| 620 | }, |
| 621 | shortestDurationFlight: shortestDurationFlight |
| 622 | ? { |
| 623 | flight: transformFlight(shortestDurationFlight |
| 624 | durationMinutes: Math.round |
| 625 | } |
| 626 | : { |
| 627 | flight: transformFlight(flights |
| 628 | durationMinutes: 0, |
| 629 | }, |
| 630 | longestDurationFlight: longestDurationFlight |
| 631 | ? { |
| 632 | flight: transformFlight(longestDurationFlight |
| 633 | durationMinutes: Math.round |
| 634 | } |
| 635 | : { |
| 636 | flight: transformFlight(flights |
| 637 | durationMinutes: 0, |
| 638 | }, |
| 639 | airlines, |
| 640 | airports, |
| 641 | topRoutes, |
| 642 | }; |
| 643 | } |
| 644 | |
| 645 | private getEmptyStats(): |
| 646 | return { |
| 647 | mostFlownAircraft: { |
| 648 | aircraftName: '', |
| 649 | flightCount: 0, |
| 650 | }, |
| 651 | aircraftStats: { |
| 652 | mostFlownAircraftName: '', |
| 653 | mostFlownAircraftFlightCount: 0, |
| 654 | mostFlownAircraftFlights: [], |
| 655 | mostCommonTailNumber: '', |
| 656 | mostCommonTailNumberCount: 0, |
| 657 | }, |
| 658 | passport: { |
| 659 | totalFlights: 0, |
| 660 | totalDistanceKm: 0, |
| 661 | totalDurationMinutes: 0, |
| 662 | totalAirports: 0, |
| 663 | totalAirlines: 0, |
| 664 | }, |
| 665 | shortestDistanceFlight: { |
| 666 | flight: {} as unknown |
| 667 | distanceKm: 0, |
| 668 | }, |
| 669 | longestDistanceFlight: { |
| 670 | flight: {} as unknown |
| 671 | distanceKm: 0, |
| 672 | }, |
| 673 | shortestDurationFlight: { |
| 674 | flight: {} as unknown |
| 675 | durationMinutes: 0, |
| 676 | }, |
| 677 | longestDurationFlight: { |
| 678 | flight: {} as unknown |
| 679 | durationMinutes: 0, |
| 680 | }, |
| 681 | airlines: [], |
| 682 | airports: [], |
| 683 | topRoutes: [], |
| 684 | }; |
| 685 | } |
| 686 | } |