# B2B Flight Ticketing Platform

A multi-tenant B2B flight ticketing platform built with Spring Boot that enables non-IATA agencies to search, book, and issue flight tickets through a master IATA agency's Amadeus connection.

## Features

- 🔐 **OAuth 2.0 Authentication** with Keycloak and MFA support
- 👥 **Multi-tenant Architecture** with complete data isolation
- 💰 **Prepaid Wallet System** with atomic transactions
- ✈️ **Amadeus GDS Integration** for flight search, booking, and ticketing
- 📊 **Comprehensive Reporting** with CSV/PDF export
- 🔄 **Resilience Patterns** with circuit breakers and retry logic
- 📝 **Audit Logging** for all operations
- 🚀 **Horizontal Scaling** with stateless architecture
- 🔒 **Data Encryption** at rest and in transit
- 📈 **Health Monitoring** with Spring Boot Actuator

## Technology Stack

- **Java**: 17+
- **Framework**: Spring Boot 3.2.1
- **Database**: PostgreSQL 15+
- **Cache**: Redis 7
- **Message Queue**: RabbitMQ 3
- **Authentication**: Keycloak OAuth 2.0
- **API Integration**: Amadeus Self-Service APIs
- **Build Tool**: Maven
- **Testing**: JUnit 5, jqwik (Property-Based Testing), TestContainers
- **Containerization**: Docker, Kubernetes
- **Monitoring**: Spring Boot Actuator, Micrometer

## Quick Start

See [QUICKSTART.md](QUICKSTART.md) for a quick start guide.

For detailed developer setup with troubleshooting, see [Developer Setup Guide](docs/DEV-SETUP.md).

### Amadeus API Integration ✈️

Your application is **already integrated** with Amadeus API! Just add your credentials:

```bash
# Quick setup
./setup-amadeus.sh

# Test integration
./test-amadeus-integration.sh

# Try your first booking
./first-booking-tutorial.sh
```

📖 **Complete Guide**: [AMADEUS_INTEGRATION_README.md](AMADEUS_INTEGRATION_README.md)

### Prerequisites

