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

# Services

# Frontend Services Documentation

This document provides comprehensive documentation for all service classes and utilities in the STO Education Platform frontend.

## Services Overview

The application uses a service layer architecture to handle business logic, API interactions, and data processing. Services are organized by functionality and provide clean interfaces for components to interact with backend systems.

## Service Categories

### 1. Email Service

#### Location: `src/services/emailService.ts`

#### Purpose

Handles all email-related functionality including template generation and email sending through Supabase Edge Functions.

#### Features

* **Template-based Emails**: Uses React Email templates for consistent styling
* **Multiple Email Types**: Supports various email types for different events
* **Supabase Integration**: Sends emails through Supabase Edge Functions
* **Error Handling**: Comprehensive error handling and logging
* **Type Safety**: Full TypeScript support with defined interfaces

#### Email Types Supported

##### Session Start Email

```typescript theme={null}
interface SessionEmailData {
  studentEmail: string;
  studentName: string;
  teacherName: string;
  courseTitle: string;
  sessionTime: string;
  sessionLink: string;
}
```

##### Announcement Email

```typescript theme={null}
interface AnnouncementEmailData {
  studentEmail: string;
  studentName: string;
  teacherName: string;
  courseTitle: string;
  announcementTitle: string;
  announcementContent: string;
  datePosted: string;
}
```

##### Purchase Confirmation Email

```typescript theme={null}
interface PurchaseEmailData {
  studentEmail: string;
  studentName: string;
  courseTitle: string;
  teacherName: string;
  purchaseDate: string;
  amount: string;
  paymentMethod: string;
  startDate: string;
  duration: string;
}
```

##### Assignment Posted Email

```typescript theme={null}
interface AssignmentEmailData {
  studentEmail: string;
  studentName: string;
  teacherName: string;
  courseTitle: string;
  assignmentTitle: string;
  assignmentDescription: string;
  dueDate: string;
}
```

##### Course Completion Email

```typescript theme={null}
interface CourseCompletionEmailData {
  studentEmail: string;
  studentName: string;
  teacherName: string;
  courseTitle: string;
  completionDate: string;
  finalGrade?: string;
  certificateLink?: string;
}
```

##### New Message Email

```typescript theme={null}
interface NewMessageEmailData {
  recipientEmail: string;
  recipientName: string;
  senderName: string;
  courseTitle?: string;
  messagePreview: string;
  sentTime: string;
}
```

##### Assignment Graded Email

```typescript theme={null}
interface AssignmentGradedEmailData {
  studentEmail: string;
  studentName: string;
  teacherName: string;
  courseTitle: string;
  assignmentTitle: string;
  grade: string;
  maxPoints: string;
  feedback?: string;
}
```

##### Payment Success Email

```typescript theme={null}
interface PaymentSuccessEmailData {
  studentEmail: string;
  studentName: string;
  courseTitle: string;
  teacherName: string;
  amount: string;
  paymentDate: string;
  paymentMethod: string;
  orderId: string;
  paymentPeriod: string;
}
```

##### New Enrollment Email

```typescript theme={null}
interface NewEnrollmentEmailData {
  teacherEmail: string;
  teacherName: string;
  studentName: string;
  courseTitle: string;
  enrollmentDate: string;
  paymentAmount: string;
  paymentPeriod: string;
}
```

#### Service Functions

##### sendSessionStartEmail

```typescript theme={null}
export const sendSessionStartEmail = async (data: SessionEmailData) => {
  // Generates HTML from SessionStartEmail template
  // Calls Supabase Edge Function with type 'session-start'
  // Returns success/error response
}
```

##### sendAnnouncementEmail

```typescript theme={null}
export const sendAnnouncementEmail = async (data: AnnouncementEmailData) => {
  // Generates HTML from AnnouncementEmail template
  // Calls Supabase Edge Function with type 'announcement'
  // Returns success/error response
}
```

##### sendPurchaseConfirmationEmail

```typescript theme={null}
export const sendPurchaseConfirmationEmail = async (data: PurchaseEmailData) => {
  // Generates HTML from PurchaseConfirmationEmail template
  // Calls Supabase Edge Function with type 'purchase'
  // Returns success/error response
}
```

##### sendAssignmentPostedEmail

```typescript theme={null}
export const sendAssignmentPostedEmail = async (data: AssignmentEmailData) => {
  // Generates HTML from AssignmentPostedEmail template
  // Calls Supabase Edge Function with type 'assignment-posted'
  // Returns success/error response
}
```

##### sendCourseCompletionEmail

