Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "flight-tracker-api",
"version": "3.90.0",
"version": "3.91.0",
"private": true,
"homepage": "https://mypreflight.io",
"author": "mypreflight",
Expand Down
10 changes: 10 additions & 0 deletions src/core/domain/events/dto/flight.events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export enum FlightEventType {
AtcCallsignWasChanged = 'flight.atc-callsign-changed',
FlightWasReleased = 'flight.released',
PilotCheckedIn = 'flight.pilot-checked-in',
StaleCheckInWasRemoved = 'flight.stale-check-in-removed',
BoardingWasStarted = 'flight.boarding-started',
BoardingWasFinished = 'flight.boarding-finished',
OffBlockWasReported = 'flight.off-block-reported',
Expand Down Expand Up @@ -71,6 +72,11 @@ export type PilotCheckedInEventPayload = AircraftFlightEventPayload & {
airportIds: string[];
};

export type StaleCheckInRemovedEventPayload = AircraftFlightEventPayload & {
captainId: string | null;
airportIds: string[];
};

export type TakeoffReportedEventPayload = FlightEventPayload & {
payload: { automaticallyDetected: boolean };
};
Expand Down Expand Up @@ -145,6 +151,10 @@ export class PilotCheckedInEvent extends FlightLifecycleEvent<PilotCheckedInEven
static readonly name = FlightEventType.PilotCheckedIn;
}

export class StaleCheckInWasRemovedEvent extends FlightLifecycleEvent<StaleCheckInRemovedEventPayload> {
static readonly name = FlightEventType.StaleCheckInWasRemoved;
}

export class BoardingWasStartedEvent extends FlightLifecycleEvent<GroundServiceEventPayload> {
static readonly name = FlightEventType.BoardingWasStarted;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
OffBlockWasReportedEvent,
OnBlockWasReportedEvent,
FlightWasClosedEvent,
StaleCheckInWasRemovedEvent,
} from '../../../../../core/domain/events/dto/flight.events';
import { QueryBus } from '@nestjs/cqrs';
import { AircraftRepository } from '../../../infra/database/repository/aircraft.repository';
Expand Down Expand Up @@ -36,6 +37,16 @@ export class FlightLifecycleListener {
);
}

@OnEvent(FlightEventType.StaleCheckInWasRemoved)
async onStaleCheckInWasRemoved(
event: StaleCheckInWasRemovedEvent,
): Promise<void> {
await this.aircraftRepository.updateState(
event.payload.aircraftId,
AircraftState.Idle,
);
}

@OnEvent(FlightEventType.OffBlockWasReported)
async onOffBlockWasReported(event: OffBlockWasReportedEvent): Promise<void> {
await this.aircraftRepository.updateState(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
FlightEventType,
PilotCheckedInEvent,
OnBlockWasReportedEvent,
StaleCheckInWasRemovedEvent,
} from '../../../../../core/domain/events/dto/flight.events';
import { AircraftRepository } from '../../../infra/database/repository/aircraft.repository';
import { RepositionRepository } from '../../../infra/database/repository/reposition.repository';
Expand All @@ -30,6 +31,16 @@ export class RepositionFlightLifecycleListener {
);
}

@OnEvent(FlightEventType.StaleCheckInWasRemoved)
async onStaleCheckInWasRemoved(
event: StaleCheckInWasRemovedEvent,
): Promise<void> {
await this.repositionRepository.removePendingPerformingFlight(
event.payload.aircraftId,
event.payload.flightId,
);
}

@OnEvent(FlightEventType.OnBlockWasReported)
async onOnBlockWasReported(event: OnBlockWasReportedEvent): Promise<void> {
await this.repositionRepository.finishPerformingFlight(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,20 @@ export class RepositionRepository {
});
}

async removePendingPerformingFlight(
aircraftId: string,
flightId: string,
): Promise<void> {
await this.prisma.aircraftReposition.deleteMany({
where: {
aircraftId,
flightId,
type: AircraftRepositionType.performing_flight,
status: AircraftRepositionStatus.pending,
},
});
}

async createDeadhead(
type: DeadheadType,
aircraftId: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
FlightEventType,
OnBlockWasReportedEvent,
PilotCheckedInEvent,
StaleCheckInWasRemovedEvent,
} from '../../../../../core/domain/events/dto/flight.events';
import { StartMonitoringAirportsWeatherCommand } from '../../command/weather/start-monitoring-airports-weather.command';
import { StopMonitoringAirportsWeatherCommand } from '../../command/weather/stop-monitoring-airports-weather.command';
Expand Down Expand Up @@ -35,6 +36,16 @@ export class WeatherFlightLifecycleListener {
}
}