- Docker and Docker Compose
- Java 17+ (for local development)
- Maven 3.8+ (for building)
- Amadeus API credentials (get free at https://developers.amadeus.com/)

## Getting Started

### 1. Start Infrastructure Services

Start PostgreSQL, Redis, RabbitMQ, and Keycloak using Docker Compose:

```bash
docker-compose up -d
```

This will start:
- PostgreSQL on port 5432
- Redis on port 6379
- RabbitMQ on port 5672 (Management UI on 15672)
- Keycloak on port 8080

### 2. Verify Services

Check that all services are running:

```bash
docker-compose ps
```

### 3. Build the Application

```bash
mvn clean install
```

### 4. Run the Application

```bash
mvn spring-boot:run
```

Or with a specific profile:

```bash
mvn spring-boot:run -Dspring-boot.run.profiles=dev
```

The application will start on port 8081 by default.

## Configuration

### Environment Profiles

- **dev**: Development environment (default)
- **test**: Testing environment
- **prod**: Production environment

### Environment Variables

For production deployment, set the following environment variables:

```bash
# Database
DATABASE_URL=jdbc:postgresql://your-db-host:5432/flight_platform
DATABASE_USERNAME=your-db-user
DATABASE_PASSWORD=your-db-password

# Redis
REDIS_HOST=your-redis-host
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password

# RabbitMQ
RABBITMQ_HOST=your-rabbitmq-host
RABBITMQ_PORT=5672
RABBITMQ_USERNAME=your-rabbitmq-user
RABBITMQ_PASSWORD=your-rabbitmq-password

# Keycloak
KEYCLOAK_REALM=your-realm
KEYCLOAK_AUTH_SERVER_URL=https://your-keycloak-server
KEYCLOAK_RESOURCE=your-client-id
KEYCLOAK_CLIENT_SECRET=your-client-secret

# Amadeus API
AMADEUS_CLIENT_ID=your-amadeus-client-id
AMADEUS_CLIENT_SECRET=your-amadeus-client-secret
```

## Testing

Run all tests:

```bash
mvn test
```

Run tests with coverage:

```bash
mvn test jacoco:report
```

## Accessing Services

- **Application**: http://localhost:8081
- **Swagger UI**: http://localhost:8081/swagger-ui.html
- **Actuator Health**: http://localhost:8081/actuator/health
- **Keycloak Admin**: http://localhost:8080 (admin/admin)
- **RabbitMQ Management**: http://localhost:15672 (flight_user/flight_pass)

## Documentation

- **[Amadeus Integration Guide](AMADEUS_INTEGRATION_README.md)**: Complete Amadeus API setup ✈️
- **[Quick Start Guide](QUICKSTART.md)**: Get started in minutes
- **[Developer Setup Guide](docs/DEV-SETUP.md)**: Complete setup with troubleshooting
- **[Deployment Guide](docs/DEPLOYMENT.md)**: Comprehensive deployment instructions
- **[API Documentation](docs/API_DOCUMENTATION.md)**: REST API reference
- **[Resilience Patterns](docs/RESILIENCE_PATTERNS.md)**: Circuit breakers and retry logic
- **[Transaction Management](docs/TRANSACTION_MANAGEMENT.md)**: Wallet and transaction handling
- **[Kubernetes Deployment](k8s/README.md)**: Production Kubernetes deployment

### Amadeus Integration Docs
- **[Integration Guide](docs/AMADEUS_INTEGRATION_GUIDE.md)**: Complete setup and configuration
- **[Quick Reference](docs/AMADEUS_QUICK_REFERENCE.md)**: Common commands and API calls
- **[First Booking Tutorial](docs/AMADEUS_FIRST_BOOKING_TUTORIAL.md)**: Step-by-step walkthrough

## Architecture

### High-Level Components

- **Authentication Service**: OAuth 2.0/OIDC with Keycloak
- **User Management**: Role-based access control (RBAC)
- **Agency Management**: Multi-tenant agency administration
- **Wallet Service**: Prepaid credit system with atomic transactions
- **Flight Service**: Amadeus API integration for flight search
- **Booking Service**: PNR creation and management
- **Ticketing Service**: Ticket issuance, void, and refund
- **Reporting Service**: Financial and transaction reports
- **Notification Service**: Email and in-app notifications
- **Audit Service**: Comprehensive audit logging

### Key Design Patterns

- **Multi-tenancy**: Complete data isolation per agency
- **Circuit Breaker**: Resilience for external API calls
- **Retry with Backoff**: Automatic retry for transient failures
- **Event-Driven**: Asynchronous processing with RabbitMQ
- **CQRS**: Separation of read and write operations
- **Repository Pattern**: Data access abstraction

## Deployment

### Docker Compose (Development)

```bash
# Start all services
docker-compose up -d

# View logs
docker-compose logs -f app

# Stop services
docker-compose down
```

### Docker (Production)

```bash
# Build image
docker build -t b2b-flight-platform:latest .

# Run container
docker run -d \
  -p 8081:8081 \
  -e SPRING_PROFILE=prod \
  -e AMADEUS_API_KEY=your_key \
  -e AMADEUS_API_SECRET=your_secret \
  b2b-flight-platform:latest
```

### Kubernetes (Production)

See [k8s/README.md](k8s/README.md) for detailed Kubernetes deployment instructions.

```bash
# Quick deployment
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/secret.yaml
kubectl apply -f k8s/postgres-deployment.yaml
kubectl apply -f k8s/redis-deployment.yaml
kubectl apply -f k8s/rabbitmq-deployment.yaml
kubectl apply -f k8s/keycloak-deployment.yaml
kubectl apply -f k8s/app-deployment.yaml
```

## Configuration

### Environment Variables

See [.env.example](.env.example) for all available environment variables.

**Required Variables:**
- `AMADEUS_API_KEY`: Amadeus API client ID
- `AMADEUS_API_SECRET`: Amadeus API client secret
- `ENCRYPTION_SECRET_KEY`: Base64-encoded encryption key

**Optional Variables:**
- `SPRING_PROFILE`: Active profile (dev/test/prod)
- `SERVER_PORT`: Application port (default: 8081)
- Database, Redis, RabbitMQ, Keycloak connection settings

### Generating Encryption Key

```bash
mvn exec:java -Dexec.mainClass="com.flightticket.util.EncryptionUtil" -Dexec.args="generateKey"
```

## Testing

### Run All Tests

```bash
mvn test
```

### Run Integration Tests

```bash
mvn verify -P integration-tests
```

### Run Property-Based Tests

```bash
mvn test -Dtest="**/*PropertyTest"
```

### Test Coverage

```bash
mvn test jacoco:report
# Report available at: target/site/jacoco/index.html
```

## API Documentation

### Swagger UI

Access interactive API documentation at: http://localhost:8081/swagger-ui.html

### OpenAPI Specification

Download OpenAPI JSON at: http://localhost:8081/api-docs

## Monitoring and Health Checks

### Health Endpoints

- **Liveness**: http://localhost:8081/actuator/health/liveness
- **Readiness**: http://localhost:8081/actuator/health/readiness
- **Full Health**: http://localhost:8081/actuator/health

### Metrics

- **Prometheus**: http://localhost:8081/actuator/prometheus
- **Metrics**: http://localhost:8081/actuator/metrics

## Security

- **Authentication**: OAuth 2.0/OIDC with Keycloak
- **Authorization**: Role-based access control (RBAC)
- **MFA**: Multi-factor authentication for admin roles
- **Encryption**: AES-256 for sensitive data at rest
- **TLS**: All connections encrypted in transit
- **Audit Logging**: All operations logged for compliance

## User Roles

- **SUPER_ADMIN**: Full system access, agency management
- **AGENCY_ADMIN**: Agency administration, user management
- **HR_USER**: Employee management within agency
- **FINANCE_USER**: Financial reports, wallet management
- **AGENT**: Flight search, booking, ticketing operations

## Accessing Services

- **Application**: http://localhost:8081
- **Keycloak Admin**: http://localhost:8080 (admin/admin)
- **RabbitMQ Management**: http://localhost:15672 (flight_user/flight_pass)
- **Actuator Health**: http://localhost:8081/actuator/health

## Project Structure

```
src/
├── main/
│   ├── java/
│   │   └── com/flightticket/
│   │       ├── aspect/           # AOP aspects for logging
│   │       ├── client/           # External API clients (Amadeus)
│   │       ├── config/           # Configuration classes
│   │       ├── controller/       # REST controllers
│   │       ├── dto/              # Data transfer objects
│   │       ├── exception/        # Custom exceptions
│   │       ├── health/           # Custom health indicators
│   │       ├── metrics/          # Business metrics
│   │       ├── model/            # JPA entities and enums
│   │       ├── repository/       # Data access repositories
│   │       ├── security/         # Security filters and aspects
│   │       ├── service/          # Business logic services
│   │       └── util/             # Utility classes
│   └── resources/
│       ├── application.yml       # Main configuration
│       ├── application-dev.yml   # Dev configuration
│       ├── application-test.yml  # Test configuration
│       ├── application-prod.yml  # Prod configuration
│       ├── logback-spring.xml    # Logging configuration
│       └── db/migration/         # Flyway migrations
└── test/
    └── java/
        └── com/flightticket/     # Test classes
            ├── integration/      # Integration tests
            └── service/          # Unit tests

k8s/                              # Kubernetes manifests
├── namespace.yaml
├── configmap.yaml
├── secret.yaml
├── postgres-deployment.yaml
├── redis-deployment.yaml
├── rabbitmq-deployment.yaml
├── keycloak-deployment.yaml
├── app-deployment.yaml
├── ingress.yaml
└── README.md

docs/                             # Documentation
├── DEPLOYMENT.md                 # Deployment guide
├── API_DOCUMENTATION.md          # API reference
├── RESILIENCE_PATTERNS.md        # Resilience patterns
└── TRANSACTION_MANAGEMENT.md     # Transaction handling

.kiro/specs/                      # Feature specifications
└── b2b-flight-ticketing-platform/
    ├── requirements.md           # Requirements document
    ├── design.md                 # Design document
    └── tasks.md                  # Implementation tasks
```

## Contributing

1. Follow the existing code style
2. Write tests for new features
3. Update documentation
4. Submit pull requests for review

## License

[Add your license here]

## Support

For issues and questions:
- Check [Deployment Guide](docs/DEPLOYMENT.md)
- Review [API Documentation](docs/API_DOCUMENTATION.md)
- Check application logs
- Review Swagger documentation

## Troubleshooting

### Common Issues

**Port Already in Use**
```bash
# Change port in docker-compose.yml or use:
SERVER_PORT=8082 mvn spring-boot:run
```

**Database Connection Failed**
```bash
# Check PostgreSQL is running
docker-compose ps postgres
# View logs
docker-compose logs postgres
```

**Keycloak Connection Failed**
```bash
# Check Keycloak is running
docker-compose ps keycloak
# View logs
docker-compose logs keycloak
```

See [Deployment Guide](docs/DEPLOYMENT.md#troubleshooting) for more troubleshooting tips.

## Stopping Services

```
src/
├── main/
│   ├── java/
│   │   └── com/flightticket/
│   │       ├── config/          # Configuration classes
│   │       ├── controller/      # REST controllers
│   │       ├── service/         # Business logic
│   │       ├── repository/      # Data access
│   │       ├── entity/          # JPA entities
│   │       └── dto/             # Data transfer objects
│   └── resources/
│       ├── application.yml      # Main configuration
│       ├── application-dev.yml  # Dev configuration
│       ├── application-test.yml # Test configuration
│       ├── application-prod.yml # Prod configuration
│       ├── logback-spring.xml   # Logging configuration
│       └── db/migration/        # Flyway migrations
└── test/
    └── java/
        └── com/flightticket/    # Test classes
```

## Stopping Services

Stop all Docker services:

```bash
docker-compose down
```

Stop and remove volumes:

```bash
docker-compose down -v
```