```typescript theme={null}
export const sendCourseCompletionEmail = async (data: CourseCompletionEmailData) => {
  // Generates HTML from CourseCompletionEmail template
  // Calls Supabase Edge Function with type 'course-completion'
  // Returns success/error response
}
```

##### sendNewMessageEmail

```typescript theme={null}
export const sendNewMessageEmail = async (data: NewMessageEmailData) => {
  // Generates HTML from NewMessageEmail template
  // Calls Supabase Edge Function with type 'new-message'
  // Returns success/error response
}
```

##### sendAssignmentGradedEmail

```typescript theme={null}
export const sendAssignmentGradedEmail = async (data: AssignmentGradedEmailData) => {
  // Generates HTML from AssignmentGradedEmail template
  // Calls Supabase Edge Function with type 'assignment-graded'
  // Returns success/error response
}
```

##### sendPaymentSuccessEmail

```typescript theme={null}
export const sendPaymentSuccessEmail = async (data: PaymentSuccessEmailData) => {
  // Generates HTML from PaymentSuccessEmail template
  // Calls Supabase Edge Function with type 'payment-success'
  // Returns success/error response
}
```

##### sendNewEnrollmentEmail

```typescript theme={null}
export const sendNewEnrollmentEmail = async (data: NewEnrollmentEmailData) => {
  // Generates HTML from NewEnrollmentEmail template
  // Calls Supabase Edge Function with type 'new-enrollment'
  // Returns success/error response
}
```

#### Implementation Details

* **Template Generation**: Uses React Email components for HTML generation
* **Edge Function Integration**: Calls `/functions/v1/send-email` endpoint
* **Error Handling**: Comprehensive error handling with logging
* **Response Format**: Consistent `{success: boolean, error?: any}` response format

#### Dependencies

