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

# Supabase functions

# Supabase Functions Documentation

This document provides comprehensive documentation for all Supabase Edge Functions in the STO Education Platform backend.

## Edge Functions Overview

The application uses Supabase Edge Functions (Deno runtime) to handle server-side logic, API integrations, and webhook processing. All functions are deployed to Supabase and handle various aspects of the platform's backend functionality.

## Function Categories

### 1. Email Functions

#### send-email

**Location**: `supabase/functions/send-email/index.ts`

**Purpose**: Handles email sending through Resend API with template support

**Features**:

* **Template System**: Multiple email templates for different use cases
* **Resend Integration**: Uses Resend API for reliable email delivery
* **HTML Templates**: Rich HTML email templates with styling
* **Error Handling**: Comprehensive error handling and logging
* **CORS Support**: Proper CORS headers for web requests

**Email Templates Supported**:

* `account-activated`: Welcome email for activated accounts
* `account-inactive`: Account suspension notification
* `account-rejected`: Application rejection notification
* `payment-success`: Payment confirmation email
* `new-enrollment`: Teacher notification for new student enrollment

**Request Interface**:

```typescript theme={null}
interface EmailRequest {
  type: string;
  email: string;
  subject: string;
  html: string;
}
```

**Template Data Structure**:

```typescript theme={null}
interface TemplateData {
  firstName: string;
  lastName: string;
  userType: string;
  // Additional fields based on template type
}
```

**Usage Example**:

