import type { FlightBundle, FlightLeg } from "../../types/flights"; import { getDirectFlights } from "./get-direct-flights"; import { getPossibleConnectingAirports } from "./get-possible-connecting-airports"; import { Airport } from "../../types/airport"; import { UTCDate } from "@date-fns/utc"; import { addDays, format, differenceInMinutes } from "date-fns"; import { getTiles } from "./get-tiles"; import { buildSeed } from "../seed/build-seed"; import { procedurallyGetUuidV4 } from "../seed/procedurally-get-uuid-v4"; import { getIndirectBundleCount, getMultipleConnectionBundleCount, } from "./get-indirect-bundle-count"; import { getBundleSortingScore } from "./get-bundle-sorting-score"; interface GetIndirectFlightBundlesOptions { originAirport: Airport; destinationAirport: Airport; date: string; } const MAX_CONNECTIONS = 3; const MAX_FLIGHTS_PER_SEGMENT = 12; const MAX_SEQUENCE_COUNT_BY_LENGTH: Record = { 2: 80, 3: 40, }; const MAX_EXTRA_MULTI_CONNECTION_BUNDLES = 40; const MAX_BUNDLES_PER_SEQUENCE = 250; const generateConnectingAirportSequences = ( airports: Airport[], maxConnections: number ) => { const sequences: Airport[][] = []; const helper = (path: Airport[], usedAirportIds: Set) => { if (path.length > 0) { sequences.push([...path]); } if (path.length === maxConnections) { return; } for (const airport of airports) { if (usedAirportIds.has(airport.id)) { continue; } path.push(airport); usedAirportIds.add(airport.id); helper(path, usedAirportIds); usedAirportIds.delete(airport.id); path.pop(); } }; helper([], new Set()); return sequences; }; const limitSequencesByLength = (sequences: Airport[][]) => { const sequencesByLength = new Map(); for (const sequence of sequences) { const sequenceLength = sequence.length; const limit = MAX_SEQUENCE_COUNT_BY_LENGTH[sequenceLength] ?? Infinity; const sequencesForLength = sequencesByLength.get(sequenceLength); if (sequencesForLength) { if (sequencesForLength.length >= limit) { continue; } sequencesForLength.push(sequence); } else { sequencesByLength.set(sequenceLength, [sequence]); } } return Array.from(sequencesByLength.values()).flat(); }; type FlightCache = Map>; const getFlightsWithCache = async ( originAirport: Airport, destinationAirport: Airport, date: string, flightCache: FlightCache ) => { const cacheKey = `${originAirport.id}-${destinationAirport.id}-${date}`; if (!flightCache.has(cacheKey)) { flightCache.set( cacheKey, getDirectFlights({ originAirport, destinationAirport, date, }) ); } return flightCache.get(cacheKey)!; }; interface GetFlightsForSegmentOptions { originAirport: Airport; destinationAirport: Airport; baseDate: string; maxAdditionalDays: number; flightCache: FlightCache; } const getFlightsForSegment = async ({ originAirport, destinationAirport, baseDate, maxAdditionalDays, flightCache, }: GetFlightsForSegmentOptions) => { const baseDateObject = new UTCDate(baseDate); const flightPromises: Promise[] = []; for (let offset = 0; offset <= maxAdditionalDays; offset += 1) { const dateToFetch = format(addDays(baseDateObject, offset), "yyyy-MM-dd"); flightPromises.push( getFlightsWithCache( originAirport, destinationAirport, dateToFetch, flightCache ) ); } const flights = (await Promise.all(flightPromises)).flat(); const sortedFlights = flights.slice().sort((first, second) => { const firstDeparture = new UTCDate(first.departTime).getTime(); const secondDeparture = new UTCDate(second.departTime).getTime(); return firstDeparture - secondDeparture; }); return sortedFlights.slice(0, MAX_FLIGHTS_PER_SEGMENT); }; const findCompatibleBundles = ( legsBySegment: FlightLeg[][], options: GetIndirectFlightBundlesOptions, maxBundles: number ): FlightBundle[] => { const minLayoverTimeInMins = 45; const maxLayoverTimeInMins = 720; const compatibleBundles: FlightBundle[] = []; const buildBundle = (currentLegs: FlightLeg[], segmentIndex: number) => { if (compatibleBundles.length >= maxBundles) { return; } if (segmentIndex === legsBySegment.length) { const legIds = currentLegs.map((leg) => leg.id).join("-"); const bundleSeed = buildSeed( `${options.originAirport.id}-${options.destinationAirport.id}-${options.date}-${legIds}-flight-bundle-generator` ); const tiles = getTiles({ bundleSeed, }); compatibleBundles.push({ id: procedurallyGetUuidV4(bundleSeed), legs: [...currentLegs], tiles, }); return; } const flightsForSegment = legsBySegment[segmentIndex]; for (const leg of flightsForSegment) { if (segmentIndex > 0) { const previousLeg = currentLegs[segmentIndex - 1]; if (previousLeg.destinationAirportId !== leg.originAirportId) { continue; } const previousArrival = new UTCDate(previousLeg.arrivalTime); const nextDeparture = new UTCDate(leg.departTime); const layoverTimeInMins = differenceInMinutes( nextDeparture, previousArrival ); const isLayoverInRange = layoverTimeInMins >= minLayoverTimeInMins && layoverTimeInMins <= maxLayoverTimeInMins; if (!isLayoverInRange) { continue; } } currentLegs.push(leg); buildBundle(currentLegs, segmentIndex + 1); currentLegs.pop(); if (compatibleBundles.length >= maxBundles) { break; } } }; buildBundle([], 0); return compatibleBundles; }; export const getIndirectFlightBundles = async ( options: GetIndirectFlightBundlesOptions ) => { const { originAirport, destinationAirport, date } = options; const possibleConnectingAirports = await getPossibleConnectingAirports({ originAirport, destinationAirport, }); const priorityScoreCache = new Map(); const getPriorityScore = (airport: Airport) => { const cachedScore = priorityScoreCache.get(airport.id); if (cachedScore !== undefined) { return cachedScore; } let score = 0; if (airport.iso_country === originAirport.iso_country) { score -= 8; } if (airport.iso_country === destinationAirport.iso_country) { score -= 4; } if (airport.continent === originAirport.continent) { score -= 2; } if (airport.continent === destinationAirport.continent) { score -= 1; } priorityScoreCache.set(airport.id, score); return score; }; const prioritizedConnectingAirports = possibleConnectingAirports .slice() .sort((firstAirport, secondAirport) => { const firstScore = getPriorityScore(firstAirport); const secondScore = getPriorityScore(secondAirport); if (firstScore !== secondScore) { return firstScore - secondScore; } return firstAirport.id.localeCompare(secondAirport.id); }); const indirectBundleCount = getIndirectBundleCount({ originAirport, destinationAirport, seed: buildSeed( `${originAirport.id}-${destinationAirport.id}-${date}-indirect-flight-bundle-counter` ), }); const multipleConnectionBundleCount = getMultipleConnectionBundleCount({ originAirport, destinationAirport, seed: buildSeed( `${originAirport.id}-${destinationAirport.id}-${date}-multiple-connection-flight-bundle-counter` ), }); const additionalMultiConnectionBundles = Math.min( MAX_EXTRA_MULTI_CONNECTION_BUNDLES, Math.max(0, multipleConnectionBundleCount - indirectBundleCount) ); const desiredBundleCount = indirectBundleCount + additionalMultiConnectionBundles; const maxGeneratedBundles = Math.max( desiredBundleCount * 3, desiredBundleCount + 40 ); const connectingAirportSequences = limitSequencesByLength( generateConnectingAirportSequences( prioritizedConnectingAirports, MAX_CONNECTIONS ) ); const allCompatibleBundles: FlightBundle[] = []; const flightCache: FlightCache = new Map(); for (const sequence of connectingAirportSequences) { const pathAirports = [originAirport, ...sequence, destinationAirport]; const segments = pathAirports.slice(0, -1).map((airport, index) => ({ originAirport: airport, destinationAirport: pathAirports[index + 1], })); const maxAdditionalDays = Math.min(sequence.length, MAX_CONNECTIONS); const legsBySegment = await Promise.all( segments.map( ({ originAirport: segmentOrigin, destinationAirport: segmentDestination, }) => getFlightsForSegment({ originAirport: segmentOrigin, destinationAirport: segmentDestination, baseDate: date, maxAdditionalDays, flightCache, }) ) ); if (legsBySegment.some((segmentFlights) => segmentFlights.length === 0)) { continue; } const bundles = findCompatibleBundles( legsBySegment, options, MAX_BUNDLES_PER_SEQUENCE ); allCompatibleBundles.push(...bundles); if (allCompatibleBundles.length > maxGeneratedBundles) { allCompatibleBundles.sort( (firstBundle, secondBundle) => getBundleSortingScore(secondBundle) - getBundleSortingScore(firstBundle) ); allCompatibleBundles.length = maxGeneratedBundles; } } const sortedBundles = allCompatibleBundles.sort((a, b) => { return getBundleSortingScore(b) - getBundleSortingScore(a); }); const originalBundles = sortedBundles.slice(0, indirectBundleCount); const selectedBundleIds = new Set(originalBundles.map((bundle) => bundle.id)); const selectedBundles = [...originalBundles]; const multiConnectionCandidates = sortedBundles.filter( (bundle) => bundle.legs.length >= 3 && !selectedBundleIds.has(bundle.id) ); for (const bundle of multiConnectionCandidates) { if (selectedBundles.length >= desiredBundleCount) { break; } selectedBundles.push(bundle); selectedBundleIds.add(bundle.id); } if (selectedBundles.length < desiredBundleCount) { for (const bundle of sortedBundles) { if (selectedBundles.length >= desiredBundleCount) { break; } if (selectedBundleIds.has(bundle.id)) { continue; } selectedBundles.push(bundle); selectedBundleIds.add(bundle.id); } } return selectedBundles .sort((a, b) => getBundleSortingScore(b) - getBundleSortingScore(a)) .slice(0, desiredBundleCount); };