# Kabayan Flights Booking Engine Implementation Plan

**Status:** Proposed; no booking-engine code has been implemented by this plan

**Repository baseline inspected:** `develop` at `afbd507` on 24 September 2026

**Scope:** Flight shopping, checkout, customer payment, Amadeus reservation/PNR creation, ticketing state, operations, and post-booking foundations

## 1. Executive decision

Kabayan Flights can be developed into an online booking platform, but Amadeus and Stripe keys alone do not prove that a production booking can be completed.

The safe implementation sequence is:

1. confirm the exact Amadeus Enterprise products, office/PCC, fare sources, reservation and ticketing capabilities enabled for Kabayan;
2. persist a server-owned offer and reprice it with Amadeus;
3. collect every traveller/contact field required by that priced offer;
4. authorize the customer payment without immediately settling it, when the selected Stripe payment method supports separate authorization and capture;
5. revalidate the price and create the Amadeus order/PNR under a per-booking lock;
6. capture the authorized payment only after the reservation succeeds;
7. confirm separately whether the reservation is merely held, queued for ticketing, or actually ticketed;
8. reconcile Stripe, Amadeus, and the local database continuously.

The public Amadeus material describes the basic sequence as Search -> Price -> Create Orders -> Order Management. It also says Enterprise access is granted per request and may have special requirements. Therefore Kabayan's signed Enterprise documentation and entitlement list, not the public Self-Service examples, must be the final API contract. See the [Amadeus API FAQ](https://admin.developers.amadeus.com/self-service/apis-docs/guides/developer-guides/faq/) and [official booking scenario](https://admin.developers.amadeus.com/self-service/apis-docs/guides/developer-guides/developer-tools/postman/).

## 2. Current implemented state

The existing application stops at search and telephone handoff:

- `GET /flights/search` invokes `FlightSearchController`, `FlightSearchService`, and `AmadeusClient`.
- The only live shopping request is `GET /v2/shopping/flight-offers`.
- OAuth client credentials are cached, and a `401` causes one token refresh and retry.
- Each Amadeus offer is converted into a display-only array. The full provider offer, traveller pricing, fare details, baggage, `bookingRequirements`, and other order inputs are discarded.
- The result page renders a price and **Call to Book** link. It has no offer-selection action.
- There are no booking, quote, traveller, payment, refund, order, PNR, ticket, webhook-event, audit-event, or reconciliation tables.
- `flights`, `airlines`, and `booking_airlines` are catalogue/CMS data. They are not live reservations.
- Laravel is already configured to use database-backed queues and cache by default, but queue jobs are not configured globally for `after_commit` dispatch.
- The local `.env` contains non-empty Amadeus client ID, client secret and URL entries, plus Stripe key and secret entries. Their values and entitlements were not tested. No Stripe webhook-secret entry is present.
- `config/services.php` does not contain Stripe configuration and `composer.json` does not include the Stripe PHP SDK.

The existing current-state documentation is in `docs/flight-booking-amadeus.md`.

## 3. Definition of done

A customer booking is complete only when the application can prove all of the following:

- the selected offer was repriced on the server and was still available;
- the displayed and charged amount/currency came from the same accepted server-side quote plus an auditable Kabayan fee/markup calculation;
- required traveller, contact, document, and payment fields were collected from Amadeus `bookingRequirements` and Kabayan policy;
- Stripe confirms an authorized or captured payment through a verified server-side response/webhook;
- Amadeus returned an order identifier and reservation locator/PNR;
- the local booking stores whether the reservation is held, queued, ticketing pending, ticketed, cancelled, or failed;
- ticket document numbers are present before the application says **ticketed**;
- retries, duplicate clicks, duplicate webhooks, timeouts, and worker restarts cannot create duplicate charges or duplicate orders;
- paid-without-booking and booked-without-payment cases enter automatic compensation or an actionable operations queue;
- an operator can see the complete audit timeline and reconcile the booking with both providers.

`PNR created`, `payment captured`, and `ticket issued` are different facts and must never be represented by one generic `confirmed` flag.

## 4. Gate 0: evidence required before booking development

No production-order code should be designed against guessed Enterprise fields. Obtain a sanitized copy of the account-specific documentation or an entitlement/export from the Amadeus account manager.

