# Airlines Management System — Generated Backend

## Overview

This is a **FastAPI-based backend** for the **Airlines Management System**, a streamlined web application designed to manage core airline operations including flight scheduling, aircraft management, passenger bookings, and crew assignments.

The system supports **4 user roles** (Administrator, Flight Manager, Booking Agent, Crew Member) and manages **10 core entities** across **5 functional modules**:

- **Aircraft Management** — Aircraft fleet and seat configurations
- **Airport & Route Management** — Airports and flight routes
- **Flight Management** — Flight scheduling, status, and pricing
- **Crew Management** — Crew members and flight assignments
- **Booking Management** — Passenger information and flight bookings

This generated backend provides:
- Full CRUD operations for all entities
- Advanced detail endpoints with eager loading for related data
- Specialized endpoints for flight search, status updates, cancellations, and schedule queries
- Batch write services for complex operations (e.g., cancel flight and all bookings)
- Comprehensive validation and business rule enforcement
- In-memory data storage (ready for database integration)

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer and runner)

## Install uv

Install `uv` using the official installation script:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

The project uses `uv` for dependency management. Install all required packages:

```bash
uv pip install fastapi uvicorn pydantic python-multipart
```

Or if you have a `requirements.txt`:

```bash
uv pip install -r requirements.txt
```

## Run the Backend

Start the FastAPI development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at:
- **Base URL:** `http://localhost:8000`
- **Interactive API Docs:** `http://localhost:8000/docs`
- **Alternative Docs:** `http://localhost:8000/redoc`

## API Docs

Once the server is running, visit `http://localhost:8000/docs` to explore the interactive **Swagger UI** documentation. You can:

- Browse all available endpoints
- Test API calls directly from the browser
- View request/response schemas
- See validation rules and examples

### Key Endpoint Categories

**Aircraft Management**
- `GET /aircraft` — List all aircraft
- `POST /aircraft` — Create new aircraft
- `GET /aircraft/{id}` — Get aircraft by ID
- `GET /aircraft/{id}/details` — Get aircraft with seats and flights
- `PUT /aircraft/{id}` — Update aircraft
- `DELETE /aircraft/{id}` — Delete aircraft

**Flight Management**
- `GET /flights` — List all flights
- `POST /flights` — Create new flight
- `GET /flights/{id}/details` — Get flight with route, aircraft, bookings, and crew
- `GET /flights/search` — Search flights by origin, destination, and date
- `POST /flights/{id}/update-status` — Update flight status
- `POST /flights/{id}/cancel` — Cancel flight and all bookings
- `GET /flights/{id}/passenger-manifest` — Get passenger list for flight

**Booking Management**
- `GET /bookings` — List all bookings
- `POST /bookings` — Create new booking
- `GET /bookings/{id}/details` — Get booking with passenger, flight, seat, and fare details
- `POST /bookings/{id}/cancel` — Cancel booking
- `POST /bookings/{id}/change-seat` — Change seat assignment
- `POST /bookings/{id}/change-flight` — Change to different flight

**Crew Management**
- `GET /crew-members` — List all crew members
- `POST /crew-members` — Create new crew member
- `GET /crew-members/{id}/details` — Get crew member with flight assignments
- `GET /crew-members/{id}/schedule` — Get crew member schedule for date range

**Other Endpoints**
- `GET /airports` — List all airports
- `GET /routes` — List all routes
- `GET /passengers/{id}/details` — Get passenger with booking history
- `GET /dashboard/metrics` — Get system metrics and statistics

## OpenAPI JSON

The OpenAPI specification is available at:

```
http://localhost:8000/openapi.json
```

You can use this JSON file to:
- Generate client SDKs in various languages
- Import into API testing tools (Postman, Insomnia)
- Generate documentation in other formats

## Project Files

```
.
├── main.py                          # FastAPI application entry point
├── models/
│   ├── aircraft.py                  # Aircraft and Seat models
│   ├── airport.py                   # Airport and Route models
│   ├── flight.py                    # Flight and FareClass models
│   ├── crew.py                      # CrewMember and FlightCrewAssignment models
│   ├── booking.py                   # Passenger and Booking models
│   └── enums.py                     # All enum definitions
├── routers/
│   ├── aircraft.py                  # Aircraft endpoints
│   ├── airports.py                  # Airport and Route endpoints
│   ├── flights.py                   # Flight endpoints
│   ├── crew.py                      # Crew endpoints
│   ├── bookings.py                  # Booking and Passenger endpoints
│   └── dashboard.py                 # Dashboard and metrics endpoints
├── services/
│   ├── aircraft_service.py          # Aircraft business logic
│   ├── flight_service.py            # Flight business logic
│   ├── booking_service.py           # Booking business logic
│   ├── crew_service.py              # Crew business logic
│   └── validation_service.py        # Validation and business rules
├── storage/
│   └── in_memory_store.py           # In-memory data storage
└── requirements.txt                 # Python dependencies
```

