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

# Utils

# Frontend Utilities Documentation

This document provides comprehensive documentation for all utility functions, classes, and helper modules in the STO Education Platform frontend.

## Utilities Overview

The application includes various utility modules that provide common functionality, helper functions, and specialized tools used throughout the application.

## Utility Categories

### 1. Update Detection Utility

#### Location: `src/utils/updateDetector.ts`

#### Purpose

Handles automatic detection of application updates and notifies users when new versions are available.

#### Features

* **Version Comparison**: Compares current app version with server version
* **Multiple Detection Methods**: Uses version numbers, build times, and hashes
* **Automatic Monitoring**: Periodic checks for updates
* **User Notifications**: Notifies users when updates are available
* **Cooldown System**: Prevents excessive update checks
* **Event-driven**: Listener pattern for update notifications

#### Classes

##### UpdateDetector

```typescript theme={null}
class UpdateDetector {
  private currentVersion: string;
  private currentBuildTime: string;
  private currentHash: string;
  private checkInterval: number;
  private isChecking: boolean;
  private listeners: Array<(updateAvailable: boolean) => void>;
  private lastUpdateCheck: number;
  private updateCheckCooldown: number;
}
```

#### Interfaces

##### UpdateInfo

```typescript theme={null}
interface UpdateInfo {
  version: string;
  buildTime: string;
  hash: string;
}
```

##### ServerVersionInfo

```typescript theme={null}
interface ServerVersionInfo {
  version: string;
  buildTime: string;
  hash: string;
  lastModified?: string;
}
```

#### Key Methods

##### Constructor

```typescript theme={null}
constructor(checkIntervalMinutes: number = 5)
```

* Initializes the update detector
* Sets up version information from various sources
* Configures check interval (default: 5 minutes)
* Logs initialization information

##### startMonitoring

```typescript theme={null}
public startMonitoring(): void
```

* Starts automatic update monitoring
* Performs immediate check for updates
* Sets up periodic checking interval
* Listens for page visibility changes
* Listens for window focus events

##### checkForUpdates

```typescript theme={null}
private async checkForUpdates(): Promise<boolean>
```

* Checks for application updates
* Implements cooldown system to prevent excessive checks
* Compares current version with server version
* Returns true if update is available

##### getCurrentVersion

```typescript theme={null}
private getCurrentVersion(): string
```

* Retrieves current application version
* Tries multiple sources:
  1. Vite injected globals (`__APP_VERSION__`)
  2. Meta tags (`meta[name="app-version"]`)
  3. Environment variables (`VITE_APP_VERSION`)

##### getCurrentBuildTime

```typescript theme={null}
private getCurrentBuildTime(): string
```

* Retrieves current build time
* Tries multiple sources:
  1. Vite injected globals (`__BUILD_TIME__`)
  2. Meta tags (`meta[name="build-time"]`)
  3. Environment variables (`VITE_BUILD_TIME`)

##### getCurrentHash

```typescript theme={null}
private getCurrentHash(): string
```

* Retrieves current build hash
* Tries multiple sources:
  1. Vite injected globals (`__BUILD_HASH__`)
  2. Meta tags (`meta[name="build-hash"]`)
  3. Environment variables (`VITE_BUILD_HASH`)

##### compareVersions

```typescript theme={null}
private compareVersions(current: string, latest: string): number
```

* Compares semantic version numbers
* Returns -1 if update needed, 0 if equal, 1 if current is newer
* Handles version parts of different lengths

##### compareBuildTimes

```typescript theme={null}
private compareBuildTimes(current: string, server: string): boolean
```

* Compares build timestamps
* Normalizes dates to ignore seconds and milliseconds
* Returns true if server build is newer

##### getServerVersion

```typescript theme={null}
public async getServerVersion(): Promise<string>
```

* Fetches server version from `/version.json`
* Handles network errors gracefully
* Returns 'unknown' if fetch fails

##### onUpdateAvailable

```typescript theme={null}
public onUpdateAvailable(callback: (updateAvailable: boolean) => void): void
```

* Registers update notification listener
* Allows components to subscribe to update events

