# Healthcare Management System — Generated Backend

## Overview

This is a **FastAPI-based backend** for the **Healthcare Management System**, a comprehensive web application designed to streamline healthcare operations including patient records, appointments, consultations, billing, and reporting.

The system supports **five core user roles**:
- **Administrator**: Manages users, departments, and system configuration
- **Doctor**: Conducts consultations, creates prescriptions, orders lab tests
- **Nurse**: Records vital signs, assists with patient care
- **Receptionist**: Manages patient registration and appointment scheduling
- **Billing Officer**: Handles invoicing and payment processing

The backend includes **8 functional modules** covering 17 core entities:
- **Department**: Organizational units and configuration
- **User**: Authentication, authorization, and audit trails
- **Patient**: Demographics, registration, and medical history
- **Insurance**: Provider directory and coverage policies
- **Appointment**: Scheduling, calendar, and status management
- **Clinical**: Consultations, prescriptions, vital signs, and lab orders
- **Billing**: Invoicing, payments, and service catalog
- **Reporting**: Analytics and business intelligence

This generated API provides full CRUD operations, custom endpoints for workflows, and enforces business rules including role-based access control, audit logging, and data validation.

## Requirements

- **Python 3.11+**
- **uv** (modern Python package manager)
- **PostgreSQL** (for production deployment)

## 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
```

Verify the installation:

```bash
uv --version
```

## Install Dependencies

Clone or navigate to the project directory, then install all dependencies:

```bash
uv sync
```

This will create a virtual environment and install FastAPI, SQLAlchemy, Pydantic, and other required packages.

## Run the Backend

Start the FastAPI development server with auto-reload:

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

The API will be available at:

```
http://127.0.0.1:8000
```

## API Docs

FastAPI provides interactive API documentation out of the box:

- **Swagger UI**: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
- **ReDoc**: [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)

These interfaces allow you to explore all endpoints, view request/response schemas, and test API calls directly from your browser.

## OpenAPI JSON

Download the OpenAPI 3.0 specification:

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

Use this JSON file to generate client SDKs, import into API testing tools (Postman, Insomnia), or integrate with API gateways.

## Project Files

```
.
├── main.py                  # FastAPI application entry point
├── models.py                # SQLAlchemy ORM models (all entities)
├── schemas.py               # Pydantic request/response schemas
├── database.py              # Database connection and session management
├── crud.py                  # CRUD operations for all entities
├── enums.py                 # Enumeration types (roles, statuses, etc.)
├── dependencies.py          # Dependency injection (DB sessions, auth)
├── routers/
│   ├── departments.py       # Department endpoints
│   ├── users.py             # User management endpoints
│   ├── patients.py          # Patient management endpoints
│   ├── appointments.py      # Appointment scheduling endpoints
│   ├── consultations.py     # Clinical consultation endpoints
│   ├── billing.py           # Invoice and payment endpoints
│   ├── reporting.py         # Report generation endpoints
│   └── audit.py             # Audit log endpoints
├── services/
│   ├── appointment_service.py     # Business logic for appointments
│   ├── consultation_service.py    # Consultation workflows
│   ├── billing_service.py         # Invoice and payment processing
│   └── report_service.py          # Report generation logic
├── utils/
│   ├── auth.py              # Authentication and password hashing
│   ├── validation.py        # Custom validation rules
│   └── audit.py             # Audit logging utilities
├── pyproject.toml           # Project dependencies and configuration
└── README.md                # This file
```

## Example Workflow

### 1. Register a New Patient

```bash
curl -X POST http://127.0.0.1:8000/patients \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "date_of_birth": "1985-06-15",
    "gender": "male",
    "phone": "+1234567890",
    "email": "john.doe@example.com",
    "address": "123 Main Street",
    "city": "Springfield",
    "state": "IL",
    "postal_code": "62701",
    "country": "USA",
    "emergency_contact_name": "Jane Doe",
    "emergency_contact_phone": "+1234567891",
    "emergency_contact_relationship": "Spouse"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "patient_number": "PAT-2024-0001",
  "first_name": "John",
  "last_name": "Doe",
  "date_of_birth": "1985-06-15",
  "gender": "male",
  "created_at": "2024-01-15T10:30:00Z"
}
```

### 2. Get Patient Details

```bash
curl -X GET http://127.0.0.1:8000/patients/550e8400-e29b-41d4-a716-446655440000/details
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "patient_number": "PAT-2024-0001",
  "first_name": "John",
  "last_name": "Doe",
  "date_of_birth": "1985-06-15",
  "gender": "male",
  "phone": "+1234567890",
  "email": "john.doe@example.com",
  "medical_record": {
    "blood_type": "O+",
    "allergies": "Penicillin",
    "chronic_conditions": "Hypertension"
  },
  "insurance_provider": {
    "name": "Blue Cross Blue Shield"
  },
  "appointments": [
    {
      "appointment_date": "2024-01-20",
      "appointment_time": "14:00:00",
      "doctor": {
        "first_name": "Sarah",
        "last_name": "Smith"
      },
      "department": {
        "name": "Cardiology"
      }
    }
  ]
}
```

### 3. Schedule an Appointment

```bash
curl -X POST http://127.0.0.1:8000/appointments \
  -H "Content-Type: application/json" \
  -d '{
    "patient_id": "550e8400-e29b-41d4-a716-446655440000",
    "doctor_id": "660e8400-e29b-41d4-a716-446655440001",
    "department_id": "770e8400-e29b-41d4-a716-446655440002",
    "appointment_date": "2024-01-25",
    "appointment_time": "10:00:00",
    "duration_minutes": 30,
    "appointment_type": "consultation",
    "reason": "Annual checkup"
  }'