## Example Workflow

### 1. Create an Airport

```bash
curl -X POST "http://localhost:8000/airports" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "JFK",
    "name": "John F. Kennedy International Airport",
    "city": "New York",
    "country": "USA",
    "timezone": "America/New_York",
    "latitude": 40.6413,
    "longitude": -73.7781
  }'
```

### 2. Create an Aircraft

```bash
curl -X POST "http://localhost:8000/aircraft" \
  -H "Content-Type: application/json" \
  -d '{
    "registration_number": "N12345",
    "model": "Boeing 737-800",
    "manufacturer": "Boeing",
    "total_seats": 189,
    "year_manufactured": 2020,
    "status": "Active"
  }'
```

### 3. Create a Route

```bash
curl -X POST "http://localhost:8000/routes" \
  -H "Content-Type: application/json" \
  -d '{
    "origin_airport_id": "<jfk_airport_id>",
    "destination_airport_id": "<lax_airport_id>",
    "distance_km": 3983,
    "estimated_duration_minutes": 360,
    "status": "Active"
  }'
```

### 4. Create a Flight

```bash
curl -X POST "http://localhost:8000/flights" \
  -H "Content-Type: application/json" \
  -d '{
    "flight_number": "AA100",
    "route_id": "<route_id>",
    "aircraft_id": "<aircraft_id>",
    "scheduled_departure": "2024-06-15T08:00:00Z",
    "scheduled_arrival": "2024-06-15T14:00:00Z",
    "base_fare": 299.99,
    "status": "Scheduled"
  }'
```

### 5. Search for Flights

```bash
curl -X GET "http://localhost:8000/flights/search?origin=JFK&destination=LAX&date=2024-06-15"
```

### 6. Get Flight Details with Related Data

```bash
curl -X GET "http://localhost:8000/flights/<flight_id>/details"
```

This returns the flight with:
- Route information (origin/destination airports)
- Aircraft details
- All bookings
- Assigned crew members

### 7. Create a Passenger

```bash
curl -X POST "http://localhost:8000/passengers" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "email": "john.doe@example.com",
    "phone": "+1234567890",
    "date_of_birth": "1985-03-15",
    "passport_number": "AB123456",
    "nationality": "USA"
  }'
```

### 8. Create a Booking

```bash
curl -X POST "http://localhost:8000/bookings" \
  -H "Content-Type: application/json" \
  -d '{
    "passenger_id": "<passenger_id>",
    "flight_id": "<flight_id>",
    "fare_class_id": "<fare_class_id>",
    "booking_status": "Confirmed",
    "payment_status": "Completed",
    "payment_method": "Credit Card"
  }'
```

### 9. Get Booking Details

```bash
curl -X GET "http://localhost:8000/bookings/<booking_id>/details"
```

### 10. Update Flight Status

```bash
curl -X POST "http://localhost:8000/flights/<flight_id>/update-status" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "Boarding"
  }'
```

## Next Steps

This generated backend provides a solid foundation. To make it production-ready, consider:

### 1. **Database Persistence**
- Replace in-memory storage with a real database (PostgreSQL, MySQL, SQLite)
- Integrate SQLAlchemy ORM for database operations
- Add database migrations using Alembic
- Implement connection pooling and transaction management

### 2. **Authentication & Authorization**
- Add JWT-based authentication
- Implement role-based access control (RBAC) for the 4 user roles
- Secure endpoints based on user permissions
- Add API key authentication for external integrations

### 3. **Code Organization**
- Split large router files into smaller, focused modules
- Move business logic from routers to dedicated service classes
- Separate data models (Pydantic) from database models (SQLAlchemy)
- Create a proper dependency injection system

### 4. **Testing**
- Add unit tests for services and business logic
- Create integration tests for API endpoints
- Implement test fixtures and factories
- Add test coverage reporting
- Set up continuous integration (CI) pipeline

### 5. **Additional Enhancements**
- Add logging and monitoring (structured logging, APM)
- Implement rate limiting and request throttling
- Add caching for frequently accessed data (Redis)
- Set up background tasks for notifications (Celery, RQ)
- Add API versioning strategy
- Implement comprehensive error handling and custom exceptions
- Add data validation middleware
- Create database indexes for performance optimization
- Add API documentation with examples and use cases
- Implement health check and readiness endpoints

### 6. **Business Features**
- Add email/SMS notifications for booking confirmations
- Implement real-time flight status updates
- Add payment gateway integration
- Create reporting and analytics endpoints
- Implement seat map visualization data
- Add loyalty program management
- Create automated crew scheduling optimization

---

**Generated by FastAPI Backend Generator**  
Ready to deploy and extend for your airline management needs!
