# Flight Search and Manual Booking Flow

## Purpose and current status

This document describes the flight-search portion of Kabayan Flights as it exists in commit `02ac8ba` on the `develop` branch. It is intentionally limited to the public flight journey, the Amadeus integration, and the data that supports that journey.

The most important current-state distinction is:

> The application can search and display live Amadeus flight offers, but it cannot create or manage a booking online.

The implemented customer journey ends at a **Call to Book** telephone link. Passenger collection, offer repricing, payment, Amadeus Flight Create Orders, PNR creation, ticketing, confirmations, changes, cancellations, and refunds are not present in this repository.

In this codebase, `Flight` and the `flights` table represent CMS-managed promotional offer cards. They do not represent live Amadeus offers, customer bookings, tickets, or flight-order records.

## Current capability summary

| Capability | Current state | Evidence/behaviour |
| --- | --- | --- |
| Airport autocomplete | Implemented | Searches the local `airports` table through public JSON endpoints. |
| One-way and round-trip search | Implemented | Sent to Amadeus Flight Offers Search. |
| Cabin-class search | Implemented in the main form | Economy, premium economy, business, and first are accepted. |
| Adult search | Implemented in the UI | One to nine adults. |
| Child, infant, and non-stop criteria | Backend-supported, not exposed by the current public forms | Accepted by `FlightSearchRequest` and sent by `FlightSearchService` when supplied. |
| Live flight shopping | Implemented | Calls `GET /v2/shopping/flight-offers`. |
| Live offer display | Implemented | Displays itinerary summaries, total price, and remaining bookable seats when supplied. |
| Offer selection | Not implemented | Offer IDs are mapped in memory but no selection action is rendered. |
| Offer repricing/confirmation | Not implemented | No Flight Offers Price endpoint is called. |
| Fare rules, baggage, branded fares, or refundability | Not implemented | These details are neither mapped nor rendered. |
| Passenger/contact capture | Not implemented | No traveller or contact form exists. |
| Payment | Not implemented | No payment provider or payment records exist. |
| Amadeus order/PNR creation | Not implemented | No Flight Create Orders request exists. |
| Booking persistence | Not implemented | There is no booking/order/passenger/payment/PNR table or model. |
| Ticketing and confirmation | Not implemented | No ticket issuance, booking email, or confirmation page exists. |
| Changes, cancellation, refund, or reconciliation | Not implemented | No post-booking workflow exists. |
| Manual booking handoff | Implemented | Every result links to the configured company telephone number. |

## System boundary

The current flow contains three distinct kinds of data:

1. **CMS catalogue data** — destinations, airlines, and promotional `flights` rows maintained by administrators.
2. **Local airport catalogue data** — active IATA airports used to constrain and label searches.
3. **Transient Amadeus search data** — live offers retrieved for one HTTP request, mapped for display, and then discarded.

No live Amadeus offer or customer booking is persisted.

## High-level request flow

```mermaid
sequenceDiagram
    actor Customer
    participant Browser
    participant Laravel
    participant DB as Local database
    participant Cache as Laravel cache
    participant Amadeus
    participant Phone as Offline booking team

    Customer->>Browser: Choose route, dates, adults, and cabin
    Browser->>Laravel: GET /flights/search?...
    Laravel->>DB: Validate/resolve active airports and optional destination
    Laravel->>Cache: Read cached OAuth access token
    alt Token is absent or expired
        Laravel->>Amadeus: POST /v1/security/oauth2/token
        Amadeus-->>Laravel: Access token and expiry
        Laravel->>Cache: Cache token with a 60-second safety margin
    end
    Laravel->>Amadeus: GET /v2/shopping/flight-offers
    Amadeus-->>Laravel: Offers, dictionaries, and metadata
    Laravel->>Laravel: Map response to display-only view models
    Laravel-->>Browser: Render flight result cards
    Customer->>Phone: Click Call to Book
    Note over Phone: Booking continues outside this application
```

