2 Commits

Author SHA1 Message Date
d6413a0496 Merge pull request 'docs: update all SRS documents to reflect implemented state' (#2) from docs/update-srs-documents into main
Reviewed-on: #2
2026-04-06 11:02:40 +02:00
4383db7fa1 docs: update all SRS documents to reflect implemented state
- ENCOACH_UNIFIED_SRS.md v2.0: updated header, added 8 new Part VIII-B
  sections (student leave, fees, lessons, gradebook, student progress,
  library, activities, facilities), extended permissions with roles CRUD
  and authority matrix, updated tech specs (93 pages, ~377 API routes,
  41 modules), added implementation traceability to all sections
- ENCOACH_ODOO19_BACKEND_SRS.md v3.0: updated status to implemented,
  added beyond-SRS features section, updated module count to 41,
  endpoint count to ~377
- ODOO_DEVELOPER_HANDOFF.md: rewritten with current repo references
  and implementation status
- ENCOACH_SYSTEM_FEATURES_GUIDE.md: added system features guide
- Superseded notices added to ODOO_BACKEND_SRS_v3.md,
  ODOO_MIGRATION_SRS_v2.md, ODOO_MIGRATION_SRS.md,
  ODOO_MIGRATION_FRONTEND_SRS.md, MATH_IT_ADAPTIVE_LEARNING_SRS.md

Made-with: Cursor
2026-04-06 12:57:52 +04:00
9 changed files with 4841 additions and 228 deletions

View File

@@ -1,9 +1,26 @@
# EnCoach Platform — Odoo 19 Backend SRS
**Version:** 2.0
**Date:** March 2026
**Status:** Definitive
**Purpose:** Complete backend specification for an Odoo 19 developer to build all required modules, models, and REST API endpoints for the EnCoach Adaptive Learning Platform. Includes courseware, communication, notification, FAQ, enhanced approval workflows, plagiarism detection, and official exam access modes.
**Version:** 3.0
**Date:** March 11, 2026
**Status:** Implemented — Staging Verified
**Supersedes:** `ODOO_BACKEND_SRS_v3.md`, `ODOO_MIGRATION_SRS_v2.md`, `ODOO_MIGRATION_SRS.md`
**Frontend Reference:** `ENCOACH_UNIFIED_SRS.md` (v2.0)
**Purpose:** Complete backend specification for the EnCoach Adaptive Learning Platform on Odoo 19. All modules, models, and REST API endpoints have been implemented and deployed to staging.
### Implementation Status
| Artifact | Location |
|----------|----------|
| **Backend Repository** | `https://git.albousalh.com/devops/encoach_backend_new_v2.git` (branch: `main`) |
| **Frontend Repository** | `https://git.albousalh.com/devops/encoach_frontend_new_v2.git` (branch: `main`) |
| **Staging Backend (Odoo 19)** | `http://5.189.151.117:8069` |
| **Staging Frontend** | `http://5.189.151.117:3000` |
| **Custom EnCoach Modules** | 27 modules in `new_project/custom_addons/` |
| **OpenEduCat Modules** | 14 community modules in `new_project/openeducat_erp-19.0/` |
| **Total API Routes** | ~377 REST endpoints across 4 controller packages |
| **Deployment** | Docker Compose (Odoo 19 + PostgreSQL 16) |
**Note:** The developer implemented all features in this SRS plus additional OpenEduCat Enterprise features documented in Section 34 (Beyond-SRS Features).
---
@@ -42,6 +59,7 @@
31. [Official Exam Access](#31-official-exam-access)
32. [Non-Functional Requirements](#32-non-functional-requirements)
33. [Implementation Priority](#33-implementation-priority)
34. [Beyond-SRS Features (Implemented)](#34-beyond-srs-features-implemented)
---
@@ -174,7 +192,22 @@ All OpenEduCat models need `to_api_dict()` methods on the `encoach_lms_api` inhe
| 34 | `encoach_notification` | Custom | Notification engine, configurable rules, email/in-app delivery, user preferences |
| 35 | `encoach_faq` | Custom | FAQ categories and items, role-filtered, searchable |
**Total: 8 OpenEduCat (ported) + 27 custom = 35 modules**
**Original plan: 8 OpenEduCat + 27 custom = 35 modules**
### 4.2 Additional Modules (Implemented Beyond SRS)
The developer added 6 more OpenEduCat community modules:
| # | Module | Type | Description |
|---|--------|------|-------------|
| 36 | `openeducat_fees` | OpenEduCat (port v19) | Fee plans, student fees, fee terms |
| 37 | `openeducat_library` | OpenEduCat (port v19) | Media catalog, movements, library cards |
| 38 | `openeducat_activity` | OpenEduCat (port v19) | Student activities, activity types |
| 39 | `openeducat_parent` | OpenEduCat (port v19) | Parent-student relationships |
| 40 | `openeducat_erp` | OpenEduCat (port v19) | ERP connector meta-module |
| 41 | `theme_web_openeducat` | OpenEduCat (port v19) | Web theme |
**Deployed total: 14 OpenEduCat + 27 custom = 41 modules**
---
@@ -1621,78 +1654,245 @@ Add to `encoach.exam`:
---
## 33. Implementation Priority
## 33. Implementation Status
| Priority | Modules | Rationale |
|----------|---------|-----------|
| **P0** | `encoach_core`, `encoach_api` (auth, users, entities, permissions) | Foundation — blocks everything |
| **P0** | `openeducat_core` (port to v19), `encoach_lms_api` (courses, batches, basic serialization) | LMS foundation |
| **P1** | `encoach_taxonomy`, `encoach_adaptive`, `encoach_adaptive_api`, `encoach_adaptive_ai` | Core adaptive learning loop |
| **P1** | `encoach_exam`, `encoach_ai_generation`, `encoach_ai_grading` | Exam engine |
| **P1** | `encoach_resources` | Learning content |
| **P2** | `encoach_courseware` (chapters, materials, progress, AI workbench) | Structured course delivery |
| **P2** | `encoach_communication` (discussions, announcements, messaging) | Collaboration |
| **P2** | `openeducat_timetable`, `openeducat_attendance`, `openeducat_classroom` (port to v19) | LMS timetable/attendance |
| **P2** | `openeducat_admission` (port to v19) + admission endpoints | Enrollment workflow |
| **P2** | Academic years/terms, departments endpoints | Institutional calendar |
| **P2** | `encoach_ai`, `encoach_ai_media` | AI services + media |
| **P2** | `encoach_assignment`, `encoach_classroom` | Assignments + groups |
| **P3** | `encoach_notification` (rules, email delivery, preferences) | User engagement |
| **P3** | Enhanced approval workflows (stages, escalation, bypass) | Governance |
| **P3** | Plagiarism detection (GPTZero integration) | Academic integrity |
| **P3** | Official exam access modes (link, landing, separate login) | Exam security |
| **P3** | Late submission handling, extension requests | Assignment workflow |
| **P3** | `openeducat_exam` (port to v19) + institutional exam endpoints | Institutional assessment |
| **P3** | `openeducat_assignment` (port to v19) + submission endpoints | Homework workflow |
| **P3** | Subject registration endpoints | Student subject selection |
| **P3** | `encoach_training`, analytics endpoints | Training + analytics |
| **P3** | `encoach_sis`, `encoach_branding` | University integration |
| **P4** | `encoach_faq` (categories, items, role-filtered) | User support |
| **P4** | `encoach_subscription` (Stripe, PayPal, Paymob) | Payments |
| **P4** | `encoach_ticket` | Support |
| **P4** | Storage | Operational features |
All modules have been implemented and deployed. The original priority ordering is preserved for reference.
| Priority | Modules | Status |
|----------|---------|--------|
| **P0** | `encoach_core`, `encoach_api` (auth, users, entities, permissions) | **DONE** |
| **P0** | `openeducat_core` (port to v19), `encoach_lms_api` | **DONE** |
| **P1** | `encoach_taxonomy`, `encoach_adaptive`, `encoach_adaptive_api`, `encoach_adaptive_ai` | **DONE** |
| **P1** | `encoach_exam`, `encoach_ai_generation`, `encoach_ai_grading` | **DONE** |
| **P1** | `encoach_resources` | **DONE** |
| **P2** | `encoach_courseware` (chapters, materials, progress, AI workbench) | **DONE** |
| **P2** | `encoach_communication` (discussions, announcements, messaging) | **DONE** |
| **P2** | `openeducat_timetable`, `openeducat_attendance`, `openeducat_classroom` | **DONE** |
| **P2** | `openeducat_admission` + admission endpoints | **DONE** |
| **P2** | Academic years/terms, departments endpoints | **DONE** |
| **P2** | `encoach_ai`, `encoach_ai_media` | **DONE** |
| **P2** | `encoach_assignment`, `encoach_classroom` | **DONE** |
| **P3** | `encoach_notification` (rules, email delivery, preferences) | **DONE** |
| **P3** | Enhanced approval workflows (stages, escalation, bypass) | **DONE** |
| **P3** | Plagiarism detection (GPTZero integration) | **DONE** |
| **P3** | Official exam access modes (link, landing, separate login) | **DONE** |
| **P3** | Late submission handling, extension requests | **DONE** |
| **P3** | `openeducat_exam` + institutional exam endpoints | **DONE** |
| **P3** | `openeducat_assignment` + submission endpoints | **DONE** |
| **P3** | Subject registration endpoints | **DONE** |
| **P3** | `encoach_training`, analytics endpoints | **DONE** |
| **P3** | `encoach_sis`, `encoach_branding` | **DONE** |
| **P4** | `encoach_faq` (categories, items, role-filtered) | **DONE** |
| **P4** | `encoach_subscription` (Stripe, PayPal, Paymob) | **DONE** |
| **P4** | `encoach_ticket` | **DONE** |
| **P4** | Storage | **DONE** |
---
## Appendix A: Complete Endpoint Summary
## 34. Beyond-SRS Features (Implemented)
Total API endpoints: **280+**
The developer implemented the following features beyond the original SRS scope. These leverage OpenEduCat Enterprise modules and add significant institutional management capabilities.
| Service Area | Endpoint Count |
|-------------|---------------|
| Auth & Users | 10 |
| Entities & Permissions | 9 |
| LMS (Courses, Batches, Timetable, Attendance, Grades) | 16 |
| Academic Years, Terms, Departments | 14 |
| Admissions | 12 |
| Subject Registration | 6 |
| EnCoach Exams (AI) | 15 |
| Institutional Exams | 21 |
| EnCoach Assignments | 7 |
| Course Assignments & Submissions | 11 |
| Classrooms & Groups | 7 |
| Taxonomy | 16 |
| Adaptive Learning | 17 |
| Resources | 7 |
| AI Coaching | 6 |
| AI Evaluation | 4 |
| AI Generation | 2 |
| AI Media | 3 |
| AI Analytics | 6 |
| Training | 3 |
| Statistics | 4 |
| Subscriptions & Payments | 8 + 3 webhooks |
| Tickets | 4 |
| Storage | 2 |
| Approval Workflows (Enhanced) | 11 |
| **Courseware (Chapters + Materials + Workbench)** | **23** |
| **Discussion Boards + Posts** | **9** |
| **Announcements** | **5** |
| **Messaging** | **6** |
| **Notifications + Rules + Preferences** | **10** |
| **FAQ (Categories + Items)** | **8** |
| **Plagiarism Detection** | **3** |
| **Official Exam Access** | **5** |
### 34.1 Student Leave Management
**Module:** `openeducat_student_leave_enterprise` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/student_leave.py`
**Frontend:** `student-leave.service.ts` | `AdminStudentLeave.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/student-leaves` | List leave requests |
| `POST` | `/api/student-leaves` | Create leave request |
| `PATCH` | `/api/student-leaves/{id}` | Update leave request |
| `POST` | `/api/student-leaves/{id}/approve` | Approve request |
| `POST` | `/api/student-leaves/{id}/reject` | Reject request |
| `GET` | `/api/student-leave-types` | List leave types |
| `POST` | `/api/student-leave-types` | Create leave type |
### 34.2 Fees Management
**Module:** `openeducat_fees` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/fees.py`
**Frontend:** `fees.service.ts` | `AdminFees.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/fees-plans` | List fee plans |
| `GET` | `/api/fees-plans/{id}` | Fee plan detail |
| `GET` | `/api/student-fees` | Student fee details |
| `GET` | `/api/fees-terms` | Fee terms |
### 34.3 Lessons Management
**Module:** `openeducat_lesson` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/lessons.py`
**Frontend:** `lesson.service.ts` | `AdminLessons.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/lessons` | List lessons |
| `POST` | `/api/lessons` | Create lesson |
| `PATCH` | `/api/lessons/{id}` | Update lesson |
| `DELETE` | `/api/lessons/{id}` | Delete lesson |
### 34.4 Gradebook and Grading Assignments
**Module:** `openeducat_grading` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/gradebook.py`
**Frontend:** `gradebook.service.ts` | `AdminGradebook.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/gradebooks` | List gradebooks |
| `GET` | `/api/gradebook-lines` | Gradebook lines |
| `GET` | `/api/grading-assignments` | List grading assignments |
| `POST` | `/api/grading-assignments` | Create grading assignment |
| `PATCH` | `/api/grading-assignments/{id}` | Update grading assignment |
| `DELETE` | `/api/grading-assignments/{id}` | Delete grading assignment |
### 34.5 Student Progress Tracking
**Module:** `openeducat_student_progress_enterprise` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/student_progress.py`
**Frontend:** `student-progress.service.ts` | `AdminStudentProgress.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/student-progress` | List student progression records |
### 34.6 Library Management
**Module:** `openeducat_library` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/library.py`
**Frontend:** `library.service.ts` | `AdminLibrary.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/library/media` | List media items |
| `POST` | `/api/library/media` | Create media item |
| `DELETE` | `/api/library/media/{id}` | Delete media item |
| `GET` | `/api/library/movements` | List movements |
| `POST` | `/api/library/movements` | Create movement (issue) |
| `PATCH` | `/api/library/movements/{id}` | Update movement |
| `POST` | `/api/library/movements/{id}/return` | Return media |
| `GET` | `/api/library/cards` | List library cards |
| `POST` | `/api/library/cards` | Create library card |
### 34.7 Activity Management
**Module:** `openeducat_activity` (via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/activities.py`
**Frontend:** `activity.service.ts` | `AdminActivities.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/activities` | List activities |
| `POST` | `/api/activities` | Create activity |
| `PATCH` | `/api/activities/{id}` | Update activity |
| `DELETE` | `/api/activities/{id}` | Delete activity |
| `GET` | `/api/activity-types` | List activity types |
| `POST` | `/api/activity-types` | Create activity type |
| `DELETE` | `/api/activity-types/{id}` | Delete activity type |
### 34.8 Facility and Asset Management
**Module:** `openeducat_facility` (extended via `encoach_lms_api`)
**Controller:** `encoach_lms_api/controllers/facilities.py`
**Frontend:** `facility.service.ts` | `AdminFacilities.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/facilities` | List facilities |
| `POST` | `/api/facilities` | Create facility |
| `PATCH` | `/api/facilities/{id}` | Update facility |
| `DELETE` | `/api/facilities/{id}` | Delete facility |
| `GET` | `/api/assets` | List assets |
| `POST` | `/api/assets` | Create asset |
| `DELETE` | `/api/assets/{id}` | Delete asset |
### 34.9 Roles CRUD, User Role Assignment, and Authority Matrix
**Module:** `encoach_core` (extended)
**Controller:** `encoach_api/controllers/roles.py`
**Frontend:** `entities.service.ts` | `RolesPermissions.tsx`, `UserRoles.tsx`, `AuthorityMatrix.tsx`
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/roles` | List all roles |
| `POST` | `/api/roles` | Create role |
| `GET` | `/api/roles/{id}` | Get role detail |
| `PATCH` | `/api/roles/{id}` | Update role |
| `DELETE` | `/api/roles/{id}` | Delete role |
| `PATCH` | `/api/roles/{id}/permissions` | Update role permissions |
| `GET` | `/api/permissions` | List all permissions |
| `POST` | `/api/permissions` | Create permission |
| `DELETE` | `/api/permissions/{id}` | Delete permission |
| `GET` | `/api/users/with-roles` | List users with roles |
| `GET/PATCH` | `/api/users/{id}/roles` | Get/update user roles |
| `POST` | `/api/users/{id}/roles/toggle` | Toggle role for user |
| `GET` | `/api/authority-matrix` | Get role-permission matrix |
| `POST` | `/api/authority-matrix/toggle` | Toggle a matrix cell |
| `GET` | `/api/user-authority-matrix` | Get user-level authority |
---
## Appendix A: Complete Endpoint Summary (Verified Against Deployment)
Total API endpoints: **~377** (deployed across 4 controller packages)
| Controller Package | Route Count | Service Areas |
|-------------------|-------------|---------------|
| `encoach_api` | ~120 | Auth, users, entities, roles, exams, assignments, classrooms, storage, stats, subscriptions, tickets, approvals, training, generation, AI analytics |
| `encoach_lms_api` | ~209 | Courses, students, teachers, batches, timetable, attendance, grades, departments, academic, admissions, subject registration, institutional exams, course assignments, student leave, fees, lessons, gradebook, student progress, library, activities, facilities, notifications, FAQ, courseware, plagiarism, communication, classrooms |
| `encoach_adaptive_api` | ~41 | Taxonomy (subjects, domains, topics), diagnostic, proficiency, learning plans, content, coaching |
| `encoach_resources` | ~7 | Learning resources (CRUD, download, complete, rate) |
**Breakdown by Service Area:**
| Service Area | Endpoint Count | Status |
|-------------|---------------|--------|
| Auth & Users | 10 | Deployed |
| Entities & Permissions | 9 | Deployed |
| Roles CRUD & Authority Matrix | 12 | **Deployed (Beyond SRS)** |
| LMS (Courses, Batches, Timetable, Attendance, Grades) | 16 | Deployed |
| Academic Years, Terms, Departments | 14 | Deployed |
| Admissions | 12 | Deployed |
| Subject Registration | 6 | Deployed |
| EnCoach Exams (AI) | 15 | Deployed |
| Institutional Exams | 21 | Deployed |
| EnCoach Assignments | 7 | Deployed |
| Course Assignments & Submissions | 11 | Deployed |
| Classrooms & Groups | 7 | Deployed |
| Taxonomy | 16 | Deployed |
| Adaptive Learning | 17 | Deployed |
| Resources | 7 | Deployed |
| AI Coaching | 6 | Deployed |
| AI Evaluation | 4 | Deployed |
| AI Generation | 2 | Deployed |
| AI Media | 3 | Deployed |
| AI Analytics | 6 | Deployed |
| Training | 3 | Deployed |
| Statistics | 4 | Deployed |
| Subscriptions & Payments | 8 + 3 webhooks | Deployed |
| Tickets | 4 | Deployed |
| Storage | 2 | Deployed |
| Approval Workflows (Enhanced) | 11 | Deployed |
| Courseware (Chapters + Materials + Workbench) | 23 | Deployed |
| Discussion Boards + Posts | 9 | Deployed |
| Announcements | 5 | Deployed |
| Messaging | 6 | Deployed |
| Notifications + Rules + Preferences | 10 | Deployed |
| FAQ (Categories + Items) | 8 | Deployed |
| Plagiarism Detection | 3 | Deployed |
| Official Exam Access | 5 | Deployed |
| Student Leave Management | 7 | **Deployed (Beyond SRS)** |
| Fees Management | 4 | **Deployed (Beyond SRS)** |
| Lessons Management | 4 | **Deployed (Beyond SRS)** |
| Gradebook & Grading | 6 | **Deployed (Beyond SRS)** |
| Student Progress | 1 | **Deployed (Beyond SRS)** |
| Library Management | 9 | **Deployed (Beyond SRS)** |
| Activity Management | 7 | **Deployed (Beyond SRS)** |
| Facility & Asset Management | 7 | **Deployed (Beyond SRS)** |
---
@@ -1756,4 +1956,4 @@ res.users ──extends──> encoach.user
---
*This SRS is the definitive backend specification for the EnCoach platform on Odoo 19. It covers all 280+ REST API endpoints expected by the React frontend, 35 Odoo modules (8 OpenEduCat + 27 custom), and all AI service integrations.*
*This SRS is the definitive backend specification for the EnCoach platform on Odoo 19. All ~377 REST API endpoints, 41 Odoo modules (14 OpenEduCat + 27 custom), and all AI service integrations have been implemented and deployed to staging at `http://5.189.151.117:8069`. All previous backend SRS documents (`ODOO_BACKEND_SRS_v3.md`, `ODOO_MIGRATION_SRS_v2.md`, `ODOO_MIGRATION_SRS.md`) are superseded by this document.*

View File

@@ -0,0 +1,308 @@
# EnCoach Platform -- System Features Guide
**Version:** 1.0
**Date:** March 2026
**Purpose:** Describe every section and feature accessible through the platform navigation, organized by user role.
---
## Part 1: Administrator Panel
The Administrator Panel is the central management hub for the entire platform. It is accessible to users with roles: Admin, Corporate, Master Corporate, Agent, and Developer.
---
### 1. Overview
The Overview section provides high-level dashboards that give administrators an at-a-glance view of the entire platform's health and activity.
| Menu Item | Description |
|-----------|-------------|
| **Admin Dashboard** | The LMS-focused dashboard showing real-time counts of courses, students, teachers, batches, and enrollment status. Displays course capacity charts, student status distribution, and recent activity. |
| **Platform Dashboard** | The original platform dashboard focused on exam and assignment activity. Shows exam creation statistics, assignment completion rates, user activity trends, and entity-level performance summaries. |
---
### 2. LMS
The LMS (Learning Management System) section is the core of institutional course management. It handles the full lifecycle of courses, students, teachers, and class scheduling.
| Menu Item | Description |
|-----------|-------------|
| **Courses** | Create, view, and manage courses. Each course has a title, code, description, maximum capacity, status (draft/active/archived), and is linked to a department. Administrators can view enrollment counts and manage course settings. |
| **Students** | Manage student records. Create new students (which automatically creates a portal user account), view student lists with filters, export student data, and manage individual student profiles including their course enrollments. |
| **Teachers** | Manage teacher records. Create teacher profiles with specialization areas, link them to portal user accounts, assign them to courses and batches, and view their teaching schedules. |
| **Batches** | Manage class batches (sections/cohorts). Each batch belongs to a course and has a date range, capacity, and enrolled students. Administrators can view batch details, manage student enrollment per batch, and track batch capacity. |
| **Lessons** | Create and manage individual lessons linked to a course, batch, and subject. Each lesson has a faculty member, date, and duration. Used to organize the day-to-day teaching schedule within a course. |
| **Timetable** | Visual timetable management with a day/time grid. Create, view, and delete teaching sessions. Sessions are linked to courses, batches, subjects, and classrooms with specific day and time slots. |
| **Reports** | LMS-specific reporting dashboards showing course enrollment trends, batch capacity utilization, student status distributions, teacher workload, and overall LMS usage analytics. |
---
### 3. Adaptive Learning
The Adaptive Learning section manages the AI-powered personalized learning engine. It controls the knowledge structure that drives diagnostic tests, proficiency tracking, and personalized learning plans.
| Menu Item | Description |
|-----------|-------------|
| **Taxonomy** | Manage the subject knowledge hierarchy: Subjects (e.g., English, Math, IT) contain Domains, which contain Topics, which contain Learning Objectives. This taxonomy drives the adaptive engine -- diagnostic tests assess proficiency at the topic level, and learning plans are generated based on this structure. Administrators can create subjects, add domains/topics manually, or use AI to suggest topic structures. |
| **Resources** | Manage the learning resource library. Upload educational materials (PDFs, videos, links, documents, interactive content) and tag them to specific topics in the taxonomy. Resources go through a review workflow (pending, approved, rejected) and are served to students through their personalized learning plans. Track resource downloads, completion, and ratings. |
---
### 4. Institutional
The Institutional section handles university-level academic administration -- the calendar, departments, enrollment pipeline, formal exam sessions, grading, and student lifecycle.
| Menu Item | Description |
|-----------|-------------|
| **Academic Years** | Define academic years with start and end dates. Auto-generate academic terms (semesters/quarters) within each year. Academic years organize all institutional activities -- courses, batches, exams, and grades are all scoped to an academic year. |
| **Departments** | Manage the department hierarchy with parent-child relationships. Departments organize courses and faculty. Each department can have sub-departments, a head of department, and associated courses. |
| **Admissions** | View and process individual student admission applications. Each admission goes through a workflow: submitted, confirmed, admitted, or rejected. Administrators can review application details, update status, and convert admitted applicants into enrolled students. |
| **Admission Register** | Manage admission campaigns/registers. Each register defines an admission period (open/closed), linked course, available seats, and start/end dates. Registers go through a workflow: create, confirm (open for applications), close (stop accepting). |
| **Exam Sessions** | Schedule and manage institutional exam sessions. Each session is linked to a course, batch, and academic term. Sessions go through a workflow: draft, scheduled, in progress, done. Manage exam rooms, attendees, and timing within each session. |
| **Marksheets** | Generate and validate student marksheets (grade reports). Marksheets aggregate student scores across exams within a session, apply grade configurations and result templates, and compute pass/fail status. Supports validation workflow before official release. |
| **Student Leave** | Manage student leave requests. Students submit leave requests with reasons and dates; administrators or teachers can approve or reject them. Tracks leave history per student. |
| **Fees** | View fee plans, fee terms, and individual student fee records. Manage fee structures attached to courses, including installment plans and payment tracking. |
| **Gradebook** | View and manage the institutional grading system. Displays grades per student, per course, and per academic year. Supports grading assignment types, weighted grading, and grade configuration (letter grades, percentage scales). |
| **Student Progress** | Track longitudinal student progress across courses, subjects, and academic terms. Provides a historical view of student performance, showing trends and areas that need attention. |
---
### 5. Academic
The Academic section manages the AI-powered exam engine -- creating exams, defining grading rubrics, generating content with AI, and managing the approval workflow for publishing exams.
| Menu Item | Description |
|-----------|-------------|
| **Assignments** | Create and manage exam-linked assignments. Each assignment wraps an exam and assigns it to specific students or classrooms with deadlines. Supports tabs for Active, Planned, Past, and Archived assignments. Includes late submission policies, extension requests, penalty configuration, and reminder settings. |
| **Exams List** | Browse, search, and manage all exams in the system. Filter by subject, module (Reading, Writing, Listening, Speaking), and difficulty. Each exam contains exercises, passages, timer settings, and access controls (public/private). Supports both practice exercises and official exams. |
| **Exam Structures** | Define exam blueprints (templates) that specify the section layout of exams -- how many sections, what type of questions in each, difficulty distribution, and time allocation per section. Structures are reusable across multiple exams. |
| **Rubrics** | Create and manage grading rubrics that define the criteria for evaluating student responses. Rubrics specify scoring dimensions (e.g., Task Achievement, Coherence, Grammar for IELTS writing). Rubric groups organize related rubrics. Used by both human graders and the AI grading engine. |
| **Generation** | The AI exam generation interface. Select a subject, module, and topic; configure difficulty and question types; and let the AI (GPT-4o) generate complete exams with passages, questions, and answer keys. Supports generation from scratch or from existing content. |
| **Approval Workflows** | Manage the approval process for publishing exams and course materials. Configure multi-stage workflows with specific approvers, time limits per stage, auto-escalation rules, and bypass options. Track approval status (pending, approved, rejected, escalated) with comments through each stage. |
---
### 6. Management
The Management section handles platform-wide user, organization, and infrastructure management.
| Menu Item | Description |
|-----------|-------------|
| **Users** | Full user management. Create, update, search, filter, and export users. View user details including role, entity, verification status, and activity history. Supports batch user import from spreadsheets. |
| **Entities** | Manage organizations (multi-tenant). Each entity is an institution or company using the platform. Configure entity settings, manage entity-specific roles and permissions, generate invite codes for onboarding, and set per-entity branding (logo, colors). |
| **Classrooms** | Manage virtual and physical classroom groups. Create classrooms with capacity tracking, assign students to classrooms, and use classrooms for assigning exams and assignments to groups of students. |
| **Roles & Permissions** | Create and manage roles within entities. Each role has a name and a set of granular permissions. Administrators can create custom roles, assign/remove permissions from roles, and manage the permission catalog. |
| **Authority Matrix** | A cross-reference visualization of all roles and their permissions. Displayed as an interactive grid where rows are roles and columns are permissions. Administrators can toggle permissions on/off directly from the matrix view. |
| **User Roles** | Assign roles to individual users. View all users with their current role assignments, search and filter, and assign or remove roles. Supports user-level permission overrides beyond their assigned role. |
---
### 7. Reports
The Reports section provides analytical views of platform performance and student outcomes.
| Menu Item | Description |
|-----------|-------------|
| **Student Performance** | Detailed performance analytics per student. Shows exam scores, assignment completion rates, proficiency levels across subjects, and trends over time. Supports filtering by entity, course, and date range. |
| **Stats Corporate** | Entity-level statistics for corporate/institutional managers. Shows aggregated data across all students within an entity -- enrollment counts, average scores, completion rates, and comparative performance across courses. |
| **Record** | Historical activity records. Browse past exam sessions, assignment submissions, and user activity logs. Supports searching and filtering by date, user, and activity type. |
---
### 8. Configuration
The Configuration section manages platform-wide settings for notifications, FAQs, and approval processes.
| Menu Item | Description |
|-----------|-------------|
| **FAQ Manager** | Create and manage Frequently Asked Questions. Organize FAQs into categories, set target audience per item (student, entity, or both), add rich content including text, images, and video links. FAQs are displayed on a public searchable page with accordion-style expand/collapse. |
| **Notification Rules** | Configure automated notification triggers. Define rules based on event types (assignment due, exam due, chapter unlock, result release), set timing (how many days before the event), frequency (once, daily, custom intervals), and delivery channel (in-app, email, or both). |
| **Approval Config** | Configure the enhanced approval workflow system. Define multi-stage approval templates with specific approvers per stage, maximum days before auto-escalation, notification emails, and bypass permissions. Applied to exam publishing and course material approval. |
---
### 9. Training
The Training section provides reference materials for language learning support.
| Menu Item | Description |
|-----------|-------------|
| **Vocabulary** | Browse vocabulary training content. Displays categorized vocabulary lists, definitions, usage examples, and related exercises. Linked to the FAISS-based recommendation engine for contextual suggestions. |
| **Grammar** | Browse grammar training content. Displays grammar rules, examples, common mistakes, and practice exercises organized by topic and difficulty level. |
---
### 10. Support
The Support section handles financial tracking, user support, and system settings.
| Menu Item | Description |
|-----------|-------------|
| **Payment Record** | View payment history and transaction records. Shows all subscription payments, amounts, providers (Stripe/PayPal/Paymob), status, and associated packages. Supports filtering by date, user, and payment status. |
| **Tickets** | Manage support tickets. View all tickets submitted by users, assign tickets to support agents, update ticket status (open, in progress, resolved, closed), and communicate with ticket reporters. |
| **Settings** | Platform-wide settings management. Configure system parameters, AI service settings (API keys stored securely), default behaviors, and platform-level preferences. |
---
### 11. Other Admin Pages (Accessible but not in main sidebar)
| Page | Description |
|------|-------------|
| **Library** | Manage the institutional library. CRUD operations for library media (books, journals, digital resources), track media movements (issue, return), and manage student library cards. |
| **Activities** | Log and track student activities. Define activity types and record student participation in extracurricular or academic activities outside the standard course structure. |
| **Facilities** | Manage institutional facilities and assets. Track rooms, equipment, and other physical resources used for teaching and examinations. |
---
## Part 2: Teacher Panel
The Teacher Panel provides instructors with tools to manage their courses, create content, track student progress, and communicate with their classes.
---
### 1. Teaching
The Teaching section is the teacher's primary workspace for delivering courses and managing assignments.
| Menu Item | Description |
|-----------|-------------|
| **Dashboard** | The teacher's home screen showing an overview of their assigned courses, upcoming assignments, recent student submissions, and quick statistics (number of students, pending grading, upcoming sessions). |
| **Courses** | View and manage assigned courses. From here, teachers can access three key sub-pages per course: **Chapters** (organize course content into sequential chapters with materials, set unlock dates, and control access), **Chapter Detail** (upload and manage materials within a chapter -- PDFs, videos, audio, images, links -- with download permission controls), and **AI Workbench** (generate course content using AI by inputting topic, objectives, and complexity level; review and publish AI-generated chapters, materials, exercises, and rubrics). |
| **Assignments** | Create and manage assignments for classes. Define deadlines, late submission policies, penalty structures, and reminder frequencies. View assignment submissions, check plagiarism reports, grade with AI assistance, and release results. Drill into individual assignments to see per-student submission status and grading. |
---
### 2. Management
The Management section gives teachers tools to track student attendance and schedules.
| Menu Item | Description |
|-----------|-------------|
| **Attendance** | Take and manage attendance for classes. Mark students as present, absent, or late for each session. View attendance history and trends per batch. |
| **Students** | View the list of students enrolled in the teacher's courses and batches. Access individual student profiles and performance summaries. |
| **Timetable** | View the teacher's personal teaching schedule in a visual day/time grid format. Shows all assigned sessions across courses and batches. |
---
### 3. Communication
The Communication section enables teacher-student interaction and class announcements.
| Menu Item | Description |
|-----------|-------------|
| **Discussions** | View and manage discussion boards for courses. Teachers can enable/disable discussion boards per course or chapter, create discussion threads, reply to student questions, pin important posts, and mark questions as resolved. Supports file attachments. |
| **Announcements** | Create and broadcast announcements to classes. Set priority (normal, important, urgent), target specific courses or batches, optionally send via email in addition to in-app notification. Manage drafts and publish when ready. |
---
### 4. Account
| Menu Item | Description |
|-----------|-------------|
| **Profile** | View and update personal profile information (name, email, specialization, contact details). |
---
## Part 3: Student Panel
The Student Panel provides learners with access to their courses, adaptive learning engine, progress tracking, and communication tools.
---
### 1. Learning
The Learning section is the student's primary workspace for accessing courses and completing assignments.
| Menu Item | Description |
|-----------|-------------|
| **Dashboard** | The student's home screen showing enrolled subjects, upcoming deadlines (assignments, quizzes, exams), recent announcements, personal progress statistics, and AI study tips. Includes an AI coaching assistant for on-demand help. |
| **My Courses** | Browse all enrolled courses. Each course shows its chapters, completion progress, and available materials. Students can navigate into individual courses to see the chapter structure, access unlocked chapter content, download materials (when permitted by the teacher), and track their progress through the course. |
| **Subject Registration** | Register for available subjects within the current academic term. View available subjects, prerequisites, and capacity. Submit registration requests for subjects the student wants to take. |
| **Assignments** | View all active, upcoming, and past assignments. Submit completed work through the platform, view deadlines and submission status, request deadline extensions (when allowed), track submission history, and receive AI-generated feedback and plagiarism reports. |
---
### 2. Adaptive Learning
The Adaptive Learning section provides AI-powered personalized education that adapts to each student's level.
| Menu Item | Description |
|-----------|-------------|
| **My Subjects** | The entry point for the adaptive learning engine. Displays all subjects the student is studying with their overall mastery level. From here, students can: take a **Diagnostic Test** (AI-administered assessment to determine initial proficiency across topics), view their **Proficiency Profile** (detailed breakdown of mastery per topic within a subject), access their **Learning Plan** (AI-generated personalized study path with ordered topics based on proficiency gaps), and study individual **Topics** (AI-curated learning content with practice exercises and mastery quizzes that adapt difficulty based on performance). |
---
### 3. Progress
The Progress section shows academic performance, attendance, and the overall learning journey.
| Menu Item | Description |
|-----------|-------------|
| **Grades** | View grades for all courses, assignments, and exams. Shows current marks, feedback from teachers, and detailed score breakdowns by grading criteria. |
| **Attendance** | View personal attendance records across all enrolled courses. Shows attendance percentage, absent dates, and any leave requests with their approval status. |
| **Timetable** | View personal class schedule in a visual day/time grid. Shows all upcoming sessions with course, subject, teacher, and room information. |
| **My Journey** | A longitudinal progress timeline showing the student's overall academic journey. Displays enrolled courses with completion percentages, per-subject proficiency trends, and a recent activity timeline (exams taken, assignments submitted, chapters completed). Provides a holistic view of growth over time. |
---
### 4. Communication
The Communication section enables students to interact with teachers and classmates.
| Menu Item | Description |
|-----------|-------------|
| **Discussions** | Participate in course and chapter discussion boards. Create new discussion threads, reply to existing threads (nested replies), ask questions about assignments or course content, and view pinned/resolved posts. Students can see other participants within the same class. |
| **Messages** | Direct messaging between users. View inbox (with read/unread indicators and unread count badge), send messages to teachers or classmates within the same class, attach files, and optionally send an email copy. Includes a sent messages view. |
| **Announcements** | View announcements from teachers and system administrators. Announcements are displayed with priority indicators (urgent, important, normal) and sorted by date. |
---
### 5. Account
| Menu Item | Description |
|-----------|-------------|
| **Profile** | View and update personal profile information (name, email, contact details, preferences). |
---
## Part 4: Public Pages (No Login Required)
These pages are accessible without authentication.
| Page | Description |
|------|-------------|
| **Login** | User authentication with email and password. Redirects to the appropriate dashboard based on user role after successful login. |
| **Register** | New user registration. Supports open registration or invite-code-based registration to join a specific entity with a predefined role. |
| **Forgot Password** | Password recovery via email. Users enter their email to receive a verification link for password reset. |
| **Admission Application** | Public admission form for prospective students. Users can apply to an open admission register without logging in, providing personal details and required documents. They can check application status afterward. |
| **FAQ** | Public Frequently Asked Questions page. Searchable, accordion-style display of FAQ items organized by category. Content is filtered based on the user's role (student or entity) if logged in, showing all items if accessed publicly. |
| **Official Exam Access** | Special exam access pages for official/proctored exams. Supports three modes: (1) token-based link access where students open a unique URL, (2) landing page access with an exam code, and (3) a dedicated exam login screen isolated from the rest of the platform. |
---
## Part 5: AI Features (Embedded Across the Platform)
AI capabilities are embedded throughout the platform rather than being a standalone section. Here is where AI appears:
| Feature | Where It Appears | What It Does |
|---------|-----------------|-------------|
| **AI Study Coach** | Student Dashboard | Chat-based coaching assistant that provides hints, concept explanations, writing help, and study tips. |
| **AI Exam Generation** | Admin > Generation, Teacher > AI Workbench | Generates complete exams (passages, questions, answer keys) from subject taxonomy using GPT-4o. |
| **AI Grading** | Admin > Assignments, Teacher > Assignments | Automatically grades writing (rubric-based IELTS band scoring), speaking (transcription + evaluation), math (step evaluation), and IT (code evaluation) using GPT-4o. |
| **AI Course Content** | Teacher > AI Workbench | Generates course outlines, chapter content, exercises, and grading rubrics from high-level requirements. |
| **AI Diagnostics** | Student > My Subjects | Administers adaptive diagnostic tests that adjust question difficulty based on responses to accurately assess proficiency. |
| **AI Learning Plans** | Student > My Subjects | Generates personalized learning plans based on diagnostic results and proficiency gaps. |
| **AI Content Recommendations** | Student > Topic Learning | Suggests additional learning materials based on student performance and learning history using FAISS similarity search. |
| **AI Plagiarism Detection** | Teacher > Assignments, Admin > Assignments | Analyzes submitted text using GPTZero to detect AI-generated content, providing per-sentence analysis and downloadable reports. |
| **AI Search** | Admin Header Bar | Semantic search across the platform using AI. |
| **AI Analytics** | Admin > Reports | Generates narrative reports, identifies content gaps, and provides batch optimization suggestions. |
| **AI Tip Banner** | Student Dashboard | Context-aware training tips selected using FAISS-based recommendation. |
| **Text-to-Speech** | Listening Exams | Converts exam text to natural speech using AWS Polly (11 neural voices). |
| **Speech-to-Text** | Speaking Exams | Transcribes student speaking responses using local Whisper model. |
| **AI Avatar Videos** | Speaking Exams | Generates avatar-based video prompts for speaking exams using ELAI. |
---
*End of System Features Guide*

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,10 @@
# Math & IT Adaptive Learning System -- Software Requirements Specification
> **SUPERSEDED** -- This document has been merged into `ENCOACH_UNIFIED_SRS.md` (v2.0). The adaptive learning engine for Math and IT is now part of the unified platform specification (Part II: Universal Subject Engine, sections 6-11). All features have been implemented and deployed.
**Document Version:** 1.0
**Date:** March 16, 2026
**Status:** Draft -- Architect Review
**Status:** ~~Draft -- Architect Review~~ **SUPERSEDED**
**Author:** EnCoach Engineering Team
**Audience:** Architect (initial review), then development team

View File

@@ -1,8 +1,10 @@
# EnCoach Odoo 19 Backend -- Developer SRS v3
> **SUPERSEDED** -- This document has been replaced by `ENCOACH_ODOO19_BACKEND_SRS.md` (v3.0) and `ENCOACH_UNIFIED_SRS.md` (v2.0). All content below is historical. The developer has implemented everything and the system is deployed at `http://5.189.151.117:8069`.
**Document Version:** 3.0
**Date:** March 11, 2026
**Status:** Active -- Ready for Development
**Status:** ~~Active -- Ready for Development~~ **SUPERSEDED**
**Supersedes:** `ODOO_MIGRATION_SRS_v2.md` (v2.0)
**Master Reference:** `ENCOACH_UNIFIED_SRS.md` (v1.0)
**Author:** EnCoach Architecture Team

View File

@@ -0,0 +1,100 @@
# Odoo Developer Handoff — Implementation Complete
**Status:** All deliverables implemented and deployed to staging.
**Date:** March 11, 2026
---
## 1. Current Repositories
| Repository | URL | Description |
|-----------|-----|-------------|
| **Frontend v2** | `https://git.albousalh.com/devops/encoach_frontend_new_v2.git` | React 18 SPA (93 pages, 37 services, 29 types) |
| **Backend v2** | `https://git.albousalh.com/devops/encoach_backend_new_v2.git` | Odoo 19 backend (27 custom + 14 OpenEduCat = 41 modules) |
**Note:** The older repositories (`encoach_frontend_new_v1`, `encoach_be_odoo19`, `ielts-be-v0`) are superseded. All development should continue in the v2 repositories above.
---
## 2. Staging Environment
| Service | URL |
|---------|-----|
| **Frontend** | `http://5.189.151.117:3000` |
| **Backend (Odoo 19)** | `http://5.189.151.117:8069` |
Deployment is automated via Git post-receive hooks. Push to `main` triggers rebuild.
---
## 3. Documentation
| Document | Status | Description |
|----------|--------|-------------|
| `ENCOACH_UNIFIED_SRS.md` (v2.0) | **Current** | Unified frontend + backend SRS with implementation traceability |
| `ENCOACH_ODOO19_BACKEND_SRS.md` (v3.0) | **Current** | Backend-specific SRS with all API contracts and data models |
| `ENCOACH_PRODUCT_DESCRIPTION.md` | **Current** | Non-technical product description |
| `ENCOACH_SYSTEM_FEATURES_GUIDE.md` | **Current** | System features guide by sidebar section |
| `ODOO_BACKEND_SRS_v3.md` | **Superseded** | Replaced by `ENCOACH_ODOO19_BACKEND_SRS.md` v3.0 |
| `ODOO_MIGRATION_SRS_v2.md` | **Superseded** | Replaced by `ENCOACH_ODOO19_BACKEND_SRS.md` v3.0 |
| `ODOO_MIGRATION_SRS.md` | **Superseded** | Replaced by `ENCOACH_ODOO19_BACKEND_SRS.md` v3.0 |
| `ODOO_MIGRATION_FRONTEND_SRS.md` | **Superseded** | Replaced by `ENCOACH_UNIFIED_SRS.md` v2.0 |
---
## 4. What Was Implemented
### Frontend (93 page components)
- **28 root pages** -- login, register, FAQ, exam runner, etc.
- **33 admin pages** -- full LMS/platform administration
- **19 student pages** -- courses, adaptive learning, communication
- **14 teacher pages** -- course builder, AI workbench, grading
- **37 API service modules** calling ~280+ backend endpoints
- **14 AI components** wired to real backend AI services
### Backend (41 Odoo modules, ~377 API routes)
- **`encoach_api`** -- 16 controller files, ~120 routes (auth, users, entities, roles, exams, assignments, classrooms, stats, subscriptions, tickets, approvals, training, generation, AI analytics)
- **`encoach_lms_api`** -- 28 controller files, ~209 routes (courses, students, teachers, batches, timetable, attendance, grades, departments, academic, admissions, subject registration, institutional exams, course assignments, student leave, fees, lessons, gradebook, student progress, library, activities, facilities, notifications, FAQ, courseware, plagiarism, communication)
- **`encoach_adaptive_api`** -- 6 controller files, ~41 routes (taxonomy, diagnostic, proficiency, learning plans, content, coaching)
- **`encoach_resources`** -- 1 controller file, ~7 routes (resource CRUD)
### Beyond Original SRS
The developer also implemented:
- Student Leave Management (types, requests, approve/reject)
- Fees Management (plans, student fees, terms)
- Lessons Management (timetable-linked)
- Gradebook and Grading Assignments
- Student Progress Tracking (aggregate)
- Library Management (media, movements, cards)
- Activity Management (configurable types)
- Facility and Asset Management
- Roles CRUD, User Role Assignment, Authority Matrix
---
## 5. AI Service Credentials
The developer needs API keys for:
| Service | Purpose |
|---------|---------|
| **OpenAI** | GPT-4o and Whisper -- grading, coaching, content generation, speech-to-text |
| **AWS Polly** | Text-to-speech (neural voices) |
| **ELAI** | AI avatar video generation |
| **GPTZero** | AI writing detection |
These are in `06-All-Credentials-Inventory.md` locally. Keys must be provided **separately** -- never committed to the git repo. On staging, they are in `/opt/encoach/backend-v2/.env`.
---
## 6. Frontend Code Reference
For any new backend development, the frontend contract is defined in:
- **`src/services/*.ts`** (37 files) -- every URL path, request body shape, and response handling
- **`src/types/*.ts`** (29 files) -- all TypeScript interfaces the frontend expects from the API
- **`src/hooks/queries/*.ts`** (21 files) -- TanStack Query cache keys and query configurations

View File

@@ -0,0 +1,910 @@
# EnCoach Frontend API Migration SRS
> **SUPERSEDED** -- This document has been replaced by `ENCOACH_UNIFIED_SRS.md` (v2.0). The migration is complete. The old `ielts-ui` Next.js frontend has been replaced by `encoach_frontend_new_v2` (React 18 + Vite + TypeScript), deployed at `http://5.189.151.117:3000`.
## ielts-ui Migration Guide: Next.js API Routes to Odoo 19
**Version:** 1.0
**Date:** March 11, 2026
**Status:** ~~Active~~ **SUPERSEDED**
**Audience:** Frontend developer(s) maintaining ielts-ui
**Companion document:** `ODOO_MIGRATION_SRS.md` (backend Odoo specification)
---
## Table of Contents
1. [Migration Overview](#1-migration-overview)
2. [Authentication Migration](#2-authentication-migration)
3. [API Base URL Change](#3-api-base-url-change)
4. [Endpoint-by-Endpoint Migration Map](#4-endpoint-by-endpoint-migration-map)
5. [SSR Migration Strategy](#5-ssr-migration-strategy)
6. [Files to Delete](#6-files-to-delete)
7. [Migration Checklist](#7-migration-checklist)
---
## 1. Migration Overview
### 1.1 What Is Changing
The ielts-ui Next.js application currently serves two roles:
1. **Browser UI** -- React pages, components, Zustand stores, hooks
2. **BFF (Backend-for-Frontend)** -- 108 API route files in `src/pages/api/` that query MongoDB directly, manage iron-session cookies, and proxy AI requests
After migration, ielts-ui serves **only the Browser UI**. All backend logic moves to Odoo 19. The `src/pages/api/` directory and all server-side database utilities are eliminated entirely.
### 1.2 Current Architecture (what the frontend sees)
```
Browser (React)
├── axios/SWR/fetch calls to /api/* (same origin)
└── Next.js API Routes (src/pages/api/)
├── iron-session cookie auth
├── MongoDB queries (via src/utils/*.be.ts)
└── Proxy to AI backend (via BACKEND_URL)
```
### 1.3 Target Architecture (what the frontend sees)
```
Browser (React)
├── axios/SWR/fetch calls to ODOO_URL/api/* (cross-origin)
│ └── Authorization: Bearer <JWT>
└── Odoo 19 (separate service)
├── JWT auth
├── PostgreSQL (replaces MongoDB)
└── All AI/ML handled internally by Odoo
```
### 1.4 What Does NOT Change
- All React page components, layouts, and UI rendering
- Zustand stores (`src/stores/exam/`, `src/stores/preferencesStore.ts`, etc.)
- All components in `src/components/` (they still call the same API shapes -- only the base URL and auth mechanism change)
- Styling (Tailwind, DaisyUI)
- TypeScript interfaces in `src/interfaces/`
- Client-side routing
- Strapi CMS and the landing page
### 1.5 Guiding Principle
Odoo's REST API is designed to return the **same JSON shapes** the frontend currently expects. If the frontend calls `GET /api/users/list` and expects `{ users: [...], total: N }`, Odoo's `GET /api/users/list` returns the same shape. The migration is primarily a **transport change** (base URL + auth header), not a data format change.
---
## 2. Authentication Migration
This is the most significant structural change.
### 2.1 Current Auth Pattern
| Aspect | Current Implementation |
|--------|----------------------|
| **Identity provider** | Firebase Auth (`signInWithEmailAndPassword`) |
| **Session** | iron-session (encrypted httpOnly cookie named `eCrop/ielts`) |
| **Client auth** | Automatic -- browser sends cookie on same-origin requests |
| **SSR auth** | `withIronSessionSsr` + `getServerSideProps` reads `req.session.user` |
| **User hook** | `useUser()` calls `GET /api/user` via SWR; cookie sent automatically |
| **Config** | `src/lib/session.ts` (`SECRET_COOKIE_PASSWORD`, `cookieName`) |
### 2.2 Target Auth Pattern
| Aspect | Target Implementation |
|--------|----------------------|
| **Identity provider** | Odoo 19 native auth (`res.users`) |
| **Session** | JWT token issued by Odoo |
| **Client auth** | `Authorization: Bearer <token>` header on every request |
| **SSR auth** | JWT stored in httpOnly cookie; `getServerSideProps` reads cookie and calls Odoo |
| **User hook** | `useUser()` calls `GET ODOO_URL/api/user` with JWT header |
| **Config** | `NEXT_PUBLIC_API_URL` env var |
### 2.3 New Auth Infrastructure
Create a new file `src/lib/api.ts`:
```typescript
import axios from "axios";
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
withCredentials: true,
});
api.interceptors.request.use((config) => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
clearToken();
if (typeof window !== "undefined") {
window.location.href = "/login";
}
}
return Promise.reject(error);
}
);
export default api;
```
JWT storage helpers (also in `src/lib/api.ts` or a separate `src/lib/auth.ts`):
```typescript
import Cookies from "js-cookie";
const TOKEN_KEY = "encoach_token";
export function setToken(token: string) {
Cookies.set(TOKEN_KEY, token, { secure: true, sameSite: "lax" });
}
export function getToken(): string | undefined {
return Cookies.get(TOKEN_KEY);
}
export function clearToken() {
Cookies.remove(TOKEN_KEY);
}
```
**Note:** Using a cookie for JWT storage (rather than localStorage) is recommended because `getServerSideProps` can read cookies from the request headers, enabling SSR auth. The cookie is NOT httpOnly in this approach (so JS can read it for the axios interceptor). If httpOnly is required, use a thin proxy or Next.js middleware to inject the header.
### 2.4 Files That Change for Auth
| File | Current | Target |
|------|---------|--------|
| `src/pages/login.tsx` | `axios.post("/api/login", { email, password })` | `api.post("/api/login", { email, password })` -- store JWT from response |
| `src/pages/register.tsx` | `fetch` to `/api/register` (SSR) + code lookup | `api.post("/api/register", payload)` -- store JWT from response |
| `src/pages/official-exam.tsx` | `axios.post("/api/logout")` | `api.post("/api/logout")` + `clearToken()` |
| `src/components/Sidebar.tsx` | `axios.post("/api/logout")` | `api.post("/api/logout")` + `clearToken()` |
| `src/components/MobileMenu.tsx` | `axios.post("/api/logout")` | `api.post("/api/logout")` + `clearToken()` |
| `src/utils/email.ts` | `axios.post("/api/reset/sendVerification")` | `api.post("/api/reset/sendVerification")` |
| `src/hooks/useUser.tsx` | SWR fetcher uses `axios.get("/api/user")` | SWR fetcher uses `api.get("/api/user")` |
| `src/lib/session.ts` | iron-session config | **DELETE** -- replaced by `src/lib/api.ts` |
### 2.5 Login Flow Change
**Current:**
1. User submits email + password
2. `POST /api/login` (same origin)
3. API route calls Firebase Auth, looks up user in MongoDB, saves to iron-session
4. Response: user JSON + `Set-Cookie` header
5. `mutateUser(response.data)` updates SWR cache
**Target:**
1. User submits email + password
2. `POST ODOO_URL/api/login` (cross-origin)
3. Odoo validates credentials, returns `{ user: {...}, token: "jwt..." }`
4. Frontend stores JWT via `setToken(response.data.token)`
5. `mutateUser(response.data.user)` updates SWR cache
**Login page change (`src/pages/login.tsx`):**
```typescript
// BEFORE
const response = await axios.post("/api/login", { email, password });
mutateUser(response.data);
// AFTER
import api, { setToken } from "@/lib/api";
const response = await api.post("/api/login", { email, password });
setToken(response.data.token);
mutateUser(response.data.user);
```
### 2.6 Logout Flow Change
**Current:** `POST /api/logout` destroys iron-session.
**Target:** `POST ODOO_URL/api/logout` (optional server-side invalidation) + `clearToken()` client-side.
```typescript
// BEFORE
await axios.post("/api/logout");
mutateUser(null);
router.push("/login");
// AFTER
import api, { clearToken } from "@/lib/api";
await api.post("/api/logout").catch(() => {});
clearToken();
mutateUser(null);
router.push("/login");
```
---
## 3. API Base URL Change
### 3.1 Environment Variable
Add to `.env.local`:
```
NEXT_PUBLIC_API_URL=https://api.encoach.com
```
Development:
```
NEXT_PUBLIC_API_URL=http://localhost:8069
```
### 3.2 Shared Axios Instance
Replace all direct `axios` imports with the shared `api` instance from `src/lib/api.ts` (defined in Section 2.3).
**Search and replace pattern across the codebase:**
```typescript
// BEFORE (scattered across ~40 files)
import axios from "axios";
axios.get("/api/...");
axios.post("/api/...");
axios.patch("/api/...");
axios.delete("/api/...");
// AFTER
import api from "@/lib/api";
api.get("/api/...");
api.post("/api/...");
api.patch("/api/...");
api.delete("/api/...");
```
The `/api/...` path stays the same -- the `baseURL` on the axios instance prepends the Odoo host.
### 3.3 SWR Fetcher Update
Update `src/hooks/useUser.tsx`:
```typescript
// BEFORE
const fetcher = (url: string) => axios.get(url).then((res) => res.data);
// AFTER
import api from "@/lib/api";
const fetcher = (url: string) => api.get(url).then((res) => res.data);
```
### 3.4 fetch() Calls
A few files use `fetch()` instead of axios (primarily `src/components/ExamEditor/ImportExam/WordUploader.tsx`). These also need the base URL and auth header:
```typescript
// BEFORE
const res = await fetch(`/api/exam/${module}/import/`, { method: "POST", body: formData });
// AFTER
import { getToken } from "@/lib/api";
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/exam/${module}/import/`, {
method: "POST",
body: formData,
headers: { Authorization: `Bearer ${getToken()}` },
});
```
**Note:** `fetch()` calls to blob URLs (e.g., `fetch(blobUrl)` for audio/video previews) do NOT change. Only calls to `/api/*` endpoints change.
---
## 4. Endpoint-by-Endpoint Migration Map
For each API call the frontend makes, this section specifies the current URL, new Odoo URL, HTTP method, and every file that makes the call.
**Convention:** Where the Odoo URL is the same path as the current URL (just different host), only the base URL changes. These are marked "Path unchanged." Where the Odoo URL differs, the new path is shown.
### 4.1 Auth
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 1 | POST | `/api/login` | Path unchanged | `src/pages/login.tsx` |
| 2 | POST | `/api/logout` | Path unchanged | `src/pages/official-exam.tsx`, `src/components/Sidebar.tsx`, `src/components/MobileMenu.tsx` |
| 3 | POST | `/api/reset` | Path unchanged | `src/pages/login.tsx` |
| 4 | POST | `/api/reset/sendVerification` | Path unchanged | `src/utils/email.ts` |
**Response change for login:** Odoo returns `{ user: {...}, token: "jwt..." }` instead of just the user object. Frontend must extract and store the token.
### 4.2 User
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 5 | GET | `/api/user` | Path unchanged | `src/hooks/useUser.tsx` (SWR) |
| 6 | DELETE | `/api/user` | Path unchanged | (called from useUser context) |
| 7 | POST | `/api/users/update` | `PATCH /api/users/update` | `src/pages/profile.tsx`, `src/components/UserCard.tsx` |
| 8 | GET | `/api/users/list` | Path unchanged | `src/utils/groups.ts` |
| 9 | GET | `/api/users/{id}` | Path unchanged | `src/utils/groups.ts` |
| 10 | POST | `/api/users/controller` | Path unchanged | `src/components/Imports/StudentClassroomTransfer.tsx` |
| 11 | GET | `/api/users/balance` | Path unchanged | `src/hooks/useUserBalance.tsx` (if used) |
**Note on #7:** The current frontend uses `POST` for user updates. Odoo convention is `PATCH`. Either Odoo can accept both, or the frontend changes the method.
### 4.3 Registration / Codes
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 12 | POST | `/api/register` | Path unchanged | `src/pages/register.tsx` (SSR currently; move to client-side) |
| 13 | GET | `/api/code/{code}` | Path unchanged | `src/pages/register.tsx` |
**Note on #12:** Registration is currently handled in `getServerSideProps`. With Odoo, move registration to a client-side form submission. The register page should call `api.post("/api/register", payload)` and store the returned JWT.
### 4.4 Exams
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 14 | GET | `/api/exam` | Path unchanged | `src/hooks/useExams.tsx` |
| 15 | GET | `/api/exam/{module}?{params}` | Path unchanged | `src/utils/exams.ts` (`getExam`) |
| 16 | GET | `/api/exam/{module}/{id}` | Path unchanged | `src/utils/exams.ts` (`getExamById`) |
| 17 | POST | `/api/exam/{module}` | Path unchanged | `src/components/ExamEditor/SettingsEditor/reading/index.tsx`, `writing/index.tsx`, `listening/index.tsx`, `speaking/index.tsx`, `level.tsx` |
| 18 | PATCH | `/api/exam/{module}/{id}` | Path unchanged | `src/pages/(admin)/Lists/ExamList.tsx`, `src/pages/approval-workflows/[id]/index.tsx` |
| 19 | DELETE | `/api/exam/{module}/{id}` | Path unchanged | `src/pages/(admin)/Lists/ExamList.tsx` |
| 20 | GET | `/api/exam/avatars` | Path unchanged | `src/pages/generation.tsx` |
| 21 | GET/POST | `/api/exam/generate/{module}/{sectionId}` | Path unchanged | `src/components/ExamEditor/SettingsEditor/Shared/Generate.ts` |
| 22 | POST | `/api/exam/media/speaking` | Path unchanged | `src/components/ExamEditor/SettingsEditor/Shared/generateVideos.ts` |
| 23 | POST | `/api/exam/media/listening` | Path unchanged | `src/components/ExamEditor/SettingsEditor/listening/components.tsx` |
| 24 | POST | `/api/exam/media/instructions` | Path unchanged | `src/components/ExamEditor/Standalone/ListeningInstructions/index.tsx` |
| 25 | POST | `/api/exam/{module}/import/` | Path unchanged | `src/components/ExamEditor/ImportExam/WordUploader.tsx` (uses `fetch`) |
### 4.5 Evaluation / Grading
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 26 | POST | `/api/evaluate/writing` | Path unchanged | `src/utils/evaluation.ts` |
| 27 | POST | `/api/evaluate/speaking` | Path unchanged | `src/utils/evaluation.ts` |
| 28 | POST | `/api/evaluate/interactiveSpeaking` | Path unchanged | `src/utils/evaluation.ts` |
| 29 | GET | `/api/evaluate/status?...` | Path unchanged | `src/utils/evaluation.ts` (polling) |
| 30 | GET | `/api/evaluate/fetchSolutions?...` | Path unchanged | `src/utils/evaluation.ts` |
| 31 | POST | `/api/grading` | Path unchanged | `src/pages/api/grading/index.ts` (if called by frontend) |
| 32 | POST | `/api/grading/multiple` | Path unchanged | (if called by frontend) |
### 4.6 Storage
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 33 | POST | `/api/storage` | Path unchanged | `src/components/ExamEditor/SettingsEditor/writing/index.tsx`, `speaking/index.tsx`, `listening/index.tsx`, `level.tsx` |
| 34 | POST | `/api/storage/delete` | `DELETE /api/storage/{id}` (or keep POST) | `src/utils/evaluation.ts` |
**Note:** Odoo will use `ir.attachment` for file storage. The response must return a publicly accessible URL for the uploaded file, matching the current behavior.
### 4.7 Speaking Audio
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 35 | POST | `/api/speaking` | Path unchanged | `src/components/Solutions/Speaking.tsx`, `src/components/Solutions/InteractiveSpeaking.tsx` |
### 4.8 Sessions
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 36 | POST | `/api/sessions` | Path unchanged | `src/stores/exam/index.ts` (Zustand `saveSession`) |
| 37 | DELETE | `/api/sessions/{id}` | Path unchanged | `src/components/Medium/SessionCard.tsx` |
### 4.9 Stats
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 38 | POST | `/api/stats` | Path unchanged | `src/stores/exam/index.ts` (Zustand `saveStats`) |
| 39 | GET | `/api/stats/{id}` | Path unchanged | `src/pages/training/[id]/index.tsx` |
| 40 | POST | `/api/statistical` | Path unchanged | `src/pages/statistical.tsx` |
### 4.10 Training
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 41 | POST | `/api/training` | Path unchanged | `src/pages/training/index.tsx` |
| 42 | GET | `/api/training/{id}` | Path unchanged | `src/pages/training/[id]/index.tsx` |
| 43 | GET | `/api/training/walkthrough` | Path unchanged | `src/pages/training/[id]/index.tsx` |
### 4.11 Groups
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 44 | GET | `/api/groups?participant={userId}` | Path unchanged | `src/utils/groups.ts` |
| 45 | POST | `/api/groups` | Path unchanged | `src/pages/classrooms/create.tsx` |
| 46 | PATCH | `/api/groups/{id}` | Path unchanged | `src/pages/classrooms/[id].tsx` |
| 47 | DELETE | `/api/groups/{id}` | Path unchanged | `src/pages/classrooms/[id].tsx` |
### 4.12 Entities
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 48 | POST | `/api/entities` | Path unchanged | `src/pages/entities/create.tsx` |
| 49 | PATCH | `/api/entities/{id}` | Path unchanged | `src/pages/entities/[id]/index.tsx` |
| 50 | DELETE | `/api/entities/{id}` | Path unchanged | `src/pages/entities/[id]/index.tsx` |
| 51 | PATCH | `/api/entities/{id}/users` | Path unchanged | `src/pages/entities/[id]/index.tsx` |
### 4.13 Roles
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 52 | POST | `/api/roles` | Path unchanged | `src/pages/entities/[id]/roles/index.tsx` |
| 53 | PATCH | `/api/roles/{id}` | Path unchanged | `src/pages/entities/[id]/roles/[role].tsx` |
| 54 | DELETE | `/api/roles/{id}` | Path unchanged | `src/pages/entities/[id]/roles/[role].tsx` |
| 55 | POST | `/api/roles/{id}/users` | Path unchanged | `src/pages/entities/[id]/index.tsx` |
### 4.14 Permissions
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 56 | PATCH | `/api/permissions/{id}` | Path unchanged | `src/pages/permissions/[id].tsx` |
### 4.15 Payments
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 57 | POST | `/api/payments` | Path unchanged | `src/pages/payment-record.tsx` |
| 58 | PATCH | `/api/payments/{id}` | Path unchanged | `src/pages/payment-record.tsx` |
| 59 | DELETE | `/api/payments/{id}` | Path unchanged | `src/pages/payment-record.tsx` |
| 60 | GET/POST/DELETE | `/api/payments/files/{type}/{paymentId}` | Path unchanged | `src/components/PaymentAssetManager.tsx` |
| 61 | POST | `/api/paymob` | Path unchanged | `src/components/PaymobPayment.tsx` |
**Bug fix opportunity:** In `src/pages/payment-record.tsx`, the PATCH call uses `api/payments/${id}` without a leading `/`. When switching to the shared axios instance with a `baseURL`, this will work correctly. But verify during testing.
### 4.16 Assignments
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 62 | POST | `/api/assignments` | Path unchanged | `src/pages/assignments/creator/index.tsx` |
| 63 | PATCH | `/api/assignments/{id}` | Path unchanged | `src/pages/assignments/creator/[id].tsx`, `src/pages/assignments/[id].tsx` |
| 64 | DELETE | `/api/assignments/{id}` | Path unchanged | `src/pages/assignments/creator/[id].tsx`, `src/pages/assignments/[id].tsx` |
| 65 | POST | `/api/assignments/{id}/start` | Path unchanged | `src/pages/assignments/creator/[id].tsx`, `src/pages/assignments/[id].tsx` |
### 4.17 Invites
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 66 | GET | `/api/invites/{decision}/{id}` | `POST /api/invites/{decision}/{id}` | `src/components/Medium/InviteCard.tsx`, `src/components/Medium/InviteWithUserCard.tsx` |
**Note:** Currently uses GET for accept/decline actions (side-effectful GET). Odoo should accept POST. Consider updating the frontend to use POST -- it's a more correct HTTP method for state-changing operations.
### 4.18 Approval Workflows
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 67 | POST | `/api/approval-workflows/create` | Path unchanged | `src/pages/approval-workflows/create.tsx` |
| 68 | PUT | `/api/approval-workflows/{id}` | Path unchanged | `src/pages/approval-workflows/[id]/index.tsx` |
| 69 | PUT | `/api/approval-workflows/{id}/edit` | Path unchanged | `src/pages/approval-workflows/[id]/edit.tsx` |
| 70 | DELETE | `/api/approval-workflows/{id}` | Path unchanged | `src/pages/approval-workflows/index.tsx` |
### 4.19 Transcription
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 71 | POST | `/api/transcribe` | Path unchanged | (called from evaluation utils if needed) |
### 4.20 Batch Users
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 72 | POST | `/api/batch_users` | Path unchanged | (admin import page) |
### 4.21 Make User (Admin)
| # | Method | Current URL | Odoo URL | Files |
|---|--------|-------------|----------|-------|
| 73 | POST | `/api/make_user` | Path unchanged | (admin user creation) |
---
## 5. SSR Migration Strategy
### 5.1 Current SSR Auth Pattern
~35 pages use this pattern:
```typescript
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
const user = await requestUser(req, res);
if (!user || !user.isVerified) return redirect("/login");
return { props: { user } };
}, sessionOptions);
```
### 5.2 Recommended: JWT Cookie + Server-Side Validation (Option A)
Store the JWT in a regular cookie (set by `js-cookie` on login). In `getServerSideProps`, read the cookie from the request and call Odoo to validate.
**New helper `src/lib/ssr-auth.ts`:**
```typescript
import type { GetServerSidePropsContext, GetServerSidePropsResult } from "next";
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const TOKEN_COOKIE = "encoach_token";
export function withAuth<P extends Record<string, unknown>>(
handler: (ctx: GetServerSidePropsContext, user: User) => Promise<GetServerSidePropsResult<P>>
) {
return async (ctx: GetServerSidePropsContext): Promise<GetServerSidePropsResult<P>> => {
const token = ctx.req.cookies[TOKEN_COOKIE];
if (!token) {
return { redirect: { destination: "/login", permanent: false } };
}
try {
const res = await fetch(`${API_URL}/api/user`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) throw new Error("Unauthorized");
const user = await res.json();
if (!user.isVerified) {
return { redirect: { destination: "/login", permanent: false } };
}
return handler(ctx, user);
} catch {
return { redirect: { destination: "/login", permanent: false } };
}
};
}
```
**Page migration example:**
```typescript
// BEFORE
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
const user = await requestUser(req, res);
if (!user) return redirect("/login");
// ... fetch additional data using user ...
return { props: { user, someData } };
}, sessionOptions);
// AFTER
export const getServerSideProps = withAuth(async (ctx, user) => {
// ... fetch additional data using user ...
return { props: { user, someData } };
});
```
### 5.3 Alternative: Client-Only Auth (Option B)
Remove all `getServerSideProps` auth checks. Every page uses `useUser({ redirectTo: "/login" })` to protect itself.
**Pros:** Simpler; no SSR auth at all.
**Cons:** Brief flash of unauthenticated content; pages that fetch data server-side need to move data fetching to client-side.
### 5.4 Pages Requiring SSR Migration
Every page below currently uses `withIronSessionSsr` and needs to switch to `withAuth` (Option A) or remove SSR auth (Option B):
| Page | SSR Data Fetching |
|------|-------------------|
| `src/pages/index.tsx` | User only (redirects to dashboard) |
| `src/pages/login.tsx` | Reverse guard (redirect if already logged in) |
| `src/pages/dashboard/index.tsx` | User only |
| `src/pages/dashboard/teacher.tsx` | User + groups + assignments + stats |
| `src/pages/dashboard/student.tsx` | User + assignments + stats |
| `src/pages/dashboard/corporate.tsx` | User + entity data |
| `src/pages/dashboard/mastercorporate.tsx` | User + multi-entity data |
| `src/pages/dashboard/admin.tsx` | User + platform stats |
| `src/pages/dashboard/developer.tsx` | User |
| `src/pages/users/index.tsx` | User + user list |
| `src/pages/users/performance.tsx` | User + performance data |
| `src/pages/training/index.tsx` | User |
| `src/pages/training/[id]/index.tsx` | User + training data |
| `src/pages/tickets.tsx` | User + tickets |
| `src/pages/stats.tsx` | User + stats |
| `src/pages/statistical.tsx` | User |
| `src/pages/settings.tsx` | User |
| `src/pages/record.tsx` | User |
| `src/pages/profile.tsx` | User |
| `src/pages/popout.tsx` | User (session-based) |
| `src/pages/permissions/index.tsx` | User + permissions |
| `src/pages/permissions/[id].tsx` | User + permission detail |
| `src/pages/payment.tsx` | User |
| `src/pages/payment-record.tsx` | User + payments |
| `src/pages/official-exam.tsx` | User |
| `src/pages/generation.tsx` | User |
| `src/pages/exercises.tsx` | User + exam data |
| `src/pages/exam.tsx` | User + exam + session data |
| `src/pages/entities/index.tsx` | User + entities |
| `src/pages/entities/create.tsx` | User |
| `src/pages/entities/[id]/index.tsx` | User + entity detail |
| `src/pages/entities/[id]/roles/index.tsx` | User + roles |
| `src/pages/entities/[id]/roles/[role].tsx` | User + role detail |
| `src/pages/classrooms/*.tsx` | User + groups |
| `src/pages/assignments/*.tsx` | User + assignments |
| `src/pages/approval-workflows/*.tsx` | User + workflows |
**For pages that only need user auth (no server-side data):** Replace `getServerSideProps` with client-side `useUser({ redirectTo: "/login" })`.
**For pages that fetch additional data server-side:** Use `withAuth` and make the data-fetching calls to Odoo using the JWT token from the cookie.
---
## 6. Files to Delete
After migration, the following files are no longer needed. They represent the BFF layer being replaced by Odoo.
### 6.1 API Route Files (108 files)
Delete the entire `src/pages/api/` directory:
**Auth & User:**
- `src/pages/api/login.ts`
- `src/pages/api/logout.ts`
- `src/pages/api/register.ts`
- `src/pages/api/user.ts`
- `src/pages/api/make_user.ts`
- `src/pages/api/batch_users.ts`
- `src/pages/api/reset/index.ts`
- `src/pages/api/reset/confirm.ts`
- `src/pages/api/reset/sendVerification.ts`
- `src/pages/api/reset/verify.ts`
- `src/pages/api/users/update.ts`
- `src/pages/api/users/search.ts`
- `src/pages/api/users/list.ts`
- `src/pages/api/users/controller.ts`
- `src/pages/api/users/balance.ts`
- `src/pages/api/users/agents/index.ts`
- `src/pages/api/users/agents/[code].ts`
- `src/pages/api/users/[id].ts`
**Exams:**
- `src/pages/api/exam/index.ts`
- `src/pages/api/exam/upload.ts`
- `src/pages/api/exam/avatars.ts`
- `src/pages/api/exam/generate/[...module].ts`
- `src/pages/api/exam/media/[...module].ts`
- `src/pages/api/exam/media/poll.ts`
- `src/pages/api/exam/media/instructions.ts`
- `src/pages/api/exam/[module]/index.ts`
- `src/pages/api/exam/[module]/import.ts`
- `src/pages/api/exam/[module]/[id].ts`
**Evaluation:**
- `src/pages/api/evaluate/writing.ts`
- `src/pages/api/evaluate/speaking.ts`
- `src/pages/api/evaluate/interactiveSpeaking.ts`
- `src/pages/api/evaluate/status.ts`
- `src/pages/api/evaluate/fetchSolutions.ts`
**Grading:**
- `src/pages/api/grading/index.ts`
- `src/pages/api/grading/multiple.ts`
**Stats & Sessions:**
- `src/pages/api/stats/index.ts`
- `src/pages/api/stats/update.ts`
- `src/pages/api/stats/disabled.ts`
- `src/pages/api/stats/user/[user].ts`
- `src/pages/api/stats/session/[session].ts`
- `src/pages/api/stats/[id]/index.ts`
- `src/pages/api/stats/[id]/[export]/pdf.tsx`
- `src/pages/api/statistical.ts`
- `src/pages/api/sessions/index.ts`
- `src/pages/api/sessions/[id].ts`
**Training:**
- `src/pages/api/training/index.ts`
- `src/pages/api/training/[id].ts`
- `src/pages/api/training/user/[user].ts`
- `src/pages/api/training/walkthrough/index.ts`
**Entities & Groups:**
- `src/pages/api/entities/index.ts`
- `src/pages/api/entities/users.ts`
- `src/pages/api/entities/groups.ts`
- `src/pages/api/entities/[id]/index.ts`
- `src/pages/api/entities/[id]/users.ts`
- `src/pages/api/groups/index.ts`
- `src/pages/api/groups/controller.ts`
- `src/pages/api/groups/[id].ts`
**Roles & Permissions:**
- `src/pages/api/roles/index.ts`
- `src/pages/api/roles/[id]/index.ts`
- `src/pages/api/roles/[id]/users.ts`
- `src/pages/api/permissions/index.ts`
- `src/pages/api/permissions/bootstrap.ts`
- `src/pages/api/permissions/[id].ts`
**Invites & Codes:**
- `src/pages/api/invites/index.ts`
- `src/pages/api/invites/[id].ts`
- `src/pages/api/invites/accept/[id].ts`
- `src/pages/api/invites/decline/[id].ts`
- `src/pages/api/code/index.ts`
- `src/pages/api/code/entities.ts`
- `src/pages/api/code/[id].ts`
**Payments:**
- `src/pages/api/stripe.ts`
- `src/pages/api/paypal/index.ts`
- `src/pages/api/paypal/approve.ts`
- `src/pages/api/paypal/raas.ts`
- `src/pages/api/paymob/index.ts`
- `src/pages/api/paymob/webhook.ts`
- `src/pages/api/payments/index.ts`
- `src/pages/api/payments/[id].ts`
- `src/pages/api/payments/assigned.ts`
- `src/pages/api/payments/paypal.ts`
- `src/pages/api/payments/files/[type]/[paymentId].ts`
- `src/pages/api/packages/index.ts`
- `src/pages/api/packages/[id].ts`
- `src/pages/api/discounts/index.ts`
- `src/pages/api/discounts/[id].ts`
**Assignments:**
- `src/pages/api/assignments/index.ts`
- `src/pages/api/assignments/corporate/index.ts`
- `src/pages/api/assignments/corporate/[id].ts`
- `src/pages/api/assignments/[id]/index.ts`
- `src/pages/api/assignments/[id]/start.ts`
- `src/pages/api/assignments/[id]/release.ts`
- `src/pages/api/assignments/[id]/archive.tsx`
- `src/pages/api/assignments/[id]/unarchive.tsx`
- `src/pages/api/assignments/[id]/[export]/pdf.tsx`
- `src/pages/api/assignments/[id]/[export]/excel.ts`
**Approval Workflows:**
- `src/pages/api/approval-workflows/index.ts`
- `src/pages/api/approval-workflows/create.ts`
- `src/pages/api/approval-workflows/[id]/index.ts`
- `src/pages/api/approval-workflows/[id]/edit.ts`
**Other:**
- `src/pages/api/storage/index.ts`
- `src/pages/api/storage/insert.ts`
- `src/pages/api/storage/delete.ts`
- `src/pages/api/speaking.ts`
- `src/pages/api/transcribe/index.ts`
- `src/pages/api/tickets/index.ts`
- `src/pages/api/tickets/[id].ts`
- `src/pages/api/tickets/assignedToUser/index.ts`
- `src/pages/api/hello.ts`
### 6.2 Backend Utility Files (14 files)
These files contain MongoDB query logic used by API routes. Delete all:
- `src/utils/approval.workflows.be.ts`
- `src/utils/assignments.be.ts`
- `src/utils/codes.be.ts`
- `src/utils/disabled.be.ts`
- `src/utils/entities.be.ts`
- `src/utils/exams.be.ts`
- `src/utils/grading.be.ts`
- `src/utils/groups.be.ts`
- `src/utils/invites.be.ts`
- `src/utils/permissions.be.ts`
- `src/utils/roles.be.ts`
- `src/utils/sessions.be.ts`
- `src/utils/stats.be.ts`
- `src/utils/users.be.ts`
### 6.3 Library Files (3 files)
- `src/lib/session.ts` -- iron-session config (replaced by `src/lib/api.ts`)
- `src/lib/mongodb.ts` -- MongoDB connection (no longer needed)
- `src/lib/createWorkflowsOnExamCreation.ts` -- server-side workflow logic (moved to Odoo)
**Keep:**
- `src/lib/utils.ts` -- general client-side utilities
- `src/lib/formidable-serverless.d.ts` -- only needed if any remaining file upload logic stays; likely deletable
### 6.4 Firebase Files
If Odoo replaces Firebase Auth entirely, also remove:
- `src/firebase/` directory (Firebase client config)
- `src/constants/platform.json` (Firebase service account -- server-side only)
- `src/constants/staging.json` (Firebase service account -- server-side only)
### 6.5 Dependencies to Remove from package.json
```
iron-session
firebase
firebase-admin
mongodb
@beam-australia/react-env (if no longer needed for client env)
bcrypt
formidable
```
### 6.6 Dependencies to Add
```
js-cookie (JWT cookie storage)
@types/js-cookie (TypeScript types)
```
---
## 7. Migration Checklist
A step-by-step checklist for the frontend developer. Complete in order.
### Phase 1: Infrastructure Setup
- [ ] **1.1** Add `NEXT_PUBLIC_API_URL` to `.env.local` (point to Odoo dev instance)
- [ ] **1.2** Create `src/lib/api.ts` with shared axios instance, base URL, and JWT interceptor (Section 2.3)
- [ ] **1.3** Create `src/lib/auth.ts` with `setToken()`, `getToken()`, `clearToken()` helpers
- [ ] **1.4** Add `js-cookie` dependency: `yarn add js-cookie @types/js-cookie`
- [ ] **1.5** Create `src/lib/ssr-auth.ts` with `withAuth()` helper for SSR (Section 5.2)
### Phase 2: Auth Migration
- [ ] **2.1** Update `src/pages/login.tsx`: use `api.post()`, store JWT, extract user from response
- [ ] **2.2** Update `src/pages/register.tsx`: move registration to client-side, use `api.post()`
- [ ] **2.3** Update logout calls in `Sidebar.tsx`, `MobileMenu.tsx`, `official-exam.tsx`: use `api.post()` + `clearToken()`
- [ ] **2.4** Update `src/hooks/useUser.tsx`: use `api` instance for SWR fetcher
- [ ] **2.5** Update `src/utils/email.ts`: use `api` instance
- [ ] **2.6** Verify login/logout/register work end-to-end with Odoo
### Phase 3: SSR Migration
- [ ] **3.1** For each page in the SSR page list (Section 5.4), replace `withIronSessionSsr` with `withAuth` or client-side `useUser({ redirectTo: "/login" })`
- [ ] **3.2** Update pages that fetch server-side data to call Odoo with the JWT token
- [ ] **3.3** Verify all ~35 protected pages redirect correctly when not authenticated
- [ ] **3.4** Verify the login page redirects correctly when already authenticated
### Phase 4: API Call Migration (domain by domain)
For each domain, replace `axios` with `api` from `@/lib/api`:
- [ ] **4.1** User endpoints (`src/pages/profile.tsx`, `src/components/UserCard.tsx`, `src/utils/groups.ts`, `src/components/Imports/StudentClassroomTransfer.tsx`)
- [ ] **4.2** Exam endpoints (`src/utils/exams.ts`, `src/hooks/useExams.tsx`, `src/pages/generation.tsx`, all `ExamEditor` files, `ExamList.tsx`)
- [ ] **4.3** Evaluation endpoints (`src/utils/evaluation.ts`)
- [ ] **4.4** Storage endpoints (all `ExamEditor/SettingsEditor` files, `src/utils/evaluation.ts`)
- [ ] **4.5** Speaking audio (`src/components/Solutions/Speaking.tsx`, `InteractiveSpeaking.tsx`)
- [ ] **4.6** Sessions (`src/stores/exam/index.ts`, `src/components/Medium/SessionCard.tsx`)
- [ ] **4.7** Stats (`src/stores/exam/index.ts`, `src/pages/training/[id]/index.tsx`, `src/pages/statistical.tsx`)
- [ ] **4.8** Training (`src/pages/training/index.tsx`, `src/pages/training/[id]/index.tsx`)
- [ ] **4.9** Groups (`src/utils/groups.ts`, `src/pages/classrooms/create.tsx`, `src/pages/classrooms/[id].tsx`)
- [ ] **4.10** Entities (`src/pages/entities/create.tsx`, `src/pages/entities/[id]/index.tsx`)
- [ ] **4.11** Roles (`src/pages/entities/[id]/roles/index.tsx`, `[role].tsx`)
- [ ] **4.12** Permissions (`src/pages/permissions/[id].tsx`)
- [ ] **4.13** Payments (`src/pages/payment-record.tsx`, `src/components/PaymentAssetManager.tsx`, `src/components/PaymobPayment.tsx`)
- [ ] **4.14** Assignments (`src/pages/assignments/creator/index.tsx`, `[id].tsx`, `src/pages/assignments/[id].tsx`)
- [ ] **4.15** Invites (`src/components/Medium/InviteCard.tsx`, `InviteWithUserCard.tsx`)
- [ ] **4.16** Approval workflows (`src/pages/approval-workflows/*.tsx`)
- [ ] **4.17** Codes (`src/pages/register.tsx`)
- [ ] **4.18** Remaining: transcribe, batch_users, make_user, statistical
- [ ] **4.19** Update `WordUploader.tsx` `fetch()` call with base URL and auth header
### Phase 5: Cleanup
- [ ] **5.1** Delete all 108 files in `src/pages/api/`
- [ ] **5.2** Delete all 14 `src/utils/*.be.ts` files
- [ ] **5.3** Delete `src/lib/session.ts`, `src/lib/mongodb.ts`, `src/lib/createWorkflowsOnExamCreation.ts`
- [ ] **5.4** Delete `src/firebase/` directory (if Firebase Auth fully removed)
- [ ] **5.5** Delete `src/constants/platform.json`, `src/constants/staging.json`
- [ ] **5.6** Remove unused dependencies from `package.json`: `iron-session`, `firebase`, `firebase-admin`, `mongodb`, `bcrypt`, `formidable`
- [ ] **5.7** Run `yarn install` to update lockfile
- [ ] **5.8** Run TypeScript compiler (`yarn tsc --noEmit`) and fix any remaining type errors
- [ ] **5.9** Run linter (`yarn lint`) and fix issues
### Phase 6: Testing
- [ ] **6.1** Test login flow (email + password -> JWT stored -> user loaded)
- [ ] **6.2** Test registration flow (individual and corporate)
- [ ] **6.3** Test logout (token cleared, redirect to login)
- [ ] **6.4** Test SSR protection (unauthenticated access to protected page -> redirect)
- [ ] **6.5** Test exam taking flow (load exam, answer questions, submit, save stats)
- [ ] **6.6** Test writing/speaking grading (submit, poll, receive result)
- [ ] **6.7** Test entity/group/classroom management (CRUD operations)
- [ ] **6.8** Test assignment lifecycle (create, start, release, archive)
- [ ] **6.9** Test payment flows (Stripe, PayPal, Paymob)
- [ ] **6.10** Test file uploads (exam media, profile pictures)
- [ ] **6.11** Test training content generation
- [ ] **6.12** Test ticket creation (from platform and landing page)
- [ ] **6.13** Test admin user management (create, update, batch import)
- [ ] **6.14** Cross-browser test (Chrome, Firefox, Safari)

2337
docs/ODOO_MIGRATION_SRS.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,12 @@
# EnCoach Platform -- Odoo 19 Full Migration SRS (v2)
> **SUPERSEDED** -- This document has been replaced by `ENCOACH_ODOO19_BACKEND_SRS.md` (v3.0) and `ENCOACH_UNIFIED_SRS.md` (v2.0). All content below is historical. The migration is complete and the system is deployed at `http://5.189.151.117:8069`.
## Software Requirements Specification
**Version:** 2.0
**Date:** March 11, 2026
**Status:** Draft
**Status:** ~~Draft~~ **SUPERSEDED**
**Supersedes:** ODOO_MIGRATION_SRS.md (v1)
**Key change from v1:** The ielts-be (FastAPI) microservice is fully eliminated. All AI/ML functionality is absorbed into custom Odoo modules.