diff --git a/docker/mock/simbrief/xml.fetcher-123456-2.json b/docker/mock/simbrief/xml.fetcher-123456-2.json index f05d72ef..88aa71a2 100644 --- a/docker/mock/simbrief/xml.fetcher-123456-2.json +++ b/docker/mock/simbrief/xml.fetcher-123456-2.json @@ -309,7 +309,11 @@ "sched_out": "1767603600", "sched_off": "1767604800", "sched_on": "1767633000", - "sched_in": "1767633900" + "sched_in": "1767633900", + "est_out": "1767603900", + "est_off": "1767604980", + "est_on": "1767633240", + "est_in": "1767633960" }, "weights": { "cargo": "8004", diff --git a/features/_context/rest-api.context.ts b/features/_context/rest-api.context.ts index 7a49760c..a279e431 100644 --- a/features/_context/rest-api.context.ts +++ b/features/_context/rest-api.context.ts @@ -14,6 +14,7 @@ export type ApiUserType = | 'operations with Simbrief ID but non existing aircraft' | 'operations with Simbrief ID and alternate airport missing from database' | 'cabin crew' + | 'new cabin crew' | 'Alan Doe' | 'Michael Doe'; @@ -30,6 +31,10 @@ const apiUsers: Record = { email: 'cabin-crew@example.com', password: 'P@$$w0rd', }, + 'new cabin crew': { + email: 'nina.doe@example.com', + password: 'P@$$w0rd', + }, 'operations with valid Simbrief ID': { email: 'abby.doe@example.com', password: 'P@$$w0rd', diff --git a/features/flight/management/flight.create-with-simbrief.feature b/features/flight/management/flight.create-with-simbrief.feature index 43548083..ec534612 100644 --- a/features/flight/management/flight.create-with-simbrief.feature +++ b/features/flight/management/flight.create-with-simbrief.feature @@ -517,18 +517,141 @@ Feature: Create a flight with Simbrief """ And I set database to initial state - Scenario: As a cabin crew I cannot create a flight + Scenario: As a cabin crew without SimBrief connected I cannot import a flight Given I am signed in as "cabin crew" When I send a "POST" request to "/api/v1/flight/create-with-simbrief" - Then the response status should be 403 + Then the response status should be 400 And the response body should contain: """json { - "message": "Forbidden resource", - "error": "Forbidden", - "statusCode": 403 + "statusCode": 400, + "error": "Bad Request", + "message": "User has not connected SimBrief ID." + } + """ + + Scenario: As a cabin crew with SimBrief connected I import my flight and I am checked in with the estimated times of the plan + Given I am signed in as "admin" + When I send a "POST" request to "/api/v1/user" with body: + """json + { + "name": "Nina Doe", + "email": "nina.doe@example.com", + "password": "P@$$w0rd", + "role": "CabinCrew", + "pilotLicenseId": "UK-54321", + "homeAirportId": "3c721cc6-c653-4fad-be43-dc9d6a149383", + "simbriefUserId": "123456" + } + """ + Then the response status should be 201 + Given I am signed in with a new session as "new cabin crew" + When I send a "POST" request to "/api/v1/flight/create-with-simbrief" + Then the response status should be 201 + And the response body property "status" should contain: + """json + "checked_in" + """ + And the response body property "timesheet" should contain: + """json + { + "scheduled": { + "offBlockTime": "2026-01-05T09:00:00.000Z", + "takeoffTime": "2026-01-05T09:20:00.000Z", + "arrivalTime": "2026-01-05T17:10:00.000Z", + "onBlockTime": "2026-01-05T17:25:00.000Z" + }, + "estimated": { + "offBlockTime": "2026-01-05T09:05:00.000Z", + "takeoffTime": "2026-01-05T09:23:00.000Z", + "arrivalTime": "2026-01-05T17:14:00.000Z", + "onBlockTime": "2026-01-05T17:26:00.000Z" + } + } + """ + And the response body property "pilot" should contain: + """json + { + "id": "@uuid", + "name": "Nina Doe", + "pilotLicenseId": "UK-54321", + "totalFlightTime": 0 } """ + And I remember the response body property "id" as "flightId" + When I send a "GET" request to "/api/v1/flight/{{flightId}}/events" + Then the response status should be 200 + And the response body should contain: + """json + [ + { + "id": "@uuid", + "scope": "user", + "type": "flight.preliminary-loadsheet-updated", + "payload": {}, + "actor": { + "id": "@uuid", + "name": "Nina Doe" + }, + "createdAt": "@date('within 1 minute from now')" + }, + { + "id": "@uuid", + "scope": "user", + "type": "flight.released", + "payload": {}, + "actor": { + "id": "@uuid", + "name": "Nina Doe" + }, + "createdAt": "@date('within 1 minute from now')" + }, + { + "id": "@uuid", + "scope": "user", + "type": "flight.pilot-checked-in", + "payload": {}, + "actor": { + "id": "@uuid", + "name": "Nina Doe" + }, + "createdAt": "@date('within 1 minute from now')" + } + ] + """ + When I send a "PATCH" request to "/api/v1/flight/{{flightId}}/departure-parking-position" with body: + """json + { "departureParkingPositionId": "ad5a6ebd-dad8-4400-8bb4-b7cee3b00fa9" } + """ + Then the response status should be 200 + When I send a "GET" request to "/api/v1/user/me" + Then the response status should be 200 + And the response body property "currentFlightId" should contain: + """json + "@uuid" + """ + And I set database to initial state + + Scenario: As a cabin crew with a flight in progress I cannot import another flight + Given I am signed in as "cabin crew" + When I send a "PATCH" request to "/api/v1/user/me" with body: + """json + { + "simbriefUserId": "123456" + } + """ + Then the response status should be 200 + When I send a "POST" request to "/api/v1/flight/create-with-simbrief" + Then the response status should be 409 + And the response body should contain: + """json + { + "statusCode": 409, + "error": "Conflict", + "message": "A flight is already in progress. Close it before importing another plan." + } + """ + And I set database to initial state Scenario: As operations user importing a plan for an aircraft not in the fleet I create it unconfirmed Given I am signed in as "operations with Simbrief ID but non existing aircraft" diff --git a/features/flight/management/flight.update-departure-parking-position.feature b/features/flight/management/flight.update-departure-parking-position.feature index 67ea2e5c..03359b4f 100644 --- a/features/flight/management/flight.update-departure-parking-position.feature +++ b/features/flight/management/flight.update-departure-parking-position.feature @@ -309,33 +309,33 @@ Feature: Update flight departure parking position } """ - Scenario: As operations I cannot update departure parking position after pilot checked in + Scenario: As operations I cannot update departure parking position after boarding started Given I am signed in as "operations" - When I send a "PATCH" request to "/api/v1/flight/48760636-9520-4863-b32f-f3618556feb7/departure-parking-position" with body: + When I send a "PATCH" request to "/api/v1/flight/7e2b8d5c-a6f3-4049-98b1-d4f9a2e35b67/departure-parking-position" with body: """json - { "departureParkingPositionId": "ad5a6ebd-dad8-4400-8bb4-b7cee3b00fa9" } + { "departureParkingPositionId": "ae098e8f-b088-41a6-a566-880c7dd5e931" } """ Then the response status should be 422 And the response body should contain: """json { - "message": "Cannot update departure parking position, because pilot is already checked in.", + "message": "Cannot update departure parking position, because boarding has started.", "error": "Unprocessable Content", "statusCode": 422 } """ - Scenario: As cabin crew I cannot update departure parking position after pilot checked in + Scenario: As cabin crew I cannot update departure parking position after boarding started Given I am signed in as "cabin crew" - When I send a "PATCH" request to "/api/v1/flight/48760636-9520-4863-b32f-f3618556feb7/departure-parking-position" with body: + When I send a "PATCH" request to "/api/v1/flight/7e2b8d5c-a6f3-4049-98b1-d4f9a2e35b67/departure-parking-position" with body: """json - { "departureParkingPositionId": "ad5a6ebd-dad8-4400-8bb4-b7cee3b00fa9" } + { "departureParkingPositionId": "ae098e8f-b088-41a6-a566-880c7dd5e931" } """ Then the response status should be 422 And the response body should contain: """json { - "message": "Cannot update departure parking position, because pilot is already checked in.", + "message": "Cannot update departure parking position, because boarding has started.", "error": "Unprocessable Content", "statusCode": 422 } diff --git a/package-lock.json b/package-lock.json index a137c373..6ff147a2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "flight-tracker-api", - "version": "3.88.0", + "version": "3.89.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "flight-tracker-api", - "version": "3.88.0", + "version": "3.89.0", "license": "Unlicense", "dependencies": { "@faker-js/faker": "^10.6.0", diff --git a/package.json b/package.json index fdda0771..561c8d97 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flight-tracker-api", - "version": "3.88.0", + "version": "3.89.0", "private": true, "homepage": "https://mypreflight.io", "author": "mypreflight", diff --git a/src/core/provider/simbrief/type/simbrief.types.ts b/src/core/provider/simbrief/type/simbrief.types.ts index 54629681..e59be04e 100644 --- a/src/core/provider/simbrief/type/simbrief.types.ts +++ b/src/core/provider/simbrief/type/simbrief.types.ts @@ -216,6 +216,10 @@ export type Times = { sched_off: string; sched_on: string; sched_in: string; + est_out?: string | EmptyElement; + est_off?: string | EmptyElement; + est_on?: string | EmptyElement; + est_in?: string | EmptyElement; }; export type Fuel = { diff --git a/src/modules/flights/application/command/create-flight-from-simbrief.command.spec.ts b/src/modules/flights/application/command/create-flight-from-simbrief.command.spec.ts index 3419fa98..508582d9 100644 --- a/src/modules/flights/application/command/create-flight-from-simbrief.command.spec.ts +++ b/src/modules/flights/application/command/create-flight-from-simbrief.command.spec.ts @@ -1,5 +1,6 @@ import { AlternateAirportCandidate, + CreateFlightFromSimbriefCommand, CreateFlightFromSimbriefHandler, } from './create-flight-from-simbrief.command'; import { AirportType } from '../../../airports/model/airport.model'; @@ -7,7 +8,11 @@ import { FlightServiceType } from '../../model/flight.model'; import { Crew, OperationalFlightPlan, + Times, } from '../../../../core/provider/simbrief/type/simbrief.types'; +import { Schedule } from '../../model/timesheet.model'; +import { PilotHasFlightInProgressError } from '../../model/error/flight.error'; +import { GetUserSimbriefIdQuery } from '../../../users/application/query/get-user-simbrief-id.query'; import { CrewMember } from '../../../crew/application/command/assign-crew-to-flight.command'; import { CrewRole } from '../../../crew/model/crew.model'; @@ -287,3 +292,95 @@ describe('CreateFlightFromSimbriefHandler weight import', () => { expect(massOf(ofpWithWeights('8004', '8004', '120'))).toBeNull(); }); }); + +describe('CreateFlightFromSimbriefHandler estimated times', () => { + let handler: CreateFlightFromSimbriefHandler; + + function estimate(times: Partial): Schedule { + return ( + handler as unknown as { + estimatedSchedule: (ofp: OperationalFlightPlan) => Schedule; + } + ).estimatedSchedule({ + times: { + sched_out: '1767603600', + sched_off: '1767604800', + sched_on: '1767633000', + sched_in: '1767633900', + ...times, + }, + } as OperationalFlightPlan); + } + + beforeEach(() => { + handler = buildHandler(); + }); + + it('takes the estimated times of the plan', () => { + expect( + estimate({ + est_out: '1767603900', + est_off: '1767604980', + est_on: '1767633240', + est_in: '1767633960', + }), + ).toEqual({ + offBlockTime: new Date('2026-01-05T09:05:00.000Z'), + takeoffTime: new Date('2026-01-05T09:23:00.000Z'), + arrivalTime: new Date('2026-01-05T17:14:00.000Z'), + onBlockTime: new Date('2026-01-05T17:26:00.000Z'), + }); + }); + + it('falls back to the scheduled time where the plan has no estimate', () => { + expect(estimate({ est_off: '1767604980', est_on: {} })).toEqual({ + offBlockTime: new Date('2026-01-05T09:00:00.000Z'), + takeoffTime: new Date('2026-01-05T09:23:00.000Z'), + arrivalTime: new Date('2026-01-05T17:10:00.000Z'), + onBlockTime: new Date('2026-01-05T17:25:00.000Z'), + }); + }); +}); + +describe('CreateFlightFromSimbriefHandler pilot import', () => { + const getOperationalFlightPlan = jest.fn(); + + function buildPilotHandler( + currentFlightId: string | null, + ): CreateFlightFromSimbriefHandler { + const queryBus = { + execute: jest.fn((query: unknown) => + Promise.resolve( + query instanceof GetUserSimbriefIdQuery + ? '123456' + : { currentFlightId }, + ), + ), + }; + + return new CreateFlightFromSimbriefHandler( + queryBus as never, + undefined as never, + { getOperationalFlightPlan } as never, + undefined as never, + undefined as never, + undefined as never, + undefined as never, + ); + } + + beforeEach(() => { + getOperationalFlightPlan.mockReset(); + }); + + it('refuses a pilot with a flight in progress before fetching the plan', async () => { + const handler = buildPilotHandler('23952e79-6b38-49ed-a1db-bd4d9b3cedab'); + + await expect( + handler.execute( + new CreateFlightFromSimbriefCommand('flight-id', 'pilot-id', true), + ), + ).rejects.toBeInstanceOf(PilotHasFlightInProgressError); + expect(getOperationalFlightPlan).not.toHaveBeenCalled(); + }); +}); diff --git a/src/modules/flights/application/command/create-flight-from-simbrief.command.ts b/src/modules/flights/application/command/create-flight-from-simbrief.command.ts index e2faed40..5c464254 100644 --- a/src/modules/flights/application/command/create-flight-from-simbrief.command.ts +++ b/src/modules/flights/application/command/create-flight-from-simbrief.command.ts @@ -5,6 +5,7 @@ import { QueryBus, } from '@nestjs/cqrs'; import { + PilotHasFlightInProgressError, SimbriefIdNotConnectedError, SimbriefPlanWithoutAircraftError, } from '../../model/error/flight.error'; @@ -16,6 +17,7 @@ import { import { FlightEventScope } from '../../model/event.model'; import { DomainEventEmitter } from '../../../../core/domain/events/domain-event-emitter'; import { GetUserSimbriefIdQuery } from '../../../users/application/query/get-user-simbrief-id.query'; +import { GetUserByIdQuery } from '../../../users/application/query/get-user-by-id.query'; import { SimbriefClient } from '../../../../core/provider/simbrief/client/simbrief.client'; import { ImportAirportByIcaoCommand } from '../../../airports/application/command/import-airport-by-icao.command'; import { ImportAircraftByRegistrationCommand } from '../../../aircraft/application/command/import-aircraft-by-registration.command'; @@ -65,6 +67,9 @@ import { WaypointsRepository } from '../../../waypoints/infra/database/waypoints import { GetSeatCapacityQuery } from '../../../manifest/application/query/get-seat-capacity.query'; import { CabinCapacity } from '../../../cabin-layouts/model/cabin-capacity.model'; import { capPassengersAtSeatCapacity } from '../../model/loadsheet.policy'; +import { Schedule } from '../../model/timesheet.model'; +import { MarkAsReadyCommand } from './mark-as-ready.command'; +import { CheckInPilotCommand } from './check-in-pilot.command'; export type AlternateAirportCandidate = { icaoCode: string; @@ -84,6 +89,7 @@ export class CreateFlightFromSimbriefCommand { constructor( public readonly flightId: string, public readonly initiatorId: string, + public readonly checkInInitiator: boolean, ) {} } @@ -100,7 +106,10 @@ export class CreateFlightFromSimbriefHandler implements ICommandHandler { - const { flightId, initiatorId } = command; + const { flightId, initiatorId, checkInInitiator } = command; + const scope = checkInInitiator + ? FlightEventScope.User + : FlightEventScope.Operations; const getSimbriefIdQuery = new GetUserSimbriefIdQuery(initiatorId); const simbriefId = await this.queryBus.execute(getSimbriefIdQuery); @@ -109,6 +118,10 @@ export class CreateFlightFromSimbriefHandler implements ICommandHandler { + const pilot = await this.queryBus.execute(new GetUserByIdQuery(pilotId)); + + if (pilot.currentFlightId !== null) { + throw new PilotHasFlightInProgressError(); + } + } + + private estimatedSchedule(ofp: OperationalFlightPlan): Schedule { + const { times } = ofp; + const estimateOr = ( + estimated: string | EmptyElement | undefined, + scheduled: string, + ): Date => this.ofpTimeToDate(this.readOfpText(estimated) || scheduled); + + return { + offBlockTime: estimateOr(times.est_out, times.sched_out), + takeoffTime: estimateOr(times.est_off, times.sched_off), + arrivalTime: estimateOr(times.est_on, times.sched_on), + onBlockTime: estimateOr(times.est_in, times.sched_in), + }; } private collectAirportNotams(ofp: OperationalFlightPlan): AirportNotams[] { diff --git a/src/modules/flights/infra/http/action/flight/create-flight-from-simbrief.action.ts b/src/modules/flights/infra/http/action/flight/create-flight-from-simbrief.action.ts index fdd3bcbe..452bcb3c 100644 --- a/src/modules/flights/infra/http/action/flight/create-flight-from-simbrief.action.ts +++ b/src/modules/flights/infra/http/action/flight/create-flight-from-simbrief.action.ts @@ -40,9 +40,10 @@ export class CreateFlightFromSimbriefAction { @ApiOperation({ summary: 'Create a flight with SimBrief data', description: - '**NOTE:** This endpoint is only available for users with the ` operations ` role.
' + + '**NOTE:** This endpoint is only available for users with the ` operations ` or ` cabin crew ` role.
' + '**NOTE:** Simbrief ID must be provided for the user, otherwise import will throw HTTP 400.
' + - '**NOTE:** An aircraft registration not yet in the fleet is created for the flight operator and marked unconfirmed until operations confirm it.', + '**NOTE:** An aircraft registration not yet in the fleet is created for the flight operator and marked unconfirmed until operations confirm it.
' + + '**NOTE:** A flight imported by operations stays in created status. A flight imported by cabin crew is marked ready and the pilot is checked in with the estimated times of the plan, so a pilot with a flight in progress cannot import another.', }) @ApiBearerAuth('jwt') @ApiBody({ type: CreateFlightRequest }) @@ -57,20 +58,21 @@ export class CreateFlightFromSimbriefAction { }) @ApiConflictResponse({ description: - 'The aircraft is in the fleet with a different type than the plan uses', + 'The aircraft is in the fleet with a different type than the plan uses, or the importing pilot has a flight in progress', type: GenericConflictResponse, }) @ApiUnprocessableEntityResponse({ description: 'The plan does not name the aircraft registration and type', }) @Post('/create-with-simbrief') - @Role(UserRole.Operations) + @Role(UserRole.Operations, UserRole.CabinCrew) async run(@Req() request: AuthorizedRequest): Promise { const flightId = v4(); const command = new CreateFlightFromSimbriefCommand( flightId, request.user.sub, + request.user.role === UserRole.CabinCrew.toLowerCase(), ); await this.commandBus.execute(command); diff --git a/src/modules/flights/infra/http/action/parking-position/update-departure-parking-position.action.ts b/src/modules/flights/infra/http/action/parking-position/update-departure-parking-position.action.ts index a28cc983..8eedf2b9 100644 --- a/src/modules/flights/infra/http/action/parking-position/update-departure-parking-position.action.ts +++ b/src/modules/flights/infra/http/action/parking-position/update-departure-parking-position.action.ts @@ -41,7 +41,7 @@ export class UpdateDepartureParkingPositionAction { summary: 'Update flight departure parking position', description: 'Assigns the departure parking position to a flight.
' + - '**NOTE:** This action is only allowed while the flight is in `created` or `ready` status (before the pilot has checked in).
' + + '**NOTE:** This action is only allowed while the flight is in `created`, `ready` or `checked_in` status (before boarding starts).
' + '**NOTE:** This endpoint is available for `operations` and `cabin crew` roles.', }) @ApiBearerAuth('jwt') diff --git a/src/modules/flights/model/error/flight.error.ts b/src/modules/flights/model/error/flight.error.ts index e1e912fb..03c9844f 100644 --- a/src/modules/flights/model/error/flight.error.ts +++ b/src/modules/flights/model/error/flight.error.ts @@ -33,7 +33,7 @@ export class FlightOfpNotFoundError extends NotFoundError { export class InvalidStatusToUpdateDepartureParkingPositionError extends UnprocessableError { constructor() { super( - 'Cannot update departure parking position, because pilot is already checked in.', + 'Cannot update departure parking position, because boarding has started.', ); } } @@ -184,6 +184,14 @@ export class SimbriefPlanWithoutAircraftError extends UnprocessableError { } } +export class PilotHasFlightInProgressError extends ConflictError { + constructor() { + super( + 'A flight is already in progress. Close it before importing another plan.', + ); + } +} + export class InvalidStatusToMarkAsReadyError extends UnprocessableError { constructor() { super('Cannot mark flight as ready. Flight is not in created status.'); diff --git a/src/modules/flights/model/flight.spec.ts b/src/modules/flights/model/flight.spec.ts index f6c0ef71..cab24cf5 100644 --- a/src/modules/flights/model/flight.spec.ts +++ b/src/modules/flights/model/flight.spec.ts @@ -491,7 +491,7 @@ describe('Flight', () => { describe.each([ { name: 'changeDepartureParkingPosition', - firstForbidden: FlightStatus.CheckedIn, + firstForbidden: FlightStatus.BoardingStarted, act: (flight: Flight) => flight.changeDepartureParkingPosition(ACTOR, 'stand-1'), field: 'departureParkingPositionId', diff --git a/src/modules/flights/model/flight.ts b/src/modules/flights/model/flight.ts index 9627eef7..3a71177e 100644 --- a/src/modules/flights/model/flight.ts +++ b/src/modules/flights/model/flight.ts @@ -463,7 +463,7 @@ export class Flight extends AggregateRoot { parkingPositionId: string, ): void { this.expectBefore( - FlightStatus.CheckedIn, + FlightStatus.BoardingStarted, InvalidStatusToUpdateDepartureParkingPositionError, );