# Bus Booking System — Generated Backend

## Overview

This is a **FastAPI-based backend** for a real-time bus seat reservation platform. The system provides:

- **Temporary seat reservations** with 15-minute expiry locks
- **Concurrent booking protection** using database-level locking
- **Real-time seat updates** via WebSocket connections
- **Comprehensive payment processing** with multiple gateway support
- **Admin monitoring dashboard** for reservation and booking management
- **Complete audit trail** through activity logging

The backend supports three user roles (**guest**, **customer**, **admin**) and manages the full booking lifecycle from seat selection through payment confirmation to ticket generation and cancellation processing.

## Requirements

- **Python 3.11+**
- **PostgreSQL 14+** (for production; SQLite for development)
- **Redis** (optional, for caching and WebSocket pub/sub)
- **uv** package manager

## Install uv

Install the `uv` package manager:

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

After installation, restart your terminal or run:

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

## Install Dependencies

Clone the repository and install dependencies:

```bash
cd bus-booking-system-backend
uv sync
```

This will create a virtual environment and install all required packages including:
- `fastapi` — Web framework
- `uvicorn` — ASGI server
- `sqlalchemy` — ORM for database operations
- `pydantic` — Data validation
- `python-jose` — JWT token handling
- `passlib` — Password hashing
- `python-multipart` — File upload support
- `websockets` — Real-time communication

## Run the Backend

Start the development server with auto-reload:

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

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

For production deployment:

```bash
uv run uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
```

## API Docs

Once the server is running, visit **`http://localhost:8000/docs`** for the interactive Swagger UI documentation. This provides:

- Complete API endpoint listing organized by module
- Request/response schemas with examples
- "Try it out" functionality for testing endpoints
- Authentication flow testing with JWT tokens

Key endpoint categories:

### User Management
- `POST /users/register` — Register new user account
- `POST /users/login` — Authenticate and receive JWT token
- `GET /users/{id}/profile` — Get user profile details
- `PUT /users/{id}/profile` — Update user profile

### Schedule & Seat Management
- `GET /schedules/search` — Search schedules by origin, destination, date
- `GET /schedules/{id}/details` — Get schedule with bus, route, and seat details
- `GET /schedules/{id}/seats` — Get real-time seat availability
- `POST /schedules/{id}/generate-seats` — Admin: Generate seat inventory

### Reservation Management
- `POST /reservations/create` — Create reservation with 15-minute lock
- `GET /reservations/{id}/details` — Get reservation with seat details
- `GET /reservations/active` — Get user's active reservations
- `DELETE /reservations/{id}` — Cancel reservation before expiry

### Booking & Payment
- `POST /bookings/create` — Convert reservation to confirmed booking
- `GET /bookings/{id}/details` — Get booking with ticket and payment info
- `GET /bookings/history` — Get user's booking history
- `POST /bookings/{id}/cancel` — Cancel booking with refund calculation
- `POST /payments/initiate` — Initiate payment transaction
- `POST /payments/webhook` — Payment gateway callback handler

### Tickets & Cancellations
- `GET /tickets/{id}` — Get ticket details with QR code
- `GET /tickets/{id}/download` — Download ticket PDF
- `GET /cancellations/{id}/details` — Get cancellation and refund details

### Admin Operations
- `GET /admin/dashboard/metrics` — Dashboard statistics
- `GET /admin/reservations/active` — Monitor active reservations
- `POST /admin/reservations/{id}/release` — Manually release stuck reservation
- `GET /activity-logs` — View comprehensive audit trail

## OpenAPI JSON

The OpenAPI 3.0 specification is available at:

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

Download it for:
- Client SDK generation (TypeScript, Python, Java, etc.)
- API testing tool integration (Postman, Insomnia)
- Contract testing and validation
- Documentation generation

## Project Files

```
bus-booking-system-backend/
├── main.py                      # FastAPI application entry point
├── pyproject.toml               # Project dependencies and metadata
├── uv.lock                      # Locked dependency versions
├── models.py                    # SQLAlchemy ORM models (13 entities)
├── schemas.py                   # Pydantic request/response schemas
├── database.py                  # Database connection and session management
├── auth.py                      # JWT authentication and password hashing
├── enums.py                     # Enum definitions (11 enums)
├── routers/
│   ├── users.py                 # User management endpoints
│   ├── routes.py                # Route CRUD endpoints
│   ├── buses.py                 # Bus fleet management endpoints
│   ├── schedules.py             # Schedule and seat endpoints
│   ├── reservations.py          # Reservation management endpoints
│   ├── bookings.py              # Booking and ticket endpoints
│   ├── payments.py              # Payment processing endpoints
│   ├── cancellations.py         # Cancellation endpoints
│   ├── admin.py                 # Admin dashboard and monitoring
│   └── websocket.py             # WebSocket real-time updates
├── services/
│   ├── reservation_service.py  # Reservation business logic
│   ├── booking_service.py      # Booking creation and confirmation
│   ├── payment_service.py      # Payment gateway integration
│   ├── cancellation_service.py # Cancellation and refund logic
│   ├── seat_service.py         # Seat locking and availability
│   └── background_jobs.py      # Reservation expiry background task
├── utils/
│   ├── qr_generator.py         # QR code generation for tickets
│   ├── email_service.py        # Email notification service
│   └── activity_logger.py      # Activity logging utility
└── tests/
    ├── test_reservations.py    # Reservation workflow tests
    ├── test_bookings.py        # Booking and payment tests
    ├── test_concurrency.py     # Concurrent booking protection tests
    └── test_expiry.py          # Reservation expiry tests
```

## Example Workflow

### 1. Register a New User

