> ## Documentation Index
> Fetch the complete documentation index at: https://docs.adhdsimple.co.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# Edge Functions Architecture

> Supabase Edge Functions system architecture with service layer integration

## Architecture

```mermaid theme={null}
graph TB
    Frontend[React Frontend] --> Services[Service Layer]
    Services --> EdgeRouter[Edge Function Router]
    EdgeRouter --> Auth[auth-operations]
    EdgeRouter --> Patient[patient-operations]
    EdgeRouter --> Prescription[clinical-prescription-operations]
    EdgeRouter --> Medication[clinical-medication-operations]
    EdgeRouter --> Payment[clinical-payment-operations]
    EdgeRouter --> Shipment[clinical-shipment-operations]
    EdgeRouter --> Delivery[clinical-delivery-operations]
    EdgeRouter --> Pharmacy[clinical-pharmacy-operations]
    EdgeRouter --> Request[clinical-request-operations]
    EdgeRouter --> Address[clinical-address-operations]
    EdgeRouter --> Clinic[clinical-clinic-operations]
    EdgeRouter --> MedImage[generate-medication-image]
    EdgeRouter --> Notifications[prescription-notifications]
    EdgeRouter --> Email[send-email]
    EdgeRouter --> Push[send-push-notification]
    
    %% Service Layer Integration
    Services --> CoreServices[Core Services]
    Services --> FeatureServices[Feature Services]
    CoreServices --> Auth
    CoreServices --> Patient
    CoreServices --> Prescription
    CoreServices --> Medication
    FeatureServices --> Payment
    FeatureServices --> Shipment
    FeatureServices --> Delivery
    FeatureServices --> Pharmacy
    FeatureServices --> Request
    FeatureServices --> Address
    FeatureServices --> Clinic
    
    %% Notification Flow
    Prescription --> Notifications
    Request --> Notifications
    Notifications --> Email
    Notifications --> Push
    Email --> SendGrid[SendGrid Email API]
    Push --> ExpoPush[Expo Push API]
    
    subgraph "Clinical Operations"
        Patient --> PatientDB[(Patient Data)]
        Prescription --> PrescriptionDB[(Prescription Data)]
        Medication --> MedicationDB[(Medication Data)]
        Request --> RequestDB[(Request Data)]
    end
    
    subgraph "Business Operations"
        Auth --> UserDB[(User Profiles)]
        Payment --> PaymentDB[(Payment Data)]
        Shipment --> ShipmentDB[(Shipment Data)]
        Delivery --> DeliveryDB[(Delivery Data)]
        Pharmacy --> PharmacyDB[(Pharmacy Data)]
        MedImage --> ImageStorage[(Image Storage)]
    end
    
    subgraph "Configuration"
        Address --> AddressDB[(Address Data)]
        Clinic --> ClinicDB[(Clinic Settings)]
    end
    
    subgraph "Communication Layer"
        Notifications --> NotificationDB[(Notification Preferences)]
        SendGrid --> PatientEmail[Patient Email]
        ExpoPush --> PatientMobile[Patient Mobile App]
    end
    
    subgraph "Security Layer"
        EdgeRouter --> JWT[JWT Validation]
        EdgeRouter --> RLS[Row Level Security]
        EdgeRouter --> Monitoring[Edge Function Monitoring]
    end
```

## Core Functions

### auth-operations

* **Purpose**: User authentication and profile management
* **Technology**: Supabase Auth with custom logic
* **Service Integration**: AuthService
* **Key Functions**:
  * Create clinic and user profiles
  * User invitations and onboarding
  * Password reset operations
  * User management (deactivate, update)
  * MFA setup and verification

### patient-operations

* **Purpose**: Comprehensive patient data management
* **Technology**: PostgreSQL with PHI protection and shared validation
* **Service Integration**: PatientService
* **Key Functions**:
  * Create and update patient records
  * Patient data retrieval with clinic isolation
  * Patient full details including health metrics, prescriptions, and titration logs
  * Patient deletion with audit trail
  * NHS number validation
  * Monitoring configuration management

### clinical-prescription-operations

* **Purpose**: Prescription management and workflow
* **Technology**: PostgreSQL with controlled substance monitoring
* **Service Integration**: PrescriptionService
* **Key Functions**:
  * Create prescription orders
  * Save prescription payment data
  * Prescription workflow management
  * Order validation and compliance
  * Prescription item management

### clinical-medication-operations

* **Purpose**: Comprehensive medication management
* **Technology**: PostgreSQL with real-time updates and shared validation
* **Service Integration**: MedicationService
* **Key Functions**:
  * Medication library management
  * Active medication tracking for patients
  * Stock movement tracking
  * Medication change detection
  * Clinical pathway integration

## Feature Functions

### clinical-payment-operations

* **Purpose**: Comprehensive payment processing and tracking
* **Technology**: PostgreSQL with Stripe integration and shared validation
* **Service Integration**: PaymentService
* **Key Functions**:
  * Payment settings management (bank accounts, processing settings)
  * Authorization payment processing (capture, cancel)
  * Order payment details retrieval
  * Prescription payment saving
  * Clinic payout management
  * Payment fees configuration
  * Stripe payment intent processing