```typescript theme={null}
const response = await fetch('/functions/v1/send-email', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${SUPABASE_ANON_KEY}`
  },
  body: JSON.stringify({
    type: 'payment-success',
    email: 'user@example.com',
    subject: 'Payment Successful',
    html: '<html>...</html>'
  })
});
```

**Environment Variables**:

* `RESEND_API_KEY`: Resend API key for email sending

***

### 2. Payment Functions

#### payment-webhook

**Location**: `supabase/functions/payment-webhook/index.ts`

**Purpose**: Handles PayMob payment webhook notifications and processes payment completion

**Features**:

* **Webhook Processing**: Handles PayMob webhook notifications
* **Order Management**: Updates order status based on payment results
* **Course Assignment**: Creates course enrollments for successful payments
* **Email Notifications**: Sends confirmation emails to users
* **Training Course Support**: Handles training course enrollments
* **Teacher Mark Scheme Support**: Processes mark scheme purchases
* **Access Period Calculation**: Calculates course access periods
* **Duplicate Prevention**: Prevents duplicate processing of webhooks

**Webhook Data Structure**:

```typescript theme={null}
interface PaymobWebhookData {
  obj: {
    id: string;
    success: boolean;
    amount_cents: number;
    currency: string;
    payment_method: string;
    order: {
      id: string;
      merchant_order_id: string;
      created_at: string;
    };
  };
}
```

**Payment Periods Supported**:

* `session` or `by_class`: Single session access
* `by_week`: Weekly access
* `by_month`: Monthly access

**Processing Flow**:

1. **Webhook Validation**: Validates webhook data structure
2. **Order Lookup**: Finds order by merchant\_order\_id
3. **Status Check**: Prevents duplicate processing
4. **Order Update**: Updates order status (completed/failed)
5. **Course Assignment**: Creates course enrollment for successful payments
6. **Email Notification**: Sends confirmation emails
7. **Access Period**: Calculates and sets course access end date

**Special Handling**:

* **Training Courses**: Creates training enrollments
* **Teacher Mark Schemes**: Updates purchase status
* **Parent Accounts**: Handles parent-student relationships
* **Access Period Calculation**: Smart calculation based on course availability

**Error Handling**:

* **Missing Data**: Graceful handling of missing webhook data
* **Order Not Found**: Proper error responses
* **Duplicate Processing**: Prevents duplicate webhook processing
* **Email Failures**: Continues processing even if emails fail

***

### 3. Video Conferencing Functions

#### create-room

**Location**: `supabase/functions/create-room/index.ts`

**Purpose**: Creates Whereby video meetings

**Features**:

* **Meeting Creation**: Creates transient Whereby meetings via REST API
* **Host/Participant URLs**: Returns separate URLs for teachers and students
* **Duration Handling**: Sets meeting end time based on session duration
* **Error Handling**: Comprehensive error handling and logging

**Request Interface**:

```typescript theme={null}
interface CreateRoomRequest {
  duration: number;
  courseId: string;
  courseTitle: string;
}
```

**Response Interface**:

```typescript theme={null}
interface CreateRoomResponse {
  meeting_id: string;
  room_url: string;
  host_room_url: string;
  startDate: string;
  endDate: string;
  courseId: string;
  courseTitle: string;
}
```

**Environment Variables**:

* `WHEREBY_API_KEY`: Whereby REST API key

***

### 4. Communication Functions

#### sendbird-webhook

**Location**: `supabase/functions/sendbird-webhook/index.ts`

**Purpose**: Handles SendBird webhook notifications for chat events

**Features**:

* **Message Notifications**: Processes incoming message webhooks
* **User Management**: Handles user-related webhook events
* **Channel Management**: Processes channel creation and updates
* **Real-time Updates**: Triggers real-time database updates

**Webhook Types Supported**:

* Message sent notifications
* User join/leave events
* Channel creation/update events
* Custom events

***

#### send-message-notification

**Location**: `supabase/functions/send-message-notification/index.ts`

**Purpose**: Sends push notifications for new messages

**Features**:

* **Push Notifications**: Sends notifications for new messages
* **User Targeting**: Targets specific users or groups
* **Message Content**: Includes message preview in notifications
* **Delivery Tracking**: Tracks notification delivery status

***

### 5. Session Management Functions

#### create-room

**Location**: `supabase/functions/create-room/index.ts`

**Purpose**: Creates new Whereby video conferencing meetings

**Features**:

* **Meeting Creation**: Creates Whereby transient meetings via REST API
* **Host URL**: Returns separate host URL for teachers
* **Room URL**: Returns participant URL for students
* **Duration Handling**: Sets meeting end time based on session duration

**Request Interface**:

```typescript theme={null}
interface CreateRoomRequest {
  duration: number;
  courseId: string;
  courseTitle: string;
}
```

***

#### delete-rooms

**Location**: `supabase/functions/delete-rooms/index.ts`

**Purpose**: Deletes Whereby meetings and updates attendance

**Features**:

* **Whereby Integration**: Calls Whereby API to delete meetings
* **Attendance Update**: Updates session attendance records
* **Course Association**: Links meeting deletion to course data
* **Error Handling**: Handles missing meetings gracefully

***

#### cleanup-sessions

**Location**: `supabase/functions/cleanup-sessions/index.ts`

**Purpose**: Cleans up expired sessions and related data

**Features**:

* **Session Cleanup**: Removes expired session data
* **Database Maintenance**: Cleans up orphaned records
* **Performance Optimization**: Improves database performance
* **Automated Execution**: Runs automatically on schedule

***

### 6. Quiz and Assessment Functions

#### notify-quiz-students

**Location**: `supabase/functions/notify-quiz-students/index.ts`

**Purpose**: Sends notifications to students about new quizzes

**Features**:

* **Student Notifications**: Notifies students about new quizzes
* **Email Integration**: Sends email notifications
* **Push Notifications**: Sends push notifications
* **Batch Processing**: Handles multiple students efficiently

***

### 7. Utility Functions

#### url-preview

**Location**: `supabase/functions/url-preview/index.ts`

**Purpose**: Generates URL previews for shared links

**Features**:

* **Link Preview**: Generates previews for shared URLs
* **Metadata Extraction**: Extracts title, description, and images
* **Caching**: Caches preview data for performance
* **Error Handling**: Handles invalid or inaccessible URLs

***

#### download-app-asset

**Location**: `supabase/functions/download-app-asset/index.ts`

**Purpose**: Serves mobile app assets and updates

**Features**:

* **Asset Serving**: Serves mobile app files
* **Version Management**: Handles different app versions
* **Update Distribution**: Distributes app updates
* **Security**: Ensures secure asset delivery

***

#### get-app-releases

**Location**: `supabase/functions/get-app-releases/index.ts`

**Purpose**: Provides information about available app releases

**Features**:

* **Release Information**: Returns available app releases
* **Version Details**: Provides version-specific information
* **Update Notifications**: Notifies about new releases
* **Platform Support**: Handles multiple platforms

***

### 8. Session Management Functions

#### update\_session

**Location**: `supabase/functions/update_session/index.ts`

**Purpose**: Updates session information and status

**Features**:

* **Session Updates**: Updates session metadata
* **Status Management**: Manages session status changes
* **User Tracking**: Tracks user session participation
* **Real-time Updates**: Provides real-time session updates

***

#### whereby-webhook

**Location**: `supabase/functions/whereby-webhook/index.ts`

**Purpose**: Handles Whereby webhook notifications

**Features**:

* **Event Processing**: Processes Whereby room events
* **Session Tracking**: Tracks session lifecycle events
* **Host Detection**: Ends session when host leaves
* **Database Updates**: Updates session records in database

***

### 9. Payment Processing Functions

#### payment-callback

**Location**: `supabase/functions/payment-callback/index.ts`

**Purpose**: Handles payment callback notifications

**Features**:

* **Callback Processing**: Processes payment callbacks
* **Status Updates**: Updates payment status
* **Error Handling**: Handles payment errors
* **Notification Sending**: Sends payment notifications

***

#### payment-webhook-multiple

**Location**: `supabase/functions/payment-webhook-multiple/index.ts`

**Purpose**: Handles multiple payment webhook notifications

**Features**:

* **Batch Processing**: Processes multiple payment notifications
* **Parallel Processing**: Handles multiple payments simultaneously
* **Error Recovery**: Recovers from individual payment failures
* **Performance Optimization**: Optimized for high-volume processing

***

### 10. Content Generation Functions

#### generate-blog-post

**Location**: `supabase/functions/generate-blog-post/index.ts`

**Purpose**: Generates blog post content using AI

**Features**:

* **AI Content Generation**: Generates blog post content
* **SEO Optimization**: Optimizes content for search engines
* **Content Validation**: Validates generated content
* **Database Integration**: Saves generated content to database

***

## Function Configuration

### Environment Variables

Each function requires specific environment variables:

#### Common Variables

* `SUPABASE_URL`: Supabase project URL
* `SUPABASE_SERVICE_ROLE_KEY`: Service role key for admin operations

#### Function-specific Variables

* `RESEND_API_KEY`: For email functions
* `WHEREBY_API_KEY`: For video conferencing functions
* `SENDBIRD_API_TOKEN`: For chat functions
* `PAYMOB_SECRET_KEY`: For payment functions

### CORS Configuration

All functions include CORS headers for web access:

```typescript theme={null}
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
```

### Error Handling

Functions implement comprehensive error handling:

```typescript theme={null}
try {
  // Function logic
} catch (error) {
  console.error('Function error:', error);
  return new Response(
    JSON.stringify({ error: error.message }),
    { status: 500, headers: corsHeaders }
  );
}
```

## Function Deployment

### Deployment Process

Functions are deployed using Supabase CLI:

```bash theme={null}
# Deploy all functions
supabase functions deploy