```bash
curl -X POST "http://localhost:8000/users/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john.doe@example.com",
    "password": "SecurePass123",
    "first_name": "John",
    "last_name": "Doe",
    "phone_number": "1234567890"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "john.doe@example.com",
  "first_name": "John",
  "last_name": "Doe",
  "role": "customer",
  "is_active": true,
  "created_at": "2024-01-15T10:30:00Z"
}
```

### 2. Login and Get JWT Token

```bash
curl -X POST "http://localhost:8000/users/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john.doe@example.com",
    "password": "SecurePass123"
  }'
```

**Response:**
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user_id": "550e8400-e29b-41d4-a716-446655440000"
}
```

### 3. Search Available Schedules

```bash
curl -X GET "http://localhost:8000/schedules/search?origin_city=Mumbai&destination_city=Pune&date=2024-01-20" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

**Response:**
```json
{
  "schedules": [
    {
      "id": "schedule-123",
      "departure_datetime": "2024-01-20T08:00:00Z",
      "arrival_datetime": "2024-01-20T11:30:00Z",
      "base_price": 500.00,
      "available_seats": 28,
      "bus": {
        "bus_number": "MH-12-AB-1234",
        "bus_type": "deluxe"
      },
      "route": {
        "origin_city": "Mumbai",
        "destination_city": "Pune",
        "distance_km": 150.0
      }
    }
  ]
}
```

### 4. Create Reservation (15-minute Lock)

```bash
curl -X POST "http://localhost:8000/reservations/create" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "schedule_id": "schedule-123",
    "seat_ids": ["seat-001", "seat-002"]
  }'
```

**Response:**
```json
{
  "id": "reservation-456",
  "schedule_id": "schedule-123",
  "reservation_datetime": "2024-01-15T10:35:00Z",
  "expiry_datetime": "2024-01-15T10:50:00Z",
  "status": "active",
  "total_amount": 1000.00,
  "seats": [
    {"seat_number": "A1", "seat_type": "standard"},
    {"seat_number": "A2", "seat_type": "standard"}
  ]
}
```

### 5. Initiate Payment

```bash
curl -X POST "http://localhost:8000/payments/initiate" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "reservation_id": "reservation-456",
    "payment_method": "upi",
    "amount": 1000.00
  }'
```

### 6. Get Booking Details

```bash
curl -X GET "http://localhost:8000/bookings/booking-789/details" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

**Response:**
```json
{
  "id": "booking-789",
  "booking_reference": "BK20240115001",
  "status": "confirmed",
  "total_amount": 1000.00,
  "schedule": {
    "departure_datetime": "2024-01-20T08:00:00Z",
    "bus": {"bus_number": "MH-12-AB-1234"},
    "route": {"origin_city": "Mumbai", "destination_city": "Pune"}
  },
  "seats": [
    {"seat_number": "A1", "seat_type": "standard"},
    {"seat_number": "A2", "seat_type": "standard"}
  ],
  "ticket": {
    "ticket_number": "TKT20240115001",
    "qr_code": "data:image/png;base64,iVBORw0KGgoAAAANS...",
    "validity_status": "valid"
  }
}
```

## Next Steps

To prepare this backend for production:

### 1. Database Persistence
- Replace in-memory SQLite with **PostgreSQL** for production
- Configure connection pooling and timeout settings
- Implement database migrations using **Alembic**
- Set up read replicas for scaling read operations
- Configure backup and disaster recovery procedures

### 2. Authentication & Security
- Implement **JWT refresh tokens** for extended sessions
- Add **rate limiting** to prevent abuse (using `slowapi`)
- Enable **CORS** with proper origin restrictions
- Implement **API key authentication** for admin operations
- Add **input sanitization** to prevent SQL injection
- Set up **HTTPS/TLS** certificates for production

### 3. Code Organization
- **Split routers** into separate files by module (already structured)
- **Extract services** for business logic separation (reservation, booking, payment)
- **Separate models** into domain models and database models
- Create **repository pattern** for database access abstraction
- Implement **dependency injection** for service layer

### 4. Testing
- Write **unit tests** for service layer business logic
- Add **integration tests** for API endpoints
- Implement **concurrency tests** for seat locking scenarios
- Create **load tests** for reservation expiry background job
- Add **WebSocket connection tests** for real-time updates
- Set up **CI/CD pipeline** with automated test execution

### 5. Background Jobs
- Implement **Celery** or **APScheduler** for reservation expiry job
- Add **monitoring** for background task execution
- Implement **dead letter queue** for failed tasks
- Add **retry logic** with exponential backoff

### 6. Real-time Features
- Set up **Redis pub/sub** for WebSocket message broadcasting
- Implement **connection pooling** for WebSocket connections
- Add **heartbeat mechanism** for connection health checks
- Implement **reconnection logic** for dropped connections

### 7. Monitoring & Logging
- Integrate **structured logging** (JSON format)
- Set up **application performance monitoring** (APM)
- Add **error tracking** (Sentry or similar)
- Implement **metrics collection** (Prometheus)
- Create **alerting rules** for critical failures

### 8. Payment Integration
- Integrate real **payment gateway SDKs** (Stripe, Razorpay, PayPal)
- Implement **webhook signature verification**
- Add **idempotency keys** for payment requests
- Set up **payment reconciliation** process

### 9. Documentation
- Add **API versioning** strategy
- Create **developer onboarding guide**
- Document **deployment procedures**
- Add **troubleshooting guide**
- Create **architecture diagrams**

### 10. Performance Optimization
- Implement **caching layer** with Redis
- Add **database query optimization** and indexing
- Enable **response compression**
- Implement **pagination** for list endpoints
- Add **eager loading** for related entities