@OnEvent(FlightEventType.StaleCheckInWasRemoved)
async onStaleCheckInWasRemoved(
event: StaleCheckInWasRemovedEvent,
): Promise<void> {
const command = new StopMonitoringAirportsWeatherCommand(
event.payload.airportIds,
);
await this.commandBus.execute(command);
}

@OnEvent(FlightEventType.OnBlockWasReported)
async onOnBlockWasReported(event: OnBlockWasReportedEvent): Promise<void> {
const command = new StopMonitoringAirportsWeatherCommand(
Expand Down
3 changes: 2 additions & 1 deletion src/modules/automations/automations.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common';
import { DelayAutoApprovalService } from './infra/service/delay-auto-approval.service';
import { StaleCheckInRemovalService } from './infra/service/stale-check-in-removal.service';
import { ScheduledJobsModule } from '../../core/scheduling/scheduled-jobs.module';

@Module({
imports: [ScheduledJobsModule],
providers: [DelayAutoApprovalService],
providers: [DelayAutoApprovalService, StaleCheckInRemovalService],
})
export class AutomationsModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { StaleCheckInRemovalService } from './stale-check-in-removal.service';
import { ScheduledJobs } from '../../../../core/scheduling/scheduled-jobs.service';
import { ListStaleCheckInsQuery } from '../../../flights/application/query/list-stale-check-ins.query';
import { RemoveStaleCheckInCommand } from '../../../flights/application/command/remove-stale-check-in.command';
import { staleCheckInCutoff } from '../../model/stale-check-in.constants';

const NOW = new Date('2026-11-18T12:00:00.000Z');

function serviceFor(flightIds: string[], failing: string[] = []) {
const queryBus = { execute: jest.fn().mockResolvedValue(flightIds) };
const commandBus = {
execute: jest.fn((command: RemoveStaleCheckInCommand) =>
failing.includes(command.flightId)
? Promise.reject(new Error('moved on'))
: Promise.resolve(),
),
};
const service = new StaleCheckInRemovalService(
queryBus as unknown as QueryBus,
commandBus as unknown as CommandBus,
{} as ScheduledJobs,
);

return { service, queryBus, commandBus };
}

describe('staleCheckInCutoff', () => {
it('is 24 hours before now', () => {
expect(staleCheckInCutoff(NOW)).toEqual(
new Date('2026-11-17T12:00:00.000Z'),
);
});
});

describe('StaleCheckInRemovalService', () => {
it('removes every flight checked in more than 24 hours ago', async () => {
const { service, queryBus, commandBus } = serviceFor(['a', 'b']);

await service.removeExpired(NOW);

expect(queryBus.execute).toHaveBeenCalledWith(
new ListStaleCheckInsQuery(new Date('2026-11-17T12:00:00.000Z')),
);
expect(commandBus.execute).toHaveBeenCalledWith(
new RemoveStaleCheckInCommand('a'),
);
expect(commandBus.execute).toHaveBeenCalledWith(
new RemoveStaleCheckInCommand('b'),
);
});

it('carries on past a flight that could not be removed', async () => {
const { service, commandBus } = serviceFor(['a', 'b'], ['a']);

await expect(service.removeExpired(NOW)).resolves.toBeUndefined();
expect(commandBus.execute).toHaveBeenCalledTimes(2);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Injectable, Logger } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ListStaleCheckInsQuery } from '../../../flights/application/query/list-stale-check-ins.query';
import { RemoveStaleCheckInCommand } from '../../../flights/application/command/remove-stale-check-in.command';
import { staleCheckInCutoff } from '../../model/stale-check-in.constants';
import {
EVERY_5_MINUTES_SECONDS,
ScheduledJobs,
} from '../../../../core/scheduling/scheduled-jobs.service';

@Injectable()
export class StaleCheckInRemovalService {
private readonly logger = new Logger(StaleCheckInRemovalService.name);

constructor(
private readonly queryBus: QueryBus,
private readonly commandBus: CommandBus,
private readonly scheduledJobs: ScheduledJobs,
) {}

@Cron(CronExpression.EVERY_5_MINUTES)
async removeStaleCheckIns(): Promise<void> {
await this.scheduledJobs.runExclusively(
'stale-check-in-removal',
EVERY_5_MINUTES_SECONDS,
() => this.removeExpired(new Date()),
);
}

async removeExpired(now: Date): Promise<void> {
const flightIds: string[] = await this.queryBus.execute(
new ListStaleCheckInsQuery(staleCheckInCutoff(now)),
);

for (const flightId of flightIds) {
try {
await this.commandBus.execute(new RemoveStaleCheckInCommand(flightId));
this.logger.log(
`Removed flight ${flightId}, checked in but not boarded for 24 hours.`,
);
} catch (error) {
this.logger.warn(
`Could not remove stale check-in ${flightId}: ${error}`,
);
}
}
}
}
7 changes: 7 additions & 0 deletions src/modules/automations/model/stale-check-in.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const STALE_CHECK_IN_AFTER_HOURS = 24;

const HOUR_MS = 60 * 60 * 1000;

export function staleCheckInCutoff(now: Date): Date {
return new Date(now.getTime() - STALE_CHECK_IN_AFTER_HOURS * HOUR_MS);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { FlightsRepository } from '../../infra/database/repository/flights.repository';
import { DomainEventEmitter } from '../../../../core/domain/events/domain-event-emitter';

export class RemoveStaleCheckInCommand {
constructor(public readonly flightId: string) {}
}

@CommandHandler(RemoveStaleCheckInCommand)
export class RemoveStaleCheckInHandler implements ICommandHandler<RemoveStaleCheckInCommand> {
constructor(
private readonly flightsRepository: FlightsRepository,
private readonly domainEvents: DomainEventEmitter,
) {}

async execute(command: RemoveStaleCheckInCommand): Promise<void> {
const flight = await this.flightsRepository.load(command.flightId);

flight.removeStaleCheckIn();

await this.domainEvents.emitRecordedAsync(flight);
await this.flightsRepository.remove(command.flightId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs';
import { FlightsRepository } from '../../infra/database/repository/flights.repository';

export class ListStaleCheckInsQuery extends Query<string[]> {
constructor(public readonly checkedInBefore: Date) {
super();
}
}

@QueryHandler(ListStaleCheckInsQuery)
export class ListStaleCheckInsHandler implements IQueryHandler<ListStaleCheckInsQuery> {
constructor(private readonly repository: FlightsRepository) {}

async execute(query: ListStaleCheckInsQuery): Promise<string[]> {
return this.repository.findStaleCheckIns(query.checkedInBefore);
}
}
4 changes: 4 additions & 0 deletions src/modules/flights/flights.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ import { GetFlightHandler } from './application/query/get-flight.query';
import { ListAllFlightsHandler } from './application/query/list-all-flights.query';
import { GetAircraftFlightHistoryHandler } from './application/query/get-aircraft-flight-history.query';
import { RemoveFlightHandler } from './application/command/remove-flight.command';
import { RemoveStaleCheckInHandler } from './application/command/remove-stale-check-in.command';
import { ListStaleCheckInsHandler } from './application/query/list-stale-check-ins.query';
import { CheckInPilotForFlightHandler } from './application/command/check-in-pilot.command';
import { StartBoardingHandler } from './application/command/start-boarding.command';
import { FinishBoardingHandler } from './application/command/finish-boarding.command';
Expand Down Expand Up @@ -214,6 +216,8 @@ import { ScheduledJobsModule } from '../../core/scheduling/scheduled-jobs.module
ListAllFlightsHandler,
GetAircraftFlightHistoryHandler,
RemoveFlightHandler,
RemoveStaleCheckInHandler,
ListStaleCheckInsHandler,
CheckInPilotForFlightHandler,
StartBoardingHandler,
FinishBoardingHandler,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
toFlightSnapshot,
} from './flight-aggregate.mapper';
import { PrismaService } from '../../../../../core/provider/prisma/prisma.service';
import { FlightEventType } from '../../../../../core/domain/events/dto/flight.events';
import { AircraftCabinLayout } from '../../../../aircraft/model/cabin-layout.model';
import { toAircraftCabinLayout } from '../../../../aircraft/model/cabin-layout-assignment';
import {
Expand Down Expand Up @@ -647,6 +648,23 @@ export class FlightsRepository {
};
}

async findStaleCheckIns(checkedInBefore: Date): Promise<string[]> {
const flights = await this.prisma.flight.findMany({
where: {
status: FlightStatus.CheckedIn,
flightEvent: {
some: {
type: FlightEventType.PilotCheckedIn,
createdAt: { lte: checkedInBefore },
},
},
},
select: { id: true },
});

return flights.map(({ id }) => id);
}

async remove(id: string): Promise<void> {
await this.prisma.airportsOnFlights.deleteMany({ where: { flightId: id } });
await this.prisma.flightEvent.deleteMany({ where: { flightId: id } });
Expand Down
6 changes: 6 additions & 0 deletions src/modules/flights/model/error/flight.error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ export class DestinationAirportSameAsDepartureAirportError extends BadRequestErr
}
}

export class StaleCheckInHasMovedOnError extends ConflictError {
constructor() {
super('Only a checked-in flight that has not started boarding is removed.');
}
}

export class ScheduledFlightCannotBeRemovedError extends BadRequestError {
constructor() {
super('Flight that has been scheduled cannot be removed.');
Expand Down
Loading
Loading