##### removeListener

```typescript theme={null}
public removeListener(callback: (updateAvailable: boolean) => void): void
```

* Removes update notification listener
* Cleans up event handlers

##### forceCheck

```typescript theme={null}
public forceCheck(): void
```

* Forces immediate update check
* Bypasses cooldown system
* Useful for manual update checking

#### Update Detection Methods

##### 1. Version Number Comparison

* Compares semantic version numbers (e.g., "1.2.3")
* Most reliable method for major updates

##### 2. Build Time Comparison

* Compares build timestamps
* Useful for detecting minor updates
* Normalizes timestamps for accurate comparison

##### 3. Build Hash Comparison

* Compares build hashes
* Detects any code changes
* Most sensitive detection method

#### Usage Example

```typescript theme={null}
import { updateDetector } from '../utils/updateDetector';

// Start monitoring for updates
updateDetector.startMonitoring();

// Listen for update notifications
updateDetector.onUpdateAvailable((hasUpdate) => {
  if (hasUpdate) {
    // Show update notification to user
    showUpdateModal();
  }
});

// Force immediate check
updateDetector.forceCheck();
```

#### Singleton Instance

```typescript theme={null}
export const updateDetector = new UpdateDetector(5); // Check every 5 minutes
```

#### Integration with Vite

The utility integrates with Vite's build process through:

* **Global Variables**: Injected via `vite.config.ts`
* **Meta Tags**: Generated during build
* **Version File**: Creates `/public/version.json`

#### Error Handling

* **Network Errors**: Graceful handling of fetch failures
* **Parse Errors**: Safe JSON parsing with fallbacks
* **Invalid Versions**: Handles malformed version strings
* **Missing Data**: Fallbacks for missing version information

#### Performance Considerations

* **Cooldown System**: Prevents excessive API calls
* **Lazy Loading**: Only checks when needed
* **Efficient Comparison**: Optimized version comparison algorithms
* **Memory Management**: Proper cleanup of event listeners

***

## Custom Hooks

### 1. Mochi Events Hook

#### Location: `src/hooks/useMochiEvents.ts`

#### Purpose

Provides real-time event handling for the Mochi gamification system using Supabase real-time subscriptions.

#### Features

* **Real-time Subscriptions**: Listens to database changes
* **Toast Notifications**: Shows user-friendly notifications
* **Event Filtering**: Filters relevant events for Mochi reactions
* **Automatic Cleanup**: Unsubscribes from channels on unmount

#### Implementation

```typescript theme={null}
export function useMochiEvents() {
  useEffect(() => {
    // Assignment submission listener
    const assignmentChannel = supabase
      .channel('assignment_submissions_mochi')
      .on('postgres_changes', {
        event: 'INSERT',
        schema: 'public',
        table: 'assignment_submissions'
      }, (payload) => {
        toast.success("🍡 Mochi is proud of your submission! Keep it up!", {
          position: "bottom-right",
          autoClose: 3000,
        });
      })
      .subscribe();

    // Session attendance listener
    const attendanceChannel = supabase
      .channel('session_attendance_mochi')
      .on('postgres_changes', {
        event: 'INSERT',
        schema: 'public',
        table: 'session_attendance'
      }, (payload) => {
        if (payload.new.status === 'attended') {
          toast.success("🎉 Mochi is happy you attended class!", {
            position: "bottom-right",
            autoClose: 3000,
          });
        }
      })
      .subscribe();

    // Cleanup function
    return () => {
      assignmentChannel.unsubscribe();
      attendanceChannel.unsubscribe();
    };
  }, []);
}
```

#### Event Types

##### Assignment Submissions

* **Table**: `assignment_submissions`
* **Event**: `INSERT`
* **Action**: Shows congratulatory message
* **Message**: "🍡 Mochi is proud of your submission! Keep it up!"

##### Session Attendance

* **Table**: `session_attendance`
* **Event**: `INSERT`
* **Condition**: Only for attended sessions
* **Action**: Shows attendance celebration
* **Message**: "🎉 Mochi is happy you attended class!"

#### Usage Example

