feat: add complete EnCoach frontend application

Full React 18 + TypeScript + Vite frontend with:
- 90+ pages (admin, student, teacher, public)
- shadcn/ui component library with 50+ components
- JWT authentication with role-based access control
- TanStack React Query for server state management
- 30+ API service modules
- AI-powered features (coaching, grading, generation)
- Adaptive learning UI (diagnostics, proficiency, plans)
- Institutional LMS management (courses, batches, timetable)
- Communication suite (discussions, announcements, DMs)
- Full CRUD with validation and confirmation dialogs

Made-with: Cursor
This commit is contained in:
Yamen Ahmad
2026-04-01 16:59:11 +04:00
commit 110a0b7105
307 changed files with 46583 additions and 0 deletions

633
docs/04-AI-Stack-Report.md Normal file
View File

@@ -0,0 +1,633 @@
# EnCoach - AI Stack Technical Report
**Analysis Date:** March 8, 2026
---
## Table of Contents
1. [AI Stack Overview](#1-ai-stack-overview)
2. [OpenAI GPT (Content Generation & Grading)](#2-openai-gpt--content-generation--grading)
3. [OpenAI Whisper (Speech-to-Text)](#3-openai-whisper--speech-to-text)
4. [AWS Polly (Text-to-Speech)](#4-aws-polly--text-to-speech)
5. [FAISS + Sentence Transformers (RAG Training Tips)](#5-faiss--sentence-transformers--rag-training-tips)
6. [ELAI (AI Avatar Video Generation)](#6-elai--ai-avatar-video-generation)
7. [GPTZero (AI Writing Detection)](#7-gptzero--ai-writing-detection)
8. [End-to-End Data Flows](#8-end-to-end-data-flows)
9. [Frontend AI Integration Points](#9-frontend-ai-integration-points)
10. [Environment Variables & Configuration](#10-environment-variables--configuration)
---
## 1. AI Stack Overview
The EnCoach platform uses **6 AI/ML services** working together to power automated IELTS exam generation, grading, and personalized training.
```
┌─────────────────────────────────────────────────────────┐
│ Frontend (Next.js) │
│ ExamEditor, ExamPage, Training, AIDetection components │
└────────────────────────┬────────────────────────────────┘
│ HTTP (JWT)
┌─────────────────────────────────────────────────────────┐
│ Backend (FastAPI) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ OpenAI │ │ Whisper │ │ AWS Polly│ │
│ │ GPT-4o │ │ (local) │ │ (cloud) │ │
│ │ GPT-3.5 │ │ base │ │ neural │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │
│ Content Gen Transcription TTS Audio │
│ Grading Speaking eval Listening MP3s │
│ Evaluation │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ FAISS + │ │ ELAI │ │ GPTZero │ │
│ │ SentTrans│ │ (cloud) │ │ (cloud) │ │
│ │ (local) │ │ avatars │ │ detect │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │
│ RAG Tips Avatar Videos AI Detection │
│ Training Speaking Writing eval │
│ │
└─────────────────────────────────────────────────────────┘
```
| Service | Type | Purpose | Model/Version |
|---|---|---|---|
| **OpenAI GPT** | Cloud API | Content generation, grading, evaluation | `gpt-4o`, `gpt-3.5-turbo` |
| **OpenAI Whisper** | Local (self-hosted) | Speech-to-text transcription | `base` (~1 GB, 4 instances) |
| **AWS Polly** | Cloud API | Text-to-speech for listening | Neural engine, 11 voices |
| **FAISS + Sentence Transformers** | Local (self-hosted) | RAG-based training tips | `all-MiniLM-L6-v2` + `IndexFlatL2` |
| **ELAI** | Cloud API | AI avatar video generation | ElevenLabs/Azure voices |
| **GPTZero** | Cloud API | AI-generated text detection | v2/predict/text |
---
## 2. OpenAI GPT — Content Generation & Grading
### 2.1 Configuration
| Setting | Value |
|---|---|
| **Default Model** | `gpt-4o` |
| **Secondary Model** | `gpt-3.5-turbo` |
| **Max Tokens** | 4,097 (300 reserved) |
| **Response Format** | `json_object` |
| **Retry Limit** | 2 (on blacklist or missing fields) |
| **Content Filter** | Blacklisted words (religious, sexual, political terms) |
**Temperature settings:**
| Context | Temperature | Behavior |
|---|---|---|
| Grading | 0.1 | Near-deterministic, consistent evaluation |
| Tips / Summaries | 0.2 | Low creativity, factual output |
| Content Generation | 0.7 | Higher creativity for passages and tasks |
### 2.2 Content Generation
GPT generates all IELTS exam content. Each module has specific prompt templates:
#### Reading Module
- **Model:** `gpt-4o`, temperature 0.7
- **Generates:** Passages with title and text body
- **Difficulty scaling:**
- Passage 1: easy
- Passage 2: hard
- Passage 3: very hard
- **Exercise types generated:** Fill in the blanks, True/False/Not Given, Matching headings, Multiple choice
- **Prompt pattern:** System prompt defines JSON schema → User prompt specifies passage difficulty, topic, and word count
#### Listening Module
- **Model:** `gpt-4o`, temperature 0.7
- **Generates:** Conversation scripts and monologues
- **Output format:**
- Conversations: `{"conversation": [{"name", "gender", "text"}]}` — 2 or 4 speakers
- Monologues: `{"monologue": "..."}` — social or academic context
- **Exercise types generated:** Same as reading (fill blanks, T/F/NG, matching, MC)
#### Writing Module
- **Task 1 (General):** Letter prompts — `gpt-3.5-turbo`
- **Task 1 (Academic):** Image-based prompts — `gpt-4o`
- **Task 2 (Essay):** Essay prompts — `gpt-4o`
#### Speaking Module
- **Model:** `gpt-4o`, temperature 0.7
- **Part 1:** 5 questions across 2 topics
- **Part 2:** 1 question + 3 follow-up prompts
- **Part 3:** 5 discussion questions
#### Level Test
- **Generates:** Multiple choice questions at varying difficulty levels
- **Supports:** Standard level, UTAS format, custom levels
### 2.3 Grading / Evaluation
GPT evaluates student answers using IELTS band scoring criteria:
#### Writing Grading
- **Model:** `gpt-4o`, temperature 0.1 (Task 1) / 0.7 (Task 2)
- **Runs in parallel:** Evaluation + Perfect Answer + Spelling Fix + GPTZero
- **Output JSON:**
```json
{
"comment": "Detailed commentary...",
"overall": 6.5,
"task_response": {
"Task Achievement": { "score": 7, "comment": "..." },
"Coherence and Cohesion": { "score": 6, "comment": "..." },
"Lexical Resource": { "score": 7, "comment": "..." },
"Grammatical Range and Accuracy": { "score": 6, "comment": "..." }
}
}
```
- **Perfect Answer:** GPT generates an ideal answer for comparison
- **Spelling Fix:** `gpt-3.5-turbo` at temperature 0.2 corrects transcription errors
#### Speaking Grading
- **Flow:** Audio → Whisper transcription → GPT-4o grading
- **Criteria:** Fluency & Coherence, Lexical Resource, Grammar, Pronunciation
- **Perfect Answers:** `gpt-4o` (Part 1), `gpt-3.5-turbo` (Parts 2/3)
#### Exam Summary
- **Model:** `gpt-3.5-turbo`, temperature 0.2
- **Uses:** OpenAI function calling (`save_evaluation_and_suggestions`)
- **Output:** Overall evaluation, suggestions, bullet points
### 2.4 Other GPT Uses
- **Training tips selection:** GPT selects relevant tips from FAISS results
- **Whisper overlap fix:** GPT-4o merges overlapping transcription segments
- **Short answer grading:** Grades fill-in-the-blank and short text answers
---
## 3. OpenAI Whisper — Speech-to-Text
### 3.1 Configuration
| Setting | Value |
|---|---|
| **Model** | `base` (~1 GB) |
| **Instances** | 4 (round-robin) |
| **Loading** | `in_memory=True` |
| **Concurrency** | `ThreadPoolExecutor` with 4 workers |
| **Language** | English |
| **Precision** | `fp16=False` |
### 3.2 How It Works
Whisper runs **locally** on the Cloud Run container (not via OpenAI's API). Four model instances are loaded into memory at startup and assigned to workers via round-robin.
**Processing pipeline:**
```
Audio Input
Resample to 16 kHz mono float32 (librosa)
Split into 30-second chunks (1/4 overlap)
Transcribe each chunk (Whisper base model)
Concatenate transcriptions
Fix overlapping text (GPT-4o removes duplicated words)
Final transcript
```
**Retry:** 3 attempts via `tenacity` library.
### 3.3 Where It's Connected
| Feature | Connection |
|---|---|
| **Speaking Grading** | Student audio → Whisper → transcript → GPT grading |
| **Audio Transcription** | Uploaded audio → Whisper → listening script for exam editor |
---
## 4. AWS Polly — Text-to-Speech
### 4.1 Configuration
| Setting | Value |
|---|---|
| **Engine** | Neural |
| **Output Format** | MP3 |
| **Region** | `eu-west-1` |
| **Max Chunk Size** | 3,000 characters (split at sentence boundaries) |
### 4.2 Available Voices
| Voice | Language/Accent |
|---|---|
| Danielle | American English |
| Gregory | American English |
| Kevin | American English |
| Ruth | American English |
| Stephen | American English |
| Arthur | British English |
| Olivia | Australian English |
| Ayanda | South African English |
| Aria | New Zealand English |
| Kajal | Indian English |
| Niamh | Irish English |
### 4.3 How It Works
**Listening exam audio generation:**
```
Generated Dialog/Monologue (from GPT)
Assign voices to speakers (random for monologue, per-speaker for dialog)
Split text into ≤3000 char chunks at sentence boundaries
AWS Polly Neural TTS → MP3 audio bytes
Concatenate audio segments
Upload to Firebase Storage
Return download URL
```
### 4.4 Where It's Connected
| Feature | Connection |
|---|---|
| **Listening Exam Audio** | GPT script → Polly TTS → MP3 → Firebase Storage → student playback |
| **Listening Instructions** | "Recording has now finished" scripts → Stephen voice → MP3 |
---
## 5. FAISS + Sentence Transformers — RAG Training Tips
### 5.1 Configuration
| Setting | Value |
|---|---|
| **Embeddings Model** | `all-MiniLM-L6-v2` (Sentence Transformers) |
| **Index Type** | `faiss.IndexFlatL2` (exact L2 search) |
| **Top-K** | 5 results per query |
| **Data Source** | `pathways_2_rw_with_ids.json` |
### 5.2 Knowledge Base Categories
| Category | Index File |
|---|---|
| `ct_focus` | `./faiss/ct_focus_tips_index.faiss` |
| `language_for_writing` | `./faiss/language_for_writing_tips_index.faiss` |
| `reading_skill` | `./faiss/reading_skill_tips_index.faiss` |
| `strategy` | `./faiss/strategy_tips_index.faiss` |
| `word_link` | `./faiss/word_link_tips_index.faiss` |
| `word_partners` | `./faiss/word_partners_tips_index.faiss` |
| `writing_skill` | `./faiss/writing_skill_tips_index.faiss` |
**Metadata:** `./faiss/tips_metadata.pkl` (pickle file with tip IDs and text)
### 5.3 How RAG Works
```
Student Exam Performance
GPT analyzes performance → generates queries (text + category)
Sentence Transformers encodes query → embedding vector
FAISS L2 search → top 5 matching tips per category
GPT selects most relevant tips from retrieved results
Tips stored in MongoDB and displayed to student
```
### 5.4 Where It's Connected
| Feature | Connection |
|---|---|
| **Training Module** | After exam → analyze weak areas → retrieve personalized tips → display training content |
| **Walkthrough** | Tips linked to specific reading/writing skills for guided learning |
---
## 6. ELAI — AI Avatar Video Generation
### 6.1 Configuration
| Setting | Value |
|---|---|
| **API Endpoint** | `https://apis.elai.io/api/v1/videos` |
| **Auth** | Bearer token (`ELAI_TOKEN`) |
| **Animation** | `fade_in` |
| **Language** | English |
### 6.2 Available Avatars
| Avatar | Gender | Voice Provider |
|---|---|---|
| Gia | Female | ElevenLabs |
| Vadim | Male | Azure |
| Orhan | Male | ElevenLabs |
| Flora | Female | Azure |
| Scarlett | Female | ElevenLabs |
| Parker | Male | Azure |
| Ethan | Male | ElevenLabs |
Each avatar has a unique `avatar_code`, `avatar_url`, `avatar_canvas` dimensions, `voice_id`, and `voice_provider`.
### 6.3 How It Works
```
Speaking Task Text (from GPT)
Select Avatar (user choice from available list)
Build video config (slide, avatar, canvas, logo, voice settings)
POST to ELAI API → create video
POST render request → start processing
Poll GET status every 10 seconds until "ready"
Return video URL for playback
```
### 6.4 Where It's Connected
| Feature | Connection |
|---|---|
| **Speaking Exam** | AI avatar presents speaking questions via video |
| **Exam Editor** | Teachers generate speaking videos while creating exams |
---
## 7. GPTZero — AI Writing Detection
### 7.1 Configuration
| Setting | Value |
|---|---|
| **API Endpoint** | `https://api.gptzero.me/v2/predict/text` |
| **Auth** | `x-api-key` header |
| **Multilingual** | `false` |
### 7.2 How It Works
```
Student's Writing Submission
POST to GPTZero API with document text
Response: predicted_class, confidence, per-sentence AI probability
Returned as part of writing evaluation
Frontend displays AI Detection component
```
**Response fields:**
- `predicted_class`: `ai`, `mixed`, or `human`
- `confidence_category`: confidence level
- `class_probabilities`: probability distribution
- `sentences`: per-sentence analysis with `highlight_sentence_for_ai` flag
### 7.3 Where It's Connected
| Feature | Connection |
|---|---|
| **Writing Grading** | Runs in parallel with GPT evaluation, perfect answer, and spelling fix |
| **Frontend UI** | `AIDetection` component displays results with radial progress, segmented bars, and highlighted AI-generated sentences |
---
## 8. End-to-End Data Flows
### 8.1 Exam Generation Flow
```
Teacher clicks "Generate" in Exam Editor
Frontend: POST /api/exam/generate/{module}/{sectionId}
Next.js API Route: proxies to BACKEND_URL/{module}/...
FastAPI Controller → Service
├── Reading: GPT-4o generates passage + exercises
├── Listening: GPT-4o generates script → Polly TTS → MP3 → Firebase
├── Writing: GPT-4o/3.5 generates task prompt
└── Speaking: GPT-4o generates questions → ELAI creates avatar video
Response with generated content → stored in exam editor state
```
### 8.2 Writing Grading Flow
```
Student submits writing answer
Frontend: POST /api/evaluate/writing
Next.js API: inserts pending evaluation in MongoDB → proxies to backend
FastAPI runs 4 tasks IN PARALLEL:
├── GPT-4o: Grade against IELTS band criteria (temp 0.1)
├── GPT-4o: Generate perfect answer for comparison
├── GPT-3.5: Fix spelling/transcription errors (temp 0.2)
└── GPTZero: Detect AI-generated content
Combined result stored in MongoDB evaluation collection
Frontend polls /api/evaluate/status until complete
UI shows: band scores, detailed comments, perfect answer, AI detection
```
### 8.3 Speaking Grading Flow
```
Student records audio response
Frontend: POST /api/evaluate/speaking (FormData with audio)
Next.js API: inserts pending evaluation → proxies to backend
FastAPI pipeline:
Whisper (local): Transcribe audio → text
GPT-4o: Grade transcript against IELTS speaking criteria (temp 0.1)
GPT-4o/3.5: Generate perfect answer
Result stored in MongoDB
Frontend polls and displays scores + transcript + perfect answer
```
### 8.4 Training / Personalized Tips Flow
```
Student completes an exam
Frontend: POST /api/training
Backend analyzes exam performance with GPT
GPT generates search queries + categories
Sentence Transformers encodes queries → FAISS L2 search
Top 5 tips per category retrieved
GPT selects most relevant tips
Training content stored in MongoDB → displayed to student
```
---
## 9. Frontend AI Integration Points
### 9.1 API Routes (Next.js → FastAPI)
| Frontend Route | Backend Route | AI Services Used |
|---|---|---|
| `POST /api/evaluate/writing` | `BACKEND_URL/grade/writing/{task}` | GPT-4o, GPT-3.5, GPTZero |
| `POST /api/evaluate/speaking` | `BACKEND_URL/grade/speaking/{task}` | Whisper, GPT-4o, GPT-3.5 |
| `GET /api/exam/generate/reading/{id}` | `BACKEND_URL/reading/{passage}` | GPT-4o |
| `GET /api/exam/generate/listening/{id}` | `BACKEND_URL/listening/{section}` | GPT-4o |
| `GET /api/exam/generate/writing/{id}` | `BACKEND_URL/writing/{task}` | GPT-4o / GPT-3.5 |
| `GET /api/exam/generate/speaking/{id}` | `BACKEND_URL/speaking/{task}` | GPT-4o |
| `POST /api/exam/media/listening` | `BACKEND_URL/listening/media` | AWS Polly |
| `POST /api/exam/media/speaking` | `BACKEND_URL/speaking/media` | ELAI |
| `POST /api/transcribe` | `BACKEND_URL/listening/transcribe` | Whisper |
| `POST /api/training` | `BACKEND_URL/training/` | GPT, FAISS, Sentence Transformers |
| `GET /api/exam/avatars` | `BACKEND_URL/speaking/avatars` | ELAI |
### 9.2 Key UI Components
| Component | Purpose |
|---|---|
| `AIDetection.tsx` | Displays AI detection results (radial progress, highlighted sentences) |
| `GenerateBtn.tsx` | Brain icon button with spinner for content generation |
| `generateVideos.ts` | Manages ELAI video creation + polling loop |
| `ExamPage.tsx` | Triggers writing/speaking evaluation + polls for results |
| `useEvaluationPolling.tsx` | Hook that polls evaluation status until grading completes |
| `generation.tsx` | Page for generating exams (gated by permissions) |
### 9.3 Permissions
| Permission | Controls |
|---|---|
| `generate_reading` | Reading passage generation |
| `generate_listening` | Listening script generation |
| `generate_writing` | Writing prompt generation |
| `generate_speaking` | Speaking task generation |
| `generate_level` | Level test generation |
---
## 10. Environment Variables & Configuration
### 10.1 Required API Keys
| Variable | Service | Where Used |
|---|---|---|
| `OPENAI_API_KEY` | OpenAI GPT-4o / GPT-3.5 | Content generation, grading, evaluation |
| `AWS_ACCESS_KEY_ID` | AWS Polly | Text-to-speech |
| `AWS_SECRET_ACCESS_KEY` | AWS Polly | Text-to-speech |
| `ELAI_TOKEN` | ELAI | Avatar video generation |
| `GPT_ZERO_API_KEY` | GPTZero | AI writing detection |
### 10.2 Backend Service Wiring (Dependency Injection)
```
DI Container
├── llm → OpenAI(client=AsyncOpenAI)
├── tts → AWSPolly(client=polly_client)
├── stt → OpenAIWhisper(model="base", num_models=4)
├── vid_gen → ELAI(client=http_client, token, avatars, conf)
├── ai_detector → GPTZero(client=http_client, key)
├── training_kb → TrainingContentKnowledgeBase(embeddings=SentenceTransformer)
├── Controllers
│ ├── ReadingController → uses llm
│ ├── ListeningController → uses llm, tts
│ ├── WritingController → uses llm, ai_detector
│ ├── SpeakingController → uses llm, stt, vid_gen
│ ├── GradeController → uses llm, stt, ai_detector
│ ├── LevelController → uses llm
│ └── TrainingController → uses llm, training_kb
```
### 10.3 Cost Drivers
| Service | Cost Model | Usage Pattern |
|---|---|---|
| **OpenAI GPT-4o** | Per token (input + output) | Every generation, every grading — highest cost |
| **OpenAI GPT-3.5** | Per token (cheaper) | Summaries, spelling, some writing tasks |
| **AWS Polly** | Per character (Neural) | Every listening exam audio |
| **ELAI** | Per video minute | Every speaking exam video |
| **GPTZero** | Per API call | Every writing grading |
| **Whisper (local)** | Compute only (no API cost) | Every speaking grading + transcription |
| **FAISS (local)** | Compute only (no API cost) | Every training session |

344
docs/ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,344 @@
# EnCoach Platform -- Architecture & Connectivity Document
## Overview
EnCoach is an **IELTS preparation and English proficiency testing platform** composed of four repositories that work together as a distributed system. The platform supports exam taking, AI-powered grading, training content, multi-tenant entity management, payments, and a public-facing marketing website.
---
## Repositories at a Glance
- **[ielts-ui](ielts-ui)** -- Full-stack Next.js 14 app. The main platform for students, teachers, admins, and corporate users. Serves both the browser UI and internal API routes.
- **[ielts-be](ielts-be)** -- Python/FastAPI backend. Handles AI/ML workloads: exam generation, grading (writing/speaking), audio transcription, TTS, and training content.
- **[encoachcms](encoachcms)** -- Strapi v4 headless CMS. Manages bilingual (EN/AR) marketing content for the landing page.
- **[encoach-landing-page](encoach-landing-page)** -- Next.js 13 marketing website. Consumes CMS content and links users into the main platform.
---
## System Architecture Diagram
```mermaid
graph TB
subgraph publicFacing ["Public-Facing Layer"]
LP["encoach-landing-page<br/>(Next.js 13)"]
CMS["encoachcms<br/>(Strapi v4)"]
end
subgraph platformCore ["Platform Core"]
UI["ielts-ui<br/>(Next.js 14 + API Routes)"]
BE["ielts-be<br/>(FastAPI / Python)"]
end
subgraph dataStores ["Data Stores"]
MongoDB["MongoDB"]
MySQL["MySQL<br/>(CMS)"]
FirebaseAuth["Firebase Auth"]
FirebaseStorage["Firebase Storage"]
GCS["Google Cloud Storage<br/>(CMS uploads)"]
end
subgraph externalServices ["External Services"]
OpenAI["OpenAI GPT-4o"]
Whisper["OpenAI Whisper<br/>(local)"]
Polly["AWS Polly<br/>(TTS)"]
ELAI["ELAI<br/>(AI Video)"]
GPTZero["GPTZero<br/>(AI Detection)"]
Stripe["Stripe"]
PayPal["PayPal"]
Paymob["Paymob"]
end
LP -->|"REST + Bearer token"| CMS
LP -->|"GET /api/packages, POST /api/tickets"| UI
LP -->|"Links to platform.encoach.com"| UI
CMS --> MySQL
CMS --> GCS
UI --> MongoDB
UI --> FirebaseAuth
UI -->|"Proxy: Bearer JWT"| BE
BE --> MongoDB
BE --> FirebaseAuth
BE --> FirebaseStorage
BE --> OpenAI
BE --> Whisper
BE --> Polly
BE --> ELAI
BE --> GPTZero
UI --> Stripe
UI --> PayPal
UI --> Paymob
LP --> Stripe
```
---
## 1. ielts-ui (Main Platform)
**Tech:** Next.js 14, React 18, TypeScript, Tailwind CSS + DaisyUI, Zustand, SWR, iron-session, Firebase Auth, MongoDB (direct)
**Role:** The central application. Serves the browser UI and acts as a **BFF (Backend-for-Frontend)** via Next.js API routes. It directly queries MongoDB for user/entity/group data and proxies AI-related requests to `ielts-be`.
### Key Modules
| Module | Description |
|--------|-------------|
| **Auth** | Firebase email/password auth + iron-session cookies. SSR-protected via `withIronSessionSsr`. |
| **Dashboards** | Role-based: student, teacher, admin, corporate, mastercorporate, developer, agent. |
| **Exams** | Taking exams (Reading, Listening, Writing, Speaking, Level). Zustand store tracks session, progress, solutions. |
| **Exam Editor** | Create/edit exams with dedicated components under `src/components/ExamEditor/`. |
| **Training** | Training content consumed from `ielts-be`. |
| **Grading** | Writing and speaking grading proxied to `ielts-be` as background tasks; UI polls for results. |
| **Entities** | Multi-tenant entity management (schools, organizations). |
| **Classrooms** | Classroom and group management for teachers. |
| **Assignments** | Assign exams to students with deadlines. |
| **Stats** | Performance statistics and PDF report generation (via `@react-pdf/renderer`). |
| **Payments** | Stripe, PayPal, Paymob webhook handlers in API routes. |
| **Tickets** | Support ticket system. |
| **User Mgmt** | Bulk import, permissions, role-based access. |
### How it Connects to ielts-be
API routes in `src/pages/api/` proxy to `BACKEND_URL` with `Authorization: Bearer ${BACKEND_JWT}`:
| UI API Route | Backend Endpoint |
|--------------|------------------|
| `/api/evaluate/writing` | `BACKEND_URL/grade/writing/{task}` |
| `/api/evaluate/speaking` | `BACKEND_URL/grade/speaking/{task}` |
| `/api/transcribe` | `BACKEND_URL/listening/transcribe` |
| `/api/training` | `BACKEND_URL/training/` |
| `/api/exam/upload` | `BACKEND_URL/{endpoint}` |
| `/api/exam/media/*` | `BACKEND_URL/{endpoint}/media` |
| `/api/exam/generate/*` | `BACKEND_URL/{endpoint}` |
| `/api/exam/avatars` | `BACKEND_URL/speaking/avatars` |
| `/api/exam/[module]/import` | `BACKEND_URL/{module}/import` |
| `/api/stats/[id]/[export]/pdf` | `BACKEND_URL/grade/summary` |
| `/api/batch_users` | `BACKEND_URL/user/import` |
### How it Connects to the Landing Page
Exposes public-ish API routes consumed by the landing page:
- `GET /api/packages` -- subscription packages (CORS-enabled)
- `POST /api/tickets` -- contact form submissions (CORS-enabled)
- `GET /api/users/agents` -- list sales agents (CORS-enabled)
---
## 2. ielts-be (AI/ML Backend)
**Tech:** Python 3.11, FastAPI, Motor (async MongoDB), Poetry, dependency-injector, OpenAI, Whisper, AWS Polly, ELAI, FAISS
**Role:** Handles all AI/ML-intensive operations -- exam content generation, grading, transcription, text-to-speech, AI video, and training recommendations. Runs as a standalone service on port 8000.
### Architecture Layers
```
API Routes --> Controllers --> Services --> Repositories
|
Third-Party Services
(OpenAI, Whisper, Polly, ELAI, GPTZero)
```
Wired together via `dependency-injector`.
### Key Capabilities
| Capability | Implementation |
|------------|----------------|
| **Writing Grading** | GPT-4o evaluates against IELTS rubric (Task Achievement, Coherence, Lexical Resource, Grammar). GPTZero checks for AI-generated text. Runs as background task; results stored in `evaluation` collection. |
| **Speaking Grading** | Whisper transcribes audio, then GPT grades (Fluency, Lexical, Grammar, Pronunciation). Parts 1/2/3 supported. |
| **Exam Generation** | GPT generates reading passages, listening dialogs, writing prompts, speaking tasks, and level-test exercises. |
| **Audio (TTS)** | AWS Polly synthesizes MP3 for listening sections. |
| **Video** | ELAI generates AI avatar videos for speaking prompts. |
| **Transcription** | Whisper (local model) for speech-to-text. |
| **Training** | FAISS + sentence-transformers for semantic search over tips; GPT for personalized recommendations. |
| **Short Answer Grading** | GPT-4o for reading/listening fill-in-the-blank answers. |
### Authentication
All endpoints (except `/api/healthcheck`) require a Bearer JWT token validated with `JWT_SECRET_KEY` (HS256). The `ielts-ui` sends this as `BACKEND_JWT`.
---
## 3. encoachcms (Content Management)
**Tech:** Strapi v4.21, Node.js 18, MySQL (prod) / SQLite (dev), Google Cloud Storage for uploads
**Role:** Headless CMS for managing the marketing website content. Editors create/update bilingual (EN/AR) content via the Strapi admin panel at `/admin`.
### Content Types (all Single Types)
`home`, `about`, `services`, `contact`, `footer`, `nav-bar`, `history`, `price`, `terms-and-conditions`, `privacy-policy`, `country-managers-contact`
### How it Connects
- Exposes REST API at `STRAPI_URL/api/{content-type}/?populate=deep&locale={en|ar}`
- Authenticated via API token (`STRAPI_TOKEN`)
- **Only consumed by `encoach-landing-page`** -- neither `ielts-ui` nor `ielts-be` use it
### Plugins
- `strapi-plugin-populate-deep` -- deep relation population
- `strapi-plugin-import-export-entries` -- content import/export
- `strapi-plugin-publisher` -- scheduled publishing
- `@strapi/plugin-i18n` -- internationalization
- `@strapi/plugin-documentation` -- OpenAPI docs
---
## 4. encoach-landing-page (Marketing Website)
**Tech:** Next.js 13 (App Router), TypeScript, Tailwind CSS + DaisyUI, Stripe
**Role:** Public marketing website at `encoach.com`. Bilingual (EN at `/`, AR at `/ar/`). Fetches content from the CMS and links users into the main platform.
### Pages
`/` (Home), `/about`, `/services`, `/price`, `/history`, `/contact`, `/terms`, `/privacy-policy`, `/contacts/[country]`, `/success` -- all mirrored under `/ar/` for Arabic.
### How it Connects
| Target | Connection |
|--------|------------|
| **encoachcms** | `getData()` fetches `STRAPI_URL/api/{page}/?populate=deep&locale={locale}` with Bearer token |
| **ielts-ui** | `GET /api/packages` for pricing, `POST /api/tickets` for contact form, `GET /api/users/agents` for sales agents |
| **Stripe** | Checkout flow; `/api/success` route validates session and POSTs to `WEBHOOK_URL` |
| **Platform links** | Buttons link to `platform.encoach.com/register`, `platform.encoach.com/official-exam` |
---
## Data Flow Diagrams
### Authentication Flow
```mermaid
sequenceDiagram
participant Browser
participant UI as ielts-ui
participant Firebase as Firebase Auth
participant Mongo as MongoDB
Browser->>UI: POST /api/login (email, password)
UI->>Firebase: signInWithEmailAndPassword
Firebase-->>UI: Firebase UID + token
UI->>Mongo: Find user by Firebase UID
Mongo-->>UI: User document
UI->>UI: Save to iron-session cookie
UI-->>Browser: Set-Cookie (eCrop/ielts)
Browser->>UI: Subsequent requests with cookie
UI->>UI: withIronSessionSsr validates cookie
```
### Exam Grading Flow (Writing)
```mermaid
sequenceDiagram
participant Student
participant UI as ielts-ui API Route
participant BE as ielts-be
participant GPT as OpenAI GPT-4o
participant GPTZero as GPTZero
participant Mongo as MongoDB
Student->>UI: Submit writing answer
UI->>BE: POST /api/exam/grade/writing/{task}
BE->>BE: Start background task
BE-->>UI: 200 OK (accepted)
UI-->>Student: "Grading in progress"
par Parallel Grading
BE->>GPT: Evaluate against IELTS rubric
GPT-->>BE: Scores + feedback
and AI Detection
BE->>GPTZero: Check for AI content
GPTZero-->>BE: AI probability
end
BE->>Mongo: Save evaluation result
Student->>UI: Poll for result
UI->>Mongo: Query evaluation
Mongo-->>UI: Grading result
UI-->>Student: Display scores + feedback
```
### Landing Page Content Flow
```mermaid
sequenceDiagram
participant Visitor
participant LP as encoach-landing-page
participant CMS as encoachcms (Strapi)
participant Platform as ielts-ui
Visitor->>LP: Visit encoach.com
LP->>CMS: GET /api/home/?populate=deep&locale=en
CMS-->>LP: Home content (JSON)
LP-->>Visitor: Rendered page
Visitor->>LP: View pricing
LP->>CMS: GET /api/price/?populate=deep&locale=en
LP->>Platform: GET /api/packages
Platform-->>LP: Package list
LP-->>Visitor: Pricing page with packages
Visitor->>LP: Submit contact form
LP->>Platform: POST /api/tickets
Platform-->>LP: Ticket created
```
---
## Shared Infrastructure
| Resource | Used By | Details |
|----------|---------|---------|
| **MongoDB** | ielts-ui, ielts-be | Same database (`MONGODB_URI` / `MONGODB_DB`). UI reads users, groups, stats directly. BE reads/writes evaluations, training. |
| **Firebase Auth** | ielts-ui, ielts-be | Shared Firebase project. UI handles login/signup; BE imports users. |
| **Firebase Storage** | ielts-be | Stores exam media (audio, images). |
| **Google Cloud Storage** | encoachcms | CMS file uploads (images, media). |
---
## Deployment Topology
| Service | Port | URL (Production) |
|---------|------|-------------------|
| ielts-ui | 3000 | `platform.encoach.com` |
| ielts-be | 8000 | Internal (proxied by ielts-ui) |
| encoachcms | 1337 | Internal (consumed by landing page) |
| encoach-landing-page | 3000 | `encoach.com` |
Both Next.js apps use `output: "standalone"` and have Dockerfiles. The BE is not directly exposed to the internet -- it sits behind ielts-ui's API route proxy layer.
---
## User Roles
| Role | Access |
|------|--------|
| **student** | Take exams, view stats, training, assignments |
| **teacher** | Manage classrooms, assignments, view student performance |
| **admin** | Full platform management, user management, entities |
| **corporate** | Corporate dashboard, bulk operations |
| **mastercorporate** | Multi-entity corporate management |
| **developer** | Developer dashboard, system tools |
| **agent** | Sales agent, visible on landing page |
---
## Key Environment Variables (Cross-Service)
| Variable | Service | Purpose |
|----------|---------|---------|
| `MONGODB_URI` / `MONGODB_DB` | ielts-ui, ielts-be | Shared MongoDB |
| `BACKEND_URL` | ielts-ui | URL of ielts-be |
| `BACKEND_JWT` / `JWT_SECRET_KEY` | ielts-ui / ielts-be | Shared JWT secret for service-to-service auth |
| `FIREBASE_*` | ielts-ui, ielts-be | Shared Firebase project credentials |
| `STRAPI_URL` / `STRAPI_TOKEN` | encoach-landing-page | CMS connection |
| `STRIPE_KEY` / `STRIPE_SECRET` | ielts-ui, encoach-landing-page | Payment processing |
| `OPENAI_API_KEY` | ielts-be | AI grading and generation |
| `AWS_ACCESS_KEY_ID/SECRET` | ielts-be | AWS Polly TTS |

249
docs/DEVELOPER_FEEDBACK.md Normal file
View File

@@ -0,0 +1,249 @@
# EnCoach Odoo 19 -- Developer Feedback
**Date:** March 11, 2026
**Status:** ALL ITEMS RESOLVED (March 13, 2026)
**Reference:** ODOO_MIGRATION_SRS_v2.md
---
## Overall Assessment
The delivery covers approximately **85% of the SRS v2 requirements**. All 15 custom modules are present, the core AI/ML services are well-implemented, data models match the specification, and 67-72 API endpoints are wired up with proper JWT authentication and security groups. The code quality is solid -- clean structure, proper error handling, and good separation of concerns.
The items below still need to be implemented to reach full SRS compliance.
---
## 1. Payment Integration (Critical -- Not Implemented)
**SRS Reference:** Section 7
All three payment services are currently stubs that return `"not yet implemented"`. The SRS requires full integration with:
### 1.1 Stripe
**Files:** `encoach_subscription/services/stripe_service.py`
Required functionality:
- Install and use the `stripe` Python SDK
- `create_checkout_session()` -- Create a Stripe Checkout Session using `stripe.checkout.Session.create()` with:
- `line_items` from the selected `encoach.package`
- `success_url` and `cancel_url` from the request
- `client_reference_id` = user ID
- `customer_email` = user email
- Apply discount if `discount_code` is provided (validate against `encoach.discount`)
- Return `{ "sessionId": "cs_...", "url": "https://checkout.stripe.com/..." }`
- **Webhook endpoint** (`POST /api/stripe/webhook`):
- Verify signature using `stripe.Webhook.construct_event()` with `STRIPE_WEBHOOK_SECRET`
- Handle `checkout.session.completed` event:
- Find user by `client_reference_id`
- Extend `subscription_expiration` by the package's `duration_days`
- Create `encoach.subscription.payment` record
- For corporate users, propagate subscription to entity members
### 1.2 PayPal
**Files:** `encoach_subscription/services/paypal_service.py`
Required functionality:
- Use PayPal REST API (`httpx` or `requests`)
- Obtain access token from `PAYPAL_ACCESS_TOKEN_URL` using `client_id` + `client_secret`
- `create_order()` -- Create PayPal order via `POST /v2/checkout/orders`:
- `intent: "CAPTURE"`
- `purchase_units` with amount from package (minus discount)
- Return `{ "orderId": "...", "approvalUrl": "https://paypal.com/..." }`
- `capture_order()` -- Capture approved order via `POST /v2/checkout/orders/{id}/capture`:
- On success, extend subscription and create payment record
- Return `{ "ok": true }`
### 1.3 Paymob
**Files:** `encoach_subscription/services/paymob_service.py`
Required functionality:
- Use Paymob API (`httpx` or `requests`)
- `create_intention()` -- Create payment intention:
- Authenticate with `PAYMOB_API_KEY`
- Create order, then payment key
- Return `{ "intentionId": "...", "clientSecret": "..." }`
- `verify_transaction()` -- Verify webhook callback:
- Validate HMAC using `PAYMOB_SECRET`
- On success, extend subscription and create payment record
- **Webhook endpoint** (`POST /api/paymob/webhook`):
- Verify transaction authenticity
- Update subscription on success
### 1.4 Subscription Extension Logic
After any successful payment (all providers), the system must:
1. Calculate new expiration: `max(current_expiration, now()) + duration_days`
2. Update `user.subscription_expiration`
3. Create `encoach.subscription.payment` record with provider, amount, transaction ID
4. For corporate users: propagate the new expiration to all entity members
---
## 2. Missing API Endpoints
**SRS Reference:** Section 4
The following endpoints are specified in the SRS but not present in the delivery:
### 2.1 Exam Variants (add to `encoach_api/controllers/generation.py` or `exams.py`)
| Endpoint | Method | Description |
|----------|--------|-------------|
| `POST /api/exam/writing/<task>/attachment` | POST | Academic writing Task 1 with image upload (multipart form with `file` + `difficulty`). Must send image to GPT-4o vision API for prompt generation. |
| `GET /api/exam/level/` | GET | Return a pre-built level exam (no AI generation) |
| `GET /api/exam/level/utas` | GET | Return a UTAS-format level exam |
| `POST /api/exam/level/import/` | POST | Import level exam from uploaded file |
| `POST /api/exam/level/custom/` | POST | Generate custom level exam from JSON specification |
| `POST /api/exam/reading/import` | POST | Import reading exam from Word/Excel file |
| `POST /api/exam/listening/import` | POST | Import listening exam from file |
### 2.2 Entity/Role/Permission Management (new controller files needed)
| Endpoint | Method | Description |
|----------|--------|-------------|
| `GET /api/entities` | GET | List entities (with pagination) |
| `POST /api/entities` | POST | Create entity |
| `PATCH /api/entities/<id>` | PATCH | Update entity |
| `DELETE /api/entities/<id>` | DELETE | Delete entity |
| `GET /api/roles` | GET | List roles (filter by entityID) |
| `POST /api/roles` | POST | Create role |
| `PATCH /api/roles/<id>` | PATCH | Update role |
| `DELETE /api/roles/<id>` | DELETE | Delete role |
| `GET /api/permissions` | GET | List permissions |
### 2.3 Other Missing Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `GET /api/discounts` | GET | List discount codes |
| `POST /api/discounts` | POST | Create discount code |
| `PATCH /api/discounts/<id>` | PATCH | Update discount code |
| `DELETE /api/discounts/<id>` | DELETE | Delete discount code |
| `GET /api/approval-workflows` | GET | List approval workflows |
| `POST /api/approval-workflows` | POST | Create approval workflow |
| `PATCH /api/approval-workflows/<id>` | PATCH | Update approval workflow |
| `DELETE /api/approval-workflows/<id>` | DELETE | Delete approval workflow |
---
## 3. Evaluation Status Endpoint Path
**SRS Reference:** Section 4.2
**Current:** `GET /api/evaluate/status?sessionId=...&exerciseId=...` (query params)
**SRS specifies:** `GET /api/evaluate/<sessionId>/<exerciseId>` (path params)
The frontend SRS document (`ODOO_MIGRATION_FRONTEND_SRS.md`) references the path-param version. Please either:
- (A) Change the endpoint to use path params to match the SRS, OR
- (B) Confirm that query params are intentional so we can update the frontend SRS
---
## 4. Record-Level Security Rules (`ir.rule`)
**SRS Reference:** Section 5
The delivery has model-level ACL rules (`ir.model.access.csv`) for each module, which is good. However, record-level security rules (`ir.rule`) are also needed to ensure:
- **Students** can only read/write their own records (sessions, stats, evaluations, training, tickets)
- **Teachers** can see records for students in their groups/assignments
- **Corporate** users can see records within their entity
- **Admin/Developer** users have unrestricted access
Example rules needed (add to each module's `security/` directory):
```xml
<!-- encoach_stats/security/rules.xml -->
<record id="rule_stat_student_own" model="ir.rule">
<field name="name">Students see own stats</field>
<field name="model_id" ref="model_encoach_stat"/>
<field name="groups" eval="[(4, ref('encoach_core.group_encoach_student'))]"/>
<field name="domain_force">[('user_id', '=', user.id)]</field>
</record>
```
Models that need record rules:
- `encoach.session` -- students see own sessions only
- `encoach.stat` -- students see own stats only
- `encoach.evaluation` -- students see own evaluations only
- `encoach.training` -- students see own training only
- `encoach.ticket` -- students see own tickets, admins see all
- `encoach.assignment` -- students see assignments they're assigned to
- `encoach.exam` -- filtered by access field (public/private/entity)
---
## 5. Whisper Scaling
**SRS Reference:** Section 6.5
**Current:** Single lazy-loaded Whisper model instance in `whisper_service.py`
**SRS specifies:** 4 model instances with `ThreadPoolExecutor(max_workers=4)` for parallel transcription
Update `encoach_ai_media/services/whisper_service.py` to:
1. Load the configurable number of model instances (from `encoach.whisper_workers` system parameter, default 4)
2. Use `concurrent.futures.ThreadPoolExecutor` to process transcription requests in parallel
3. Round-robin or queue-based assignment of requests to model instances
This is important for production performance when multiple students submit speaking exams simultaneously.
---
## 6. FAISS Index Type
**SRS Reference:** Section 6.8
**Current:** `faiss.IndexFlatIP` (inner product)
**SRS specifies:** `faiss.IndexFlatL2` (L2/Euclidean distance)
The current implementation normalizes vectors and uses inner product, which effectively gives cosine similarity. This works correctly, but it's a deviation from the SRS. If the original `ielts-be` training data was built with L2 distance, the results may differ slightly. Please verify which index type the original system used and align accordingly.
---
## 7. Payment Webhook Endpoints
**SRS Reference:** Section 7
In addition to the payment service implementations (Item 1 above), the following webhook controller routes need to be added to `encoach_api/controllers/subscriptions.py`:
```python
@http.route('/api/stripe/webhook', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
def stripe_webhook(self, **kwargs):
"""Handle Stripe webhook events (checkout.session.completed, etc.)."""
...
@http.route('/api/paymob/webhook', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
def paymob_webhook(self, **kwargs):
"""Handle Paymob transaction callbacks."""
...
```
These must be `auth='public'` (no JWT) since they're called by external services.
---
## Summary of Action Items
| # | Item | Priority | Status |
|---|------|----------|--------|
| 1 | Payment integration (Stripe/PayPal/Paymob) | **Critical** | RESOLVED |
| 2 | Missing API endpoints (~20 endpoints) | **High** | RESOLVED |
| 3 | Evaluation status endpoint path alignment | **Medium** | RESOLVED |
| 4 | `ir.rule` record-level security rules | **High** | RESOLVED |
| 5 | Whisper multi-instance scaling | **Medium** | RESOLVED |
| 6 | FAISS index type verification | **Low** | RESOLVED |
| 7 | Payment webhook endpoints | **Critical** | RESOLVED |
---
## Changes Already Applied
The following small fixes have been applied directly to the codebase:
1. **`encoach_ai_media/__manifest__.py`** -- Added missing `external_dependencies`: `numpy`, `openai-whisper`, `librosa`, `soundfile`, `httpx`
2. **`encoach_training/__manifest__.py`** -- Added missing `external_dependencies`: `numpy`, `faiss-cpu`, `sentence-transformers`
3. **`requirements.txt`** -- Created at project root with all Python dependencies and versions from SRS Section 6.10

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,186 @@
# EnCoach -- Product Description
**Prepared for:** UTAS University Management
**Date:** March 24, 2026
**Version:** 1.0
**Classification:** Client-Facing
---
## 1. Executive Summary
EnCoach is an AI-powered adaptive learning platform designed to deliver personalized education across multiple academic subjects. The platform automatically assesses each student's current knowledge level, generates a tailored learning plan, delivers the right content at the right time, and continuously adjusts as the student progresses. EnCoach serves two distinct audiences -- **UTAS-enrolled students** who follow university curriculum with AI-enhanced guidance, and **freelance learners** worldwide who access fully AI-driven self-paced programs. The platform launches with three subjects -- **IELTS/English, Mathematics, and Information Technology** -- and is designed to accommodate any additional subject without rebuilding the system.
---
## 2. Product Vision
### The Problem
Traditional learning platforms deliver the same material to every student regardless of their existing knowledge. Students waste time reviewing topics they already understand, while critical gaps in their foundation go unaddressed. Teachers lack visibility into individual student needs at scale, and institutions struggle to provide personalized learning outside the classroom.
### The Solution
EnCoach combines a proven Learning Management System with an intelligent adaptive engine that treats every student as an individual. The platform:
- **Discovers what each student knows** through an AI-driven diagnostic assessment
- **Builds a personalized roadmap** that prioritizes weak areas while respecting how topics build on each other
- **Delivers the right content** -- human-curated materials when available, AI-generated explanations when not
- **Adapts in real time** -- as students learn faster or struggle, the plan adjusts automatically
- **Provides an AI coaching companion** available on every page for hints, explanations, and study advice
### Strategic Value for UTAS
| Value | Description |
|-------|-------------|
| **Scalable personalization** | Every UTAS student receives an individualized learning experience without increasing teaching staff |
| **Multi-subject from day one** | English, Math, and IT share a single platform; new subjects can be added by defining a topic structure |
| **Revenue expansion** | Freelance students outside UTAS generate subscription revenue on the same platform |
| **Data-driven insights** | Real-time analytics show administrators exactly where students succeed or struggle, per topic, per class, per department |
| **Quality assurance** | AI-generated content is supplementary -- academic staff control the primary learning materials and approve AI outputs |
---
## 3. Key Capabilities
### 3.1 Adaptive Learning Engine
The core innovation of EnCoach. When a student begins a new subject, the platform runs an intelligent diagnostic that adapts in real time -- asking harder questions when answers are correct and easier ones when they are not. Within minutes, the system maps the student's strengths and weaknesses across every topic in the subject.
From this assessment, the AI generates a **personalized learning plan**: a sequenced path through topics the student needs to study, ordered so that foundational concepts are learned before advanced ones. As the student works through the plan, short mastery quizzes confirm understanding before moving on. If a student struggles, the system provides additional resources and intensifies AI coaching. If they progress quickly, the plan accelerates.
**For UTAS students**, the learning plan aligns with the university's curriculum and semester schedule. Teachers can view and override individual plans. **For freelance students**, the AI generates the complete plan independently based on the student's goals and timeline.
### 3.2 Multi-Subject Support
EnCoach is not a single-purpose English testing tool -- it is a universal education platform. Every subject is organized into the same clear hierarchy:
- **Subject** (e.g., Mathematics)
- **Domain** (e.g., Algebra)
- **Topic** (e.g., Linear Equations)
This structure supports any academic discipline. The platform launches with:
| Subject | Coverage |
|---------|----------|
| **IELTS / English** | Reading, Listening, Writing, Speaking, Grammar, Vocabulary, Pronunciation |
| **Mathematics** | Arithmetic, Algebra, Geometry, Statistics & Probability, Calculus |
| **Information Technology** | Computer Fundamentals, Networking, Databases, Programming, Cybersecurity |
Adding a new subject (e.g., Arabic, Physics, Business) requires only defining its topic structure -- the adaptive engine, exam system, grading, and analytics apply automatically.
### 3.3 Learning Management System
A full-featured LMS for structured academic delivery:
- **Course management** -- Create courses with modules and lessons, assign instructors, set enrollment limits
- **Student enrollment** -- UTAS students enrolled automatically via SIS sync; freelance students self-enroll
- **Batches** -- Group students for cohort-based learning and shared schedules
- **Timetable** -- Schedule and display class sessions for students, teachers, and administrators
- **Attendance** -- Teachers record attendance; students view their own records; administrators monitor patterns
- **Gradebook** -- Centralized grade management with AI-generated narrative reports for academic reviews
### 3.4 Exam Engine
A powerful assessment system that goes far beyond multiple-choice:
- **AI-generated exams** -- The platform creates new exam content on demand for any subject and difficulty level. English exams include reading passages, listening scripts, writing tasks, and speaking prompts. Math exams include numerical problems, word problems, and multi-step worked problems. IT exams include code completion, scenario-based questions, and true/false items.
- **AI-powered grading** -- Writing and speaking responses are graded automatically against detailed rubrics. Math answers are checked with numerical tolerance. IT code answers are evaluated for correctness and approach. All AI grades can be reviewed and approved by teachers through an approval workflow.
- **AI writing detection** -- Every written submission is scanned for AI-generated content, providing per-sentence confidence scores.
- **Multiple delivery modes** -- Practice exams, timed official exams, scheduled assignments, diagnostic assessments, and mastery quizzes.
### 3.5 AI Assistant
An intelligent companion embedded throughout the platform:
| What It Does | Where |
|-------------|-------|
| **Answers questions** in natural language about any topic | Available on every page via a chat drawer |
| **Gives hints** during practice exercises without revealing the answer | Practice and study pages |
| **Explains grades** so students understand what to improve | After exam results |
| **Suggests what to study next** based on progress and weaknesses | Student dashboard |
| **Generates study tips** personalized to the student's current topic | Topic learning pages |
| **Helps teachers create content** -- course outlines, assignments, rubrics | Teacher course builder |
| **Produces report narratives** for academic reviews | Admin reports |
| **Flags at-risk students** based on attendance, grades, and engagement patterns | Teacher and admin dashboards |
### 3.6 Administration and Reporting
Comprehensive tools for managing the platform at every level:
- **User management** -- Create, search, filter, and export student, teacher, and corporate accounts
- **Multi-tenant organizations** -- Each institution or company operates in its own space with its own roles, permissions, and branding
- **Classroom management** -- Create student groups, transfer students between classes
- **Assignment scheduling** -- Schedule exams with start/end dates, assign to classrooms or individual students, track completion
- **Permission system** -- Granular control over who can view, create, edit, or delete content, organized by subject
- **Analytics dashboards** -- Real-time metrics on student performance, subject completion rates, AI usage, content gaps, and resource utilization
- **Support ticketing** -- Built-in helpdesk for students and staff to report issues
- **Payment management** -- Institutional licensing for UTAS, individual subscriptions for freelance students, with support for multiple payment providers
---
## 4. User Experience
### The Student Experience
A student logs in and sees their personalized dashboard: current subjects, learning plan progress, upcoming assignments, and a study streak counter. They select a subject and see their mastery profile -- a visual map showing which topics they have mastered, which they are working on, and which are locked until prerequisites are completed. Clicking a topic opens the learning page with curated materials (PDFs, videos, articles) and AI-generated explanations. After studying, a short mastery quiz confirms understanding. Throughout the experience, the AI coach is always available for hints, explanations, and encouragement. The student can also attend scheduled classes, view their timetable, check grades, and track attendance -- all from a single, unified interface.
### The Teacher Experience
A teacher logs in to see their class dashboard with insights at a glance: which students are progressing, which are at risk, and where content gaps exist. They can create courses using the AI course builder that generates outlines from a topic description. When grading, the AI Grading Assistant suggests marks and provides feedback drafts that the teacher can accept, modify, or override. Teachers can view any student's learning plan, adjust it if needed, and monitor mastery across their entire class through a heatmap visualization. Attendance recording and timetable management are integrated directly into their workflow.
### The Administrator Experience
An administrator has full visibility across the entire platform. The LMS dashboard shows enrollment numbers, completion rates, and subject-level performance across all courses. The platform dashboard provides user counts, entity statistics, and system health. Administrators manage organizations, roles, and permissions; they create exam structures, configure approval workflows, and oversee the content library. AI-powered reports generate narrative summaries for academic reviews, and the batch optimizer suggests class compositions for balanced learning outcomes.
---
## 5. How AI Powers the Platform
EnCoach integrates six specialized AI capabilities, each designed for a specific educational purpose:
| Capability | What It Does for Users |
|-----------|----------------------|
| **Intelligent Conversation** | Powers the AI Assistant, the study coach, grade explanations, writing help, and content generation. Understands context -- it knows what page you are on, what topic you are studying, and what your recent performance looks like. |
| **Speech Recognition** | Converts student voice recordings into text for speaking exam grading. Supports multiple accents and speaking styles. |
| **Text-to-Speech** | Generates natural-sounding audio for English listening exams. Supports 11 distinct voices with regional accents for authentic test preparation. |
| **AI Video Avatars** | Creates video-based speaking prompts with realistic virtual presenters, making speaking practice more engaging and exam-like. |
| **Content Authenticity** | Scans written submissions to detect AI-generated text, ensuring academic integrity with per-sentence confidence analysis. |
| **Smart Recommendations** | Finds the most relevant training tips, study materials, and content recommendations based on semantic understanding of each student's needs -- not just keyword matching. |
All AI-generated content is supplementary. Academic staff control primary learning materials, and AI outputs can be routed through approval workflows before students see them.
---
## 6. Integration with UTAS
| Integration Area | How It Works |
|-----------------|-------------|
| **Student Information System (SIS)** | Student enrollment data syncs automatically from UTAS SIS. New students appear in EnCoach without manual data entry. Student records stay synchronized throughout the semester. |
| **Curriculum Alignment** | Learning plans for UTAS students follow the university's curriculum. The topic taxonomy maps to UTAS course structures, ensuring adaptive learning enhances rather than replaces the academic program. |
| **Institutional Licensing** | UTAS operates under an institutional license covering all enrolled students and staff. No individual subscriptions needed for university members. |
| **Teacher and Admin Oversight** | UTAS teachers see their students' AI-generated learning plans and can adjust them. Administrators have full visibility into performance analytics across all departments and subjects. |
| **Branding** | The platform can display UTAS branding (logo, colors) for an institution-native experience. |
---
## 7. Platform at a Glance
| Dimension | Details |
|-----------|---------|
| **Subjects** | IELTS/English, Mathematics, Information Technology (extensible to any subject) |
| **User Roles** | Student, Teacher, Admin, Corporate, Master Corporate, Agent, Developer |
| **Student Modes** | UTAS Institutional (SIS-synced, curriculum-aligned) and Freelance (self-registered, AI-guided) |
| **AI Capabilities** | Adaptive diagnostics, personalized learning plans, content generation, automated grading, real-time coaching, writing integrity detection |
| **LMS Features** | Courses, batches, timetable, attendance, gradebook, reporting |
| **Exam Types** | Practice, official, assignment-based, diagnostic, mastery quiz |
| **Content Model** | Hybrid -- human-uploaded resources prioritized, AI-generated content fills gaps |
| **Payment Options** | Institutional license, individual subscription, bundled packages |
| **Payment Providers** | Stripe, PayPal, Paymob |
| **Security** | Server-side authorization, role-based access control, encrypted authentication, data isolation between organizations |
| **Deployment** | Cloud-hosted, containerized architecture, automated scaling |
| **Accessibility** | Responsive design (desktop and mobile), accessible form controls, screen reader support |
---
*This document describes the EnCoach platform as specified in the Unified Platform SRS (v1.0, March 2026). For detailed technical specifications, refer to ENCOACH_UNIFIED_SRS.md.*

2471
docs/ENCOACH_UNIFIED_SRS.md Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

747
docs/ODOO_BACKEND_SRS_v3.md Normal file
View File

@@ -0,0 +1,747 @@
# EnCoach Odoo 19 Backend -- Developer SRS v3
**Document Version:** 3.0
**Date:** March 11, 2026
**Status:** Active -- Ready for Development
**Supersedes:** `ODOO_MIGRATION_SRS_v2.md` (v2.0)
**Master Reference:** `ENCOACH_UNIFIED_SRS.md` (v1.0)
**Author:** EnCoach Architecture Team
---
## Purpose
This document is the **backend implementation specification** for the Odoo 19 developer. It defines every API endpoint, data model, and module the frontend expects. The frontend is **fully built and wired** -- it makes real HTTP calls to these endpoints via TanStack Query. Your job is to ensure every endpoint listed here exists, returns the correct response shape, and connects to the correct Odoo models.
**Source of truth for response shapes:** `encoach_frontend_new/src/types/*.ts` (14 files)
**Source of truth for endpoint paths:** `encoach_frontend_new/src/services/*.ts` (21 files)
---
## Table of Contents
1. [What Already Exists](#1-what-already-exists)
2. [What Needs to Be Built or Modified](#2-what-needs-to-be-built-or-modified)
3. [New Odoo Modules](#3-new-odoo-modules)
4. [Existing Module Modifications](#4-existing-module-modifications)
5. [Complete API Contract](#5-complete-api-contract)
6. [Data Model Specification](#6-data-model-specification)
7. [AI Service Integration](#7-ai-service-integration)
8. [Response Format Standards](#8-response-format-standards)
9. [Non-Functional Requirements](#9-non-functional-requirements)
10. [Implementation Priority](#10-implementation-priority)
---
## 1. What Already Exists
### 1.1 Existing Odoo Modules (15)
These modules are built and deployed in `ielts-be-v0/`:
| # | Module | Controller File | Endpoints |
|---|--------|----------------|-----------|
| 1 | `encoach_core` | -- | Users, entities, roles, permissions, codes, invites |
| 2 | `encoach_ai` | -- | OpenAI service wrapper, constants, blacklist |
| 3 | `encoach_ai_media` | `media.py` | TTS (Polly), STT (Whisper), ELAI avatars |
| 4 | `encoach_ai_generation` | `generation.py` | Exam content generation per module |
| 5 | `encoach_ai_grading` | `grading.py` | Writing/speaking AI grading |
| 6 | `encoach_exam` | `exams.py` | Exam CRUD, approval workflows |
| 7 | `encoach_assignment` | `assignments.py` | Assignment management |
| 8 | `encoach_evaluation` | `evaluations.py` | Evaluation results and AI jobs |
| 9 | `encoach_stats` | `sessions.py`, `stats.py` | Exam sessions and statistics |
| 10 | `encoach_training` | `training.py` | Training content, tips (FAISS), walkthroughs |
| 11 | `encoach_classroom` | `classrooms.py` | Classroom groups |
| 12 | `encoach_subscription` | `subscriptions.py`, `discounts.py` | Packages, payments, discounts |
| 13 | `encoach_registration` | `registration.py` | User registration, batch import |
| 14 | `encoach_ticket` | `tickets.py` | Support tickets |
| 15 | `encoach_api` | `auth.py`, `users.py`, `entities.py`, `storage.py`, `approvals.py` | REST API controllers (81+ endpoints) |
### 1.2 Existing Endpoint Count by Group
| Group | Estimated Count | Status |
|-------|----------------|--------|
| Auth (`/api/login`, `/api/logout`, etc.) | 4 | Built |
| Users (`/api/user`, `/api/users/*`) | 6 | Built |
| Entities & Roles (`/api/entities`, `/api/roles`, `/api/permissions`) | 7 | Built |
| Exams (`/api/exam/*`) | 7 | Built |
| AI Generation (`/api/exam/*/generate`) | 12 | Built |
| Media (`/api/exam/*/media`, `/api/transcribe`) | 6 | Built |
| Evaluations (`/api/evaluate/*`, `/api/grading/*`) | 6 | Built |
| Classrooms (`/api/groups`) | 3 | Built |
| Assignments (`/api/assignments`) | 8 | Built |
| Sessions & Stats (`/api/sessions`, `/api/stats`, `/api/statistical`) | 5 | Built |
| Training (`/api/training/*`) | 4 | Built |
| Subscriptions (`/api/packages`, `/api/stripe`, etc.) | 7 | Built |
| Registration (`/api/register`, `/api/code/*`) | 4 | Built |
| Tickets (`/api/tickets`) | 3 | Built |
| Storage (`/api/storage`) | 2 | Built |
| Approvals (`/api/approval-workflows`) | 3 | Built |
| **TOTAL EXISTING** | **~87** | |
---
## 2. What Needs to Be Built or Modified
### 2.1 New Endpoints Required (Frontend Expects These)
The frontend calls the following endpoints that **do not exist yet**. You must create them.
| Group | Count | Priority |
|-------|-------|----------|
| Taxonomy (subjects, domains, topics) | 14 | P0 |
| Adaptive Learning (diagnostic, proficiency, learning plans) | 16 | P0 |
| Resources (upload, manage, review) | 7 | P1 |
| AI Coaching (chat, suggest, explain, tips) | 6 | P1 |
| AI Utilities (search, insights, alerts, reports) | 5 | P2 |
| Analytics (student, class, subject, content gaps) | 4 | P2 |
| LMS Bridge (courses, batches, timetable, attendance, grades) | 13 | P1 |
| **TOTAL NEW** | **~65** | |
### 2.2 Existing Modules Requiring Modification
| Module | What to Change |
|--------|---------------|
| `encoach_exam` | Add `subject_id` (Many2one to `encoach.subject`) and `topic_ids` (Many2many to `encoach.topic`) fields to `encoach.exam` model |
| `encoach_stats` | Add `topic_id` and `subject_id` fields to `encoach.stat` model |
| `encoach_training` | Add `subject_id` field to `encoach.training.tip` for per-subject FAISS indices |
| `encoach_ai_generation` | Extend prompts to support Math (include LaTeX/KaTeX formatting) and IT (code blocks, syntax) question types |
| `encoach_ai_grading` | Add grading logic for numerical-tolerance (Math) and keyword/pattern (IT) answers |
| `encoach_subscription` | Add `subjects` field to `encoach.package` for subject-scoped subscriptions |
| `encoach_api` | Add new controller files for all new endpoint groups |
---
## 3. New Odoo Modules
Create these 8 new modules:
### 3.1 `encoach_taxonomy`
**Purpose:** Subject/domain/topic/learning-objective hierarchy.
**Models:**
| Model | Key Fields |
|-------|-----------|
| `encoach.subject` | `name` (Char), `code` (Char unique), `is_active` (Boolean), `diagnostic_config` (Text/JSON), `mastery_threshold` (Float default=80), `grading_scale` (Selection: percentage/band/letter), `grading_scale_config` (Text/JSON) |
| `encoach.domain` | `name` (Char), `code` (Char), `subject_id` (M2O encoach.subject), `sequence` (Integer) |
| `encoach.topic` | `name` (Char), `code` (Char), `domain_id` (M2O encoach.domain), `estimated_hours` (Float), `difficulty_level` (Selection: easy/medium/hard), `prerequisite_ids` (M2M self-ref), `question_type_weights` (Text/JSON) |
| `encoach.learning.objective` | `name` (Char), `topic_id` (M2O encoach.topic), `bloom_level` (Selection: remember/understand/apply/analyze/evaluate/create), `sequence` (Integer) |
**Computed fields on `encoach.subject`:** `domain_count`, `topic_count`
**Computed fields on `encoach.domain`:** `topic_count`
**Computed fields on `encoach.topic`:** `objective_count`, `prerequisite_names` (list of names)
### 3.2 `encoach_resources`
**Purpose:** Human-uploaded learning materials tagged to topics.
**Models:**
| Model | Key Fields |
|-------|-----------|
| `encoach.resource` | `name` (Char), `resource_type` (Selection: pdf/video/link/document/interactive), `url` (Char), `file` (Binary), `file_name` (Char), `topic_ids` (M2M encoach.topic), `author_id` (M2O res.users), `is_published` (Boolean), `review_status` (Selection: pending/approved/rejected) |
| `encoach.resource.completion` | `student_id` (M2O res.users), `resource_id` (M2O encoach.resource), `viewed` (Boolean), `time_spent_minutes` (Integer), `rating` (Integer 1-5) |
### 3.3 `encoach_adaptive`
**Purpose:** Core adaptive learning engine -- proficiency tracking, learning plans, content cache.
**Models:**
| Model | Key Fields |
|-------|-----------|
| `encoach.proficiency` | `student_id` (M2O res.users), `topic_id` (M2O encoach.topic), `mastery` (Float 0-100), `mastery_level` (Selection: not_started/beginner/developing/proficient/mastered -- computed from mastery), `last_assessed` (Datetime), `time_spent_minutes` (Integer) |
| `encoach.learning.plan` | `student_id` (M2O res.users), `subject_id` (M2O encoach.subject), `status` (Selection: active/paused/completed), `ai_summary` (Text), `overall_progress` (Float -- computed), `target_completion` (Date) |
| `encoach.learning.plan.item` | `plan_id` (M2O encoach.learning.plan), `topic_id` (M2O encoach.topic), `sequence` (Integer), `status` (Selection: locked/available/in_progress/completed), `estimated_hours` (Float), `actual_hours` (Float), `mastery` (Float -- from proficiency) |
| `encoach.ai.content.cache` | `topic_id` (M2O encoach.topic), `content_type` (Char), `difficulty_level` (Char), `content` (Text/JSON), `model_used` (Char), `review_status` (Selection: auto/reviewed/rejected) |
**Business logic:**
- `mastery_level` is computed: 0-19 = not_started, 20-39 = beginner, 40-59 = developing, 60-79 = proficient, 80-100 = mastered
- `overall_progress` is computed from item statuses (completed_count / total_count * 100)
- When a plan item is completed, unlock the next item(s) based on prerequisite graph
### 3.4 `encoach_adaptive_api`
**Purpose:** REST controllers for the adaptive learning engine.
**Controller files to create:**
- `taxonomy.py` -- `/api/subjects`, `/api/domains`, `/api/topics`, `/api/subjects/{id}/taxonomy`
- `resources.py` -- `/api/resources`
- `diagnostic.py` -- `/api/diagnostic/start`, `/api/diagnostic/answer`, `/api/diagnostic/{id}/result`
- `proficiency.py` -- `/api/proficiency`, `/api/proficiency/summary`, `/api/proficiency/class`
- `learning_plan.py` -- `/api/learning-plan`, `/api/learning-plan/generate`, etc.
- `content.py` -- `/api/topics/{id}/content`, `/api/topics/{id}/practice`, `/api/topics/{id}/mastery-quiz`
### 3.5 `encoach_adaptive_ai`
**Purpose:** AI logic for diagnostics, plan generation, content generation, coaching.
**Key services:**
- Diagnostic question selection (adaptive difficulty algorithm)
- Learning plan generation (topological sort of topics by prerequisites, weighted by proficiency gaps)
- AI content generation for topics (call OpenAI GPT-4o with topic context)
- Practice question generation per topic
- Mastery quiz generation and grading
- Coaching: chat, hints, explanations, study suggestions, writing help, contextual tips
### 3.6 `encoach_lms_api`
**Purpose:** REST API bridge exposing OpenEduCat models to the frontend.
**Controller files to create:**
- `courses.py` -- `/api/courses`, `/api/courses/{id}`, `/api/courses/ai-generate`
- `batches.py` -- `/api/batches`, `/api/batches/{id}`
- `timetable.py` -- `/api/timetable`
- `attendance.py` -- `/api/attendance`
- `grades.py` -- `/api/grades`
**Note:** These controllers wrap the existing OpenEduCat Odoo models (`op.course`, `op.batch`, `op.session`, `op.attendance.sheet`, etc.) behind a clean REST API. Do NOT duplicate the models -- use the OpenEduCat models directly.
### 3.7 `encoach_sis`
**Purpose:** UTAS Student Information System integration.
**Models:**
- `encoach.sis.sync` -- sync job tracking (status, last_run, next_run, error_log)
- `encoach.sis.mapping` -- field mapping between SIS fields and EnCoach fields
### 3.8 `encoach_branding`
**Purpose:** Tenant whitelabeling.
**Models:**
- `encoach.branding` -- `entity_id` (M2O encoach.entity), `logo` (Binary), `primary_color` (Char), `secondary_color` (Char), `font_family` (Char)
---
## 4. Existing Module Modifications
### 4.1 `encoach_exam` -- Add Subject/Topic Fields
```python
# In encoach_exam/models/exam.py, add:
subject_id = fields.Many2one('encoach.subject', string='Subject')
topic_ids = fields.Many2many('encoach.topic', string='Topics')
is_diagnostic = fields.Boolean(string='Is Diagnostic Exam', default=False)
```
### 4.2 `encoach_stats` -- Add Subject/Topic Fields
```python
# In encoach_stats/models/stat.py, add:
subject_id = fields.Many2one('encoach.subject', string='Subject')
topic_id = fields.Many2one('encoach.topic', string='Topic')
```
### 4.3 `encoach_training` -- Add Subject Field
```python
# In encoach_training/models/training_tip.py, add:
subject_id = fields.Many2one('encoach.subject', string='Subject')
```
### 4.4 `encoach_subscription` -- Add Subject Scoping
```python
# In encoach_subscription/models/package.py, add:
subject_ids = fields.Many2many('encoach.subject', string='Included Subjects')
```
### 4.5 `encoach_ai_generation` -- Multi-Subject Prompts
Extend the generation prompts to handle:
- **Math:** Include LaTeX formatting instructions in prompts, numerical-tolerance answer checking
- **IT:** Include code block formatting, syntax highlighting hints, code-completion question types
- **Generic:** Accept `subject_id` and `topic_id` parameters, adjust prompt templates per subject
### 4.6 `encoach_ai_grading` -- Multi-Subject Grading
Extend grading logic:
- **IELTS:** Band scoring (existing)
- **Math:** Numerical tolerance (accept answers within +/- epsilon), step-by-step partial credit
- **IT:** Keyword matching, regex pattern matching, AI-graded code explanations
---
## 5. Complete API Contract
This is the definitive list of every endpoint the frontend calls. Each entry shows the HTTP method, path, request body (if POST/PATCH), and expected response shape. **The TypeScript type files in `encoach_frontend_new/src/types/` are the canonical response shapes.**
### 5.1 Authentication (Existing -- `auth.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/login` | `{ login: string, password: string }` | `{ token: string, user: User }` |
| `POST` | `/api/logout` | -- | `void` |
| `GET` | `/api/user` | -- | `User` |
| `POST` | `/api/reset/sendVerification` | `{ email: string }` | `{ success: boolean }` |
**User shape:** See `src/types/auth.ts` -- must include: `id`, `name`, `email`, `login`, `user_type` (one of: student/teacher/admin/corporate/mastercorporate/agent/developer), `is_verified`, `entities` (array of {id, name, role}), `classrooms`.
### 5.2 Users (Existing -- `users.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `GET` | `/api/users/list` | Query: `type`, `entity_id`, `page`, `size`, `search`, `sort`, `order` | `PaginatedResponse<User>` |
| `GET` | `/api/users/{id}` | -- | `User` |
| `PATCH` | `/api/users/update` | `{ id, ...fields }` | `User` |
| `POST` | `/api/users/create` | `Partial<User>` | `User` |
| `POST` | `/api/batch_users` | `{ users: Partial<User>[] }` | `{ success: boolean }` |
**PaginatedResponse shape:** `{ items: T[], total: number, page: number, size: number, pages: number }`
### 5.3 Entities (Existing -- `entities.service.ts`)
| Method | Path | Response |
|--------|------|----------|
| `GET` | `/api/entities` | `PaginatedResponse<Entity>` |
| `GET` | `/api/entities/{id}` | `Entity` |
| `POST` | `/api/entities` | `Entity` |
| `PATCH` | `/api/entities/{id}` | `Entity` |
| `DELETE` | `/api/entities/{id}` | `{ success: boolean }` |
| `GET` | `/api/entities/{id}/roles` | `EntityRole[]` |
| `POST` | `/api/entities/{id}/roles` | `EntityRole` |
| `PATCH` | `/api/roles/{id}/permissions` | `EntityRole` |
| `GET` | `/api/permissions?entity_id=` | `string[]` (list of permission keys for current user) |
### 5.4 Exams (Existing -- `exams.service.ts`)
| Method | Path | Response |
|--------|------|----------|
| `GET` | `/api/exam/{module}` | `PaginatedResponse<Exam>` |
| `GET` | `/api/exam/{module}/{id}` | `Exam` |
| `POST` | `/api/exam` | `Exam` |
| `PATCH` | `/api/exam/{id}` | `Exam` |
| `DELETE` | `/api/exam/{id}` | `{ success: boolean }` |
| `PATCH` | `/api/exam/{id}/access` | `Exam` |
| `GET` | `/api/rubrics` | `PaginatedResponse<Rubric>` |
| `POST` | `/api/rubrics` | `Rubric` |
| `GET` | `/api/rubric-groups` | `PaginatedResponse<RubricGroup>` |
| `GET` | `/api/exam-structures` | `PaginatedResponse<ExamStructure>` |
| `POST` | `/api/exam-structures` | `ExamStructure` |
| `DELETE` | `/api/exam-structures/{id}` | `{ success: boolean }` |
| `GET` | `/api/exam/avatars` | `[{ id, name, thumbnail, voice }]` |
**Note:** `Exam` response must now include optional `subject_id` and `topic_ids` fields.
### 5.5 Assignments (Existing -- `assignments.service.ts`)
| Method | Path | Response |
|--------|------|----------|
| `GET` | `/api/assignments` | `PaginatedResponse<Assignment>` |
| `GET` | `/api/assignments/{id}` | `Assignment` |
| `POST` | `/api/assignments` | `Assignment` |
| `PATCH` | `/api/assignments/{id}` | `Assignment` |
| `DELETE` | `/api/assignments/{id}` | `{ success: boolean }` |
| `POST` | `/api/assignments/{id}/archive` | `Assignment` |
| `POST` | `/api/assignments/{id}/start` | `Assignment` |
### 5.6 Classrooms (Existing -- `classrooms.service.ts`)
| Method | Path | Response |
|--------|------|----------|
| `GET` | `/api/groups` | `PaginatedResponse<Classroom>` |
| `GET` | `/api/groups/{id}` | `Classroom` |
| `POST` | `/api/groups` | `Classroom` |
| `DELETE` | `/api/groups/{id}` | `{ success: boolean }` |
| `POST` | `/api/groups/transfer` | `{ success: boolean }` |
| `POST` | `/api/groups/{id}/members` | `{ success: boolean }` |
| `POST` | `/api/groups/{id}/members/remove` | `{ success: boolean }` |
### 5.7 Stats (Existing -- `stats.service.ts`)
| Method | Path | Response |
|--------|------|----------|
| `GET` | `/api/sessions` | `ExamSession[]` |
| `GET` | `/api/stats` | `ExamStat[]` |
| `GET` | `/api/statistical` | `StatisticalData` |
| `GET` | `/api/stats/performance` | `unknown[]` |
### 5.8 Evaluations (Existing -- `evaluations.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/evaluate/writing` | `{ session_id, text, rubric_id? }` | `Evaluation` |
| `POST` | `/api/evaluate/speaking` | `{ session_id, audio_url, rubric_id? }` | `Evaluation` |
| `POST` | `/api/grading/multiple` | `{ session_id, answers: [{exercise_index, answer}] }` | `{ results: [{exercise_index, correct, score}] }` |
| `POST` | `/api/transcribe` | `FormData (audio file)` | `{ text: string }` |
### 5.9 Generation (Existing -- `generation.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/exam/{module}/generate` | `{ title, label?, entity_id?, subject_id?, topic_id?, difficulty?, count? }` | `{ exam_id, exercises: [] }` |
| `POST` | `/api/exam/{module}/generate/scratch` | Same as above | Same as above |
**Note:** Must now accept `subject_id` and `topic_id` to scope generation to specific subjects/topics.
### 5.10 Training, Subscriptions, Tickets, Storage, Approvals (Existing)
These follow the existing patterns. See `training.service.ts`, `subscriptions.service.ts`, `tickets.service.ts`, `storage.service.ts`, `approvals.service.ts` for exact paths.
---
### 5.11 Taxonomy (NEW -- `taxonomy.service.ts`)
| Method | Path | Request/Params | Response |
|--------|------|---------------|----------|
| `GET` | `/api/subjects` | -- | `Subject[]` |
| `GET` | `/api/subjects/{id}` | -- | `Subject` |
| `POST` | `/api/subjects` | `Partial<Subject>` | `Subject` |
| `PATCH` | `/api/subjects/{id}` | `Partial<Subject>` | `Subject` |
| `DELETE` | `/api/subjects/{id}` | -- | `{ success: boolean }` |
| `GET` | `/api/subjects/{id}/taxonomy` | -- | `TaxonomyTree` (nested: subject + domains + topics + objectives) |
| `POST` | `/api/subjects/{id}/taxonomy/import` | `FormData (CSV/JSON)` | `{ success: boolean }` |
| `GET` | `/api/domains` | Query: `subject_id?` | `Domain[]` |
| `POST` | `/api/domains` | `Partial<Domain>` | `Domain` |
| `PATCH` | `/api/domains/{id}` | `Partial<Domain>` | `Domain` |
| `DELETE` | `/api/domains/{id}` | -- | `{ success: boolean }` |
| `POST` | `/api/domains/{id}/ai-suggest` | -- | `{ suggestions: Partial<Topic>[] }` |
| `GET` | `/api/topics` | Query: `domain_id?`, `subject_id?` | `Topic[]` |
| `POST` | `/api/topics` | `Partial<Topic>` | `Topic` |
| `PATCH` | `/api/topics/{id}` | `Partial<Topic>` | `Topic` |
| `DELETE` | `/api/topics/{id}` | -- | `{ success: boolean }` |
**TaxonomyTree shape:**
```json
{
"subject": { "id": 1, "name": "IELTS", "code": "IELTS", ... },
"domains": [
{
"id": 1, "name": "Writing", "code": "W", "sequence": 1,
"topics": [
{
"id": 1, "name": "Task 1", "difficulty_level": "medium",
"objectives": [
{ "id": 1, "name": "Describe trends", "bloom_level": "apply" }
]
}
]
}
]
}
```
### 5.12 Resources (NEW -- `resources.service.ts`)
| Method | Path | Request/Params | Response |
|--------|------|---------------|----------|
| `GET` | `/api/resources` | Query: `topic_id?`, `resource_type?`, `review_status?`, `page`, `size`, `search` | `PaginatedResponse<Resource>` |
| `POST` | `/api/resources` | `FormData` (file + metadata) | `Resource` |
| `PATCH` | `/api/resources/{id}` | `Partial<Resource>` | `Resource` |
| `DELETE` | `/api/resources/{id}` | -- | `{ success: boolean }` |
| `POST` | `/api/resources/{id}/complete` | -- | `ResourceCompletion` |
| `POST` | `/api/resources/{id}/rate` | `{ rating: number }` | `{ success: boolean }` |
| `GET` | `/api/resources/{id}/download` | -- | Binary file (stream) |
### 5.13 Diagnostic Assessment (NEW -- `adaptive.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/diagnostic/start` | `{ subject_id: number }` | `{ session: DiagnosticSession, first_question: DiagnosticQuestion }` |
| `POST` | `/api/diagnostic/answer` | `{ session_id, question_id, answer }` | `{ next_question?: DiagnosticQuestion, completed: boolean }` |
| `GET` | `/api/diagnostic/{id}/result` | -- | `DiagnosticResult` |
**DiagnosticQuestion shape:**
```json
{
"id": "q_uuid",
"topic_id": 5,
"topic_name": "Line Graphs",
"domain_name": "Writing",
"difficulty": "medium",
"question_type": "multiple_choice",
"question_text": "Which of the following...",
"options": ["A", "B", "C", "D"],
"time_limit_seconds": 120
}
```
**Diagnostic algorithm:**
1. On `/start`: Create a diagnostic session. Pull topics from all domains. Start with `starting_difficulty` from subject's `diagnostic_config`.
2. On `/answer`: Grade the answer. If correct, increase difficulty and mastery estimate for that topic. If incorrect, decrease. Select the next question from a different domain/topic. Use Computer Adaptive Testing (CAT) principles.
3. Continue until `total_question_cap` reached or all domains have 2+ data points.
4. On completion: Write proficiency records for all assessed topics.
### 5.14 Proficiency (NEW -- `adaptive.service.ts`)
| Method | Path | Params | Response |
|--------|------|--------|----------|
| `GET` | `/api/proficiency` | Query: `subject_id?` | `Proficiency[]` |
| `GET` | `/api/proficiency/summary` | -- | `ProficiencySummary[]` |
| `GET` | `/api/proficiency/class` | Query: `subject_id?` | Class-level aggregation |
**ProficiencySummary shape:**
```json
{
"subject_id": 1,
"subject_name": "IELTS",
"overall_mastery": 65.5,
"domain_scores": [{ "domain_id": 1, "domain_name": "Writing", "mastery": 72 }],
"topics_mastered": 8,
"topics_total": 20
}
```
### 5.15 Learning Plan (NEW -- `adaptive.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `GET` | `/api/learning-plan` | Query: `subject_id` | `LearningPlan` |
| `POST` | `/api/learning-plan/generate` | `{ subject_id, target_completion? }` | `LearningPlan` |
| `PATCH` | `/api/learning-plan/{id}` | `Partial<LearningPlan>` | `LearningPlan` |
| `POST` | `/api/learning-plan/{id}/pause` | -- | `LearningPlan` |
| `POST` | `/api/learning-plan/{id}/resume` | -- | `LearningPlan` |
**Plan generation algorithm:**
1. Get student's proficiency records for the subject.
2. Identify topics below mastery threshold.
3. Topologically sort topics by prerequisites.
4. Create plan items in sequence. First item = available, rest = locked.
5. Call GPT-4o to generate `ai_summary` (natural language description of the plan).
6. Set `estimated_hours` from topic definitions.
### 5.16 Content Delivery (NEW -- `adaptive.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `GET` | `/api/topics/{id}/content` | -- | `TopicContent` |
| `POST` | `/api/topics/{id}/generate-content` | -- | `TopicContent` |
| `POST` | `/api/topics/{id}/practice` | -- | `{ questions: [] }` |
| `POST` | `/api/topics/{id}/practice/grade` | `{ answers: [] }` | `{ results: [], mastery_update: number }` |
| `POST` | `/api/topics/{id}/mastery-quiz` | -- | `{ questions: [] }` |
| `POST` | `/api/topics/{id}/mastery-quiz/submit` | `{ answers: [] }` | `{ passed: boolean, score: number, mastery_update: number }` |
**TopicContent shape:**
```json
{
"topic_id": 5,
"topic_name": "Line Graphs",
"resources": [{ "id": 1, "name": "...", "resource_type": "pdf", "url": "..." }],
"ai_content": {
"explanation": "Line graphs show...",
"examples": ["Example 1...", "Example 2..."],
"key_points": ["Point 1", "Point 2"],
"model_used": "gpt-4o"
},
"has_content_gap": true
}
```
**`has_content_gap`** = true when no human-uploaded resources exist for this topic, and AI content was generated to fill the gap.
### 5.17 AI Coaching (NEW -- `coaching.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/coach/chat` | `{ message, context?: { page?, topic_id?, subject_id? }, history?: AiChatMessage[] }` | `{ message: string, suggestions?: string[] }` |
| `POST` | `/api/coach/hint` | `{ topic_id, question_id }` | `{ hint: string }` |
| `POST` | `/api/coach/explain` | `{ context, scores? }` | `{ explanation: string }` |
| `POST` | `/api/coach/suggest` | `{ subject_id? }` | `{ suggestions: string[], study_plan_tips: string[] }` |
| `POST` | `/api/coach/writing-help` | `{ text, task_type }` | `{ feedback, improved, grammar_notes: string[] }` |
| `GET` | `/api/coach/tip` | Query: `context` | `{ title, content, category }` |
All coaching endpoints use GPT-4o with appropriate system prompts.
### 5.18 AI Utilities (NEW -- `analytics.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `POST` | `/api/ai/search` | `{ query }` | `AiSearchResult[]` |
| `POST` | `/api/ai/insights` | `{ data: {} }` | `AiInsight[]` |
| `GET` | `/api/ai/alerts` | -- | `AiAlert[]` |
| `POST` | `/api/ai/report-narrative` | `{ report_type, data: {} }` | `{ narrative: string }` |
| `POST` | `/api/ai/batch-optimize` | `{ batch_id }` | `AiBatchOptimization[]` |
| `POST` | `/api/ai/grade-suggest` | `{ submission_id, text, rubric_id? }` | `AiGradingResult` |
### 5.19 Analytics (NEW -- `analytics.service.ts`)
| Method | Path | Params | Response |
|--------|------|--------|----------|
| `GET` | `/api/analytics/student` | Query params | Dashboard data |
| `GET` | `/api/analytics/class` | Query params | Class analytics |
| `GET` | `/api/analytics/subject` | Query params | Subject analytics |
| `GET` | `/api/analytics/content-gaps` | Query: `subject_id?` | `{ gaps: [{ topic_id, topic_name, resource_count }] }` |
### 5.20 LMS Bridge (NEW -- `lms.service.ts`)
| Method | Path | Request | Response |
|--------|------|---------|----------|
| `GET` | `/api/courses` | Query: `page`, `size`, `search`, `status` | `PaginatedResponse<Course>` |
| `GET` | `/api/courses/{id}` | -- | `Course` |
| `POST` | `/api/courses` | `CourseCreateRequest` | `Course` |
| `PATCH` | `/api/courses/{id}` | `Partial<CourseCreateRequest>` | `Course` |
| `DELETE` | `/api/courses/{id}` | -- | `{ success: boolean }` |
| `POST` | `/api/courses/ai-generate` | `{ title, subject_id?, level? }` | `{ outline: {} }` |
| `GET` | `/api/batches` | Query: pagination | `PaginatedResponse<Batch>` |
| `GET` | `/api/batches/{id}` | -- | `Batch` |
| `POST` | `/api/batches` | `Partial<Batch>` | `Batch` |
| `PATCH` | `/api/batches/{id}` | `Partial<Batch>` | `Batch` |
| `DELETE` | `/api/batches/{id}` | -- | `{ success: boolean }` |
| `GET` | `/api/timetable` | Query: `course_id?`, `teacher_id?`, `batch_id?` | `TimetableSession[]` |
| `POST` | `/api/timetable` | `Partial<TimetableSession>` | `TimetableSession` |
| `GET` | `/api/attendance` | Query: `course_id?`, `student_id?`, `date?` | `AttendanceRecord[]` |
| `POST` | `/api/attendance` | `{ course_id, date, records: [{student_id, status}] }` | `{ success: boolean }` |
| `GET` | `/api/grades` | Query: `course_id?`, `student_id?` | `GradeRecord[]` |
**Course shape:** See `src/types/lms.ts` -- must include: `id`, `title`, `code`, `subject_id?`, `subject_name?`, `instructor_id`, `instructor_name`, `description`, `level`, `modules[]`, `enrolled`, `max_capacity`, `status`, `start_date`, `end_date`, `progress?`.
---
## 6. Data Model Specification
All data model details are in **Section 30 of `ENCOACH_UNIFIED_SRS.md`** (existing models: 30.1, new models: 30.2-30.4). Refer to that document for the complete field-level specification.
**Key relationships:**
```
Subject (1) → (N) Domain (1) → (N) Topic (1) → (N) LearningObjective
Topic (M) ↔ (M) Topic (prerequisites -- self-referencing M2M)
Topic (M) ↔ (M) Resource
Student (1) → (N) Proficiency (per topic)
Student (1) → (N) LearningPlan (per subject) → (N) LearningPlanItem (per topic)
Exam → Subject (optional M2O)
Exam → Topic[] (optional M2M)
```
---
## 7. AI Service Integration
The following external AI services are already configured (API keys in `encoach_core/data/constants.xml` and server `.env`):
| Service | Purpose | Config Key |
|---------|---------|-----------|
| OpenAI GPT-4o | Content generation, grading, coaching, plan generation | `encoach.openai_api_key` |
| OpenAI GPT-3.5-turbo | Lightweight tasks (tips, search, suggestions) | Same key |
| OpenAI Whisper (local) | Speech-to-text | Local model |
| AWS Polly (Neural) | Text-to-speech for listening exams | `encoach.aws_access_key_id`, `encoach.aws_secret_access_key` |
| ELAI | AI avatar video generation | `encoach.elai_api_key` |
| GPTZero | AI writing detection | `encoach.gptzero_api_key` |
| FAISS + SentenceTransformers | Semantic similarity for training tips | Local model (`all-MiniLM-L6-v2`) |
**New AI tasks to implement:**
| Task | Model | Endpoint |
|------|-------|----------|
| Diagnostic question generation | GPT-4o | `/api/diagnostic/start`, `/answer` |
| Learning plan generation | GPT-4o | `/api/learning-plan/generate` |
| Topic content generation | GPT-4o | `/api/topics/{id}/generate-content` |
| Practice question generation | GPT-4o | `/api/topics/{id}/practice` |
| Mastery quiz generation | GPT-4o | `/api/topics/{id}/mastery-quiz` |
| AI coaching chat | GPT-4o | `/api/coach/chat` |
| Study suggestions | GPT-3.5-turbo | `/api/coach/suggest` |
| Writing feedback | GPT-4o | `/api/coach/writing-help` |
| Grade explanation | GPT-4o | `/api/coach/explain` |
| Contextual tips | GPT-3.5-turbo | `/api/coach/tip` |
| Semantic search | FAISS | `/api/ai/search` |
| Report narrative | GPT-4o | `/api/ai/report-narrative` |
| Data insights | GPT-4o | `/api/ai/insights` |
| Topic suggestion | GPT-4o | `/api/domains/{id}/ai-suggest` |
| Course outline generation | GPT-4o | `/api/courses/ai-generate` |
| Batch optimization | GPT-3.5-turbo | `/api/ai/batch-optimize` |
---
## 8. Response Format Standards
### 8.1 Paginated Responses
All list endpoints that support pagination must return:
```json
{
"items": [...],
"total": 150,
"page": 1,
"size": 20,
"pages": 8
}
```
Query parameters: `page` (1-based), `size` (default 20), `search` (text filter), `sort` (field name), `order` (asc/desc).
### 8.2 Error Responses
```json
{
"error": "Human-readable error message",
"code": "ERROR_CODE",
"details": {}
}
```
HTTP status codes: 400 (validation), 401 (unauthorized), 403 (forbidden), 404 (not found), 500 (server error).
### 8.3 Success Responses
For write operations that don't return an entity:
```json
{
"success": true,
"message": "Optional message"
}
```
### 8.4 JWT Token
- Token returned on login as `{ token: "...", user: {...} }`
- Frontend sends `Authorization: Bearer <token>` on every request
- 401 response = token expired, frontend redirects to login
---
## 9. Non-Functional Requirements
| Requirement | Specification |
|-------------|--------------|
| API response time (CRUD) | < 2 seconds |
| Diagnostic question generation | < 3 seconds |
| AI grading (writing/speaking) | < 60 seconds |
| Learning plan generation | < 10 seconds |
| AI content generation | < 15 seconds |
| Concurrent students per subject | 200 |
| Topics per subject | 500 |
| Resources per subject | 1,000 |
| Pagination on all list endpoints | Required |
| Server-side search/filter | Required |
| Soft delete for resources | Required (preserve completion records) |
| Proficiency weighted averages | Required (never direct overwrite) |
| Math content | LaTeX/KaTeX formatting in question text |
| IT content | Code blocks with language hints in question text |
---
## 10. Implementation Priority
| Phase | Modules | Endpoints | Estimated Effort |
|-------|---------|-----------|-----------------|
| **P0** | `encoach_taxonomy`, modify `encoach_exam`/`encoach_stats`/`encoach_training` | Taxonomy CRUD (14), Subject/Topic fields on existing models | 1 week |
| **P1** | `encoach_adaptive`, `encoach_adaptive_api`, `encoach_adaptive_ai` | Diagnostic (3), Proficiency (3), Learning Plan (5), Content (6) | 2 weeks |
| **P1** | `encoach_resources` | Resource CRUD (7) | 3 days |
| **P1** | `encoach_lms_api` | LMS bridge (13) | 1 week |
| **P2** | `encoach_adaptive_ai` (coaching) | AI Coaching (6), AI Utilities (5) | 1 week |
| **P2** | Analytics controllers | Analytics (4) | 3 days |
| **P3** | `encoach_sis`, `encoach_branding` | SIS (4), Branding | 1 week |
| **P3** | Multi-subject prompts/grading | Modify generation & grading modules | 3 days |
| **TOTAL** | 8 new modules + 7 modified | ~65 new endpoints | ~7 weeks |
---
## Appendix: File Handoff Checklist
| File/Folder | Purpose | Location |
|-------------|---------|----------|
| This document | Backend SRS | `ODOO_BACKEND_SRS_v3.md` |
| Product SRS | Full platform specification | `ENCOACH_UNIFIED_SRS.md` |
| TypeScript types | Response shape contracts | `encoach_frontend_new/src/types/*.ts` |
| Service layer | Endpoint path contracts | `encoach_frontend_new/src/services/*.ts` |
| Existing modules | Already-built backend | `ielts-be-v0/` |
| Developer feedback | Review of existing work | `ielts-be-v0/DEVELOPER_FEEDBACK.md` |
| AI keys & config | Service credentials | `ielts-be-v0/encoach_core/data/constants.xml` |
---
*This document supersedes `ODOO_MIGRATION_SRS_v2.md`. The Odoo developer should treat this as the definitive backend specification. All endpoint paths, response shapes, and data models are aligned with the production frontend at `encoach_frontend_new/`.*

File diff suppressed because it is too large Load Diff

727
docs/UTAS_MASTER_PLAN.md Normal file
View File

@@ -0,0 +1,727 @@
# EnCoach -- UTAS University Deployment Master Plan
**Document Version:** 1.0
**Date:** March 16, 2026
**Classification:** Confidential -- EnCoach & UTAS Internal
**Prepared by:** EnCoach Engineering Team
---
## Table of Contents
1. [Executive Summary](#1-executive-summary)
2. [Project Scope and Objectives](#2-project-scope-and-objectives)
3. [System Architecture](#3-system-architecture)
4. [Feature Modules Breakdown](#4-feature-modules-breakdown)
5. [Development Phases](#5-development-phases)
6. [University Integration Plan](#6-university-integration-plan)
7. [Master Timeline](#7-master-timeline)
8. [Testing and Rollout Strategy](#8-testing-and-rollout-strategy)
9. [Team and Responsibilities](#9-team-and-responsibilities)
10. [Risk Register](#10-risk-register)
11. [Assumptions and Prerequisites](#11-assumptions-and-prerequisites)
---
## 1. Executive Summary
EnCoach is deploying a comprehensive AI-powered education platform for the University of Technology and Applied Sciences (UTAS). The platform delivers nine integrated modules spanning self-paced English learning, AI-graded examinations, Mathematics and IT courses with AI-assisted assessment, a full Learning Management System, university SIS integration, institutional whitelabeling, AI virtual tutors, and a support ticketing system.
### Platform at a Glance
| Dimension | Detail |
|-----------|--------|
| **Modules** | 9 (English Self Learning, Examinations, Math, IT, LMS, Whitelabeling, Humanisation, SIS Integration, Ticketing) |
| **AI Services** | 6 (OpenAI GPT-4o, Whisper STT, AWS Polly TTS, ELAI Avatars, GPTZero Detection, FAISS Semantic Search) |
| **Backend** | Odoo 19 -- 15 custom modules, 70+ REST API endpoints, PostgreSQL |
| **Frontend** | React 18 SPA -- 55+ pages, TypeScript, Tailwind CSS, shadcn/ui |
| **LMS Engine** | OpenEduCat (Odoo-native modules) |
| **Team** | 1 Solution Architect, 1 Senior Developer (AI-assisted), 1 Full-Stack Developer (AI-assisted) |
### Key Milestones
| Milestone | Target Date |
|-----------|-------------|
| Project Kickoff | April 1, 2026 |
| Staging Demo to UTAS | April 24, 2026 |
| English Self Learning + Examinations -- GO LIVE | June 12, 2026 |
| Math + IT + LMS + Ticketing -- GO LIVE | July 24, 2026 |
| Full Platform GO LIVE (SIS, Whitelabeling, Humanisation) | August 21, 2026 |
### Current State of Development
The platform is not starting from zero. Significant engineering has already been completed:
- **Backend (Odoo 19):** 15 custom modules fully developed, covering exams, AI grading, content generation, media services, training, assignments, classrooms, subscriptions, registration, and ticketing. All AI services (OpenAI, Whisper, Polly, ELAI, GPTZero, FAISS) are integrated and configured. The backend is deployed and running on a staging server.
- **Frontend (React):** A complete UI prototype with 55+ pages across student, teacher, and admin portals. Role-based routing, layouts, and forms are built. Currently using mock data -- API integration is the primary remaining work.
- **Infrastructure:** Docker Compose deployment with PostgreSQL, staging environment operational at the current staging server.
---
## 2. Project Scope and Objectives
### 2.1 Objectives
1. **Deliver a production-ready AI-powered education platform** for UTAS covering English, Mathematics, and IT subjects.
2. **Integrate with UTAS's existing Student Information System (SIS)** for seamless student enrollment, grade sync, and attendance tracking.
3. **Provide institutional whitelabeling** with UTAS branding, colors, and identity.
4. **Deploy AI virtual tutors** (Humanisation) to enhance the student learning experience across subjects.
5. **Establish a scalable LMS** built on OpenEduCat for course management, timetabling, and academic administration.
### 2.2 Module Scope
| # | Module | Description | Acceptance Criteria |
|---|--------|-------------|---------------------|
| 1 | **English Self Learning** | AI-powered IELTS preparation: Reading, Listening, Writing, Speaking practice with AI grading, personalized training tips, and progress tracking. | Students can complete full practice sessions in all 4 skills; AI grading returns scores within 60 seconds; training tips are personalized to weaknesses. |
| 2 | **Examinations** | Full exam lifecycle: AI-generated exam content, timed exam sessions, automated grading, results dashboard, and teacher approval workflows. | Teachers can generate, review, and assign exams; students complete timed exams; grading is automated with band scores and feedback. |
| 3 | **Mathematics** | Math courses and AI-assisted exams: course content delivery, formula-based question generation, automated grading for numerical and short-answer responses. | Students access Math courses; AI generates Math questions at configurable difficulty levels; automated grading handles numerical and short-answer formats. |
| 4 | **Information Technology** | IT courses and AI-assisted exams: course content delivery, conceptual and practical question generation, automated grading for MCQ and short-answer formats. | Students access IT courses; AI generates IT questions across topics; automated grading covers MCQ, true/false, and short answers. |
| 5 | **LMS (OpenEduCat)** | Course management, enrollment, timetabling, attendance tracking, batch management, gradebook, and academic reporting via OpenEduCat Odoo modules. | Admin manages courses, batches, and timetables; teachers record attendance and grades; students view schedules and progress. |
| 6 | **Whitelabeling** | UTAS institutional branding: customizable logo, color palette, fonts, login screen, email templates, and report headers. | Platform displays UTAS branding throughout; branding is configurable via admin settings without code changes. |
| 7 | **Humanisation** | AI-powered virtual tutors using ELAI avatar technology: video-based tutoring, interactive speaking practice, and subject-specific AI guidance. | AI avatars present content and interact with students across subjects; avatar selection is available; videos generate within 2 minutes. |
| 8 | **SIS Integration** | Bidirectional integration with UTAS's existing Student Information System: student enrollment sync, grade export, attendance sync, and course catalog mapping. | Student data syncs from SIS to EnCoach on enrollment; grades and attendance export back to SIS; data is consistent within 15-minute sync cycles. |
| 9 | **Ticketing** | Support ticket system for students and staff: ticket creation, categorization, assignment, status tracking, and resolution workflow. | Users submit tickets; staff can categorize, assign, and resolve; status updates are visible to the reporter. |
### 2.3 Out of Scope (This Engagement)
- Mobile native applications (iOS/Android)
- Content creation for Math and IT courses (content to be provided by UTAS or generated via AI)
- UTAS internal network infrastructure changes
- Marketing website / landing page redesign
- Payment gateway integration for UTAS (institutional licensing assumed)
---
## 3. System Architecture
### 3.1 Architecture Overview
```mermaid
graph TB
subgraph frontend ["Frontend Layer"]
ReactApp["React 18 SPA<br/>TypeScript + Tailwind + shadcn/ui<br/>55+ pages, role-based routing"]
end
subgraph backend ["Backend Layer -- Odoo 19"]
API["REST API Controllers<br/>70+ JSON endpoints"]
Core["Core Modules<br/>Users, Entities, Roles, Permissions"]
Exam["Exam Engine<br/>Reading, Listening, Writing, Speaking, Level"]
LMS["OpenEduCat LMS<br/>Courses, Batches, Timetable, Attendance"]
AI["AI Modules<br/>Generation, Grading, Media, Training"]
Sub["Business Modules<br/>Subscriptions, Tickets, Registration"]
end
subgraph aiServices ["AI Services"]
GPT["OpenAI GPT-4o<br/>Content Generation + Grading"]
Whisper["OpenAI Whisper<br/>Speech-to-Text (local)"]
Polly["AWS Polly<br/>Text-to-Speech (neural)"]
ELAI["ELAI<br/>AI Avatar Video"]
GPTZero["GPTZero<br/>AI Writing Detection"]
FAISS["FAISS + SentenceTransformers<br/>Semantic Search"]
end
subgraph dataLayer ["Data Layer"]
PG["PostgreSQL 16"]
end
subgraph external ["External Systems"]
SIS["UTAS SIS<br/>Student Information System"]
end
ReactApp -->|"JWT Auth + REST API"| API
API --> Core
API --> Exam
API --> LMS
API --> AI
API --> Sub
AI --> GPT
AI --> Whisper
AI --> Polly
AI --> ELAI
AI --> GPTZero
AI --> FAISS
Core --> PG
Exam --> PG
LMS --> PG
Sub --> PG
API <-->|"REST API Sync"| SIS
```
### 3.2 Technology Stack
| Layer | Technology | Details |
|-------|-----------|---------|
| **Frontend** | React 18, TypeScript, Vite 5 | SPA with TanStack Query, React Router v6, Zod validation |
| **UI Framework** | shadcn/ui, Tailwind CSS | Radix UI primitives, responsive design, dark mode capable |
| **Backend** | Odoo 19, Python 3.11 | 15 custom modules, ORM-based data access, background job processing |
| **Database** | PostgreSQL 16 | Odoo-managed schema, full-text search, JSONB for flexible data |
| **LMS** | OpenEduCat | Odoo-native education modules: courses, batches, attendance, timetable |
| **AI -- Text Generation** | OpenAI GPT-4o, GPT-3.5-turbo | Exam content generation, grading, evaluation, training tips |
| **AI -- Speech-to-Text** | OpenAI Whisper (local, base model) | 4 instances, round-robin, 30s chunked transcription |
| **AI -- Text-to-Speech** | AWS Polly (Neural) | 11 English voices, MP3 output, sentence-boundary chunking |
| **AI -- Video** | ELAI | 7 AI avatars (male/female), ElevenLabs + Azure voices |
| **AI -- Detection** | GPTZero | AI-generated writing detection per submission |
| **AI -- Search** | FAISS + all-MiniLM-L6-v2 | Semantic similarity search over training tips knowledge base |
| **Deployment** | Docker Compose | Odoo + PostgreSQL containers, Nginx reverse proxy |
| **Version Control** | Gitea | Private repositories for frontend and backend |
### 3.3 Deployment Architecture
```mermaid
graph LR
subgraph production ["Production Server"]
Nginx["Nginx<br/>Reverse Proxy<br/>SSL Termination"]
FrontendContainer["Frontend Container<br/>React SPA<br/>Port 3000"]
OdooContainer["Odoo 19 Container<br/>Python 3.11<br/>Port 8069"]
DBContainer["PostgreSQL 16<br/>Port 5432"]
end
Browser["Browser"] -->|"HTTPS"| Nginx
Nginx -->|"/app/*"| FrontendContainer
Nginx -->|"/api/*"| OdooContainer
OdooContainer --> DBContainer
FrontendContainer -->|"REST API"| OdooContainer
```
### 3.4 Existing Assets Inventory
| Asset | Count | Status |
|-------|-------|--------|
| Odoo custom modules | 15 | Deployed on staging |
| Backend REST API endpoints | 70+ | Functional, English/IELTS focused |
| Frontend pages (React) | 55+ | UI complete, mock data only |
| AI service integrations | 6 | Configured and tested |
| ELAI avatar profiles | 7 | Seeded in database |
| Training tips (FAISS) | 80 | Imported with embeddings |
| Odoo data models | 20+ | Schema deployed |
---
## 4. Feature Modules Breakdown
### 4.1 English Self Learning
| Aspect | Detail |
|--------|--------|
| **Current State** | Backend complete: AI-powered generation for Reading, Listening, Writing, Speaking. Grading via GPT-4o with IELTS rubric. Polly TTS for listening audio. ELAI avatars for speaking. FAISS-based personalized training tips. Frontend UI built (mocked). |
| **Work Required** | Replace mock authentication with Odoo JWT. Wire all student-facing pages to backend APIs. Integrate AI grading display (scores, feedback, AI detection). Connect training/tips module. |
| **Dependencies** | Stable Odoo API (Phase 1 complete). Frontend auth working. |
| **Effort** | 6 person-weeks |
| **Risk** | Low -- both backend and frontend exist; integration is the main task. |
### 4.2 Examinations
| Aspect | Detail |
|--------|--------|
| **Current State** | Backend complete: exam CRUD, 5 module types (reading, listening, writing, speaking, level), AI generation endpoints, approval workflows. Frontend: exam editor, exam list, generation page, approval workflows (all mocked). |
| **Work Required** | Wire admin exam management pages to APIs. Connect AI generation UI to real endpoints. Implement exam-taking flow with timer and state persistence. Connect grading pipeline and results display. |
| **Dependencies** | English Self Learning module (shared components). |
| **Effort** | Included in English Self Learning estimate (shared codebase). |
| **Risk** | Low -- core exam engine is proven. |
### 4.3 Mathematics
| Aspect | Detail |
|--------|--------|
| **Current State** | No backend module exists. No frontend pages exist. The AI exam engine (GPT-based generation + grading) provides a reusable foundation. |
| **Work Required** | **Backend:** Create `encoach_math` Odoo module with Math-specific exam models, AI prompt templates for formula-based questions, numerical grading logic, and multi-format question types (MCQ, fill-in, short answer, calculation). **Frontend:** Create Math course pages, Math exam taking interface with formula rendering (KaTeX/MathJax), Math-specific grading display. |
| **Dependencies** | Core exam engine must be stable. AI prompts require testing with GPT-4o for mathematical accuracy. |
| **Effort** | 5 person-weeks |
| **Risk** | Medium -- AI generation of math questions requires careful prompt engineering for accuracy. Formula rendering on frontend adds complexity. |
### 4.4 Information Technology
| Aspect | Detail |
|--------|--------|
| **Current State** | No backend module exists. No frontend pages exist. Similar to Math, the exam engine provides a foundation. |
| **Work Required** | **Backend:** Create `encoach_it` Odoo module with IT-specific exam models, AI prompt templates for conceptual and practical IT questions (networking, databases, programming concepts, security), grading logic for MCQ and short-answer. **Frontend:** Create IT course pages, IT exam interface, IT-specific grading display. |
| **Dependencies** | Core exam engine must be stable. |
| **Effort** | 4 person-weeks |
| **Risk** | Low-Medium -- IT subjects are text-based (no formula complexity). AI generation of IT questions is straightforward with GPT-4o. |
### 4.5 LMS (OpenEduCat)
| Aspect | Detail |
|--------|--------|
| **Current State** | OpenEduCat modules will be provided and installed into Odoo 19. Frontend LMS pages exist and are fully built: student dashboard, courses, course detail, assignments, grades, attendance, timetable (student); courses, course builder, assignments, attendance, students, timetable (teacher); dashboard, courses, students, teachers, batches, batch detail, timetable, reports, settings (admin). All pages use mock data. |
| **Work Required** | **Backend:** Install OpenEduCat modules. Create REST API controller layer (`encoach_lms_api`) to expose OpenEduCat models as JSON endpoints matching the frontend's data expectations. Map OpenEduCat models to frontend data interfaces (Course, Module, Lesson, Batch, Timetable, Attendance, Grade). **Frontend:** Replace mock data imports with API calls using TanStack Query. Wire forms to create/update APIs. |
| **Dependencies** | OpenEduCat modules provided and compatible with Odoo 19. |
| **Effort** | 3 person-weeks |
| **Risk** | Medium -- OpenEduCat model compatibility with Odoo 19 must be verified. API mapping between OpenEduCat's data structures and the frontend's interfaces requires careful alignment. |
### 4.6 Whitelabeling
| Aspect | Detail |
|--------|--------|
| **Current State** | No whitelabeling support. Frontend uses CSS variables for theming (Tailwind + shadcn/ui) with `darkMode: ["class"]` configured but not activated. No branding configuration. |
| **Work Required** | **Backend:** Create `encoach_branding` model in Odoo for tenant branding settings (logo, primary color, secondary color, font, favicon, login background, email header). Expose branding API endpoint. **Frontend:** Create a branding provider that fetches configuration on app load and applies CSS variables dynamically. Configure logo, colors, and fonts from API. Add admin UI for branding management. |
| **Dependencies** | UTAS provides brand assets (logo, color palette, fonts). |
| **Effort** | 2 person-weeks |
| **Risk** | Low -- CSS variable-based theming is well-established. |
### 4.7 Humanisation (AI Virtual Tutors)
| Aspect | Detail |
|--------|--------|
| **Current State** | ELAI integration exists for speaking exam avatar videos. 7 avatars configured (Gia, Vadim, Orhan, Flora, Scarlett, Parker, Ethan) with ElevenLabs and Azure voices. Currently limited to presenting speaking exam questions. |
| **Work Required** | **Backend:** Extend ELAI integration to support tutoring mode -- avatars explain concepts, provide feedback narration, and guide students through exercises. Create endpoints for on-demand tutoring video generation per subject. **Frontend:** Build tutor interaction UI -- avatar selector, video player with synchronized content, interactive Q&A flow. Integrate across English, Math, and IT modules. |
| **Dependencies** | ELAI API capacity and cost model for increased video generation. Subject-specific scripts/prompts. |
| **Effort** | 3 person-weeks |
| **Risk** | Medium -- ELAI video generation time (1-3 minutes per video) affects real-time tutoring UX. Cost scales with usage. |
### 4.8 SIS Integration
| Aspect | Detail |
|--------|--------|
| **Current State** | No SIS integration exists. UTAS has an existing Student Information System that we must integrate with via API. |
| **Work Required** | **Discovery:** Obtain UTAS SIS API documentation, authentication method, and data schemas. **Backend:** Create `encoach_sis` Odoo module with SIS sync models, scheduled sync jobs (cron), and conflict resolution. Implement: student enrollment import, grade export, attendance sync, course catalog mapping. **Frontend:** SIS sync status dashboard for admin. Sync logs and error reporting. |
| **Dependencies** | UTAS provides SIS API documentation, test environment access, and a technical contact. |
| **Effort** | 4 person-weeks |
| **Risk** | High -- entirely dependent on UTAS SIS API quality, documentation completeness, and test environment availability. This is the single highest-risk module. |
### 4.9 Ticketing
| Aspect | Detail |
|--------|--------|
| **Current State** | Backend complete: `encoach_ticket` Odoo module with full CRUD, categorization, and status workflow. API endpoints exist (`/api/tickets`). Frontend: Tickets page exists in admin portal (mocked). |
| **Work Required** | Wire frontend tickets page to backend API. Add ticket creation flow for students and teachers. Add ticket assignment and resolution workflow for admin. |
| **Dependencies** | None -- self-contained module. |
| **Effort** | 1 person-week |
| **Risk** | Low -- both backend and frontend exist. |
### 4.10 Effort Summary
| Module | Person-Weeks | Wave |
|--------|-------------|------|
| English Self Learning + Examinations | 6 | Wave 1 |
| Mathematics | 5 | Wave 2 |
| Information Technology | 4 | Wave 2 |
| LMS (OpenEduCat) | 3 | Wave 2 |
| Ticketing | 1 | Wave 2 |
| Whitelabeling | 2 | Wave 3 |
| Humanisation | 3 | Wave 3 |
| SIS Integration | 4 | Wave 3 |
| **Total** | **28 person-weeks** | |
With a team of 3 producing approximately 3 person-weeks per calendar week, the raw work is approximately 9-10 calendar weeks. Adding UAT cycles, amendments, and buffer, the overall calendar duration is 20 weeks (April 1 -- August 21).
---
## 5. Development Phases
The project is structured into three overlapping waves. Each wave follows a build-test-deploy cycle and produces a production-ready deliverable.
### 5.1 Wave 1 -- Foundation (April 1 -- June 12)
**Goal:** English Self Learning and Examinations modules live in production with real UTAS users.
This wave transforms the existing backend and frontend from separate prototypes into an integrated, production-ready platform.
#### Sprint Breakdown
| Sprint | Dates | Focus | Deliverables |
|--------|-------|-------|-------------|
| **S1** | Apr 1-11 | **Stabilization & Auth** | Fix remaining backend bugs. Replace mock auth with Odoo JWT in React frontend. Set up API service layer. Configure production deployment pipeline. |
| **S2** | Apr 12-18 | **Core API Integration** | Wire student dashboard, courses, and profile pages. Implement exam list and exam detail APIs. Connect user management and entity management. |
| **S3** | Apr 19-25 | **Exam Engine Integration** | Wire exam-taking flow (reading, listening, writing, speaking). Connect AI generation endpoints to exam editor. Integrate timer, state persistence, and submission. **Staging demo to UTAS (Apr 24-25).** |
| **S4** | Apr 26 -- May 9 | **AI Features & Grading** | Wire AI grading pipeline (writing evaluation, speaking evaluation). Connect TTS audio playback. Connect ELAI avatar videos. Integrate training tips and personalized recommendations. Connect AI detection display. |
| **S5** | May 10-23 | **UAT Round 1** | Deploy to UTAS staging. Conduct UAT with UTAS staff and selected students. Collect feedback. Bug fixes and amendments. |
| **S6** | May 24 -- Jun 6 | **UAT Round 2 & Hardening** | Address UAT feedback. Performance optimization. Security review. Documentation. |
| **S7** | Jun 7-12 | **GO LIVE** | Production deployment. Monitoring setup. Handover to UTAS for English + Examinations. Post-launch support begins. |
#### Wave 1 Exit Criteria
- Students can register, log in, and complete full English practice sessions
- AI grading returns accurate band scores with detailed feedback for writing and speaking
- Teachers can generate, review, approve, and assign exams
- Admin can manage users, entities, classrooms, and assignments
- Training tips are personalized based on exam performance
- Platform is stable under expected UTAS load
### 5.2 Wave 2 -- Expansion (May 17 -- July 24)
**Goal:** Mathematics, Information Technology, LMS, and Ticketing modules live in production.
Wave 2 begins during Wave 1's UAT phase, leveraging developers freed from active feature work.
#### Sprint Breakdown
| Sprint | Dates | Focus | Deliverables |
|--------|-------|-------|-------------|
| **S8** | May 17-30 | **Math & IT Backend** | Create `encoach_math` and `encoach_it` Odoo modules. Develop AI prompt templates for Math question generation (numerical, formula-based, word problems). Develop AI prompt templates for IT questions (conceptual, practical). Implement grading logic for non-essay formats. |
| **S9** | May 31 -- Jun 13 | **OpenEduCat & LMS API** | Install and configure OpenEduCat modules in Odoo 19. Create `encoach_lms_api` controller layer. Map OpenEduCat models to frontend data interfaces. Wire LMS admin pages (courses, batches, timetable, attendance). |
| **S10** | Jun 14-27 | **Math & IT Frontend + LMS Wiring** | Build Math exam interface with formula rendering. Build IT exam interface. Wire student and teacher LMS pages. Wire ticketing module. |
| **S11** | Jun 28 -- Jul 11 | **UAT Round 1** | Deploy Math, IT, LMS, Ticketing to staging. UAT with UTAS staff. Math AI accuracy testing. LMS workflow validation. |
| **S12** | Jul 12-18 | **Amendments** | Address UAT feedback. Fix Math/IT grading edge cases. LMS refinements. |
| **S13** | Jul 19-24 | **GO LIVE** | Production deployment of Math, IT, LMS, Ticketing. Post-launch support begins. |
#### Wave 2 Exit Criteria
- Math and IT exams generate accurately via AI with appropriate difficulty levels
- LMS (OpenEduCat) fully functional: courses, enrollment, attendance, timetable, gradebook
- Ticketing system operational for students and staff
- All modules integrated with Wave 1 platform (single sign-on, unified navigation)
### 5.3 Wave 3 -- Integration (July 1 -- August 21)
**Goal:** Whitelabeling, SIS integration, and Humanisation modules complete. Full platform go-live.
Wave 3 begins during Wave 2's frontend phase, with SIS discovery starting earlier.
#### Sprint Breakdown
| Sprint | Dates | Focus | Deliverables |
|--------|-------|-------|-------------|
| **S14** | Jul 1-11 | **Whitelabeling + SIS Discovery** | Implement branding configuration backend and frontend. Apply UTAS brand assets. Begin SIS API discovery and documentation review with UTAS IT team. |
| **S15** | Jul 12-25 | **SIS Integration Development** | Build `encoach_sis` Odoo module. Implement student enrollment import. Implement grade export. Implement attendance sync. Build admin SIS dashboard. |
| **S16** | Jul 26 -- Aug 1 | **Humanisation** | Extend ELAI integration for tutoring mode. Build tutor interaction UI. Generate subject-specific avatar tutoring content. |
| **S17** | Aug 2-8 | **Integration Testing** | End-to-end testing of all 9 modules together. SIS sync validation with UTAS test data. Performance testing under load. Security audit. |
| **S18** | Aug 9-15 | **Final UAT** | Full platform UAT with UTAS. All modules tested together. Final amendments. |
| **S19** | Aug 16-21 | **Full Platform GO LIVE** | Production deployment of complete platform. All 9 modules active. Monitoring and support in place. |
#### Wave 3 Exit Criteria
- Platform displays UTAS branding throughout
- SIS syncs student enrollment, grades, and attendance bidirectionally
- AI virtual tutors available across English, Math, and IT
- All 9 modules function as an integrated platform
- Performance meets production requirements under expected load
---
## 6. University Integration Plan
### 6.1 Integration Architecture
```mermaid
sequenceDiagram
participant SIS as UTAS SIS
participant Odoo as EnCoach Odoo 19
participant React as EnCoach Frontend
participant Student as Student
Note over SIS,Odoo: Enrollment Sync (SIS → EnCoach)
SIS->>Odoo: Student enrollment data (scheduled sync)
Odoo->>Odoo: Create/update student records
Odoo->>Odoo: Assign to courses and batches
Note over Student,React: Daily Usage
Student->>React: Login, take courses, complete exams
React->>Odoo: API calls (exam, grading, attendance)
Odoo->>Odoo: Record grades, attendance, progress
Note over Odoo,SIS: Grade & Attendance Export (EnCoach → SIS)
Odoo->>SIS: Grade export (scheduled sync)
Odoo->>SIS: Attendance export (scheduled sync)
```
### 6.2 Data Exchange Specification
| Data Flow | Direction | Frequency | Format |
|-----------|-----------|-----------|--------|
| Student enrollment | SIS → EnCoach | On enrollment + daily sync | REST API / CSV import |
| Course catalog mapping | Bidirectional | On setup + manual sync | REST API |
| Exam grades | EnCoach → SIS | After grading + daily batch | REST API |
| Attendance records | EnCoach → SIS | End of day batch | REST API |
| Student status changes | SIS → EnCoach | Real-time webhook or daily | REST API |
### 6.3 Authentication Strategy
| Phase | Method | Detail |
|-------|--------|--------|
| **Initial (Wave 1-2)** | Odoo-native JWT | Students and staff authenticate directly with EnCoach. Credentials provisioned from SIS enrollment data. |
| **Full Integration (Wave 3)** | SSO via SAML/OAuth | If UTAS SIS supports SSO, students authenticate once at UTAS portal and access EnCoach seamlessly. Fallback to JWT if SSO is not available. |
### 6.4 UTAS Responsibilities for Integration
| Deliverable | Required By | Impact if Delayed |
|-------------|-------------|-------------------|
| SIS API documentation | June 15, 2026 | Blocks SIS module development; delays Wave 3 by equivalent duration |
| SIS test environment access | July 1, 2026 | Blocks integration testing |
| SIS technical contact (dedicated) | June 15, 2026 | Slows discovery and issue resolution |
| Brand assets (logo, colors, fonts) | June 15, 2026 | Blocks whitelabeling completion |
| UAT testers (3-5 staff, 10-20 students) | May 1, 2026 | Delays UAT cycles; risks quality |
| Math and IT course content (if not AI-generated) | May 15, 2026 | Delays Math/IT module population |
| Production server provisioning | August 1, 2026 | Blocks production deployment |
---
## 7. Master Timeline
### 7.1 Gantt Chart
```mermaid
gantt
title EnCoach UTAS Deployment -- Master Timeline
dateFormat YYYY-MM-DD
axisFormat %d %b
section Wave1_Foundation
S1_Stabilize_Auth :s1, 2026-04-01, 11d
S2_Core_API_Integration :s2, 2026-04-12, 7d
S3_Exam_Engine_Integration :s3, 2026-04-19, 7d
UTAS_Staging_Demo :milestone, m1, 2026-04-24, 0d
S4_AI_Features_Grading :s4, 2026-04-26, 14d
S5_UAT_Round_1 :s5, 2026-05-10, 14d
S6_UAT_Round_2_Hardening :s6, 2026-05-24, 14d
S7_English_Exams_GO_LIVE :s7, 2026-06-07, 5d
English_Exams_LIVE :milestone, m2, 2026-06-12, 0d
section Wave2_Expansion
S8_Math_IT_Backend :s8, 2026-05-17, 14d
S9_OpenEduCat_LMS_API :s9, 2026-05-31, 14d
S10_Math_IT_LMS_Frontend :s10, 2026-06-14, 14d
S11_UAT_Math_IT_LMS :s11, 2026-06-28, 14d
S12_Amendments :s12, 2026-07-12, 7d
S13_Math_IT_LMS_GO_LIVE :s13, 2026-07-19, 5d
Math_IT_LMS_LIVE :milestone, m3, 2026-07-24, 0d
section Wave3_Integration
S14_Whitelabeling_SIS_Discovery :s14, 2026-07-01, 11d
S15_SIS_Integration :s15, 2026-07-12, 14d
S16_Humanisation :s16, 2026-07-26, 7d
S17_Integration_Testing :s17, 2026-08-02, 7d
S18_Final_UAT :s18, 2026-08-09, 7d
S19_Full_Platform_GO_LIVE :s19, 2026-08-16, 5d
Full_Platform_LIVE :milestone, m4, 2026-08-21, 0d
section PostLaunch
Post_Launch_Support :pls, 2026-08-21, 30d
```
### 7.2 Key Milestones
| # | Milestone | Date | Gate Criteria |
|---|-----------|------|---------------|
| M0 | Project Kickoff | April 1, 2026 | Team assembled, scope agreed, environments ready |
| M1 | UTAS Staging Demo | April 24, 2026 | English + Exams functional on staging, basic end-to-end flow |
| M2 | Wave 1 GO LIVE | June 12, 2026 | English Self Learning + Examinations in production, 2 UAT rounds passed |
| M3 | Wave 2 GO LIVE | July 24, 2026 | Math + IT + LMS + Ticketing in production, UAT passed |
| M4 | Full Platform GO LIVE | August 21, 2026 | All 9 modules in production, SIS integration validated, full UAT passed |
| M5 | Post-Launch Support Ends | September 21, 2026 | 30-day support period complete, handover documentation delivered |
### 7.3 Critical Path
The critical path runs through:
1. **Wave 1 auth stabilization** (blocks all frontend work)
2. **Wave 1 API integration** (blocks UAT and all subsequent waves)
3. **UTAS SIS API documentation delivery** (blocks Wave 3 SIS development)
4. **OpenEduCat module compatibility** (blocks LMS development)
Any delay on items 1-2 cascades through the entire timeline. Items 3-4 are external dependencies that must be tracked proactively.
---
## 8. Testing and Rollout Strategy
### 8.1 Testing Stages
```mermaid
graph LR
Dev["Developer Testing<br/>Unit + Integration<br/>Continuous"] --> Staging["Staging<br/>System Integration<br/>Per Sprint"]
Staging --> UAT["UAT with UTAS<br/>Acceptance<br/>Per Wave"]
UAT --> Perf["Performance Testing<br/>Load + Stress<br/>Pre-Go-Live"]
Perf --> Security["Security Audit<br/>OWASP Top 10<br/>Pre-Go-Live"]
Security --> GoLive["GO LIVE<br/>Production<br/>Per Wave"]
```
| Stage | Who | When | Scope |
|-------|-----|------|-------|
| **Developer Testing** | EnCoach dev team | Continuous | Unit tests, API integration tests, manual smoke tests per feature |
| **Staging Deployment** | EnCoach dev team | End of each sprint | Full platform on staging server, regression testing, cross-module integration |
| **UAT (User Acceptance)** | UTAS staff + students | 2 rounds per wave | Guided test scenarios, real-world usage, feedback collection |
| **Performance Testing** | EnCoach dev team | Before each go-live | Concurrent user simulation (target: 200 simultaneous users), API response times (<2s for standard, <60s for AI grading) |
| **Security Audit** | EnCoach architect | Before production go-live | Authentication review, authorization checks, API input validation, OWASP Top 10 |
### 8.2 UAT Process
Each wave includes two UAT rounds:
**UAT Round 1 (2 weeks):**
1. EnCoach deploys to staging environment
2. UTAS UAT team receives test accounts and test scenarios document
3. UTAS testers execute scenarios and log issues via shared tracking system
4. EnCoach triages issues daily (critical = same day, high = 2 days, medium = next sprint)
5. Weekly status call between EnCoach and UTAS
**UAT Round 2 (2 weeks):**
1. All critical and high issues from Round 1 resolved
2. Re-test of failed scenarios
3. Exploratory testing by UTAS testers
4. Go-live readiness assessment
5. Sign-off by UTAS project lead
### 8.3 Go-Live Checklist (Per Wave)
| # | Item | Owner |
|---|------|-------|
| 1 | All critical and high UAT issues resolved | EnCoach |
| 2 | Performance tests pass (response time, concurrent users) | EnCoach |
| 3 | Security audit complete, no critical findings | EnCoach |
| 4 | Production environment provisioned and configured | EnCoach + UTAS IT |
| 5 | DNS / domain configured (if applicable) | UTAS IT |
| 6 | SSL certificate installed | EnCoach + UTAS IT |
| 7 | Database backup and restore procedure tested | EnCoach |
| 8 | Monitoring and alerting configured | EnCoach |
| 9 | Rollback procedure documented and tested | EnCoach |
| 10 | UTAS project lead sign-off | UTAS |
### 8.4 Rollback Plan
Each go-live deployment includes a documented rollback procedure:
1. **Database snapshot** taken immediately before production deployment
2. **Previous container images** tagged and retained (minimum 3 previous versions)
3. **Rollback trigger criteria:** >5% error rate, >10s average response time, data integrity issue
4. **Rollback execution time:** <15 minutes (Docker image swap + database restore)
5. **Communication:** UTAS IT notified within 5 minutes of rollback decision
### 8.5 Post-Launch Support
| Period | Coverage | Scope |
|--------|----------|-------|
| Week 1-2 after each go-live | Daily monitoring, same-day critical fixes | Bug fixes, performance tuning, user support |
| Week 3-4 after each go-live | Standard monitoring, 2-day response for non-critical | Bug fixes, minor enhancements from feedback |
| After Full Platform GO LIVE | 30-day support period (Aug 21 -- Sep 21) | Full platform support, knowledge transfer to UTAS IT |
---
## 9. Team and Responsibilities
### 9.1 EnCoach Team
| Role | Responsibilities |
|------|-----------------|
| **Solution Architect** | System architecture decisions. University integration design. SIS API mapping. Security and performance oversight. Code review. UTAS stakeholder communication. Sprint planning. |
| **Senior Developer (AI-assisted)** | Backend development (Odoo modules). AI service integration. Math/IT module AI prompts. SIS integration implementation. Database design. API development. |
| **Full-Stack Developer (AI-assisted)** | Frontend development (React). API integration. UI/UX implementation. Whitelabeling. LMS frontend wiring. Testing. |
### 9.2 UTAS Responsibilities
| Role | Responsibilities |
|------|-----------------|
| **Project Sponsor** | Budget approval. Strategic decisions. Escalation resolution. |
| **Project Lead** | Scope sign-off. UAT coordination. Go-live approval. Weekly status reviews. |
| **IT Department** | SIS API documentation and test environment. Production server provisioning. Network and DNS configuration. SSL certificates. |
| **Subject Matter Experts** | Math and IT course content review. Exam quality validation. Training content verification. |
| **UAT Testers (3-5 staff, 10-20 students)** | Execute test scenarios. Log issues and feedback. Re-test after fixes. |
### 9.3 Communication Plan
| Activity | Frequency | Participants | Medium |
|----------|-----------|-------------|--------|
| Sprint status report | Weekly (Friday) | EnCoach team → UTAS Project Lead | Email + document |
| Demo / walkthrough | Bi-weekly | EnCoach team + UTAS stakeholders | Video call + screen share |
| UAT feedback review | Daily during UAT | EnCoach team + UTAS testers | Shared issue tracker |
| Escalation call | As needed | Architect + UTAS Project Lead | Video call |
| Go-live readiness review | Before each go-live | All stakeholders | Meeting |
### 9.4 Escalation Path
```
Level 1: Developer → Solution Architect (same day)
Level 2: Solution Architect → UTAS Project Lead (1 business day)
Level 3: UTAS Project Lead → UTAS Project Sponsor (2 business days)
```
---
## 10. Risk Register
| # | Risk | Probability | Impact | Mitigation |
|---|------|------------|--------|------------|
| R1 | **UTAS SIS API documentation delayed or incomplete** | High | High | Begin SIS discovery in Wave 2 (early July). Prepare alternative sync methods (CSV import/export) as fallback. Weekly check-ins with UTAS IT from June onwards. |
| R2 | **Math AI question generation inaccuracy** | Medium | Medium | Invest in thorough prompt engineering with GPT-4o. Build validation test suite with known-correct Math problems. Include human review step in exam approval workflow. |
| R3 | **OpenEduCat incompatibility with Odoo 19** | Medium | High | Test OpenEduCat installation early (Sprint S9). Identify compatibility issues before committing to LMS frontend work. Fallback: build minimal LMS models within existing Odoo modules. |
| R4 | **Frontend API integration slower than estimated** | Medium | Medium | Prioritize critical paths (auth, core pages) first. Use API contract testing to parallelize frontend and backend work. Leverage AI coding assistants to accelerate repetitive wiring. |
| R5 | **Team bandwidth constraints** | Medium | High | AI-assisted development (both developers use AI tools) effectively increases output by 1.5-2x. Strict scope management -- no feature creep. Clear sprint goals with daily standups. |
| R6 | **ELAI video generation latency for Humanisation** | Low | Medium | Pre-generate common tutoring videos. Cache frequently requested content. Set user expectations (1-3 min generation time). Consider alternative: pre-recorded avatar videos for standard content. |
| R7 | **Production infrastructure not ready on time** | Low | High | Request production server provisioning by August 1 (3 weeks before go-live). Test deployment procedure on staging first. Have cloud-based fallback plan. |
| R8 | **UTAS UAT testers unavailable or insufficient feedback** | Medium | Medium | Provide detailed test scenarios with step-by-step instructions. Offer guided UAT sessions. Establish minimum UAT participation requirements in the scope agreement. |
---
## 11. Assumptions and Prerequisites
### 11.1 Assumptions
| # | Assumption | Impact if Invalid |
|---|-----------|-------------------|
| A1 | UTAS provides 3-5 staff and 10-20 students for UAT testing | Delays UAT; reduces quality assurance |
| A2 | OpenEduCat modules are compatible with Odoo 19 | Requires building custom LMS models; adds 3-4 weeks |
| A3 | UTAS SIS exposes REST APIs for enrollment, grades, and attendance | Requires alternative integration (CSV, database sync); adds 2-3 weeks |
| A4 | Math and IT course content is either provided by UTAS or generated by AI | If neither, course content creation becomes a separate workstream |
| A5 | The platform will be accessed via web browsers only (no mobile app) | Mobile app would be a separate project |
| A6 | Institutional licensing model (no per-student payment processing) | Payment gateway integration would add 2-3 weeks |
| A7 | Single UTAS deployment (not multi-university / multi-tenant initially) | Multi-tenant support would add architectural complexity |
| A8 | Internet connectivity at UTAS is sufficient for AI cloud services (OpenAI, ELAI, AWS Polly) | On-premise AI deployment would be a separate project |
### 11.2 Prerequisites (with Deadlines)
| # | Prerequisite | Owner | Deadline | Status |
|---|-------------|-------|----------|--------|
| P1 | Scope agreement signed | UTAS + EnCoach | March 31, 2026 | Pending |
| P2 | OpenEduCat modules provided | EnCoach / UTAS | May 15, 2026 | Pending |
| P3 | UTAS brand assets delivered | UTAS | June 15, 2026 | Pending |
| P4 | SIS API documentation provided | UTAS IT | June 15, 2026 | Pending |
| P5 | SIS test environment access granted | UTAS IT | July 1, 2026 | Pending |
| P6 | UAT test team identified | UTAS | May 1, 2026 | Pending |
| P7 | Production server provisioned | UTAS IT / EnCoach | August 1, 2026 | Pending |
| P8 | Math/IT course content available | UTAS SMEs | May 15, 2026 | Pending |
---
## Appendix A: Module-to-API Mapping (Existing Backend Endpoints)
The following 70+ API endpoints are already built and deployed in the Odoo 19 backend. These form the foundation for Wave 1 frontend integration.
| Category | Endpoints | Count |
|----------|-----------|-------|
| Authentication | `/api/login`, `/api/logout`, `/api/reset`, `/api/reset/sendVerification` | 4 |
| Users | `/api/user`, `/api/users/update`, `/api/users/list`, `/api/users/<id>` | 4 |
| Entities & Roles | `/api/entities`, `/api/roles`, `/api/permissions` | 7 |
| Exams | `/api/exam`, `/api/exam/<module>`, `/api/exam/<module>/<id>`, `/api/exam/avatars` | 7 |
| AI Generation | `/api/exam/reading/*`, `/api/exam/listening/*`, `/api/exam/writing/*`, `/api/exam/speaking/*`, `/api/exam/level/generate` | 8 |
| Media | `/api/exam/listening/media`, `/api/exam/listening/transcribe`, `/api/exam/speaking/media`, `/api/transcribe` | 6 |
| Evaluations & Grading | `/api/evaluate/writing`, `/api/evaluate/speaking`, `/api/evaluate/interactiveSpeaking`, `/api/grading/multiple` | 6 |
| Classrooms | `/api/groups`, `/api/groups/<id>` | 3 |
| Assignments | `/api/assignments`, `/api/assignments/<id>`, `/api/assignments/<id>/start`, release, archive | 8 |
| Sessions & Stats | `/api/sessions`, `/api/stats`, `/api/statistical` | 5 |
| Training | `/api/training`, `/api/training/<id>`, `/api/training/tips`, `/api/training/walkthrough` | 4 |
| Subscriptions | `/api/packages`, `/api/stripe`, `/api/paypal`, `/api/paymob` + webhooks | 7 |
| Registration | `/api/register`, `/api/code/<code>`, `/api/batch_users`, `/api/make_user` | 4 |
| Tickets | `/api/tickets`, `/api/tickets/<id>` | 3 |
| Storage | `/api/storage`, `/api/storage/delete` | 2 |
| Approvals | `/api/approval-workflows`, `/api/approval-workflows/<id>` | 3 |
| **Total** | | **~81** |
---
## Appendix B: AI Service Configuration Summary
| Service | Model | Key Config | Usage |
|---------|-------|-----------|-------|
| OpenAI GPT | gpt-4o (primary), gpt-3.5-turbo (secondary) | Temperature: 0.1 (grading), 0.7 (generation), 0.2 (summaries). Max tokens: 4,097. JSON response format. | Exam generation, grading, evaluation, training tips |
| Whisper | base (local, ~1GB) | 4 instances, round-robin, 16kHz mono, 30s chunks with overlap | Speaking transcription, audio-to-text |
| AWS Polly | Neural engine | 11 voices, MP3 output, 3,000 char chunks | Listening exam audio generation |
| ELAI | 7 avatars | ElevenLabs + Azure voices, fade_in animation | Speaking exam video, virtual tutoring |
| GPTZero | v2/predict/text | Per-sentence analysis, confidence scoring | Writing AI detection |
| FAISS | IndexFlatL2 + all-MiniLM-L6-v2 | Top-5 results, 7 category indices, 80 training tips | Personalized training recommendations |
---
## Appendix C: Frontend Page Inventory (New React Application)
| Portal | Pages | Key Features |
|--------|-------|-------------|
| **Student** | Dashboard, Courses, Course Detail, Assignments, Grades, Attendance, Timetable, Profile | 8 pages |
| **Teacher** | Dashboard, Courses, Course Builder, Course Edit, Assignments, Assignment Detail, Attendance, Students, Timetable, Profile | 10 pages |
| **Admin (LMS)** | Dashboard, Courses, Students, Teachers, Batches, Batch Detail, Timetable, Reports, Settings, Profile | 10 pages |
| **Admin (Platform)** | Platform Dashboard, Assignments, Exams List, Exam Structures, Rubrics, Generation, Approval Workflows, Users, Entities, Classrooms, Student Performance, Stats Corporate, Record, Vocabulary, Grammar, Payment Record, Tickets, Settings, Exam | 19 pages |
| **Auth** | Login, Register, Forgot Password | 3 pages |
| **Total** | | **~50+ pages** |
---
*Document prepared by EnCoach Engineering Team. For questions or clarifications, contact the Solution Architect.*

86
docs/UTAS_SYSTEM_SCOPE.md Normal file
View File

@@ -0,0 +1,86 @@
# EnCoach -- UTAS System Scope Definition
**Date:** March 16, 2026
**Project:** EnCoach University Deployment for UTAS
---
## Core Modules
### 1. Learning Management System (LMS)
| Item | Detail |
|------|--------|
| **Engine** | OpenEduCat (Odoo 19 native modules) |
| **Frontend** | React 18 SPA -- student, teacher, and admin portals (50+ pages built) |
| **Capabilities** | Course catalog and enrollment, batch/cohort management, timetable scheduling, attendance tracking, gradebook, academic reporting |
| **Integration** | REST API bridge between OpenEduCat models and React frontend |
| **Subjects** | English Self Learning, Mathematics, Information Technology (extensible) |
### 2. Exam Portal
| Item | Detail |
|------|--------|
| **Exam Types** | Reading, Listening, Writing, Speaking, Level Test, Math, IT |
| **AI Generation** | GPT-4o generates exam content per subject and difficulty level |
| **AI Grading** | Automated grading for writing (GPT-4o + IELTS rubric), speaking (Whisper STT + GPT-4o), MCQ, short answer, numerical |
| **AI Detection** | GPTZero flags AI-generated student submissions |
| **Media** | AWS Polly TTS for listening audio, ELAI avatars for speaking video |
| **Workflow** | Exam creation, review, approval, assignment, timed sessions, grading, results |
| **Roles** | Admin creates/approves, teacher assigns, student takes, system grades |
### 3. Student Onboarding
| Item | Detail |
|------|--------|
| **Registration** | Self-registration or bulk import (CSV/batch) by admin |
| **SIS Sync** | Automatic student provisioning from UTAS Student Information System |
| **Enrollment** | Assignment to courses, batches, and classrooms upon registration |
| **Verification** | Email verification, registration code validation |
| **Roles** | Student, teacher, admin -- role-based access from first login |
### 4. Knowledge Base
| Item | Detail |
|------|--------|
| **Training Tips** | 80+ categorized tips (reading, writing, strategy, vocabulary, grammar) with FAISS semantic search |
| **Personalization** | After each exam, GPT analyzes performance and retrieves relevant tips via RAG (Retrieval-Augmented Generation) |
| **Walkthroughs** | Per-module guided learning paths |
| **AI Tutoring** | ELAI avatar virtual tutors provide video-based explanations and guidance (Humanisation) |
| **Content Scope** | English/IELTS (existing), Math and IT (to be developed) |
### 5. Helpdesk System
| Item | Detail |
|------|--------|
| **Ticketing** | Students and staff create support tickets with category, priority, and description |
| **Workflow** | Creation, assignment, status tracking (open, in-progress, resolved, closed) |
| **Roles** | Students/teachers submit; admin staff categorize, assign, and resolve |
| **Backend** | `encoach_ticket` Odoo module with full CRUD API (`/api/tickets`) |
### 6. API Integration with SIS
| Item | Detail |
|------|--------|
| **Direction** | Bidirectional: UTAS SIS <--> EnCoach |
| **Inbound (SIS to EnCoach)** | Student enrollment data, course catalog mapping, student status changes |
| **Outbound (EnCoach to SIS)** | Exam grades, attendance records, course completion status |
| **Method** | REST API (preferred) or CSV import/export (fallback) |
| **Frequency** | Real-time webhook (if available) or scheduled sync (daily batch) |
| **Prerequisite** | UTAS provides SIS API documentation, test environment, and technical contact |
---
## Technology Stack Summary
| Layer | Technology |
|-------|-----------|
| Frontend | React 18, TypeScript, Vite, Tailwind CSS, shadcn/ui |
| Backend | Odoo 19, Python 3.11, PostgreSQL 16 |
| LMS | OpenEduCat (Odoo modules) |
| AI | OpenAI GPT-4o, Whisper, AWS Polly, ELAI, GPTZero, FAISS |
| Deployment | Docker Compose, Nginx |
---
*EnCoach Engineering -- UTAS Deployment*