From 721c2d3b4e2db46026eee2ce8270a5234784481e Mon Sep 17 00:00:00 2001 From: Oskar Barcz Date: Tue, 17 Nov 2026 17:12:09 +0100 Subject: [PATCH 1/2] Give every seeded user an ATIS source The user's defaultAtisSource is required on the Prisma type, but the seeded users never set it. The seed runs untyped in CI, so nothing failed there, but the dev server type-checks it and would not start. Each user gets say_intentions, the column's default. --- prisma/seed/resource/users.seed.ts | 10 ++++ .../get-aircraft-by-registration.query.ts | 50 ------------------- 2 files changed, 10 insertions(+), 50 deletions(-) delete mode 100644 src/modules/aircraft/application/query/get-aircraft-by-registration.query.ts diff --git a/prisma/seed/resource/users.seed.ts b/prisma/seed/resource/users.seed.ts index ff9b1a4f..f46de6ee 100644 --- a/prisma/seed/resource/users.seed.ts +++ b/prisma/seed/resource/users.seed.ts @@ -40,6 +40,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -71,6 +72,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.SayIntentions, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -102,6 +104,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -133,6 +136,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -166,6 +170,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: '3c721cc6-c653-4fad-be43-dc9d6a149383', // KJFK lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -200,6 +205,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: 'f35c094a-bec5-4803-be32-bd80a14b441a', // EDDF lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -234,6 +240,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: '616cbdd7-ccfc-4687-8cf6-1e7236435046', // EPWA lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -265,6 +272,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -297,6 +305,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, @@ -328,6 +337,7 @@ export async function loadUsers(tx: Prisma.TransactionClient): Promise { lastAirportId: null, lastAirportUpdatedAt: null, defaultWeatherSource: WeatherSource.AviationWeatherGov, + defaultAtisSource: WeatherSource.SayIntentions, discordBriefingsEnabled: true, discordPreliminaryLoadsheetEnabled: true, discordFinalLoadsheetEnabled: true, diff --git a/src/modules/aircraft/application/query/get-aircraft-by-registration.query.ts b/src/modules/aircraft/application/query/get-aircraft-by-registration.query.ts deleted file mode 100644 index 43616008..00000000 --- a/src/modules/aircraft/application/query/get-aircraft-by-registration.query.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Query, QueryHandler, IQueryHandler } from '@nestjs/cqrs'; -import { AircraftRepository } from '../../infra/database/repository/aircraft.repository'; -import { LegacyCreateAircraftResponse } from '../../infra/http/request/aircraft.request'; -import { AircraftWithRegistrationNotFoundError } from '../../model/error/aircraft.error'; -import { findAirframeByType } from '../../../airframes/data/airframes'; -import { toAircraftCabinLayout } from '../../model/cabin-layout-assignment'; -import { AirframeNotFoundError } from '../../../airframes/model/error/airframe.error'; - -export class GetAircraftByRegistrationQuery extends Query { - constructor(public readonly registration: string) { - super(); - } -} - -@QueryHandler(GetAircraftByRegistrationQuery) -export class GetAircraftByRegistrationHandler implements IQueryHandler { - constructor(private readonly repository: AircraftRepository) {} - - async execute( - query: GetAircraftByRegistrationQuery, - ): Promise { - const aircraft = await this.repository.findWithOperatorBy({ - registration: query.registration, - }); - - if (!aircraft) { - throw new AircraftWithRegistrationNotFoundError(); - } - - const airframe = findAirframeByType(aircraft.type); - - if (!airframe) { - throw new AirframeNotFoundError(); - } - - return { - id: aircraft.id, - airframe, - registration: aircraft.registration, - selcal: aircraft.selcal, - livery: aircraft.livery, - operator: aircraft.operator, - cabinLayout: toAircraftCabinLayout( - aircraft.layout, - aircraft.operator?.iataCode ?? null, - airframe.iataType, - ), - }; - } -} From c541e844c375e739e509e2a5d0b0d222c3955587 Mon Sep 17 00:00:00 2001 From: Oskar Barcz Date: Tue, 17 Nov 2026 17:12:09 +0100 Subject: [PATCH 2/2] Add unknown aircraft from a SimBrief import, unconfirmed until operations confirm them An imported plan whose registration isn't in the fleet now creates the aircraft for the plan's operator with the plan's ICAO type and the operator's default livery, marked unconfirmed, instead of failing with 404. A plan that flies a fleet registration as another type is refused with 409, and a plan without a registration or type with 422. Aircraft gain isConfirmed (default true, so existing and manually created aircraft stay confirmed). Every aircraft read model returns it and the aircraft PATCH accepts it, which is how operations confirm an aircraft. --- .../mock/simbrief/xml.fetcher-111222-2.json | 3 +- .../mock/simbrief/xml.fetcher-123456-2.json | 3 +- .../mock/simbrief/xml.fetcher-333444-2.json | 3 +- .../mock/simbrief/xml.fetcher-654321-2.json | 18 +++- features/aircraft/aircraft.create.feature | 4 + features/aircraft/aircraft.get.feature | 4 + features/aircraft/aircraft.list.feature | 8 ++ features/aircraft/aircraft.update.feature | 69 ++++++++++++++ features/aircraft/cabin-layout.assign.feature | 6 ++ features/aircraft/hold-variant.assign.feature | 3 + .../reposition/reposition.create.feature | 1 + .../actions/flight.check-in-pilot.feature | 1 + features/flight/actions/flight.close.feature | 1 + .../actions/flight.report-off-block.feature | 1 + .../actions/flight.report-on-block.feature | 1 + .../flight.create-with-simbrief.feature | 83 +++++++++++++++-- .../flight/management/flight.create.feature | 2 + openspec/specs/aircraft-management/spec.md | 28 ++++++ package-lock.json | 4 +- package.json | 2 +- .../migration.sql | 2 + prisma/schema.prisma | 1 + prisma/seed/resource/aircrafts.seed.ts | 8 ++ src/modules/aircraft/aircraft.module.ts | 4 +- ...t-aircraft-by-registration.command.spec.ts | 90 +++++++++++++++++++ ...import-aircraft-by-registration.command.ts | 73 +++++++++++++++ .../query/get-aircraft-by-id.query.ts | 1 + .../repository/aircraft.repository.ts | 28 ++++++ .../infra/http/request/aircraft.request.ts | 21 ++++- .../aircraft/model/error/aircraft.error.ts | 16 ++-- .../create-flight-from-simbrief.command.ts | 39 +++++--- .../create-flight-from-simbrief.action.ts | 17 +++- .../flights/model/error/flight.error.ts | 8 ++ 33 files changed, 520 insertions(+), 33 deletions(-) create mode 100644 prisma/migrations/20261117150000_add_aircraft_is_confirmed/migration.sql create mode 100644 src/modules/aircraft/application/command/import-aircraft-by-registration.command.spec.ts create mode 100644 src/modules/aircraft/application/command/import-aircraft-by-registration.command.ts diff --git a/docker/mock/simbrief/xml.fetcher-111222-2.json b/docker/mock/simbrief/xml.fetcher-111222-2.json index cf069470..4069afe2 100644 --- a/docker/mock/simbrief/xml.fetcher-111222-2.json +++ b/docker/mock/simbrief/xml.fetcher-111222-2.json @@ -75,7 +75,8 @@ ] }, "aircraft": { - "reg": "D-AIMC" + "reg": "D-AIMC", + "icaocode": "A339" }, "times": { "sched_out": "1767603600", diff --git a/docker/mock/simbrief/xml.fetcher-123456-2.json b/docker/mock/simbrief/xml.fetcher-123456-2.json index ed43de98..f05d72ef 100644 --- a/docker/mock/simbrief/xml.fetcher-123456-2.json +++ b/docker/mock/simbrief/xml.fetcher-123456-2.json @@ -302,7 +302,8 @@ ] }, "aircraft": { - "reg": "D-AIMC" + "reg": "D-AIMC", + "icaocode": "A339" }, "times": { "sched_out": "1767603600", diff --git a/docker/mock/simbrief/xml.fetcher-333444-2.json b/docker/mock/simbrief/xml.fetcher-333444-2.json index 4a02ba9f..f4bbb97f 100644 --- a/docker/mock/simbrief/xml.fetcher-333444-2.json +++ b/docker/mock/simbrief/xml.fetcher-333444-2.json @@ -79,7 +79,8 @@ ] }, "aircraft": { - "reg": "D-AIMC" + "reg": "D-AIMC", + "icaocode": "A339" }, "times": { "sched_out": "1767603600", diff --git a/docker/mock/simbrief/xml.fetcher-654321-2.json b/docker/mock/simbrief/xml.fetcher-654321-2.json index 3d8d5a6a..d646cdd8 100644 --- a/docker/mock/simbrief/xml.fetcher-654321-2.json +++ b/docker/mock/simbrief/xml.fetcher-654321-2.json @@ -1,7 +1,16 @@ { + "params": { + "request_id": "162595444", + "sequence_id": "816599746ea6", + "units": "kgs" + }, "general": { "icao_airline": "DLH", - "flight_number": "80" + "flight_number": "80", + "is_etops": "1", + "gc_distance": "3350", + "total_burn": "156000", + "cont_rule": "3%" }, "origin": { "icao_code": "EDDF", @@ -77,7 +86,8 @@ ] }, "aircraft": { - "reg": "D-TEST" + "reg": "D-TEST", + "icaocode": "A339" }, "times": { "sched_out": "1767603600", @@ -91,6 +101,10 @@ "est_zfw": "206523", "pax_count": "348" }, + "text": { + "tlr_section": "TAKEOFF AND LANDING REPORT DLH80", + "plan_html": "

