# Laravel CMS – System Architecture

**Purpose**: Management & orchestration layer for Moodle LMS  
**Key Integration**: Moodle LMS (content storage & delivery)  
**Architecture**: Multi-tenant CMS with REST API sync

---

## System Overview

- **Laravel CMS**: Management & orchestration layer
- **Moodle LMS**: Content storage & delivery layer
- **Users**: Admins, teachers, content editors, students
- **Multi-Tenant**: Separate databases per organization
- **Real-time**: Notifications via Pusher/Soketi

---

## Why This CMS Exists

- Centralized content management interface
- Decouples business logic from LMS complexity
- Scales independently from Moodle
- Multi-tenant support for multiple organizations
- User-friendly content authoring workflow

---

## High-level Architecture

```mermaid
graph TD
    User[Users<br/>Admin/Teacher/Student] --> CMS[Laravel CMS<br/>Management Layer]
    
    CMS --> MasterDB[(Master Database<br/>Users, Tenants)]
    CMS --> TenantDB1[(Tenant DB 1<br/>ICC)]
    CMS --> TenantDB2[(Tenant DB 2<br/>OMO)]
    
    CMS --> Moodle[Moodle LMS<br/>Content Storage & Delivery]
    CMS --> S3[AWS S3<br/>Media Files]
    CMS --> Queue[Queue System<br/>Async Jobs]
    CMS --> Notifications[Pusher/Soketi<br/>Real-time]
    
    Moodle --> MoodleDB[(Moodle Database<br/>Content & Grades)]
    
    Student[Students] --> Moodle
    
    style CMS fill:#e1f5ff
    style Moodle fill:#fff4e1
```

---

## Technology Stack

- **Framework**: Laravel 11.x (PHP 8.2+)
- **Database**: MySQL (master + per-tenant databases)
- **Queue**: Database queue (configurable: Redis, SQS)
- **Storage**: Local filesystem + AWS S3
- **Cache**: Laravel cache (Redis/database/file)
- **External**: Moodle LMS, Keycloak/ICANID SSO, OpenAI/Gemini

---

## Core Modules

- **Authentication & Authorization**: Multi-provider auth (Laravel, Keycloak, ICANID, Google OAuth)
- **User Management**: Users, teachers, students with multi-tenant support
- **Content Management**: Courses, sections, activities (quizzes, assignments, resources)
- **Moodle Integration**: REST API sync for content and enrollments
- **Assessment**: Exams, rubrics, grading, performance tracking
- **Notifications**: Real-time notifications via WebSocket

---

## Folder Structure

- **`app/Http/Controllers/`**: Request handlers
- **`app/Models/`**: Eloquent ORM models
- **`app/Services/`**: Business logic layer
- **`app/Jobs/`**: Async queue jobs
- **`app/ApiService/`**: Moodle API wrappers
- **`routes/`**: Web, API, console routes
- **`database/migrations/`**: Schema definitions

---

## Moodle Integration – Role Split

**Laravel CMS Responsibilities:**
- Content authoring & organization
- User & enrollment management
- Business logic & workflows
- Multi-tenant orchestration

**Moodle LMS Responsibilities:**
- Actual learning content storage
- Student-facing learning interface
- Assessment execution & grading
- Completion tracking & gradebook

---

## Moodle Data Flow – Content Creation

```mermaid
sequenceDiagram
    participant Admin
    participant CMS as Laravel CMS
    participant Observer
    participant Moodle API
    participant Moodle DB
    
    Admin->>CMS: Create Course/Section/Activity
    CMS->>CMS: Save to api_moodle table
    CMS->>Observer: ApiMoodle created
    Observer->>CMS: Create Course record
    CMS->>Moodle API: POST create_course/create_activity
    Moodle API->>Moodle DB: Store content
    Moodle API->>CMS: Return moodle_id
    CMS->>CMS: Update api_moodle.moodle_id
    CMS->>Admin: Success with IDs
```

---

## Moodle Data Flow – User Enrollment

```mermaid
sequenceDiagram
    participant Admin
    participant CMS as Laravel CMS
    participant Queue
    participant Job
    participant Moodle API
    
    Admin->>CMS: Enroll student in course
    CMS->>CMS: Create course_student record
    CMS->>Queue: Dispatch enrollment job
    
    Queue->>Job: ProcessStudentEnrollmentJob
    Job->>Moodle API: POST core_enrol_enrol_users
    Moodle API->>Job: Enrollment success
    Job->>CMS: Update enrollment status
```

---

## Data Ownership

**Laravel CMS Stores:**
- Content metadata & structure
- User accounts & roles
- Enrollment relationships
- Business configuration
- Aggregated scores

**Moodle LMS Stores:**
- Actual learning content
- Student submissions
- Detailed grades & attempts
- Completion data (source of truth)
- User login credentials

---

## Multi-Tenant Architecture

- **Master Database**: Users, tenants, global config
- **Tenant Databases**: Separate DB per organization (ICC, OMO, etc.)
- **Dynamic Connections**: Runtime tenant connection setup
- **User Assignment**: Users can belong to multiple tenants
- **Domain Routing**: Automatic tenant selection by domain

---

## Authentication Methods

- **Laravel Auth**: Standard email/password
- **Keycloak SSO**: Enterprise SSO integration
- **ICANID SSO**: Custom SSO provider
- **Google OAuth**: Social login
- **API Tokens**: Laravel Sanctum for API access

---

## Authorization (RBAC)

- **Roles**: Admin, teacher, content_editor, student
- **Permissions**: Route-based permissions
- **Role-Permission Mapping**: Many-to-many relationships
- **Admin Bypass**: Admin role bypasses all checks
- **Tenant-Specific**: Permissions per tenant database