* **React Email Templates**: Located in `src/emails/`
* **Supabase**: For Edge Function calls
* **Environment Variables**: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`

***

### 2. Mochi Service

#### Location: `src/services/mochiService.ts`

#### Purpose

Handles the Mochi gamification system that tracks student progress, engagement, and provides motivational feedback through a virtual pet system.

#### Features

* **Progress Tracking**: Tracks assignment completion, attendance, and grades
* **Gamification**: Level system and mood tracking
* **Course-specific Scores**: Individual scores per course
* **Overall Scores**: Aggregate scores across all courses
* **Real-time Updates**: Automatic score recalculation
* **Data Validation**: Ensures score integrity and bounds checking

#### Mochi Score Interface

```typescript theme={null}
interface MochiScore {
  id: string;
  student_id: string;
  course_id: string | null;  // null for overall score
  overall_score: number;     // 0-100
  assignment_score: number;  // 0-100
  attendance_score: number;  // 0-100
  grade_score: number;       // 0-100
  level: number;             // 1-5
  mood: 'happy' | 'neutral' | 'sad' | 'excited' | 'sleeping';
  total_assignments: number;
  total_sessions: number;
  last_updated: string;
}
```

#### Service Methods

##### getOverallScore

```typescript theme={null}
static async getOverallScore(studentId: string): Promise<MochiScore | null>
```

* Fetches the overall Mochi score for a student
* Returns null if no score exists
* Handles database errors gracefully

##### getCourseScores

```typescript theme={null}
static async getCourseScores(studentId: string): Promise<{[courseId: string]: MochiScore}>
```

* Fetches course-specific Mochi scores
* Returns a map of course IDs to scores
* Handles missing scores gracefully

##### calculateAndSaveScores

```typescript theme={null}
static async calculateAndSaveScores(studentId: string, activeCourseIds: string[] = [])
```

* Calculates scores for all active courses
* Saves course-specific scores
* Calculates and saves overall score
* Handles errors during calculation

##### calculateOverallScore (Private)

```typescript theme={null}
private static async calculateOverallScore(studentId: string, activeCourseIds: string[])
```

* Calculates overall score from course scores
* Weights: Assignments (40%), Attendance (30%), Grades (30%)
* Determines level (1-5) and mood based on score
* Returns comprehensive score object

##### calculateCourseScore (Private)

```typescript theme={null}
private static async calculateCourseScore(studentId: string, courseId: string)
```

* Calculates score for a specific course
* Tracks assignment submissions and timeliness
* Calculates attendance percentage
* Calculates grade average
* Returns validated score object

##### saveCourseScore

```typescript theme={null}
static async saveCourseScore(studentId: string, courseId: string, scores: ScoreData)
```

* Saves course-specific scores to database
* Handles both insert and update operations
* Validates score data before saving
* Comprehensive error handling

##### saveOverallScore

```typescript theme={null}
static async saveOverallScore(studentId: string, scores: ScoreData)
```

* Saves overall score to database
* Uses course\_id = null for overall scores
* Handles both insert and update operations
* Validates score data before saving

##### triggerRecalculation

```typescript theme={null}
static async triggerRecalculation(studentId: string)
```

* Triggers complete score recalculation
* Fetches active courses for student
* Calculates scores for each course
* Calculates overall score
* Saves all scores to database

#### Score Calculation Logic

##### Assignment Score Calculation

* **Base Points**: 50 points for submission
* **Early Submission Bonus**: Up to 20 points for early submission
* **Grading Bonus**: 30 points for graded assignments
* **Late Penalty**: -20 points for overdue assignments
* **Range**: 0-100 points

##### Attendance Score Calculation

* **Formula**: (Attended Sessions / Total Sessions) × 100
* **Range**: 0-100 percentage

##### Grade Score Calculation

* **Formula**: Average of all graded assignment percentages
* **Range**: 0-100 percentage

##### Overall Score Calculation

* **Weighted Average**:
  * Assignments: 40% weight
  * Attendance: 30% weight
  * Grades: 30% weight
* **Range**: 0-100 points

##### Level Calculation

* **Formula**: Math.floor(overallScore / 20) + 1
* **Range**: 1-5 levels

##### Mood Calculation

* **Excited**: Score ≥ 90
* **Happy**: Score ≥ 70
* **Neutral**: Score ≥ 50
* **Sad**: Score ≥ 30
* **Sleeping**: Score \< 30

#### Data Validation

* **Score Bounds**: All scores validated to be 0-100
* **Level Bounds**: Level validated to be 1-5
* **Database Constraints**: Proper error handling for database operations
* **Null Handling**: Graceful handling of missing data

#### Dependencies

* **Supabase**: Database operations
* **Database Tables**:
  * `mochi_scores`
  * `assignments`
  * `assignment_submissions`
  * `session_attendance`
  * `course_assignments`

***

### 3. Page Content Service

#### Location: `src/services/pageContentService.ts`

#### Purpose

Handles dynamic page content management for the Content Management System (CMS), allowing administrators to edit page content in real-time.

#### Features

* **Dynamic Content**: Editable page content management
* **Page-specific Content**: Content organized by page identifier
* **CRUD Operations**: Create, read, update, delete content
* **Batch Operations**: Save multiple content items at once
* **Import/Export**: Content import and export functionality
* **Error Handling**: Comprehensive error handling and validation

#### Interfaces

##### PageContentItem

```typescript theme={null}
interface PageContentItem {
  [key: string]: string;  // Key-value pairs for content
}
```

##### PageData

```typescript theme={null}
interface PageData {
  id?: number;
  page: string;
  content: PageContentItem;
}
```

#### Service Methods

##### getPageContent

```typescript theme={null}
async getPageContent(page: string): Promise<PageContentItem>
```

* Fetches all content for a specific page
* Returns empty object if no content exists
* Handles database errors gracefully
* Validates page parameter

##### getContent

```typescript theme={null}
async getContent(page: string, contentKey: string): Promise<string | null>
```

* Fetches specific content item by key
* Returns null if content doesn't exist
* Validates both page and contentKey parameters
* Uses getPageContent internally

##### savePageContent

```typescript theme={null}
async savePageContent(page: string, content: PageContentItem): Promise<void>
```

* Saves entire page content object
* Handles both insert and update operations
* Validates page parameter
* Comprehensive error handling

##### saveContent

```typescript theme={null}
async saveContent(page: string, contentKey: string, contentValue: string): Promise<void>
```

* Saves individual content item
* Updates existing content or adds new item
* Validates all parameters
* Uses savePageContent internally

##### exportPageContent

```typescript theme={null}
async exportPageContent(page: string): Promise<PageContentItem>
```

* Exports all content for a page
* Used for backup or migration purposes
* Returns complete content object

##### importPageContent

```typescript theme={null}
async importPageContent(page: string, contentMap: PageContentItem): Promise<void>
```

* Imports content for a page
* Validates content map
* Saves entire content at once
* Used for content migration

##### checkPageContentExists

```typescript theme={null}
async checkPageContentExists(page: string): Promise<boolean>
```

* Checks if any content exists for a page
* Returns boolean result
* Used for conditional rendering
* Validates page parameter

#### Implementation Details

* **Database Table**: Uses `page_data` table
* **Upsert Logic**: Handles both insert and update operations
* **Error Codes**: Handles PGRST116 (no rows found) gracefully
* **Validation**: Comprehensive parameter validation
* **Logging**: Detailed error logging for debugging

#### Usage Examples

##### Loading Page Content

```typescript theme={null}
const content = await pageContentService.getPageContent('about');
const title = content['page-title'] || 'Default Title';
```

##### Saving Content

```typescript theme={null}
await pageContentService.saveContent('about', 'hero-title', 'Welcome to STO Education');
```

##### Batch Content Save

```typescript theme={null}
const contentMap = {
  'hero-title': 'Welcome to STO Education',
  'hero-subtitle': 'Quality Education for All',
  'hero-description': 'Learn with the best teachers...'
};
await pageContentService.savePageContent('home', contentMap);
```

#### Dependencies

* **Supabase**: Database operations
* **Database Table**: `page_data` with columns:
  * `id`: Primary key
  * `page`: Page identifier
  * `content`: JSON content object

***

### 4. Teacher Mark Scheme Service

#### Location: `src/services/teacherMarkSchemeService.ts`

#### Purpose

Handles teacher mark scheme purchases, payment processing, and access management for students.

#### Features

* **Purchase Management**: Handles mark scheme purchases
* **Payment Integration**: Integrates with PayMob payment system
* **Access Control**: Manages student access to purchased schemes
* **Order Management**: Creates and manages purchase orders
* **Status Tracking**: Tracks payment and purchase status

#### Interfaces

##### TeacherMarkSchemePurchase

```typescript theme={null}
interface TeacherMarkSchemePurchase {
  id: string;
  student_id: string;
  teacher_mark_scheme_id: string;
  order_id: string;
  amount_paid: number;
  currency: string;
  payment_status: 'pending' | 'completed' | 'failed' | 'refunded';
  purchase_date: string;
}
```

##### TeacherMarkSchemeWithPurchase

```typescript theme={null}
interface TeacherMarkSchemeWithPurchase extends TeacherMarkScheme {
  is_purchased: boolean;
  purchase_details?: TeacherMarkSchemePurchase;
}
```

##### TeacherMarkSchemePaymentRequest

```typescript theme={null}
interface TeacherMarkSchemePaymentRequest {
  student_id: string;
  teacher_mark_scheme_id: string;
  amount: number;
  currency?: string;
}
```

##### TeacherMarkSchemePaymentResponse

```typescript theme={null}
interface TeacherMarkSchemePaymentResponse {
  success: boolean;
  order_id?: string;
  payment_url?: string;
  error?: string;
}
```

#### Service Methods

##### checkPurchaseStatus

```typescript theme={null}
static async checkPurchaseStatus(studentId: string, teacherMarkSchemeId: string): Promise<boolean>
```

* Checks if student has purchased a specific mark scheme
* Returns true if purchase exists and is completed
* Handles database errors gracefully
* Validates student and scheme IDs

##### getStudentPurchases

```typescript theme={null}
static async getStudentPurchases(studentId: string): Promise<TeacherMarkSchemeWithPurchase[]>
```

* Fetches all purchased mark schemes for a student
* Includes mark scheme details and purchase information
* Returns array of mark schemes with purchase status
* Handles database joins and errors

##### createPaymentRequest

```typescript theme={null}
static async createPaymentRequest(request: TeacherMarkSchemePaymentRequest): Promise<TeacherMarkSchemePaymentResponse>
```

* Creates payment request for mark scheme purchase
* Creates order record in orders table
* Creates purchase record in purchases table
* Returns payment information for PayMob integration

##### updatePaymentStatus

```typescript theme={null}
static async updatePaymentStatus(orderId: string, status: 'completed' | 'failed' | 'refunded'): Promise<boolean>
```

* Updates payment status after payment processing
* Updates both order and purchase records
* Handles status transitions
* Returns success/failure result

##### getTeacherMarkSchemeWithPurchaseStatus

```typescript theme={null}
static async getTeacherMarkSchemeWithPurchaseStatus(teacherMarkSchemeId: string, studentId?: string): Promise<TeacherMarkSchemeWithPurchase | null>
```

* Fetches mark scheme details with purchase status
* Includes purchase information if student ID provided
* Validates scheme is public and approved
* Returns null if scheme not found

#### Payment Flow

##### 1. Purchase Initiation

```typescript theme={null}
const paymentRequest = {
  student_id: 'student-uuid',
  teacher_mark_scheme_id: 'scheme-uuid',
  amount: 50.00,
  currency: 'EGP'
};