```

### 4. Record Vital Signs

```bash
curl -X POST http://127.0.0.1:8000/vital-signs \
  -H "Content-Type: application/json" \
  -d '{
    "patient_id": "550e8400-e29b-41d4-a716-446655440000",
    "recorded_by_user_id": "880e8400-e29b-41d4-a716-446655440003",
    "systolic_bp": 120,
    "diastolic_bp": 80,
    "pulse_rate": 72,
    "temperature_celsius": 36.8,
    "weight_kg": 75.5,
    "height_cm": 175.0,
    "oxygen_saturation": 98
  }'
```

### 5. Create Consultation with Prescriptions

```bash
curl -X POST http://127.0.0.1:8000/consultations/complete \
  -H "Content-Type: application/json" \
  -d '{
    "consultation": {
      "appointment_id": "990e8400-e29b-41d4-a716-446655440004",
      "patient_id": "550e8400-e29b-41d4-a716-446655440000",
      "doctor_id": "660e8400-e29b-41d4-a716-446655440001",
      "chief_complaint": "Persistent headaches",
      "diagnosis": "Tension headache",
      "treatment_plan": "Rest and medication"
    },
    "prescriptions": [
      {
        "medication_name": "Ibuprofen",
        "dosage": "400mg",
        "frequency": "Twice daily",
        "duration": "7 days",
        "quantity": 14
      }
    ],
    "lab_tests": [
      {
        "test_name": "Complete Blood Count",
        "test_type": "Hematology"
      }
    ]
  }'
```

### 6. Generate Invoice

```bash
curl -X POST http://127.0.0.1:8000/invoices \
  -H "Content-Type: application/json" \
  -d '{
    "patient_id": "550e8400-e29b-41d4-a716-446655440000",
    "appointment_id": "990e8400-e29b-41d4-a716-446655440004",
    "line_items": [
      {
        "service_id": "aa0e8400-e29b-41d4-a716-446655440005",
        "description": "General Consultation",
        "quantity": 1,
        "unit_price": 150.00
      },
      {
        "service_id": "bb0e8400-e29b-41d4-a716-446655440006",
        "description": "Complete Blood Count",
        "quantity": 1,
        "unit_price": 45.00
      }
    ]
  }'
```

### 7. List All Appointments

```bash
curl -X GET "http://127.0.0.1:8000/appointments?status=scheduled&skip=0&limit=20"
```

## Next Steps

This generated backend provides a solid foundation. To prepare for production deployment:

### 1. **Database Persistence**
   - Replace in-memory storage with PostgreSQL
   - Configure connection pooling in `database.py`
   - Run Alembic migrations for schema management
   - Set up automated backups

### 2. **Authentication & Authorization**
   - Implement JWT-based authentication
   - Add role-based access control (RBAC) middleware
   - Secure endpoints based on user roles (administrator, doctor, nurse, receptionist, billing_officer)
   - Add password hashing with bcrypt/Argon2
   - Implement session management and token refresh

### 3. **Code Organization**
   - Split `main.py` into modular routers (`routers/patients.py`, `routers/appointments.py`, etc.)
   - Extract business logic into service layer (`services/consultation_service.py`)
   - Separate SQLAlchemy models and Pydantic schemas
   - Create utility modules for validation, audit logging, and error handling

### 4. **Testing**
   - Add unit tests with pytest for CRUD operations
   - Write integration tests for workflows (appointment scheduling, consultation completion)
   - Test business rules (no double-booking, allergy warnings)
   - Add end-to-end API tests using TestClient
   - Implement test fixtures and factories

### 5. **Audit Logging**
   - Implement automatic audit trail for all create/update/delete operations
   - Log user actions with IP address and user agent
   - Store old/new values in `audit_logs` table

### 6. **Validation & Error Handling**
   - Add custom validators for medical data (blood pressure ranges, vital signs)
   - Implement consistent error responses with proper HTTP status codes
   - Add request/response logging middleware

### 7. **Performance Optimization**
   - Implement eager loading for detail endpoints
   - Add database indexes on foreign keys and frequently queried fields
   - Enable query result caching for reports
   - Add pagination to all list endpoints

### 8. **Documentation**
   - Enhance OpenAPI schemas with detailed descriptions and examples
   - Document all workflows and business rules
   - Create developer guides for extending the API

### 9. **Security Hardening**
   - Enable CORS with appropriate origins
   - Add rate limiting to prevent abuse
   - Implement input sanitization to prevent SQL injection
   - Enable HTTPS in production
   - Add security headers (HSTS, CSP)

### 10. **Deployment**
   - Containerize with Docker
   - Set up CI/CD pipeline (GitHub Actions, GitLab CI)
   - Configure environment-based settings (dev, staging, production)
   - Add monitoring and logging (Sentry, CloudWatch, ELK stack)
   - Set up health check endpoints

---

**Generated by:** Healthcare Management System Backend Generator  
**Framework:** FastAPI 0.100+  
**License:** MIT