```typescript theme={null}
import { useMochiEvents } from '../hooks/useMochiEvents';

function StudentDashboard() {
  useMochiEvents(); // Enables Mochi event notifications
  
  return (
    <div>
      {/* Dashboard content */}
    </div>
  );
}
```

#### Dependencies

* **Supabase**: Real-time subscriptions
* **React Toastify**: Toast notifications
* **React**: useEffect hook for lifecycle management

***

## Type Definitions

### Location: `src/lib/types.ts`

#### Purpose

Centralized TypeScript type definitions for the entire application.

#### Core Types

##### Education System Types

```typescript theme={null}
interface EducationSystem {
  id: string;
  name: string;
}

interface EducationGrade {
  id: string;
  education_system_id: string;
  name: string;
}

interface Subject {
  id: string;
  name: string;
}
```

##### Teacher Subject Types

```typescript theme={null}
interface TeacherSubject {
  id: string;
  subject_id: string;
  education_system_id: string;
  education_grade_id: string;
  subject: {
    name: string;
  };
  education_system: {
    name: string;
  };
  education_grade: {
    name: string;
  };
}

interface TeacherSubjectResponse {
  id: string;
  subject_id: string;
  education_system_id: string;
  education_grade_id: string;
  subject: {
    name: string;
  }[];
  education_system: {
    name: string;
  }[];
  education_grade: {
    name: string;
  }[];
}
```

##### User Registration Types

```typescript theme={null}
interface SignUpFormData {
  email: string;
  password: string;
  confirmPassword: string;
  firstName: string;
  lastName: string;
  mobile: string;
  educationSystemId?: string;
  educationGradeId?: string;
  country: string;
  region: string;
  city: string;
  userType: 'student' | 'parent' | 'teacher';
  gender: 'male' | 'female' | 'other';
  nationality?: string;
}
```

##### Course Types

```typescript theme={null}
interface Course {
  id: string;
  title: string;
  cost: number;
  rating?: number;
  ratings_count?: number;
  sessions_count: number;
  session_duration: number;
  teacher: {
    first_name: string;
    last_name: string;
  };
  education_system: {
    id: string;
    name: string;
  };
  education_grade: {
    id: string;
    name: string;
  };
  subject: {
    id: string;
    name: string;
  };
}
```

##### Profile Types

```typescript theme={null}
interface Profile {
  id: string;
  first_name: string;
  last_name: string;
  gender: string;
  email: string;
  mobile: string;
  country: string;
  region: string;
  city: string;
  profile_image: string | null;
  education_system?: {
    name: string;
  };
  education_grade?: {
    name: string;
  };
}
```

##### Teacher Mark Scheme Types

```typescript theme={null}
interface TeacherMarkScheme {
  id: string;
  subject_id: string;
  exam_category: 'AL' | 'IGCSE';
  paper_year: string;
  paper_season: 'w' | 's' | 'm';
  paper_category: string;
  original_filename: string;
  file_url: string;
  file_size: number;
  teacher_explanation: string;
  teacher_notes?: string;
  is_public: boolean;
  is_approved: boolean;
  created_at: string;
  updated_at: string;
}

interface TeacherMarkSchemePurchase {
  id: string;
  student_id: string;
  teacher_mark_scheme_id: string;
  order_id: string;
  purchase_date: string;
  amount_paid: number;
  currency: string;
  payment_status: 'pending' | 'completed' | 'failed' | 'refunded';
  access_expires_at?: string;
  created_at: string;
  updated_at: string;
}

interface TeacherMarkSchemeWithPurchase extends TeacherMarkScheme {
  is_purchased?: boolean;
  purchase_details?: TeacherMarkSchemePurchase;
}

interface TeacherMarkSchemePaymentRequest {
  teacher_mark_scheme_id: string;
  amount: number;
  currency?: string;
  student_id: string;
}

interface TeacherMarkSchemePaymentResponse {
  success: boolean;
  payment_url?: string;
  order_id?: string;
  error?: string;
}
```

***

## Library Utilities

### 1. Authentication Utilities

#### Location: `src/lib/auth.ts`