---

## Security & Permissions

- **CSRF Protection**: All forms protected
- **SQL Injection Prevention**: Eloquent ORM with parameter binding
- **XSS Protection**: Input sanitization, HTMLPurifier
- **Password Hashing**: Bcrypt via Laravel Hash
- **API Authentication**: Sanctum tokens
- **Error Tracking**: Sentry integration

---

## Content Types

- **Courses**: Top-level containers
- **Sections**: Course chapters
- **Quizzes**: Assessment activities
- **Assignments**: Submission-based activities
- **Resources**: File downloads
- **URLs**: External links
- **H5P Tools**: Interactive content

---

## Sync Strategy

**CMS → Moodle (Synchronous):**
- Content creation/updates
- Immediate REST API calls
- Error handling & logging

**CMS → Moodle (Asynchronous):**
- User creation (queue job)
- Enrollment processing (queue job)
- Bulk operations

**Moodle → CMS (Scheduled):**
- Activity completions (every 5 min)
- Course data sync (on-demand)

---

## Queue System

- **Driver**: Database queue (configurable)
- **Workers**: Multiple workers via Supervisor
- **Key Jobs**:
  - Student creation
  - Enrollment processing
  - Activity completion sync
  - Bulk imports
- **Retry**: Automatic retry with backoff

---

## Scheduled Tasks (Cron)

- **Activity Completion**: Every 5 minutes
- **Deletion Queue**: Every minute
- **Log Clearing**: Daily at midnight
- **Study Session Auto-End**: Every 5 minutes
- **Student History Update**: Twice daily (tenant-specific)

---

## Deployment Architecture

- **Web Server**: Nginx/Apache + PHP-FPM
- **Application**: Laravel application in PHP-FPM workers
- **Queue Workers**: Supervisor-managed workers
- **Cron**: Laravel scheduler (single cron entry)
- **Storage**: Local + AWS S3
- **Monitoring**: Sentry for errors

---

## Configuration Highlights

**Environment Variables:**
- `URL_API_LMS`: Moodle REST API endpoint
- `TOKEN_LMS`: Moodle web service token
- `DB_*`: Database connections
- `AWS_*`: S3 configuration
- `QUEUE_CONNECTION`: Queue driver

**Config Files:**
- `config/services.php`: External services
- `config/database.php`: DB connections
- `config/queue.php`: Queue settings

---

## Key Models

- **`ApiMoodle`**: Moodle entities (courses, sections, activities)
- **`Course`**: CMS course representation
- **`Students`**: Student records
- **`Teachers`**: Teacher records
- **`User`**: System users
- **`HocmaiTenant`**: Tenant definitions

---

## Key Relationships

**Hierarchical:**
- Course → Sections → Activities (via `parent_id`)

**Many-to-Many:**
- Users ↔ Roles ↔ Permissions
- Students ↔ Courses (enrollments)
- Teachers ↔ Courses (assignments)
- Classes ↔ Courses

**One-to-One:**
- User → Teacher (optional)

---

## Main System Flows

1. **User Login**: Multi-provider auth → Role check → Tenant selection
2. **Content Creation**: CMS form → Save to DB → Sync to Moodle → Store IDs
3. **Enrollment**: Admin action → Queue job → Moodle API → Update status
4. **Completion Tracking**: Moodle → Scheduled sync → Update CMS progress

---

## Moodle API Integration

**Authentication:**
- Token-based (Moodle web service token)
- Included in all API requests

**Key Endpoints:**
- `core_course_create_courses`: Create courses
- `core_user_create_users`: Create users
- `core_enrol_enrol_users`: Enroll users
- `local_custom_service_create_activity_*`: Create activities
- `core_completion_get_activities_completion_status`: Get completions

---

## Data Model Overview

**Master Database:**
- Users, roles, permissions
- Tenants, tenant domains
- User-tenant assignments

**Tenant Databases:**
- Courses, sections, activities
- Students, teachers, classes
- Enrollments, assessments
- Activity progress tracking

**Moodle Database:**
- Actual content & submissions
- Grades & completion data

---

## Error Handling

- **API Errors**: Logged with context
- **Queue Failures**: Stored in `failed_jobs` table
- **Validation**: Laravel form validation
- **Exception Handling**: Try-catch blocks with logging
- **Monitoring**: Sentry for production errors

---

## Performance Optimizations

- **Caching**: Route, config, view caching
- **Queue Processing**: Async for heavy operations
- **Database**: Connection pooling, query optimization
- **CDN**: Static assets (if configured)
- **Indexing**: Database indexes on foreign keys

---

## TL;DR – System Summary

- **Laravel CMS** = Management & orchestration layer
- **Moodle LMS** = Content storage & delivery layer
- **Multi-Tenant** = Separate databases per organization
- **Sync Strategy** = CMS → Moodle (API), Moodle → CMS (scheduled)
- **Key Principle**: CMS manages, Moodle delivers

---

## Key Takeaways

1. **Separation of Concerns**: CMS handles management, Moodle handles delivery
2. **Multi-Tenancy**: Isolated databases with dynamic connections
3. **Async Processing**: Heavy operations via queue system
4. **REST API Integration**: Token-based Moodle API communication
5. **Role-Based Access**: Granular permissions per tenant
6. **Scalability**: Independent scaling of CMS and Moodle

---

## Questions?

**Documentation**: `docs/system-architecture.md`  
**Key Files**: `app/Models/Common.php`, `app/ApiService/FeService.php`  
**Configuration**: `config/services.php`, `.env`