# Deploy specific function
supabase functions deploy function-name

# Deploy with environment variables
supabase functions deploy --env-file .env
```

### Local Development

Functions can be run locally for development:

```bash theme={null}
# Start local development server
supabase functions serve

# Serve specific function
supabase functions serve function-name
```

## Function Monitoring

### Logging

All functions include comprehensive logging:

```typescript theme={null}
console.log('Function started:', { params });
console.log('Processing data:', data);
console.log('Function completed successfully');
```

### Error Tracking

Functions log errors for monitoring:

```typescript theme={null}
console.error('Error in function:', error);
console.error('Error details:', error.message);
```

## Function Security

### Authentication

Functions validate requests:

```typescript theme={null}
// Check authorization header
const authHeader = req.headers.get('authorization');
if (!authHeader) {
  return new Response('Unauthorized', { status: 401 });
}
```

### Input Validation

Functions validate input data:

```typescript theme={null}
if (!requiredField) {
  return new Response(
    JSON.stringify({ error: 'Missing required field' }),
    { status: 400 }
  );
}
```

## Function Performance

### Optimization Strategies

* **Efficient Database Queries**: Optimized database operations
* **Caching**: Caching for frequently accessed data
* **Batch Processing**: Processing multiple items efficiently
* **Error Recovery**: Graceful error handling and recovery

### Monitoring

* **Response Times**: Monitor function execution times
* **Error Rates**: Track function error rates
* **Resource Usage**: Monitor memory and CPU usage
* **Success Rates**: Track function success rates

## Future Function Enhancements

### Planned Features

* **Advanced Caching**: Redis integration for better caching
* **Message Queues**: Background job processing
* **Advanced Analytics**: Enhanced analytics and reporting
* **AI Integration**: More AI-powered features

### Performance Improvements

* **Function Optimization**: Better performance optimization
* **Database Optimization**: Improved database queries
* **Caching Strategies**: Advanced caching mechanisms
* **Load Balancing**: Better load distribution

## Function Testing

### Testing Strategy

* **Unit Tests**: Test individual function logic
* **Integration Tests**: Test function interactions
* **End-to-End Tests**: Test complete workflows
* **Load Tests**: Test function performance under load

### Testing Tools

* **Deno Test**: Built-in testing framework
* **Mock Data**: Test with mock data
* **Error Simulation**: Test error scenarios
* **Performance Testing**: Test function performance