const response = await TeacherMarkSchemeService.createPaymentRequest(paymentRequest);
```

##### 2. Order Creation

* Creates order record with:
  * Base amount
  * Service fee (3%)
  * Tax (14% VAT)
  * Total amount
  * Take-home amount (60% for teacher)

##### 3. Purchase Record

* Creates purchase record linking:
  * Student ID
  * Mark scheme ID
  * Order ID
  * Payment status (pending)

##### 4. Payment Processing

* Integrates with PayMob payment gateway
* Returns payment URL for student
* Tracks payment status

##### 5. Status Updates

* Updates order status on payment completion
* Updates purchase status
* Enables access to mark scheme

#### Database Schema

##### Orders Table

```sql theme={null}
CREATE TABLE orders (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES profiles(id),
  course_id UUID REFERENCES courses(id),
  base_amount DECIMAL,
  service_fee DECIMAL,
  tax DECIMAL,
  amount DECIMAL,
  take_home DECIMAL,
  payment_ref TEXT,
  status TEXT,
  payment_period TEXT,
  created_at TIMESTAMP
);
```

##### Student Teacher Mark Scheme Purchases Table

```sql theme={null}
CREATE TABLE student_teacher_mark_scheme_purchases (
  id UUID PRIMARY KEY,
  student_id UUID REFERENCES profiles(id),
  teacher_mark_scheme_id UUID REFERENCES teacher_mark_schemes(id),
  order_id UUID REFERENCES orders(id),
  amount_paid DECIMAL,
  currency TEXT,
  payment_status TEXT,
  purchase_date TIMESTAMP,
  created_at TIMESTAMP,
  updated_at TIMESTAMP
);
```

#### Error Handling

* **Database Errors**: Comprehensive error handling for all database operations
* **Validation**: Parameter validation for all methods
* **Status Validation**: Ensures valid status transitions
* **Logging**: Detailed error logging for debugging

#### Dependencies

* **Supabase**: Database operations
* **PayMob Integration**: Payment processing
* **Database Tables**:
  * `orders`
  * `student_teacher_mark_scheme_purchases`
  * `teacher_mark_schemes`
  * `profiles`

## Service Integration Patterns

### 1. Error Handling Pattern

```typescript theme={null}
try {
  const result = await service.method(params);
  return { success: true, data: result };
} catch (error) {
  console.error('Service error:', error);
  return { success: false, error: error.message };
}
```

### 2. Database Operation Pattern

```typescript theme={null}
const { data, error } = await supabase
  .from('table')
  .select('*')
  .eq('id', id)
  .single();