## Entry points into flight search

### Main search form

The shared form at `resources/views/partials/flight-search-form.blade.php` is used on the public site. It submits a `GET` request to the named route `flights.search`.

It currently exposes:

- round trip or one way;
- origin and destination airport autocomplete;
- departure and optional return date;
- adults;
- cabin class.

Dates default to 30 days from today for departure and 44 days from today for return.

### CMS destination and flight cards

CMS-managed flight and destination cards link directly to the same search route:

- `App\Models\Destination::flightSearchUrl()` sets the destination slug, default origin, round trip, one adult, and economy.
- `App\Models\Flight::flightSearchUrl()` derives an active IATA origin/destination and converts the card's Economy/Business class to an Amadeus cabin class.
- When card links do not provide dates, the service applies the 30-day departure and 14-night trip defaults.

The price in a CMS `flights` row is a static **starting from** marketing price. It is not sent to Amadeus, used to filter Amadeus results, or verified against the returned live price.

### Public routes

The relevant routes are declared in `routes/web.php` and do not require authentication:

| Method | Route | Purpose |
| --- | --- | --- |
| `GET` | `/flights` | Marketing/catalogue page and flight search form. |
| `GET` | `/flights/search` | Validates criteria, calls Amadeus, and renders results. |
| `GET` | `/airports/search` | Searches active local airports for autocomplete. |
| `GET` | `/airports/resolve` | Converts an IATA code or unambiguous airport label to a local airport. |

There is no route for selecting an offer, checkout, payment, booking creation, confirmation, or booking management.

## Detailed search flow

### 1. Airport lookup in the browser

`resources/js/airport-autocomplete.js` waits 250 ms after input and calls `/airports/search` once the search text contains at least two characters. Results are limited to ten in the current UI.

The browser stores the selected airport's three-letter IATA code in a hidden input while displaying the human-readable label. Existing codes are resolved through `/airports/resolve` when a component loads.

Both endpoints query the local `airports` table through `App\Services\AirportService`; they do not call Amadeus location APIs. Only locally stored, active airports can be submitted successfully.

### 2. Request validation

`App\Http\Requests\FlightSearchRequest` uppercases airport and cabin codes and validates:

| Input | Rules/current meaning |
| --- | --- |
| `destination` | Optional CMS destination slug. |
| `from` | Optional at request level; when present it must be an active local three-letter IATA code. The service falls back to the configured default origin. |
| `to` | Optional at request level because a destination slug may supply it; otherwise the service requires a valid active local IATA code. |
| `trip_type` | `round_trip` or `one_way`. Defaults to round trip. |
| `depart_date` | Today or later. Defaults to 30 days from today. |
| `return_date` | On/after departure. For a round trip it defaults to 14 days after departure. |
| `adults` | 1-9. Defaults to 1. |
| `children` | 0-9. Defaults to 0. |
| `infants` | 0-9 and additionally cannot exceed adults. Defaults to 0. |
| `travel_class` | `ECONOMY`, `PREMIUM_ECONOMY`, `BUSINESS`, or `FIRST`. |
| `non_stop` | Boolean. Defaults to false. |

Currency and maximum result count are not accepted from the public request. They are controlled by application configuration.

### 3. Destination resolution and normalization

`App\Services\Amadeus\FlightSearchService::normalizeCriteria()` applies defaults and repeats the business checks needed by the service.

When `destination` is present:

1. It must identify a published, active CMS destination.
2. The destination must have an `airport_code`.
3. That code must resolve to an active row in the local airport catalogue.
4. The destination's airport code replaces any submitted `to` value.

The service also resolves display labels for the origin and destination from the local airport table.

### 4. Amadeus query construction

The normalized criteria are converted to these Amadeus query parameters:

