# EnCoach Platform -- Frontend Software Requirements Specification

**Document Version:** 1.1
**Date:** April 2026
**Status:** Active -- Ready for Development
**Source Document:** `encoach_workflows_v3.pdf` (v3.0, April 2026)
**Audience:** Odoo Developer (full-stack, using Cursor IDE)
**Scope:** All new frontend pages, components, and UI flows required to implement the 6 platform workflows, exam template paths (international + custom), adaptive learning engine, Math/IT support, and white-labelling.

---

## Implementation Context

| Artifact | Location |
|----------|----------|
| **Frontend Repository** | `https://git.albousalh.com/devops/encoach_frontend_new_v2.git` (branch: `main`) |
| **Backend Repository** | `https://git.albousalh.com/devops/encoach_backend_new_v2.git` (branch: `main`) |
| **Staging Frontend** | `http://5.189.151.117:3000` |
| **Staging Backend (Odoo 19)** | `http://5.189.151.117:8069` |
| **Frontend Stack** | React 18, TypeScript, Vite 5, shadcn/ui, TanStack Query v5, React Router v6 |
| **Backend Stack** | Odoo 19, Python 3.11, PostgreSQL 16, Docker Compose |

---

## Table of Contents

**Part I -- Context and Baseline**
1. [Introduction](#1-introduction)
2. [Existing System Summary](#2-existing-system-summary)
3. [Architecture and Conventions](#3-architecture-and-conventions)

**Part II -- Workflow 1: User Signup (Individual)**
4. [Registration Page](#4-registration-page)
5. [Email Verification Page](#5-email-verification-page)
6. [Onboarding Wizard](#6-onboarding-wizard)

**Part III -- Workflow 2: Placement Test**
7. [Placement Test Briefing](#7-placement-test-briefing)
8. [CAT Test Interface](#8-cat-test-interface)
9. [Placement Results and Learning Path Preview](#9-placement-results-and-learning-path-preview)
10. [Payment and Access Options](#10-payment-and-access-options)

**Part IV -- Workflow 3: Exam Configuration (International + Custom)**
11. [Exam Template Paths](#11-exam-template-paths)
12. [International Template -- IELTS Exam Initialization](#12-international-template----ielts-exam-initialization)
13. [Per-Skill Configuration Panels](#13-per-skill-configuration-panels)
14. [Content Pool and Question Assembly](#14-content-pool-and-question-assembly)
15. [Exam Assembly and Validation](#15-exam-assembly-and-validation)
16. [Custom Template -- Exam Creation](#16-custom-template----exam-creation)

**Part V -- Workflow 4: General English Exam**
17. [Exam Session Interface](#17-exam-session-interface)
18. [Grading and Score Release](#18-grading-and-score-release)
19. [Results Display and Reporting](#19-results-display-and-reporting)
20. [Result Routing](#20-result-routing)

**Part VI -- Workflow 5: Course Generation**
21. [Gap Analysis Dashboard](#21-gap-analysis-dashboard)
22. [Course Structure Configuration](#22-course-structure-configuration)
23. [Module Builder](#23-module-builder)
24. [Course Delivery and Progress](#24-course-delivery-and-progress)

**Part VII -- Workflow 6: Entity Student Onboarding**
25. [Admin Bulk Upload Interface](#25-admin-bulk-upload-interface)
26. [Credential Delivery Dashboard](#26-credential-delivery-dashboard)
27. [Entity Student First Login](#27-entity-student-first-login)

**Part VIII -- AI Course Generation**
28. [General English AI Course Generation](#28-general-english-ai-course-generation)
29. [AI IELTS Course Generation](#29-ai-ielts-course-generation)

**Part IX -- Adaptive Learning Engine UI**
30. [Adaptive Engine Dashboard](#30-adaptive-engine-dashboard)
31. [Engine Signals and Decision Visualization](#31-engine-signals-and-decision-visualization)

**Part X -- Entity Management and White-Labelling**
32. [Entity Level Mapping Configuration](#32-entity-level-mapping-configuration)
33. [White-Label Branding Settings](#33-white-label-branding-settings)

**Part XI -- Math and IT Subject Support**
34. [Math Content Rendering](#34-math-content-rendering)
35. [IT Content Rendering](#35-it-content-rendering)
36. [Subject-Agnostic Placement and Courses](#36-subject-agnostic-placement-and-courses)

**Part XII -- Score Release and Reporting**
37. [Admin Score Approval Queue](#37-admin-score-approval-queue)
38. [PDF Report with QR Code](#38-pdf-report-with-qr-code)
39. [Public Score Verification Page](#39-public-score-verification-page)

**Part XIII -- Technical Specifications**
40. [New Pages Inventory](#40-new-pages-inventory)
41. [New Services Inventory](#41-new-services-inventory)
42. [New Types Inventory](#42-new-types-inventory)
43. [API Contracts](#43-api-contracts)

---

# Part I -- Context and Baseline

## 1. Introduction

### 1.1 Purpose

This document specifies every frontend page, component, and user interaction required to implement the EnCoach platform workflows as defined in `encoach_workflows_v3.pdf` (v3.0). It is the single source of truth for frontend development of the workflow features.

### 1.2 Scope

The document covers 6 workflows, the adaptive learning engine (4 phases), Math/IT subject support, white-labelling, and score release/reporting. Each section describes:

- **What the user sees** -- page layout, components, form fields
- **What the user does** -- interactions, validations, navigation flow
- **What the frontend calls** -- API endpoints, request/response shapes
- **Error and edge cases** -- validation messages, loading states, empty states

### 1.3 Audience

This document is written for a full-stack Odoo developer who will implement both the frontend React code and the backend Odoo modules. The developer uses Cursor IDE and has access to both the frontend and backend repositories.

### 1.4 Design Principles (from Workflow Document)

| # | Principle | Impact on Frontend |
|---|-----------|-------------------|
| 1 | Exam type is always the root parameter | Every exam/course flow starts with an exam type selector (Academic vs General Training) |
| 2 | Learning path shown before payment | Student sees their personalised course plan BEFORE any payment prompt |
| 3 | Teacher as supervisor, not builder | In adaptive mode, teacher UI shows oversight controls (thresholds, alerts), not manual sequencing |
| 4 | All results stored on all paths | Every exam attempt shows in student history regardless of pass/fail |
| 5 | Shared content database | Content pool browser shows all content once -- never duplicated across exam and course views |
| 6 | White-labelling support | All student-facing pages apply entity branding (logo, colours) when student is linked to an entity |

### 1.5 Workflow Coverage

| # | Workflow | Status | Sections |
|---|----------|--------|----------|
| 1 | User Signup (Individual) | To Build | 4--6 |
| 2 | Placement Test | To Build | 7--10 |
| 3 | IELTS / English Exam Configuration | To Build | 11--14 |
| 4 | General English Exam Generation | To Build | 15--18 |
| 5 | Course Generation | To Build | 19--22 |
| 6 | Entity Student Onboarding | To Build | 23--25 |
| -- | AI Course Generation (General English + IELTS) | To Build | 26--27 |
| -- | Adaptive Learning Engine UI | To Build | 28--29 |
| -- | Entity / White-Label Management | To Build | 30--31 |
| -- | Math and IT Subject Support | To Build | 32--34 |
| -- | Score Release and Reporting | To Build | 35--37 |

---

## 2. Existing System Summary

The platform already has a working frontend with the following inventory. New workflow pages will be built alongside and integrated with this existing codebase.

### 2.1 Current Inventory

| Category | Count | Details |
|----------|-------|---------|
| Page Components | 93 | 28 root, 33 admin, 19 student, 14 teacher |
| API Service Modules | 37 | `src/services/*.service.ts` |
| TypeScript Type Files | 29 | `src/types/*.ts` |
| TanStack Query Hooks | 21 | `src/hooks/queries/*.ts` |

### 2.2 Existing Page Structure

- **Public:** `/login`, `/register`, `/forgot-password`, `/apply`, `/faq`, `/exam/...`
- **Student** (`/student/*`): dashboard, courses, assignments, adaptive flow, courseware, discussions
- **Teacher** (`/teacher/*`): courses, assignments, attendance, chapters, AI workbench
- **Admin** (`/admin/*`): LMS dashboard, courses, students, platform admin, users, exams, taxonomy

### 2.3 Key Existing Components

- `ProtectedRoute` -- role-based route gating (`student`, `teacher`, `admin`, `corporate`, `mastercorporate`, `agent`, `developer`)
- `StudentLayout`, `TeacherLayout`, `AdminLmsLayout` -- role-specific navigation shells
- `AuthContext` -- JWT authentication context
- `api-client.ts` -- centralised Axios instance with `/api` proxy to Odoo backend
- `query-client.ts` -- TanStack Query client configuration

### 2.4 Tech Stack

| Technology | Version | Purpose |
|------------|---------|---------|
| React | 18 | UI framework |
| TypeScript | 5.8 | Type safety |
| Vite | 5 | Build tool (SWC plugin) |
| React Router | 6 | Client-side routing |
| TanStack Query | 5 | Server state management |
| shadcn/ui + Radix | Latest | Component library |
| Tailwind CSS | 3 | Styling |
| react-hook-form + Zod | Latest | Form management and validation |
| recharts | Latest | Charts and data visualization |
| lucide-react | Latest | Icons |

---

## 3. Architecture and Conventions

### 3.1 File Organization

All new files must follow the existing project structure:

```
src/
  pages/
    admin/           # Admin-facing pages (exam config, bulk upload, score approval)
    student/         # Student-facing pages (exam session, placement, course delivery)
    teacher/         # Teacher-facing pages (content review, grading queue)
    PublicPage.tsx    # Public pages (score verification, signup)
  services/
    workflow-name.service.ts   # API service module
  types/
    workflow-name.ts           # TypeScript interfaces
  hooks/
    queries/
      useWorkflowName.ts      # TanStack Query hooks
  components/
    ui/              # Reusable shadcn primitives
    workflow-name/   # Workflow-specific components
```

### 3.2 API Communication Pattern

Every API call follows the existing pattern:

```typescript
// src/services/example.service.ts
import apiClient from "@/lib/api-client";

export const exampleService = {
  getItems: () => apiClient.get("/api/example/items"),
  createItem: (data: CreateItemRequest) => apiClient.post("/api/example/items", data),
};
```

All endpoints are proxied through Vite dev server: `/api` maps to `http://127.0.0.1:8069`.

### 3.3 State Management Pattern

```typescript
// src/hooks/queries/useExample.ts
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { exampleService } from "@/services/example.service";

export const useExampleItems = () =>
  useQuery({ queryKey: ["example", "items"], queryFn: exampleService.getItems });

export const useCreateExample = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: exampleService.createItem,
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["example"] }),
  });
};
```

### 3.4 Form Pattern

All forms use `react-hook-form` with `Zod` validation schemas:

```typescript
const schema = z.object({ name: z.string().min(1), email: z.string().email() });
type FormData = z.infer<typeof schema>;

const form = useForm<FormData>({ resolver: zodResolver(schema) });
```

### 3.5 Routing Convention

New routes are added to `src/App.tsx` within the appropriate `ProtectedRoute` wrapper:

```tsx
<Route element={<ProtectedRoute allowedRoles={["student"]} />}>
  <Route element={<StudentLayout />}>
    <Route path="/student/placement" element={<PlacementTest />} />
  </Route>
</Route>
```

---

# Part II -- Workflow 1: User Signup (Individual)

## 4. Registration Page

**Route:** `/register`
**Access:** Public (unauthenticated)
**Replaces/Enhances:** Existing `/register` page

### 4.1 Page Layout

The registration page contains a single centered card with the following fields:

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Full Name | Text input | Required, min 2 characters | |
| Email | Email input | Required, valid email format | Checked for uniqueness on blur |
| Password | Password input | Required, min 8 characters | Strength indicator bar (weak/medium/strong) |
| Confirm Password | Password input | Must match password | |
| Role | Radio group | Required, one of: `academic_student`, `self_learner`, `teacher` | Labels: "Academic Student", "Self-Learner", "Teacher" |
| CAPTCHA | CAPTCHA widget | Required | Integration with reCAPTCHA v2 or hCaptcha. Only shown for individual self-registration; entity bulk-upload accounts bypass this. |
| Submit | Button | All fields valid + CAPTCHA verified | Text: "Create Account" |

### 4.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| REG-01 | Password strength indicator updates in real time as user types. Strength levels: Weak (red, < 8 chars or no variety), Medium (yellow, 8+ chars with 2 of: uppercase, lowercase, number, symbol), Strong (green, 8+ chars with 3+ of: uppercase, lowercase, number, symbol). |
| REG-02 | Email uniqueness is checked on blur via `POST /api/auth/check-email`. If email exists, show inline error: "An account with this email already exists." |
| REG-03 | CAPTCHA token is included in the registration request body. Backend verifies the token before creating the account. |
| REG-04 | On successful submission, the backend returns a 201 status. Frontend navigates to `/verify-email?email={email}`. |
| REG-05 | On validation error (422), show field-level error messages returned by the backend. |
| REG-06 | A "Already have an account? Sign in" link navigates to `/login`. |

### 4.3 API Contract

**Request:** `POST /api/auth/register`

```json
{
  "name": "string",
  "email": "string",
  "password": "string",
  "role": "academic_student | self_learner | teacher",
  "captcha_token": "string"
}
```

**Response (201):**
```json
{
  "success": true,
  "message": "Account created. Please verify your email.",
  "user_id": 42
}
```

---

## 5. Email Verification Page

**Route:** `/verify-email`
**Access:** Public (unauthenticated)
**Query Params:** `?email={email}`

### 5.1 Page Layout

Centered card with:

- Instruction text: "We've sent a 6-digit verification code to {email}"
- 6-digit OTP input (using `input-otp` component already in the project)
- "Verify" button
- "Resend code" link with countdown timer (disabled for 60 seconds after each send)
- Attempt counter text: "Resend attempts: {count}/3"

### 5.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| VERIFY-01 | OTP input auto-focuses on the first digit. Each digit field advances focus to the next on input. |
| VERIFY-02 | When all 6 digits are entered, the "Verify" button becomes enabled. Optionally, auto-submit on 6th digit. |
| VERIFY-03 | On success (200), navigate to `/onboarding` (the onboarding wizard). |
| VERIFY-04 | On invalid OTP (400), show error: "Invalid verification code. Please try again." Clear the input. |
| VERIFY-05 | On expired OTP (410), show error: "This code has expired. Please request a new one." |
| VERIFY-06 | "Resend code" calls `POST /api/auth/resend-otp`. Maximum 3 resend attempts. After 3 attempts, show: "Maximum resend attempts reached. Please contact support." |
| VERIFY-07 | OTP expires after 15 minutes. Timer is shown below the input: "Code expires in MM:SS". |

### 5.3 API Contract

**Verify:** `POST /api/auth/verify-email`
```json
{ "email": "string", "otp": "string" }
```

**Resend:** `POST /api/auth/resend-otp`
```json
{ "email": "string" }
```

---

## 6. Onboarding Wizard

**Route:** `/onboarding`
**Access:** Authenticated, account status = `unactivated`
**Guard:** If account is already `activated`, redirect to role-appropriate dashboard.

### 6.1 Wizard Structure

A multi-step wizard with 4 steps, a progress bar at the top showing the current step (1/4, 2/4, 3/4, 4/4), and Back/Next buttons at the bottom.

#### Step 1 -- Learning Goal

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Goal | Radio card group | Required, select one | Options are dynamic, loaded from `GET /api/onboarding/goals`. Each option has an icon, title, and description. Examples: General English, IELTS Academic, IELTS General Training, TOEFL, STEP, Mathematics, IT, Other Certification. |

#### Step 2 -- Target and Timeline

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Target Level/Band | Slider or select | Required | For IELTS: band score slider 4.0--9.0 in 0.5 steps. For General English: CEFR level select (A1--C2). For Math/IT: proficiency level select (Beginner/Intermediate/Advanced). |
| Exam Date | Date picker | Optional | "I have an upcoming exam on..." If set, system calculates study timeline. |
| No Exam Date | Checkbox | -- | "I don't have a specific exam date" -- hides date picker. |

#### Step 3 -- Study Preferences

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Hours per Week | Slider | Required, 1--40 | Default: 10. Shows estimated completion time based on gap. |
| Study Mode | Radio group | Required | Options: "Self-study", "With a teacher". |
| Learning Style | Checkbox group (multi-select) | Required, at least one | Options: Visual, Audio, Reading, Mixed. Icons for each. |

#### Step 4 -- Placement Test

| Content | Description |
|---------|-------------|
| Heading | "Ready to find your level?" |
| Description | "Take a short placement test (~20-30 minutes) so we can create a personalised learning plan for you." |
| Primary action | "Take Placement Test Now" -- navigates to `/student/placement` |
| Secondary action | "Skip for Now" -- displays a warning: "Without a placement test, we'll start you at B1 (intermediate) level. You can take the test anytime from your dashboard." |

### 6.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| WIZ-01 | Wizard state is preserved in local component state. Data is NOT submitted until the user completes all 4 steps. |
| WIZ-02 | "Back" button on Step 1 is hidden. "Back" on Steps 2--4 returns to the previous step without losing data. |
| WIZ-03 | On Step 4 completion (either "Take Test" or "Skip"), the wizard data is submitted via `POST /api/onboarding/complete`. |
| WIZ-04 | On success, account status changes to `activated`. If "Take Test" was chosen, navigate to `/student/placement`. If "Skip", navigate to `/student/dashboard`. |
| WIZ-05 | The goals list in Step 1 is fetched from the backend and is dynamic. If the platform adds a new exam template, it appears automatically. |
| WIZ-06 | If the user closes the browser mid-wizard and logs in again, they are redirected back to `/onboarding` (because account status is still `unactivated`). |

### 6.3 API Contract

**Goals list:** `GET /api/onboarding/goals`
```json
{
  "goals": [
    { "id": "ielts_academic", "title": "IELTS Academic", "description": "...", "icon": "graduation-cap" },
    { "id": "general_english", "title": "General English", "description": "...", "icon": "book-open" },
    { "id": "mathematics", "title": "Mathematics", "description": "...", "icon": "calculator" }
  ]
}
```

**Complete wizard:** `POST /api/onboarding/complete`
```json
{
  "goal": "ielts_academic",
  "target_band": 7.0,
  "exam_date": "2026-09-15",
  "hours_per_week": 10,
  "study_mode": "self_study",
  "learning_style": ["visual", "reading"],
  "placement_decision": "take_now | skip"
}
```

---

# Part III -- Workflow 2: Placement Test

## 7. Placement Test Briefing

**Route:** `/student/placement`
**Access:** Authenticated, role = `student`
**Prerequisite:** Onboarding wizard completed (account = `activated`)

### 7.1 Page Layout

Full-width card with:

- **Subject selector** (if student goal supports multiple subjects): shown only if the student's profile has Math or IT as goal. Default subject is pre-selected based on onboarding wizard goal.
- **Test overview card:** Subject name, estimated duration "20--30 minutes", dimension count "4 sections", adaptive note "The test adapts to your level -- questions get harder or easier based on your answers."
- **Dimension breakdown table:**

| Dimension | Questions | Content | Duration |
|-----------|-----------|---------|----------|
| Grammar | ~30 MCQ | Tenses, articles, prepositions, clauses | ~8 min |
| Vocabulary | ~20 items | Definition match, gap fill, collocations | ~5 min |
| Reading | ~10 Q / 2 passages | TF/NG, MCQ -- passages progress easy to difficult | ~10 min |
| Speaking | 3 prompts (optional) | Record 60-second responses | ~5 min |

- **"Begin Test" button** (primary, large)
- **Note for entity students:** "This test is mandatory. Your results will be shared with your institution."

### 7.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| BRIEF-01 | For Math subject, the dimension breakdown changes to: Arithmetic (~20 MCQ), Algebra (~15 items), Geometry (~10 Q), Problem Solving (~10 Q). For IT: Computer Basics (~20 MCQ), Programming Logic (~15 items), Networking (~10 Q), Problem Solving (~10 Q). |
| BRIEF-02 | "Begin Test" calls `POST /api/placement/start` which creates a CAT session and returns a `session_id`. Navigate to `/student/placement/test?session={session_id}`. |
| BRIEF-03 | If an active placement session already exists (user refreshed), resume from where they left off. |

---

## 8. CAT Test Interface

**Route:** `/student/placement/test`
**Access:** Authenticated, role = `student`, active placement session
**Query Params:** `?session={session_id}`

### 8.1 Page Layout

Full-screen test interface with no navigation sidebar (distraction-free mode):

- **Top bar:** Timer (counting up, showing elapsed time), current section name (e.g., "Grammar"), progress indicator (question X of estimated ~Y), "Pause" button (if allowed)
- **Main area:** Question display area (adapts to question type)
- **Bottom bar:** "Previous" button (disabled for CAT -- no going back), "Next" / "Submit Answer" button, section progress dots

### 8.2 Question Type Renderers

Each question type requires a specific renderer component:

| Question Type | Renderer | Used In |
|---------------|----------|---------|
| MCQ (single answer) | Radio button list with A/B/C/D labels | Grammar, Vocabulary, Reading |
| MCQ (multiple answers) | Checkbox list | Reading |
| Gap fill | Text input embedded in a sentence | Vocabulary |
| True/False/Not Given | 3-option radio for each statement | Reading |
| Definition match | Drag-and-drop or select matching | Vocabulary |
| Audio recording | Microphone button, waveform display, playback, re-record | Speaking |
| Reading passage + questions | Split view: passage on left, questions on right (desktop). Scrollable passage above questions (mobile). | Reading |

### 8.3 CAT-Specific Behaviour

| ID | Requirement |
|----|-------------|
| CAT-01 | After each answer submission, the frontend calls `POST /api/placement/answer` with the answer. The backend returns the next question (which may be harder or easier based on the IRT algorithm). |
| CAT-02 | The frontend does NOT preload all questions. Each question is fetched one at a time from the backend. Show a brief loading spinner between questions (skeleton loader). |
| CAT-03 | The progress indicator shows an estimated count (e.g., "Question 12 of ~30") because the CAT engine may terminate early if SEM reaches precision. |
| CAT-04 | When the backend returns `section_complete: true`, show a transition screen: "Grammar section complete. Next: Vocabulary" with a 3-second countdown or "Continue" button. |
| CAT-05 | The Speaking section shows a microphone permission prompt. If denied, skip the section with a note: "Speaking section skipped. Your placement will be based on the other three sections." |
| CAT-06 | For speaking prompts, show: prompt text, a "Start Recording" button, a 60-second countdown timer, waveform visualizer during recording, "Stop" button, playback controls, "Re-record" option (max 1 re-record per prompt), and "Submit Recording" button. |
| CAT-07 | Audio recordings are uploaded to the backend as blobs via `POST /api/placement/speaking-upload`. |
| CAT-08 | On the final question of the last section, the "Submit" button shows "Finish Test". After clicking, navigate to `/student/placement/results?session={session_id}`. |

### 8.4 Auto-Save

| ID | Requirement |
|----|-------------|
| SAVE-01 | All answers are auto-saved to the backend every 10 seconds via `POST /api/placement/autosave`. |
| SAVE-02 | A small "Saved" indicator appears at the bottom of the screen after each successful auto-save. |
| SAVE-03 | If the browser closes mid-test, the student can resume from the last saved position when they log in again. |

### 8.5 API Contracts

**Start session:** `POST /api/placement/start`
```json
{ "subject": "english | math | it" }
```
Response:
```json
{ "session_id": "uuid", "first_question": { "id": 1, "type": "mcq", "section": "grammar", "stem": "...", "options": [...], "estimated_total": 30 } }
```

**Submit answer:** `POST /api/placement/answer`
```json
{ "session_id": "uuid", "question_id": 1, "answer": "B", "time_spent_ms": 12340 }
```
Response:
```json
{ "next_question": { ... }, "section_complete": false, "test_complete": false, "progress": { "current": 13, "estimated_total": 30 } }
```

**Auto-save:** `POST /api/placement/autosave`
```json
{ "session_id": "uuid", "current_answer": { "question_id": 15, "answer": "C" } }
```

**Upload speaking:** `POST /api/placement/speaking-upload` (multipart/form-data)
Fields: `session_id`, `prompt_id`, `audio_file` (blob)

---

## 9. Placement Results and Learning Path Preview

**Route:** `/student/placement/results`
**Access:** Authenticated, role = `student`
**Query Params:** `?session={session_id}`

### 9.1 Page Layout

Results page with two main sections:

#### Section A -- Your Results

- **Overall CEFR level** displayed prominently (e.g., "B2" with a coloured badge)
- **Per-dimension scores** in a radar chart (Grammar, Vocabulary, Reading, Speaking)
- **Score table:**

| Dimension | Score | CEFR Level | Gap to Target |
|-----------|-------|------------|---------------|
| Grammar | 72% | B2 | +0.5 to C1 |
| Vocabulary | 58% | B1 | +1.0 to B2 |
| Reading | 65% | B2 | +0.5 to C1 |
| Speaking | Pending | -- | AI evaluation in progress |

- **Note for entity students:** If `results_release_mode = manual_approval`, show: "Your results are being reviewed by your institution. You will be notified when they are released." Hide the actual scores until approved.

#### Section B -- Your Personalised Learning Path

- **Course outline card** with estimated duration, module count, and study hours per week
- **Skill gap modules** listed by priority (largest gap first) with:
  - Module name
  - Estimated hours
  - Resource types (icons: PDF, Video, Audio, Exercise)
  - Difficulty level
- **"View Full Course Plan" button** -- expands to show detailed module breakdown
- **Key design principle:** This learning path is shown BEFORE any payment prompt.

### 9.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| RES-01 | Results are fetched from `GET /api/placement/results?session_id={id}`. |
| RES-02 | If Speaking evaluation is still in progress (`speaking_status: "pending"`), show a "Pending" badge. Poll `GET /api/placement/speaking-status?session_id={id}` every 30 seconds until complete. When complete, update the Speaking row in the table. |
| RES-03 | The learning path preview is fetched from `GET /api/placement/learning-path?session_id={id}`. |
| RES-04 | Entity students whose results are pending approval see a simplified view with a "Results Pending" message. |
| RES-05 | For Math/IT subjects, CEFR levels are replaced with proficiency levels (Beginner/Intermediate/Advanced/Expert). |
| RES-06 | "Continue" button at the bottom navigates to the payment/access page (Section 10). |

---

## 10. Payment and Access Options

**Route:** `/student/placement/access`
**Access:** Authenticated, role = `student`

### 10.1 Page Layout

Three pricing cards side by side:

| Card | Title | Description | CTA |
|------|-------|-------------|-----|
| Full Access | "Unlock Full Course" | Full subscription or one-time payment. Complete access to all modules, AI tutoring, and practice exams. | "Subscribe Now" |
| Free Trial | "Try Free for 7 Days" | Limited access: first 3 modules only. Upgrade prompt after trial. | "Start Free Trial" |
| Skip | "Continue to Dashboard" | Dashboard access only. No course access. Prompted to subscribe later. | "Skip for Now" |

### 10.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| PAY-01 | "Subscribe Now" navigates to `/student/subscription` (existing subscription page). |
| PAY-02 | "Start Free Trial" calls `POST /api/subscription/trial` and navigates to `/student/dashboard`. |
| PAY-03 | "Skip for Now" navigates to `/student/dashboard`. A persistent banner appears on the dashboard: "Unlock your personalised course -- Subscribe now" with a dismiss option. |
| PAY-04 | Entity students bypass this page entirely. Their access is controlled by the institution. |

---

# Part IV -- Workflow 3: Exam Configuration (International + Custom)

The platform supports two distinct exam template paths. Both paths share the same exam session, grading, and score release infrastructure (Part V). The key difference is who defines the exam structure.

## 11. Exam Template Paths

### 11.1 Two Paths Overview

| Aspect | Path 1: International Templates | Path 2: Custom Templates |
|--------|--------------------------------|--------------------------|
| **Examples** | IELTS Academic, IELTS General Training, TOEFL, STEP, IC3 | University midterm, entity-specific exam, department quiz |
| **Who creates the template** | EnCoach development team (pre-loaded during deployment) | Teacher or Entity Admin (via the platform UI) |
| **Structure modifiable?** | No -- parts, question counts, time limits, and skills are permanently locked | Yes -- fully configurable by the creator |
| **Question assembly** | Teacher fills fixed structural slots using Auto/Manual/Hybrid modes | Teacher adds questions freely to their own defined sections |
| **Available to** | All entities and individual students | Only the creating entity or teacher's students |
| **Added via** | Developer seeds template data into `encoach.exam.template` during module installation | Teacher/Admin uses the Custom Exam Creation UI (Section 16) |

### 11.2 Template Selection Page

**Route:** `/admin/exam/create`
**Access:** Authenticated, role = `admin` or `teacher`

The entry point for all exam creation is a template selection page:

- **Section A -- International Exam Templates:** A grid of cards showing pre-loaded templates (IELTS Academic, IELTS General Training, TOEFL, STEP, IC3). Each card shows: template name, icon, skill count, total questions, total time. A "Locked" badge indicates the structure cannot be modified. Clicking a card navigates to the international template wizard (Section 12).

- **Section B -- Custom Exam:** A single "Create Custom Exam" card with a plus icon. Clicking navigates to the custom exam creation form (Section 16).

### 11.3 Functional Requirements

| ID | Requirement |
|----|-------------|
| TMPL-01 | Available international templates are loaded from `GET /api/exam/templates?type=international`. Only templates with `active = true` are shown. |
| TMPL-02 | The "Create Custom Exam" option is always available to teachers and admins. |
| TMPL-03 | International template cards display a "Locked" badge and tooltip: "This exam structure is defined by the exam body and cannot be modified." |

---

## 12. International Template -- IELTS Exam Initialization

**Route:** `/admin/exam/ielts/create`
**Access:** Authenticated, role = `admin` or `teacher`

### 11.1 Page Layout

A step-by-step wizard (stepper component) with 5 phases matching the workflow document.

#### Phase 1 -- Exam Initialization Form

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Exam Type | Toggle or radio | Required | Options: "IELTS Academic", "IELTS General Training" |
| Target Skills | Checkbox group (multi-select) | Required, at least one | Options: Listening, Reading, Writing, Speaking. Pre-checked: all four. |
| Exam Title | Text input | Required, max 200 chars | Auto-generated suggestion: "IELTS [Academic/General] -- [Date]" |
| Target Band | Slider | Required, 4.0--9.0 in 0.5 steps | Default: 6.5 |
| Difficulty | Select | Required | Options: Easy, Medium, Hard. Mapped to band ranges. |
| Randomization | Toggle | Default: ON | "Randomize question order within each section" |
| Assembly Mode | Radio cards | Required | **Auto:** System builds entire exam from rules. **Manual:** Teacher handpicks every item. **Hybrid:** System suggests, teacher refines. |
| Score Release Mode | Radio | Required | **Auto-release:** Student sees results immediately. **Manual approval:** Entity admin must approve before student sees results. |

### 11.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| IELTS-01 | The exam structure (parts per skill, question counts per part) is fixed by the IELTS template and CANNOT be modified. A read-only info box shows: "IELTS Structure: Listening (4 parts, 40 Q), Reading (3 passages, 40 Q), Writing (2 tasks), Speaking (3 parts, 11-14 min)". |
| IELTS-02 | "Next" button saves the initialization data via `POST /api/exam/ielts/create` and returns an `exam_id`. Navigates to Phase 2. |
| IELTS-03 | Assembly mode selection changes the behaviour of Phase 3 (content retrieval). |

### 11.3 API Contract

**Create IELTS exam:** `POST /api/exam/ielts/create`
```json
{
  "exam_type": "academic | general_training",
  "skills": ["listening", "reading", "writing", "speaking"],
  "title": "string",
  "target_band": 6.5,
  "difficulty": "easy | medium | hard",
  "randomize": true,
  "assembly_mode": "auto | manual | hybrid",
  "results_release_mode": "auto | manual_approval"
}
```

---

## 13. Per-Skill Configuration Panels

**Route:** `/admin/exam/ielts/:examId/skills`
**Access:** Authenticated, role = `admin` or `teacher`

### 12.1 Page Layout

Tabbed interface with one tab per selected skill. Each tab shows the fixed structure for that skill:

#### Listening Tab
| Part | Questions | Content Type | Time |
|------|-----------|-------------|------|
| Part 1 | 10 | Conversation (2 speakers, everyday context) | ~6 min |
| Part 2 | 10 | Monologue (social/everyday context) | ~6 min |
| Part 3 | 10 | Conversation (2-4 speakers, academic context) | ~6 min |
| Part 4 | 10 | Monologue (academic lecture) | ~8 min |

#### Reading Tab (Academic)
| Passage | Questions | Text Type |
|---------|-----------|-----------|
| Passage 1 | 13--14 | Factual/descriptive |
| Passage 2 | 13--14 | Discursive/analytical |
| Passage 3 | 13--14 | Complex argumentative |

#### Reading Tab (General Training)
| Section | Questions | Text Type |
|---------|-----------|-----------|
| Section 1 | 13--14 | Short texts (everyday) |
| Section 2 | 13--14 | Workplace texts |
| Section 3 | 13--14 | General interest (longer) |

#### Writing Tab
| Task | Type | Min Words |
|------|------|-----------|
| Task 1 | Academic: describe visual data. General: write a letter. | 150 |
| Task 2 | Essay (both types) | 250 |

#### Speaking Tab
| Part | Duration | Format |
|------|----------|--------|
| Part 1 | 4--5 min | Familiar topic questions |
| Part 2 | 3--4 min | Cue card long turn (1 min prep + 2 min speaking) |
| Part 3 | 4--5 min | Abstract discussion linked to Part 2 topic |

### 12.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| SKILL-01 | The structure tables above are READ-ONLY. The teacher/admin cannot change the number of parts, questions per part, or time limits. These are fixed IELTS template values. |
| SKILL-02 | Each skill tab shows the available content pool count: "Available: 245 questions for Listening Part 1". Fetched from `GET /api/exam/ielts/:examId/content-pool-count`. |
| SKILL-03 | A "Configure Content" button on each tab navigates to the content pool view (Section 13) for that specific skill/part. |
| SKILL-04 | A summary panel on the right shows overall exam completion status: how many questions are filled vs required per skill. |

---

## 14. Content Pool and Question Assembly

**Route:** `/admin/exam/ielts/:examId/content`
**Access:** Authenticated, role = `admin` or `teacher`

### 13.1 Page Layout

Split view:
- **Left panel (60%):** Content pool browser with filters
- **Right panel (40%):** Selected questions for the current section

#### Content Pool Browser

| Filter | Type | Options |
|--------|------|---------|
| Skill | Dropdown | Listening, Reading, Writing, Speaking |
| Part | Dropdown | Depends on skill (e.g., Part 1--4 for Listening) |
| Difficulty | Slider | Easy / Medium / Hard |
| Topic | Multi-select tags | Loaded from backend |
| Status | Checkbox | Available, Seen (by this student), Flagged, Retired |
| Search | Text input | Search question text/stem |

Content items displayed as cards with: preview text (truncated), difficulty badge, topic tags, usage count, quality rating.

#### Assembly Behaviour by Mode

| Mode | Left Panel | Right Panel |
|------|------------|-------------|
| **Auto** | Greyed out (system selects automatically). "System has selected 40 questions. Review below." | Shows system-selected questions. Teacher can "Swap" individual items. |
| **Manual** | Full browsing. Teacher clicks "Add" on each item. | Shows teacher-selected items with drag-and-drop reordering. Count badge: "12/40 selected". |
| **Hybrid** | System pre-populates suggestions (highlighted). Teacher can accept, reject, or swap. | Shows suggested items. "Accept All" or individual accept/reject buttons. |

### 13.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| POOL-01 | The content pool is fetched from `GET /api/exam/ielts/:examId/content-pool` with filter parameters. Returns 3--5x more items than needed. |
| POOL-02 | Content filters exclude: items seen by the assigned student (if student is specified), flagged items, retired items. Topic diversity and difficulty curve are applied by the backend. |
| POOL-03 | In Auto mode, `POST /api/exam/ielts/:examId/auto-assemble` triggers the backend to select questions. Frontend displays the result and allows the teacher to swap items. |
| POOL-04 | In Manual mode, the right panel tracks a running count. The teacher cannot proceed until all structural slots are filled (e.g., 40/40 for Listening). |
| POOL-05 | In Hybrid mode, `POST /api/exam/ielts/:examId/suggest` returns suggested items. Teacher reviews and confirms. |
| POOL-06 | "Save & Continue" persists the selection via `PUT /api/exam/ielts/:examId/sections/:sectionId/questions`. |

---

## 15. Exam Assembly and Validation

**Route:** `/admin/exam/ielts/:examId/validate`
**Access:** Authenticated, role = `admin` or `teacher`

### 14.1 Page Layout

Full exam preview with validation report:

#### Validation Checklist

| Check | Status | Description |
|-------|--------|-------------|
| Question Count | Pass/Fail | "Listening: 40/40, Reading: 40/40, Writing: 2/2, Speaking: 3 parts" |
| Media URLs | Pass/Fail | All audio files and images are accessible |
| Answer Keys | Pass/Fail | All auto-scored items have correct answers defined |
| No Duplicates | Pass/Fail | No question appears in multiple sections |
| Rubrics | Pass/Fail | Writing and Speaking tasks have rubrics linked |
| Time Specification | Pass/Fail | Each section has a valid time limit |

- **Red items** block publishing. **Yellow items** are warnings (can proceed with acknowledgement).
- "Preview Exam" button opens a read-only student-view preview of the exam.

#### Teacher Review Panel (Manual/Hybrid only)

- Expandable sections per skill with all selected questions
- Swap, reorder, replace actions per question
- Inline passage/audio preview

#### Publish Actions

| Button | Action |
|--------|--------|
| "Save as Draft" | `PUT /api/exam/ielts/:examId` with `status: "draft"` |
| "Publish" | `PUT /api/exam/ielts/:examId` with `status: "published"`. Only enabled if all validation checks pass. |
| "Assign to Students" | Opens a student/batch selector dialog. Calls `POST /api/exam/ielts/:examId/assign`. |

### 14.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| VAL-01 | Validation runs automatically when the page loads via `GET /api/exam/ielts/:examId/validate`. |
| VAL-02 | After publishing, the exam is locked for editing. A "Duplicate" option allows creating a copy for modification. |
| VAL-03 | "Assign to Students" shows a searchable student list and batch list. Multiple students and batches can be selected. Each assignment includes an optional access window (start date, end date). |

---

## 16. Custom Template -- Exam Creation

**Route:** `/admin/exam/custom/create`
**Access:** Authenticated, role = `admin` or `teacher`

### 16.1 Page Layout

A form-based exam builder where the teacher defines the entire exam structure from scratch.

#### Step 1 -- Exam Properties

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Exam Title | Text input | Required, max 200 chars | |
| Subject | Select | Required | Loaded from taxonomy: English, Mathematics, IT, etc. |
| Description | Textarea | Optional | Exam purpose and instructions for students |
| Total Time | Number (minutes) | Required, min 5 | Overall exam duration |
| Pass Threshold | Percentage slider | Optional, 0--100 | Minimum score to pass. If not set, no pass/fail routing. |
| Score Release Mode | Radio | Required | **Auto-release:** student sees results immediately. **Manual approval:** entity admin must approve. |
| Randomize Questions | Toggle | Default: OFF | Randomize question order for each student |

#### Step 2 -- Section Builder

The teacher adds one or more sections. Each section is a collapsible panel:

| Field | Type | Validation | Notes |
|-------|------|------------|-------|
| Section Title | Text input | Required | e.g., "Part A -- Grammar", "Section 2 -- Essay" |
| Skill/Category | Select | Optional | Tag this section with a skill (Listening, Reading, Writing, Speaking, Grammar, Vocabulary, or custom label) |
| Question Count | Number | Required, min 1 | How many questions this section will contain |
| Time Limit | Number (minutes) | Optional | Per-section time limit. If not set, section shares the overall exam timer. |
| Scoring Method | Select | Required | **Auto-scored:** MCQ, gap fill, TF/NG (system grades automatically). **Rubric-scored:** Writing, Speaking (teacher or AI grades). **Mixed:** section contains both types. |

- **"Add Section"** button: adds a new section panel
- Sections can be reordered via drag-and-drop
- Sections can be deleted (with confirmation dialog)

#### Step 3 -- Question Assignment

For each section, the teacher adds questions using the same content pool browser (Section 14) or by creating new questions inline:

- **"Browse Content Pool"** button: opens the shared content pool with filters (subject, skill, difficulty, topic)
- **"Create New Question"** button: opens an inline question form (question type, stem, options, correct answer, marks, difficulty)
- Running count: "8/10 questions added"
- The teacher can add questions beyond the defined count (extras are held as alternates for randomization)

#### Step 4 -- Review and Publish

Same validation and publish flow as Section 15 (Exam Assembly and Validation), but the validation rules adapt:
- Question count per section must meet the defined minimum
- If scoring method is "Rubric-scored", rubrics must be linked
- Time limits must be valid
- Answer keys must exist for all auto-scored questions

### 16.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| CUSTOM-01 | Custom exam creation calls `POST /api/exam/custom/create` with the full exam structure (properties + sections + questions). Returns an `exam_id`. |
| CUSTOM-02 | There are NO locked structural constraints. The teacher has full control over section count, question count, time limits, and skill assignments. |
| CUSTOM-03 | Custom exams are scoped to the creating teacher's entity. If the teacher has no entity, the exam is personal (visible only to that teacher's students). |
| CUSTOM-04 | Custom exams use the same exam session interface (Section 17), grading pipeline (Section 18), score release gate (Section 18), and results display (Section 19) as international template exams. |
| CUSTOM-05 | A "Save as Template" option allows the teacher to save a custom exam structure as a reusable template for future exams. This creates a record in `encoach.exam.template` with `editable = true` and `type = custom`. |
| CUSTOM-06 | "My Templates" section on the template selection page (Section 11.2) shows the teacher's saved custom templates. |

### 16.3 API Contracts

**Create custom exam:** `POST /api/exam/custom/create`
```json
{
  "title": "UTAS English Midterm -- Spring 2026",
  "subject_id": 1,
  "description": "...",
  "total_time_min": 90,
  "pass_threshold": 60,
  "results_release_mode": "auto",
  "randomize": false,
  "sections": [
    {
      "title": "Part A -- Grammar",
      "skill": "grammar",
      "question_count": 20,
      "time_limit_min": 30,
      "scoring_method": "auto",
      "question_ids": [101, 102, 103]
    },
    {
      "title": "Part B -- Writing",
      "skill": "writing",
      "question_count": 2,
      "time_limit_min": 60,
      "scoring_method": "rubric",
      "question_ids": [201, 202]
    }
  ]
}
```

**Save as template:** `POST /api/exam/templates/custom`
```json
{
  "name": "UTAS English Midterm Template",
  "structure": { "sections": [...] },
  "editable": true,
  "type": "custom"
}
```

**Get teacher's custom templates:** `GET /api/exam/templates?type=custom`

---

# Part V -- Workflow 4: General English Exam

## 17. Exam Session Interface

**Route:** `/student/exam/:examId/session`
**Access:** Authenticated, role = `student`, exam assigned to this student

### 15.1 Page Layout

Full-screen distraction-free interface (no sidebar, minimal header):

- **Top bar:** Exam title, current section name, section timer (countdown), overall progress bar
- **Main area:** Question renderer (varies by question type -- see Section 8.2 for renderers)
- **Bottom bar:** "Previous" button, "Next" button, "Flag for Review" button, "Submit Section" button (on last question of section)
- **Section transitions:** Brief screen between sections showing: "Section Complete. Next: [Section Name]. Time limit: [X minutes]."

### 15.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| EXAM-01 | The exam is loaded from `GET /api/exam/:examId/session`. Returns all sections, time limits, and questions (pre-loaded, unlike CAT). |
| EXAM-02 | Each section has its own countdown timer. When time expires, answers for that section are auto-submitted and the student moves to the next section. Warning at 5 minutes and 1 minute remaining. |
| EXAM-03 | Answers are auto-saved every 10 seconds via `POST /api/exam/:examId/autosave`. |
| EXAM-04 | "Flag for Review" marks a question with a flag icon. Flagged questions appear in a review panel before final submission. |
| EXAM-05 | Before final submission, show a review summary: answered count, unanswered count, flagged count, per section. "Submit Exam" button confirms submission. |
| EXAM-06 | After submission, navigate to a "Submission Confirmation" page. If `results_release_mode = auto`, show results immediately (Section 17). If `manual_approval`, show "Your exam has been submitted. Results will be available after review." |
| EXAM-07 | For Writing tasks: rich text editor with word count. Minimum word count indicator (turns red below 150 for Task 1, below 250 for Task 2). |
| EXAM-08 | For Speaking tasks: audio recording interface (same as placement test -- Section 8.2). |
| EXAM-09 | For Listening tasks: audio player with play/pause, progress bar, volume control. Audio plays once (IELTS standard). Replay is NOT allowed unless the exam is configured for practice mode. |

---

## 18. Grading and Score Release

**Route:** `/student/exam/:examId/status` (student view)
**Route:** `/admin/exam/:examId/grading` (admin/teacher view)

### 16.1 Student View

| State | Display |
|-------|---------|
| Submitted, auto-scoring in progress | "Your Listening and Reading scores are being calculated..." (spinner) |
| L/R scored, W/S pending teacher review | Show L/R band scores. W/S shows "Pending Review" with estimated wait time. |
| Fully scored, release = auto | Show all scores immediately (Section 17). |
| Fully scored, release = manual_approval | "Your results are complete and under review by your institution. You will be notified when they are released." |
| Released by admin | Show all scores (Section 17). |

### 16.2 Admin/Teacher Grading Queue

Page layout: Table of submissions pending grading.

| Column | Content |
|--------|---------|
| Student Name | Link to student profile |
| Exam Title | Link to exam config |
| Skill | Writing or Speaking (the skill needing manual grading) |
| Submitted At | Timestamp |
| Status | "Pending" / "In Progress" / "Graded" |
| Action | "Grade Now" button |

**Grading Interface:** When "Grade Now" is clicked, show:
- Student's response (essay text for Writing, audio playback for Speaking)
- Rubric criteria panel with score selectors for each criterion
- For IELTS Writing: Task Achievement, Coherence and Cohesion, Lexical Resource, Grammatical Range and Accuracy (each scored 0--9)
- For IELTS Speaking: Fluency and Coherence, Lexical Resource, Grammatical Range and Accuracy, Pronunciation (each scored 0--9)
- "AI Grade Suggestion" button: calls `POST /api/grading/ai-suggest` and populates the rubric with AI-suggested scores. Teacher can accept or override.
- "Submit Grade" button: saves the score and moves to the next submission in the queue.

---

## 19. Results Display and Reporting

**Route:** `/student/exam/:examId/results`
**Access:** Authenticated, role = `student`, results released

### 17.1 Page Layout

#### Score Summary Card
- **Overall Band Score** (large, prominent): e.g., "6.5"
- **CEFR Equivalent:** e.g., "C1 -- Effective Operational Proficiency"
- **Per-Skill Radar Chart:** Listening, Reading, Writing, Speaking on four axes
- **Per-Skill Table:**

| Skill | Band | CEFR | Gap to Target |
|-------|------|------|---------------|
| Listening | 7.0 | C2 | -- |
| Reading | 6.0 | C1 | +1.0 |
| Writing | 5.5 | B2 | +1.5 |
| Speaking | 6.5 | C1 | +0.5 |

#### Feedback Section
- Per-question feedback (expandable accordions per section)
- Weak areas highlighted with recommendations
- "Areas to improve" summary: top 3 weakness areas with linked learning resources

#### Actions
- **"Download PDF Report"** button: generates PDF with QR code (Section 36)
- **"View Recommended Course"** button: navigates to course generation (Section 19)
- **"Retake Exam"** button (if practice mode): creates a new exam attempt

---

## 20. Result Routing

Embedded within the results page (Section 17), a prominent action card at the bottom:

### 18.1 Pass / Sufficient Score Path

Card title: "Congratulations! You've reached your target."
- "Register for Official IELTS Exam" button -- navigates to `/student/exam-registration`
- "Continue Studying" button -- navigates to `/student/dashboard`

### 18.2 Below Threshold Path

Card title: "Let's build a plan to reach your target."
- "Start Adaptive Training" button -- navigates to `/student/course/generate?from=exam&examId={id}`
- Skill gap summary shown inline (from gap analysis)
- Teacher notification note: "Your teacher has been notified of your results."

---

# Part VI -- Workflow 5: Course Generation

## 21. Gap Analysis Dashboard

**Route:** `/student/course/generate`
**Access:** Authenticated, role = `student` (individual path) or `admin`/`teacher` (entity path)
**Query Params:** `?from=exam&examId={id}` or `?from=placement&sessionId={id}`

### 19.1 Page Layout

#### Skill Gap Visualization
- **Bar chart:** Skills ranked by gap size (largest first). Each bar shows current level vs target.
- **Table view:**

| Skill | Current | Target | Gap | Priority | Est. Hours |
|-------|---------|--------|-----|----------|-----------|
| Writing | 5.5 (B2) | 7.0 (C2) | 1.5 | High | 40 |
| Reading | 6.0 (C1) | 7.0 (C2) | 1.0 | Medium | 25 |
| Speaking | 6.5 (C1) | 7.0 (C2) | 0.5 | Low | 15 |
| Listening | 7.0 (C2) | 7.0 (C2) | 0.0 | -- | 0 |

- **Question-type weaknesses:** Expandable per skill. Shows error rate per question type (e.g., "MCQ: 85% correct, Gap Fill: 42% correct").
- **Topic weaknesses:** Grouped by category (e.g., "Environment: 3/5 wrong, Technology: 1/5 wrong").

### 19.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| GAP-01 | Gap analysis is fetched from `GET /api/course/gap-analysis?source={exam|placement}&source_id={id}`. |
| GAP-02 | For individual students, the "Generate Course" button is shown. Clicking it triggers automatic course structure generation (Section 20). |
| GAP-03 | For entity students, the page is view-only. A message states: "Your teacher will configure your course based on these results." |

---

## 22. Course Structure Configuration

**Route:** `/admin/course/configure/:courseId` (entity path) or `/student/course/configure/:courseId` (individual path)

### 20.1 Individual Student Path (Auto-Generated)

The system auto-generates a course structure. The student sees a read-only preview:

- Course title (auto-generated: e.g., "IELTS Preparation -- Writing & Reading Focus")
- Duration estimate
- Module list with skill assignments, hours, and resource type icons
- "Start Course" button -- begins the course immediately
- "Customize" button (optional) -- allows minor adjustments (reorder modules, skip low-priority skills)

### 20.2 Entity/Teacher Path (Manual Configuration)

Admin/Teacher configurable form:

| Field | Type | Validation |
|-------|------|------------|
| Course Title | Text input | Required |
| Exam Type | Select | IELTS Academic, IELTS General Training, General English |
| Target Band/Level | Slider/Select | Required |
| Duration | Number (weeks) | Required, 1--52 |
| Study Hours/Week | Slider | Required, 1--40 |
| Skills | Checkbox group | Pre-selected from gap analysis (gap >= 1.0). Teacher can override. |
| Skill Weightings | Sliders per skill | Hours per skill. Informed by gap size. Must sum to total estimated hours. |
| Progression Model | Radio cards | **Linear:** Fixed module order. **Parallel:** All sections active simultaneously. **Adaptive:** Engine manages order based on performance. |

### 20.3 Functional Requirements

| ID | Requirement |
|----|-------------|
| COURSE-01 | Individual path: `POST /api/course/auto-generate` with `source_id` (exam or placement session). Returns a pre-built course structure. |
| COURSE-02 | Entity path: `POST /api/course/create` with teacher-configured parameters. Returns a `course_id` for module building. |
| COURSE-03 | Progression model "Adaptive" requires the adaptive engine to be active. If not yet deployed, show a note: "Adaptive mode will be available after the engine is deployed. Defaulting to Parallel." |

---

## 23. Module Builder

**Route:** `/admin/course/:courseId/modules`
**Access:** Authenticated, role = `admin` or `teacher`

### 21.1 Page Layout

Each skill section is a collapsible panel containing its modules:

```
Writing Section (40 hours, 5 modules)
  ├── Module 1: Task Achievement Basics (8h)
  │     └── Resources: [PDF] [Video] [Exercise] [AI-Generated]
  ├── Module 2: Coherence and Cohesion (8h)
  │     └── Resources: [PDF] [Exercise]
  └── ... more modules
Reading Section (25 hours, 3 modules)
  ├── Module 1: Skimming and Scanning (10h)
  └── ...
```

#### Module Configuration

| Field | Type | Notes |
|-------|------|-------|
| Module Title | Text input | Required |
| Estimated Hours | Number | Required |
| Resources | Resource attachment panel | Browse and attach: PDF, Video, Audio, Exercise, AI-generated content. Uses shared content database. |
| Practice Exercises | Exercise builder | Add practice questions with answer keys. |
| Completion Criteria | Select | Options: "Complete all resources", "Score 70%+ on exercises", "Teacher approval" |
| Prerequisite Module | Select (optional) | For linear/adaptive progression |

### 21.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| MOD-01 | Resources are selected from the shared content database via a search/browse modal. `GET /api/resources?skill={skill}&difficulty={level}&type={type}`. |
| MOD-02 | AI-generated resources can be requested inline: "Generate AI Content" button opens a brief form (topic, difficulty, type) and calls `POST /api/ai/generate-resource`. |
| MOD-03 | Modules can be reordered via drag-and-drop. |
| MOD-04 | "Publish Course" button on the module builder page publishes the course and assigns it to the student(s). Calls `PUT /api/course/:courseId` with `status: "published"`. |

---

## 24. Course Delivery and Progress

**Route:** `/student/course/:courseId`
**Access:** Authenticated, role = `student`

### 22.1 Student Course View

- **Course header:** Title, overall progress percentage, estimated time remaining
- **Module list:** Collapsible sections per skill. Each module shows:
  - Title, status (locked/available/in-progress/completed), progress bar
  - Resource list with type icons and completion checkmarks
  - "Start" / "Continue" button
- **Adaptive indicators** (when progression = Adaptive):
  - "Recommended Next" badge on the module the engine suggests
  - "Unlocked!" animation when a new module becomes available
  - "Skipped" badge if the engine determines the student doesn't need a module (95%+ score)

### 22.2 Resource Viewer

In-platform viewers for each content type:

| Type | Viewer | Implementation |
|------|--------|----------------|
| PDF | Embedded PDF viewer (browser native or `react-pdf`) | Full-screen overlay or inline |
| Video | HTML5 `<video>` player with controls | Inline with progress tracking |
| Audio | HTML5 `<audio>` player with waveform | Inline |
| Exercise | Interactive question renderer (same components as exam) | Inline with submit/check |
| AI-generated | Rendered text/HTML content | Inline |

### 22.3 Progress Dashboard (Teacher View)

**Route:** `/teacher/course/:courseId/progress`

Table of enrolled students with:

| Column | Content |
|--------|---------|
| Student Name | Link to student detail |
| Overall Progress | Progress bar (%) |
| Current Module | Module name |
| Time Spent | Total hours |
| Predicted Band Improvement | AI-estimated band gain (e.g., "+1.0") |
| Last Activity | Timestamp |
| Alert | "No progress for 3+ days" warning icon |

### 22.4 Post-Course Assessment

When a student completes all modules:
- Completion celebration screen
- "Take Post-Course Assessment" button: assigns a new practice exam (same type as the diagnostic exam) to measure improvement
- Results comparison: side-by-side pre-test vs post-test scores

### 22.5 Functional Requirements

| ID | Requirement |
|----|-------------|
| DELIVER-01 | Course data is fetched from `GET /api/course/:courseId`. Includes all sections, modules, resources, and student progress. |
| DELIVER-02 | Resource completion is tracked via `POST /api/course/:courseId/progress` with `resource_id`, `completion_percent`, and `time_spent_ms`. |
| DELIVER-03 | Checkpoint exercises trigger scoring via `POST /api/course/:courseId/checkpoint`. If the score is below the threshold, the engine may insert remedial resources. |
| DELIVER-04 | The post-course exam is assigned via `POST /api/course/:courseId/post-test`. |

---

# Part VII -- Workflow 6: Entity Student Onboarding

## 25. Admin Bulk Upload Interface

**Route:** `/admin/entity/students/upload`
**Access:** Authenticated, role = `admin` or `corporate` or `mastercorporate`

### 23.1 Page Layout

#### Step 1 -- Upload

- **File upload zone:** Drag-and-drop or click-to-browse. Accepts `.csv` files only.
- **Download Template** link: downloads a sample CSV with headers: `student_name, institutional_email, national_id, student_id, enrolled_programme`
- **Upload button:** "Upload & Validate"

#### Step 2 -- Validation Report

After upload, the backend validates the CSV and returns a report:

| Column | Content |
|--------|---------|
| Row # | Row number in CSV |
| Student Name | Name from CSV |
| Email | Email from CSV |
| Status | "Valid" (green check) / "Error" (red X) / "Warning" (yellow !) |
| Issue | Error description (e.g., "Duplicate email", "Missing required field: national_id", "Invalid email format") |

- **Summary bar:** "247 valid, 3 errors, 1 warning"
- **"Fix & Re-upload"** button: allows the admin to download the error rows, fix them, and re-upload
- **"Confirm & Create Accounts"** button: only enabled if there are zero errors (warnings are allowed). Calls `POST /api/entity/students/bulk-create`.

#### Step 3 -- Confirmation

- Success message: "248 student accounts created successfully."
- Table of created accounts with: name, email, default password indicator ("National ID"), status ("Pending First Login")
- **"Send Credential Emails"** button: triggers `POST /api/entity/students/send-credentials`. Sends notification emails to all newly created students.

### 23.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| BULK-01 | CSV validation is done on the backend via `POST /api/entity/students/validate-csv` (multipart/form-data). Returns validation report JSON. |
| BULK-02 | Bulk account creation: username = institutional email, default password = national ID number. All accounts tagged with the admin's `entity_id`. |
| BULK-03 | CAPTCHA is NOT required for entity bulk-upload accounts. |
| BULK-04 | The admin can optionally set a "Bypass Placement" flag for specific students (e.g., Year 2 students who already have a known level). |
| BULK-05 | SIS integration (if entity has SIS configured): show an "Import from SIS" tab alongside the CSV upload tab. This calls `POST /api/entity/students/sis-import`. |

---

## 26. Credential Delivery Dashboard

**Route:** `/admin/entity/students/credentials`
**Access:** Authenticated, role = `admin` or `corporate` or `mastercorporate`

### 24.1 Page Layout

Table of entity students with credential delivery status:

| Column | Content |
|--------|---------|
| Student Name | Text |
| Email | Text |
| Account Status | "Pending First Login" / "Active" / "Password Reset Required" |
| Email Sent | Yes/No with timestamp |
| First Login | Yes/No with timestamp |
| Placement Status | "Not Started" / "In Progress" / "Completed" / "Bypassed" |

Filters: Account Status, Email Sent, Placement Status, Date range.

Actions:
- **"Resend Email"** button per row: calls `POST /api/entity/students/:id/resend-credentials`
- **"Resend All Pending"** button: calls `POST /api/entity/students/resend-all-pending`
- **Bulk actions:** Select multiple rows, "Resend Selected"

---

## 27. Entity Student First Login

**Route:** `/reset-password` (triggered automatically on first login)
**Access:** Authenticated, `first_login = true`

### 25.1 Page Layout

Centered card with:
- Heading: "Welcome to [Entity Name]'s Learning Platform"
- Subtext: "For security, please set a new password before continuing."
- Fields: New Password (with strength indicator), Confirm Password
- "Set Password & Continue" button

### 25.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| FIRST-01 | When the system detects `first_login = true` on any login, redirect to `/reset-password`. No other page is accessible until password is reset. |
| FIRST-02 | After password reset, `first_login` is set to `false`. The student is redirected to `/student/placement` (mandatory placement test). |
| FIRST-03 | No onboarding wizard is shown to entity students. They go directly from password reset to placement test. |
| FIRST-04 | Entity branding (logo, colours) is applied to this page if white-labelling is configured. |

---

# Part VIII -- AI Course Generation

## 28. General English AI Course Generation

**Route:** `/student/course/ai-english/:courseId`
**Access:** Authenticated, role = `student`

### 26.1 Student Profile and Goal Setting

Before the AI course begins, a confirmation screen shows:

- **Current CEFR Level:** (from placement test results, e.g., "B1")
- **Target CEFR Level:** (e.g., "B2") -- editable
- **Learning Style:** (from onboarding wizard) -- editable
- **Estimated Duration:** (calculated based on gap and study hours/week)
- **"Start AI Course"** button: calls `POST /api/ai-course/english/create`

### 26.2 Content Taxonomy Browser (Teacher/Admin)

**Route:** `/admin/ai-course/english/taxonomy`

Read-only taxonomy reference showing what the AI uses to generate content:

| Dimension | Description | Examples |
|-----------|-------------|---------|
| Grammar Topics by CEFR | Grammar points per level | A1: present simple; B2: conditionals, passive voice; C1: inversion |
| Vocabulary Bands | Frequency tiers | High-freq 1000-3000, Academic Word List, topic-specific |
| Skill Areas | Content types per skill | Reading fluency, Writing practice, Speaking fluency, Listening comprehension |
| Topic Categories | Real-world subjects | Daily life, work, travel, technology, culture, environment |

### 26.3 AI Generation Progress (Student View)

While the AI generates content:
- Progress indicator: "Generating your personalised course... Step 2/5: Creating grammar exercises"
- Steps: Profile Analysis, Reading Content, Grammar Exercises, Speaking Prompts, Vocabulary Sets
- Estimated time: "This usually takes 1--2 minutes"

### 26.4 Quality Gate Status (Admin/Teacher View)

**Route:** `/admin/ai-course/english/:courseId/quality`

| Check | Status | Detail |
|-------|--------|--------|
| Readability Score | Pass/Fail | "Flesch-Kincaid: 65 (target B2 range: 60-70)" |
| CEFR Calibration | Pass/Fail | "Content difficulty matches B2 level" |
| Grammar Accuracy | Pass/Fail | "No grammar errors detected in generated content" |
| Length Compliance | Pass/Fail | "All passages within 200-400 word range" |

- **"Approve"** button: marks content as approved, available for the student
- **"Reject & Regenerate"** button: sends content back to AI with error notes (max 3 attempts)
- **"Edit"** button: opens content in an inline editor for manual correction

### 26.5 Autonomous Course Delivery (Student View)

Three parallel module tracks displayed as columns:

```
┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│   Grammar    │  │    Skills   │  │  Vocabulary  │
│  Track       │  │    Track    │  │    Track     │
├─────────────┤  ├─────────────┤  ├─────────────┤
│ ✅ Mod 1    │  │ ✅ Mod 1    │  │ 🔄 Mod 1    │
│ 🔄 Mod 2    │  │ ⬜ Mod 2    │  │ ⬜ Mod 2    │
│ ⬜ Mod 3    │  │ ⬜ Mod 3    │  │ ⬜ Mod 3    │
└─────────────┘  └─────────────┘  └─────────────┘
```

- **Grammar Track:** Explanations, exercises, and worked examples
- **Skills Track:** Reading/Writing/Speaking tasks at CEFR level
- **Vocabulary Track:** Contextual word learning with spaced repetition

Each module shows: title, completion status, estimated time, "Start" / "Continue" button.

When a level is achieved, a celebration modal: "You've reached B2! Ready for the next level?" with options to level up or take a reassessment.

### 26.6 Progress Report

- CEFR gain chart (before vs after)
- Time spent per track
- Module completion rates
- "Next Level" recommendation

---

## 29. AI IELTS Course Generation

**Route:** `/student/course/ai-ielts/:courseId`
**Access:** Authenticated, role = `student`

### 27.1 IELTS Gap Profile Display

Before the AI IELTS course begins, a profile summary:

- **Exam Type:** Academic or General Training
- **Current Bands:** Per skill (from placement/diagnostic exam)
- **Target Band:** (editable)
- **Skills ranked by gap size:** Largest gap = highest priority (visual ranking)
- **Weak question types:** Per skill (e.g., "Reading: TFNG accuracy 40%, Gap Fill accuracy 55%")
- **"Start AI IELTS Course"** button

### 27.2 AI Content Generation Per Skill

While content is generated, a per-skill progress panel:

| Skill | Status | Detail |
|-------|--------|--------|
| Listening | Generating... | "Creating audio scripts for Parts 1-4" |
| Reading | Complete | "3 passages generated with 40 questions" |
| Writing | In Quality Check | "Validating Task 1 and Task 2 prompts" |
| Speaking | Complete | "Cue cards and question sets ready" |

### 27.3 IELTS Standards Validation Status (Admin View)

**Route:** `/admin/ai-course/ielts/:courseId/validation`

This is the unique two-layer validation pipeline. The admin sees:

#### Layer 1 -- Automated IELTS Standards Check

| Check | Status | Detail |
|-------|--------|--------|
| Format Compliance | Pass/Fail | Word counts within IELTS ranges, correct part structure, question type matches spec |
| CEFR Band Calibration | Pass/Fail | Readability mapped to target band, difficulty matches band descriptor |
| Answer Key Completeness | Pass/Fail | All auto-scored items have correct answers, W/S rubrics linked with 4 criteria |

If any check fails, an error detail panel shows specific issues: "Reading Passage 2: word count 890 -- exceeds IELTS maximum of 850 words."

#### Layer 2 -- IELTS Examiner Review Queue

Table of content items pending examiner review:

| Column | Content |
|--------|---------|
| Skill | Listening/Reading/Writing/Speaking |
| Content Type | Passage/Audio Script/Prompt/Cue Card |
| Target Band | Band level |
| Generated At | Timestamp |
| Examiner | Assigned examiner (or "Unassigned") |
| Status | "Pending Review" / "Approved" / "Rejected" |
| Action | "Review" button |

**Review Interface:**
- Full content preview
- Examiner checklist: accuracy of topic/context, appropriateness of difficulty, alignment with real IELTS conditions, cultural sensitivity
- "Approve" (marks as `ielts_certified = true`) or "Reject with Notes" (returns to AI for regeneration)

**Content source gate:** AI-generated content requires mandatory examiner review. Content uploaded by an IELTS-certified entity shows "Spot-check only" status.

### 27.4 IELTS Course Delivery (Student View)

Four parallel skill paths displayed as columns:

```
┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐
│ Writing  │  │ Reading  │  │ Speaking │  │ Listening│
│ Path     │  │ Path     │  │ Path     │  │ Path     │
├──────────┤  ├──────────┤  ├──────────┤  ├──────────┤
│ T1+T2    │  │ 3 Sets   │  │ P1/P2/P3 │  │ P1-P4   │
│ + Models │  │ + Full Q │  │ + Cue    │  │ + Audio  │
│ + Rubric │  │          │  │ + Model  │  │ + Q Sets │
└──────────┘  └──────────┘  └──────────┘  └──────────┘
```

### 27.5 Practice Exam and Readiness Check

When the adaptive engine determines the target band is likely reached:
- Modal: "Your performance suggests you're ready for band [X]. Take a full practice exam to confirm?"
- "Take Practice Exam" button -- assigns a full IELTS practice exam
- After the practice exam, if band confirmed: "You've reached your target! Register for the official IELTS exam?"
- If not yet reached: "Almost there! The AI has generated harder content for your next set of modules."

### 27.6 Progress Report

- Band improvement per skill (before vs after chart)
- Modules completed count
- Total time spent
- Weak area evolution (how weak areas improved over time)
- "Recommended next step" action card

---

# Part IX -- Adaptive Learning Engine UI

## 30. Adaptive Engine Dashboard

**Route:** `/admin/adaptive/dashboard`
**Access:** Authenticated, role = `admin`

### 28.1 Engine Status Overview

| Metric | Display |
|--------|---------|
| Active Students | Count of students currently in adaptive courses |
| Engine Phase | Current implementation phase (1: Rule-based, 2: IRT-CAT, 3: Collaborative, 4: Full ML) |
| Decisions Today | Count of adaptive decisions made today |
| Average Improvement | Average band/CEFR improvement across all students |
| Alerts | Count of "no progress 3+ days" alerts |

### 28.2 Student Adaptive Profiles (Admin View)

Table of students with adaptive learning data:

| Column | Content |
|--------|---------|
| Student | Name, link to profile |
| Subject | English/IELTS/Math/IT |
| Current Level | CEFR or band |
| Target Level | CEFR or band |
| Days Active | Count |
| Last Decision | "Served harder content" / "Inserted micro-lesson" / "Skipped module" |
| Progress Trend | Sparkline (mini chart) |
| Alert | Warning icon if no progress 3+ days |

### 28.3 Teacher Threshold Configuration

**Route:** `/teacher/adaptive/settings`

For Phase 1 (rule-based engine), teachers set explicit thresholds:

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| Difficulty Step-Up Threshold | Percentage | 85% | If student scores above this, serve harder content |
| Difficulty Step-Down Threshold | Percentage | 50% | If student scores below this, serve easier content |
| Micro-Lesson Trigger | Number | 2 | Insert a micro-lesson if student is stuck N+ times on a topic |
| Module Skip Threshold | Percentage | 95% | Skip module if pre-test score is above this |
| No-Progress Alert Days | Number | 3 | Alert teacher if student has no progress for N days |
| Max Retries per Exercise | Number | 3 | Maximum retries before flagging for teacher review |

### 28.4 Functional Requirements

| ID | Requirement |
|----|-------------|
| ADAPT-01 | Dashboard data is fetched from `GET /api/adaptive/dashboard`. |
| ADAPT-02 | Student profiles are fetched from `GET /api/adaptive/students?page={n}&limit={m}`. |
| ADAPT-03 | Teacher thresholds are saved via `PUT /api/adaptive/settings`. |
| ADAPT-04 | No-progress alerts trigger a visual badge on the teacher sidebar and an optional email notification. |

---

## 31. Engine Signals and Decision Visualization

**Route:** `/admin/adaptive/student/:studentId`
**Access:** Authenticated, role = `admin` or `teacher`

### 29.1 Signal Timeline

A timeline of all engine signals for a specific student:

| Time | Signal | Value | Decision Made |
|------|--------|-------|---------------|
| 10:32 | Quiz score | 92% | Serve harder content |
| 10:45 | Time on task | 3 min (fast) | Confirm difficulty increase |
| 11:00 | Quiz score | 45% | Revert to easier content |
| 11:15 | Retry count | 3 | Insert micro-lesson |
| 14:00 | Module completion | Module 3 | Unlock Module 4 |

Signals read by the engine (from workflow document):
- Quiz scores, error rate, retry count, time on task, video completion, study time patterns, module completion, band delta, past attempt history, CAT placement results.

Decisions made by the engine:
- Next content to serve, difficulty adjustment, resource type matching to learning style, micro-lesson insertion, module skip, teacher alert.

### 29.2 Ability Model (Phase 2+)

For IRT-based phases, show the student's ability estimate:
- **Ability estimate (theta):** Current IRT ability value per skill
- **Standard Error of Measurement (SEM):** Confidence in the estimate
- **Ability trajectory chart:** Line chart showing theta over time

---

# Part X -- Entity Management and White-Labelling

## 32. Entity Level Mapping Configuration

**Route:** `/admin/entity/:entityId/level-mapping`
**Access:** Authenticated, role = `admin` or `mastercorporate`

### 30.1 Page Layout

Configuration table for mapping CEFR scores to institutional levels:

| CEFR Min Score | CEFR Max Score | Internal Level Name | CEFR Equivalent |
|----------------|----------------|---------------------|-----------------|
| 0 | 29 | Foundation | Pre-A1 |
| 30 | 49 | Level 1 | A1--A2 |
| 50 | 69 | Level 2 | B1--B2 |
| 70 | 84 | Level 3 | C1 |
| 85 | 100 | High Flyer | C2 |

- Editable rows with inline editing
- "Add Row" button to add new mappings
- "Save" button: `PUT /api/entity/:entityId/level-mapping`
- "Reset to Default" button: restores standard CEFR mapping

### 30.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| LEVEL-01 | Level mappings are loaded from `GET /api/entity/:entityId/level-mapping`. |
| LEVEL-02 | When a student's placement results are displayed, both the CEFR level and the entity's internal level name are shown side by side. |
| LEVEL-03 | Level mappings must not have overlapping score ranges. Frontend validates this before saving. |

---

## 33. White-Label Branding Settings

**Route:** `/admin/entity/:entityId/branding`
**Access:** Authenticated, role = `admin` or `mastercorporate`

### 31.1 Page Layout

Branding configuration form:

| Field | Type | Notes |
|-------|------|-------|
| Entity Logo | Image upload | Accepted formats: PNG, SVG, JPEG. Max 2MB. Displayed in header and login page. |
| Primary Color | Colour picker | Used for buttons, links, active states |
| Secondary Color | Colour picker | Used for accents, badges, secondary buttons |
| Background Color | Colour picker | Used for page backgrounds |
| Custom Subdomain | Text input | e.g., "utas" results in "utas.encoach.com" |
| Login Page Title | Text input | Custom welcome message on the login page |
| Login Page Description | Textarea | Custom description text |
| Favicon | Image upload | 32x32 or 64x64 ICO/PNG |

- **Live Preview panel** on the right showing how the login page and dashboard will look with the configured branding
- **"Save Branding"** button: `PUT /api/entity/:entityId/branding`
- **"Reset to Default"** button: restores EnCoach default branding

### 31.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| BRAND-01 | When a student linked to an entity logs in, the frontend loads entity branding from `GET /api/entity/branding` (using the authenticated user's `entity_id`). |
| BRAND-02 | Branding is applied via CSS custom properties: `--primary`, `--secondary`, `--background`. These override the default Tailwind theme. |
| BRAND-03 | The logo replaces the EnCoach logo in the header, login page, and PDF reports. |
| BRAND-04 | White-labelling affects ONLY the presentation layer. No workflow logic changes. |
| BRAND-05 | If no entity branding is configured (or student has no entity), the default EnCoach branding is used. |

---

# Part XI -- Math and IT Subject Support

## 34. Math Content Rendering

### 32.1 Formula Display

All math content must be rendered using **KaTeX** (preferred for performance) or **MathJax** as fallback:

- Inline formulas: `$x^2 + y^2 = z^2$` rendered inline with text
- Block formulas: `$$\int_0^1 x^2 dx = \frac{1}{3}$$` rendered as centered blocks
- Formula rendering must work in: questions, answer options, passage text, explanations, and feedback

### 32.2 Math Question Types

In addition to the standard question types (MCQ, gap fill, TF/NG), Math requires:

| Question Type | Renderer | Example |
|---------------|----------|---------|
| Numerical Input | Number input with tolerance | "Solve: $2x + 5 = 13$. x = ___" (accept 4 +/- 0.01) |
| Expression Input | Math input field (using `mathquill` or similar) | "Simplify: $\frac{2x^2}{4x}$ = ___" |
| Graph Plot | Interactive graph component | "Plot the function $y = 2x + 3$" |
| Multiple Steps | Step-by-step input fields | "Show your working:" followed by numbered step inputs |
| Matrix Input | Grid of number inputs | "Enter the result matrix:" |

### 32.3 Dependencies

```
npm install katex react-katex
```

---

## 35. IT Content Rendering

### 33.1 Code Display and Execution

IT course content requires code display and optionally code execution:

| Component | Implementation | Notes |
|-----------|----------------|-------|
| Code Block | Syntax-highlighted code viewer (using `prism-react-renderer` or `highlight.js`) | Supports: Python, JavaScript, HTML, CSS, SQL, Java, C |
| Code Editor | Monaco Editor (VS Code's editor) or CodeMirror | For IT exercises where students write code |
| Code Output | Terminal-like output display | Shows stdout/stderr from code execution |

### 33.2 IT Question Types

| Question Type | Renderer | Example |
|---------------|----------|---------|
| Code Completion | Code editor with blanks | "Complete the function: `def add(a, b): return ___`" |
| Code Output Prediction | Code block + MCQ | "What does this code output?" |
| SQL Query | SQL editor + result table display | "Write a query to select all users older than 30" |
| Drag-and-Drop Code | Draggable code blocks | "Arrange these lines in the correct order" |
| Networking Diagram | Interactive network diagram component | "Identify the subnet for this IP address" |

### 33.3 Dependencies

```
npm install @monaco-editor/react prism-react-renderer
```

---

## 36. Subject-Agnostic Placement and Courses

### 34.1 Subject Selector Component

A reusable component that appears at the start of placement tests and course generation for students with Math or IT goals. The selector shows available subjects with icons:

- English (default)
- Mathematics (when available, September 2026)
- Information Technology (when available, September 2026)

### 34.2 Taxonomy Browser

**Route:** `/admin/taxonomy`

Tree view of the subject taxonomy:

```
Subject: Mathematics
  └── Domain: Algebra
       ├── Topic: Linear Equations
       │     ├── Learning Objective: Solve single-variable linear equations
       │     └── Learning Objective: Graph linear equations
       └── Topic: Quadratic Equations
             ├── Learning Objective: Factor quadratic expressions
             └── Learning Objective: Apply the quadratic formula
```

Admin can CRUD taxonomy nodes. The taxonomy drives what content the AI generates and how the adaptive engine organises modules.

### 34.3 Functional Requirements

| ID | Requirement |
|----|-------------|
| SUBJ-01 | The subject selector fetches available subjects from `GET /api/taxonomy/subjects`. |
| SUBJ-02 | Placement test dimensions change per subject (Grammar/Vocab/Reading/Speaking for English, Arithmetic/Algebra/Geometry/Problem-Solving for Math, etc.). The test briefing page (Section 7) dynamically adjusts. |
| SUBJ-03 | Course generation and AI content generation use the same pipelines regardless of subject. The subject taxonomy determines the content topics. |

---

# Part XII -- Score Release and Reporting

## 37. Admin Score Approval Queue

**Route:** `/admin/scores/pending`
**Access:** Authenticated, role = `admin` or `corporate` or `mastercorporate`

### 35.1 Page Layout

Table of exam results pending approval:

| Column | Content |
|--------|---------|
| Student Name | Text |
| Exam Title | Text |
| Exam Type | Official / Practice |
| Submitted At | Timestamp |
| Overall Score | Band or CEFR |
| Status | "Pending Approval" / "Approved" / "Rejected" |
| Action | "Approve" / "Reject" / "View Details" buttons |

Bulk actions: "Approve All Selected"

### 35.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| SCORE-01 | Only exams with `results_release_mode = manual_approval` appear in this queue. |
| SCORE-02 | "Approve" calls `POST /api/scores/:attemptId/release`. The student is notified and can now see their results. |
| SCORE-03 | "Reject" opens a dialog for a reason. Calls `POST /api/scores/:attemptId/reject` with reason text. The student sees: "Your results require further review. Reason: [reason]." |
| SCORE-04 | Practice exams (`results_release_mode = auto`) never appear in this queue. Their results are auto-released. |

---

## 38. PDF Report with QR Code

### 36.1 Report Content

The PDF report is generated on the backend but the frontend triggers it and provides a download link.

Report contents:
- **Header:** Entity logo (if white-labelled) or EnCoach logo, report title ("Exam Results Report")
- **Student info:** Name, email, student ID, entity name (if applicable)
- **Exam info:** Title, type, date taken, exam ID
- **Scores:** Per-skill band scores and overall band score, CEFR equivalent
- **Performance summary:** Strengths and weaknesses, per-question accuracy by category
- **QR Code:** Embedded at bottom-right. Encodes: `student_id`, `exam_id`, `score`, `issue_date`, and a `verification_hash`. When scanned, links to the public verification page.
- **Footer:** "Verified by EnCoach Platform. Scan QR code to verify authenticity."

### 36.2 Frontend Integration

- "Download PDF Report" button on the results page (Section 17) calls `GET /api/reports/exam/:attemptId/pdf` and triggers a browser download.
- Loading state: "Generating your report..." spinner while the backend creates the PDF.

---

## 39. Public Score Verification Page

**Route:** `/verify/:verificationHash`
**Access:** Public (no authentication required)

### 37.1 Page Layout

Minimal public page with EnCoach branding:

- **Header:** "Score Verification"
- **Verification result:**
  - If valid: Green checkmark. "This result is verified." Student name, exam type, overall score, date issued.
  - If invalid: Red X. "This verification code is invalid or has expired."
- **No other navigation or links** (this is a public verification page only)

### 37.2 Functional Requirements

| ID | Requirement |
|----|-------------|
| VERIFY-QR-01 | The page calls `GET /api/verify/:hash` on mount. Returns verification status and basic score info (no detailed per-question data). |
| VERIFY-QR-02 | This page must be accessible without authentication. |
| VERIFY-QR-03 | The verification hash is a signed token that cannot be tampered with. |

---

# Part XIII -- Technical Specifications

## 40. New Pages Inventory

| # | Page | Route | Role | Section |
|---|------|-------|------|---------|
| 1 | Registration (enhanced) | `/register` | Public | 4 |
| 2 | Email Verification | `/verify-email` | Public | 5 |
| 3 | Onboarding Wizard | `/onboarding` | Student | 6 |
| 4 | Placement Briefing | `/student/placement` | Student | 7 |
| 5 | CAT Test Interface | `/student/placement/test` | Student | 8 |
| 6 | Placement Results | `/student/placement/results` | Student | 9 |
| 7 | Payment/Access | `/student/placement/access` | Student | 10 |
| 8 | Template Selection | `/admin/exam/create` | Admin/Teacher | 11 |
| 9 | IELTS Exam Create | `/admin/exam/ielts/create` | Admin/Teacher | 12 |
| 10 | IELTS Skill Config | `/admin/exam/ielts/:id/skills` | Admin/Teacher | 13 |
| 11 | Content Pool Browser | `/admin/exam/ielts/:id/content` | Admin/Teacher | 14 |
| 12 | Exam Validation | `/admin/exam/ielts/:id/validate` | Admin/Teacher | 15 |
| 13 | Custom Exam Create | `/admin/exam/custom/create` | Admin/Teacher | 16 |
| 14 | Exam Session | `/student/exam/:id/session` | Student | 17 |
| 15 | Grading Queue | `/admin/exam/:id/grading` | Admin/Teacher | 18 |
| 16 | Exam Results | `/student/exam/:id/results` | Student | 19 |
| 17 | Gap Analysis | `/student/course/generate` | Student/Admin | 21 |
| 18 | Course Configure | `/admin/course/configure/:id` | Admin/Teacher | 22 |
| 19 | Module Builder | `/admin/course/:id/modules` | Admin/Teacher | 23 |
| 20 | Course Delivery | `/student/course/:id` | Student | 24 |
| 21 | Teacher Progress | `/teacher/course/:id/progress` | Teacher | 24 |
| 22 | Bulk Upload | `/admin/entity/students/upload` | Admin | 25 |
| 23 | Credential Dashboard | `/admin/entity/students/credentials` | Admin | 26 |
| 24 | First Login Reset | `/reset-password` | Student | 27 |
| 25 | AI English Course | `/student/course/ai-english/:id` | Student | 28 |
| 26 | AI English Quality | `/admin/ai-course/english/:id/quality` | Admin/Teacher | 28 |
| 27 | AI English Taxonomy | `/admin/ai-course/english/taxonomy` | Admin | 28 |
| 28 | AI IELTS Course | `/student/course/ai-ielts/:id` | Student | 29 |
| 29 | AI IELTS Validation | `/admin/ai-course/ielts/:id/validation` | Admin | 29 |
| 30 | Adaptive Dashboard | `/admin/adaptive/dashboard` | Admin | 30 |
| 31 | Adaptive Student Detail | `/admin/adaptive/student/:id` | Admin/Teacher | 31 |
| 32 | Adaptive Settings | `/teacher/adaptive/settings` | Teacher | 30 |
| 33 | Level Mapping Config | `/admin/entity/:id/level-mapping` | Admin | 32 |
| 34 | White-Label Branding | `/admin/entity/:id/branding` | Admin | 33 |
| 35 | Taxonomy Browser | `/admin/taxonomy` | Admin | 36 |
| 36 | Score Approval Queue | `/admin/scores/pending` | Admin | 37 |
| 37 | Score Verification | `/verify/:hash` | Public | 39 |

**Total new pages: 37**

---

## 41. New Services Inventory

| # | Service File | Purpose | Key Endpoints |
|---|-------------|---------|---------------|
| 1 | `signup.service.ts` | Registration, OTP, onboarding | `/api/auth/register`, `/api/auth/verify-email`, `/api/auth/resend-otp`, `/api/auth/check-email`, `/api/onboarding/*` |
| 2 | `placement.service.ts` | CAT placement test | `/api/placement/start`, `/api/placement/answer`, `/api/placement/autosave`, `/api/placement/results`, `/api/placement/speaking-upload`, `/api/placement/speaking-status`, `/api/placement/learning-path` |
| 3 | `exam-template.service.ts` | Template selection, custom templates | `/api/exam/templates`, `/api/exam/templates/custom` |
| 4 | `ielts-exam.service.ts` | IELTS exam CRUD and assembly | `/api/exam/ielts/create`, `/api/exam/ielts/:id/*` (skills, content-pool, auto-assemble, suggest, validate, assign) |
| 5 | `custom-exam.service.ts` | Custom exam CRUD | `/api/exam/custom/create`, `/api/exam/custom/:id/*` |
| 6 | `exam-session.service.ts` | Student exam taking | `/api/exam/:id/session`, `/api/exam/:id/autosave`, `/api/exam/:id/submit` |
| 7 | `grading.service.ts` | Manual and AI grading | `/api/grading/queue`, `/api/grading/:id/submit`, `/api/grading/ai-suggest` |
| 8 | `course-generation.service.ts` | Gap analysis, course config | `/api/course/gap-analysis`, `/api/course/auto-generate`, `/api/course/create`, `/api/course/:id/*` |
| 9 | `ai-course.service.ts` | AI course generation (English + IELTS) | `/api/ai-course/english/create`, `/api/ai-course/ielts/create`, `/api/ai-course/:id/quality`, `/api/ai-course/:id/validation` |
| 10 | `entity-onboarding.service.ts` | Bulk upload, credentials | `/api/entity/students/validate-csv`, `/api/entity/students/bulk-create`, `/api/entity/students/send-credentials`, `/api/entity/students/sis-import` |
| 11 | `adaptive.service.ts` | Adaptive engine UI | `/api/adaptive/dashboard`, `/api/adaptive/students`, `/api/adaptive/settings`, `/api/adaptive/student/:id/signals` |
| 12 | `level-mapping.service.ts` | Entity level mapping | `/api/entity/:id/level-mapping` |
| 13 | `branding.service.ts` | White-label branding | `/api/entity/:id/branding`, `/api/entity/branding` |
| 14 | `score-release.service.ts` | Score approval | `/api/scores/pending`, `/api/scores/:id/release`, `/api/scores/:id/reject` |
| 15 | `report.service.ts` | PDF report generation | `/api/reports/exam/:id/pdf` |
| 16 | `verification.service.ts` | Public score verification | `/api/verify/:hash` |
| 17 | `taxonomy.service.ts` | Subject taxonomy CRUD | `/api/taxonomy/subjects`, `/api/taxonomy/tree` |

**Total new services: 17**

---

## 42. New Types Inventory

| # | Type File | Key Interfaces |
|---|-----------|----------------|
| 1 | `signup.ts` | `RegisterRequest`, `VerifyEmailRequest`, `OnboardingData`, `Goal` |
| 2 | `placement.ts` | `CATSession`, `CATQuestion`, `CATAnswer`, `PlacementResult`, `LearningPathPreview`, `SpeakingUpload` |
| 3 | `exam-template.ts` | `ExamTemplate`, `TemplatePath`, `TemplateCard`, `TemplateType` |
| 4 | `ielts-exam.ts` | `IELTSExamConfig`, `IELTSSkillConfig`, `ContentPoolItem`, `AssemblyMode`, `ExamValidationReport` |
| 5 | `custom-exam.ts` | `CustomExamConfig`, `CustomSection`, `CustomScoringMethod`, `CustomExamCreateRequest` |
| 6 | `exam-session.ts` | `ExamSession`, `ExamSection`, `ExamQuestion`, `ExamAnswer`, `SubmissionSummary` |
| 7 | `grading.ts` | `GradingQueueItem`, `RubricCriteria`, `AIGradeSuggestion`, `GradeSubmission` |
| 8 | `course-generation.ts` | `GapAnalysis`, `SkillGap`, `CourseConfig`, `ModuleConfig`, `ProgressionModel` |
| 9 | `ai-course.ts` | `AICourseConfig`, `QualityGateResult`, `IELTSValidationResult`, `ExaminerReview` |
| 10 | `entity-onboarding.ts` | `CSVValidationReport`, `BulkCreateResult`, `CredentialStatus`, `EntityStudent` |
| 11 | `adaptive.ts` | `AdaptiveDashboard`, `AdaptiveStudentProfile`, `EngineSignal`, `EngineDecision`, `ThresholdSettings`, `AbilityModel` |
| 12 | `level-mapping.ts` | `LevelMapping`, `LevelMappingRow` |
| 13 | `branding.ts` | `EntityBranding`, `BrandingConfig` |
| 14 | `score-release.ts` | `PendingScore`, `ScoreReleaseAction` |
| 15 | `math.ts` | `NumericalQuestion`, `ExpressionQuestion`, `MatrixQuestion`, `GraphQuestion` |
| 16 | `it.ts` | `CodeQuestion`, `SQLQuestion`, `CodeExecutionResult` |

**Total new type files: 16**

---

## 43. API Contracts

### 43.1 Authentication

All API calls (except public routes) require a JWT token in the `Authorization` header:
```
Authorization: Bearer <jwt_token>
```

Public routes (no auth required):
- `POST /api/auth/register`
- `POST /api/auth/verify-email`
- `POST /api/auth/resend-otp`
- `POST /api/auth/check-email`
- `GET /api/verify/:hash`

### 43.2 Standard Response Format

All API responses follow this envelope:

```json
{
  "success": true,
  "data": { ... },
  "message": "optional message",
  "errors": []
}
```

Error responses:
```json
{
  "success": false,
  "data": null,
  "message": "Error description",
  "errors": [
    { "field": "email", "message": "Email already exists" }
  ]
}
```

### 43.3 Pagination

List endpoints support pagination:
```
GET /api/resource?page=1&limit=20&sort=created_at&order=desc
```

Response includes:
```json
{
  "data": [...],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 247,
    "total_pages": 13
  }
}
```

### 43.4 Full Endpoint Summary

| Category | Endpoint Count | Section Reference |
|----------|---------------|-------------------|
| Auth & Signup | 5 | 4--6 |
| Placement Test | 7 | 7--10 |
| Exam Templates | 3 | 11 |
| IELTS Exam Config | 12 | 12--15 |
| Custom Exam Config | 4 | 16 |
| Exam Session | 4 | 17 |
| Grading | 4 | 18 |
| Course Generation | 8 | 21--24 |
| AI Course Generation | 6 | 28--29 |
| Entity Onboarding | 6 | 25--27 |
| Adaptive Engine | 5 | 30--31 |
| Entity/Branding | 4 | 32--33 |
| Score Release | 4 | 37 |
| Reports | 1 | 38 |
| Verification | 1 | 39 |
| Taxonomy | 2 | 36 |
| **Total** | **~76** | |

---

## End of Document

**Document Version:** 1.1
**Total New Pages:** 37
**Total New Services:** 17
**Total New Type Files:** 16
**Total New API Endpoints:** ~76
**Workflow Coverage:** All 6 workflows + Exam Template Paths (International + Custom) + Adaptive Engine (4 phases) + Math/IT + White-Labelling + Score Release

This document covers the complete frontend implementation required by `encoach_workflows_v3.pdf`. The developer should implement these features on top of the existing 93-page frontend codebase.