Simbrief OFP

Mock OFP

" + }, "crew": { "pilot_id": "371340", "cpt": "..... .....", diff --git a/features/aircraft/aircraft.create.feature b/features/aircraft/aircraft.create.feature index eb22d00b..3bdc2e64 100644 --- a/features/aircraft/aircraft.create.feature +++ b/features/aircraft/aircraft.create.feature @@ -54,6 +54,7 @@ Feature: Create aircraft for operator "livery": "Sunshine", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -147,6 +148,7 @@ Feature: Create aircraft for operator "livery": "Sunshine", "currentState": "idle", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -214,6 +216,7 @@ Feature: Create aircraft for operator "livery": "Sunshine", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -281,6 +284,7 @@ Feature: Create aircraft for operator "livery": "@defaultLivery('Lufthansa')", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", diff --git a/features/aircraft/aircraft.get.feature b/features/aircraft/aircraft.get.feature index e79f5790..bae090d0 100644 --- a/features/aircraft/aircraft.get.feature +++ b/features/aircraft/aircraft.get.feature @@ -23,6 +23,7 @@ Feature: Get aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -68,6 +69,7 @@ Feature: Get aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -113,6 +115,7 @@ Feature: Get aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -158,6 +161,7 @@ Feature: Get aircraft "selcal": null, "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "5c88ea21-f482-47ff-8b1f-3d0c9bbd6caf", diff --git a/features/aircraft/aircraft.list.feature b/features/aircraft/aircraft.list.feature index 1558f326..86ffba2d 100644 --- a/features/aircraft/aircraft.list.feature +++ b/features/aircraft/aircraft.list.feature @@ -24,6 +24,7 @@ Feature: List aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -61,6 +62,7 @@ Feature: List aircraft "selcal": "BD-EF", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", @@ -123,6 +125,7 @@ Feature: List aircraft "selcal": "BD-EG", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -177,6 +180,7 @@ Feature: List aircraft "selcal": "BD-FG", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", @@ -235,6 +239,7 @@ Feature: List aircraft "selcal": "BE-FG", "currentState": "cruise", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", @@ -293,6 +298,7 @@ Feature: List aircraft "selcal": "CD-EF", "currentState": "cruise", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", @@ -351,6 +357,7 @@ Feature: List aircraft "selcal": "CD-EG", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", @@ -409,6 +416,7 @@ Feature: List aircraft "selcal": "CE-FG", "currentState": "cruise", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "lh-74h", "airlineIata": "LH", diff --git a/features/aircraft/aircraft.update.feature b/features/aircraft/aircraft.update.feature index 91bf2680..a263a4a8 100644 --- a/features/aircraft/aircraft.update.feature +++ b/features/aircraft/aircraft.update.feature @@ -46,6 +46,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -121,6 +122,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -172,6 +174,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 120, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -223,6 +226,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -274,6 +278,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "3c721cc6-c653-4fad-be43-dc9d6a149383", @@ -325,6 +330,7 @@ Feature: Update aircraft "selcal": "LR-CK", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": null, "baseAirport": null, "lastAirport": null, @@ -543,6 +549,69 @@ Feature: Update aircraft } """ + Scenario: As operations I can confirm an aircraft created from an imported flight plan + Given I am signed in as "operations with Simbrief ID but non existing aircraft" + When I send a "POST" request to "/api/v1/flight/create-with-simbrief" + Then the response status should be 201 + And I remember the response body property "aircraft.id" as "aircraftId" + When I send a "PATCH" request to "/api/v1/operator/40b1b34e-aea1-4cec-acbe-f2bf97c06d7d/aircraft/{{aircraftId}}" with body: + """json + { + "isConfirmed": true + } + """ + Then the response status should be 200 + And the response body should contain: + """json + { + "id": "@uuid", + "airframe": { + "type": "A339", + "iataType": "339", + "name": "Airbus A330-900", + "cruiseSpeed": { "value": 0.8, "unit": "mach" }, + "serviceCeiling": 41400, + "performanceCode": "D", + "weightCategory": "heavy", + "serviceType": "passenger" + }, + "registration": "D-TEST", + "selcal": null, + "livery": "@defaultLivery('Lufthansa')", + "currentState": "planned", + "etopsThresholdMinutes": null, + "isConfirmed": true, + "cabinLayout": null, + "holdVariant": null, + "baseAirport": null, + "lastAirport": null, + "lastAirportUpdatedAt": null, + "lastParkingPosition": null + } + """ + And I set database to initial state + + Scenario: As operations I cannot set the aircraft confirmation to null + Given I am signed in as "operations" + When I send a "PATCH" request to "/api/v1/operator/40b1b34e-aea1-4cec-acbe-f2bf97c06d7d/aircraft/9f5da1a4-f09e-4961-8299-82d688337d1f" with body: + """json + { + "isConfirmed": null + } + """ + Then the response status should be 400 + And the response body should contain: + """json + { + "statusCode": 400, + "message": "Request validation failed.", + "error": "Bad Request", + "violations": { + "isConfirmed": ["isConfirmed must be a boolean value"] + } + } + """ + Scenario: As an unauthorized user I cannot update aircraft When I send a "PATCH" request to "/api/v1/operator/40b1b34e-aea1-4cec-acbe-f2bf97c06d7d/aircraft/9f5da1a4-f09e-4961-8299-82d688337d1f" with body: """json diff --git a/features/aircraft/cabin-layout.assign.feature b/features/aircraft/cabin-layout.assign.feature index 9fe1df9c..b408281d 100644 --- a/features/aircraft/cabin-layout.assign.feature +++ b/features/aircraft/cabin-layout.assign.feature @@ -28,6 +28,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "Oneworld (2023)", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", @@ -100,6 +101,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "Team USA (2023)", "currentState": "cruise", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w-2", "airlineIata": "AA", @@ -169,6 +171,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "KLM (2022)", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "baseAirport": { "id": "f35c094a-bec5-4803-be32-bd80a14b441a", @@ -220,6 +223,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "Air France (2021)", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", @@ -310,6 +314,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "Icelandair (2023)", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "fi-752-1", "airlineIata": "FI", @@ -365,6 +370,7 @@ Feature: Assign a cabin layout to an aircraft "livery": "KLM (2022)", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "kl-738", "airlineIata": "KL", diff --git a/features/aircraft/hold-variant.assign.feature b/features/aircraft/hold-variant.assign.feature index f2042034..a89d3a46 100644 --- a/features/aircraft/hold-variant.assign.feature +++ b/features/aircraft/hold-variant.assign.feature @@ -28,6 +28,7 @@ Feature: Assign a cargo hold variant to an aircraft "livery": "Sunshine (2024)", "currentState": "checked_in", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "de-321", "airlineIata": "DE", @@ -95,6 +96,7 @@ Feature: Assign a cargo hold variant to an aircraft "livery": "Air France (2021)", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "holdVariant": null, "baseAirport": { @@ -146,6 +148,7 @@ Feature: Assign a cargo hold variant to an aircraft "livery": "Air France (2021)", "currentState": "planned", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": null, "holdVariant": "a320-bulk", "baseAirport": { diff --git a/features/aircraft/reposition/reposition.create.feature b/features/aircraft/reposition/reposition.create.feature index 9ce786a1..c8e7797a 100644 --- a/features/aircraft/reposition/reposition.create.feature +++ b/features/aircraft/reposition/reposition.create.feature @@ -135,6 +135,7 @@ Feature: Reposition an aircraft "selcal": "SK-PK", "currentState": "checked_in", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "de-321", "airlineIata": "DE", diff --git a/features/flight/actions/flight.check-in-pilot.feature b/features/flight/actions/flight.check-in-pilot.feature index 36b9e67b..f02cd825 100644 --- a/features/flight/actions/flight.check-in-pilot.feature +++ b/features/flight/actions/flight.check-in-pilot.feature @@ -439,6 +439,7 @@ Feature: Check in pilot for flight "selcal": "KY-JO", "currentState": "checked_in", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", diff --git a/features/flight/actions/flight.close.feature b/features/flight/actions/flight.close.feature index d07e9e96..923bff72 100644 --- a/features/flight/actions/flight.close.feature +++ b/features/flight/actions/flight.close.feature @@ -399,6 +399,7 @@ Feature: Close flight "selcal": "AB-FG", "currentState": "idle", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", diff --git a/features/flight/actions/flight.report-off-block.feature b/features/flight/actions/flight.report-off-block.feature index a26a5bdb..c75e0750 100644 --- a/features/flight/actions/flight.report-off-block.feature +++ b/features/flight/actions/flight.report-off-block.feature @@ -320,6 +320,7 @@ Feature: Report off-block "selcal": "AB-DE", "currentState": "cruise", "etopsThresholdMinutes": null, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", diff --git a/features/flight/actions/flight.report-on-block.feature b/features/flight/actions/flight.report-on-block.feature index e7f9e0c1..6c7a94a2 100644 --- a/features/flight/actions/flight.report-on-block.feature +++ b/features/flight/actions/flight.report-on-block.feature @@ -1283,6 +1283,7 @@ Feature: Report on-block "selcal": "KY-JO", "currentState": "idle", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", diff --git a/features/flight/management/flight.create-with-simbrief.feature b/features/flight/management/flight.create-with-simbrief.feature index 3ee6f6dd..43548083 100644 --- a/features/flight/management/flight.create-with-simbrief.feature +++ b/features/flight/management/flight.create-with-simbrief.feature @@ -530,18 +530,91 @@ Feature: Create a flight with Simbrief } """ - Scenario: As operations user with incorrect SimBrief flight plan I cannot create a flight + 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" When I send a "POST" request to "/api/v1/flight/create-with-simbrief" - Then the response status should be 404 + Then the response status should be 201 + And the response body property "aircraft" should contain: + """json + { + "id": "@uuid", + "airframe": { + "type": "A339", + "iataType": "339", + "name": "Airbus A330-900", + "cruiseSpeed": { "value": 0.8, "unit": "mach" }, + "serviceCeiling": 41400, + "performanceCode": "D", + "weightCategory": "heavy", + "serviceType": "passenger" + }, + "registration": "D-TEST", + "selcal": null, + "livery": "@defaultLivery('Lufthansa')", + "operator": { + "id": "40b1b34e-aea1-4cec-acbe-f2bf97c06d7d", + "icaoCode": "DLH", + "iataCode": "LH", + "shortName": "Lufthansa", + "fullName": "Deutsche Lufthansa AG", + "callsign": "LUFTHANSA" + }, + "cabinLayout": null + } + """ + And I remember the response body property "aircraft.id" as "aircraftId" + When I send a "GET" request to "/api/v1/operator/40b1b34e-aea1-4cec-acbe-f2bf97c06d7d/aircraft/{{aircraftId}}" + Then the response status should be 200 And the response body should contain: """json { - "statusCode": 404, - "error": "Not Found", - "message": "Aircraft with given registration not found." + "id": "@uuid", + "airframe": { + "type": "A339", + "iataType": "339", + "name": "Airbus A330-900", + "cruiseSpeed": { "value": 0.8, "unit": "mach" }, + "serviceCeiling": 41400, + "performanceCode": "D", + "weightCategory": "heavy", + "serviceType": "passenger" + }, + "registration": "D-TEST", + "selcal": null, + "livery": "@defaultLivery('Lufthansa')", + "currentState": "planned", + "etopsThresholdMinutes": null, + "isConfirmed": false, + "cabinLayout": null, + "holdVariant": null, + "baseAirport": null, + "lastAirport": null, + "lastAirportUpdatedAt": null, + "lastParkingPosition": null + } + """ + And I set database to initial state + + Scenario: As operations user I cannot import a plan that flies a fleet aircraft as a different type + Given I am signed in as "operations with valid Simbrief ID" + When I send a "PATCH" request to "/api/v1/operator/40b1b34e-aea1-4cec-acbe-f2bf97c06d7d/aircraft/9f5da1a4-f09e-4961-8299-82d688337d1f" with body: + """json + { + "type": "A359" } """ + 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": "Aircraft D-AIMC is registered as A359, but the flight plan uses A339." + } + """ + And I set database to initial state Scenario: As operations user with a SimBrief plan referencing an airport missing from database I import it from SkyLink and create a flight Given I am signed in as "operations with Simbrief ID and alternate airport missing from database" diff --git a/features/flight/management/flight.create.feature b/features/flight/management/flight.create.feature index 834874d5..6c6dfb9e 100644 --- a/features/flight/management/flight.create.feature +++ b/features/flight/management/flight.create.feature @@ -200,6 +200,7 @@ Feature: Create a flight "selcal": "KY-JO", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", @@ -413,6 +414,7 @@ Feature: Create a flight "selcal": "KY-JO", "currentState": "planned", "etopsThresholdMinutes": 180, + "isConfirmed": true, "cabinLayout": { "id": "aa-77w", "airlineIata": "AA", diff --git a/openspec/specs/aircraft-management/spec.md b/openspec/specs/aircraft-management/spec.md index 96e71807..077b75eb 100644 --- a/openspec/specs/aircraft-management/spec.md +++ b/openspec/specs/aircraft-management/spec.md @@ -185,3 +185,31 @@ assignment to its own request, so that the aircraft write endpoints remain uncha - **WHEN** an aircraft is edited with a hold variant in the request body - **THEN** the aircraft's assigned hold variant is unchanged + +### Requirement: Aircraft carry whether operations confirmed them + +The system SHALL record on every aircraft whether operations confirmed its data, and SHALL return it as `isConfirmed` on every aircraft read model under `/api/v1/operator/{operatorId}/aircraft`. An aircraft operations create SHALL start confirmed; an aircraft a flight plan import creates SHALL start unconfirmed. An operations user SHALL set it by sending `isConfirmed` on `PATCH /api/v1/operator/{operatorId}/aircraft/{aircraftId}`; omitting it SHALL leave it unchanged, and `null` SHALL be rejected with `400 Bad Request`. + +#### Scenario: Confirm an aircraft created by an import + +- **WHEN** an operations user updates an unconfirmed aircraft with `isConfirmed` set to `true` +- **THEN** the response's `isConfirmed` is `true` + +#### Scenario: Confirmation cannot be null + +- **WHEN** an operations user updates an aircraft with `isConfirmed` set to `null` +- **THEN** the request is rejected with `400 Bad Request` and the aircraft is unchanged + +### Requirement: A SimBrief import resolves the aircraft by registration + +The system SHALL resolve the aircraft of an imported SimBrief plan by its registration, upper-cased and trimmed. When no aircraft has that registration, the system SHALL create one for the plan's operator with the plan's ICAO type, the operator's default livery and no SELCAL, base airport or ETOPS threshold, marked unconfirmed. When an aircraft has that registration but a different type, the import SHALL be rejected with `409 Conflict` and no flight SHALL be created. A plan with no registration or no type SHALL be rejected with `422 Unprocessable Content`, and a new registration whose type is not a known airframe with `404 Not Found`. + +#### Scenario: Import a plan for a registration not in the fleet + +- **WHEN** an operations user imports a plan whose registration no aircraft has +- **THEN** the flight is created on a new aircraft of the plan's operator and type, and the aircraft's `isConfirmed` is `false` + +#### Scenario: Import a plan that flies a fleet aircraft as another type + +- **WHEN** an operations user imports a plan whose registration belongs to an aircraft of a different type +- **THEN** the import is rejected with `409 Conflict` naming both types, and no flight is created diff --git a/package-lock.json b/package-lock.json index af8a5731..a137c373 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "flight-tracker-api", - "version": "3.87.0", + "version": "3.88.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "flight-tracker-api", - "version": "3.87.0", + "version": "3.88.0", "license": "Unlicense", "dependencies": { "@faker-js/faker": "^10.6.0", diff --git a/package.json b/package.json index 1d6c2ecb..fdda0771 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flight-tracker-api", - "version": "3.87.0", + "version": "3.88.0", "private": true, "homepage": "https://mypreflight.io", "author": "mypreflight", diff --git a/prisma/migrations/20261117150000_add_aircraft_is_confirmed/migration.sql b/prisma/migrations/20261117150000_add_aircraft_is_confirmed/migration.sql new file mode 100644 index 00000000..9ce6ffd2 --- /dev/null +++ b/prisma/migrations/20261117150000_add_aircraft_is_confirmed/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "aircraft" ADD COLUMN "isConfirmed" BOOLEAN NOT NULL DEFAULT true; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index da235bc6..a418e32d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -19,6 +19,7 @@ model Aircraft { etopsThresholdMinutes Int? cabinLayout String? holdVariant String? + isConfirmed Boolean @default(true) operatorId String? @db.Uuid baseAirportId String? @db.Uuid lastAirportId String? @db.Uuid diff --git a/prisma/seed/resource/aircrafts.seed.ts b/prisma/seed/resource/aircrafts.seed.ts index b11a32cf..77b10114 100644 --- a/prisma/seed/resource/aircrafts.seed.ts +++ b/prisma/seed/resource/aircrafts.seed.ts @@ -11,6 +11,7 @@ export async function loadAircraft( livery: 'Fanhansa (2024)', cabinLayout: null, holdVariant: null, + isConfirmed: true, operatorId: '40b1b34e-aea1-4cec-acbe-f2bf97c06d7d', // Lufthansa currentState: AircraftState.planned, // LH450 Created etopsThresholdMinutes: 180, @@ -28,6 +29,7 @@ export async function loadAircraft( livery: 'Sunshine (2024)', cabinLayout: 'de-321', holdVariant: null, + isConfirmed: true, operatorId: '5c649579-22eb-4c07-a96c-b74a77f53871', // Condor currentState: AircraftState.checked_in, // DE1014 CheckedIn etopsThresholdMinutes: null, @@ -45,6 +47,7 @@ export async function loadAircraft( livery: 'Water (2024)', cabinLayout: null, holdVariant: null, + isConfirmed: true, operatorId: '5c649579-22eb-4c07-a96c-b74a77f53871', // Condor currentState: AircraftState.idle, etopsThresholdMinutes: null, @@ -62,6 +65,7 @@ export async function loadAircraft( livery: 'Team USA (2023)', cabinLayout: 'aa-77w', holdVariant: null, + isConfirmed: true, operatorId: '1f630d38-ad24-47cc-950b-3783e71bbd10', // American Airlines currentState: AircraftState.cruise, // AA4913 TaxiingIn etopsThresholdMinutes: 180, @@ -109,6 +113,7 @@ export async function loadAircraft( livery, cabinLayout: CABIN_LAYOUTS[registration] ?? null, holdVariant: null, + isConfirmed: true, operatorId, currentState, etopsThresholdMinutes, @@ -393,6 +398,7 @@ export async function loadAircraft( livery: 'Air France (2021)', cabinLayout: null, holdVariant: 'a320-cls', + isConfirmed: true, operatorId: '3a1354c5-d9fb-428b-9f87-0e887e491f0d', // Air France currentState: AircraftState.planned, etopsThresholdMinutes: null, @@ -410,6 +416,7 @@ export async function loadAircraft( livery: 'Icelandair (2023)', cabinLayout: 'fi-752-1', holdVariant: null, + isConfirmed: true, operatorId: 'e4ba1445-b413-49a9-b0c5-c8bd3df14b42', // Icelandair currentState: AircraftState.planned, etopsThresholdMinutes: 180, @@ -427,6 +434,7 @@ export async function loadAircraft( livery: 'KLM (2022)', cabinLayout: 'kl-738', holdVariant: null, + isConfirmed: true, operatorId: '7d724b05-8eb9-4e66-84cc-bb101369d1a0', // KLM currentState: AircraftState.planned, etopsThresholdMinutes: null, diff --git a/src/modules/aircraft/aircraft.module.ts b/src/modules/aircraft/aircraft.module.ts index 89da7c09..adbe917f 100644 --- a/src/modules/aircraft/aircraft.module.ts +++ b/src/modules/aircraft/aircraft.module.ts @@ -23,8 +23,8 @@ import { AssignCabinLayoutHandler } from './application/command/assign-cabin-lay import { RemoveCabinLayoutHandler } from './application/command/remove-cabin-layout.command'; import { AssignHoldVariantHandler } from './application/command/assign-hold-variant.command'; import { RemoveHoldVariantHandler } from './application/command/remove-hold-variant.command'; +import { ImportAircraftByRegistrationHandler } from './application/command/import-aircraft-by-registration.command'; import { GetAircraftByIdHandler } from './application/query/get-aircraft-by-id.query'; -import { GetAircraftByRegistrationHandler } from './application/query/get-aircraft-by-registration.query'; import { ListAllAircraftHandler } from './application/query/list-all-aircraft.query'; import { CheckAircraftExistsHandler } from './application/query/check-aircraft-exists.query'; import { GetOperatorFleetSummaryHandler } from './application/query/get-operator-fleet-summary.query'; @@ -63,8 +63,8 @@ import { RepositionFlightLifecycleListener } from './application/event/external/ RemoveCabinLayoutHandler, AssignHoldVariantHandler, RemoveHoldVariantHandler, + ImportAircraftByRegistrationHandler, GetAircraftByIdHandler, - GetAircraftByRegistrationHandler, ListAllAircraftHandler, CheckAircraftExistsHandler, GetOperatorFleetSummaryHandler, diff --git a/src/modules/aircraft/application/command/import-aircraft-by-registration.command.spec.ts b/src/modules/aircraft/application/command/import-aircraft-by-registration.command.spec.ts new file mode 100644 index 00000000..78c013f1 --- /dev/null +++ b/src/modules/aircraft/application/command/import-aircraft-by-registration.command.spec.ts @@ -0,0 +1,90 @@ +import { QueryBus } from '@nestjs/cqrs'; +import { + ImportAircraftByRegistrationCommand, + ImportAircraftByRegistrationHandler, +} from './import-aircraft-by-registration.command'; +import { AircraftRepository } from '../../infra/database/repository/aircraft.repository'; +import { DomainEventEmitter } from '../../../../core/domain/events/domain-event-emitter'; +import { AircraftTypeMismatchError } from '../../model/error/aircraft.error'; +import { AirframeNotFoundError } from '../../../airframes/model/error/airframe.error'; +import { AircraftCreatedEvent } from '../../../../core/domain/events/dto/aircraft.event'; + +const OPERATOR_ID = '40b1b34e-aea1-4cec-acbe-f2bf97c06d7d'; + +function setUp(existing: { id: string; type: string } | null) { + const repository = { + findOneBy: jest.fn().mockResolvedValue(existing), + createUnconfirmed: jest.fn().mockResolvedValue(undefined), + }; + const domainEvents = { emitAsync: jest.fn().mockResolvedValue([]) }; + const queryBus = { + execute: jest.fn().mockResolvedValue({ shortName: 'Lufthansa' }), + }; + + const handler = new ImportAircraftByRegistrationHandler( + repository as unknown as AircraftRepository, + domainEvents as unknown as DomainEventEmitter, + queryBus as unknown as QueryBus, + ); + + return { handler, repository, domainEvents }; +} + +describe('ImportAircraftByRegistrationHandler', () => { + it('returns the aircraft in the fleet when its type matches the plan', async () => { + const { handler, repository } = setUp({ id: 'aircraft-1', type: 'A339' }); + + await expect( + handler.execute( + new ImportAircraftByRegistrationCommand('D-AIMC', 'A339', OPERATOR_ID), + ), + ).resolves.toBe('aircraft-1'); + expect(repository.createUnconfirmed).not.toHaveBeenCalled(); + }); + + it('refuses a plan that flies a fleet aircraft as a different type', async () => { + const { handler, repository } = setUp({ id: 'aircraft-1', type: 'A339' }); + + await expect( + handler.execute( + new ImportAircraftByRegistrationCommand('D-AIMC', 'B77W', OPERATOR_ID), + ), + ).rejects.toThrow(new AircraftTypeMismatchError('D-AIMC', 'A339', 'B77W')); + expect(repository.createUnconfirmed).not.toHaveBeenCalled(); + }); + + it('creates an unknown registration as an unconfirmed aircraft of the operator', async () => { + const { handler, repository, domainEvents } = setUp(null); + + const aircraftId = await handler.execute( + new ImportAircraftByRegistrationCommand('D-AIXP', 'A359', OPERATOR_ID), + ); + + expect(repository.createUnconfirmed).toHaveBeenCalledWith( + aircraftId, + OPERATOR_ID, + { + type: 'A359', + registration: 'D-AIXP', + livery: `Lufthansa ${new Date().getFullYear()}`, + }, + ); + expect(domainEvents.emitAsync).toHaveBeenCalledWith( + expect.any(AircraftCreatedEvent), + ); + expect(domainEvents.emitAsync.mock.calls[0][0]).toMatchObject({ + payload: { aircraftId, operatorId: OPERATOR_ID }, + }); + }); + + it('refuses to create an unknown registration of a type that is not a known airframe', async () => { + const { handler, repository } = setUp(null); + + await expect( + handler.execute( + new ImportAircraftByRegistrationCommand('D-AIXP', 'ZZZZ', OPERATOR_ID), + ), + ).rejects.toThrow(AirframeNotFoundError); + expect(repository.createUnconfirmed).not.toHaveBeenCalled(); + }); +}); diff --git a/src/modules/aircraft/application/command/import-aircraft-by-registration.command.ts b/src/modules/aircraft/application/command/import-aircraft-by-registration.command.ts new file mode 100644 index 00000000..4476370a --- /dev/null +++ b/src/modules/aircraft/application/command/import-aircraft-by-registration.command.ts @@ -0,0 +1,73 @@ +import { + Command, + CommandHandler, + ICommandHandler, + QueryBus, +} from '@nestjs/cqrs'; +import { v4 } from 'uuid'; +import { AircraftRepository } from '../../infra/database/repository/aircraft.repository'; +import { AircraftTypeMismatchError } from '../../model/error/aircraft.error'; +import { findAirframeByType } from '../../../airframes/data/airframes'; +import { AirframeNotFoundError } from '../../../airframes/model/error/airframe.error'; +import { GetOperatorByIdQuery } from '../../../operators/application/query/get-operator-by-id.query'; +import { DomainEventEmitter } from '../../../../core/domain/events/domain-event-emitter'; +import { AircraftCreatedEvent } from '../../../../core/domain/events/dto/aircraft.event'; + +export class ImportAircraftByRegistrationCommand extends Command { + constructor( + public readonly registration: string, + public readonly type: string, + public readonly operatorId: string, + ) { + super(); + } +} + +@CommandHandler(ImportAircraftByRegistrationCommand) +export class ImportAircraftByRegistrationHandler implements ICommandHandler< + ImportAircraftByRegistrationCommand, + string +> { + constructor( + private readonly aircraftRepository: AircraftRepository, + private readonly domainEvents: DomainEventEmitter, + private readonly queryBus: QueryBus, + ) {} + + async execute(command: ImportAircraftByRegistrationCommand): Promise { + const { registration, type, operatorId } = command; + + const existing = await this.aircraftRepository.findOneBy({ + registration, + }); + + if (existing) { + if (existing.type !== type) { + throw new AircraftTypeMismatchError(registration, existing.type, type); + } + + return existing.id; + } + + if (!findAirframeByType(type)) { + throw new AirframeNotFoundError(); + } + + const operator = await this.queryBus.execute( + new GetOperatorByIdQuery(operatorId), + ); + + const aircraftId = v4(); + + await this.aircraftRepository.createUnconfirmed(aircraftId, operatorId, { + type, + registration, + livery: `${operator.shortName} ${new Date().getFullYear()}`, + }); + await this.domainEvents.emitAsync( + new AircraftCreatedEvent({ aircraftId, operatorId }), + ); + + return aircraftId; + } +} diff --git a/src/modules/aircraft/application/query/get-aircraft-by-id.query.ts b/src/modules/aircraft/application/query/get-aircraft-by-id.query.ts index e44205d3..884dd63c 100644 --- a/src/modules/aircraft/application/query/get-aircraft-by-id.query.ts +++ b/src/modules/aircraft/application/query/get-aircraft-by-id.query.ts @@ -61,6 +61,7 @@ export class GetAircraftByIdHandler implements IQueryHandler; +function isUniqueConstraintViolation(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + (error as { code?: string }).code === 'P2002' + ); +} + @Injectable() export class AircraftRepository { constructor(private readonly prisma: PrismaService) {} @@ -126,6 +136,24 @@ export class AircraftRepository { }); } + async createUnconfirmed( + id: string, + operatorId: string, + data: { type: string; registration: string; livery: string }, + ): Promise { + try { + await this.prisma.aircraft.create({ + data: { id, ...data, operatorId, isConfirmed: false }, + }); + } catch (error) { + if (isUniqueConstraintViolation(error)) { + throw new AircraftWithRegistrationAlreadyExistsError(); + } + + throw error; + } + } + async findAll(): Promise { return this.prisma.aircraft.findMany({ select: aircraftWithOperatorFields, diff --git a/src/modules/aircraft/infra/http/request/aircraft.request.ts b/src/modules/aircraft/infra/http/request/aircraft.request.ts index 9cdad63b..a6bb20bf 100644 --- a/src/modules/aircraft/infra/http/request/aircraft.request.ts +++ b/src/modules/aircraft/infra/http/request/aircraft.request.ts @@ -1,12 +1,14 @@ import { ApiProperty, PartialType } from '@nestjs/swagger'; import { Aircraft, AircraftState } from '../../../model/aircraft.model'; import { + IsBoolean, IsIn, IsNotEmpty, IsOptional, IsString, IsUUID, Length, + ValidateIf, } from 'class-validator'; import { LegacyOperatorResponse } from '../../../../operators/infra/http/request/operator.request'; import { Coordinates } from '../../../../airports/model/airport.model'; @@ -79,7 +81,17 @@ export class CreateAircraftRequest { etopsThresholdMinutes?: number | null; } -export class UpdateAircraftRequest extends PartialType(CreateAircraftRequest) {} +export class UpdateAircraftRequest extends PartialType(CreateAircraftRequest) { + @ApiProperty({ + description: + 'Whether operations confirmed the aircraft data is correct. Aircraft created from an imported flight plan start unconfirmed.', + example: true, + required: false, + }) + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + isConfirmed?: boolean; +} export class AircraftAirport { @ApiProperty({ @@ -215,6 +227,13 @@ export class GetAircraftResponse extends Aircraft { nullable: true, }) holdVariant!: string | null; + + @ApiProperty({ + description: + 'Whether operations confirmed the aircraft data is correct; false for an aircraft created from an imported flight plan until operations confirm it', + example: true, + }) + isConfirmed!: boolean; } export class LegacyCreateAircraftResponse extends Aircraft { diff --git a/src/modules/aircraft/model/error/aircraft.error.ts b/src/modules/aircraft/model/error/aircraft.error.ts index 7990786e..e3018dd3 100644 --- a/src/modules/aircraft/model/error/aircraft.error.ts +++ b/src/modules/aircraft/model/error/aircraft.error.ts @@ -9,15 +9,21 @@ export class AircraftNotFoundError extends NotFoundError { } } -export class AircraftWithRegistrationNotFoundError extends NotFoundError { +export class AircraftWithRegistrationAlreadyExistsError extends ConflictError { constructor() { - super('Aircraft with given registration not found.'); + super('Aircraft with given registration already exists.'); } } -export class AircraftWithRegistrationAlreadyExistsError extends ConflictError { - constructor() { - super('Aircraft with given registration already exists.'); +export class AircraftTypeMismatchError extends ConflictError { + constructor( + registration: string, + registeredType: string, + plannedType: string, + ) { + super( + `Aircraft ${registration} is registered as ${registeredType}, but the flight plan uses ${plannedType}.`, + ); } } 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 5f64b380..e2faed40 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 @@ -4,7 +4,10 @@ import { ICommandHandler, QueryBus, } from '@nestjs/cqrs'; -import { SimbriefIdNotConnectedError } from '../../model/error/flight.error'; +import { + SimbriefIdNotConnectedError, + SimbriefPlanWithoutAircraftError, +} from '../../model/error/flight.error'; import { FlightsRepository } from '../../infra/database/repository/flights.repository'; import { FlightWasCreatedEvent, @@ -15,7 +18,7 @@ import { DomainEventEmitter } from '../../../../core/domain/events/domain-event- import { GetUserSimbriefIdQuery } from '../../../users/application/query/get-user-simbrief-id.query'; import { SimbriefClient } from '../../../../core/provider/simbrief/client/simbrief.client'; import { ImportAirportByIcaoCommand } from '../../../airports/application/command/import-airport-by-icao.command'; -import { GetAircraftByRegistrationQuery } from '../../../aircraft/application/query/get-aircraft-by-registration.query'; +import { ImportAircraftByRegistrationCommand } from '../../../aircraft/application/command/import-aircraft-by-registration.command'; import { GetOperatorByIcaoCodeQuery } from '../../../operators/application/query/get-operator-by-icao-code.query'; import { FlightServiceType, FlightTracking } from '../../model/flight.model'; import { @@ -108,28 +111,44 @@ export class CreateFlightFromSimbriefHandler implements ICommandHandler 0 ? filedAtcCallsign : callsign, isEtops: ofp.general.is_etops === '1', - aircraftId: aircraft.id, + aircraftId, operatorId: operator.id, departureAirportId: departureAirportId, tracking: FlightTracking.Private, 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 cd365c77..fdd3bcbe 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 @@ -3,12 +3,14 @@ import { ApiBadRequestResponse, ApiBearerAuth, ApiBody, + ApiConflictResponse, ApiCreatedResponse, ApiForbiddenResponse, ApiNotFoundResponse, ApiOperation, ApiTags, ApiUnauthorizedResponse, + ApiUnprocessableEntityResponse, } from '@nestjs/swagger'; import { CommandBus, QueryBus } from '@nestjs/cqrs'; import { v4 } from 'uuid'; @@ -21,6 +23,7 @@ import { GenericBadRequestResponse } from '../../../../../../core/http/response/ import { GenericNotFoundResponse } from '../../../../../../core/http/response/not-found.response'; import { UnauthorizedResponse } from '../../../../../../core/http/response/unauthorized.response'; import { ForbiddenResponse } from '../../../../../../core/http/response/forbidden.response'; +import { GenericConflictResponse } from '../../../../../../core/http/response/conflict.response'; import { Role } from '../../../../../../core/http/auth/decorator/role.decorator'; import { AuthorizedRequest } from '../../../../../../core/http/request/authorized.request'; import { CreateFlightFromSimbriefCommand } from '../../../../application/command/create-flight-from-simbrief.command'; @@ -38,7 +41,8 @@ export class CreateFlightFromSimbriefAction { summary: 'Create a flight with SimBrief data', description: '**NOTE:** This endpoint is only available for users with the ` operations ` role.
' + - '**NOTE:** Simbrief ID must be provided for the user, otherwise import will throw HTTP 400.', + '**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.', }) @ApiBearerAuth('jwt') @ApiBody({ type: CreateFlightRequest }) @@ -47,9 +51,18 @@ export class CreateFlightFromSimbriefAction { @ApiUnauthorizedResponse({ type: UnauthorizedResponse }) @ApiForbiddenResponse({ type: ForbiddenResponse }) @ApiNotFoundResponse({ - description: 'Airports or aircraft does not exist', + description: + 'The operator or an airport cannot be found, or the aircraft is not in the fleet and its type is not a known airframe', type: GenericNotFoundResponse, }) + @ApiConflictResponse({ + description: + 'The aircraft is in the fleet with a different type than the plan uses', + type: GenericConflictResponse, + }) + @ApiUnprocessableEntityResponse({ + description: 'The plan does not name the aircraft registration and type', + }) @Post('/create-with-simbrief') @Role(UserRole.Operations) async run(@Req() request: AuthorizedRequest): Promise { diff --git a/src/modules/flights/model/error/flight.error.ts b/src/modules/flights/model/error/flight.error.ts index 745ca7e9..e1e912fb 100644 --- a/src/modules/flights/model/error/flight.error.ts +++ b/src/modules/flights/model/error/flight.error.ts @@ -176,6 +176,14 @@ export class SimbriefIdNotConnectedError extends BadRequestError { } } +export class SimbriefPlanWithoutAircraftError extends UnprocessableError { + constructor() { + super( + 'The SimBrief plan does not name the aircraft registration and type.', + ); + } +} + export class InvalidStatusToMarkAsReadyError extends UnprocessableError { constructor() { super('Cannot mark flight as ready. Flight is not in created status.');