| Application value | Amadeus parameter |
| --- | --- |
| `from` | `originLocationCode` |
| `to` | `destinationLocationCode` |
| `depart_date` | `departureDate` |
| `return_date` | `returnDate` (omitted for one way) |
| `adults` | `adults` |
| `children` | `children` (omitted when zero) |
| `infants` | `infants` (omitted when zero) |
| `travel_class` | `travelClass` |
| `non_stop` | `nonStop=true` (omitted when false) |
| configured currency | `currencyCode` |
| configured maximum | `max` |

### 5. OAuth client-credentials authentication

`App\Services\Amadeus\AmadeusClient` uses Laravel's HTTP client directly; no Amadeus SDK is installed.

When there is no cached token, the client posts form data to:

```text
POST /v1/security/oauth2/token
grant_type=client_credentials
client_id=<configured value>
client_secret=<configured value>
```

The access token is stored through Laravel's configured cache under `amadeus.oauth.token`. The cache lifetime is the returned `expires_in` minus 60 seconds, with a minimum lifetime of 60 seconds.

Authentication has a 30-second timeout. Credentials and tokens are not deliberately logged by this flow.

### 6. Flight Offers Search call

The client sends an authenticated request to:

```text
GET /v2/shopping/flight-offers
```

The search has a 45-second timeout. If Amadeus returns `401`, the cached token is deleted and the search is tried once more with a newly obtained token. Other failures, including a second `401`, `429`, server errors, and network failures, are not automatically retried.

There is currently no application-level search-result cache, rate limiter specific to these public routes, circuit breaker, or concurrent token-refresh lock.

### 7. Response mapping

`FlightSearchService::mapOffers()` converts the provider response into an in-memory display structure. For each offer it retains:

- offer ID and source;
- one-way flag;
- number of bookable seats;
- grand total/total, base price, and currency;
- first validating-airline code;
- traveller count;
- itineraries and their durations;
- segment departure/arrival time, IATA code, and terminal;
- marketing carrier code/name and flight number;
- aircraft code/name;
- segment duration and stops.

Carrier and aircraft display names come from Amadeus response dictionaries.

The mapper does **not** retain the complete raw offer, traveller pricing details, fare details by segment, booking requirements, fare rules, baggage allowances, payment requirements, or other data needed to reprice or create an order. Nothing from the response is written to the database or session.

### 8. Results and manual handoff

`resources/views/flights/search.blade.php` displays outbound and optional return summaries, total price, and the remaining-seat value when available.

The offer ID is not rendered into a form or link. The only action is:

```text
tel:<configured company telephone number>
```

Consequently, clicking **Call to Book** does not send the selected offer ID or itinerary to an internal booking team. Any identification, repricing, passenger collection, payment, reservation, PNR creation, or ticketing must happen manually in systems outside this application.

## Error handling

Validation failures remain Laravel validation errors.

For other failures, `FlightSearchController`:

1. logs `Amadeus flight search failed`, the exception message, and the validated search input;
2. renders the search-results page with no offers;
3. shows a generic message inviting the customer to retry or call the company.

The user does not see raw provider error details. There is no dedicated Amadeus health check, structured provider error storage, alerting, or search-failure metric in this feature.

## Configuration

The integration is configured in `config/services.php`:

| Environment variable | Purpose | Example/default in `.env.example` |
| --- | --- | --- |
| `AMADEUS_CLIENT_ID` | OAuth client ID | No value committed. |
| `AMADEUS_CLIENT_SECRET` | OAuth client secret | No value committed. |
| `AMADEUS_API_URL` | Amadeus API base URL | `https://travel.api.amadeus.com` |
| `AMADEUS_DEFAULT_ORIGIN` | Default origin IATA code | `LHR` |
| `AMADEUS_CURRENCY` | Requested result currency | `GBP` |
| `AMADEUS_MAX_OFFERS` | Maximum offers requested | `50` |

The committed default base URL is the production host. A developer intending to use a different Amadeus environment must configure the appropriate base URL and matching credentials explicitly.

