From 929892cc67d244414242d0785b019fa77afc76df Mon Sep 17 00:00:00 2001 From: Oskar Barcz Date: Wed, 18 Nov 2026 10:45:29 +0100 Subject: [PATCH] Remove a flight that was checked in but not boarded for 24 hours A pilot's own import checks them in straight away, and one flight in progress blocks the next import, so an import they never fly would block them for good. Every five minutes, a flight checked in more than 24 hours ago that hasn't started boarding is removed. Each module undoes what check-in started for it: the pilot's current flight and pending travel, the pilot's aircraft entry, the aircraft's checked-in state and pending flight, a rotation that only this check-in started, and the weather watch. Repositionings to the departure airport stay, since that move happened. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 +- package.json | 2 +- src/core/domain/events/dto/flight.events.ts | 10 ++++ .../external/flight-lifecycle.listener.ts | 11 ++++ .../reposition-flight-lifecycle.listener.ts | 11 ++++ .../repository/reposition.repository.ts | 14 +++++ .../weather-flight-lifecycle.listener.ts | 11 ++++ src/modules/automations/automations.module.ts | 3 +- .../stale-check-in-removal.service.spec.ts | 59 +++++++++++++++++++ .../service/stale-check-in-removal.service.ts | 49 +++++++++++++++ .../model/stale-check-in.constants.ts | 7 +++ .../command/remove-stale-check-in.command.ts | 24 ++++++++ .../query/list-stale-check-ins.query.ts | 17 ++++++ src/modules/flights/flights.module.ts | 4 ++ .../database/repository/flights.repository.ts | 18 ++++++ .../flights/model/error/flight.error.ts | 6 ++ src/modules/flights/model/flight.spec.ts | 33 +++++++++++ src/modules/flights/model/flight.ts | 15 +++++ .../external/flight-lifecycle.listener.ts | 26 ++++++++ .../external/flight-lifecycle.listener.ts | 11 ++++ .../event/external/user-aircraft.listener.ts | 8 +++ .../repository/user-aircraft.repository.ts | 4 ++ .../repository/user-travel.repository.ts | 10 ++++ .../database/repository/users.repository.ts | 11 ++++ 24 files changed, 364 insertions(+), 4 deletions(-) create mode 100644 src/modules/automations/infra/service/stale-check-in-removal.service.spec.ts create mode 100644 src/modules/automations/infra/service/stale-check-in-removal.service.ts create mode 100644 src/modules/automations/model/stale-check-in.constants.ts create mode 100644 src/modules/flights/application/command/remove-stale-check-in.command.ts create mode 100644 src/modules/flights/application/query/list-stale-check-ins.query.ts diff --git a/package-lock.json b/package-lock.json index 0c1d8eed..2a1040e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "flight-tracker-api", - "version": "3.90.0", + "version": "3.91.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "flight-tracker-api", - "version": "3.90.0", + "version": "3.91.0", "license": "Unlicense", "dependencies": { "@faker-js/faker": "^10.6.0", diff --git a/package.json b/package.json index 31a67e73..8567bb53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flight-tracker-api", - "version": "3.90.0", + "version": "3.91.0", "private": true, "homepage": "https://mypreflight.io", "author": "mypreflight", diff --git a/src/core/domain/events/dto/flight.events.ts b/src/core/domain/events/dto/flight.events.ts index 22318991..90e10217 100644 --- a/src/core/domain/events/dto/flight.events.ts +++ b/src/core/domain/events/dto/flight.events.ts @@ -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', @@ -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 }; }; @@ -145,6 +151,10 @@ export class PilotCheckedInEvent extends FlightLifecycleEvent { + static readonly name = FlightEventType.StaleCheckInWasRemoved; +} + export class BoardingWasStartedEvent extends FlightLifecycleEvent { static readonly name = FlightEventType.BoardingWasStarted; } diff --git a/src/modules/aircraft/application/event/external/flight-lifecycle.listener.ts b/src/modules/aircraft/application/event/external/flight-lifecycle.listener.ts index 8695a2b8..b59a6fb4 100644 --- a/src/modules/aircraft/application/event/external/flight-lifecycle.listener.ts +++ b/src/modules/aircraft/application/event/external/flight-lifecycle.listener.ts @@ -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'; @@ -36,6 +37,16 @@ export class FlightLifecycleListener { ); } + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + await this.aircraftRepository.updateState( + event.payload.aircraftId, + AircraftState.Idle, + ); + } + @OnEvent(FlightEventType.OffBlockWasReported) async onOffBlockWasReported(event: OffBlockWasReportedEvent): Promise { await this.aircraftRepository.updateState( diff --git a/src/modules/aircraft/application/event/external/reposition-flight-lifecycle.listener.ts b/src/modules/aircraft/application/event/external/reposition-flight-lifecycle.listener.ts index 01dfeefe..a15ecc70 100644 --- a/src/modules/aircraft/application/event/external/reposition-flight-lifecycle.listener.ts +++ b/src/modules/aircraft/application/event/external/reposition-flight-lifecycle.listener.ts @@ -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'; @@ -30,6 +31,16 @@ export class RepositionFlightLifecycleListener { ); } + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + await this.repositionRepository.removePendingPerformingFlight( + event.payload.aircraftId, + event.payload.flightId, + ); + } + @OnEvent(FlightEventType.OnBlockWasReported) async onOnBlockWasReported(event: OnBlockWasReportedEvent): Promise { await this.repositionRepository.finishPerformingFlight( diff --git a/src/modules/aircraft/infra/database/repository/reposition.repository.ts b/src/modules/aircraft/infra/database/repository/reposition.repository.ts index bfc15587..88d82bcc 100644 --- a/src/modules/aircraft/infra/database/repository/reposition.repository.ts +++ b/src/modules/aircraft/infra/database/repository/reposition.repository.ts @@ -84,6 +84,20 @@ export class RepositionRepository { }); } + async removePendingPerformingFlight( + aircraftId: string, + flightId: string, + ): Promise { + await this.prisma.aircraftReposition.deleteMany({ + where: { + aircraftId, + flightId, + type: AircraftRepositionType.performing_flight, + status: AircraftRepositionStatus.pending, + }, + }); + } + async createDeadhead( type: DeadheadType, aircraftId: string, diff --git a/src/modules/airports/application/event/external/weather-flight-lifecycle.listener.ts b/src/modules/airports/application/event/external/weather-flight-lifecycle.listener.ts index 9fa70d83..24ad3a9f 100644 --- a/src/modules/airports/application/event/external/weather-flight-lifecycle.listener.ts +++ b/src/modules/airports/application/event/external/weather-flight-lifecycle.listener.ts @@ -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'; @@ -35,6 +36,16 @@ export class WeatherFlightLifecycleListener { } } + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + const command = new StopMonitoringAirportsWeatherCommand( + event.payload.airportIds, + ); + await this.commandBus.execute(command); + } + @OnEvent(FlightEventType.OnBlockWasReported) async onOnBlockWasReported(event: OnBlockWasReportedEvent): Promise { const command = new StopMonitoringAirportsWeatherCommand( diff --git a/src/modules/automations/automations.module.ts b/src/modules/automations/automations.module.ts index a11b4049..ae847719 100644 --- a/src/modules/automations/automations.module.ts +++ b/src/modules/automations/automations.module.ts @@ -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 {} diff --git a/src/modules/automations/infra/service/stale-check-in-removal.service.spec.ts b/src/modules/automations/infra/service/stale-check-in-removal.service.spec.ts new file mode 100644 index 00000000..5fe6baaf --- /dev/null +++ b/src/modules/automations/infra/service/stale-check-in-removal.service.spec.ts @@ -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); + }); +}); diff --git a/src/modules/automations/infra/service/stale-check-in-removal.service.ts b/src/modules/automations/infra/service/stale-check-in-removal.service.ts new file mode 100644 index 00000000..517149f7 --- /dev/null +++ b/src/modules/automations/infra/service/stale-check-in-removal.service.ts @@ -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 { + await this.scheduledJobs.runExclusively( + 'stale-check-in-removal', + EVERY_5_MINUTES_SECONDS, + () => this.removeExpired(new Date()), + ); + } + + async removeExpired(now: Date): Promise { + 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}`, + ); + } + } + } +} diff --git a/src/modules/automations/model/stale-check-in.constants.ts b/src/modules/automations/model/stale-check-in.constants.ts new file mode 100644 index 00000000..afb1160d --- /dev/null +++ b/src/modules/automations/model/stale-check-in.constants.ts @@ -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); +} diff --git a/src/modules/flights/application/command/remove-stale-check-in.command.ts b/src/modules/flights/application/command/remove-stale-check-in.command.ts new file mode 100644 index 00000000..517bd1e1 --- /dev/null +++ b/src/modules/flights/application/command/remove-stale-check-in.command.ts @@ -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 { + constructor( + private readonly flightsRepository: FlightsRepository, + private readonly domainEvents: DomainEventEmitter, + ) {} + + async execute(command: RemoveStaleCheckInCommand): Promise { + const flight = await this.flightsRepository.load(command.flightId); + + flight.removeStaleCheckIn(); + + await this.domainEvents.emitRecordedAsync(flight); + await this.flightsRepository.remove(command.flightId); + } +} diff --git a/src/modules/flights/application/query/list-stale-check-ins.query.ts b/src/modules/flights/application/query/list-stale-check-ins.query.ts new file mode 100644 index 00000000..7405ea16 --- /dev/null +++ b/src/modules/flights/application/query/list-stale-check-ins.query.ts @@ -0,0 +1,17 @@ +import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs'; +import { FlightsRepository } from '../../infra/database/repository/flights.repository'; + +export class ListStaleCheckInsQuery extends Query { + constructor(public readonly checkedInBefore: Date) { + super(); + } +} + +@QueryHandler(ListStaleCheckInsQuery) +export class ListStaleCheckInsHandler implements IQueryHandler { + constructor(private readonly repository: FlightsRepository) {} + + async execute(query: ListStaleCheckInsQuery): Promise { + return this.repository.findStaleCheckIns(query.checkedInBefore); + } +} diff --git a/src/modules/flights/flights.module.ts b/src/modules/flights/flights.module.ts index adf35e72..8bc9abf4 100644 --- a/src/modules/flights/flights.module.ts +++ b/src/modules/flights/flights.module.ts @@ -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'; @@ -214,6 +216,8 @@ import { ScheduledJobsModule } from '../../core/scheduling/scheduled-jobs.module ListAllFlightsHandler, GetAircraftFlightHistoryHandler, RemoveFlightHandler, + RemoveStaleCheckInHandler, + ListStaleCheckInsHandler, CheckInPilotForFlightHandler, StartBoardingHandler, FinishBoardingHandler, diff --git a/src/modules/flights/infra/database/repository/flights.repository.ts b/src/modules/flights/infra/database/repository/flights.repository.ts index 30429c02..dbae3def 100644 --- a/src/modules/flights/infra/database/repository/flights.repository.ts +++ b/src/modules/flights/infra/database/repository/flights.repository.ts @@ -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 { @@ -647,6 +648,23 @@ export class FlightsRepository { }; } + async findStaleCheckIns(checkedInBefore: Date): Promise { + 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 { await this.prisma.airportsOnFlights.deleteMany({ where: { flightId: id } }); await this.prisma.flightEvent.deleteMany({ where: { flightId: id } }); diff --git a/src/modules/flights/model/error/flight.error.ts b/src/modules/flights/model/error/flight.error.ts index be763b76..35e26e0f 100644 --- a/src/modules/flights/model/error/flight.error.ts +++ b/src/modules/flights/model/error/flight.error.ts @@ -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.'); diff --git a/src/modules/flights/model/flight.spec.ts b/src/modules/flights/model/flight.spec.ts index cab24cf5..afcbd3a6 100644 --- a/src/modules/flights/model/flight.spec.ts +++ b/src/modules/flights/model/flight.spec.ts @@ -19,6 +19,7 @@ import { PilotCheckedInEvent, PredictedTimesheetWasUpdatedEvent, ScheduledTimesheetWasUpdatedEvent, + StaleCheckInWasRemovedEvent, TakeoffWasReportedEvent, } from '../../../core/domain/events/dto/flight.events'; import { Flight, FlightActor } from './flight'; @@ -63,6 +64,7 @@ import { InvalidStatusToUpdateLoadsheetError, PreliminaryLoadsheetMissingError, ScheduledFlightCannotBeRemovedError, + StaleCheckInHasMovedOnError, } from './error/flight.error'; import { UnresolvedEmergencyCannotCloseFlightError } from './error/emergency.error'; import { FlightHasUnacceptedDelayError } from './error/delay.error'; @@ -586,6 +588,37 @@ describe('Flight', () => { }); }); + describe('removing a stale check-in', () => { + it('records the removal with the captain, aircraft and airports to clean up', () => { + const flight = flightIn(FlightStatus.CheckedIn, { captainId: 'pilot-1' }); + + flight.removeStaleCheckIn(); + + const event = onlyEvent(flight); + expect(event).toBeInstanceOf(StaleCheckInWasRemovedEvent); + expect(event.payload).toEqual({ + flightId: flight.snapshot().id, + scope: FlightEventScope.Operations, + actorId: null, + aircraftId: flight.snapshot().aircraftId, + captainId: 'pilot-1', + airportIds: flight.snapshot().airports.map((airport) => airport.id), + }); + }); + + it.each(LIFECYCLE.filter((status) => status !== FlightStatus.CheckedIn))( + 'leaves a flight in %s alone', + (status) => { + const flight = flightIn(status); + + expect(() => flight.removeStaleCheckIn()).toThrow( + StaleCheckInHasMovedOnError, + ); + expect(flight.getUncommittedEvents()).toHaveLength(0); + }, + ); + }); + describe('guards for records outside the flight', () => { it('allows removing only a created flight', () => { expect(() => diff --git a/src/modules/flights/model/flight.ts b/src/modules/flights/model/flight.ts index 3a71177e..878fe010 100644 --- a/src/modules/flights/model/flight.ts +++ b/src/modules/flights/model/flight.ts @@ -21,6 +21,7 @@ import { PilotCheckedInEvent, PredictedTimesheetWasUpdatedEvent, ScheduledTimesheetWasUpdatedEvent, + StaleCheckInWasRemovedEvent, TakeoffWasReportedEvent, } from '../../../core/domain/events/dto/flight.events'; import { AirportType } from '../../airports/model/airport.model'; @@ -59,6 +60,7 @@ import { InvalidStatusToUpdateLoadsheetError, PreliminaryLoadsheetMissingError, ScheduledFlightCannotBeRemovedError, + StaleCheckInHasMovedOnError, } from './error/flight.error'; import { UnresolvedEmergencyCannotCloseFlightError } from './error/emergency.error'; import { FlightHasUnacceptedDelayError } from './error/delay.error'; @@ -506,6 +508,19 @@ export class Flight extends AggregateRoot { ); } + removeStaleCheckIn(): void { + this.expectStatus(FlightStatus.CheckedIn, StaleCheckInHasMovedOnError); + + this.apply( + new StaleCheckInWasRemovedEvent({ + ...this.eventFor({ id: null, scope: FlightEventScope.Operations }), + aircraftId: this.state.aircraftId, + captainId: this.state.captainId, + airportIds: this.airportIds(), + }), + ); + } + assertCanUpdatePreliminaryLoadsheet(): void { this.expectStatus( FlightStatus.Created, diff --git a/src/modules/rotations/application/event/external/flight-lifecycle.listener.ts b/src/modules/rotations/application/event/external/flight-lifecycle.listener.ts index fc595c05..f3c48a42 100644 --- a/src/modules/rotations/application/event/external/flight-lifecycle.listener.ts +++ b/src/modules/rotations/application/event/external/flight-lifecycle.listener.ts @@ -4,9 +4,11 @@ import { FlightEventType, PilotCheckedInEvent, FlightWasClosedEvent, + StaleCheckInWasRemovedEvent, } from '../../../../../core/domain/events/dto/flight.events'; import { RotationsRepository } from '../../../infra/database/repository/rotations.repository'; import { RotationStatus } from '../../../model/rotation.model'; +import { FlightStatus } from '../../../../flights/model/flight.model'; @Injectable() export class FlightLifecycleListener { @@ -31,6 +33,30 @@ export class FlightLifecycleListener { ); } + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + const leg = await this.repository.findLegByFlightId(event.payload.flightId); + if (!leg) { + return; + } + + const rotation = await this.repository.findById(leg.rotationId); + if (!rotation || rotation.status !== RotationStatus.InProgress) { + return; + } + + const anyLegFlown = rotation.legs.some( + (candidate) => candidate.flight?.status === FlightStatus.Closed, + ); + if (anyLegFlown) { + return; + } + + await this.repository.updateStatus(rotation.id, RotationStatus.Ready, null); + } + @OnEvent(FlightEventType.FlightWasClosed) async onFlightWasClosed(event: FlightWasClosedEvent): Promise { const leg = await this.repository.findLegByFlightId(event.payload.flightId); diff --git a/src/modules/users/application/event/external/flight-lifecycle.listener.ts b/src/modules/users/application/event/external/flight-lifecycle.listener.ts index 6705bd39..cec6869a 100644 --- a/src/modules/users/application/event/external/flight-lifecycle.listener.ts +++ b/src/modules/users/application/event/external/flight-lifecycle.listener.ts @@ -6,6 +6,7 @@ import { PilotCheckedInEvent, OnBlockWasReportedEvent, FlightWasClosedEvent, + StaleCheckInWasRemovedEvent, } from '../../../../../core/domain/events/dto/flight.events'; import { UsersRepository } from '../../../infra/database/repository/users.repository'; import { UserTravelRepository } from '../../../infra/database/repository/user-travel.repository'; @@ -34,6 +35,16 @@ export class FlightLifecycleListener { await this.recordCheckInTravel(userId, event.payload.flightId); } + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + const { flightId } = event.payload; + + await this.usersRepository.clearCurrentFlight(flightId); + await this.travelRepository.removePendingPerformingFlight(flightId); + } + @OnEvent(FlightEventType.OnBlockWasReported) async onOnBlockWasReported(event: OnBlockWasReportedEvent): Promise { const completionStatsQuery = new GetFlightCompletionStatsQuery( diff --git a/src/modules/users/application/event/external/user-aircraft.listener.ts b/src/modules/users/application/event/external/user-aircraft.listener.ts index dda26961..3ffc6454 100644 --- a/src/modules/users/application/event/external/user-aircraft.listener.ts +++ b/src/modules/users/application/event/external/user-aircraft.listener.ts @@ -3,6 +3,7 @@ import { OnEvent } from '@nestjs/event-emitter'; import { FlightEventType, PilotCheckedInEvent, + StaleCheckInWasRemovedEvent, } from '../../../../../core/domain/events/dto/flight.events'; import { UserAircraftRepository } from '../../../infra/database/repository/user-aircraft.repository'; @@ -26,4 +27,11 @@ export class UserAircraftListener { flightId: event.payload.flightId, }); } + + @OnEvent(FlightEventType.StaleCheckInWasRemoved) + async onStaleCheckInWasRemoved( + event: StaleCheckInWasRemovedEvent, + ): Promise { + await this.userAircraftRepository.removeForFlight(event.payload.flightId); + } } diff --git a/src/modules/users/infra/database/repository/user-aircraft.repository.ts b/src/modules/users/infra/database/repository/user-aircraft.repository.ts index ce228b94..9e334d20 100644 --- a/src/modules/users/infra/database/repository/user-aircraft.repository.ts +++ b/src/modules/users/infra/database/repository/user-aircraft.repository.ts @@ -53,6 +53,10 @@ export class UserAircraftRepository { await this.prisma.userAircraft.create({ data }); } + async removeForFlight(flightId: string): Promise { + await this.prisma.userAircraft.deleteMany({ where: { flightId } }); + } + async findByUser(userId: string): Promise { const rows = await this.prisma.userAircraft.findMany({ where: { userId }, diff --git a/src/modules/users/infra/database/repository/user-travel.repository.ts b/src/modules/users/infra/database/repository/user-travel.repository.ts index 942833e5..deaab131 100644 --- a/src/modules/users/infra/database/repository/user-travel.repository.ts +++ b/src/modules/users/infra/database/repository/user-travel.repository.ts @@ -83,6 +83,16 @@ export class UserTravelRepository { }); } + async removePendingPerformingFlight(flightId: string): Promise { + await this.prisma.userTravel.deleteMany({ + where: { + flightId, + type: UserTravelType.performing_flight, + status: UserTravelStatus.pending, + }, + }); + } + async createDeadhead( type: DeadheadType, userId: string, diff --git a/src/modules/users/infra/database/repository/users.repository.ts b/src/modules/users/infra/database/repository/users.repository.ts index 11930930..c9df4256 100644 --- a/src/modules/users/infra/database/repository/users.repository.ts +++ b/src/modules/users/infra/database/repository/users.repository.ts @@ -418,6 +418,17 @@ export class UsersRepository { await this.cacheManager.del(cacheByUser(CACHE_KEYS.USER_ME, id)); } + async clearCurrentFlight(flightId: string): Promise { + const user = await this.prisma.user.findFirst({ + where: { currentFlightId: flightId }, + select: { id: true }, + }); + + if (user) { + await this.setCurrentFlight(user.id, null); + } + } + async setCurrentFlight( userId: string, flightId: string | null,