| Area | Evidence to obtain | Why it blocks production design |
| --- | --- | --- |
| Enterprise products | Exact API names, versions, endpoints, schemas, environments, and operations enabled for Kabayan | Enterprise access is product-specific; a working search token does not prove Price, Order, Ticket, Cancel, or Refund access. |
| Office setup | Office ID/PCC, source/profile, queuing office, allowed validating carriers, and fare sources | These determine content, ownership, routing, and how an order is serviced. |
| Ticketing | IATA/BSP authority or consolidator agreement, ticketing responsibility, time limits, queues, and permitted agreement values | A PNR is not an issued ticket. Payment must be sequenced around the real ticketing arrangement. |
| Supplier settlement | How Kabayan funds the airline/consolidator and what Amadeus payment data is required | Stripe collects money from the customer; it does not automatically pay the airline or consolidator. |
| Order lifecycle | Retrieve, cancel, void, refund, exchange, split-PNR, schedule-change and disruption capabilities | Post-booking promises must match the contracted API/office workflow. |
| Provider behaviour | Rate limits, timeout guidance, retry rules, request IDs, duplicate-order protection, queues/events, and retention | Required for safe idempotency and recovery. |
| Test approval | Approved test travellers, routes, cards, order cases, cancellation cases, and whether test bookings affect inventory | Prevents unsafe trial reservations and establishes an evidence-based contract suite. |
| Stripe account | Legal entity, settlement currencies, allowed payment methods, manual-capture support, Radar policy, webhook endpoint, and refund/dispute process | Payment methods do not all have the same authorization/capture semantics. |
| Commercial rules | Markup/service fee, VAT/tax treatment, currency conversion, price-change tolerance, and refund fees | The amount must be calculated once on the server and explained to the customer. |
| Customer policy | Guest/account checkout, supported markets, passenger-document rules, terms acceptance, privacy retention, cancellation/support SLA | Drives validation, storage, consent, and customer communications. |

The public Amadeus FAQ explicitly separates customer payment from payment to the consolidator/airline and states that Enterprise capabilities are account-specific. Kabayan must get its own contract answer for each row rather than copying the Self-Service ticketing model.

## 5. Target booking flow

```mermaid
sequenceDiagram
    actor Customer
    participant Web as Kabayan browser
    participant App as Laravel booking domain
    participant DB as Database
    participant Stripe
    participant Amadeus
    participant Ops as Booking operations

    Customer->>Web: Search and select an offer
    Web->>App: POST selection using opaque quote token
    App->>DB: Load server-owned raw offer
    App->>Amadeus: Flight Offers Price
    Amadeus-->>App: Priced offer + requirements + expiry/rules
    App->>DB: Save immutable priced snapshot and amount
    App-->>Web: Checkout fields derived from requirements
    Customer->>Web: Submit travellers, contact, consent, payment method
    Web->>App: Create/confirm payment for booking reference
    App->>DB: Lock booking and validate quote
    App->>Stripe: Authorize server-calculated amount
    Stripe-->>App: requires_capture or failure
    App->>Amadeus: Final price validation
    alt Price unchanged and available
        App->>Amadeus: Create flight order
        Amadeus-->>App: Order ID + PNR + ticketing state
        App->>Stripe: Capture authorization
        alt Capture succeeds
            App->>DB: Mark paid and reservation created
            App-->>Web: Reservation confirmation
        else Capture fails or is uncertain
            App->>DB: Mark compensation/manual review
            App->>Amadeus: Cancel/void if contract permits
            App->>Ops: Urgent booked-without-payment case
        end
    else Price changed or booking failed
        App->>Stripe: Cancel authorization
        App->>DB: Store failure/price change
        App-->>Web: Request explicit customer acceptance/retry
    end
    App->>Amadeus: Retrieve order/ticket status asynchronously
    App->>DB: Reconcile PNR, tickets, and provider states
```

### Meaning of “successful payment”