After changing environment configuration in a cached Laravel deployment, clear/rebuild the configuration cache through the normal deployment process.

## Relevant persistence model

### `airports`

Local airport catalogue containing unique three-letter IATA codes, names, cities, countries, and an active flag. The committed seed JSON contains a deliberately limited catalogue rather than the complete Amadeus location inventory.

### `destinations`

CMS destinations can carry a three-letter `airport_code`. Destination-led searches use this code and ignore a submitted destination airport.

### `flights`

CMS promotional cards contain destination/airline relationships, origin/destination labels, Economy/Business class, a static price, ordering, publication, and active state.

These rows only help customers enter a search. They have no relationship to an Amadeus offer ID and are not booking records.

### Missing booking-domain persistence

There are no models or migrations for:

- search quotes or offer snapshots;
- booking attempts;
- travellers/passengers or contacts;
- payments, refunds, or payment events;
- Amadeus orders or PNRs;
- tickets or documents;
- booking status history, audit events, or reconciliation.

## UI and implementation mismatches to be aware of

The public `home.blade.php`, `flights.blade.php`, and `destination.blade.php` templates contain claims such as secure payment processing, instant online booking/confirmation, accepted payment methods, and baggage being shown during booking. Those capabilities are not implemented by the current application flow.

The admin dashboard's booking and revenue values are hard-coded to zero, and **Manage Bookings** links to `#`; it is a placeholder rather than a booking console.

The result-page update form also exposes fewer fields than the initial search form. It retains trip type and destination but currently exposes only origin, destination, dates, and adults. Updating a search that originally included children, infants, a non-economy cabin, or non-stop filtering will omit those values, causing the service defaults to be applied.

## Test coverage and verification boundary

The repository includes tests for airport administration/service behaviour, flight-card administration, and some generated search URLs. It currently has no focused automated tests for:

- `FlightSearchRequest`;
- `FlightSearchController` success/failure responses;
- criteria normalization;
- Amadeus OAuth token caching and refresh;
- Flight Offers Search parameters;
- Amadeus response mapping;
- provider errors and timeouts;
- the full browser-to-results journey.

No live Amadeus search or booking capability should be inferred from unrelated passing tests. Live availability also depends on the configured Amadeus account, credentials, environment, products, and provider response.

## Main code map

| Responsibility | File |
| --- | --- |
| Public route definitions | `routes/web.php` |
| Search validation | `app/Http/Requests/FlightSearchRequest.php` |
| Search orchestration and error fallback | `app/Http/Controllers/FlightSearchController.php` |
| Criteria normalization and offer mapping | `app/Services/Amadeus/FlightSearchService.php` |
| OAuth and Amadeus HTTP calls | `app/Services/Amadeus/AmadeusClient.php` |
| Airport lookup/normalization | `app/Services/AirportService.php` |
| Airport JSON endpoints | `app/Http/Controllers/AirportSearchController.php` |
| Main public search form | `resources/views/partials/flight-search-form.blade.php` |
| Search results and phone handoff | `resources/views/flights/search.blade.php` |
| Airport autocomplete behaviour | `resources/js/airport-autocomplete.js` |
| Date-range behaviour | `resources/js/flight-date-range.js` |
| Amadeus/environment configuration | `config/services.php`, `.env.example` |
| CMS offer-card URL construction | `app/Models/Flight.php`, `app/Models/Destination.php` |
| Airport and CMS schema | `database/migrations/` |

## Boundary for future booking work

A true online booking flow must not submit the display-mapped result directly to Flight Create Orders. At minimum, it would need a server-owned booking attempt, a securely retained provider offer, server-side repricing/validation, explicit handling of returned booking requirements, traveller/contact capture, payment orchestration, idempotency and concurrency controls, durable order/PNR state, failure recovery, and reconciliation.

Those items describe the missing boundary; they are not implemented or implied by the current search integration.