if (error) {
  throw new Error(`Database error: ${error.message}`);
}

return data;
```

### 3. Validation Pattern

```typescript theme={null}
if (!param || param.trim() === '') {
  throw new Error('Invalid parameter');
}
```

## Service Testing Strategy

### 1. Unit Testing

* **Service Methods**: Test individual service methods
* **Error Handling**: Test error scenarios
* **Validation**: Test parameter validation
* **Mocking**: Mock external dependencies

### 2. Integration Testing

* **Database Integration**: Test database operations
* **API Integration**: Test external API calls
* **End-to-End**: Test complete service flows

### 3. Performance Testing

* **Response Times**: Measure service response times
* **Database Performance**: Test database query performance
* **Memory Usage**: Monitor memory consumption

## Service Documentation Standards

### 1. Code Documentation

* **JSDoc Comments**: Comprehensive method documentation
* **Type Definitions**: Clear TypeScript interfaces
* **Usage Examples**: Practical usage examples
* **Error Scenarios**: Documented error handling

### 2. API Documentation

* **Method Signatures**: Clear method signatures
* **Parameter Types**: Detailed parameter documentation
* **Return Types**: Clear return type documentation
* **Error Types**: Documented error types

## Future Service Enhancements

### 1. Planned Features

* **Caching Layer**: Implement service-level caching
* **Rate Limiting**: Add rate limiting for API calls
* **Retry Logic**: Implement retry mechanisms
* **Monitoring**: Add service monitoring and metrics

### 2. Performance Improvements

* **Connection Pooling**: Optimize database connections
* **Query Optimization**: Optimize database queries
* **Batch Operations**: Implement batch processing
* **Async Processing**: Add background processing

### 3. Security Enhancements

* **Input Sanitization**: Enhanced input validation
* **Access Control**: Implement service-level access control
* **Audit Logging**: Add comprehensive audit logging
* **Encryption**: Implement data encryption
