diff --git a/features/flight/management/flight.list.feature b/features/flight/management/flight.list.feature index 02e5a669..d68ab10c 100644 --- a/features/flight/management/flight.list.feature +++ b/features/flight/management/flight.list.feature @@ -74,6 +74,58 @@ Feature: Get flights list Then the response status should be 200 And the response header "X-Total-Count" should be "16" + Scenario: As a cabin crew I can list only the flights I captained + Given I am signed in as "cabin crew" + When I send a "GET" request to "/api/v1/flight?phase=finished&captain=me&sort=actualOnBlockTime&order=desc" + Then the response status should be 200 + And the response header "X-Total-Count" should be "3" + And the response body property "0.flightNumber" should contain: + """json + "LH40" + """ + And the response body property "2.flightNumber" should contain: + """json + "AA4905" + """ + + Scenario: As a cabin crew who hasn't finished a flight yet I list none of my own + Given I am signed in as "Alan Doe" + When I send a "GET" request to "/api/v1/flight?phase=finished&captain=me" + Then the response status should be 200 + And the response header "X-Total-Count" should be "0" + And the response body should contain: + """json + [] + """ + + Scenario: As an unauthorized user I cannot list my own flights + When I send a "GET" request to "/api/v1/flight?captain=me" + Then the response status should be 401 + And the response body should contain: + """json + { + "statusCode": 401, + "error": "Unauthorized", + "message": "Sign in to list your own flights." + } + """ + + Scenario: As cabin crew I cannot list the flights of another captain + Given I am signed in as "cabin crew" + When I send a "GET" request to "/api/v1/flight?captain=someone" + Then the response status should be 400 + And the response body should contain: + """json + { + "statusCode": 400, + "message": "Request validation failed.", + "error": "Bad Request", + "violations": { + "captain": ["captain must be one of the following values: me"] + } + } + """ + Scenario: As cabin crew I can list upcoming flights by scheduled off-block, earliest first Given I am signed in as "cabin crew" When I send a "GET" request to "/api/v1/flight?phase=upcoming&sort=scheduledOffBlockTime&order=asc&limit=5" diff --git a/features/user/simbrief/simbrief.verify.feature b/features/user/simbrief/simbrief.verify.feature index 49633a59..f1af8717 100644 --- a/features/user/simbrief/simbrief.verify.feature +++ b/features/user/simbrief/simbrief.verify.feature @@ -13,11 +13,13 @@ Feature: Verify a Simbrief user ID "origin": { "icaoCode": "EDDF", "iataCode": "FRA", + "city": "Frankfurt", "name": "FRANKFURT INTL" }, "destination": { "icaoCode": "EPWA", "iataCode": "WAW", + "city": "Warsaw", "name": "WARSAW CHOPIN" }, "aircraft": { @@ -45,11 +47,13 @@ Feature: Verify a Simbrief user ID "origin": { "icaoCode": "EDDF", "iataCode": "FRA", + "city": "Frankfurt", "name": "FRANKFURT INTL" }, "destination": { "icaoCode": "EPWA", "iataCode": "WAW", + "city": "Warsaw", "name": "WARSAW CHOPIN" }, "aircraft": { diff --git a/package-lock.json b/package-lock.json index 6ff147a2..0c1d8eed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "flight-tracker-api", - "version": "3.89.0", + "version": "3.90.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "flight-tracker-api", - "version": "3.89.0", + "version": "3.90.0", "license": "Unlicense", "dependencies": { "@faker-js/faker": "^10.6.0", diff --git a/package.json b/package.json index 561c8d97..31a67e73 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flight-tracker-api", - "version": "3.89.0", + "version": "3.90.0", "private": true, "homepage": "https://mypreflight.io", "author": "mypreflight", diff --git a/src/modules/flights/application/query/list-all-flights.query.ts b/src/modules/flights/application/query/list-all-flights.query.ts index 38f6755e..29ed33fb 100644 --- a/src/modules/flights/application/query/list-all-flights.query.ts +++ b/src/modules/flights/application/query/list-all-flights.query.ts @@ -31,6 +31,7 @@ export class ListAllFlightsQuery extends Query { constructor( public readonly onlyPublic: boolean, public readonly filters?: FlightListFilters, + public readonly captainId: string | null = null, ) { super(); } @@ -47,6 +48,7 @@ export class ListAllFlightsHandler implements IQueryHandler const { flights, totalCount } = await this.repository.findAll( query.filters, query.onlyPublic, + query.captainId, ); const [pilotsById, flightsWithNotoc] = await Promise.all([ diff --git a/src/modules/flights/infra/database/repository/flights.repository.ts b/src/modules/flights/infra/database/repository/flights.repository.ts index e6d11273..30429c02 100644 --- a/src/modules/flights/infra/database/repository/flights.repository.ts +++ b/src/modules/flights/infra/database/repository/flights.repository.ts @@ -565,9 +565,14 @@ export class FlightsRepository { async findAll( filters?: FlightListFilters, onlyPublic?: boolean, + captainId?: string | null, ): Promise { const where: Prisma.FlightWhereInput = {}; + if (captainId) { + where.captainId = captainId; + } + if (filters?.phase === FlightPhase.Upcoming) { where.status = { in: [FlightStatus.Created, FlightStatus.Ready], diff --git a/src/modules/flights/infra/http/action/flight/list-flights.action.ts b/src/modules/flights/infra/http/action/flight/list-flights.action.ts index 46168c5c..0f4d3a7c 100644 --- a/src/modules/flights/infra/http/action/flight/list-flights.action.ts +++ b/src/modules/flights/infra/http/action/flight/list-flights.action.ts @@ -14,11 +14,13 @@ import { UnauthorizedResponse } from '../../../../../../core/http/response/unaut import { SkipAuth } from '../../../../../../core/http/auth/decorator/skip-auth.decorator'; import { AuthorizedRequest } from '../../../../../../core/http/request/authorized.request'; import { + FlightListCaptain, FlightListOrder, FlightListSort, FlightPhase, } from '../../../../model/flight.model'; import { ListAllFlightsQuery } from '../../../../application/query/list-all-flights.query'; +import { OwnFlightsRequireSignInError } from '../../../../model/error/flight.error'; @ApiTags('flight') @Controller('api/v1/flight') @@ -59,6 +61,14 @@ export class ListFlightsAction { default: FlightListSort.CreatedAt, required: false, }) + @ApiQuery({ + name: 'captain', + description: + 'Only the flights the signed-in user captained, that is checked in to. Requires signing in.', + type: 'string', + enum: FlightListCaptain, + required: false, + }) @ApiQuery({ name: 'order', description: 'Direction of the ordering', @@ -87,7 +97,14 @@ export class ListFlightsAction { @Res() response: Response, ): Promise { const onlyPublic = !request.user; - const query = new ListAllFlightsQuery(onlyPublic, filters); + + if (filters.captain === FlightListCaptain.Me && !request.user) { + throw new OwnFlightsRequireSignInError(); + } + + const captainId = + filters.captain === FlightListCaptain.Me ? request.user.sub : null; + const query = new ListAllFlightsQuery(onlyPublic, filters, captainId); const { flights, totalCount } = await this.queryBus.execute(query); response.setHeader('X-Total-Count', totalCount.toString()); diff --git a/src/modules/flights/infra/http/request/flight.dto.ts b/src/modules/flights/infra/http/request/flight.dto.ts index 34dee15c..f363f1a2 100644 --- a/src/modules/flights/infra/http/request/flight.dto.ts +++ b/src/modules/flights/infra/http/request/flight.dto.ts @@ -28,6 +28,7 @@ import { import { Loadsheet } from '../../../model/loadsheet.model'; import { Type } from 'class-transformer'; import { + FlightListCaptain, FlightListOrder, FlightListSort, FlightPhase, @@ -401,6 +402,10 @@ export class FlightListFilters { @IsOptional() @IsEnum(FlightListOrder) order: FlightListOrder = FlightListOrder.Descending; + + @IsOptional() + @IsEnum(FlightListCaptain) + captain?: FlightListCaptain; } export class UpdateFlightVisibilityRequest extends PickType(FlightDto, [ diff --git a/src/modules/flights/model/error/flight.error.ts b/src/modules/flights/model/error/flight.error.ts index 03c9844f..be763b76 100644 --- a/src/modules/flights/model/error/flight.error.ts +++ b/src/modules/flights/model/error/flight.error.ts @@ -3,9 +3,16 @@ import { ConflictError, ForbiddenError, NotFoundError, + UnauthorizedError, UnprocessableError, } from '../../../../core/errors/domain-error'; +export class OwnFlightsRequireSignInError extends UnauthorizedError { + constructor() { + super('Sign in to list your own flights.'); + } +} + export class FlightNotFoundError extends NotFoundError { constructor() { super('Flight with given ID not found.'); diff --git a/src/modules/flights/model/flight.model.ts b/src/modules/flights/model/flight.model.ts index 3ef8692e..6e62284f 100644 --- a/src/modules/flights/model/flight.model.ts +++ b/src/modules/flights/model/flight.model.ts @@ -33,6 +33,10 @@ export enum FlightListOrder { Descending = 'desc', } +export enum FlightListCaptain { + Me = 'me', +} + export enum FlightSource { Manual = 'manual', Simbrief = 'simbrief', diff --git a/src/modules/users/application/query/verify-simbrief-user.query.spec.ts b/src/modules/users/application/query/verify-simbrief-user.query.spec.ts index dc863721..30547720 100644 --- a/src/modules/users/application/query/verify-simbrief-user.query.spec.ts +++ b/src/modules/users/application/query/verify-simbrief-user.query.spec.ts @@ -5,6 +5,9 @@ import { import { SimbriefClient } from '../../../../core/provider/simbrief/client/simbrief.client'; import { SimbriefUserNotFoundError } from '../../../../core/provider/simbrief/error/simbrief.error'; import { OperationalFlightPlan } from '../../../../core/provider/simbrief/type/simbrief.types'; +import { GetAirportByIcaoCodeQuery } from '../../../airports/application/query/get-airport-by-icao-code.query'; +import { AirportByIcaoCodeNotFoundError } from '../../../airports/model/error/airport.error'; +import { QueryBus } from '@nestjs/cqrs'; const ofp = { fetch: { userid: '987654', status: 'Success' }, @@ -16,14 +19,29 @@ const ofp = { times: { sched_out: '1786891620', sched_in: '1786898820' }, } as OperationalFlightPlan; +type KnownAirports = Record; + function handlerReturning( plan: OperationalFlightPlan | null, + knownAirports: KnownAirports = {}, ): VerifySimbriefUserHandler { const client = { findOperationalFlightPlan: () => Promise.resolve(plan), } as unknown as SimbriefClient; + const queryBus = { + execute: (query: GetAirportByIcaoCodeQuery) => { + const known = knownAirports[query.icaoCode]; + + return known + ? Promise.resolve({ + iataCode: known.iataCode, + city: { name: known.city }, + }) + : Promise.reject(new AirportByIcaoCodeNotFoundError()); + }, + } as unknown as QueryBus; - return new VerifySimbriefUserHandler(client); + return new VerifySimbriefUserHandler(client, queryBus); } describe('VerifySimbriefUserHandler', () => { @@ -39,11 +57,13 @@ describe('VerifySimbriefUserHandler', () => { origin: { icaoCode: 'EDDF', iataCode: 'FRA', + city: null, name: 'FRANKFURT INTL', }, destination: { icaoCode: 'EPWA', iataCode: 'WAW', + city: null, name: 'WARSAW CHOPIN', }, aircraft: { @@ -74,8 +94,8 @@ describe('VerifySimbriefUserHandler', () => { expect(account.latestFlight).toEqual({ callsign: 'DLH0400', - origin: { icaoCode: 'EDDF', iataCode: null, name: null }, - destination: { icaoCode: 'EPWA', iataCode: null, name: null }, + origin: { icaoCode: 'EDDF', iataCode: null, city: null, name: null }, + destination: { icaoCode: 'EPWA', iataCode: null, city: null, name: null }, aircraft: { registration: 'D-AIRC', type: null, name: null }, scheduledOffBlockTime: null, scheduledOnBlockTime: null, @@ -83,6 +103,38 @@ describe('VerifySimbriefUserHandler', () => { }); }); + it('takes the IATA code and city of an airport MyPreflight knows', async () => { + const sparse = { + params: {}, + general: { icao_airline: 'DLH', flight_number: '0400' }, + origin: { icao_code: 'EDDF', iata_code: {}, name: {} }, + destination: { + icao_code: 'EPWA', + iata_code: 'WAW', + name: 'WARSAW CHOPIN', + }, + aircraft: { reg: 'D-AIRC' }, + times: {}, + } as unknown as OperationalFlightPlan; + + const account = await handlerReturning(sparse, { + EDDF: { iataCode: 'FRA', city: 'Frankfurt' }, + }).execute(new VerifySimbriefUserQuery('987654')); + + expect(account.latestFlight.origin).toEqual({ + icaoCode: 'EDDF', + iataCode: 'FRA', + city: 'Frankfurt', + name: null, + }); + expect(account.latestFlight.destination).toEqual({ + icaoCode: 'EPWA', + iataCode: 'WAW', + city: null, + name: 'WARSAW CHOPIN', + }); + }); + it('rejects a user ID Simbrief does not know', async () => { await expect( handlerReturning(null).execute(new VerifySimbriefUserQuery('999999')), diff --git a/src/modules/users/application/query/verify-simbrief-user.query.ts b/src/modules/users/application/query/verify-simbrief-user.query.ts index f5686aa0..582f911a 100644 --- a/src/modules/users/application/query/verify-simbrief-user.query.ts +++ b/src/modules/users/application/query/verify-simbrief-user.query.ts @@ -1,4 +1,4 @@ -import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs'; +import { IQueryHandler, Query, QueryBus, QueryHandler } from '@nestjs/cqrs'; import { SimbriefClient } from '../../../../core/provider/simbrief/client/simbrief.client'; import { SimbriefUserNotFoundError } from '../../../../core/provider/simbrief/error/simbrief.error'; import { @@ -11,6 +11,10 @@ import { SimbriefAirport, SimbriefFlight, } from '../../model/simbrief-account.model'; +import { GetAirportByIcaoCodeQuery } from '../../../airports/application/query/get-airport-by-icao-code.query'; +import { AirportByIcaoCodeNotFoundError } from '../../../airports/model/error/airport.error'; + +type KnownAirport = { iataCode: string; city: string }; export class VerifySimbriefUserQuery extends Query { constructor(public readonly simbriefUserId: string) { @@ -20,7 +24,10 @@ export class VerifySimbriefUserQuery extends Query { @QueryHandler(VerifySimbriefUserQuery) export class VerifySimbriefUserHandler implements IQueryHandler { - constructor(private readonly simbriefClient: SimbriefClient) {} + constructor( + private readonly simbriefClient: SimbriefClient, + private readonly queryBus: QueryBus, + ) {} async execute(query: VerifySimbriefUserQuery): Promise { const ofp = await this.simbriefClient.findOperationalFlightPlan( @@ -33,15 +40,20 @@ export class VerifySimbriefUserHandler implements IQueryHandler { + const [origin, destination] = await Promise.all([ + this.toAirport(ofp.origin), + this.toAirport(ofp.destination), + ]); + return { callsign: `${ofp.general.icao_airline ?? ''}${ofp.general.flight_number ?? ''}`, - origin: this.toAirport(ofp.origin), - destination: this.toAirport(ofp.destination), + origin, + destination, aircraft: this.toAircraft(ofp.aircraft), scheduledOffBlockTime: this.toDate(ofp.times?.sched_out), scheduledOnBlockTime: this.toDate(ofp.times?.sched_in), @@ -49,14 +61,37 @@ export class VerifySimbriefUserHandler implements IQueryHandler { + const known = await this.findKnownAirport(airport.icao_code); + return { icaoCode: airport.icao_code, - iataCode: this.readText(airport.iata_code), + iataCode: known?.iataCode ?? this.readText(airport.iata_code), + city: known?.city ?? null, name: this.readText(airport.name), }; } + private async findKnownAirport( + icaoCode: string, + ): Promise { + try { + const airport = await this.queryBus.execute( + new GetAirportByIcaoCodeQuery(icaoCode), + ); + + return { iataCode: airport.iataCode, city: airport.city.name }; + } catch (error) { + if (error instanceof AirportByIcaoCodeNotFoundError) { + return null; + } + + throw error; + } + } + private toAircraft( aircraft: OperationalFlightPlan['aircraft'], ): SimbriefAircraft { diff --git a/src/modules/users/model/simbrief-account.model.ts b/src/modules/users/model/simbrief-account.model.ts index b13368ca..101f419a 100644 --- a/src/modules/users/model/simbrief-account.model.ts +++ b/src/modules/users/model/simbrief-account.model.ts @@ -8,13 +8,23 @@ export class SimbriefAirport { icaoCode!: string; @ApiProperty({ - description: 'IATA code of the airport', + description: + "IATA code of the airport, MyPreflight's own when the airport is known, otherwise as SimBrief reports it", example: 'LHR', type: 'string', nullable: true, }) iataCode!: string | null; + @ApiProperty({ + description: + 'City the airport serves, when MyPreflight already knows the airport', + example: 'London', + type: 'string', + nullable: true, + }) + city!: string | null; + @ApiProperty({ description: 'Airport name as SimBrief reports it', example: 'HEATHROW',