For the initial card-only flow, the recommended meaning is **successful authorization** before PNR creation and **successful capture** after PNR creation. Stripe documents that a manually captured PaymentIntent reaches `requires_capture` after authorization and can then be captured or cancelled. See [Confirm a PaymentIntent](https://docs.stripe.com/api/payment_intents/confirm) and [Capture a PaymentIntent](https://docs.stripe.com/api/payment_intents/capture).

This recommendation is conditional on:

- Kabayan's selected payment methods supporting manual capture;
- the Stripe authorization window covering the order operation;
- Amadeus allowing the reservation/ticketing sequence agreed with Kabayan;
- the price remaining within the authorized amount.

If the final price increases, do not silently charge more. Cancel/release the authorization and ask the customer to accept and authorize the new total. If the final price decreases, capture only the accepted lower total and record the difference.

If Kabayan insists on full capture before order creation, the engine needs an automatic void/refund path, a funded refund policy, and an operations SLA for paid-without-booking cases. That is a supported fallback design, not the recommended default.

## 6. Booking state model

Use explicit, append-only transitions. A suggested top-level state model is:

```text
draft
  -> pricing
  -> priced
  -> passenger_details_complete
  -> payment_pending
  -> payment_action_required
  -> payment_authorized
  -> order_creating
  -> reservation_created
  -> payment_capturing
  -> paid
  -> ticketing_pending
  -> ticketed
```

Expected exception/terminal states:

```text
quote_expired
price_changed
sold_out
payment_failed
payment_cancelled
order_failed
order_status_unknown
capture_failed
compensation_pending
manual_review
cancel_pending
cancelled
refund_pending
partially_refunded
refunded
expired
```

Rules:

- a booking has one current state plus an immutable event history;
- transitions occur through one domain service, never arbitrary controller updates;
- provider status and local status are stored separately;
- `reservation_created` requires the Amadeus order ID and PNR/locator;
- `paid` requires provider-confirmed captured funds, not a browser redirect;
- `ticketed` requires ticket/document numbers or the account-specific equivalent;
- unknown outcomes must be retrieved/reconciled before retrying an external create call.

## 7. Persistence design

Amounts are integers in the currency's minor unit. Provider IDs receive unique indexes. Sensitive payloads are encrypted and access-controlled; logs contain references, not raw personal data.

| Table/aggregate | Important fields and purpose |
| --- | --- |
| `flight_searches` | Public opaque token, normalized criteria, expiry, owner/session, provider request ID. |
| `flight_offer_snapshots` | Search ID, provider offer ID, raw offer JSON, hash, displayed total/currency, expiry. Immutable source for selection. |
| `flight_quotes` | Booking ID, priced-offer JSON, offer hash, supplier/base/tax/fee/grand-total minor amounts, currency, `bookingRequirements`, fare rules summary, expires/accepted timestamps. |
| `bookings` | ULID/public reference, user/guest ownership, independent local/payment/order/ticketing statuses, current quote, version, consent timestamps. |
| `booking_travellers` | Provider traveller ID, type, names, DOB, gender only when required, encrypted document data, loyalty references. |
| `booking_contacts` | Booking contact email/phone/address and required emergency/invoice contacts. |
| `booking_segments` | Immutable itinerary snapshot shown at purchase time, not a foreign key to CMS `flights`. |
| `payment_attempts` | Unique PaymentIntent ID, amount/currency, capture method, status, idempotency key, provider request/error references. No PAN or CVC. |
| `flight_order_attempts` | Request fingerprint, status, provider request ID, Amadeus order ID, PNR, sanitized response/error, started/completed timestamps. |
| `tickets` | Traveller/segment links, document number, issued/void/refund state and timestamps. |
| `refunds` | Payment and supplier-side refund references, amount, reason, independent provider statuses. |
| `booking_events` | Append-only actor, transition, reason, correlation ID, safe metadata, timestamp. |
| `webhook_events` | Unique Stripe event ID, signature-verified receipt time, processing status, attempts and error. |
| `outbox_messages` | After-commit jobs/events to prevent a committed booking change from losing its follow-up work. |
| `reconciliation_checks` | Scheduled Stripe/Amadeus comparisons, mismatches, retry/manual-review state. |

The raw search/pricing snapshots are needed because the current display mapper throws away fields required by the next Amadeus call. The browser must never be trusted to send back a price or provider payload as the source of truth.

## 8. Laravel module boundary

Keep provider details behind interfaces so the booking domain is testable and Enterprise contract changes remain localized.

```text
app/Domain/Booking/
  Actions/
  Data/
  Enums/
  Events/
  Exceptions/
  Models/
  Policies/
  Services/

app/Integrations/Amadeus/
  AmadeusAuthenticator
  FlightShoppingGateway
  FlightPricingGateway
  FlightOrderGateway
  TicketingGateway                 # only if entitled
  DTOs/Mappers/ErrorClassifier

app/Integrations/Stripe/
  PaymentGateway
  StripeWebhookHandler
  StripeErrorClassifier

app/Jobs/Booking/
  CreateFlightOrder
  CaptureAuthorizedPayment
  CompensateFailedBooking
  ReconcileBooking
  SendBookingConfirmation
```

Controllers validate transport input and call domain actions. They must not assemble Amadeus order bodies or perform multi-provider orchestration directly.

Suggested public endpoints, subject to the guest/account decision:

| Method | Route | Responsibility |
| --- | --- | --- |
| `POST` | `/flights/offers/{opaqueToken}/price` | Load server snapshot, reprice, create booking/quote. |
| `GET` | `/bookings/{reference}/checkout` | Render fields required by the current quote. |
| `PUT` | `/bookings/{reference}/travellers` | Validate/save passengers and contacts. |
| `POST` | `/bookings/{reference}/payment-intent` | Create/reuse one server-priced PaymentIntent. |
| `GET` | `/bookings/{reference}/processing` | Show durable state while webhook/jobs complete. |
| `GET` | `/bookings/{reference}/confirmation` | Show reservation/payment/ticketing facts separately. |
| `POST` | `/stripe/webhook` | Verify signature, deduplicate, persist, dispatch processing. |

All booking routes use opaque references, ownership/guest-access controls, CSRF where applicable, rate limits, and an idempotency token for mutations.

## 9. Amadeus API adoption matrix

“Use all possible APIs” should mean all APIs that add customer or operational value and are actually entitled, not calling every catalogue endpoint.

| Capability | Proposed phase | Purpose | Gate |
| --- | --- | --- | --- |
| Flight Offers Search | Core; refactor existing | Obtain complete server-owned offers; consider POST if the Enterprise contract/content requires it. | Confirm Enterprise schema/content sources. |
| Flight Offers Price | Core | Confirm price/availability, requirements, fees, baggage/fare data immediately before acceptance/order. | Required. |
| Flight Create Orders / Enterprise book service | Core | Create reservation/order and obtain order identifiers/PNR. | Required plus office/ticketing agreement. |
| Flight Order Management / retrieve | Core | Resolve unknown outcomes and reconcile reservation/ticket state. | Required for production safety. |
| Cancel/void order | Core operations | Compensate failed payment and support eligible pre-ticket cancellation. | Exact entitlement and ticketing rules. |
| Structured fare rules | Core customer disclosure | Show change/refund restrictions before payment. | Use the Enterprise product actually enabled. |
| Branded Fares Upsell | Phase 2 | Let customers compare fare families and inclusions. | Airline coverage and pricing flow. |
| Seatmap Display | Phase 2 | Display/select available seats when supported. | Carrier support, seat price/order mapping. |
| Additional baggage/ancillaries | Phase 2 | Price and book supported extras through the priced offer/order. | Contract, fulfilment and refund behaviour. |
| Ticket issuance/retrieve/void/refund | Phase 2 or core if enabled | Automate ticket documents and after-sales operations. | Kabayan IATA/BSP/consolidator workflow and Enterprise product. |
| Flight Availabilities Search | Later/operational | Rich availability/booking-class use cases, not required for a basic consumer checkout. | Product need and entitlement. |
| Schedule/status/check-in links | Post-booking enhancement | Operational notifications and manage-trip experience. | Separate data freshness and notification design. |
| Price analysis/choice prediction/inspiration | Merchandising later | Ranking and discovery; not part of transactional correctness. | Demonstrated product value and consent/transparency where relevant. |

The [official Amadeus tutorial catalogue](https://admin.developers.amadeus.com/self-service/apis-docs/guides/developer-guides/resources/) lists these public API families, but Enterprise equivalents and payloads must be mapped from Kabayan's own documentation.

## 10. Stripe design

- Use the official Stripe PHP SDK and pin both the SDK and Stripe API version.
- Use Stripe Payment Element/Stripe.js so card details never pass through Laravel.
- Create exactly one PaymentIntent per booking payment attempt and derive its amount/currency only from the accepted server quote.
- Default the first release to payment methods verified to support the chosen manual-capture flow; do not enable every Dashboard method automatically.
- Send a stable idempotency key for every Stripe mutation. Stripe documents idempotent POST retries in [Idempotent requests](https://docs.stripe.com/api/idempotent_requests).
- Treat webhooks as authoritative asynchronous input, verify the signature against a dedicated webhook secret, store event IDs uniquely, and acknowledge quickly before queued processing.
- Never fulfill from the browser return URL alone. Stripe recommends server-side webhook handling because the browser can close or be manipulated; see [Payment Element migration and post-payment events](https://docs.stripe.com/payments/payment-element/migration).
- Implement authorization cancellation, full/partial capture, refunds, disputes, and an operator-visible mismatch state.
- Store Stripe IDs, amounts, statuses, request IDs, and safe error codes; never store PAN, CVC, or the PaymentIntent client secret in logs.

Before Stripe implementation, add and deploy a distinct `STRIPE_WEBHOOK_SECRET`; the current local environment does not define one.

## 11. Concurrency, idempotency, and recovery

### Local controls

- Create the local booking and immutable quote before any payment/order side effect.
- Use a database transaction plus a row/advisory lock around each state transition.
- Use an optimistic `version` column so stale browser requests fail safely.
- Give payment attempts and flight-order attempts unique request fingerprints.
- Disable repeated checkout actions in the UI, but do not rely on the UI for correctness.
- Dispatch outbox/queue work after the database commit. Do not rely on the current global `after_commit = false` default.

### External call rules

- Stripe mutations always use provider idempotency keys.
- For Amadeus order creation, use the account's supported idempotency/correlation mechanism if one exists.
- If an Amadeus create-order response times out, mark `order_status_unknown` and retrieve/search using the supported provider reference before retrying.
- Never blindly retry a non-idempotent order creation.
- Classify provider errors into validation, price change, sold out, authentication, rate limit, transient, permanent, and unknown-outcome groups.
- Persist provider request IDs and sanitized error details for support.

### Reconciliation

A scheduled command should select non-terminal and recently completed bookings, retrieve current Stripe and Amadeus state, compare them with local state, repair safe differences, and create an alert/manual-review item for unsafe differences. Required mismatch alerts include:

- Stripe authorized/captured but no Amadeus order;
- Amadeus order/PNR exists but Stripe is not captured;
- local ticketed state without ticket documents;
- provider cancellation/refund not reflected locally;
- webhook/job failures beyond retry policy;
- reservations nearing a ticketing or payment deadline.

## 12. Failure and compensation matrix

| Failure | Customer result | Automated action | Operations action |
| --- | --- | --- | --- |
| Price changed before authorization | Show new itemized total and require acceptance | Expire old quote/PaymentIntent | None unless repeated provider issue. |
| Authorization failed | Stay in checkout with safe decline guidance | Mark attempt failed; allow new attempt | Review fraud/processor patterns only. |
| Authorization succeeded, final price increased | Do not book at an unapproved higher amount | Cancel authorization; issue new quote | Review only if cancellation is uncertain. |
| Authorization succeeded, order sold out/failed | Explain no booking was created | Cancel authorization; reconcile release | Urgent if cancellation is uncertain. |
| Order timed out/unknown | Show processing, not failure or success | Retrieve/reconcile before any retry | Review after bounded retries. |
| Order created, capture failed | Do not claim paid/ticketed | Cancel/void order if permitted; retry only when safe | Highest-priority manual case. |
| Capture succeeded, local commit/webhook failed | Show processing from durable reference | Webhook/reconciliation repairs local state | Review if unresolved. |
| Ticket issuance fails after paid reservation | Show reservation and ticketing pending separately | Retry/retrieve under contract rules | Service and refund/rebook decision. |
| Cancellation succeeds but refund fails | Show cancellation and refund pending separately | Retry/reconcile Stripe refund | Finance queue. |

## 13. Security, privacy, and compliance workstream

- Minimize passport/document collection to what the itinerary and provider require.
- Encrypt sensitive traveller/document fields with a rotation plan; restrict decryption to booking roles.
- Redact names, DOBs, passports, tokens, raw payloads, and Stripe client secrets from application logs and error reporting.
- Store provider payloads on private storage or encrypted database columns with defined retention.
- Add policy-based access for customers, booking agents, finance, support, and administrators.
- Record the exact terms, fare rules, privacy notice, amount/currency, and customer consent version accepted at checkout.
- Use CSRF protection, strict request validation, rate limiting, CSP and secure headers; verify webhook signatures and reject replays.
- Complete PCI scope review based on Stripe Elements, UK GDPR/data-retention review, consumer/travel-contract review, and ATOL/IATA/BSP/consolidator review with qualified advisors before launch.
- Ensure confirmation wording distinguishes reservation, ticket issuance, and protected-package status; do not infer legal protection from code.

## 14. Operations console

The first production release needs an internal console, not only customer pages. It should provide:

- search by Kabayan reference, PNR, Amadeus order ID, Stripe PaymentIntent ID, email, and travel date;
- independent quote, payment, reservation, and ticketing statuses;
- itemized supplier price, Kabayan fee/markup, captured amount, refunded amount, and currency;
- traveller/segment/ticket summary with masked documents;
- chronological immutable booking events and provider request IDs;
- guarded actions for retrieve/reconcile, resend confirmation, cancel authorization, capture, cancel order, and refund;
- mandatory reason/audit entry for manual actions;
- queues for compensation pending, ticketing pending, refund pending, unknown outcomes, and approaching deadlines;
- role separation for booking operations, finance, and administrators.

## 15. Test and release strategy

### Automated layers

1. **Domain tests:** every allowed/forbidden state transition, amount arithmetic, price-change acceptance, ticketing semantics, and compensation decision.
2. **HTTP/validation tests:** offer token ownership/expiry, passenger requirements, authorization, CSRF, rate limits, and redaction.
3. **Provider contract tests:** sanitized real Enterprise fixtures for Search, Price, Requirements, Create, Retrieve, Cancel, Ticket and provider errors.
4. **Concurrency tests:** duplicate clicks, duplicate webhooks, two workers, lock expiry, retry after timeout, and stale quote versions.
5. **Stripe test-mode tests:** 3DS/action required, decline, manual authorization/capture, cancellation, webhook reordering/duplication, refund and dispute fixtures.
6. **Amadeus approved-environment tests:** price change, sold out, reservation success, retrieve, cancel, ticketing state, and unknown response recovery.
7. **Browser tests:** search -> select -> reprice -> passenger details -> payment -> processing -> confirmation, including accessibility and mobile paths.

### Release gates

- no live keys or personal data in fixtures, logs, source control, or screenshots;
- database migrations and rollbacks exercised on a production-like database;
- workers, scheduler, failed-job storage, alerts, and webhook endpoint verified in staging;
- reconciliation proves it can identify seeded mismatches;
- provider timeout/rate-limit tests pass without duplicate side effects;
- an explicitly approved end-to-end reservation/cancellation test passes in the correct Amadeus environment;
- finance/operations complete a failure drill for paid-without-booking and booked-without-payment;
- launch starts with restricted routes/carriers/payment methods and a small monitored pilot.

Passing mocked tests alone is not evidence that the Enterprise office can price, reserve, ticket, cancel, or refund a real itinerary.

## 16. Delivery phases and acceptance criteria

Calendar estimates should be made only after Gate 0 resolves the Enterprise contract and Kabayan business rules.

### Phase 0 — provider and business contract

Deliverables:

- entitlement/API matrix using Kabayan's actual Enterprise documentation;
- ticketing/settlement/payment sequence decision record;
- checkout field matrix generated from real `bookingRequirements` fixtures;
- business rules for fees, price changes, cancellations, refunds, guests, markets and currencies;
- approved test plan.

Exit: every Gate 0 row has an owner and written evidence; one end-to-end sanitized API scenario is understood.

### Phase 1 — transaction foundation

Deliverables:

- booking domain, migrations, enums/state machine, audit events, provider-attempt records;
- gateway interfaces and standardized provider error model;
- locks, idempotency keys, outbox, jobs, scheduler and observability baseline.

Exit: concurrency tests prove duplicate local mutations cannot create duplicate attempts.

### Phase 2 — offer selection and repricing

Deliverables:

- persist complete search offers behind opaque short-lived tokens;
- **Select flight** action;
- server-side Flight Offers Price integration;
- price/fare/baggage/requirements review and explicit price-change acceptance.

Exit: the browser cannot choose the amount/currency or alter the provider offer, and expired/changed/sold-out offers are handled.

### Phase 3 — travellers and checkout

Deliverables:

- dynamic traveller/contact/document validation based on priced requirements;
- itemized order summary, fare restrictions, consent and privacy handling;
- resumable guest/account checkout according to the approved decision.

Exit: a complete, validated, auditable order draft can be produced without payment.

### Phase 4 — Stripe authorization

Deliverables:

- Stripe SDK/config/API version, Payment Element, PaymentIntents and manual capture where supported;
- signed/deduplicated webhook ingestion;
- payment attempts, cancellation, capture/refund primitives and finance views.

Exit: Stripe test-mode scenarios and webhook reordering/duplication tests pass; no card data reaches Laravel.

### Phase 5 — Amadeus order and compensation orchestration

Deliverables:

- final price validation, Create Order, Retrieve, and pre-ticket cancel/void according to entitlement;
- payment authorization -> PNR -> capture orchestration;
- unknown-outcome recovery, compensation jobs, operator alerts and processing UI.

Exit: approved Amadeus environment proves successful and failure flows without duplicate orders or charges.

### Phase 6 — ticketing, confirmation and reconciliation

Deliverables:

- ticket-state/document retrieval or approved manual/consolidator handoff;
- customer email/page with reservation/payment/ticket facts;
- admin booking console, reconciliation command/dashboard, operational runbooks.

Exit: seeded cross-provider mismatches are detected, surfaced and resolved; support can operate without database edits.

### Phase 7 — advanced Enterprise capabilities

Add only after core reliability: fare-family upsell, seat selection, baggage/ancillaries, richer ticketing/after-sales automation, disruptions/status and merchandising APIs.

Exit: each capability has carrier coverage, pricing, fulfilment, refund, accessibility, observability, and support acceptance criteria.

### Phase 8 — controlled production rollout

Start with an allow-list of routes/carriers, card-based manually capturable methods, capped amounts and staffed operations. Expand only after reconciled production evidence shows stable bookings, capture, ticketing and cancellation.

## 17. Decisions needed from Kabayan before implementation

1. What exact Amadeus Enterprise API/product list, versions, and documentation were supplied to this account?
2. Does Kabayan issue tickets through its own IATA/BSP office, an Amadeus office, or a consolidator? Who owns and services the PNR?
3. Can ticket issuance be delayed until Stripe capture, and what is the reservation/ticketing time limit?
4. Which retrieve, cancel, void, ticket, refund, exchange, queue and notification operations are enabled?
5. Should checkout support guests, authenticated customers, or both?
6. What markets, currencies, passenger types, payment methods and maximum transaction values are in the first release?
7. How are markup/service fees, VAT, exchange rates and price changes calculated and disclosed?
8. Are seats, bags, fare-family upsells and loyalty numbers core launch scope or Phase 7?
9. What customer cancellation/refund policy and operational response times are approved?
10. Who staffs the manual-review queue when payment and Amadeus states disagree?

Do not send secrets in documentation or chat. The useful starting material is the sanitized Enterprise endpoint/schema pack, entitlement list, office/ticketing workflow, and representative success/error payloads.

## 18. Recommended immediate next step

Run a short Phase 0 contract workshop and produce one checked-in, secret-free `docs/amadeus-enterprise-contract.md` containing:

- enabled operation names and versions;
- base URLs/environments without credentials;
- required office/queue identifiers represented by placeholders;
- field-by-field Search -> Price -> Create -> Retrieve mapping;
- real sanitized `bookingRequirements` examples;
- ticketing/settlement sequence;
- retry/idempotency/unknown-outcome rules;
- approved test cases.

Only after that document is reviewed should Phase 1 migrations and interfaces be finalized. This avoids building a polished checkout around the wrong Enterprise contract.