#### Purpose

Provides authentication-related utility functions and helpers.

#### Features

* **User Session Management**: Handles user session operations
* **Profile Retrieval**: Fetches user profile information
* **Session Validation**: Validates user sessions
* **Error Handling**: Comprehensive error handling

#### Key Functions

```typescript theme={null}
// Get current user from session
async function getCurrentUser() {
  const { data: { session } } = await supabase.auth.getSession();
  return session?.user ?? null;
}

// Get user profile
async function getUserProfile(userId: string) {
  const { data, error } = await supabase
    .from('profiles')
    .select('*')
    .eq('id', userId)
    .single();
  
  return { data, error };
}
```

### 2. Payment Utilities

#### Location: `src/lib/paymob.ts`

#### Purpose

Handles PayMob payment gateway integration and payment processing.

#### Features

* **Payment Intent Creation**: Creates payment intentions
* **Payment Link Generation**: Generates payment URLs
* **Billing Data Handling**: Manages billing information
* **Error Handling**: Comprehensive payment error handling

#### Key Functions

```typescript theme={null}
// Create payment intention
async function createPaymentIntention(
  config: PaymobConfig,
  request: PaymentRequest
): Promise<string>

// Generate payment link
function generatePaymentLink(
  publicKey: string, 
  clientSecret: string
): string
```

### 3. Analytics Utilities

#### Location: `src/lib/posthog.ts`

#### Purpose

Provides PostHog analytics integration with custom hooks and utility functions.

#### Features

* **Event Tracking**: Custom event tracking
* **User Identification**: User identification and properties
* **Feature Flags**: Feature flag support
* **Group Analytics**: Group-based analytics

#### Custom Hook

```typescript theme={null}
export const useAnalytics = () => {
  const posthog = usePostHog();
  
  return {
    track: (event: string, properties?: Record<string, any>) => void;
    identify: (userId: string, properties?: Record<string, any>) => void;
    setUser: (properties: Record<string, any>) => void;
    reset: () => void;
    isFeatureEnabled: (flag: string): boolean;
    group: (groupType: string, groupKey: string, properties?: Record<string, any>) => void;
  };
};
```

### 4. Supabase Utilities

#### Location: `src/lib/supabase.ts`

#### Purpose

Provides Supabase client configuration and initialization.

#### Implementation

```typescript theme={null}
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

export const supabase = createClient(supabaseUrl, supabaseAnonKey);
```

***

## Utility Best Practices

### 1. Error Handling

* **Graceful Degradation**: Handle errors without breaking functionality
* **User-friendly Messages**: Provide clear error messages
* **Logging**: Comprehensive error logging for debugging
* **Fallbacks**: Provide fallback values when possible

### 2. Performance Optimization

* **Lazy Loading**: Load utilities only when needed
* **Caching**: Cache expensive operations
* **Debouncing**: Prevent excessive function calls
* **Memory Management**: Proper cleanup of resources

### 3. Type Safety

* **TypeScript Interfaces**: Define clear interfaces
* **Generic Types**: Use generics for reusable utilities
* **Type Guards**: Implement type checking functions
* **Documentation**: Document type definitions

### 4. Testing

* **Unit Tests**: Test individual utility functions
* **Integration Tests**: Test utility integrations
* **Mock Dependencies**: Mock external dependencies
* **Edge Cases**: Test error conditions and edge cases

## Future Utility Enhancements

### 1. Planned Features

* **Caching Layer**: Implement utility-level caching
* **Performance Monitoring**: Add performance metrics
* **Advanced Error Handling**: Enhanced error recovery
* **Utility Composition**: Better utility composition patterns

### 2. Performance Improvements

* **Bundle Optimization**: Optimize utility bundle size
* **Tree Shaking**: Better tree shaking support
* **Lazy Loading**: Advanced lazy loading strategies
* **Memory Optimization**: Better memory management

### 3. Developer Experience

* **Better Documentation**: Enhanced documentation
* **Development Tools**: Better development utilities
* **Debugging Support**: Enhanced debugging capabilities
* **Testing Utilities**: Better testing support
