Skip to main content

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
Announcement Email
Purchase Confirmation Email
Assignment Posted Email
Course Completion Email
New Message Email
Assignment Graded Email
Payment Success Email
New Enrollment Email

Service Functions

sendSessionStartEmail
sendAnnouncementEmail
sendPurchaseConfirmationEmail
sendAssignmentPostedEmail
sendCourseCompletionEmail
sendNewMessageEmail
sendAssignmentGradedEmail
sendPaymentSuccessEmail
sendNewEnrollmentEmail

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

Service Methods

getOverallScore
  • Fetches the overall Mochi score for a student
  • Returns null if no score exists
  • Handles database errors gracefully
getCourseScores
  • Fetches course-specific Mochi scores
  • Returns a map of course IDs to scores
  • Handles missing scores gracefully
calculateAndSaveScores
  • Calculates scores for all active courses
  • Saves course-specific scores
  • Calculates and saves overall score
  • Handles errors during calculation
calculateOverallScore (Private)
  • 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)
  • Calculates score for a specific course
  • Tracks assignment submissions and timeliness
  • Calculates attendance percentage
  • Calculates grade average
  • Returns validated score object
saveCourseScore
  • Saves course-specific scores to database
  • Handles both insert and update operations
  • Validates score data before saving
  • Comprehensive error handling
saveOverallScore
  • Saves overall score to database
  • Uses course_id = null for overall scores
  • Handles both insert and update operations
  • Validates score data before saving
triggerRecalculation
  • 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
PageData

Service Methods

getPageContent
  • Fetches all content for a specific page
  • Returns empty object if no content exists
  • Handles database errors gracefully
  • Validates page parameter
getContent
  • Fetches specific content item by key
  • Returns null if content doesn’t exist
  • Validates both page and contentKey parameters
  • Uses getPageContent internally
savePageContent
  • Saves entire page content object
  • Handles both insert and update operations
  • Validates page parameter
  • Comprehensive error handling
saveContent
  • Saves individual content item
  • Updates existing content or adds new item
  • Validates all parameters
  • Uses savePageContent internally
exportPageContent
  • Exports all content for a page
  • Used for backup or migration purposes
  • Returns complete content object
importPageContent
  • Imports content for a page
  • Validates content map
  • Saves entire content at once
  • Used for content migration
checkPageContentExists
  • 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
Saving Content
Batch Content Save

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
TeacherMarkSchemeWithPurchase
TeacherMarkSchemePaymentRequest
TeacherMarkSchemePaymentResponse

Service Methods

checkPurchaseStatus
  • 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
  • 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
  • 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
  • Updates payment status after payment processing
  • Updates both order and purchase records
  • Handles status transitions
  • Returns success/failure result
getTeacherMarkSchemeWithPurchaseStatus
  • 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
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
Student Teacher Mark Scheme Purchases Table

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

2. Database Operation Pattern

3. Validation Pattern

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