### clinical-shipment-operations

* **Purpose**: Comprehensive medication delivery management
* **Technology**: PostgreSQL with shipment tracking and shared validation
* **Service Integration**: ShipmentService
* **Key Functions**:
  * Shipment creation with prescriptions
  * Delivery status updates
  * Shipment arrival marking
  * Contents verification
  * Prescription reassignment
  * Clinic and pharmacy shipment listing
  * DHL API integration

### clinical-delivery-operations

* **Purpose**: Delivery fee configuration and management
* **Technology**: PostgreSQL with clinic-specific delivery settings
* **Service Integration**: DeliveryService
* **Key Functions**:
  * Delivery fee retrieval with default creation
  * Clinic-specific delivery fee updates
  * Delivery cost configuration
  * Shipping price management

### clinical-pharmacy-operations

* **Purpose**: Pharmacy order management and statistics
* **Technology**: PostgreSQL with pharmacy-specific operations
* **Service Integration**: PharmacyService
* **Key Functions**:
  * Order management for pharmacies
  * Shipment tracking for pharmacy operations
  * Label generation for pharmacy orders
  * Pharmacy statistics and reporting
  * Prescriber activity reports
  * Controlled drugs register management

### clinical-request-operations

* **Purpose**: Patient app request management
* **Technology**: PostgreSQL with request workflow processing
* **Service Integration**: PatientRequestService
* **Key Functions**:
  * Patient app request creation and management
  * Review workflows for clinical staff
  * Request status tracking
  * Integration with prescription workflow

### clinical-address-operations

* **Purpose**: Address validation and management
* **Technology**: UK postcode lookup integration
* **Service Integration**: AddressService
* **Key Functions**:
  * UK postcode lookup and validation
  * Address formatting and standardization
  * Pickup address management
  * Address history tracking

### clinical-clinic-operations

* **Purpose**: Clinic settings and configuration
* **Technology**: PostgreSQL with clinic-specific settings
* **Service Integration**: ClinicService
* **Key Functions**:
  * Clinic settings management
  * Configuration updates
  * Clinic-specific preferences
  * Multi-clinic support

## Specialized Functions

### generate-medication-image

* **Purpose**: Medication image generation and management
* **Technology**: Image processing with Supabase storage
* **Key Functions**:
  * Medication image creation
  * Image storage management
  * Visual medication library
  * Asset optimization

### prescription-notifications

* **Purpose**: Email and push notification system for prescription lifecycle events
* **Technology**: Deno with SendGrid and Expo Push integration
* **Key Functions**:
  * Send email notifications via SendGrid
  * Send push notifications via Expo
  * Patient preference checking
  * Event-based notification triggering (request\_created, prescribed, etc.)

### send-email

* **Purpose**: Email service integration
* **Technology**: SendGrid API integration
* **Key Functions**:
  * Email template management
  * Email delivery tracking
  * Bounce and complaint handling
  * Clinic branding support

### send-push-notification

* **Purpose**: Push notification service
* **Technology**: Expo Push API integration
* **Key Functions**:
  * Push notification delivery
  * Device token management
  * Notification preferences
  * Delivery tracking

## Service Layer Integration

### Architecture Benefits

* **Type Safety**: All functions use Zod validation for inputs
* **Consistent Error Handling**: Shared error handling patterns
* **Service Mapping**: Each function corresponds to a specific service
* **Centralized Logic**: Business logic centralized in services
* **Testability**: Functions can be tested independently

### Request Flow

1. **Frontend** → Service Layer (PatientService, PrescriptionService, etc.)
2. **Service Layer** → Edge Function (clinical-patient-operations, etc.)
3. **Edge Function** → Database operations with validation
4. **Response** → Service Layer → Frontend

### Error Handling

* **Timeout Protection**: 10-30 seconds per function
* **Security Incident Logging**: Comprehensive audit trail
* **Sanitized Error Responses**: User-friendly error messages
* **Performance Monitoring**: Function call duration tracking

## Security Implementation

### Authentication Headers

All functions require JWT authentication with specific compliance headers:

* `X-PHI-Protection`: Patient data protection
* `X-NHS-Compliance`: NHS regulatory compliance
* `X-Controlled-Drug-Monitoring`: Prescription monitoring
* `X-Audit-Level`: Compliance audit requirements

### Row Level Security

* **Service Role Permissions**: Functions use service\_role for database access
* **RLS Policy Enforcement**: All data access filtered by clinic/user
* **Data Isolation**: Complete separation between clinics
* **Audit Trail**: All operations logged for compliance

### Monitoring

* **Function Call Duration**: Performance tracking
* **Success/Failure Rates**: Reliability monitoring
* **Security Incident Detection**: Anomaly detection
* **Console Logging**: Development debugging support

<Note>
  **All edge functions integrate with the service layer architecture and use consistent error handling, validation, and security patterns**
</Note>
