From a1f012774e7d362fa57e37402ed7c49e64f685d5 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Tue, 20 Oct 2026 13:41:40 +0300 Subject: [PATCH] Adapt LMS backend for makeup education --- README.md | 18 +- cmd/main.go | 15 +- .../000112_rezina_email_brand.up.sql | 2 +- .../000113_generic_assessment_levels.down.sql | 38 + .../000113_generic_assessment_levels.up.sql | 42 + ...00114_subject_assessment_progress.down.sql | 7 + .../000114_subject_assessment_progress.up.sql | 9 + ...5_education_subscription_category.down.sql | 13 + ...115_education_subscription_category.up.sql | 19 + .../000116_remove_initial_assessment.down.sql | 20 + .../000116_remove_initial_assessment.up.sql | 28 + db/query/question_sets.sql | 31 - db/query/user.sql | 17 +- docs/docs.go | 4226 +++++++++++++---- ...itial-assessment-client-app-integration.md | 813 ---- ...itial-assessment-question-writing-guide.md | 137 - docs/overview.md | 41 +- ...d-question-types-for-remedial-education.md | 216 + docs/swagger.json | 4226 +++++++++++++---- docs/swagger.yaml | 2939 +++++++++--- gen/db/models.go | 42 +- gen/db/question_sets.sql.go | 102 - gen/db/user.sql.go | 277 +- internal/domain/initial_assessment.go | 449 -- internal/domain/initial_assessment_test.go | 78 - internal/domain/program.go | 20 +- internal/domain/questions.go | 15 +- internal/domain/subscriptions.go | 11 +- internal/domain/user.go | 47 +- internal/ports/initial_assessment.go | 6 - internal/ports/questions.go | 8 - internal/ports/user.go | 1 - internal/repository/initial_assessment.go | 12 - .../initial_assessment_thresholds.go | 156 - internal/repository/questions.go | 78 - internal/repository/user.go | 73 +- internal/services/assessment/helpers.go | 13 - .../services/assessment/initial_assessment.go | 46 - internal/services/assessment/placement.go | 257 - internal/services/assessment/service.go | 28 - .../learnernotifications/subscription.go | 4 + internal/services/questions/service.go | 4 - internal/services/subscriptions/service.go | 1 + internal/web_server/app.go | 176 +- .../web_server/content_access_middleware.go | 10 +- .../exam_prep_catalog_course_handler.go | 6 - .../handlers/exam_prep_lesson_handler.go | 6 - .../handlers/exam_prep_module_handler.go | 6 - .../handlers/exam_prep_practice_handler.go | 13 - .../handlers/exam_prep_unit_handler.go | 6 - .../web_server/handlers/export_filters.go | 77 +- internal/web_server/handlers/handlers.go | 160 +- .../web_server/handlers/initial_assessment.go | 414 -- .../handlers/lms_progress_handler.go | 2 +- .../web_server/handlers/payments_admin.go | 2 +- .../handlers/practice_full_update_handler.go | 2 - .../web_server/handlers/program_handler.go | 4 +- internal/web_server/handlers/questions.go | 67 +- .../handlers/subscription_checkout_link.go | 2 +- internal/web_server/handlers/subscriptions.go | 10 +- internal/web_server/handlers/user.go | 18 +- internal/web_server/routes.go | 55 - 62 files changed, 9489 insertions(+), 6132 deletions(-) create mode 100644 db/migrations/000113_generic_assessment_levels.down.sql create mode 100644 db/migrations/000113_generic_assessment_levels.up.sql create mode 100644 db/migrations/000114_subject_assessment_progress.down.sql create mode 100644 db/migrations/000114_subject_assessment_progress.up.sql create mode 100644 db/migrations/000115_education_subscription_category.down.sql create mode 100644 db/migrations/000115_education_subscription_category.up.sql create mode 100644 db/migrations/000116_remove_initial_assessment.down.sql create mode 100644 db/migrations/000116_remove_initial_assessment.up.sql delete mode 100644 docs/initial-assessment-client-app-integration.md delete mode 100644 docs/initial-assessment-question-writing-guide.md create mode 100644 docs/recommended-question-types-for-remedial-education.md delete mode 100644 internal/domain/initial_assessment.go delete mode 100644 internal/domain/initial_assessment_test.go delete mode 100644 internal/ports/initial_assessment.go delete mode 100644 internal/repository/initial_assessment.go delete mode 100644 internal/repository/initial_assessment_thresholds.go delete mode 100644 internal/services/assessment/helpers.go delete mode 100644 internal/services/assessment/initial_assessment.go delete mode 100644 internal/services/assessment/placement.go delete mode 100644 internal/services/assessment/service.go delete mode 100644 internal/web_server/handlers/initial_assessment.go diff --git a/README.md b/README.md index 12b0b66f..89c03b00 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Rezina Backend API -Golang API for **Rezina**, an LMS and exam-prep platform. It serves the mobile learner apps and the [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) panel: authentication, content (Learn English + Duolingo/IELTS), practices/questions, subscriptions & payments, team RBAC, analytics, notifications, and more. +Golang API for **Rezina**, a remedial and makeup education LMS. It serves the learner apps and the [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) panel: authentication, academic programs and courses, practices and assessments, subscriptions and payments, team RBAC, analytics, notifications, and more. | | | |---|---| @@ -41,8 +41,7 @@ Golang API for **Rezina**, an LMS and exam-prep platform. It serves the mobile l ## Features - **Learners**: registration/login (email OTP, Google, Apple), profiles, field options, progress -- **Learn English LMS**: programs → courses → modules → lessons; practices & questions; video engagement -- **Exam prep (Duolingo / IELTS)**: catalog courses → units → modules → lessons; reorder APIs; shared stimulus blocks +- **Learning content**: programs → courses → modules → lessons; practices, subject-focused assessments, and video engagement - **Dynamic question types**: type definitions, groups, multi-slot answers, select-missing-words, etc. - **Subscriptions & payments**: plans (including one-time lifetime), Chapa / Arifpay / related gateways, admin grant/extend/cancel - **Team admin**: invite by email, accept-invite flow, refresh tokens, password reset, custom RBAC roles @@ -310,7 +309,7 @@ Custom roles live in RBAC tables; migration `000097` allows custom names on `tea ## Domain overview -### Learn English content +### Learning content ``` Learning programs @@ -322,17 +321,6 @@ Learning programs Reorder: program / course / module / lesson ordered-id endpoints (admin). -### Exam prep (Duolingo / IELTS) - -``` -Catalog courses - └── Units - └── Unit modules - └── Lessons - └── Lesson practices -``` - -Reorder APIs mirror the LMS hierarchy for catalog courses, units, modules, and lessons. ### Practices & questions diff --git a/cmd/main.go b/cmd/main.go index 765fb3d7..54c6c1b4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -10,19 +10,18 @@ import ( minioclient "Rezina-Backend/internal/pkgs/minio" "Rezina-Backend/internal/repository" activitylogservice "Rezina-Backend/internal/services/activity_log" - "Rezina-Backend/internal/services/arifpay" "Rezina-Backend/internal/services/appversions" - "Rezina-Backend/internal/services/chapa" - "Rezina-Backend/internal/services/assessment" + "Rezina-Backend/internal/services/arifpay" "Rezina-Backend/internal/services/authentication" + "Rezina-Backend/internal/services/chapa" cloudconvertservice "Rezina-Backend/internal/services/cloudconvert" coursesservice "Rezina-Backend/internal/services/courses" "Rezina-Backend/internal/services/emailtemplates" "Rezina-Backend/internal/services/examprep" "Rezina-Backend/internal/services/faqs" issuereporting "Rezina-Backend/internal/services/issue_reporting" - lessonsservice "Rezina-Backend/internal/services/lessons" learnernotificationsservice "Rezina-Backend/internal/services/learnernotifications" + lessonsservice "Rezina-Backend/internal/services/lessons" "Rezina-Backend/internal/services/lmsprogress" "Rezina-Backend/internal/services/messenger" minioservice "Rezina-Backend/internal/services/minio" @@ -244,13 +243,6 @@ func main() { // transferStore := repository.NewTransferStore(store) // walletStore := wallet.WalletStore(store) - assessmentSvc := assessment.NewService( - repository.NewUserStore(store), - store, // Use store directly as it implements QuestionStore - notificationSvc, - cfg, - ) - // Vimeo service for video hosting var vimeoSvc *vimeoservice.Service if cfg.Vimeo.Enabled && cfg.Vimeo.AccessToken != "" { @@ -370,7 +362,6 @@ func main() { // Initialize and start HTTP server app := httpserver.NewApp( - assessmentSvc, questionsSvc, faqSvc, appVersionSvc, diff --git a/db/migrations/000112_rezina_email_brand.up.sql b/db/migrations/000112_rezina_email_brand.up.sql index 2589606a..537cecab 100644 --- a/db/migrations/000112_rezina_email_brand.up.sql +++ b/db/migrations/000112_rezina_email_brand.up.sql @@ -1,4 +1,4 @@ --- Update system email templates to the Rezina brand for existing installations. +-- Update system email templates to the Rezina brand for existing installations. UPDATE email_templates SET name = REPLACE(name, 'Yimaru Academy', 'Rezina'), subject = REPLACE(subject, 'Yimaru Academy', 'Rezina'), diff --git a/db/migrations/000113_generic_assessment_levels.down.sql b/db/migrations/000113_generic_assessment_levels.down.sql new file mode 100644 index 00000000..8f9aa9c7 --- /dev/null +++ b/db/migrations/000113_generic_assessment_levels.down.sql @@ -0,0 +1,38 @@ +DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level; + +UPDATE question_sets +SET description = CASE UPPER(TRIM(description)) + WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1' + WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2' + ELSE description END, + updated_at = NOW() +WHERE set_type = 'INITIAL_ASSESSMENT' + AND UPPER(TRIM(description)) IN ('FOUNDATION', 'DEVELOPING', 'SECURE', 'EXTENSION', 'ADVANCED', 'MASTERY'); + +UPDATE user_initial_assessment_progress +SET next_level = CASE UPPER(TRIM(next_level)) + WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1' + WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2' + ELSE UPPER(TRIM(next_level)) END, + highest_passed_level = CASE UPPER(TRIM(highest_passed_level)) + WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1' + WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2' + ELSE UPPER(TRIM(highest_passed_level)) END; + +UPDATE initial_assessment_level_thresholds +SET level = CASE UPPER(TRIM(level)) + WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1' + WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2' + ELSE UPPER(TRIM(level)) END; + +ALTER TABLE user_initial_assessment_progress + ADD CONSTRAINT user_initial_assessment_progress_next_level_check + CHECK (UPPER(TRIM(next_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')), + ADD CONSTRAINT user_initial_assessment_progress_highest_passed_check + CHECK (highest_passed_level IS NULL OR UPPER(TRIM(highest_passed_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')); + +CREATE UNIQUE INDEX idx_initial_assessment_one_published_per_level +ON question_sets ((UPPER(TRIM(description)))) +WHERE set_type = 'INITIAL_ASSESSMENT' + AND UPPER(TRIM(status)) = 'PUBLISHED' + AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2'); diff --git a/db/migrations/000113_generic_assessment_levels.up.sql b/db/migrations/000113_generic_assessment_levels.up.sql new file mode 100644 index 00000000..44caeae8 --- /dev/null +++ b/db/migrations/000113_generic_assessment_levels.up.sql @@ -0,0 +1,42 @@ +-- Replace CEFR defaults with curriculum-defined remediation bands while retaining +-- existing assessment data and allowing longer administrator-defined labels. +ALTER TABLE initial_assessment_level_thresholds ALTER COLUMN level TYPE VARCHAR(64); +UPDATE initial_assessment_level_thresholds +SET level = CASE UPPER(TRIM(level)) + WHEN 'A1' THEN 'FOUNDATION' + WHEN 'A2' THEN 'DEVELOPING' + WHEN 'B1' THEN 'SECURE' + WHEN 'B2' THEN 'EXTENSION' + WHEN 'C1' THEN 'ADVANCED' + WHEN 'C2' THEN 'MASTERY' + ELSE UPPER(TRIM(level)) END; + +ALTER TABLE user_initial_assessment_progress ALTER COLUMN next_level TYPE VARCHAR(64); +ALTER TABLE user_initial_assessment_progress ALTER COLUMN highest_passed_level TYPE VARCHAR(64); +ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_next_level_check; +ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_highest_passed_check; +UPDATE user_initial_assessment_progress +SET next_level = CASE UPPER(TRIM(next_level)) + WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE' + WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY' + ELSE UPPER(TRIM(next_level)) END, + highest_passed_level = CASE UPPER(TRIM(highest_passed_level)) + WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE' + WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY' + ELSE UPPER(TRIM(highest_passed_level)) END; + +UPDATE question_sets +SET description = CASE UPPER(TRIM(description)) + WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE' + WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY' + ELSE description END, + updated_at = NOW() +WHERE set_type = 'INITIAL_ASSESSMENT' + AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2'); + +DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level; +CREATE UNIQUE INDEX idx_initial_assessment_one_published_per_level +ON question_sets ((UPPER(TRIM(description))), (COALESCE(UPPER(TRIM(owner_type)), 'STANDALONE')), (COALESCE(owner_id, 0))) +WHERE set_type = 'INITIAL_ASSESSMENT' + AND UPPER(TRIM(status)) = 'PUBLISHED' + AND NULLIF(TRIM(description), '') IS NOT NULL; diff --git a/db/migrations/000114_subject_assessment_progress.down.sql b/db/migrations/000114_subject_assessment_progress.down.sql new file mode 100644 index 00000000..922b7a75 --- /dev/null +++ b/db/migrations/000114_subject_assessment_progress.down.sql @@ -0,0 +1,7 @@ +ALTER TABLE user_initial_assessment_progress + DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_pkey; + +ALTER TABLE user_initial_assessment_progress + ADD CONSTRAINT user_initial_assessment_progress_pkey PRIMARY KEY (user_id); + +ALTER TABLE user_initial_assessment_progress DROP COLUMN IF EXISTS subject_id; diff --git a/db/migrations/000114_subject_assessment_progress.up.sql b/db/migrations/000114_subject_assessment_progress.up.sql new file mode 100644 index 00000000..e07593c3 --- /dev/null +++ b/db/migrations/000114_subject_assessment_progress.up.sql @@ -0,0 +1,9 @@ +-- Persist placement independently for each subject (subject_id is the subject/course identifier). +ALTER TABLE user_initial_assessment_progress + ADD COLUMN subject_id BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE user_initial_assessment_progress + DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_pkey; + +ALTER TABLE user_initial_assessment_progress + ADD CONSTRAINT user_initial_assessment_progress_pkey PRIMARY KEY (user_id, subject_id); diff --git a/db/migrations/000115_education_subscription_category.down.sql b/db/migrations/000115_education_subscription_category.down.sql new file mode 100644 index 00000000..f6ad6f78 --- /dev/null +++ b/db/migrations/000115_education_subscription_category.down.sql @@ -0,0 +1,13 @@ +ALTER TABLE programs DROP CONSTRAINT IF EXISTS chk_programs_category; +UPDATE programs SET category = 'LEARN_ENGLISH', updated_at = NOW(); +ALTER TABLE programs + ADD CONSTRAINT chk_programs_category CHECK (category = 'LEARN_ENGLISH'); + +UPDATE subscription_plans +SET category = 'LEARN_ENGLISH', updated_at = NOW() +WHERE category = 'EDUCATION'; + +ALTER TABLE subscription_plans DROP CONSTRAINT IF EXISTS chk_subscription_plans_category; +ALTER TABLE subscription_plans + ADD CONSTRAINT chk_subscription_plans_category + CHECK (category IN ('LEARN_ENGLISH', 'IELTS', 'DUOLINGO')); diff --git a/db/migrations/000115_education_subscription_category.up.sql b/db/migrations/000115_education_subscription_category.up.sql new file mode 100644 index 00000000..0d84981d --- /dev/null +++ b/db/migrations/000115_education_subscription_category.up.sql @@ -0,0 +1,19 @@ +-- Generalize the active LMS subscription product. Keep inactive legacy plan rows +-- available for historical billing and reporting records. +ALTER TABLE subscription_plans DROP CONSTRAINT IF EXISTS chk_subscription_plans_category; +ALTER TABLE subscription_plans + ADD CONSTRAINT chk_subscription_plans_category + CHECK (category IN ('EDUCATION', 'LEARN_ENGLISH', 'IELTS', 'DUOLINGO')); + +UPDATE subscription_plans +SET category = 'EDUCATION', updated_at = NOW() +WHERE category = 'LEARN_ENGLISH'; + +UPDATE subscription_plans +SET is_active = FALSE, updated_at = NOW() +WHERE category IN ('IELTS', 'DUOLINGO'); + +ALTER TABLE programs DROP CONSTRAINT IF EXISTS chk_programs_category; +UPDATE programs SET category = 'EDUCATION', updated_at = NOW(); +ALTER TABLE programs + ADD CONSTRAINT chk_programs_category CHECK (category = 'EDUCATION'); diff --git a/db/migrations/000116_remove_initial_assessment.down.sql b/db/migrations/000116_remove_initial_assessment.down.sql new file mode 100644 index 00000000..9f98d1c7 --- /dev/null +++ b/db/migrations/000116_remove_initial_assessment.down.sql @@ -0,0 +1,20 @@ +ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check; +ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check + CHECK (set_type IN ('PRACTICE', 'INITIAL_ASSESSMENT', 'QUIZ', 'EXAM', 'SURVEY', 'CAPSTONE')); + +UPDATE question_sets qs +SET set_type = retired.set_type +FROM retired_initial_assessment_question_sets retired +WHERE retired.question_set_id = qs.id; + +ALTER TABLE retired_user_initial_assessment_progress RENAME TO user_initial_assessment_progress; +ALTER TABLE retired_initial_assessment_level_thresholds RENAME TO initial_assessment_level_thresholds; + +ALTER TABLE users ADD COLUMN initial_assessment_completed BOOLEAN NOT NULL DEFAULT FALSE; +UPDATE users u +SET initial_assessment_completed = archive.completed +FROM retired_initial_assessment_completion archive +WHERE archive.user_id = u.id; + +DROP TABLE retired_initial_assessment_completion; +DROP TABLE retired_initial_assessment_question_sets; diff --git a/db/migrations/000116_remove_initial_assessment.up.sql b/db/migrations/000116_remove_initial_assessment.up.sql new file mode 100644 index 00000000..eb0c6b1c --- /dev/null +++ b/db/migrations/000116_remove_initial_assessment.up.sql @@ -0,0 +1,28 @@ +-- Preserve existing assessment questions as ordinary practice and archive learner/configuration +-- metadata so a rollback can restore the previous feature without losing its records. +CREATE TABLE retired_initial_assessment_question_sets ( + question_set_id BIGINT PRIMARY KEY, + set_type VARCHAR(30) NOT NULL +); + +INSERT INTO retired_initial_assessment_question_sets (question_set_id, set_type) +SELECT id, set_type FROM question_sets WHERE set_type = 'INITIAL_ASSESSMENT'; + +UPDATE question_sets SET set_type = 'PRACTICE' WHERE set_type = 'INITIAL_ASSESSMENT'; + +ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check; +ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check + CHECK (set_type IN ('PRACTICE', 'QUIZ', 'EXAM', 'SURVEY', 'CAPSTONE')); + +ALTER TABLE initial_assessment_level_thresholds RENAME TO retired_initial_assessment_level_thresholds; +ALTER TABLE user_initial_assessment_progress RENAME TO retired_user_initial_assessment_progress; + +CREATE TABLE retired_initial_assessment_completion ( + user_id BIGINT PRIMARY KEY, + completed BOOLEAN NOT NULL +); + +INSERT INTO retired_initial_assessment_completion (user_id, completed) +SELECT id, initial_assessment_completed FROM users; + +ALTER TABLE users DROP COLUMN initial_assessment_completed; diff --git a/db/query/question_sets.sql b/db/query/question_sets.sql index 1ab70cb8..a1ea1acb 100644 --- a/db/query/question_sets.sql +++ b/db/query/question_sets.sql @@ -72,37 +72,6 @@ WHERE id = $1; DELETE FROM question_sets WHERE id = $1; --- name: GetInitialAssessmentSet :one -SELECT * -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) = 'A1' -ORDER BY created_at DESC -LIMIT 1; - --- name: GetInitialAssessmentSetByLevel :one -SELECT * -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) = sqlc.arg('level')::text -ORDER BY - CASE - WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0 - ELSE 1 - END, - created_at DESC -LIMIT 1; - --- name: ListPublishedInitialAssessmentLevels :many -SELECT DISTINCT UPPER(TRIM(description))::text AS level -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2') -ORDER BY level; - -- name: AddUserPersonaToQuestionSet :one INSERT INTO question_set_personas ( question_set_id, diff --git a/db/query/user.sql b/db/query/user.sql index a4e87229..bd2c7c1d 100644 --- a/db/query/user.sql +++ b/db/query/user.sql @@ -94,7 +94,6 @@ INSERT INTO users ( language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -130,7 +129,6 @@ VALUES ( $22, $23, $24, - $25, CURRENT_TIMESTAMP ) RETURNING @@ -154,7 +152,6 @@ RETURNING language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -213,7 +210,6 @@ SELECT language_goal, language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -256,7 +252,6 @@ WHERE AND (sqlc.narg('learning_goal')::TEXT IS NULL OR LOWER(TRIM(COALESCE(learning_goal, ''))) = LOWER(TRIM(sqlc.narg('learning_goal')::TEXT))) AND (sqlc.narg('knowledge_level')::TEXT IS NULL OR LOWER(TRIM(COALESCE(knowledge_level, ''))) = LOWER(TRIM(sqlc.narg('knowledge_level')::TEXT))) AND (sqlc.narg('profile_completed')::BOOLEAN IS NULL OR profile_completed = sqlc.narg('profile_completed')::BOOLEAN) - AND (sqlc.narg('initial_assessment_completed')::BOOLEAN IS NULL OR initial_assessment_completed = sqlc.narg('initial_assessment_completed')::BOOLEAN) AND ( sqlc.narg('min_profile_completion_pct')::INT IS NULL OR profile_completion_percentage >= sqlc.narg('min_profile_completion_pct')::INT @@ -471,7 +466,6 @@ SELECT language_challange, favourite_topic, - initial_assessment_completed, profile_picture_url, preferred_language, email_verified, @@ -511,13 +505,12 @@ SET language_goal = COALESCE($11, language_goal), language_challange = COALESCE($12, language_challange), favourite_topic = COALESCE($13, favourite_topic), - initial_assessment_completed = COALESCE($14, initial_assessment_completed), - profile_picture_url = COALESCE($15, profile_picture_url), - preferred_language = COALESCE($16, preferred_language), - gender = COALESCE($17, gender), - birth_day = COALESCE($18, birth_day), + profile_picture_url = COALESCE($14, profile_picture_url), + preferred_language = COALESCE($15, preferred_language), + gender = COALESCE($16, gender), + birth_day = COALESCE($17, birth_day), updated_at = CURRENT_TIMESTAMP -WHERE id = $19; +WHERE id = $18; -- name: DeleteUser :exec DELETE FROM users diff --git a/docs/docs.go b/docs/docs.go index 229cd747..d86d75f9 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -108,6 +108,18 @@ const docTemplate = `{ } } }, + "/api/v1/activity-logs/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "activity-logs" + ], + "summary": "Export activity logs as CSV (admin)", + "responses": {} + } + }, "/api/v1/activity-logs/{id}": { "get": { "description": "Returns a single activity log entry by its ID", @@ -1415,7 +1427,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "Plan category (LEARN_ENGLISH, IELTS, DUOLINGO)", + "description": "Plan category (EDUCATION)", "name": "plan_category", "in": "query" }, @@ -1492,6 +1504,18 @@ const docTemplate = `{ } } }, + "/api/v1/admin/payments/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "payments" + ], + "summary": "Export payments as CSV (admin)", + "responses": {} + } + }, "/api/v1/admin/payments/{id}": { "get": { "description": "Returns any payment record by ID without learner ownership restriction", @@ -1665,6 +1689,70 @@ const docTemplate = `{ } } }, + "/api/v1/admin/subscriptions/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "subscriptions" + ], + "summary": "Export user subscriptions as CSV (admin)", + "responses": {} + } + }, + "/api/v1/admin/subscriptions/{id}/cancel": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Cancels any user_subscriptions row by ID. Does not require ownership by the caller.", + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Cancel a learner subscription (admin)", + "parameters": [ + { + "type": "integer", + "description": "Subscription ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/users/deletion-requests": { "get": { "description": "Returns account deletion requests for admin panel tracking with filtering and pagination", @@ -1762,6 +1850,82 @@ const docTemplate = `{ } } }, + "/api/v1/admin/users/{user_id}/learning-activity": { + "get": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Returns LMS and exam-prep completion trees, progress summaries, completed ID snapshots, and recent activity timeline", + "produces": [ + "application/json" + ], + "tags": [ + "lms" + ], + "summary": "Get full learning activity for a user (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target user ID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Max recent-activity items (default 40, max 120)", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Include practice completions in recent-activity feed", + "name": "include_practices", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUserLearningActivityDetails" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/users/{user_id}/lms-learning-activity": { "get": { "security": [ @@ -1872,6 +2036,140 @@ const docTemplate = `{ } } }, + "/api/v1/admin/users/{user_id}/subscriptions": { + "get": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Returns display status, active plans by category, full subscription history, and related payments", + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Get all subscription details for a user (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target user ID", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUserSubscriptionDetails" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/admin/users/{user_id}/subscriptions/extend": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Unified admin action: if the learner has no active subscription in the plan's category, creates one (grant). If they already have an active subscription in that category, extends it by one period of the selected plan (and switches plan_id when different). Optionally records a SUCCESS payment at the plan price (record_payment, default true).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Grant or extend a learner subscription (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target learner user ID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "description": "Plan to grant or extend", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.adminApplySubscriptionReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/{id}": { "get": { "description": "Get a single admin by id", @@ -1974,7 +2272,7 @@ const docTemplate = `{ }, "/api/v1/analytics/dashboard": { "get": { - "description": "Platform analytics with optional date filters: all-time (default), year, year+month, or custom from/to range. When year is set, payments.revenue_monthly returns Jan–Dec SUCCESS revenue totals (UTC) per currency for that calendar year — use for yearly revenue charts. Daily series remains in revenue_last_30_days (see date_filter.series_*). Courses section counts LMS + exam_prep inventory.", + "description": "Platform analytics with optional date filters in Africa/Addis_Ababa (EAT): all-time (default), year, year+month, or custom from/to range. When year is set, payments.revenue_monthly returns Jan–Dec SUCCESS revenue totals (EAT) per currency for that calendar year. Optional payment_method filters payment/revenue metrics (exact or METHOD:% variants). Daily series remains in revenue_last_30_days (see date_filter.series_*). Courses section counts LMS + exam_prep inventory.", "produces": [ "application/json" ], @@ -1985,27 +2283,33 @@ const docTemplate = `{ "parameters": [ { "type": "integer", - "description": "Calendar year (e.g. 2025)", + "description": "EAT calendar year (e.g. 2025)", "name": "year", "in": "query" }, { "type": "integer", - "description": "Calendar month 1-12 (requires year)", + "description": "EAT calendar month 1-12 (requires year)", "name": "month", "in": "query" }, { "type": "string", - "description": "Custom range start (YYYY-MM-DD or RFC3339)", + "description": "Custom EAT range start (YYYY-MM-DD or RFC3339)", "name": "from", "in": "query" }, { "type": "string", - "description": "Custom range end (YYYY-MM-DD or RFC3339, inclusive)", + "description": "Custom EAT range end (YYYY-MM-DD or RFC3339, inclusive)", "name": "to", "in": "query" + }, + { + "type": "string", + "description": "Filter payment/revenue metrics (e.g. CHAPA, ARIFPAY, ADMIN_GRANT)", + "name": "payment_method", + "in": "query" } ], "responses": { @@ -2078,126 +2382,6 @@ const docTemplate = `{ } } }, - "/api/v1/assessment/questions": { - "get": { - "description": "Returns all active assessment questions from the initial assessment set", - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "List assessment questions", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionWithDetails" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - }, - "post": { - "description": "Creates a new assessment question using the unified questions system", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "Create assessment question", - "parameters": [ - { - "description": "Create question payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/handlers.createQuestionReq" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, - "/api/v1/assessment/questions/{id}": { - "get": { - "description": "Returns a single assessment question with its options or answer", - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "Get assessment question by ID", - "parameters": [ - { - "type": "integer", - "description": "Question ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.QuestionWithDetails" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, "/api/v1/auth/apple": { "post": { "description": "Validates an Apple identity token (iOS, Android, or web). On first sign-in, include email and name if Apple only returns them to the client once.", @@ -2605,663 +2789,6 @@ const docTemplate = `{ "responses": {} } }, - "/api/v1/exam-prep/catalog-courses": { - "get": { - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep catalog courses", - "parameters": [ - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "post": { - "description": "Top-level exam track (DET, IELTS, …) in schema exam_prep — separate from LMS programs/courses", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep catalog course", - "parameters": [ - { - "description": "Catalog course", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepCatalogCourseInput" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/reorder": { - "put": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Reorder all exam-prep catalog courses", - "parameters": [ - { - "description": "ordered_ids: every catalog course id exactly once", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/{catalogCourseId}/units": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep units for a catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "post": { - "description": "Unit under a catalog course (e.g. chapter title). Optional sort_order assigns position within that catalog course (siblings at or after that index are shifted); omit to append after the current highest sort_order in the catalog course.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "description": "Unit", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepUnitInput" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/{catalogCourseId}/units/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder units within a catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "description": "ordered_ids: every unit id in this catalog course, new order", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/catalog-courses/{id}": { - "get": { - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep catalog course by ID", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "put": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepCatalogCourseInput" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/lessons/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep lesson by ID", - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep lesson", - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep lesson", - "responses": {} - } - }, - "/api/v1/exam-prep/lessons/{lessonId}/practices": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep practices for a lesson", - "parameters": [ - { - "type": "integer", - "description": "Exam prep lesson ID", - "name": "lessonId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep practice (under a lesson; uses shared question_sets)", - "parameters": [ - { - "type": "integer", - "description": "Exam prep lesson ID (unit_module_lessons.id)", - "name": "lessonId", - "in": "path", - "required": true - }, - { - "description": "Practice", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepPracticeInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep module by ID", - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep module", - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep module", - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{moduleId}/lessons": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep lessons for a unit module", - "parameters": [ - { - "type": "integer", - "description": "Exam prep unit module ID", - "name": "moduleId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep lesson (under a unit module)", - "parameters": [ - { - "type": "integer", - "description": "Exam prep unit module ID", - "name": "moduleId", - "in": "path", - "required": true - }, - { - "description": "Lesson", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepLessonInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{moduleId}/lessons/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder lessons within an exam-prep unit module", - "responses": {} - } - }, - "/api/v1/exam-prep/practices/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep practice by ID", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep practice", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepPracticeInput" - } - } - ], - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep practice", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep unit by ID", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepUnitInput" - } - } - ], - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{unitId}/modules": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep modules for a unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep module", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - }, - { - "description": "Module", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepModuleInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{unitId}/modules/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder modules within a unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - }, - { - "description": "ordered_ids", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": {} - } - }, "/api/v1/faqs": { "get": { "description": "Returns active FAQs for public/help center usage", @@ -3439,6 +2966,74 @@ const docTemplate = `{ } } }, + "/api/v1/files/complete-upload": { + "post": { + "description": "Call after PUT upload to upload_url. Returns the same file metadata shape as POST /files/upload.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "files" + ], + "summary": "Complete presigned MinIO upload", + "parameters": [ + { + "description": "Complete upload request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.completePresignedUploadReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/files/presign-upload": { + "post": { + "description": "Returns a short-lived PUT URL and object key. Upload the file with HTTP PUT to upload_url using the same Content-Type, then call POST /files/complete-upload.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "files" + ], + "summary": "Create presigned MinIO upload URL", + "parameters": [ + { + "description": "Presigned upload request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.presignedUploadReq" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/files/refresh-url": { "post": { "consumes": [ @@ -4127,14 +3722,14 @@ const docTemplate = `{ }, "/api/v1/lms/progress-summary": { "get": { - "description": "Returns the learner's nested LMS hierarchy with the same access progress data exposed on the individual program, course, module, and lesson APIs.", + "description": "Returns the learner's nested Learn English hierarchy (programs) and exam-prep hierarchy (exam_prep) with the same access progress data exposed on the individual content APIs.", "produces": [ "application/json" ], "tags": [ "lms" ], - "summary": "Get my LMS progress summary", + "summary": "Get my LMS and exam-prep progress summary", "responses": { "200": { "description": "OK", @@ -4353,9 +3948,36 @@ const docTemplate = `{ "responses": {} } }, + "/api/v1/modules/{moduleId}/lessons/reorder": { + "put": { + "tags": [ + "lessons" + ], + "summary": "Reorder lessons within a module", + "parameters": [ + { + "type": "integer", + "description": "Module ID", + "name": "moduleId", + "in": "path", + "required": true + }, + { + "description": "ordered_ids: every lesson id in this module, in the new order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ReorderIDsRequest" + } + } + ], + "responses": {} + } + }, "/api/v1/notifications/bulk-email": { "post": { - "description": "Sends an email to specified user IDs, all users of a role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339).", + "description": "Sends an email to specified user IDs, users of a platform role, team member IDs, team members of a team_role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339).", "consumes": [ "multipart/form-data" ], @@ -4388,6 +4010,89 @@ const docTemplate = `{ } } }, + "/api/v1/notifications/bulk-in-app": { + "post": { + "description": "Creates in-app notifications for specified platform user IDs, users matching a platform role, team member IDs, or team members matching a team_role. Optionally schedule for later with scheduled_at (RFC3339).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Send bulk in-app notification", + "parameters": [ + { + "description": "Bulk in-app content", + "name": "body", + "in": "body", + "required": true, + "schema": { + "type": "object", + "properties": { + "level": { + "type": "string" + }, + "message": { + "type": "string" + }, + "role": { + "type": "string" + }, + "scheduled_at": { + "type": "string" + }, + "team_member_ids": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "team_role": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + }, + "user_ids": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + } + } + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/notifications/bulk-push": { "post": { "description": "Sends a push notification to specified user IDs or all users matching a role. Optionally schedule for later with scheduled_at (RFC3339).", @@ -4528,6 +4233,52 @@ const docTemplate = `{ } } }, + "/api/v1/notifications/delete-in-app": { + "post": { + "description": "Deletes in-app notifications by ID for the authenticated user. Non-matching IDs are ignored.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Delete multiple in-app notifications", + "parameters": [ + { + "description": "Notification IDs", + "name": "body", + "in": "body", + "required": true, + "schema": { + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/notifications/scheduled": { "get": { "description": "Returns paginated scheduled notifications with optional status, channel, and date filters", @@ -4828,6 +4579,51 @@ const docTemplate = `{ } } } + }, + "delete": { + "description": "Deletes one in-app notification owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Delete a single in-app notification", + "parameters": [ + { + "type": "integer", + "description": "Notification ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } } }, "/api/v1/payments": { @@ -4946,6 +4742,118 @@ const docTemplate = `{ } } }, + "/api/v1/payments/chapa/direct": { + "post": { + "description": "Starts a Chapa Direct Charge (USSD push or OTP) for a subscription plan without hosted checkout redirect.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Initiate Chapa direct charge subscription payment", + "parameters": [ + { + "description": "Chapa direct charge request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.initiateChapaDirectPaymentReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/payments/chapa/direct/authorize": { + "post": { + "description": "Completes OTP authorization for Chapa direct charge methods that require it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Authorize Chapa direct charge with OTP", + "parameters": [ + { + "description": "Chapa direct charge authorization request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.authorizeChapaDirectPaymentReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/payments/chapa/direct/methods": { + "get": { + "description": "Returns wallet methods supported by Chapa Direct Charge API (USSD push and OTP flows).", + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Get Chapa direct charge payment methods", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/payments/chapa/success": { "get": { "description": "Displays the Rezina success page after Chapa redirects the learner to return_url", @@ -5428,6 +5336,32 @@ const docTemplate = `{ } }, "/api/v1/practices": { + "get": { + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Page size (default 20, max 200)", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Page offset (default 0)", + "name": "offset", + "in": "query" + }, + { + "type": "boolean", + "description": "When true, return only practices with no parent links (admin)", + "name": "unlinked_only", + "in": "query" + } + ], + "responses": {} + }, "post": { "consumes": [ "application/json" @@ -5437,7 +5371,7 @@ const docTemplate = `{ ], "parameters": [ { - "description": "Practice (parent_kind: COURSE | MODULE | LESSON)", + "description": "Practice (optional parents; link later via PUT /practices/:id/parents)", "name": "body", "in": "body", "required": true, @@ -5478,7 +5412,7 @@ const docTemplate = `{ "required": true }, { - "description": "Fields to update (parent is immutable)", + "description": "Practice metadata fields to update", "name": "body", "in": "body", "required": true, @@ -5505,9 +5439,161 @@ const docTemplate = `{ "responses": {} } }, + "/api/v1/practices/{id}/full": { + "get": { + "description": "Returns practice metadata, linked question set settings, and all questions in the set (same shape as PUT /practices/{id}/full).", + "produces": [ + "application/json" + ], + "tags": [ + "practices" + ], + "summary": "Get LMS practice with question set and questions", + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + }, + "put": { + "description": "Updates practice metadata, linked question set settings, and syncs questions in one request. Questions omitted from the questions array are removed from the set (not deleted from the bank).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "practices" + ], + "summary": "Full update LMS practice with question set and questions", + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Full practice update payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.FullUpdatePracticeInput" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/practices/{id}/parents": { + "put": { + "consumes": [ + "application/json" + ], + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Parent links (replaces all; use empty array to detach)", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdatePracticeParentsInput" + } + } + ], + "responses": {} + } + }, + "/api/v1/practices/{id}/parents/{parentKind}/{parentId}": { + "delete": { + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Parent kind (COURSE, MODULE, LESSON)", + "name": "parentKind", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Parent entity ID", + "name": "parentId", + "in": "path", + "required": true + } + ], + "responses": {} + } + }, "/api/v1/practices/{practiceId}/questions": { "get": { - "description": "Returns paginated questions for a practice(question-set), including AUDIO fields", + "description": "Returns paginated questions for an LMS practice, including shared stimulus blocks and each question's effective dynamic payload", "produces": [ "application/json" ], @@ -5518,7 +5604,7 @@ const docTemplate = `{ "parameters": [ { "type": "integer", - "description": "Practice(question-set) ID", + "description": "LMS practice ID", "name": "practiceId", "in": "path", "required": true @@ -6003,7 +6089,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Set type (PRACTICE, INITIAL_ASSESSMENT, QUIZ, EXAM, SURVEY, CAPSTONE)", + "description": "Set type (PRACTICE, QUIZ, EXAM, SURVEY, CAPSTONE)", "name": "set_type", "in": "query", "required": true @@ -6457,7 +6543,7 @@ const docTemplate = `{ }, "/api/v1/question-sets/{setId}/questions": { "get": { - "description": "Returns all questions in a question set with details", + "description": "Returns all questions in a question set with contextual shared stimulus data for linked LMS and exam-prep practices", "produces": [ "application/json" ], @@ -6496,7 +6582,7 @@ const docTemplate = `{ } }, "post": { - "description": "Links a question to a question set", + "description": "Links a question to a question set. Omit display_order to append after the current max; the assigned value is returned in the response.", "consumes": [ "application/json" ], @@ -6882,6 +6968,176 @@ const docTemplate = `{ } } }, + "/api/v1/questions/type-definition-groups": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "List question type definition groups", + "parameters": [ + { + "type": "string", + "description": "Filter by status (ACTIVE, INACTIVE)", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "default": 20, + "description": "Page size (default 20, max 200)", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Page offset", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Create question type definition group", + "parameters": [ + { + "description": "Group payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.createQuestionTypeDefinitionGroupReq" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/questions/type-definition-groups/{id}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Get question type definition group with definitions", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + }, + "put": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Update question type definition group", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Update group payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.updateQuestionTypeDefinitionGroupReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + }, + "delete": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Delete question type definition group", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/questions/type-definitions": { "get": { "produces": [ @@ -7115,6 +7371,61 @@ const docTemplate = `{ } } }, + "/api/v1/questions/type-definitions/{id}/practices": { + "get": { + "description": "Returns LMS and exam-prep practices whose linked question set contains at least one non-archived question matching the definition (by question_type_definition_id or legacy question_type).", + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "List practices globally by question type definition", + "parameters": [ + { + "type": "integer", + "description": "Question type definition id", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "default": 20, + "description": "Limit", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Offset", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/questions/validate-question-type-definition": { "post": { "description": "Validates selected stimulus and response component kinds for temporary question-type definitions (component-level validation only)", @@ -8150,7 +8461,7 @@ const docTemplate = `{ }, "/api/v1/subscription-plans": { "get": { - "description": "Returns all subscription plans", + "description": "Returns subscription plans. Optional category filter: EDUCATION.", "produces": [ "application/json" ], @@ -8161,9 +8472,15 @@ const docTemplate = `{ "parameters": [ { "type": "boolean", - "description": "Return only active plans", + "description": "Return only active plans (default true)", "name": "active_only", "in": "query" + }, + { + "type": "string", + "description": "Filter by plan category (EDUCATION)", + "name": "category", + "in": "query" } ], "responses": { @@ -8173,6 +8490,12 @@ const docTemplate = `{ "$ref": "#/definitions/domain.Response" } }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -8482,14 +8805,47 @@ const docTemplate = `{ }, "/api/v1/subscriptions/me": { "get": { - "description": "Returns the authenticated user's active subscription", + "description": "Returns all active subscriptions for the authenticated user (one per plan category)", "produces": [ "application/json" ], "tags": [ "subscriptions" ], - "summary": "Get current subscription", + "summary": "Get active subscriptions", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/subscriptions/request-checkout-link": { + "post": { + "description": "Sends the standalone web checkout URL to the learner by email or SMS (registration channel). Intended when mobile clients show a subscription-required state.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Send web checkout link to learner", + "parameters": [ + { + "description": "Optional plan or category for deep link", + "name": "body", + "in": "body", + "schema": { + "$ref": "#/definitions/handlers.requestCheckoutLinkReq" + } + } + ], "responses": { "200": { "description": "OK", @@ -8497,8 +8853,26 @@ const docTemplate = `{ "$ref": "#/definitions/domain.Response" } }, - "404": { - "description": "Not Found", + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "429": { + "description": "Too Many Requests", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "503": { + "description": "Service Unavailable", "schema": { "$ref": "#/definitions/domain.ErrorResponse" } @@ -9018,6 +9392,79 @@ const docTemplate = `{ } } } + }, + "put": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Update the authenticated team member's own profile fields", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Update my team profile", + "parameters": [ + { + "description": "Profile update payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateMyTeamProfileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.TeamMemberResponse" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } } }, "/api/v1/team/members": { @@ -9195,6 +9642,18 @@ const docTemplate = `{ } } }, + "/api/v1/team/members/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "team" + ], + "summary": "Export team members as CSV (admin)", + "responses": {} + } + }, "/api/v1/team/members/invite": { "post": { "description": "Creates a pending team member (email + team_role only) and sends an invitation email; profile is completed on accept", @@ -9704,6 +10163,110 @@ const docTemplate = `{ } } }, + "/api/v1/team/resetPassword": { + "post": { + "description": "Completes team password reset using email + OTP from the reset link. Public.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Reset team member password", + "parameters": [ + { + "description": "Reset payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.TeamResetPasswordReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/team/sendResetCode": { + "post": { + "description": "Sends a password-reset email with a link to the team member (admin panel). Public.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Send team password reset link", + "parameters": [ + { + "description": "Email", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.TeamSendPasswordResetReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/team/stats": { "get": { "security": [ @@ -9762,6 +10325,42 @@ const docTemplate = `{ } } }, + "/api/v1/team/verifyResetCode": { + "get": { + "description": "Checks whether email+otp from a reset link are still valid without consuming the OTP. Public.", + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Verify team password reset link", + "parameters": [ + { + "type": "string", + "description": "Team member email", + "name": "email", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Reset OTP from the email link", + "name": "otp", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/tenant": { "get": { "description": "Check if phone number or email exist", @@ -9911,6 +10510,64 @@ const docTemplate = `{ } } }, + "/api/v1/user/knowledge-level": { + "put": { + "description": "Updates the authenticated learner's self-reported knowledge level.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Update user's knowledge level", + "parameters": [ + { + "description": "Knowledge level", + "name": "knowledge_level", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateKnowledgeLevelReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/user/me": { "delete": { "security": [ @@ -10091,7 +10748,7 @@ const docTemplate = `{ }, "/api/v1/user/sendResetCode": { "post": { - "description": "Send reset code", + "description": "Sends a password-reset OTP code by email or SMS for learner (mobile) accounts. Email delivers the numeric code (not a link).", "consumes": [ "application/json" ], @@ -10485,7 +11142,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED)", + "description": "User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED, or INACTIVE for all non-ACTIVE statuses)", "name": "status", "in": "query" }, @@ -10530,6 +11187,18 @@ const docTemplate = `{ } } }, + "/api/v1/users/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "user" + ], + "summary": "Export users as CSV (admin)", + "responses": {} + } + }, "/api/v1/users/summary": { "get": { "security": [ @@ -11387,65 +12056,6 @@ const docTemplate = `{ } } }, - "/api/v1/{tenant_slug}/user/knowledge-level": { - "put": { - "description": "Updates the knowledge level of the specified user after initial assessment", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "Update user's knowledge level", - "parameters": [ - { - "type": "integer", - "description": "User ID", - "name": "user_id", - "in": "path", - "required": true - }, - { - "description": "Knowledge level", - "name": "knowledge_level", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateKnowledgeLevelReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, "/api/v1/{tenant_slug}/user/register": { "post": { "description": "Register user", @@ -11770,6 +12380,444 @@ const docTemplate = `{ } } }, + "domain.AdminExamPrepCatalogCourseLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "units": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepUnitLearningEntry" + } + } + } + }, + "domain.AdminExamPrepLessonLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminExamPrepModuleLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepLessonLearningEntry" + } + }, + "name": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminExamPrepPracticeLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "exam_prep_practice_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminExamPrepUnitLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepModuleLearningEntry" + } + }, + "name": { + "type": "string" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminExamPrepUserLearningActivityTree": { + "type": "object", + "properties": { + "catalog_courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepCatalogCourseLearningEntry" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminLMSCourseLearningEntry": { + "type": "object", + "properties": { + "course_level_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSModuleLearningEntry" + } + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSLessonLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "lesson_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminLMSModuleLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSLessonLearningEntry" + } + }, + "module_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSPracticeLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "lms_practice_id": { + "type": "integer" + }, + "scope": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminLMSProgramLearningEntry": { + "type": "object", + "properties": { + "courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSCourseLearningEntry" + } + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSUserLearningActivityTree": { + "type": "object", + "properties": { + "programs": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSProgramLearningEntry" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserExamPrepLearningSection": { + "type": "object", + "properties": { + "completions": { + "$ref": "#/definitions/domain.AdminExamPrepUserLearningActivityTree" + }, + "progress": { + "$ref": "#/definitions/domain.ExamPrepProgressSummary" + } + } + }, + "domain.AdminUserLMSLearningSection": { + "type": "object", + "properties": { + "completed_ids": { + "$ref": "#/definitions/domain.LMSUserProgress" + }, + "completions": { + "$ref": "#/definitions/domain.AdminLMSUserLearningActivityTree" + }, + "progress": { + "$ref": "#/definitions/domain.LMSProgressSummary" + } + } + }, + "domain.AdminUserLearningActivityDetails": { + "type": "object", + "properties": { + "exam_prep": { + "$ref": "#/definitions/domain.AdminUserExamPrepLearningSection" + }, + "lms": { + "$ref": "#/definitions/domain.AdminUserLMSLearningSection" + }, + "recent_activity": { + "$ref": "#/definitions/domain.UserRecentActivityFeed" + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionDetails": { + "type": "object", + "properties": { + "active_by_category": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + }, + "active_subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionRecord" + } + }, + "display_status": { + "type": "string" + }, + "has_active_subscription": { + "type": "boolean" + }, + "payments": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionPayment" + } + }, + "subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionRecord" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionPayment": { + "type": "object", + "properties": { + "amount": { + "type": "number" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "paid_at": { + "type": "string" + }, + "payment_method": { + "type": "string" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "status": { + "type": "string" + }, + "subscription_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionRecord": { + "type": "object", + "properties": { + "auto_renew": { + "type": "boolean" + }, + "cancelled_at": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "duration_unit": { + "type": "string" + }, + "duration_value": { + "type": "integer" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_currently_active": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, + "payment_method": { + "type": "string" + }, + "payment_reference": { + "type": "string" + }, + "plan_category": { + "type": "string" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "price": { + "type": "number" + }, + "starts_at": { + "type": "string" + }, + "status": { + "type": "string" + }, + "updated_at": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } + }, "domain.AgeGroup": { "type": "string", "enum": [ @@ -11888,6 +12936,9 @@ const docTemplate = `{ "month": { "type": "integer" }, + "payment_method": { + "type": "string" + }, "range_end": { "type": "string" }, @@ -11903,6 +12954,9 @@ const docTemplate = `{ "series_start": { "type": "string" }, + "timezone": { + "type": "string" + }, "to": { "type": "string" }, @@ -12138,9 +13192,98 @@ const docTemplate = `{ } } }, + "domain.AnalyticsSubscriptionRenewal": { + "type": "object", + "properties": { + "avg_days_to_resubscribe": { + "type": "number" + }, + "expired_in_period": { + "type": "integer" + }, + "first_time_subscriptions": { + "type": "integer" + }, + "median_days_to_resubscribe": { + "type": "number" + }, + "renewal_rate": { + "description": "0–1; renewed_after_expiry / expired_in_period", + "type": "number" + }, + "renewed_after_expiry": { + "type": "integer" + }, + "resubscribe_after_expiry": { + "type": "integer" + }, + "returning_subscriptions": { + "type": "integer" + } + } + }, + "domain.AnalyticsSubscriptionSnapshot": { + "type": "object", + "properties": { + "active_learners": { + "type": "integer" + }, + "active_now": { + "type": "integer" + }, + "auto_renew_enabled": { + "type": "integer" + }, + "cancelled_now": { + "type": "integer" + }, + "expired_now": { + "type": "integer" + }, + "expiring_within_30_days": { + "type": "integer" + }, + "expiring_within_7_days": { + "type": "integer" + }, + "lifetime_active": { + "type": "integer" + }, + "pending_now": { + "type": "integer" + }, + "term_active": { + "type": "integer" + } + } + }, "domain.AnalyticsSubscriptionsSection": { "type": "object", "properties": { + "acquisition_by_source": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_category": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_lifetime": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_plan": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "active_subscriptions": { "type": "integer" }, @@ -12150,6 +13293,24 @@ const docTemplate = `{ "$ref": "#/definitions/domain.AnalyticsLabelCount" } }, + "cancellations_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "expirations_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "new_by_cohort": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "new_month": { "type": "integer" }, @@ -12165,12 +13326,40 @@ const docTemplate = `{ "new_week": { "type": "integer" }, + "renewal": { + "description": "Resubscribe / renewal behaviour", + "allOf": [ + { + "$ref": "#/definitions/domain.AnalyticsSubscriptionRenewal" + } + ] + }, + "resubscriptions_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "revenue_by_category": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelAmount" + } + }, "revenue_by_plan": { "type": "array", "items": { "$ref": "#/definitions/domain.AnalyticsRevenueByPlan" } }, + "snapshot": { + "description": "Learner subscription behaviour", + "allOf": [ + { + "$ref": "#/definitions/domain.AnalyticsSubscriptionSnapshot" + } + ] + }, "total_subscriptions": { "type": "integer" } @@ -12228,6 +13417,12 @@ const docTemplate = `{ "$ref": "#/definitions/domain.AnalyticsLabelCount" } }, + "by_gender": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "by_knowledge_level": { "type": "array", "items": { @@ -12353,12 +13548,31 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the program when set; omit to append after current max within program_id (uniqueness is per-program).", "type": "integer", @@ -12376,6 +13590,15 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ @@ -12389,6 +13612,16 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" } @@ -12400,9 +13633,28 @@ const docTemplate = `{ "title" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" }, @@ -12420,6 +13672,15 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12429,6 +13690,16 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" } @@ -12440,6 +13711,29 @@ const docTemplate = `{ "question_set_id" ], "properties": { + "parent_id": { + "type": "integer" + }, + "parent_kind": { + "description": "ParentKind and ParentID are accepted for backward compatibility when parents is omitted.", + "enum": [ + "CATALOG_COURSE", + "UNIT", + "LESSON" + ], + "allOf": [ + { + "$ref": "#/definitions/domain.ExamPrepParentKind" + } + ] + }, + "parents": { + "description": "Parents optionally attaches the practice to catalog course, unit, or lesson. Omit or null to create unlinked.", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepPracticeParent" + } + }, "persona_id": { "type": "integer" }, @@ -12475,12 +13769,31 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the catalog course when set; omit to append after current max sort_order within catalog_course_id.", "type": "integer", @@ -12497,6 +13810,15 @@ const docTemplate = `{ "title" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12555,6 +13877,15 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12564,6 +13895,16 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the course when set; omit to append after current max within course_id (uniqueness is per-course).", "type": "integer", @@ -12574,8 +13915,6 @@ const docTemplate = `{ "domain.CreatePracticeInput": { "type": "object", "required": [ - "parent_id", - "parent_kind", "question_set_id" ], "properties": { @@ -12583,6 +13922,7 @@ const docTemplate = `{ "type": "integer" }, "parent_kind": { + "description": "ParentKind and ParentID are accepted for backward compatibility when parents is omitted.", "enum": [ "COURSE", "MODULE", @@ -12594,6 +13934,13 @@ const docTemplate = `{ } ] }, + "parents": { + "description": "Parents optionally attaches the practice to hierarchy entities. Omit or null to create unlinked.", + "type": "array", + "items": { + "$ref": "#/definitions/domain.PracticeParent" + } + }, "persona_id": { "type": "integer" }, @@ -12631,12 +13978,19 @@ const docTemplate = `{ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "description": { @@ -12645,6 +13999,16 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder inserts at this global program order when set; omit to append after current max (sort_order uniqueness is enforced).", "type": "integer", @@ -12655,6 +14019,21 @@ const docTemplate = `{ } } }, + "domain.CreateQuestionOptionInput": { + "type": "object", + "properties": { + "isCorrect": { + "type": "boolean" + }, + "optionOrder": { + "type": "integer", + "format": "int32" + }, + "optionText": { + "type": "string" + } + } + }, "domain.CreateRoleReq": { "type": "object", "required": [ @@ -12671,6 +14050,17 @@ const docTemplate = `{ } } }, + "domain.CreateShortAnswerInput": { + "type": "object", + "properties": { + "acceptableAnswer": { + "type": "string" + }, + "matchType": { + "type": "string" + } + } + }, "domain.CreateTeamMemberReq": { "type": "object", "required": [ @@ -12813,6 +14203,293 @@ const docTemplate = `{ } } }, + "domain.ExamPrepParentKind": { + "type": "string", + "enum": [ + "CATALOG_COURSE", + "UNIT", + "LESSON" + ], + "x-enum-varnames": [ + "ExamPrepParentKindCatalogCourse", + "ExamPrepParentKindUnit", + "ExamPrepParentKindLesson" + ] + }, + "domain.ExamPrepPracticeParent": { + "type": "object", + "properties": { + "parent_id": { + "type": "integer" + }, + "parent_kind": { + "$ref": "#/definitions/domain.ExamPrepParentKind" + } + } + }, + "domain.ExamPrepProgressSummary": { + "type": "object", + "properties": { + "catalog_courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryCatalogCourse" + } + } + } + }, + "domain.ExamPrepProgressSummaryCatalogCourse": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "units": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryUnit" + } + } + } + }, + "domain.ExamPrepProgressSummaryLesson": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "module_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.ExamPrepProgressSummaryModule": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryLesson" + } + }, + "name": { + "type": "string" + }, + "unit_id": { + "type": "integer" + } + } + }, + "domain.ExamPrepProgressSummaryUnit": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "catalog_course_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryModule" + } + }, + "name": { + "type": "string" + } + } + }, + "domain.FullUpdatePracticeInput": { + "type": "object", + "properties": { + "practice": { + "$ref": "#/definitions/domain.FullUpdatePracticeShellInput" + }, + "question_set": { + "$ref": "#/definitions/domain.FullUpdateQuestionSetInput" + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FullUpdatePracticeQuestionItem" + } + }, + "stimulus_blocks": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FullUpdateStimulusBlockItem" + } + } + } + }, + "domain.FullUpdatePracticeQuestionItem": { + "type": "object", + "properties": { + "associated_question_id": { + "type": "integer" + }, + "audio_correct_answer_text": { + "type": "string" + }, + "difficulty_level": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "dynamic_payload": { + "$ref": "#/definitions/domain.DynamicQuestionPayload" + }, + "explanation": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "image_url": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateQuestionOptionInput" + } + }, + "points": { + "type": "integer" + }, + "question_text": { + "type": "string" + }, + "question_type": { + "type": "string" + }, + "question_type_definition_id": { + "type": "integer" + }, + "sample_answer_voice_prompt": { + "type": "string" + }, + "short_answers": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateShortAnswerInput" + } + }, + "status": { + "type": "string" + }, + "stimulus_block_key": { + "type": "string" + }, + "tips": { + "type": "string" + }, + "voice_prompt": { + "type": "string" + } + } + }, + "domain.FullUpdatePracticeShellInput": { + "type": "object", + "properties": { + "authoring_profile": { + "type": "string" + }, + "persona_id": { + "type": "integer" + }, + "publish_status": { + "type": "string" + }, + "question_set_id": { + "type": "integer" + }, + "quick_tips": { + "type": "string" + }, + "story_description": { + "type": "string" + }, + "story_image": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "domain.FullUpdateQuestionSetInput": { + "type": "object", + "properties": { + "banner_image": { + "type": "string" + }, + "description": { + "type": "string" + }, + "intro_video_url": { + "type": "string" + }, + "passing_score": { + "type": "integer" + }, + "persona": { + "type": "string" + }, + "shuffle_questions": { + "type": "boolean" + }, + "status": { + "type": "string" + }, + "time_limit_minutes": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.FullUpdateStimulusBlockItem": { + "type": "object", + "properties": { + "block_key": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "stimulus": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.DynamicElementInstance" + } + } + } + }, "domain.InviteTeamMemberReq": { "type": "object", "required": [ @@ -12828,6 +14505,161 @@ const docTemplate = `{ } } }, + "domain.LMSEntityAccess": { + "type": "object", + "properties": { + "completed_count": { + "type": "integer" + }, + "is_accessible": { + "type": "boolean" + }, + "is_completed": { + "type": "boolean" + }, + "progress_percent": { + "type": "integer" + }, + "progress_percent_precise": { + "type": "number" + }, + "reason": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummary": { + "type": "object", + "properties": { + "exam_prep": { + "$ref": "#/definitions/domain.ExamPrepProgressSummary" + }, + "programs": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryProgram" + } + } + } + }, + "domain.LMSProgressSummaryCourse": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryModule" + } + }, + "name": { + "type": "string" + }, + "program_id": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummaryLesson": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "module_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.LMSProgressSummaryModule": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "course_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryLesson" + } + }, + "name": { + "type": "string" + }, + "program_id": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummaryProgram": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryCourse" + } + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + } + } + }, + "domain.LMSUserProgress": { + "type": "object", + "properties": { + "course_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "lesson_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "module_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "program_ids": { + "type": "array", + "items": { + "type": "integer" + } + } + } + }, "domain.LogEntry": { "type": "object", "properties": { @@ -12956,137 +14788,78 @@ const docTemplate = `{ } } }, - "domain.QuestionAudioAnswer": { + "domain.PracticeParent": { "type": "object", "properties": { - "correctAnswerText": { - "type": "string" + "parent_id": { + "type": "integer" }, - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer", - "format": "int64" - }, - "questionID": { - "type": "integer", - "format": "int64" + "parent_kind": { + "$ref": "#/definitions/domain.ParentKind" } } }, - "domain.QuestionOption": { + "domain.RecentActivityCourseRef": { "type": "object", "properties": { - "createdAt": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "isCorrect": { - "type": "boolean" - }, - "optionOrder": { - "type": "integer", - "format": "int32" - }, - "optionText": { + "name": { "type": "string" - }, - "questionID": { - "type": "integer", - "format": "int64" } } }, - "domain.QuestionShortAnswer": { + "domain.RecentActivityLessonRef": { "type": "object", "properties": { - "acceptableAnswer": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "matchType": { + "sort_order": { + "type": "integer" + }, + "title": { "type": "string" - }, - "questionID": { - "type": "integer", - "format": "int64" } } }, - "domain.QuestionWithDetails": { + "domain.RecentActivityModuleRef": { "type": "object", "properties": { - "audioAnswer": { - "$ref": "#/definitions/domain.QuestionAudioAnswer" - }, - "createdAt": { - "type": "string" - }, - "difficultyLevel": { - "type": "string" - }, - "dynamicPayload": { - "$ref": "#/definitions/domain.DynamicQuestionPayload" - }, - "explanation": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "imageURL": { + "name": { "type": "string" }, - "options": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionOption" - } + "sort_order": { + "type": "integer" + } + } + }, + "domain.RecentActivityPracticeRef": { + "type": "object", + "properties": { + "lms_practice_id": { + "type": "integer" }, - "points": { - "type": "integer", - "format": "int32" - }, - "questionText": { + "scope": { + "description": "lesson | module | course", "type": "string" }, - "questionType": { + "title": { "type": "string" + } + } + }, + "domain.RecentActivityProgramRef": { + "type": "object", + "properties": { + "id": { + "type": "integer" }, - "questionTypeDefinitionID": { - "type": "integer", - "format": "int64" - }, - "sampleAnswerVoicePrompt": { - "type": "string" - }, - "shortAnswers": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionShortAnswer" - } - }, - "status": { - "type": "string" - }, - "tips": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "voicePrompt": { + "name": { "type": "string" } } @@ -13154,6 +14927,7 @@ const docTemplate = `{ "enum": [ "SUPER_ADMIN", "ADMIN", + "CONTENT_MANAGER", "STUDENT", "OPEN_LEARNER", "INSTRUCTOR", @@ -13162,6 +14936,7 @@ const docTemplate = `{ "x-enum-varnames": [ "RoleSuperAdmin", "RoleAdmin", + "RoleContentManager", "RoleStudent", "RoleOpenLearner", "RoleInstructor", @@ -13349,6 +15124,26 @@ const docTemplate = `{ "TeamMemberStatusTerminated" ] }, + "domain.TeamResetPasswordReq": { + "type": "object", + "required": [ + "email", + "otp", + "password" + ], + "properties": { + "email": { + "type": "string" + }, + "otp": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + } + } + }, "domain.TeamRole": { "type": "string", "enum": [ @@ -13372,15 +15167,44 @@ const docTemplate = `{ "TeamRoleAnalyst" ] }, + "domain.TeamSendPasswordResetReq": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "type": "string" + } + } + }, "domain.UpdateCourseInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13392,6 +15216,15 @@ const docTemplate = `{ "domain.UpdateExamPrepCatalogCourseInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ @@ -13405,6 +15238,15 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13416,6 +15258,13 @@ const docTemplate = `{ "domain.UpdateExamPrepPracticeInput": { "type": "object", "properties": { + "authoring_profile": { + "type": "string", + "enum": [ + "STANDALONE", + "IELTS_SHARED_STIMULUS" + ] + }, "persona_id": { "type": "integer" }, @@ -13445,15 +15294,47 @@ const docTemplate = `{ } } }, + "domain.UpdateExamPrepPracticeParentsInput": { + "type": "object", + "required": [ + "parents" + ], + "properties": { + "parents": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepPracticeParent" + } + } + } + }, "domain.UpdateExamPrepUnitInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13477,6 +15358,15 @@ const docTemplate = `{ "domain.UpdateLessonInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -13526,6 +15416,15 @@ const docTemplate = `{ "domain.UpdateModuleInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -13535,14 +15434,59 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" } } }, + "domain.UpdateMyTeamProfileReq": { + "type": "object", + "properties": { + "bio": { + "type": "string" + }, + "department": { + "type": "string" + }, + "first_name": { + "type": "string" + }, + "job_title": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "phone_number": { + "type": "string" + }, + "profile_picture_url": { + "type": "string" + }, + "work_phone": { + "type": "string" + } + } + }, "domain.UpdatePracticeInput": { "type": "object", "properties": { + "authoring_profile": { + "type": "string", + "enum": [ + "STANDALONE", + "IELTS_SHARED_STIMULUS" + ] + }, "persona_id": { "type": "integer" }, @@ -13572,15 +15516,36 @@ const docTemplate = `{ } } }, + "domain.UpdatePracticeParentsInput": { + "type": "object", + "required": [ + "parents" + ], + "properties": { + "parents": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.PracticeParent" + } + } + } + }, "domain.UpdateProgramInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "description": { @@ -13589,6 +15554,15 @@ const docTemplate = `{ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13696,9 +15670,6 @@ const docTemplate = `{ "gender": { "type": "string" }, - "initial_assessment_completed": { - "type": "boolean" - }, "knowledge_level": { "type": "string" }, @@ -13734,6 +15705,12 @@ const docTemplate = `{ "domain.UserProfileResponse": { "type": "object", "properties": { + "active_subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserProfileSubscription" + } + }, "age_group": { "type": "string" }, @@ -13769,10 +15746,6 @@ const docTemplate = `{ "id": { "type": "integer" }, - "initial_assessment_completed": { - "description": "Profile fields", - "type": "boolean" - }, "language_challange": { "type": "string" }, @@ -13789,6 +15762,7 @@ const docTemplate = `{ "type": "string" }, "nick_name": { + "description": "Profile fields", "type": "string" }, "occupation": { @@ -13829,6 +15803,102 @@ const docTemplate = `{ } } }, + "domain.UserProfileSubscription": { + "type": "object", + "properties": { + "auto_renew": { + "type": "boolean" + }, + "category": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "duration_unit": { + "type": "string" + }, + "duration_value": { + "type": "integer" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_lifetime": { + "type": "boolean" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "price": { + "type": "number" + }, + "starts_at": { + "type": "string" + }, + "status": { + "type": "string" + } + } + }, + "domain.UserRecentActivityFeed": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserRecentActivityItem" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.UserRecentActivityItem": { + "type": "object", + "properties": { + "course": { + "$ref": "#/definitions/domain.RecentActivityCourseRef" + }, + "headline": { + "description": "Headline is optional server-rendered primary line (client may ignore and build from refs).", + "type": "string" + }, + "id": { + "type": "string" + }, + "kind": { + "description": "Kind drives default icon treatment on the client (e.g. joined vs completion).", + "type": "string" + }, + "lesson": { + "$ref": "#/definitions/domain.RecentActivityLessonRef" + }, + "module": { + "$ref": "#/definitions/domain.RecentActivityModuleRef" + }, + "occurred_at": { + "description": "OccurredAt is when the platform recorded the event (typically completion time).", + "type": "string" + }, + "practice": { + "$ref": "#/definitions/domain.RecentActivityPracticeRef" + }, + "program": { + "$ref": "#/definitions/domain.RecentActivityProgramRef" + } + } + }, "domain.UserStatus": { "type": "string", "enum": [ @@ -14346,8 +16416,15 @@ const docTemplate = `{ "question_id" ], "properties": { + "associated_question_id": { + "description": "Section anchor question in the same set; must have a lower display_order and no association of its own.", + "type": "integer", + "minimum": 1 + }, "display_order": { - "type": "integer" + "description": "Omit to append after the current highest display_order in the set; set explicitly to insert at a position.", + "type": "integer", + "minimum": 0 }, "question_id": { "type": "integer" @@ -14368,6 +16445,41 @@ const docTemplate = `{ } } }, + "handlers.adminApplySubscriptionReq": { + "type": "object", + "required": [ + "plan_id" + ], + "properties": { + "plan_id": { + "type": "integer", + "minimum": 1 + }, + "record_payment": { + "description": "RecordPayment when omitted defaults to true (record SUCCESS payment at plan price).", + "type": "boolean" + } + } + }, + "handlers.authorizeChapaDirectPaymentReq": { + "type": "object", + "required": [ + "otp", + "request_id", + "session_id" + ], + "properties": { + "otp": { + "type": "string" + }, + "request_id": { + "type": "string" + }, + "session_id": { + "type": "string" + } + } + }, "handlers.autoRenewReq": { "type": "object", "properties": { @@ -14394,6 +16506,20 @@ const docTemplate = `{ } } }, + "handlers.completePresignedUploadReq": { + "type": "object", + "properties": { + "file_size": { + "type": "integer" + }, + "media_type": { + "type": "string" + }, + "object_key": { + "type": "string" + } + } + }, "handlers.createEmailTemplateReq": { "type": "object", "required": [ @@ -14542,18 +16668,13 @@ const docTemplate = `{ "required": [ "category", "currency", - "duration_unit", - "duration_value", - "name", - "price" + "name" ], "properties": { "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "currency": { @@ -14563,21 +16684,20 @@ const docTemplate = `{ "type": "string" }, "duration_unit": { - "type": "string", - "enum": [ - "DAY", - "WEEK", - "MONTH", - "YEAR" - ] + "type": "string" }, "duration_value": { - "type": "integer", - "minimum": 1 + "type": "integer" }, "is_active": { "type": "boolean" }, + "is_free": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, "name": { "type": "string" }, @@ -14675,7 +16795,6 @@ const docTemplate = `{ "type": "string", "enum": [ "PRACTICE", - "INITIAL_ASSESSMENT", "QUIZ", "EXAM", "SURVEY", @@ -14696,6 +16815,26 @@ const docTemplate = `{ } } }, + "handlers.createQuestionTypeDefinitionGroupReq": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "description": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "status": { + "type": "string" + } + } + }, "handlers.createQuestionTypeDefinitionReq": { "type": "object", "required": [ @@ -14709,6 +16848,12 @@ const docTemplate = `{ "display_name": { "type": "string" }, + "group_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, "key": { "type": "string" }, @@ -14741,6 +16886,29 @@ const docTemplate = `{ } } }, + "handlers.initiateChapaDirectPaymentReq": { + "type": "object", + "required": [ + "email", + "payment_method", + "phone", + "plan_id" + ], + "properties": { + "email": { + "type": "string" + }, + "payment_method": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "plan_id": { + "type": "integer" + } + } + }, "handlers.initiateDirectPaymentReq": { "type": "object", "required": [ @@ -14887,6 +17055,23 @@ const docTemplate = `{ } } }, + "handlers.presignedUploadReq": { + "type": "object", + "properties": { + "content_type": { + "type": "string" + }, + "file_size": { + "type": "integer" + }, + "filename": { + "type": "string" + }, + "media_type": { + "type": "string" + } + } + }, "handlers.previewEmailTemplateReq": { "type": "object", "properties": { @@ -14921,6 +17106,17 @@ const docTemplate = `{ } } }, + "handlers.requestCheckoutLinkReq": { + "type": "object", + "properties": { + "category": { + "type": "string" + }, + "plan_id": { + "type": "integer" + } + } + }, "handlers.shortAnswerInput": { "type": "object", "required": [ @@ -15156,9 +17352,7 @@ const docTemplate = `{ "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "currency": { @@ -15176,6 +17370,12 @@ const docTemplate = `{ "is_active": { "type": "boolean" }, + "is_free": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, "name": { "type": "string" }, @@ -15190,6 +17390,10 @@ const docTemplate = `{ "display_order" ], "properties": { + "associated_question_id": { + "type": "integer", + "minimum": 1 + }, "display_order": { "type": "integer" } @@ -15283,44 +17487,26 @@ const docTemplate = `{ } } }, - "handlers.updateQuestionTypeDefinitionReq": { + "handlers.updateQuestionTypeDefinitionGroupReq": { "type": "object", "properties": { "description": { "type": "string" }, - "display_name": { + "display_order": { + "type": "integer" + }, + "name": { "type": "string" }, - "response_component_kinds": { - "type": "array", - "items": { - "type": "string" - } - }, - "response_schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.DynamicElementDefinition" - } - }, "status": { "type": "string" - }, - "stimulus_component_kinds": { - "type": "array", - "items": { - "type": "string" - } - }, - "stimulus_schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.DynamicElementDefinition" - } } } }, + "handlers.updateQuestionTypeDefinitionReq": { + "type": "object" + }, "handlers.validateQuestionTypeDefinitionReq": { "type": "object", "properties": { diff --git a/docs/initial-assessment-client-app-integration.md b/docs/initial-assessment-client-app-integration.md deleted file mode 100644 index dc879ea3..00000000 --- a/docs/initial-assessment-client-app-integration.md +++ /dev/null @@ -1,813 +0,0 @@ -# Initial Placement Assessment — Client App Integration Guide - -This guide documents how to integrate the **initial placement assessment** into the Rezina **learner mobile app** (iOS / Android / React Native / Flutter). The feature runs a **progressive, one-set-per-CEFR-level** flow: the learner starts at **A1**, answers that level’s published set, and advances to the next level only when they meet that level’s **pass score**. Failing a level (or running out of published higher sets) finalizes `knowledge_level` as the highest level already passed (A1 if none). - -> **Scope:** Learner-facing placement flow only. Admin configuration (per-level sets, questions, pass thresholds) is managed in **Rezina Admin** under **Content → Initial assessment** and is out of scope for the mobile client. - ---- - -## Table of contents - -1. [Feature overview](#feature-overview) -2. [How placement content is selected](#how-placement-content-is-selected) -3. [Prerequisites (ops / admin)](#prerequisites-ops--admin) -4. [Architecture](#architecture) -5. [Authentication](#authentication) -6. [Response envelopes](#response-envelopes) -7. [User profile flags](#user-profile-flags) -8. [Recommended UX flow](#recommended-ux-flow) -9. [API reference](#api-reference) -10. [Question payload shapes](#question-payload-shapes) -11. [Building answer payloads](#building-answer-payloads) -12. [Scoring & CEFR mapping](#scoring--cefr-mapping) -13. [Legacy knowledge-level endpoint](#legacy-knowledge-level-endpoint) -14. [TypeScript types](#typescript-types) -15. [Example API client](#example-api-client) -16. [React Native integration patterns](#react-native-integration-patterns) -17. [Error handling](#error-handling) -18. [Edge cases & product rules](#edge-cases--product-rules) -19. [Integration checklist](#integration-checklist) -20. [Quick reference](#quick-reference) - ---- - -## Feature overview - -| Capability | Client app | Backend | -|------------|------------|---------| -| Decide whether to show placement | Read `initial_assessment_completed` / `knowledge_level` from profile | Stored on `users` | -| Load session / next level | `GET /api/v1/assessment/session` (**auth**) | Progressive progress + published levels | -| Load placement questions | `GET /api/v1/assessment/questions?level=A1` | Published `INITIAL_ASSESSMENT` set for that CEFR level | -| Load one question | `GET /api/v1/assessment/questions/{id}` | Same scrubbing as list (no correct answers) | -| Submit & grade one level | `POST /api/v1/assessment/submit` (**auth**) `{ level, answers }` | Grades that level set vs pass threshold; advances or finalizes | -| Persist final result | When submit returns `completed: true` | Sets `knowledge_level` + `initial_assessment_completed = true` | - -### What the learner gets - -1. **One question set per CEFR level** (A1–C2), authored and published independently in admin. -2. Progressive testing: start at A1 → pass → next level → … until fail or C2 pass. -3. Questions authored as **Multiple choice** or **True / False** (recommended for auto-scoring). -4. Final profile `knowledge_level` = highest level **passed** (or `A1` if they fail A1). - -### What the client must **not** do - -- Do **not** grade answers locally for the official result — always call `POST /assessment/submit`. -- Do **not** skip levels or submit a level other than `session.next_level`. -- Do **not** trust or display `is_correct` from list/get responses (backend forces them to `false` / strips them). -- Do **not** call admin threshold APIs from the mobile app (`/admin/assessment/level-thresholds`). -- Do **not** rely on `PUT /user/knowledge-level` as the primary placement completion path (see [Legacy knowledge-level endpoint](#legacy-knowledge-level-endpoint)). - ---- - -## How placement content is selected - -1. **Level set:** published `question_sets` row with `set_type = 'INITIAL_ASSESSMENT'` and `description` = CEFR level (`A1`…`C2`). At most one published set per level. -2. **Questions:** only items in that set whose question `status = 'PUBLISHED'`. -3. **Progress:** server tracks `next_level` / `highest_passed_level` per user. Submit must use the current `next_level`. -4. **Pass mark:** `initial_assessment_level_thresholds.min_percent` for that level (default 70%). - -If a level’s set is draft, empty, or has no published questions, list/submit for that level fails. - ---- - -## Prerequisites (ops / admin) - -Before the app can run a successful placement flow: - -1. Run migrations through `000102_initial_assessment_per_level` (thresholds + progress + unique published-per-level). -2. In Admin → **Initial assessment**: - - For **each** CEFR level you want live, publish its set (“Live for learners”) with published MCQ / True-False questions. - - At minimum publish **A1** (learners always start there). - - Configure **Pass thresholds** (default 70% per level). -3. Optionally configure pass scores differently per level under the Pass thresholds tab. - ---- - -## Architecture - -```mermaid -sequenceDiagram - participant App as Mobile app - participant API as Rezina API - participant DB as Postgres - - App->>API: GET /user/user-profile (auth) - API-->>App: initial_assessment_completed, profile fields - - alt not completed - App->>API: GET /assessment/session (auth) - API-->>App: next_level, published_levels - - loop until completed - App->>API: GET /assessment/questions?level={next_level} - API->>DB: published INITIAL_ASSESSMENT set for that CEFR level - API-->>App: questions (correct answers scrubbed) - App->>App: Collect answers (option IDs) - App->>API: POST /assessment/submit { level, answers } (auth) - API->>DB: grade vs pass threshold; advance or finalize - API-->>App: passed, next_level?, completed, knowledge_level? - end - - App->>App: Show result screen; route into app - else already completed - App->>App: Skip placement (or show “retake” only if product allows) - end -``` - ---- - -## Authentication - -| Endpoint | Auth | -|----------|------| -| `GET /api/v1/assessment/session` | **Required** — learner JWT | -| `GET /api/v1/assessment/questions?level=` | **Public** (prefer after login) | -| `GET /api/v1/assessment/questions/:id` | **Public** | -| `POST /api/v1/assessment/submit` | **Required** — learner JWT | -| `GET /api/v1/user/user-profile` | **Required** | -| `PUT /api/v1/user/knowledge-level` | **Required** (learner JWT + `users.update_self`) — legacy / manual | - -**Recommendation:** Drive the flow from `GET /assessment/session` after login. Submit without a valid session returns `401`. - -Base URL pattern: - -```http -{API_BASE_URL}/api/v1/... -``` - -Example: - -```http -Authorization: Bearer eyJhbGciOi... -Content-Type: application/json -``` - ---- - -## Response envelopes - -Successful responses typically look like: - -```json -{ - "message": "Questions fetched successfully", - "data": [ /* payload */ ], - "success": true, - "status_code": 200, - "metadata": null -} -``` - -Errors: - -```json -{ - "message": "Human-readable summary", - "error": "Detail string" -} -``` - -Always read the business payload from `data`. - ---- - -## User profile flags - -After login / on app launch, load the learner profile: - -```http -GET /api/v1/user/user-profile -Authorization: Bearer -``` - -Relevant fields: - -| Field | Type | Meaning | -|-------|------|---------| -| `initial_assessment_completed` | `boolean` | `true` after a successful `POST /assessment/submit` | -| `knowledge_level` | `string` (when present on profile / user objects) | After placement: CEFR code `A1`…`C2` | - -> **Note:** Some profile DTOs historically emphasized `initial_assessment_completed` more than `knowledge_level`. After submit, trust the **submit response** (`knowledge_level` / `level`) and refresh the profile. If your profile mapper omits `knowledge_level`, use the submit result and any user-detail endpoint your app already uses that includes it. - -### Gating recommendation - -```text -IF !user.initial_assessment_completed - → show Placement Assessment flow (blocking or soft gate) -ELSE - → continue normal onboarding / home -``` - -Product choices: - -- **Hard gate:** cannot enter main content until completed. -- **Soft gate:** can dismiss and take later (still call submit when finished). - -Retakes: submit can be called again; it **overwrites** `knowledge_level` and keeps `initial_assessment_completed = true`. Decide in the app whether retakes are allowed. - ---- - -## Recommended UX flow - -1. **Gate** — After auth, if `initial_assessment_completed === false`, open Placement. -2. **Intro** — Explain that answers determine starting level (A1–C2); optional time limit if you surface set metadata later. -3. **Load questions** — `GET /assessment/questions`; show loading / empty / error states. -4. **Quiz UI** — One question per screen or a scrollable list; support MCQ and True/False. -5. **Local draft answers** — Keep `{ question_id, selected_option_ids[] }` in memory (and optionally secure storage if process death is a concern). -6. **Submit** — Disable UI, call `POST /assessment/submit`. -7. **Result** — Show `score_percent`, `level` (e.g. “You’re at **B1**”), optional breakdown from `questions[]`. -8. **Continue** — Persist flags in app state; navigate home / curriculum. - -Shuffle: if the published set has `shuffle_questions = true`, the list API currently returns set order from DB; client may shuffle locally for UX **only if** product wants it — grading does not depend on order. - ---- - -## API reference - -### 1. Placement session - -```http -GET /api/v1/assessment/session -Authorization: Bearer -``` - -**Success `data`:** - -```json -{ - "next_level": "A1", - "highest_passed_level": null, - "completed": false, - "initial_assessment_completed": false, - "published_levels": ["A1", "A2", "B1"] -} -``` - -When `completed` is true, `knowledge_level` is set and the app should skip the flow (unless product allows a retake via support/admin reset). - -### 2. List placement questions for a level - -```http -GET /api/v1/assessment/questions?level=A1 -``` - -**Auth:** optional (public). **`level`** defaults to `A1` when omitted; prefer the `next_level` from session. - -**Success `data`:** array of question objects (see [Question payload shapes](#question-payload-shapes)). - -**Important scrubbing (anti-cheat):** - -- Flat `options[].is_correct` is forced to `false`. -- `short_answers` removed. -- `audio_correct_answer_text` removed. -- Dynamic payload option `is_correct` keys stripped. - -**404:** no published set for that level. - ---- - -### 3. Get one placement question - -```http -GET /api/v1/assessment/questions/{id} -``` - -**Auth:** optional (public). - -Same scrubbing as list. Useful for deep links; most apps only need the list endpoint. - ---- - -### 4. Submit one CEFR level (primary) - -```http -POST /api/v1/assessment/submit -Authorization: Bearer -Content-Type: application/json -``` - -**Body:** - -```json -{ - "level": "A1", - "answers": [ - { - "question_id": 303, - "selected_option_ids": [1201] - }, - { - "question_id": 304, - "selected_option_ids": [1210] - } - ] -} -``` - -| Field | Required | Description | -|-------|----------|-------------| -| `level` | yes | Must equal `session.next_level` | -| `answers` | yes (can be `[]`) | One entry per answered question | -| `answers[].question_id` | yes | Question ID from list | -| `answers[].selected_option_ids` | for MCQ / True-False | Numeric option primary keys from `options[].id` | -| `answers[].text_answer` | for short-answer (if ever present) | string | -| `answers[].dynamic_answers` | for DYNAMIC MC slots | see below | - -**Success `data` example (continue):** - -```json -{ - "question_set_id": 42, - "level_attempted": "A1", - "score_percent": 80, - "passed": true, - "pass_percent": 70, - "next_level": "A2", - "completed": false, - "level": "A1", - "points_earned": 8, - "points_max": 10, - "gradable_questions": 10, - "correct_questions": 8, - "skipped_ungradable_questions": 0, - "questions": [], - "initial_assessment_completed": false -} -``` - -**Success `data` example (finalized):** - -```json -{ - "question_set_id": 43, - "level_attempted": "A2", - "score_percent": 40, - "passed": false, - "pass_percent": 70, - "completed": true, - "level": "A1", - "knowledge_level": "A1", - "initial_assessment_completed": true, - "points_earned": 4, - "points_max": 10, - "gradable_questions": 10, - "correct_questions": 4, - "skipped_ungradable_questions": 0, - "questions": [] -} -``` - -On finalize the API also updates: - -- `users.knowledge_level` ← final CEFR (`A1`…`C2`) -- `users.initial_assessment_completed` ← `true` - -**HTTP errors:** - -| Status | When | -|--------|------| -| `401` | Missing / invalid auth | -| `404` | No published placement set | -| `400` | No gradable questions / validation failure | -| `500` | Unexpected server error | - ---- - -## Question payload shapes - -List/get items follow the shared `questionRes` shape. Fields you typically need: - -```json -{ - "id": 303, - "question_text": "Choose the correct greeting.", - "question_type": "MCQ", - "difficulty_level": "EASY", - "points": 1, - "tips": null, - "explanation": null, - "status": "PUBLISHED", - "options": [ - { "id": 1201, "option_text": "Hello", "option_order": 1, "is_correct": false }, - { "id": 1202, "option_text": "Goodbye", "option_order": 2, "is_correct": false } - ], - "dynamic_payload": null -} -``` - -### Types the mobile app should support first - -| `question_type` | UI | Answer field | -|-----------------|----|--------------| -| `MCQ` | Radio / single select among `options` | `selected_option_ids: [option.id]` | -| `TRUE_FALSE` | True / False (usually two options) | `selected_option_ids: [option.id]` | - -Admin product guidance is **MCQ + True/False only**. Still tolerate missing `question_text` when content lives in `dynamic_payload` (see below). - -### Dynamic / outbound shape (important) - -For some deployments the API **normalizes** legacy MCQ/True-False into `dynamic_payload` and may **omit** top-level `question_text` / `options`. Mobile should resolve display content as: - -1. Prefer flat `question_text` if non-empty. -2. Else read stimulus text from `dynamic_payload.stimulus` where `kind` is one of `QUESTION_TEXT`, `INSTRUCTION`, `TEXT_PASSAGE`, `TEXT`. -3. Prefer flat `options` if present and non-empty. -4. Else read `dynamic_payload.response[]` entries with `kind` `MULTIPLE_CHOICE` or `OPTION`, and parse `value.options` (or a bare options array). - -Example dynamic fragment: - -```json -{ - "question_type": "MCQ", - "question_text": null, - "options": null, - "dynamic_payload": { - "stimulus": [ - { "id": "question_text_1", "kind": "QUESTION_TEXT", "value": "Pick the correct article." } - ], - "response": [ - { - "id": "multiple_choice_1", - "kind": "MULTIPLE_CHOICE", - "value": { - "options": [ - { "id": "a", "text": "a", "option_text": "a" }, - { "id": "b", "text": "an", "option_text": "an" } - ] - } - } - ] - } -} -``` - -**Answering rules when options are only dynamic:** - -- Prefer submitting classic `selected_option_ids` **when flat numeric `options[].id` exist**. -- If only string option IDs exist in the dynamic slot, submit: - -```json -{ - "question_id": 303, - "dynamic_answers": [ - { - "element_id": "multiple_choice_1", - "selected_option_ids": ["a"] - } - ] -} -``` - ---- - -## Building answer payloads - -### Single-select MCQ / True-False (flat options) - -```ts -function answerMcq(questionId: number, optionId: number) { - return { - question_id: questionId, - selected_option_ids: [optionId], - }; -} -``` - -Rules: - -- Send **exactly** the set of correct option IDs expected by the server for multi-correct items (rare for placement; usually one). -- Omitting a question from `answers` counts as incorrect / skipped for scoring (0 points), but still counts in the denominator if the question is gradable. - -### Do not send - -- Correctness flags -- Explanations -- Threshold configuration - ---- - -## Scoring & CEFR mapping - -Progressive placement (authoritative on server): - -1. Only **auto-gradable** questions count: `MCQ`, `TRUE_FALSE`, `SHORT_ANSWER`, and DYNAMIC multiple-choice/option slots. -2. `AUDIO` / other dynamic kinds are **skipped** and do not affect the percentage denominator. -3. For the attempted level: `score_percent = points_earned / points_max * 100`. -4. **Pass** if `score_percent >= pass_percent` for that level (`min_percent` in admin thresholds; default **70%**). -5. On **pass**: if a next CEFR level has a published set → `next_level` returned and assessment continues; if C2 passed or next set missing → finalize. -6. On **fail**: finalize. `knowledge_level` = highest level already passed, or **A1** if none. - -The mobile app should display `passed`, `next_level`, and final `knowledge_level` from the submit response — do not recompute locally. - ---- - -## Legacy knowledge-level endpoint - -```http -PUT /api/v1/user/knowledge-level -Authorization: Bearer -Content-Type: application/json - -{ "knowledge_level": "B1" } -``` - -Requires a valid learner JWT. Without auth middleware the handler cannot resolve the caller (this used to be a routing bug — the route must include `authMiddleware`). - -This updates `knowledge_level` **without** going through grading and historically expected values like beginner/intermediate/advanced. Prefer **`POST /assessment/submit`** for placement. - -Use the legacy endpoint only if product still has a “pick your level manually” escape hatch — and then set `initial_assessment_completed` via submit or confirm whether your backend path marks completion (submit is the path that sets both fields). - ---- - -## TypeScript types - -```ts -export type CefrLevel = "A1" | "A2" | "B1" | "B2" | "C1" | "C2"; - -export interface PlacementOption { - id: number; - option_text: string; - option_order: number; - is_correct?: boolean; // always false/untrusted on learner APIs -} - -export interface DynamicElement { - id: string; - kind: string; - value?: unknown; -} - -export interface DynamicQuestionPayload { - stimulus: DynamicElement[]; - response: DynamicElement[]; -} - -export interface PlacementQuestion { - id: number; - question_text?: string | null; - question_type: string; - difficulty_level?: string | null; - points?: number; - tips?: string | null; - explanation?: string | null; - status?: string; - options?: PlacementOption[] | null; - dynamic_payload?: DynamicQuestionPayload | null; -} - -export interface PlacementAnswer { - question_id: number; - selected_option_ids?: number[]; - text_answer?: string; - dynamic_answers?: Array<{ - element_id: string; - selected_option_ids?: string[]; - text_answer?: string; - }>; -} - -export interface PlacementQuestionResult { - question_id: number; - question_type: string; - gradable: boolean; - correct: boolean; - points_earned: number; - points_max: number; - skipped: boolean; -} - -export interface PlacementSubmitResult { - question_set_id: number; - score_percent: number; - level: CefrLevel | string; - points_earned: number; - points_max: number; - gradable_questions: number; - correct_questions: number; - skipped_ungradable_questions: number; - questions: PlacementQuestionResult[]; - knowledge_level: CefrLevel | string; - initial_assessment_completed: boolean; -} - -export interface ApiEnvelope { - message: string; - data: T; - success: boolean; - status_code?: number; - metadata?: unknown; -} -``` - ---- - -## Example API client - -```ts -const API_BASE = process.env.EXPO_PUBLIC_API_BASE_URL; // e.g. https://api.example.com/api/v1 - -async function api( - path: string, - opts: RequestInit & { token?: string } = {}, -): Promise { - const headers: Record = { - Accept: "application/json", - ...(opts.body ? { "Content-Type": "application/json" } : {}), - ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), - }; - const res = await fetch(`${API_BASE}${path}`, { ...opts, headers }); - const body = await res.json(); - if (!res.ok) { - throw new Error(body?.error || body?.message || `HTTP ${res.status}`); - } - return body.data as T; -} - -export function listPlacementQuestions() { - return api("/assessment/questions"); -} - -export function submitPlacement(token: string, answers: PlacementAnswer[]) { - return api("/assessment/submit", { - method: "POST", - token, - body: JSON.stringify({ answers }), - }); -} -``` - -### Resolving prompt + choices for UI - -```ts -function stimulusText(q: PlacementQuestion): string { - const flat = (q.question_text ?? "").trim(); - if (flat) return flat; - const kinds = ["QUESTION_TEXT", "INSTRUCTION", "TEXT_PASSAGE", "TEXT"]; - for (const kind of kinds) { - for (const el of q.dynamic_payload?.stimulus ?? []) { - if (String(el.kind).toUpperCase() !== kind) continue; - if (typeof el.value === "string" && el.value.trim()) return el.value.trim(); - } - } - return `Question #${q.id}`; -} - -type UiOption = { key: string; label: string; numericId?: number }; - -function uiOptions(q: PlacementQuestion): UiOption[] { - if (q.options?.length) { - return [...q.options] - .sort((a, b) => a.option_order - b.option_order) - .map((o) => ({ - key: String(o.id), - label: o.option_text, - numericId: o.id, - })); - } - for (const el of q.dynamic_payload?.response ?? []) { - const kind = String(el.kind).toUpperCase(); - if (kind !== "MULTIPLE_CHOICE" && kind !== "OPTION") continue; - const value = el.value as any; - const raw = Array.isArray(value) ? value : value?.options; - if (!Array.isArray(raw)) continue; - return raw.map((o: any, i: number) => ({ - key: String(o.id ?? i), - label: String(o.option_text ?? o.text ?? ""), - })); - } - return []; -} -``` - ---- - -## React Native integration patterns - -### Screen state machine - -```text -idle → loadingQuestions → inProgress → submitting → result - ↘ error -``` - -### Minimal hook sketch - -```ts -function usePlacementAssessment(token: string) { - const [questions, setQuestions] = useState([]); - const [answers, setAnswers] = useState>({}); // questionId → optionId - const [result, setResult] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - listPlacementQuestions() - .then(setQuestions) - .catch((e) => setError(String(e.message || e))); - }, []); - - async function submit() { - const payload: PlacementAnswer[] = Object.entries(answers).map( - ([questionId, optionId]) => ({ - question_id: Number(questionId), - selected_option_ids: [optionId], - }), - ); - const graded = await submitPlacement(token, payload); - setResult(graded); - return graded; - } - - return { questions, answers, setAnswers, submit, result, error }; -} -``` - -### Offline / background - -- Prefer completing submit while online. -- If you cache questions offline, still require online submit for official CEFR write. -- Do not store correct answers client-side (they are not returned). - ---- - -## Error handling - -| Situation | UX | -|-----------|----| -| Empty question list | “Placement test is not available yet.” Retry / support | -| Network failure on list | Retry button | -| `401` on submit | Refresh token / re-login, then retry with same answers | -| `404` on submit | Set unpublished — show ops message | -| `400` no gradable questions | Same as empty / misconfigured content | -| Partial answers | Allowed; score will be lower — optionally warn “Unanswered questions count as incorrect” | - -Idempotency: submitting twice overwrites the stored level; show a confirm dialog on retake. - ---- - -## Edge cases & product rules - -1. **Draft questions** never appear — admins must publish each question. -2. **Draft placement set** — learners get no set (`404` on submit / empty list). -3. **Multiple published sets** — learners always get the newest preferred standalone set; clients never pass a set ID. -4. **Points** — use `points` for progress UI if desired; server score uses the same. -5. **Explanations / tips** — may be present on the question object; safe to show **after** submit using local copy, or hide until result screen (they are not authoritative grading data). -6. **Create assessment question** `POST /assessment/questions` exists for legacy tooling — **do not** use it from the learner app. -7. **Thresholds** are admin-only; do not hardcode bands except for offline demos. - ---- - -## Integration checklist - -- [ ] After login, read `initial_assessment_completed` and gate UX. -- [ ] Implement `GET /assessment/questions` loader + empty/error states. -- [ ] Render MCQ and True/False (flat `options` and dynamic fallback). -- [ ] Track selected option IDs per question. -- [ ] Call `POST /assessment/submit` with bearer token. -- [ ] Show `score_percent` + `level` / `knowledge_level` on result screen. -- [ ] Refresh local user session/profile after success. -- [ ] Handle `401` / `404` / `400` with actionable copy. -- [ ] Confirm staging has a **published** set and **published** questions before QA. -- [ ] QA score bands against admin thresholds (change a threshold in admin and verify mapping). -- [ ] Decide product policy for retakes and unanswered questions. - ---- - -## Quick reference - -| Action | Method & path | Auth | -|--------|---------------|------| -| List questions | `GET /api/v1/assessment/questions` | Public | -| Get question | `GET /api/v1/assessment/questions/{id}` | Public | -| Submit & grade | `POST /api/v1/assessment/submit` | Learner JWT | -| Profile gate | `GET /api/v1/user/user-profile` | Learner JWT | -| Manual level (legacy) | `PUT /api/v1/user/knowledge-level` | Learner JWT | - -**Submit body (typical):** - -```json -{ "answers": [{ "question_id": 1, "selected_option_ids": [10] }] } -``` - -**Success highlights:** - -```json -{ - "score_percent": 70, - "level": "B1", - "knowledge_level": "B1", - "initial_assessment_completed": true -} -``` - -**CEFR levels:** `A1`, `A2`, `B1`, `B2`, `C1`, `C2`. - ---- - -## Related admin surface - -For content authors / QA: - -- Admin route: `/new-content/initial-assessment` -- Tabs: Placement set · Questions · Score thresholds -- Questions must be **Published** to reach the mobile list/submit pipeline - -This completes the learner-app integration path for the graded initial placement assessment. diff --git a/docs/initial-assessment-question-writing-guide.md b/docs/initial-assessment-question-writing-guide.md deleted file mode 100644 index 1127dad3..00000000 --- a/docs/initial-assessment-question-writing-guide.md +++ /dev/null @@ -1,137 +0,0 @@ -# Writing questions for the initial assessment - -This guide is for anyone building or reviewing the question sets used to place a learner at a starting English level. The aim is to get a useful estimate of what a learner can do, not to catch them out or produce a long exam. - -## How the placement assessment works - -The assessment is organized into separate question sets for CEFR levels A1 through C2. A learner works through the levels progressively. The system grades a level set against its configured pass threshold: a pass moves the learner on to the next level, while a non-pass ends the progression and records the resulting level. As a result, each level set needs enough questions to give a stable signal, and the questions should genuinely reflect that level. - -The backend currently auto-grades `MCQ`, `TRUE_FALSE`, `SHORT_ANSWER`, and supported `DYNAMIC` questions whose response contains multiple-choice or option slots. `AUDIO` and other dynamic response types are returned to the learner, but are skipped in the placement score. A set with no gradable questions cannot be submitted successfully. This distinction matters: a question can be useful in a broader language course but still contribute nothing to placement as the feature currently works. - -## Recommended mix - -Use a mix of the following, weighted toward questions that can be marked consistently: - -| Format | Best use in placement | Scoring status | -|---|---|---| -| Multiple choice (`MCQ`) | Vocabulary, grammar in context, reading comprehension | Auto-graded | -| True/false (`TRUE_FALSE`) | A small number of checks against a short text or dialogue | Auto-graded; use sparingly | -| Short answer (`SHORT_ANSWER`) | A word, phrase, or tightly constrained form with known acceptable answers | Auto-graded against configured answers | -| Dynamic multiple choice / option | Builder-based versions of selected-answer questions, such as a cloze passage with selectable answers | Auto-graded when the response slot is supported | -| Audio or open response | Listening or speaking evidence, if useful to the learning program | Currently not included in placement scoring | - -For a first version, make multiple choice the backbone. Add short answers only where the accepted response can be defined without ambiguity. Use dynamic item types only after confirming that their answer format is one the placement grader supports. Do not count on audio, free writing, speaking, matching, ordering, or other builder formats to affect a learner's placement result unless grading support has been added and verified. - -True/false is easy to answer by guessing, so it should not dominate a set. If used, tie it to a short passage or exchange and make the statement test understanding rather than a tiny wording detail. - -## What to assess - -### Vocabulary - -Test whether the learner can understand a word in a realistic sentence or exchange. Avoid isolated definitions when context can show how the word is used. At early levels, common everyday words are appropriate; at higher levels, test nuance, collocation, and meaning in context. - -### Grammar - -Ask learners to choose or supply a form that makes sense in a sentence or short conversation. Cover a range of useful structures at each level. Avoid questions where two answers are acceptable in ordinary English, even if one is the answer key you had in mind. - -### Reading - -Use short, level-appropriate passages such as a message, notice, short story, or practical instruction. Ask about the main point, a stated detail, or a simple inference. Keep the passage and question together so the answer does not depend on outside knowledge. - -### Listening - -Listening can add valuable evidence, but audio questions currently do not count toward the automatic placement score. They may be included for a separate, non-scored experience, but should not be used to determine the level until the scoring path supports them. If listening is made gradable later, use clear recordings, provide any necessary replay rules, and test comprehension rather than audio quality or accent familiarity. - -### Writing and speaking - -Open writing and speaking can reveal more than selected-answer questions, especially at higher levels. They also need rubrics and usually human review. The current placement score does not grade open-ended responses. Treat them as separate diagnostic evidence unless a reliable scoring process is implemented. - -## Build a clear progression across CEFR levels - -Each published set should represent its own CEFR band, not just be a harder copy of the previous one. Keep instructions and language accessible at the level being assessed. A learner should be able to understand what the question asks even when they do not know the answer. - -- **A1:** familiar people, places, routines, basic needs, simple present forms, common words, and very short messages. -- **A2:** everyday exchanges, routine past and future references, simple descriptions, and short practical texts. -- **B1:** familiar topics and experiences, connected text, opinions with simple reasons, and common less-predictable situations. -- **B2:** more detailed explanations, main ideas and implications in longer texts, and a broader range of vocabulary and structures. -- **C1:** nuanced meaning, tone, argument structure, less predictable language, and demanding but still fair texts. -- **C2:** precise interpretation, subtle distinctions, complex arguments, and flexible command of language. Avoid making specialist subject knowledge the hidden test. - -These are drafting cues, not a substitute for a CEFR-aligned review. Have a language educator check that the vocabulary, text length, and task demand fit the intended level. - -## Writing good multiple-choice items - -1. Put one clear task in the prompt. State the context needed to answer it. -2. Make sure exactly one option is correct, unless the interface and scoring are deliberately configured for multiple correct selections. -3. Write plausible distractors based on likely learner errors. Avoid joke answers or options that are obviously unrelated. -4. Keep options similar in length and grammatical form. Do not let the correct answer stand out by style. -5. Avoid “all of the above,” “none of the above,” tricky negatives, and clues copied from the prompt. -6. Check that no distractor is also acceptable in common usage or a different reasonable interpretation of the context. -7. Keep each question independent unless a shared passage is intentionally used. One wrong answer should not give away or determine another. - -**Example (A2 vocabulary)** - -> The bus leaves at 8:15. We should arrive at the station by 8:00 so we have time to ___ our tickets. -> -> A. buy -> B. borrow -> C. invite -> D. explain - -The context makes the intended meaning clear, and the distractors are possible English verbs without being equally suitable answers. - -## Writing short-answer items - -Short-answer questions work best when the response is brief and predictable: a word, a form, or a short phrase. The system compares the learner's response with the acceptable answers configured for the question. It is not a substitute for assessing an open paragraph. - -- List ordinary variants that should receive credit, such as a common spelling or contraction, where appropriate. -- Keep the expected response narrow enough that a correct answer can be recognized consistently. -- Avoid prompts that could reasonably be answered in several different ways unless every valid form is entered as acceptable. -- Check capitalization, punctuation, and spacing behavior before relying on a distinction. Prefer not to make those details the point of the item. -- Do not use short answer for free translation or open writing unless the accepted-answer list can cover legitimate responses fairly. - -## Dynamic questions - -The question builder supports many stimulus and response components, but the placement grader supports only specific response patterns. A dynamic question is not automatically gradable just because it can be created or displayed in the admin panel. For placement, use dynamic multiple-choice or option responses only when their configuration and submitted answer are supported by the grader. Confirm this with a representative authored item before building a whole level set around it. - -Formats such as audio response, sequence ordering, matching, label selection, or open text may be useful elsewhere in the LMS. Do not assume they contribute to placement until the grading implementation explicitly handles them. - -## Balance, length, and points - -Keep each level set short enough that a learner can finish without fatigue. Include enough questions to sample more than one skill area, but do not inflate the set with near-duplicates. A practical starting point is around 10–15 gradable questions per level, adjusted after educators review the learner experience and score stability. - -Use points consistently. If a question has no positive point value, the grader treats it as worth one point. For an initial version, giving each question one point makes the result easier to explain and avoids accidental weighting. If some items receive more weight, document why and check that the threshold still produces sensible outcomes. - -Mix task types and content areas, but do not let a single unfamiliar topic decide the result. For example, a learner's knowledge of a specialized sport or workplace should not determine their English level. - -## Common problems to catch before publishing - -- A set contains only questions the placement grader skips. -- The correct option is exposed by length, grammar, or a repeated phrase. -- More than one answer is defensible, or the answer key is wrong. -- A short-answer key omits common valid forms. -- The question tests cultural or specialist knowledge instead of English ability. -- Several questions test the same narrow grammar point while other useful abilities are absent. -- Reading text is far above the level even though the questions are labeled for a lower band. -- A question depends on information not included in the prompt or passage. -- A dynamic question was previewed in the builder but never checked through the placement submission and scoring flow. -- A set is published before confirming that it has at least one gradable question; in practice, all intended scored questions should be gradable. - -## Review checklist - -Before publishing a level set, confirm that: - -- The set is labeled with the intended CEFR level (A1–C2). -- Its questions are appropriate to that level and cover a reasonable range of language use. -- Every scored item has one unambiguous answer key or an adequate list of acceptable short answers. -- Question wording and answer options have been proofread by someone other than the author. -- Correct answers are not visible to learners in the question response. -- Every question intended to affect placement uses a currently auto-graded format. -- A sample submission produces the expected score and pass/fail progression for the configured threshold. -- Unscored diagnostic items are clearly understood to be excluded from the placement result. - -## Suggested authoring workflow - -Draft the set in a document first. For each item, record its target level, skill or language point, question format, correct answer, and reason the distractors are plausible. Have a second reviewer check the answer key and level. Enter the questions into the matching `INITIAL_ASSESSMENT` set, preview them as a learner, and verify a sample submission end to end. Revise items that are confusing or too easy to guess before publishing. - -The strongest placement set is not the one with the most elaborate question formats. It is the one whose questions are clear, level-appropriate, gradable, and broad enough to give a dependable picture of the learner's English. diff --git a/docs/overview.md b/docs/overview.md index 0b2dee9e..a1db62f0 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -87,8 +87,7 @@ Request → Fiber middleware (CORS, logging, resolveFileURLs) → authMiddleware (JWT parse → Locals: user_id / team_member_id, role, permissions) → RequirePermission("key") // admin write paths - → RequireLMSSubscriptionUnlessFree() // learner LMS reads - → RequireExamPrepSubscription() // exam-prep group + → RequireLMSSubscriptionUnlessFree() // learner course reads → Handler (thin: bind, validate, call service, map domain errors → HTTP) → Service (business rules, orchestration) → Repository (sqlc queries) @@ -108,11 +107,9 @@ Cron (same process): scheduled notification dispatch, account-deletion purge, su --- -## Two parallel content domains +## Learning content -The most important design decision: **LMS and exam prep are separate trees**, not polymorphic aliases. - -### Learn English (LMS) — `public` schema +The active learning hierarchy is organized for academic programs and subject-focused remedial instruction. ``` programs @@ -122,29 +119,9 @@ programs └── practices → questions ``` -- Programs have `category = LEARN_ENGLISH` only (migration `000080`). - Reorder: `PUT /programs/reorder`, `/programs/:id/courses/reorder`, `/courses/:id/modules/reorder`, `/modules/:id/lessons/reorder`. - Learner routes use `RequireLMSSubscriptionUnlessFree()` — `FREE` access tier content bypasses subscription. -### Exam prep — `exam_prep` schema - -``` -catalog_courses (category: IELTS | DUOLINGO) - └── units - └── unit_modules - └── lessons - └── practices → questions (shared question engine) -``` - -- Route prefix: `/api/v1/exam-prep/*`. -- Group middleware: `RequireExamPrepSubscription()` — checks active sub with matching `IELTS` or `DUOLINGO` category. -- Catalog course **requires** `category` on create (`CreateExamPrepCatalogCourseInput`). - -### Shared practice engine - -Both domains use the same **practices / questions / stimulus blocks / dynamic question types** services, with different parent-link tables and permission keys (`practices.*` vs `exam_prep.practices.*`). - -Practices support **multi-parent** links and explicit unlink (`DELETE .../parents/:parentKind/:parentId`). --- @@ -173,11 +150,7 @@ Refresh: separate endpoints for learners and team (`/auth/refresh`, `/team/refre Plans (`subscription_plans.category`): -| Category | Unlocks | Expiry model | -|----------|---------|--------------| -| `LEARN_ENGLISH` | LMS content (non-free tier) | Duration-based; renewal reminders | -| `IELTS` | Exam prep catalog where `category = IELTS` | Lifetime sentinel expiry | -| `DUOLINGO` | Exam prep catalog where `category = DUOLINGO` | Lifetime sentinel expiry | +Subscription plan categories are stored in the database and control access to paid learning content. Historic category rows may remain during migration; course content itself is organized by the LMS hierarchy. Active row: `user_subscriptions` joined to plan. Content entities carry: @@ -201,7 +174,6 @@ Registered in `internal/web_server/routes.go`. Representative groups: | `/auth/*` | register, login, OTP, Google, Apple, refresh | Public / JWT | | `/team/*` | login, invite, accept-invite, members CRUD | Team JWT | | `/programs`, `/courses`, `/modules`, `/lessons` | LMS CRUD + learner GET | JWT + permissions / subscription | -| `/exam-prep/*` | catalog courses → units → modules → lessons | JWT + exam prep sub | | `/practices`, `/questions` | LMS practice engine | JWT + permissions | | `/progress/*`, `/lms/progress*` | lesson complete, practice complete | Learner JWT + LMS sub | | `/subscriptions/*` | plans, checkout, me, request-checkout-link | Mixed | @@ -257,7 +229,6 @@ Backup: `make backup` / `make restore`. | Team | `services/team` | Invites, team CRUD | | RBAC | `services/rbac` | Custom roles / permissions | | Programs / courses | `services/programs`, `courses`, `modules`, `lessons` | LMS tree | -| Exam prep | `services/examprep` | Catalog tree | | Practices | `services/practices`, `practicecontent`, `questions` | Content + assessment | | Assessment | `services/assessment` | Scoring / evaluation | | Subscriptions | `services/subscriptions` | Plans, checkout, entitlements | @@ -299,10 +270,8 @@ For a peer engineer — use Swagger + one code walk: | # | Show | Point | |---|------|-------| -| 1 | `routes.go` lines 86–180 | Two content trees + middleware chain | +| 1 | `routes.go` lines 86–180 | Learning content routes + middleware chain | | 2 | Swagger → `GET /programs` | LMS list; note permission + subscription middleware | -| 3 | Swagger → `GET /exam-prep/catalog-courses` | Separate schema; `category` field | -| 4 | `domain/exam_prep_catalog_course.go` | Validation at boundary | | 5 | `POST /subscriptions/checkout` | Server creates Chapa session; no client-side secret | | 6 | `GET /subscriptions/me` | Entitlement source of truth for apps | | 7 | `db/query/` + `gen/db` | sqlc workflow | diff --git a/docs/recommended-question-types-for-remedial-education.md b/docs/recommended-question-types-for-remedial-education.md new file mode 100644 index 00000000..87259944 --- /dev/null +++ b/docs/recommended-question-types-for-remedial-education.md @@ -0,0 +1,216 @@ +# Writing Questions for Rezina LMS + +## A practical guide for lessons, practice, and review + +Rezina is being shaped for remedial and makeup education. Questions should help a teacher see what a learner understands, where a step went wrong, and what to practise next. A question can be simple and still do that well. More elaborate formats are useful when the learner needs to work with a diagram, sort steps, or connect related ideas, but they should earn their place by making the task clearer. + +This guide covers the question formats available through the backend question builder, how to use them across subjects, and what to consider when building image-based activities. It is written for the day-to-day work of teaching: introducing an idea, giving learners practice, checking understanding, and deciding what to revisit. + +## Start with the learning evidence + +Before choosing a format, write down what a correct response would show. For example: + +- The learner can identify the numerator and denominator in a fraction. +- The learner can put the stages of a process in order. +- The learner can find the part of a plant shown in a diagram. +- The learner can explain why a particular operation is needed. + +Then choose the response format that lets the learner show that evidence with the least distraction. Avoid turning a question into a puzzle about the interface. If reading is not the skill being assessed, keep the instructions short and familiar. + +## Recommended question formats + +The builder separates question content (the **stimulus**) from the learner's response. A stimulus can combine text, an image, a passage, a table, audio, or an attachment with one or more response components. The names in parentheses are the backend component names and may appear in the admin interface. + +### 1. Single-answer and multiple-answer choice + +**Backend components:** `MULTIPLE_CHOICE`, `OPTION`; legacy question types also include `MCQ` and `TRUE_FALSE`. + +Use a choice question when the aim is to check recognition, understanding of a concept, or a common misconception. It works well for a quick lesson check, a short practice round, or revision where the learner can get immediate feedback. + +**Good fits** + +- Select the equivalent fraction from four options. +- Choose the force that would make an object slow down. +- Identify the main idea of a short paragraph. +- Select all statements that describe a mammal, when selecting every correct statement is part of the learning objective. + +**Writing notes** + +- Ask one clear question. Keep the options similar in length and grammatical form. +- Use plausible distractors based on mistakes learners actually make. Avoid silly options that make the answer obvious. +- State whether the learner should choose one answer or every correct answer. +- Keep option sets to a manageable size. Three or four strong options are usually better than a long list of weak ones. +- Avoid “all of the above” and “none of the above”; they make reasoning less visible. +- When an item allows more than one correct answer, make sure the scoring and learner instructions match that intent. + +### 2. True or false + +**Backend components:** a `TRUE_FALSE` question, or a builder definition configured for the same response. + +Use this sparingly to check a single, precise statement. It is fast to answer, but the learner has a high chance of guessing correctly, and the format rarely shows how they reached the answer. + +**Example:** “A rectangle always has four right angles.” + +Avoid statements that hinge on a hidden exception, a vague word such as “usually,” or two claims joined together. For important concepts, ask the learner to choose a reason or correct a false statement in a follow-up practice item. + +### 3. Short answer + +**Backend component:** `SHORT_ANSWER` (with `TEXT_INPUT` available as a response component). + +Use a short answer when the learner should recall a term, number, or brief phrase without seeing a list of options. It is useful for vocabulary, labels, basic facts, and short calculations. + +**Examples** + +- “What is 7 × 8?” +- “Name the gas that plants take in during photosynthesis.” +- “Write the fraction shown in the diagram.” + +Automatic checking can compare configured acceptable answers using exact, case-insensitive, or contains matching. It does not understand equivalent wording or mathematical equivalence on its own. Add acceptable variants deliberately (for example, `0.5` and `1/2` if both should count), and do not use “contains” matching where an accidental partial match could be marked correct. Questions that need working, reasoning, units, or nuanced wording should be reviewed by a teacher or assessed with a separate structured item. + +### 4. Matching + +**Backend components:** `MATCHING_INPUTS` in the stimulus and `MATCHING_ANSWER` in the response. + +Use matching to connect two related sets: word and definition, symbol and meaning, cause and effect, or object and label. Keep the sets short enough that learners can compare them without losing track. + +**Examples** + +- Match each fraction to its picture. +- Match a scientific instrument to what it measures. +- Match a historical event to its period. + +Do not rely on color alone to distinguish pairs. If answers can be reused, say so; otherwise, make the one-to-one relationship clear. Check that the learner app supports the matching interaction and that its scoring behavior is suitable for the lesson. If not, a teacher can review the result or the same content can be presented as a choice question. + +### 5. Put in order + +**Backend component:** `SEQUENCE_ORDER`. + +Use sequencing when the order itself matters: steps in a calculation, stages in a life cycle, events in a timeline, or instructions for a practical task. + +**Examples** + +- Put the steps for finding a common denominator in order. +- Arrange the stages of seed germination. +- Place events on a short timeline. + +Keep the sequence focused on one process and avoid steps that could reasonably happen in either order. Give enough context to make the start and end clear. The backend exposes this as a builder response type; confirm the learner app supports the intended interaction and scoring before publishing it. + +### 6. Select missing words + +**Backend components:** `SELECT_MISSING_WORDS` in the stimulus and/or response. + +Use a gap-fill passage to check understanding in context, especially for key vocabulary, grammar within a subject explanation, or a short procedure. Keep the passage short and make each blank test an important idea rather than a minor word. + +**Examples** + +- A short science explanation with a missing term such as “evaporation.” +- A worked method with the name of a missing step. +- A sentence about a number pattern with the missing value. + +Do not remove so many words that the passage becomes a guessing game. Make sure the surrounding clues do not make the answer trivial. The format exists in the builder; check how the learner app displays it and handles submitted answers. + +### 7. Label an image or select a location + +**Backend components:** `IMAGE` as stimulus and `LABEL_SELECTION` as a response component. + +Image-based questions can make a concept concrete. A learner might select a part of a diagram, match labels to a figure, identify a feature on a map, or choose a point on a number line. The backend catalog provides image stimulus and label-selection response components, which are the building blocks for this kind of activity. + +**Useful applications** + +- Label the numerator and denominator in a fraction model. +- Select the heart chamber named in the prompt. +- Identify a landform on a map. +- Mark the point that represents a value on a number line. +- Choose the angle being discussed in a geometry figure. + +Keep the image legible on a phone-sized screen. Use a concise prompt and make target areas large enough to tap. Provide a text equivalent or accessible labels where possible, and never make color the only clue. Crop out irrelevant details and use consistent orientation. If the learner must place several labels, keep the number small and group related labels. + +**Implementation note:** `IMAGE` and `LABEL_SELECTION` are available component kinds, but their presence alone does not guarantee that every deployed learner app renders clickable hotspots or scores them. Confirm the client payload, answer submission, and scoring behavior before building a lesson around an interactive image. If that path is not available, keep the image as a visual prompt and ask a conventional multiple-choice or short-answer question about it. + +### 8. Tables and data interpretation + +**Backend component:** `TABLE` as stimulus; pair it with a suitable response such as multiple choice or short answer. + +Tables are a useful way to present measurements, schedules, survey results, or number patterns without embedding the data in a long paragraph. Ask one thing at a time: find a value, compare two entries, or infer a simple relationship. + +Check that headings include units and that the table remains readable on narrow screens. For younger learners or those still building reading fluency, avoid dense tables with unnecessary rows and columns. + +### 9. Reading passage with a question + +**Backend component:** `TEXT_PASSAGE` as stimulus; use a response that tests the intended reading or subject skill. + +A short passage can provide context for comprehension, science, social studies, or applied numeracy. Ask about information that the learner can locate or infer from the passage, and make clear whether outside knowledge is expected. + +Keep passages short enough that learners can focus on the idea being taught. If the goal is science knowledge rather than reading endurance, use direct language and, where appropriate, a diagram or table alongside the text. + +### 10. Audio prompt and spoken response + +**Backend components:** `AUDIO_PROMPT` stimulus and `AUDIO_RESPONSE` response. + +Audio can make sense when listening or oral explanation is part of the objective—for example, following spoken instructions or explaining a solution aloud. Consider device access, speech differences, and the time needed to review recordings before making audio response a routine part of a course. + +Provide a written alternative when audio is not itself the skill being taught. Audio responses may need teacher review or a learner app that provides its own feedback. + +### 11. File or PDF response + +**Backend components:** `PDF_ATTACHMENT` stimulus and `PDF_UPLOAD` response. + +Use a file upload when the learner needs to submit a page of working, a diagram, or a longer piece of written work. Give a clear file type and size expectation, and offer a way to complete the work if the learner has no scanner or camera. + +## Use images with a teaching purpose + +An interactive image should help the learner notice or manipulate something meaningful. A clickable picture added only for decoration adds loading time and visual clutter without improving the evidence the question provides. + +When planning an image activity, write down: + +1. **What the learner does:** select one region, place a label, connect labels, or mark a point. +2. **What counts as correct:** identify the accepted target or targets, including any reasonable alternatives. +3. **How it works without a mouse:** support touch and keyboard operation where the client allows it. +4. **What happens when it is unavailable:** provide a clear text-based alternative if the image or interaction cannot be used. +5. **How it is scored:** decide whether the response can be checked automatically or needs teacher review, then verify that the deployed client and backend support that route. + +For diagrams, use a clear source image, meaningful alt text, and labels that do not overlap important details. For maps, include a scale or orientation if the task depends on it. For number lines and charts, make tick marks, axes, units, and legends easy to read. Avoid putting essential question wording only inside the image. + +## Keep practice sets balanced + +A useful set samples several important skills without overloading any one of them. For each subject and lesson, consider whether it includes: + +- Core knowledge or vocabulary. +- Applying a method or concept to a new example. +- Reading a diagram, table, or passage when that is part of the subject. +- At least one item that can reveal a likely misconception. + +Avoid making every item a simple recall question. At the same time, do not make every item long or complex: the assessment should leave enough time for learners to think, not spend the session deciphering instructions. + +## A short review checklist for authors + +Before publishing a question, check: + +- Does it measure one clear learning objective? +- Is the expected answer unambiguous and the marking key correct? +- Are the distractors plausible and free of accidental clues? +- Is the wording appropriate for the learner's reading level? +- Does the chosen response type work on the learner's expected devices? +- If an image or audio clip is used, does it contribute directly to the task? +- Is there an accessible alternative where one is needed? +- If a response needs automatic grading, have you confirmed that the learner app and backend support it? + +## Backend component reference + +| Purpose | Builder components | +| --- | --- | +| Prompt and directions | `QUESTION_TEXT`, `INSTRUCTION` | +| Preparation or answer time | `PREP_TIME`, `ANSWER_TIMER` | +| Reading content | `TEXT_PASSAGE` | +| Image stimulus | `IMAGE` | +| Matching content and response | `MATCHING_INPUTS`, `MATCHING_ANSWER` | +| Missing-word activity | `SELECT_MISSING_WORDS` | +| Table or data | `TABLE` | +| PDF resource or learner submission | `PDF_ATTACHMENT`, `PDF_UPLOAD` | +| Audio stimulus and recording | `AUDIO_PROMPT`, `AUDIO_RESPONSE` | +| Text response | `TEXT_INPUT`, `SHORT_ANSWER` | +| Choice response | `MULTIPLE_CHOICE`, `OPTION` | +| Image label or target selection | `LABEL_SELECTION` | +| Ordering activity | `SEQUENCE_ORDER` | + +The builder catalog describes the components available to compose question types. A component being listed does not by itself guarantee that a particular learner app or scoring flow implements it end to end. Validate the full path in the client that learners will use. diff --git a/docs/swagger.json b/docs/swagger.json index 4315b879..5cbedbdf 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -100,6 +100,18 @@ } } }, + "/api/v1/activity-logs/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "activity-logs" + ], + "summary": "Export activity logs as CSV (admin)", + "responses": {} + } + }, "/api/v1/activity-logs/{id}": { "get": { "description": "Returns a single activity log entry by its ID", @@ -1407,7 +1419,7 @@ }, { "type": "string", - "description": "Plan category (LEARN_ENGLISH, IELTS, DUOLINGO)", + "description": "Plan category (EDUCATION)", "name": "plan_category", "in": "query" }, @@ -1484,6 +1496,18 @@ } } }, + "/api/v1/admin/payments/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "payments" + ], + "summary": "Export payments as CSV (admin)", + "responses": {} + } + }, "/api/v1/admin/payments/{id}": { "get": { "description": "Returns any payment record by ID without learner ownership restriction", @@ -1657,6 +1681,70 @@ } } }, + "/api/v1/admin/subscriptions/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "subscriptions" + ], + "summary": "Export user subscriptions as CSV (admin)", + "responses": {} + } + }, + "/api/v1/admin/subscriptions/{id}/cancel": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Cancels any user_subscriptions row by ID. Does not require ownership by the caller.", + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Cancel a learner subscription (admin)", + "parameters": [ + { + "type": "integer", + "description": "Subscription ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/users/deletion-requests": { "get": { "description": "Returns account deletion requests for admin panel tracking with filtering and pagination", @@ -1754,6 +1842,82 @@ } } }, + "/api/v1/admin/users/{user_id}/learning-activity": { + "get": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Returns LMS and exam-prep completion trees, progress summaries, completed ID snapshots, and recent activity timeline", + "produces": [ + "application/json" + ], + "tags": [ + "lms" + ], + "summary": "Get full learning activity for a user (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target user ID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Max recent-activity items (default 40, max 120)", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Include practice completions in recent-activity feed", + "name": "include_practices", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUserLearningActivityDetails" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/users/{user_id}/lms-learning-activity": { "get": { "security": [ @@ -1864,6 +2028,140 @@ } } }, + "/api/v1/admin/users/{user_id}/subscriptions": { + "get": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Returns display status, active plans by category, full subscription history, and related payments", + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Get all subscription details for a user (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target user ID", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUserSubscriptionDetails" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/admin/users/{user_id}/subscriptions/extend": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Unified admin action: if the learner has no active subscription in the plan's category, creates one (grant). If they already have an active subscription in that category, extends it by one period of the selected plan (and switches plan_id when different). Optionally records a SUCCESS payment at the plan price (record_payment, default true).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Grant or extend a learner subscription (admin)", + "parameters": [ + { + "type": "integer", + "description": "Target learner user ID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "description": "Plan to grant or extend", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.adminApplySubscriptionReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/admin/{id}": { "get": { "description": "Get a single admin by id", @@ -1966,7 +2264,7 @@ }, "/api/v1/analytics/dashboard": { "get": { - "description": "Platform analytics with optional date filters: all-time (default), year, year+month, or custom from/to range. When year is set, payments.revenue_monthly returns Jan–Dec SUCCESS revenue totals (UTC) per currency for that calendar year — use for yearly revenue charts. Daily series remains in revenue_last_30_days (see date_filter.series_*). Courses section counts LMS + exam_prep inventory.", + "description": "Platform analytics with optional date filters in Africa/Addis_Ababa (EAT): all-time (default), year, year+month, or custom from/to range. When year is set, payments.revenue_monthly returns Jan–Dec SUCCESS revenue totals (EAT) per currency for that calendar year. Optional payment_method filters payment/revenue metrics (exact or METHOD:% variants). Daily series remains in revenue_last_30_days (see date_filter.series_*). Courses section counts LMS + exam_prep inventory.", "produces": [ "application/json" ], @@ -1977,27 +2275,33 @@ "parameters": [ { "type": "integer", - "description": "Calendar year (e.g. 2025)", + "description": "EAT calendar year (e.g. 2025)", "name": "year", "in": "query" }, { "type": "integer", - "description": "Calendar month 1-12 (requires year)", + "description": "EAT calendar month 1-12 (requires year)", "name": "month", "in": "query" }, { "type": "string", - "description": "Custom range start (YYYY-MM-DD or RFC3339)", + "description": "Custom EAT range start (YYYY-MM-DD or RFC3339)", "name": "from", "in": "query" }, { "type": "string", - "description": "Custom range end (YYYY-MM-DD or RFC3339, inclusive)", + "description": "Custom EAT range end (YYYY-MM-DD or RFC3339, inclusive)", "name": "to", "in": "query" + }, + { + "type": "string", + "description": "Filter payment/revenue metrics (e.g. CHAPA, ARIFPAY, ADMIN_GRANT)", + "name": "payment_method", + "in": "query" } ], "responses": { @@ -2070,126 +2374,6 @@ } } }, - "/api/v1/assessment/questions": { - "get": { - "description": "Returns all active assessment questions from the initial assessment set", - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "List assessment questions", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionWithDetails" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - }, - "post": { - "description": "Creates a new assessment question using the unified questions system", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "Create assessment question", - "parameters": [ - { - "description": "Create question payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/handlers.createQuestionReq" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, - "/api/v1/assessment/questions/{id}": { - "get": { - "description": "Returns a single assessment question with its options or answer", - "produces": [ - "application/json" - ], - "tags": [ - "assessment-question" - ], - "summary": "Get assessment question by ID", - "parameters": [ - { - "type": "integer", - "description": "Question ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.QuestionWithDetails" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, "/api/v1/auth/apple": { "post": { "description": "Validates an Apple identity token (iOS, Android, or web). On first sign-in, include email and name if Apple only returns them to the client once.", @@ -2597,663 +2781,6 @@ "responses": {} } }, - "/api/v1/exam-prep/catalog-courses": { - "get": { - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep catalog courses", - "parameters": [ - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "post": { - "description": "Top-level exam track (DET, IELTS, …) in schema exam_prep — separate from LMS programs/courses", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep catalog course", - "parameters": [ - { - "description": "Catalog course", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepCatalogCourseInput" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/reorder": { - "put": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Reorder all exam-prep catalog courses", - "parameters": [ - { - "description": "ordered_ids: every catalog course id exactly once", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/{catalogCourseId}/units": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep units for a catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "post": { - "description": "Unit under a catalog course (e.g. chapter title). Optional sort_order assigns position within that catalog course (siblings at or after that index are shifted); omit to append after the current highest sort_order in the catalog course.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "description": "Unit", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepUnitInput" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/catalog-courses/{catalogCourseId}/units/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder units within a catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "catalogCourseId", - "in": "path", - "required": true - }, - { - "description": "ordered_ids: every unit id in this catalog course, new order", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/catalog-courses/{id}": { - "get": { - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep catalog course by ID", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "put": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepCatalogCourseInput" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep catalog course", - "parameters": [ - { - "type": "integer", - "description": "Catalog course ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - } - } - } - }, - "/api/v1/exam-prep/lessons/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep lesson by ID", - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep lesson", - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep lesson", - "responses": {} - } - }, - "/api/v1/exam-prep/lessons/{lessonId}/practices": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep practices for a lesson", - "parameters": [ - { - "type": "integer", - "description": "Exam prep lesson ID", - "name": "lessonId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep practice (under a lesson; uses shared question_sets)", - "parameters": [ - { - "type": "integer", - "description": "Exam prep lesson ID (unit_module_lessons.id)", - "name": "lessonId", - "in": "path", - "required": true - }, - { - "description": "Practice", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepPracticeInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep module by ID", - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep module", - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep module", - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{moduleId}/lessons": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep lessons for a unit module", - "parameters": [ - { - "type": "integer", - "description": "Exam prep unit module ID", - "name": "moduleId", - "in": "path", - "required": true - }, - { - "type": "integer", - "default": 20, - "description": "Page size", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "default": 0, - "description": "Offset", - "name": "offset", - "in": "query" - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep lesson (under a unit module)", - "parameters": [ - { - "type": "integer", - "description": "Exam prep unit module ID", - "name": "moduleId", - "in": "path", - "required": true - }, - { - "description": "Lesson", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepLessonInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/modules/{moduleId}/lessons/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder lessons within an exam-prep unit module", - "responses": {} - } - }, - "/api/v1/exam-prep/practices/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep practice by ID", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep practice", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepPracticeInput" - } - } - ], - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep practice", - "parameters": [ - { - "type": "integer", - "description": "Exam prep practice ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{id}": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "Get exam-prep unit by ID", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Update exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Fields to update", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateExamPrepUnitInput" - } - } - ], - "responses": {} - }, - "delete": { - "tags": [ - "exam-prep" - ], - "summary": "Delete exam-prep unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{unitId}/modules": { - "get": { - "tags": [ - "exam-prep" - ], - "summary": "List exam-prep modules for a unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - } - ], - "responses": {} - }, - "post": { - "tags": [ - "exam-prep" - ], - "summary": "Create exam-prep module", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - }, - { - "description": "Module", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateExamPrepModuleInput" - } - } - ], - "responses": {} - } - }, - "/api/v1/exam-prep/units/{unitId}/modules/reorder": { - "put": { - "tags": [ - "exam-prep" - ], - "summary": "Reorder modules within a unit", - "parameters": [ - { - "type": "integer", - "description": "Unit ID", - "name": "unitId", - "in": "path", - "required": true - }, - { - "description": "ordered_ids", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReorderIDsRequest" - } - } - ], - "responses": {} - } - }, "/api/v1/faqs": { "get": { "description": "Returns active FAQs for public/help center usage", @@ -3431,6 +2958,74 @@ } } }, + "/api/v1/files/complete-upload": { + "post": { + "description": "Call after PUT upload to upload_url. Returns the same file metadata shape as POST /files/upload.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "files" + ], + "summary": "Complete presigned MinIO upload", + "parameters": [ + { + "description": "Complete upload request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.completePresignedUploadReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/files/presign-upload": { + "post": { + "description": "Returns a short-lived PUT URL and object key. Upload the file with HTTP PUT to upload_url using the same Content-Type, then call POST /files/complete-upload.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "files" + ], + "summary": "Create presigned MinIO upload URL", + "parameters": [ + { + "description": "Presigned upload request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.presignedUploadReq" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/files/refresh-url": { "post": { "consumes": [ @@ -4119,14 +3714,14 @@ }, "/api/v1/lms/progress-summary": { "get": { - "description": "Returns the learner's nested LMS hierarchy with the same access progress data exposed on the individual program, course, module, and lesson APIs.", + "description": "Returns the learner's nested Learn English hierarchy (programs) and exam-prep hierarchy (exam_prep) with the same access progress data exposed on the individual content APIs.", "produces": [ "application/json" ], "tags": [ "lms" ], - "summary": "Get my LMS progress summary", + "summary": "Get my LMS and exam-prep progress summary", "responses": { "200": { "description": "OK", @@ -4345,9 +3940,36 @@ "responses": {} } }, + "/api/v1/modules/{moduleId}/lessons/reorder": { + "put": { + "tags": [ + "lessons" + ], + "summary": "Reorder lessons within a module", + "parameters": [ + { + "type": "integer", + "description": "Module ID", + "name": "moduleId", + "in": "path", + "required": true + }, + { + "description": "ordered_ids: every lesson id in this module, in the new order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ReorderIDsRequest" + } + } + ], + "responses": {} + } + }, "/api/v1/notifications/bulk-email": { "post": { - "description": "Sends an email to specified user IDs, all users of a role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339).", + "description": "Sends an email to specified user IDs, users of a platform role, team member IDs, team members of a team_role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339).", "consumes": [ "multipart/form-data" ], @@ -4380,6 +4002,89 @@ } } }, + "/api/v1/notifications/bulk-in-app": { + "post": { + "description": "Creates in-app notifications for specified platform user IDs, users matching a platform role, team member IDs, or team members matching a team_role. Optionally schedule for later with scheduled_at (RFC3339).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Send bulk in-app notification", + "parameters": [ + { + "description": "Bulk in-app content", + "name": "body", + "in": "body", + "required": true, + "schema": { + "type": "object", + "properties": { + "level": { + "type": "string" + }, + "message": { + "type": "string" + }, + "role": { + "type": "string" + }, + "scheduled_at": { + "type": "string" + }, + "team_member_ids": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "team_role": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + }, + "user_ids": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + } + } + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/notifications/bulk-push": { "post": { "description": "Sends a push notification to specified user IDs or all users matching a role. Optionally schedule for later with scheduled_at (RFC3339).", @@ -4520,6 +4225,52 @@ } } }, + "/api/v1/notifications/delete-in-app": { + "post": { + "description": "Deletes in-app notifications by ID for the authenticated user. Non-matching IDs are ignored.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Delete multiple in-app notifications", + "parameters": [ + { + "description": "Notification IDs", + "name": "body", + "in": "body", + "required": true, + "schema": { + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/notifications/scheduled": { "get": { "description": "Returns paginated scheduled notifications with optional status, channel, and date filters", @@ -4820,6 +4571,51 @@ } } } + }, + "delete": { + "description": "Deletes one in-app notification owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "notifications" + ], + "summary": "Delete a single in-app notification", + "parameters": [ + { + "type": "integer", + "description": "Notification ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } } }, "/api/v1/payments": { @@ -4938,6 +4734,118 @@ } } }, + "/api/v1/payments/chapa/direct": { + "post": { + "description": "Starts a Chapa Direct Charge (USSD push or OTP) for a subscription plan without hosted checkout redirect.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Initiate Chapa direct charge subscription payment", + "parameters": [ + { + "description": "Chapa direct charge request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.initiateChapaDirectPaymentReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/payments/chapa/direct/authorize": { + "post": { + "description": "Completes OTP authorization for Chapa direct charge methods that require it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Authorize Chapa direct charge with OTP", + "parameters": [ + { + "description": "Chapa direct charge authorization request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.authorizeChapaDirectPaymentReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/payments/chapa/direct/methods": { + "get": { + "description": "Returns wallet methods supported by Chapa Direct Charge API (USSD push and OTP flows).", + "produces": [ + "application/json" + ], + "tags": [ + "payments" + ], + "summary": "Get Chapa direct charge payment methods", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/payments/chapa/success": { "get": { "description": "Displays the Rezina success page after Chapa redirects the learner to return_url", @@ -5420,6 +5328,32 @@ } }, "/api/v1/practices": { + "get": { + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Page size (default 20, max 200)", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Page offset (default 0)", + "name": "offset", + "in": "query" + }, + { + "type": "boolean", + "description": "When true, return only practices with no parent links (admin)", + "name": "unlinked_only", + "in": "query" + } + ], + "responses": {} + }, "post": { "consumes": [ "application/json" @@ -5429,7 +5363,7 @@ ], "parameters": [ { - "description": "Practice (parent_kind: COURSE | MODULE | LESSON)", + "description": "Practice (optional parents; link later via PUT /practices/:id/parents)", "name": "body", "in": "body", "required": true, @@ -5470,7 +5404,7 @@ "required": true }, { - "description": "Fields to update (parent is immutable)", + "description": "Practice metadata fields to update", "name": "body", "in": "body", "required": true, @@ -5497,9 +5431,161 @@ "responses": {} } }, + "/api/v1/practices/{id}/full": { + "get": { + "description": "Returns practice metadata, linked question set settings, and all questions in the set (same shape as PUT /practices/{id}/full).", + "produces": [ + "application/json" + ], + "tags": [ + "practices" + ], + "summary": "Get LMS practice with question set and questions", + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + }, + "put": { + "description": "Updates practice metadata, linked question set settings, and syncs questions in one request. Questions omitted from the questions array are removed from the set (not deleted from the bank).", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "practices" + ], + "summary": "Full update LMS practice with question set and questions", + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Full practice update payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.FullUpdatePracticeInput" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/practices/{id}/parents": { + "put": { + "consumes": [ + "application/json" + ], + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Parent links (replaces all; use empty array to detach)", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdatePracticeParentsInput" + } + } + ], + "responses": {} + } + }, + "/api/v1/practices/{id}/parents/{parentKind}/{parentId}": { + "delete": { + "tags": [ + "practices" + ], + "parameters": [ + { + "type": "integer", + "description": "Practice ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Parent kind (COURSE, MODULE, LESSON)", + "name": "parentKind", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Parent entity ID", + "name": "parentId", + "in": "path", + "required": true + } + ], + "responses": {} + } + }, "/api/v1/practices/{practiceId}/questions": { "get": { - "description": "Returns paginated questions for a practice(question-set), including AUDIO fields", + "description": "Returns paginated questions for an LMS practice, including shared stimulus blocks and each question's effective dynamic payload", "produces": [ "application/json" ], @@ -5510,7 +5596,7 @@ "parameters": [ { "type": "integer", - "description": "Practice(question-set) ID", + "description": "LMS practice ID", "name": "practiceId", "in": "path", "required": true @@ -5995,7 +6081,7 @@ "parameters": [ { "type": "string", - "description": "Set type (PRACTICE, INITIAL_ASSESSMENT, QUIZ, EXAM, SURVEY, CAPSTONE)", + "description": "Set type (PRACTICE, QUIZ, EXAM, SURVEY, CAPSTONE)", "name": "set_type", "in": "query", "required": true @@ -6449,7 +6535,7 @@ }, "/api/v1/question-sets/{setId}/questions": { "get": { - "description": "Returns all questions in a question set with details", + "description": "Returns all questions in a question set with contextual shared stimulus data for linked LMS and exam-prep practices", "produces": [ "application/json" ], @@ -6488,7 +6574,7 @@ } }, "post": { - "description": "Links a question to a question set", + "description": "Links a question to a question set. Omit display_order to append after the current max; the assigned value is returned in the response.", "consumes": [ "application/json" ], @@ -6874,6 +6960,176 @@ } } }, + "/api/v1/questions/type-definition-groups": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "List question type definition groups", + "parameters": [ + { + "type": "string", + "description": "Filter by status (ACTIVE, INACTIVE)", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "default": 20, + "description": "Page size (default 20, max 200)", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Page offset", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Create question type definition group", + "parameters": [ + { + "description": "Group payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.createQuestionTypeDefinitionGroupReq" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/questions/type-definition-groups/{id}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Get question type definition group with definitions", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + }, + "put": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Update question type definition group", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Update group payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers.updateQuestionTypeDefinitionGroupReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + }, + "delete": { + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "Delete question type definition group", + "parameters": [ + { + "type": "integer", + "description": "Group id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/questions/type-definitions": { "get": { "produces": [ @@ -7107,6 +7363,61 @@ } } }, + "/api/v1/questions/type-definitions/{id}/practices": { + "get": { + "description": "Returns LMS and exam-prep practices whose linked question set contains at least one non-archived question matching the definition (by question_type_definition_id or legacy question_type).", + "produces": [ + "application/json" + ], + "tags": [ + "questions" + ], + "summary": "List practices globally by question type definition", + "parameters": [ + { + "type": "integer", + "description": "Question type definition id", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "default": 20, + "description": "Limit", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Offset", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/questions/validate-question-type-definition": { "post": { "description": "Validates selected stimulus and response component kinds for temporary question-type definitions (component-level validation only)", @@ -8142,7 +8453,7 @@ }, "/api/v1/subscription-plans": { "get": { - "description": "Returns all subscription plans", + "description": "Returns subscription plans. Optional category filter: EDUCATION.", "produces": [ "application/json" ], @@ -8153,9 +8464,15 @@ "parameters": [ { "type": "boolean", - "description": "Return only active plans", + "description": "Return only active plans (default true)", "name": "active_only", "in": "query" + }, + { + "type": "string", + "description": "Filter by plan category (EDUCATION)", + "name": "category", + "in": "query" } ], "responses": { @@ -8165,6 +8482,12 @@ "$ref": "#/definitions/domain.Response" } }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -8474,14 +8797,47 @@ }, "/api/v1/subscriptions/me": { "get": { - "description": "Returns the authenticated user's active subscription", + "description": "Returns all active subscriptions for the authenticated user (one per plan category)", "produces": [ "application/json" ], "tags": [ "subscriptions" ], - "summary": "Get current subscription", + "summary": "Get active subscriptions", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, + "/api/v1/subscriptions/request-checkout-link": { + "post": { + "description": "Sends the standalone web checkout URL to the learner by email or SMS (registration channel). Intended when mobile clients show a subscription-required state.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "subscriptions" + ], + "summary": "Send web checkout link to learner", + "parameters": [ + { + "description": "Optional plan or category for deep link", + "name": "body", + "in": "body", + "schema": { + "$ref": "#/definitions/handlers.requestCheckoutLinkReq" + } + } + ], "responses": { "200": { "description": "OK", @@ -8489,8 +8845,26 @@ "$ref": "#/definitions/domain.Response" } }, - "404": { - "description": "Not Found", + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "429": { + "description": "Too Many Requests", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "503": { + "description": "Service Unavailable", "schema": { "$ref": "#/definitions/domain.ErrorResponse" } @@ -9010,6 +9384,79 @@ } } } + }, + "put": { + "security": [ + { + "Bearer": [] + } + ], + "description": "Update the authenticated team member's own profile fields", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Update my team profile", + "parameters": [ + { + "description": "Profile update payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateMyTeamProfileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/domain.Response" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.TeamMemberResponse" + } + } + } + ] + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } } }, "/api/v1/team/members": { @@ -9187,6 +9634,18 @@ } } }, + "/api/v1/team/members/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "team" + ], + "summary": "Export team members as CSV (admin)", + "responses": {} + } + }, "/api/v1/team/members/invite": { "post": { "description": "Creates a pending team member (email + team_role only) and sends an invitation email; profile is completed on accept", @@ -9696,6 +10155,110 @@ } } }, + "/api/v1/team/resetPassword": { + "post": { + "description": "Completes team password reset using email + OTP from the reset link. Public.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Reset team member password", + "parameters": [ + { + "description": "Reset payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.TeamResetPasswordReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, + "/api/v1/team/sendResetCode": { + "post": { + "description": "Sends a password-reset email with a link to the team member (admin panel). Public.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Send team password reset link", + "parameters": [ + { + "description": "Email", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.TeamSendPasswordResetReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/team/stats": { "get": { "security": [ @@ -9754,6 +10317,42 @@ } } }, + "/api/v1/team/verifyResetCode": { + "get": { + "description": "Checks whether email+otp from a reset link are still valid without consuming the OTP. Public.", + "produces": [ + "application/json" + ], + "tags": [ + "team" + ], + "summary": "Verify team password reset link", + "parameters": [ + { + "type": "string", + "description": "Team member email", + "name": "email", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Reset OTP from the email link", + "name": "otp", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + } + } + } + }, "/api/v1/tenant": { "get": { "description": "Check if phone number or email exist", @@ -9903,6 +10502,64 @@ } } }, + "/api/v1/user/knowledge-level": { + "put": { + "description": "Updates the authenticated learner's self-reported knowledge level.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Update user's knowledge level", + "parameters": [ + { + "description": "Knowledge level", + "name": "knowledge_level", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateKnowledgeLevelReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Response" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.ErrorResponse" + } + } + } + } + }, "/api/v1/user/me": { "delete": { "security": [ @@ -10083,7 +10740,7 @@ }, "/api/v1/user/sendResetCode": { "post": { - "description": "Send reset code", + "description": "Sends a password-reset OTP code by email or SMS for learner (mobile) accounts. Email delivers the numeric code (not a link).", "consumes": [ "application/json" ], @@ -10477,7 +11134,7 @@ }, { "type": "string", - "description": "User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED)", + "description": "User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED, or INACTIVE for all non-ACTIVE statuses)", "name": "status", "in": "query" }, @@ -10522,6 +11179,18 @@ } } }, + "/api/v1/users/export": { + "get": { + "produces": [ + "text/csv" + ], + "tags": [ + "user" + ], + "summary": "Export users as CSV (admin)", + "responses": {} + } + }, "/api/v1/users/summary": { "get": { "security": [ @@ -11379,65 +12048,6 @@ } } }, - "/api/v1/{tenant_slug}/user/knowledge-level": { - "put": { - "description": "Updates the knowledge level of the specified user after initial assessment", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "Update user's knowledge level", - "parameters": [ - { - "type": "integer", - "description": "User ID", - "name": "user_id", - "in": "path", - "required": true - }, - { - "description": "Knowledge level", - "name": "knowledge_level", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateKnowledgeLevelReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Response" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/domain.ErrorResponse" - } - } - } - } - }, "/api/v1/{tenant_slug}/user/register": { "post": { "description": "Register user", @@ -11762,6 +12372,444 @@ } } }, + "domain.AdminExamPrepCatalogCourseLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "units": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepUnitLearningEntry" + } + } + } + }, + "domain.AdminExamPrepLessonLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminExamPrepModuleLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepLessonLearningEntry" + } + }, + "name": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminExamPrepPracticeLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "exam_prep_practice_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminExamPrepUnitLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepModuleLearningEntry" + } + }, + "name": { + "type": "string" + }, + "practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminExamPrepUserLearningActivityTree": { + "type": "object", + "properties": { + "catalog_courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminExamPrepCatalogCourseLearningEntry" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminLMSCourseLearningEntry": { + "type": "object", + "properties": { + "course_level_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSModuleLearningEntry" + } + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSLessonLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "lesson_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "sort_order": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminLMSModuleLearningEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSLessonLearningEntry" + } + }, + "module_practices": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSPracticeLearningEntry" + } + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSPracticeLearningEntry": { + "type": "object", + "properties": { + "completed_at": { + "type": "string" + }, + "lms_practice_id": { + "type": "integer" + }, + "scope": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "domain.AdminLMSProgramLearningEntry": { + "type": "object", + "properties": { + "courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSCourseLearningEntry" + } + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "rollup_completed_at": { + "type": "string" + }, + "sort_order": { + "type": "integer" + } + } + }, + "domain.AdminLMSUserLearningActivityTree": { + "type": "object", + "properties": { + "programs": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLMSProgramLearningEntry" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserExamPrepLearningSection": { + "type": "object", + "properties": { + "completions": { + "$ref": "#/definitions/domain.AdminExamPrepUserLearningActivityTree" + }, + "progress": { + "$ref": "#/definitions/domain.ExamPrepProgressSummary" + } + } + }, + "domain.AdminUserLMSLearningSection": { + "type": "object", + "properties": { + "completed_ids": { + "$ref": "#/definitions/domain.LMSUserProgress" + }, + "completions": { + "$ref": "#/definitions/domain.AdminLMSUserLearningActivityTree" + }, + "progress": { + "$ref": "#/definitions/domain.LMSProgressSummary" + } + } + }, + "domain.AdminUserLearningActivityDetails": { + "type": "object", + "properties": { + "exam_prep": { + "$ref": "#/definitions/domain.AdminUserExamPrepLearningSection" + }, + "lms": { + "$ref": "#/definitions/domain.AdminUserLMSLearningSection" + }, + "recent_activity": { + "$ref": "#/definitions/domain.UserRecentActivityFeed" + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionDetails": { + "type": "object", + "properties": { + "active_by_category": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + }, + "active_subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionRecord" + } + }, + "display_status": { + "type": "string" + }, + "has_active_subscription": { + "type": "boolean" + }, + "payments": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionPayment" + } + }, + "subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUserSubscriptionRecord" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionPayment": { + "type": "object", + "properties": { + "amount": { + "type": "number" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "paid_at": { + "type": "string" + }, + "payment_method": { + "type": "string" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "status": { + "type": "string" + }, + "subscription_id": { + "type": "integer" + } + } + }, + "domain.AdminUserSubscriptionRecord": { + "type": "object", + "properties": { + "auto_renew": { + "type": "boolean" + }, + "cancelled_at": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "duration_unit": { + "type": "string" + }, + "duration_value": { + "type": "integer" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_currently_active": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, + "payment_method": { + "type": "string" + }, + "payment_reference": { + "type": "string" + }, + "plan_category": { + "type": "string" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "price": { + "type": "number" + }, + "starts_at": { + "type": "string" + }, + "status": { + "type": "string" + }, + "updated_at": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } + }, "domain.AgeGroup": { "type": "string", "enum": [ @@ -11880,6 +12928,9 @@ "month": { "type": "integer" }, + "payment_method": { + "type": "string" + }, "range_end": { "type": "string" }, @@ -11895,6 +12946,9 @@ "series_start": { "type": "string" }, + "timezone": { + "type": "string" + }, "to": { "type": "string" }, @@ -12130,9 +13184,98 @@ } } }, + "domain.AnalyticsSubscriptionRenewal": { + "type": "object", + "properties": { + "avg_days_to_resubscribe": { + "type": "number" + }, + "expired_in_period": { + "type": "integer" + }, + "first_time_subscriptions": { + "type": "integer" + }, + "median_days_to_resubscribe": { + "type": "number" + }, + "renewal_rate": { + "description": "0–1; renewed_after_expiry / expired_in_period", + "type": "number" + }, + "renewed_after_expiry": { + "type": "integer" + }, + "resubscribe_after_expiry": { + "type": "integer" + }, + "returning_subscriptions": { + "type": "integer" + } + } + }, + "domain.AnalyticsSubscriptionSnapshot": { + "type": "object", + "properties": { + "active_learners": { + "type": "integer" + }, + "active_now": { + "type": "integer" + }, + "auto_renew_enabled": { + "type": "integer" + }, + "cancelled_now": { + "type": "integer" + }, + "expired_now": { + "type": "integer" + }, + "expiring_within_30_days": { + "type": "integer" + }, + "expiring_within_7_days": { + "type": "integer" + }, + "lifetime_active": { + "type": "integer" + }, + "pending_now": { + "type": "integer" + }, + "term_active": { + "type": "integer" + } + } + }, "domain.AnalyticsSubscriptionsSection": { "type": "object", "properties": { + "acquisition_by_source": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_category": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_lifetime": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, + "active_by_plan": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "active_subscriptions": { "type": "integer" }, @@ -12142,6 +13285,24 @@ "$ref": "#/definitions/domain.AnalyticsLabelCount" } }, + "cancellations_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "expirations_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "new_by_cohort": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "new_month": { "type": "integer" }, @@ -12157,12 +13318,40 @@ "new_week": { "type": "integer" }, + "renewal": { + "description": "Resubscribe / renewal behaviour", + "allOf": [ + { + "$ref": "#/definitions/domain.AnalyticsSubscriptionRenewal" + } + ] + }, + "resubscriptions_last_30_days": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsTimePoint" + } + }, + "revenue_by_category": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelAmount" + } + }, "revenue_by_plan": { "type": "array", "items": { "$ref": "#/definitions/domain.AnalyticsRevenueByPlan" } }, + "snapshot": { + "description": "Learner subscription behaviour", + "allOf": [ + { + "$ref": "#/definitions/domain.AnalyticsSubscriptionSnapshot" + } + ] + }, "total_subscriptions": { "type": "integer" } @@ -12220,6 +13409,12 @@ "$ref": "#/definitions/domain.AnalyticsLabelCount" } }, + "by_gender": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AnalyticsLabelCount" + } + }, "by_knowledge_level": { "type": "array", "items": { @@ -12345,12 +13540,31 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the program when set; omit to append after current max within program_id (uniqueness is per-program).", "type": "integer", @@ -12368,6 +13582,15 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ @@ -12381,6 +13604,16 @@ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" } @@ -12392,9 +13625,28 @@ "title" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" }, @@ -12412,6 +13664,15 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12421,6 +13682,16 @@ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "thumbnail": { "type": "string" } @@ -12432,6 +13703,29 @@ "question_set_id" ], "properties": { + "parent_id": { + "type": "integer" + }, + "parent_kind": { + "description": "ParentKind and ParentID are accepted for backward compatibility when parents is omitted.", + "enum": [ + "CATALOG_COURSE", + "UNIT", + "LESSON" + ], + "allOf": [ + { + "$ref": "#/definitions/domain.ExamPrepParentKind" + } + ] + }, + "parents": { + "description": "Parents optionally attaches the practice to catalog course, unit, or lesson. Omit or null to create unlinked.", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepPracticeParent" + } + }, "persona_id": { "type": "integer" }, @@ -12467,12 +13761,31 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the catalog course when set; omit to append after current max sort_order within catalog_course_id.", "type": "integer", @@ -12489,6 +13802,15 @@ "title" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12547,6 +13869,15 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -12556,6 +13887,16 @@ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder within the course when set; omit to append after current max within course_id (uniqueness is per-course).", "type": "integer", @@ -12566,8 +13907,6 @@ "domain.CreatePracticeInput": { "type": "object", "required": [ - "parent_id", - "parent_kind", "question_set_id" ], "properties": { @@ -12575,6 +13914,7 @@ "type": "integer" }, "parent_kind": { + "description": "ParentKind and ParentID are accepted for backward compatibility when parents is omitted.", "enum": [ "COURSE", "MODULE", @@ -12586,6 +13926,13 @@ } ] }, + "parents": { + "description": "Parents optionally attaches the practice to hierarchy entities. Omit or null to create unlinked.", + "type": "array", + "items": { + "$ref": "#/definitions/domain.PracticeParent" + } + }, "persona_id": { "type": "integer" }, @@ -12623,12 +13970,19 @@ "name" ], "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "description": { @@ -12637,6 +13991,16 @@ "name": { "type": "string" }, + "publish_status": { + "description": "Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.", + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "description": "SortOrder inserts at this global program order when set; omit to append after current max (sort_order uniqueness is enforced).", "type": "integer", @@ -12647,6 +14011,21 @@ } } }, + "domain.CreateQuestionOptionInput": { + "type": "object", + "properties": { + "isCorrect": { + "type": "boolean" + }, + "optionOrder": { + "type": "integer", + "format": "int32" + }, + "optionText": { + "type": "string" + } + } + }, "domain.CreateRoleReq": { "type": "object", "required": [ @@ -12663,6 +14042,17 @@ } } }, + "domain.CreateShortAnswerInput": { + "type": "object", + "properties": { + "acceptableAnswer": { + "type": "string" + }, + "matchType": { + "type": "string" + } + } + }, "domain.CreateTeamMemberReq": { "type": "object", "required": [ @@ -12805,6 +14195,293 @@ } } }, + "domain.ExamPrepParentKind": { + "type": "string", + "enum": [ + "CATALOG_COURSE", + "UNIT", + "LESSON" + ], + "x-enum-varnames": [ + "ExamPrepParentKindCatalogCourse", + "ExamPrepParentKindUnit", + "ExamPrepParentKindLesson" + ] + }, + "domain.ExamPrepPracticeParent": { + "type": "object", + "properties": { + "parent_id": { + "type": "integer" + }, + "parent_kind": { + "$ref": "#/definitions/domain.ExamPrepParentKind" + } + } + }, + "domain.ExamPrepProgressSummary": { + "type": "object", + "properties": { + "catalog_courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryCatalogCourse" + } + } + } + }, + "domain.ExamPrepProgressSummaryCatalogCourse": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "units": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryUnit" + } + } + } + }, + "domain.ExamPrepProgressSummaryLesson": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "module_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.ExamPrepProgressSummaryModule": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryLesson" + } + }, + "name": { + "type": "string" + }, + "unit_id": { + "type": "integer" + } + } + }, + "domain.ExamPrepProgressSummaryUnit": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "catalog_course_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepProgressSummaryModule" + } + }, + "name": { + "type": "string" + } + } + }, + "domain.FullUpdatePracticeInput": { + "type": "object", + "properties": { + "practice": { + "$ref": "#/definitions/domain.FullUpdatePracticeShellInput" + }, + "question_set": { + "$ref": "#/definitions/domain.FullUpdateQuestionSetInput" + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FullUpdatePracticeQuestionItem" + } + }, + "stimulus_blocks": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FullUpdateStimulusBlockItem" + } + } + } + }, + "domain.FullUpdatePracticeQuestionItem": { + "type": "object", + "properties": { + "associated_question_id": { + "type": "integer" + }, + "audio_correct_answer_text": { + "type": "string" + }, + "difficulty_level": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "dynamic_payload": { + "$ref": "#/definitions/domain.DynamicQuestionPayload" + }, + "explanation": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "image_url": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateQuestionOptionInput" + } + }, + "points": { + "type": "integer" + }, + "question_text": { + "type": "string" + }, + "question_type": { + "type": "string" + }, + "question_type_definition_id": { + "type": "integer" + }, + "sample_answer_voice_prompt": { + "type": "string" + }, + "short_answers": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateShortAnswerInput" + } + }, + "status": { + "type": "string" + }, + "stimulus_block_key": { + "type": "string" + }, + "tips": { + "type": "string" + }, + "voice_prompt": { + "type": "string" + } + } + }, + "domain.FullUpdatePracticeShellInput": { + "type": "object", + "properties": { + "authoring_profile": { + "type": "string" + }, + "persona_id": { + "type": "integer" + }, + "publish_status": { + "type": "string" + }, + "question_set_id": { + "type": "integer" + }, + "quick_tips": { + "type": "string" + }, + "story_description": { + "type": "string" + }, + "story_image": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "domain.FullUpdateQuestionSetInput": { + "type": "object", + "properties": { + "banner_image": { + "type": "string" + }, + "description": { + "type": "string" + }, + "intro_video_url": { + "type": "string" + }, + "passing_score": { + "type": "integer" + }, + "persona": { + "type": "string" + }, + "shuffle_questions": { + "type": "boolean" + }, + "status": { + "type": "string" + }, + "time_limit_minutes": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.FullUpdateStimulusBlockItem": { + "type": "object", + "properties": { + "block_key": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "stimulus": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.DynamicElementInstance" + } + } + } + }, "domain.InviteTeamMemberReq": { "type": "object", "required": [ @@ -12820,6 +14497,161 @@ } } }, + "domain.LMSEntityAccess": { + "type": "object", + "properties": { + "completed_count": { + "type": "integer" + }, + "is_accessible": { + "type": "boolean" + }, + "is_completed": { + "type": "boolean" + }, + "progress_percent": { + "type": "integer" + }, + "progress_percent_precise": { + "type": "number" + }, + "reason": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummary": { + "type": "object", + "properties": { + "exam_prep": { + "$ref": "#/definitions/domain.ExamPrepProgressSummary" + }, + "programs": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryProgram" + } + } + } + }, + "domain.LMSProgressSummaryCourse": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryModule" + } + }, + "name": { + "type": "string" + }, + "program_id": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummaryLesson": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "id": { + "type": "integer" + }, + "module_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + } + }, + "domain.LMSProgressSummaryModule": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "course_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "lessons": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryLesson" + } + }, + "name": { + "type": "string" + }, + "program_id": { + "type": "integer" + } + } + }, + "domain.LMSProgressSummaryProgram": { + "type": "object", + "properties": { + "access": { + "$ref": "#/definitions/domain.LMSEntityAccess" + }, + "courses": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.LMSProgressSummaryCourse" + } + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + } + } + }, + "domain.LMSUserProgress": { + "type": "object", + "properties": { + "course_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "lesson_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "module_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "program_ids": { + "type": "array", + "items": { + "type": "integer" + } + } + } + }, "domain.LogEntry": { "type": "object", "properties": { @@ -12948,137 +14780,78 @@ } } }, - "domain.QuestionAudioAnswer": { + "domain.PracticeParent": { "type": "object", "properties": { - "correctAnswerText": { - "type": "string" + "parent_id": { + "type": "integer" }, - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer", - "format": "int64" - }, - "questionID": { - "type": "integer", - "format": "int64" + "parent_kind": { + "$ref": "#/definitions/domain.ParentKind" } } }, - "domain.QuestionOption": { + "domain.RecentActivityCourseRef": { "type": "object", "properties": { - "createdAt": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "isCorrect": { - "type": "boolean" - }, - "optionOrder": { - "type": "integer", - "format": "int32" - }, - "optionText": { + "name": { "type": "string" - }, - "questionID": { - "type": "integer", - "format": "int64" } } }, - "domain.QuestionShortAnswer": { + "domain.RecentActivityLessonRef": { "type": "object", "properties": { - "acceptableAnswer": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "matchType": { + "sort_order": { + "type": "integer" + }, + "title": { "type": "string" - }, - "questionID": { - "type": "integer", - "format": "int64" } } }, - "domain.QuestionWithDetails": { + "domain.RecentActivityModuleRef": { "type": "object", "properties": { - "audioAnswer": { - "$ref": "#/definitions/domain.QuestionAudioAnswer" - }, - "createdAt": { - "type": "string" - }, - "difficultyLevel": { - "type": "string" - }, - "dynamicPayload": { - "$ref": "#/definitions/domain.DynamicQuestionPayload" - }, - "explanation": { - "type": "string" - }, "id": { - "type": "integer", - "format": "int64" + "type": "integer" }, - "imageURL": { + "name": { "type": "string" }, - "options": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionOption" - } + "sort_order": { + "type": "integer" + } + } + }, + "domain.RecentActivityPracticeRef": { + "type": "object", + "properties": { + "lms_practice_id": { + "type": "integer" }, - "points": { - "type": "integer", - "format": "int32" - }, - "questionText": { + "scope": { + "description": "lesson | module | course", "type": "string" }, - "questionType": { + "title": { "type": "string" + } + } + }, + "domain.RecentActivityProgramRef": { + "type": "object", + "properties": { + "id": { + "type": "integer" }, - "questionTypeDefinitionID": { - "type": "integer", - "format": "int64" - }, - "sampleAnswerVoicePrompt": { - "type": "string" - }, - "shortAnswers": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.QuestionShortAnswer" - } - }, - "status": { - "type": "string" - }, - "tips": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "voicePrompt": { + "name": { "type": "string" } } @@ -13146,6 +14919,7 @@ "enum": [ "SUPER_ADMIN", "ADMIN", + "CONTENT_MANAGER", "STUDENT", "OPEN_LEARNER", "INSTRUCTOR", @@ -13154,6 +14928,7 @@ "x-enum-varnames": [ "RoleSuperAdmin", "RoleAdmin", + "RoleContentManager", "RoleStudent", "RoleOpenLearner", "RoleInstructor", @@ -13341,6 +15116,26 @@ "TeamMemberStatusTerminated" ] }, + "domain.TeamResetPasswordReq": { + "type": "object", + "required": [ + "email", + "otp", + "password" + ], + "properties": { + "email": { + "type": "string" + }, + "otp": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + } + } + }, "domain.TeamRole": { "type": "string", "enum": [ @@ -13364,15 +15159,44 @@ "TeamRoleAnalyst" ] }, + "domain.TeamSendPasswordResetReq": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "type": "string" + } + } + }, "domain.UpdateCourseInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13384,6 +15208,15 @@ "domain.UpdateExamPrepCatalogCourseInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ @@ -13397,6 +15230,15 @@ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13408,6 +15250,13 @@ "domain.UpdateExamPrepPracticeInput": { "type": "object", "properties": { + "authoring_profile": { + "type": "string", + "enum": [ + "STANDALONE", + "IELTS_SHARED_STIMULUS" + ] + }, "persona_id": { "type": "integer" }, @@ -13437,15 +15286,47 @@ } } }, + "domain.UpdateExamPrepPracticeParentsInput": { + "type": "object", + "required": [ + "parents" + ], + "properties": { + "parents": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ExamPrepPracticeParent" + } + } + } + }, "domain.UpdateExamPrepUnitInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13469,6 +15350,15 @@ "domain.UpdateLessonInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -13518,6 +15408,15 @@ "domain.UpdateModuleInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "description": { "type": "string" }, @@ -13527,14 +15426,59 @@ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" } } }, + "domain.UpdateMyTeamProfileReq": { + "type": "object", + "properties": { + "bio": { + "type": "string" + }, + "department": { + "type": "string" + }, + "first_name": { + "type": "string" + }, + "job_title": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "phone_number": { + "type": "string" + }, + "profile_picture_url": { + "type": "string" + }, + "work_phone": { + "type": "string" + } + } + }, "domain.UpdatePracticeInput": { "type": "object", "properties": { + "authoring_profile": { + "type": "string", + "enum": [ + "STANDALONE", + "IELTS_SHARED_STIMULUS" + ] + }, "persona_id": { "type": "integer" }, @@ -13564,15 +15508,36 @@ } } }, + "domain.UpdatePracticeParentsInput": { + "type": "object", + "required": [ + "parents" + ], + "properties": { + "parents": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.PracticeParent" + } + } + } + }, "domain.UpdateProgramInput": { "type": "object", "properties": { + "access_tier": { + "type": "string", + "enum": [ + "FREE", + "free", + "PREMIUM", + "premium" + ] + }, "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "description": { @@ -13581,6 +15546,15 @@ "name": { "type": "string" }, + "publish_status": { + "type": "string", + "enum": [ + "DRAFT", + "draft", + "PUBLISHED", + "published" + ] + }, "sort_order": { "type": "integer" }, @@ -13688,9 +15662,6 @@ "gender": { "type": "string" }, - "initial_assessment_completed": { - "type": "boolean" - }, "knowledge_level": { "type": "string" }, @@ -13726,6 +15697,12 @@ "domain.UserProfileResponse": { "type": "object", "properties": { + "active_subscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserProfileSubscription" + } + }, "age_group": { "type": "string" }, @@ -13761,10 +15738,6 @@ "id": { "type": "integer" }, - "initial_assessment_completed": { - "description": "Profile fields", - "type": "boolean" - }, "language_challange": { "type": "string" }, @@ -13781,6 +15754,7 @@ "type": "string" }, "nick_name": { + "description": "Profile fields", "type": "string" }, "occupation": { @@ -13821,6 +15795,102 @@ } } }, + "domain.UserProfileSubscription": { + "type": "object", + "properties": { + "auto_renew": { + "type": "boolean" + }, + "category": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "duration_unit": { + "type": "string" + }, + "duration_value": { + "type": "integer" + }, + "expires_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_lifetime": { + "type": "boolean" + }, + "plan_id": { + "type": "integer" + }, + "plan_name": { + "type": "string" + }, + "price": { + "type": "number" + }, + "starts_at": { + "type": "string" + }, + "status": { + "type": "string" + } + } + }, + "domain.UserRecentActivityFeed": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserRecentActivityItem" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "domain.UserRecentActivityItem": { + "type": "object", + "properties": { + "course": { + "$ref": "#/definitions/domain.RecentActivityCourseRef" + }, + "headline": { + "description": "Headline is optional server-rendered primary line (client may ignore and build from refs).", + "type": "string" + }, + "id": { + "type": "string" + }, + "kind": { + "description": "Kind drives default icon treatment on the client (e.g. joined vs completion).", + "type": "string" + }, + "lesson": { + "$ref": "#/definitions/domain.RecentActivityLessonRef" + }, + "module": { + "$ref": "#/definitions/domain.RecentActivityModuleRef" + }, + "occurred_at": { + "description": "OccurredAt is when the platform recorded the event (typically completion time).", + "type": "string" + }, + "practice": { + "$ref": "#/definitions/domain.RecentActivityPracticeRef" + }, + "program": { + "$ref": "#/definitions/domain.RecentActivityProgramRef" + } + } + }, "domain.UserStatus": { "type": "string", "enum": [ @@ -14338,8 +16408,15 @@ "question_id" ], "properties": { + "associated_question_id": { + "description": "Section anchor question in the same set; must have a lower display_order and no association of its own.", + "type": "integer", + "minimum": 1 + }, "display_order": { - "type": "integer" + "description": "Omit to append after the current highest display_order in the set; set explicitly to insert at a position.", + "type": "integer", + "minimum": 0 }, "question_id": { "type": "integer" @@ -14360,6 +16437,41 @@ } } }, + "handlers.adminApplySubscriptionReq": { + "type": "object", + "required": [ + "plan_id" + ], + "properties": { + "plan_id": { + "type": "integer", + "minimum": 1 + }, + "record_payment": { + "description": "RecordPayment when omitted defaults to true (record SUCCESS payment at plan price).", + "type": "boolean" + } + } + }, + "handlers.authorizeChapaDirectPaymentReq": { + "type": "object", + "required": [ + "otp", + "request_id", + "session_id" + ], + "properties": { + "otp": { + "type": "string" + }, + "request_id": { + "type": "string" + }, + "session_id": { + "type": "string" + } + } + }, "handlers.autoRenewReq": { "type": "object", "properties": { @@ -14386,6 +16498,20 @@ } } }, + "handlers.completePresignedUploadReq": { + "type": "object", + "properties": { + "file_size": { + "type": "integer" + }, + "media_type": { + "type": "string" + }, + "object_key": { + "type": "string" + } + } + }, "handlers.createEmailTemplateReq": { "type": "object", "required": [ @@ -14534,18 +16660,13 @@ "required": [ "category", "currency", - "duration_unit", - "duration_value", - "name", - "price" + "name" ], "properties": { "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "currency": { @@ -14555,21 +16676,20 @@ "type": "string" }, "duration_unit": { - "type": "string", - "enum": [ - "DAY", - "WEEK", - "MONTH", - "YEAR" - ] + "type": "string" }, "duration_value": { - "type": "integer", - "minimum": 1 + "type": "integer" }, "is_active": { "type": "boolean" }, + "is_free": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, "name": { "type": "string" }, @@ -14667,7 +16787,6 @@ "type": "string", "enum": [ "PRACTICE", - "INITIAL_ASSESSMENT", "QUIZ", "EXAM", "SURVEY", @@ -14688,6 +16807,26 @@ } } }, + "handlers.createQuestionTypeDefinitionGroupReq": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "description": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "status": { + "type": "string" + } + } + }, "handlers.createQuestionTypeDefinitionReq": { "type": "object", "required": [ @@ -14701,6 +16840,12 @@ "display_name": { "type": "string" }, + "group_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, "key": { "type": "string" }, @@ -14733,6 +16878,29 @@ } } }, + "handlers.initiateChapaDirectPaymentReq": { + "type": "object", + "required": [ + "email", + "payment_method", + "phone", + "plan_id" + ], + "properties": { + "email": { + "type": "string" + }, + "payment_method": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "plan_id": { + "type": "integer" + } + } + }, "handlers.initiateDirectPaymentReq": { "type": "object", "required": [ @@ -14879,6 +17047,23 @@ } } }, + "handlers.presignedUploadReq": { + "type": "object", + "properties": { + "content_type": { + "type": "string" + }, + "file_size": { + "type": "integer" + }, + "filename": { + "type": "string" + }, + "media_type": { + "type": "string" + } + } + }, "handlers.previewEmailTemplateReq": { "type": "object", "properties": { @@ -14913,6 +17098,17 @@ } } }, + "handlers.requestCheckoutLinkReq": { + "type": "object", + "properties": { + "category": { + "type": "string" + }, + "plan_id": { + "type": "integer" + } + } + }, "handlers.shortAnswerInput": { "type": "object", "required": [ @@ -15148,9 +17344,7 @@ "category": { "type": "string", "enum": [ - "LEARN_ENGLISH", - "IELTS", - "DUOLINGO" + "EDUCATION" ] }, "currency": { @@ -15168,6 +17362,12 @@ "is_active": { "type": "boolean" }, + "is_free": { + "type": "boolean" + }, + "is_lifetime": { + "type": "boolean" + }, "name": { "type": "string" }, @@ -15182,6 +17382,10 @@ "display_order" ], "properties": { + "associated_question_id": { + "type": "integer", + "minimum": 1 + }, "display_order": { "type": "integer" } @@ -15275,44 +17479,26 @@ } } }, - "handlers.updateQuestionTypeDefinitionReq": { + "handlers.updateQuestionTypeDefinitionGroupReq": { "type": "object", "properties": { "description": { "type": "string" }, - "display_name": { + "display_order": { + "type": "integer" + }, + "name": { "type": "string" }, - "response_component_kinds": { - "type": "array", - "items": { - "type": "string" - } - }, - "response_schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.DynamicElementDefinition" - } - }, "status": { "type": "string" - }, - "stimulus_component_kinds": { - "type": "array", - "items": { - "type": "string" - } - }, - "stimulus_schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.DynamicElementDefinition" - } } } }, + "handlers.updateQuestionTypeDefinitionReq": { + "type": "object" + }, "handlers.validateQuestionTypeDefinitionReq": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 6cafb902..1213e60c 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -35,6 +35,292 @@ definitions: - password - token type: object + domain.AdminExamPrepCatalogCourseLearningEntry: + properties: + id: + type: integer + name: + type: string + practices: + items: + $ref: '#/definitions/domain.AdminExamPrepPracticeLearningEntry' + type: array + sort_order: + type: integer + units: + items: + $ref: '#/definitions/domain.AdminExamPrepUnitLearningEntry' + type: array + type: object + domain.AdminExamPrepLessonLearningEntry: + properties: + id: + type: integer + practices: + items: + $ref: '#/definitions/domain.AdminExamPrepPracticeLearningEntry' + type: array + sort_order: + type: integer + title: + type: string + type: object + domain.AdminExamPrepModuleLearningEntry: + properties: + id: + type: integer + lessons: + items: + $ref: '#/definitions/domain.AdminExamPrepLessonLearningEntry' + type: array + name: + type: string + sort_order: + type: integer + type: object + domain.AdminExamPrepPracticeLearningEntry: + properties: + completed_at: + type: string + exam_prep_practice_id: + type: integer + title: + type: string + type: object + domain.AdminExamPrepUnitLearningEntry: + properties: + id: + type: integer + modules: + items: + $ref: '#/definitions/domain.AdminExamPrepModuleLearningEntry' + type: array + name: + type: string + practices: + items: + $ref: '#/definitions/domain.AdminExamPrepPracticeLearningEntry' + type: array + sort_order: + type: integer + type: object + domain.AdminExamPrepUserLearningActivityTree: + properties: + catalog_courses: + items: + $ref: '#/definitions/domain.AdminExamPrepCatalogCourseLearningEntry' + type: array + user_id: + type: integer + type: object + domain.AdminLMSCourseLearningEntry: + properties: + course_level_practices: + items: + $ref: '#/definitions/domain.AdminLMSPracticeLearningEntry' + type: array + id: + type: integer + modules: + items: + $ref: '#/definitions/domain.AdminLMSModuleLearningEntry' + type: array + name: + type: string + rollup_completed_at: + type: string + sort_order: + type: integer + type: object + domain.AdminLMSLessonLearningEntry: + properties: + completed_at: + type: string + id: + type: integer + lesson_practices: + items: + $ref: '#/definitions/domain.AdminLMSPracticeLearningEntry' + type: array + sort_order: + type: integer + title: + type: string + type: object + domain.AdminLMSModuleLearningEntry: + properties: + id: + type: integer + lessons: + items: + $ref: '#/definitions/domain.AdminLMSLessonLearningEntry' + type: array + module_practices: + items: + $ref: '#/definitions/domain.AdminLMSPracticeLearningEntry' + type: array + name: + type: string + rollup_completed_at: + type: string + sort_order: + type: integer + type: object + domain.AdminLMSPracticeLearningEntry: + properties: + completed_at: + type: string + lms_practice_id: + type: integer + scope: + type: string + title: + type: string + type: object + domain.AdminLMSProgramLearningEntry: + properties: + courses: + items: + $ref: '#/definitions/domain.AdminLMSCourseLearningEntry' + type: array + id: + type: integer + name: + type: string + rollup_completed_at: + type: string + sort_order: + type: integer + type: object + domain.AdminLMSUserLearningActivityTree: + properties: + programs: + items: + $ref: '#/definitions/domain.AdminLMSProgramLearningEntry' + type: array + user_id: + type: integer + type: object + domain.AdminUserExamPrepLearningSection: + properties: + completions: + $ref: '#/definitions/domain.AdminExamPrepUserLearningActivityTree' + progress: + $ref: '#/definitions/domain.ExamPrepProgressSummary' + type: object + domain.AdminUserLMSLearningSection: + properties: + completed_ids: + $ref: '#/definitions/domain.LMSUserProgress' + completions: + $ref: '#/definitions/domain.AdminLMSUserLearningActivityTree' + progress: + $ref: '#/definitions/domain.LMSProgressSummary' + type: object + domain.AdminUserLearningActivityDetails: + properties: + exam_prep: + $ref: '#/definitions/domain.AdminUserExamPrepLearningSection' + lms: + $ref: '#/definitions/domain.AdminUserLMSLearningSection' + recent_activity: + $ref: '#/definitions/domain.UserRecentActivityFeed' + user_id: + type: integer + type: object + domain.AdminUserSubscriptionDetails: + properties: + active_by_category: + additionalProperties: + type: boolean + type: object + active_subscriptions: + items: + $ref: '#/definitions/domain.AdminUserSubscriptionRecord' + type: array + display_status: + type: string + has_active_subscription: + type: boolean + payments: + items: + $ref: '#/definitions/domain.AdminUserSubscriptionPayment' + type: array + subscriptions: + items: + $ref: '#/definitions/domain.AdminUserSubscriptionRecord' + type: array + user_id: + type: integer + type: object + domain.AdminUserSubscriptionPayment: + properties: + amount: + type: number + created_at: + type: string + currency: + type: string + expires_at: + type: string + id: + type: integer + paid_at: + type: string + payment_method: + type: string + plan_id: + type: integer + plan_name: + type: string + status: + type: string + subscription_id: + type: integer + type: object + domain.AdminUserSubscriptionRecord: + properties: + auto_renew: + type: boolean + cancelled_at: + type: string + created_at: + type: string + currency: + type: string + duration_unit: + type: string + duration_value: + type: integer + expires_at: + type: string + id: + type: integer + is_currently_active: + type: boolean + is_lifetime: + type: boolean + payment_method: + type: string + payment_reference: + type: string + plan_category: + type: string + plan_id: + type: integer + plan_name: + type: string + price: + type: number + starts_at: + type: string + status: + type: string + updated_at: + type: string + user_id: + type: integer + type: object domain.AgeGroup: enum: - UNDER_13 @@ -118,6 +404,8 @@ definitions: type: string month: type: integer + payment_method: + type: string range_end: type: string range_start: @@ -128,6 +416,8 @@ definitions: type: string series_start: type: string + timezone: + type: string to: type: string year: @@ -285,14 +575,85 @@ definitions: revenue: type: number type: object + domain.AnalyticsSubscriptionRenewal: + properties: + avg_days_to_resubscribe: + type: number + expired_in_period: + type: integer + first_time_subscriptions: + type: integer + median_days_to_resubscribe: + type: number + renewal_rate: + description: 0–1; renewed_after_expiry / expired_in_period + type: number + renewed_after_expiry: + type: integer + resubscribe_after_expiry: + type: integer + returning_subscriptions: + type: integer + type: object + domain.AnalyticsSubscriptionSnapshot: + properties: + active_learners: + type: integer + active_now: + type: integer + auto_renew_enabled: + type: integer + cancelled_now: + type: integer + expired_now: + type: integer + expiring_within_7_days: + type: integer + expiring_within_30_days: + type: integer + lifetime_active: + type: integer + pending_now: + type: integer + term_active: + type: integer + type: object domain.AnalyticsSubscriptionsSection: properties: + acquisition_by_source: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array + active_by_category: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array + active_by_lifetime: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array + active_by_plan: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array active_subscriptions: type: integer by_status: items: $ref: '#/definitions/domain.AnalyticsLabelCount' type: array + cancellations_last_30_days: + items: + $ref: '#/definitions/domain.AnalyticsTimePoint' + type: array + expirations_last_30_days: + items: + $ref: '#/definitions/domain.AnalyticsTimePoint' + type: array + new_by_cohort: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array new_month: type: integer new_subscriptions_last_30_days: @@ -303,10 +664,26 @@ definitions: type: integer new_week: type: integer + renewal: + allOf: + - $ref: '#/definitions/domain.AnalyticsSubscriptionRenewal' + description: Resubscribe / renewal behaviour + resubscriptions_last_30_days: + items: + $ref: '#/definitions/domain.AnalyticsTimePoint' + type: array + revenue_by_category: + items: + $ref: '#/definitions/domain.AnalyticsLabelAmount' + type: array revenue_by_plan: items: $ref: '#/definitions/domain.AnalyticsRevenueByPlan' type: array + snapshot: + allOf: + - $ref: '#/definitions/domain.AnalyticsSubscriptionSnapshot' + description: Learner subscription behaviour total_subscriptions: type: integer type: object @@ -344,6 +721,10 @@ definitions: items: $ref: '#/definitions/domain.AnalyticsLabelCount' type: array + by_gender: + items: + $ref: '#/definitions/domain.AnalyticsLabelCount' + type: array by_knowledge_level: items: $ref: '#/definitions/domain.AnalyticsLabelCount' @@ -424,10 +805,26 @@ definitions: type: object domain.CreateCourseInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: description: SortOrder within the program when set; omit to append after current max within program_id (uniqueness is per-program). @@ -440,6 +837,13 @@ definitions: type: object domain.CreateExamPrepCatalogCourseInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string category: enum: - IELTS @@ -449,6 +853,15 @@ definitions: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string thumbnail: type: string required: @@ -457,8 +870,24 @@ definitions: type: object domain.CreateExamPrepLessonInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string thumbnail: type: string title: @@ -470,12 +899,28 @@ definitions: type: object domain.CreateExamPrepModuleInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string icon: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string thumbnail: type: string required: @@ -483,6 +928,23 @@ definitions: type: object domain.CreateExamPrepPracticeInput: properties: + parent_id: + type: integer + parent_kind: + allOf: + - $ref: '#/definitions/domain.ExamPrepParentKind' + description: ParentKind and ParentID are accepted for backward compatibility + when parents is omitted. + enum: + - CATALOG_COURSE + - UNIT + - LESSON + parents: + description: Parents optionally attaches the practice to catalog course, unit, + or lesson. Omit or null to create unlinked. + items: + $ref: '#/definitions/domain.ExamPrepPracticeParent' + type: array persona_id: type: integer publish_status: @@ -507,10 +969,26 @@ definitions: type: object domain.CreateExamPrepUnitInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: description: SortOrder within the catalog course when set; omit to append after current max sort_order within catalog_course_id. @@ -523,6 +1001,13 @@ definitions: type: object domain.CreateLessonInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string publish_status: @@ -565,12 +1050,28 @@ definitions: type: object domain.CreateModuleInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string icon: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: description: SortOrder within the course when set; omit to append after current max within course_id (uniqueness is per-course). @@ -586,10 +1087,18 @@ definitions: parent_kind: allOf: - $ref: '#/definitions/domain.ParentKind' + description: ParentKind and ParentID are accepted for backward compatibility + when parents is omitted. enum: - COURSE - MODULE - LESSON + parents: + description: Parents optionally attaches the practice to hierarchy entities. + Omit or null to create unlinked. + items: + $ref: '#/definitions/domain.PracticeParent' + type: array persona_id: type: integer publish_status: @@ -612,22 +1121,34 @@ definitions: title: type: string required: - - parent_id - - parent_kind - question_set_id type: object domain.CreateProgramInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string category: enum: - - LEARN_ENGLISH - - IELTS - - DUOLINGO + - EDUCATION type: string description: type: string name: type: string + publish_status: + description: Omit or empty defaults to DRAFT; set PUBLISHED to make visible + to learners immediately. + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: description: SortOrder inserts at this global program order when set; omit to append after current max (sort_order uniqueness is enforced). @@ -639,6 +1160,16 @@ definitions: - category - name type: object + domain.CreateQuestionOptionInput: + properties: + isCorrect: + type: boolean + optionOrder: + format: int32 + type: integer + optionText: + type: string + type: object domain.CreateRoleReq: properties: description: @@ -650,6 +1181,13 @@ definitions: required: - name type: object + domain.CreateShortAnswerInput: + properties: + acceptableAnswer: + type: string + matchType: + type: string + type: object domain.CreateTeamMemberReq: properties: bio: @@ -748,6 +1286,195 @@ definitions: message: type: string type: object + domain.ExamPrepParentKind: + enum: + - CATALOG_COURSE + - UNIT + - LESSON + type: string + x-enum-varnames: + - ExamPrepParentKindCatalogCourse + - ExamPrepParentKindUnit + - ExamPrepParentKindLesson + domain.ExamPrepPracticeParent: + properties: + parent_id: + type: integer + parent_kind: + $ref: '#/definitions/domain.ExamPrepParentKind' + type: object + domain.ExamPrepProgressSummary: + properties: + catalog_courses: + items: + $ref: '#/definitions/domain.ExamPrepProgressSummaryCatalogCourse' + type: array + type: object + domain.ExamPrepProgressSummaryCatalogCourse: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + id: + type: integer + name: + type: string + units: + items: + $ref: '#/definitions/domain.ExamPrepProgressSummaryUnit' + type: array + type: object + domain.ExamPrepProgressSummaryLesson: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + id: + type: integer + module_id: + type: integer + title: + type: string + type: object + domain.ExamPrepProgressSummaryModule: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + id: + type: integer + lessons: + items: + $ref: '#/definitions/domain.ExamPrepProgressSummaryLesson' + type: array + name: + type: string + unit_id: + type: integer + type: object + domain.ExamPrepProgressSummaryUnit: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + catalog_course_id: + type: integer + id: + type: integer + modules: + items: + $ref: '#/definitions/domain.ExamPrepProgressSummaryModule' + type: array + name: + type: string + type: object + domain.FullUpdatePracticeInput: + properties: + practice: + $ref: '#/definitions/domain.FullUpdatePracticeShellInput' + question_set: + $ref: '#/definitions/domain.FullUpdateQuestionSetInput' + questions: + items: + $ref: '#/definitions/domain.FullUpdatePracticeQuestionItem' + type: array + stimulus_blocks: + items: + $ref: '#/definitions/domain.FullUpdateStimulusBlockItem' + type: array + type: object + domain.FullUpdatePracticeQuestionItem: + properties: + associated_question_id: + type: integer + audio_correct_answer_text: + type: string + difficulty_level: + type: string + display_order: + type: integer + dynamic_payload: + $ref: '#/definitions/domain.DynamicQuestionPayload' + explanation: + type: string + id: + type: integer + image_url: + type: string + options: + items: + $ref: '#/definitions/domain.CreateQuestionOptionInput' + type: array + points: + type: integer + question_text: + type: string + question_type: + type: string + question_type_definition_id: + type: integer + sample_answer_voice_prompt: + type: string + short_answers: + items: + $ref: '#/definitions/domain.CreateShortAnswerInput' + type: array + status: + type: string + stimulus_block_key: + type: string + tips: + type: string + voice_prompt: + type: string + type: object + domain.FullUpdatePracticeShellInput: + properties: + authoring_profile: + type: string + persona_id: + type: integer + publish_status: + type: string + question_set_id: + type: integer + quick_tips: + type: string + story_description: + type: string + story_image: + type: string + title: + type: string + type: object + domain.FullUpdateQuestionSetInput: + properties: + banner_image: + type: string + description: + type: string + intro_video_url: + type: string + passing_score: + type: integer + persona: + type: string + shuffle_questions: + type: boolean + status: + type: string + time_limit_minutes: + type: integer + title: + type: string + type: object + domain.FullUpdateStimulusBlockItem: + properties: + block_key: + type: string + display_order: + type: integer + stimulus: + items: + $ref: '#/definitions/domain.DynamicElementInstance' + type: array + type: object domain.InviteTeamMemberReq: properties: email: @@ -758,6 +1485,107 @@ definitions: - email - team_role type: object + domain.LMSEntityAccess: + properties: + completed_count: + type: integer + is_accessible: + type: boolean + is_completed: + type: boolean + progress_percent: + type: integer + progress_percent_precise: + type: number + reason: + type: string + total_count: + type: integer + type: object + domain.LMSProgressSummary: + properties: + exam_prep: + $ref: '#/definitions/domain.ExamPrepProgressSummary' + programs: + items: + $ref: '#/definitions/domain.LMSProgressSummaryProgram' + type: array + type: object + domain.LMSProgressSummaryCourse: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + id: + type: integer + modules: + items: + $ref: '#/definitions/domain.LMSProgressSummaryModule' + type: array + name: + type: string + program_id: + type: integer + type: object + domain.LMSProgressSummaryLesson: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + id: + type: integer + module_id: + type: integer + title: + type: string + type: object + domain.LMSProgressSummaryModule: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + course_id: + type: integer + id: + type: integer + lessons: + items: + $ref: '#/definitions/domain.LMSProgressSummaryLesson' + type: array + name: + type: string + program_id: + type: integer + type: object + domain.LMSProgressSummaryProgram: + properties: + access: + $ref: '#/definitions/domain.LMSEntityAccess' + courses: + items: + $ref: '#/definitions/domain.LMSProgressSummaryCourse' + type: array + id: + type: integer + name: + type: string + type: object + domain.LMSUserProgress: + properties: + course_ids: + items: + type: integer + type: array + lesson_ids: + items: + type: integer + type: array + module_ids: + items: + type: integer + type: array + program_ids: + items: + type: integer + type: array + type: object domain.LogEntry: properties: caller: @@ -844,96 +1672,53 @@ definitions: name: type: string type: object - domain.QuestionAudioAnswer: + domain.PracticeParent: properties: - correctAnswerText: - type: string - createdAt: - type: string - id: - format: int64 + parent_id: type: integer - questionID: - format: int64 + parent_kind: + $ref: '#/definitions/domain.ParentKind' + type: object + domain.RecentActivityCourseRef: + properties: + id: + type: integer + name: + type: string + type: object + domain.RecentActivityLessonRef: + properties: + id: + type: integer + sort_order: + type: integer + title: + type: string + type: object + domain.RecentActivityModuleRef: + properties: + id: + type: integer + name: + type: string + sort_order: type: integer type: object - domain.QuestionOption: + domain.RecentActivityPracticeRef: properties: - createdAt: + lms_practice_id: + type: integer + scope: + description: lesson | module | course type: string - id: - format: int64 - type: integer - isCorrect: - type: boolean - optionOrder: - format: int32 - type: integer - optionText: + title: type: string - questionID: - format: int64 - type: integer type: object - domain.QuestionShortAnswer: + domain.RecentActivityProgramRef: properties: - acceptableAnswer: - type: string - createdAt: - type: string id: - format: int64 type: integer - matchType: - type: string - questionID: - format: int64 - type: integer - type: object - domain.QuestionWithDetails: - properties: - audioAnswer: - $ref: '#/definitions/domain.QuestionAudioAnswer' - createdAt: - type: string - difficultyLevel: - type: string - dynamicPayload: - $ref: '#/definitions/domain.DynamicQuestionPayload' - explanation: - type: string - id: - format: int64 - type: integer - imageURL: - type: string - options: - items: - $ref: '#/definitions/domain.QuestionOption' - type: array - points: - format: int32 - type: integer - questionText: - type: string - questionType: - type: string - questionTypeDefinitionID: - format: int64 - type: integer - sampleAnswerVoicePrompt: - type: string - shortAnswers: - items: - $ref: '#/definitions/domain.QuestionShortAnswer' - type: array - status: - type: string - tips: - type: string - updatedAt: - type: string - voicePrompt: + name: type: string type: object domain.RegisterUserReq: @@ -978,6 +1763,7 @@ definitions: enum: - SUPER_ADMIN - ADMIN + - CONTENT_MANAGER - STUDENT - OPEN_LEARNER - INSTRUCTOR @@ -986,6 +1772,7 @@ definitions: x-enum-varnames: - RoleSuperAdmin - RoleAdmin + - RoleContentManager - RoleStudent - RoleOpenLearner - RoleInstructor @@ -1111,6 +1898,20 @@ definitions: - TeamMemberStatusInactive - TeamMemberStatusSuspended - TeamMemberStatusTerminated + domain.TeamResetPasswordReq: + properties: + email: + type: string + otp: + type: string + password: + minLength: 8 + type: string + required: + - email + - otp + - password + type: object domain.TeamRole: enum: - SUPER_ADMIN @@ -1131,12 +1932,33 @@ definitions: - TeamRoleFinance - TeamRoleHR - TeamRoleAnalyst + domain.TeamSendPasswordResetReq: + properties: + email: + type: string + required: + - email + type: object domain.UpdateCourseInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string name: type: string + publish_status: + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: type: integer thumbnail: @@ -1144,6 +1966,13 @@ definitions: type: object domain.UpdateExamPrepCatalogCourseInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string category: enum: - IELTS @@ -1153,6 +1982,13 @@ definitions: type: string name: type: string + publish_status: + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: type: integer thumbnail: @@ -1160,6 +1996,11 @@ definitions: type: object domain.UpdateExamPrepPracticeInput: properties: + authoring_profile: + enum: + - STANDALONE + - IELTS_SHARED_STIMULUS + type: string persona_id: type: integer publish_status: @@ -1180,12 +2021,35 @@ definitions: title: type: string type: object + domain.UpdateExamPrepPracticeParentsInput: + properties: + parents: + items: + $ref: '#/definitions/domain.ExamPrepPracticeParent' + type: array + required: + - parents + type: object domain.UpdateExamPrepUnitInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string name: type: string + publish_status: + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: type: integer thumbnail: @@ -1201,6 +2065,13 @@ definitions: type: object domain.UpdateLessonInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string publish_status: @@ -1234,17 +2105,55 @@ definitions: type: object domain.UpdateModuleInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string description: type: string icon: type: string name: type: string + publish_status: + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: type: integer type: object + domain.UpdateMyTeamProfileReq: + properties: + bio: + type: string + department: + type: string + first_name: + type: string + job_title: + type: string + last_name: + type: string + phone_number: + type: string + profile_picture_url: + type: string + work_phone: + type: string + type: object domain.UpdatePracticeInput: properties: + authoring_profile: + enum: + - STANDALONE + - IELTS_SHARED_STIMULUS + type: string persona_id: type: integer publish_status: @@ -1265,18 +2174,39 @@ definitions: title: type: string type: object + domain.UpdatePracticeParentsInput: + properties: + parents: + items: + $ref: '#/definitions/domain.PracticeParent' + type: array + required: + - parents + type: object domain.UpdateProgramInput: properties: + access_tier: + enum: + - FREE + - free + - PREMIUM + - premium + type: string category: enum: - - LEARN_ENGLISH - - IELTS - - DUOLINGO + - EDUCATION type: string description: type: string name: type: string + publish_status: + enum: + - DRAFT + - draft + - PUBLISHED + - published + type: string sort_order: type: integer thumbnail: @@ -1348,8 +2278,6 @@ definitions: type: string gender: type: string - initial_assessment_completed: - type: boolean knowledge_level: type: string language_challange: @@ -1373,6 +2301,10 @@ definitions: type: object domain.UserProfileResponse: properties: + active_subscriptions: + items: + $ref: '#/definitions/domain.UserProfileSubscription' + type: array age_group: type: string birth_day: @@ -1397,9 +2329,6 @@ definitions: type: string id: type: integer - initial_assessment_completed: - description: Profile fields - type: boolean language_challange: type: string language_goal: @@ -1411,6 +2340,7 @@ definitions: learning_goal: type: string nick_name: + description: Profile fields type: string occupation: type: string @@ -1437,6 +2367,73 @@ definitions: updated_at: type: string type: object + domain.UserProfileSubscription: + properties: + auto_renew: + type: boolean + category: + type: string + created_at: + type: string + currency: + type: string + duration_unit: + type: string + duration_value: + type: integer + expires_at: + type: string + id: + type: integer + is_lifetime: + type: boolean + plan_id: + type: integer + plan_name: + type: string + price: + type: number + starts_at: + type: string + status: + type: string + type: object + domain.UserRecentActivityFeed: + properties: + items: + items: + $ref: '#/definitions/domain.UserRecentActivityItem' + type: array + user_id: + type: integer + type: object + domain.UserRecentActivityItem: + properties: + course: + $ref: '#/definitions/domain.RecentActivityCourseRef' + headline: + description: Headline is optional server-rendered primary line (client may + ignore and build from refs). + type: string + id: + type: string + kind: + description: Kind drives default icon treatment on the client (e.g. joined + vs completion). + type: string + lesson: + $ref: '#/definitions/domain.RecentActivityLessonRef' + module: + $ref: '#/definitions/domain.RecentActivityModuleRef' + occurred_at: + description: OccurredAt is when the platform recorded the event (typically + completion time). + type: string + practice: + $ref: '#/definitions/domain.RecentActivityPracticeRef' + program: + $ref: '#/definitions/domain.RecentActivityProgramRef' + type: object domain.UserStatus: enum: - PENDING @@ -1783,7 +2780,15 @@ definitions: type: object handlers.addQuestionToSetReq: properties: + associated_question_id: + description: Section anchor question in the same set; must have a lower display_order + and no association of its own. + minimum: 1 + type: integer display_order: + description: Omit to append after the current highest display_order in the + set; set explicitly to insert at a position. + minimum: 0 type: integer question_id: type: integer @@ -1799,6 +2804,31 @@ definitions: required: - user_id type: object + handlers.adminApplySubscriptionReq: + properties: + plan_id: + minimum: 1 + type: integer + record_payment: + description: RecordPayment when omitted defaults to true (record SUCCESS payment + at plan price). + type: boolean + required: + - plan_id + type: object + handlers.authorizeChapaDirectPaymentReq: + properties: + otp: + type: string + request_id: + type: string + session_id: + type: string + required: + - otp + - request_id + - session_id + type: object handlers.autoRenewReq: properties: auto_renew: @@ -1817,6 +2847,15 @@ definitions: - current_password - new_password type: object + handlers.completePresignedUploadReq: + properties: + file_size: + type: integer + media_type: + type: string + object_key: + type: string + type: object handlers.createEmailTemplateReq: properties: body_html: @@ -1919,26 +2958,22 @@ definitions: properties: category: enum: - - LEARN_ENGLISH - - IELTS - - DUOLINGO + - EDUCATION type: string currency: type: string description: type: string duration_unit: - enum: - - DAY - - WEEK - - MONTH - - YEAR type: string duration_value: - minimum: 1 type: integer is_active: type: boolean + is_free: + type: boolean + is_lifetime: + type: boolean name: type: string price: @@ -1947,10 +2982,7 @@ definitions: required: - category - currency - - duration_unit - - duration_value - name - - price type: object handlers.createQuestionReq: properties: @@ -2008,7 +3040,6 @@ definitions: set_type: enum: - PRACTICE - - INITIAL_ASSESSMENT - QUIZ - EXAM - SURVEY @@ -2026,12 +3057,29 @@ definitions: - set_type - title type: object + handlers.createQuestionTypeDefinitionGroupReq: + properties: + description: + type: string + display_order: + type: integer + name: + type: string + status: + type: string + required: + - name + type: object handlers.createQuestionTypeDefinitionReq: properties: description: type: string display_name: type: string + group_ids: + items: + type: integer + type: array key: type: string response_component_kinds: @@ -2056,6 +3104,22 @@ definitions: - display_name - key type: object + handlers.initiateChapaDirectPaymentReq: + properties: + email: + type: string + payment_method: + type: string + phone: + type: string + plan_id: + type: integer + required: + - email + - payment_method + - phone + - plan_id + type: object handlers.initiateDirectPaymentReq: properties: email: @@ -2154,6 +3218,17 @@ definitions: required: - option_text type: object + handlers.presignedUploadReq: + properties: + content_type: + type: string + file_size: + type: integer + filename: + type: string + media_type: + type: string + type: object handlers.previewEmailTemplateReq: properties: variables: @@ -2177,6 +3252,13 @@ definitions: - access_token - refresh_token type: object + handlers.requestCheckoutLinkReq: + properties: + category: + type: string + plan_id: + type: integer + type: object handlers.shortAnswerInput: properties: acceptable_answer: @@ -2335,9 +3417,7 @@ definitions: properties: category: enum: - - LEARN_ENGLISH - - IELTS - - DUOLINGO + - EDUCATION type: string currency: type: string @@ -2349,6 +3429,10 @@ definitions: type: integer is_active: type: boolean + is_free: + type: boolean + is_lifetime: + type: boolean name: type: string price: @@ -2356,6 +3440,9 @@ definitions: type: object handlers.updateQuestionOrderReq: properties: + associated_question_id: + minimum: 1 + type: integer display_order: type: integer required: @@ -2419,30 +3506,18 @@ definitions: title: type: string type: object - handlers.updateQuestionTypeDefinitionReq: + handlers.updateQuestionTypeDefinitionGroupReq: properties: description: type: string - display_name: + display_order: + type: integer + name: type: string - response_component_kinds: - items: - type: string - type: array - response_schema: - items: - $ref: '#/definitions/domain.DynamicElementDefinition' - type: array status: type: string - stimulus_component_kinds: - items: - type: string - type: array - stimulus_schema: - items: - $ref: '#/definitions/domain.DynamicElementDefinition' - type: array + type: object + handlers.updateQuestionTypeDefinitionReq: type: object handlers.validateQuestionTypeDefinitionReq: properties: @@ -2691,46 +3766,6 @@ paths: summary: Check if phone number or email exist tags: - user - /api/v1/{tenant_slug}/user/knowledge-level: - put: - consumes: - - application/json - description: Updates the knowledge level of the specified user after initial - assessment - parameters: - - description: User ID - in: path - name: user_id - required: true - type: integer - - description: Knowledge level - in: body - name: knowledge_level - required: true - schema: - $ref: '#/definitions/domain.UpdateKnowledgeLevelReq' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.ErrorResponse' - "404": - description: Not Found - schema: - $ref: '#/definitions/domain.ErrorResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.ErrorResponse' - summary: Update user's knowledge level - tags: - - user /api/v1/{tenant_slug}/user/register: post: consumes: @@ -2959,6 +3994,14 @@ paths: summary: Get activity log by ID tags: - activity-logs + /api/v1/activity-logs/export: + get: + produces: + - text/csv + responses: {} + summary: Export activity logs as CSV (admin) + tags: + - activity-logs /api/v1/admin: get: consumes: @@ -3849,7 +4892,7 @@ paths: in: query name: currency type: string - - description: Plan category (LEARN_ENGLISH, IELTS, DUOLINGO) + - description: Plan category (EDUCATION) in: query name: plan_category type: string @@ -3928,6 +4971,14 @@ paths: summary: Get payment by ID (admin) tags: - payments + /api/v1/admin/payments/export: + get: + produces: + - text/csv + responses: {} + summary: Export payments as CSV (admin) + tags: + - payments /api/v1/admin/roles/{role}/bulk-deactivate: post: consumes: @@ -4032,6 +5083,95 @@ paths: only) tags: - admin + /api/v1/admin/subscriptions/{id}/cancel: + post: + description: Cancels any user_subscriptions row by ID. Does not require ownership + by the caller. + parameters: + - description: Subscription ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + security: + - Bearer: [] + summary: Cancel a learner subscription (admin) + tags: + - subscriptions + /api/v1/admin/subscriptions/export: + get: + produces: + - text/csv + responses: {} + summary: Export user subscriptions as CSV (admin) + tags: + - subscriptions + /api/v1/admin/users/{user_id}/learning-activity: + get: + description: Returns LMS and exam-prep completion trees, progress summaries, + completed ID snapshots, and recent activity timeline + parameters: + - description: Target user ID + in: path + name: user_id + required: true + type: integer + - description: Max recent-activity items (default 40, max 120) + in: query + name: limit + type: integer + - description: Include practice completions in recent-activity feed + in: query + name: include_practices + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/domain.Response' + - properties: + data: + $ref: '#/definitions/domain.AdminUserLearningActivityDetails' + type: object + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + security: + - Bearer: [] + summary: Get full learning activity for a user (admin) + tags: + - lms /api/v1/admin/users/{user_id}/lms-learning-activity: get: description: Returns programs, courses, modules, and lessons with completion @@ -4108,6 +5248,94 @@ paths: summary: Recent activity timeline for a user (admin) tags: - lms + /api/v1/admin/users/{user_id}/subscriptions: + get: + description: Returns display status, active plans by category, full subscription + history, and related payments + parameters: + - description: Target user ID + in: path + name: user_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/domain.Response' + - properties: + data: + $ref: '#/definitions/domain.AdminUserSubscriptionDetails' + type: object + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + security: + - Bearer: [] + summary: Get all subscription details for a user (admin) + tags: + - subscriptions + /api/v1/admin/users/{user_id}/subscriptions/extend: + post: + consumes: + - application/json + description: 'Unified admin action: if the learner has no active subscription + in the plan''s category, creates one (grant). If they already have an active + subscription in that category, extends it by one period of the selected plan + (and switches plan_id when different). Optionally records a SUCCESS payment + at the plan price (record_payment, default true).' + parameters: + - description: Target learner user ID + in: path + name: user_id + required: true + type: integer + - description: Plan to grant or extend + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.adminApplySubscriptionReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "201": + description: Created + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + security: + - Bearer: [] + summary: Grant or extend a learner subscription (admin) + tags: + - subscriptions /api/v1/admin/users/deletion-requests: get: consumes: @@ -4175,28 +5403,34 @@ paths: - user /api/v1/analytics/dashboard: get: - description: 'Platform analytics with optional date filters: all-time (default), - year, year+month, or custom from/to range. When year is set, payments.revenue_monthly - returns Jan–Dec SUCCESS revenue totals (UTC) per currency for that calendar - year — use for yearly revenue charts. Daily series remains in revenue_last_30_days - (see date_filter.series_*). Courses section counts LMS + exam_prep inventory.' + description: 'Platform analytics with optional date filters in Africa/Addis_Ababa + (EAT): all-time (default), year, year+month, or custom from/to range. When + year is set, payments.revenue_monthly returns Jan–Dec SUCCESS revenue totals + (EAT) per currency for that calendar year. Optional payment_method filters + payment/revenue metrics (exact or METHOD:% variants). Daily series remains + in revenue_last_30_days (see date_filter.series_*). Courses section counts + LMS + exam_prep inventory.' parameters: - - description: Calendar year (e.g. 2025) + - description: EAT calendar year (e.g. 2025) in: query name: year type: integer - - description: Calendar month 1-12 (requires year) + - description: EAT calendar month 1-12 (requires year) in: query name: month type: integer - - description: Custom range start (YYYY-MM-DD or RFC3339) + - description: Custom EAT range start (YYYY-MM-DD or RFC3339) in: query name: from type: string - - description: Custom range end (YYYY-MM-DD or RFC3339, inclusive) + - description: Custom EAT range end (YYYY-MM-DD or RFC3339, inclusive) in: query name: to type: string + - description: Filter payment/revenue metrics (e.g. CHAPA, ARIFPAY, ADMIN_GRANT) + in: query + name: payment_method + type: string produces: - application/json responses: @@ -4248,86 +5482,6 @@ paths: summary: Check mobile app version tags: - app-versions - /api/v1/assessment/questions: - get: - description: Returns all active assessment questions from the initial assessment - set - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/domain.QuestionWithDetails' - type: array - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.ErrorResponse' - summary: List assessment questions - tags: - - assessment-question - post: - consumes: - - application/json - description: Creates a new assessment question using the unified questions system - parameters: - - description: Create question payload - in: body - name: body - required: true - schema: - $ref: '#/definitions/handlers.createQuestionReq' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/domain.Response' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.ErrorResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.ErrorResponse' - summary: Create assessment question - tags: - - assessment-question - /api/v1/assessment/questions/{id}: - get: - description: Returns a single assessment question with its options or answer - parameters: - - description: Question ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.QuestionWithDetails' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.ErrorResponse' - "404": - description: Not Found - schema: - $ref: '#/definitions/domain.ErrorResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.ErrorResponse' - summary: Get assessment question by ID - tags: - - assessment-question /api/v1/auth/apple: post: consumes: @@ -4598,450 +5752,6 @@ paths: responses: {} tags: - practices - /api/v1/exam-prep/catalog-courses: - get: - parameters: - - default: 20 - description: Page size - in: query - name: limit - type: integer - - default: 0 - description: Offset - in: query - name: offset - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: List exam-prep catalog courses - tags: - - exam-prep - post: - consumes: - - application/json - description: Top-level exam track (DET, IELTS, …) in schema exam_prep — separate - from LMS programs/courses - parameters: - - description: Catalog course - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateExamPrepCatalogCourseInput' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/domain.Response' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.ErrorResponse' - summary: Create exam-prep catalog course - tags: - - exam-prep - /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units: - get: - parameters: - - description: Catalog course ID - in: path - name: catalogCourseId - required: true - type: integer - - default: 20 - description: Page size - in: query - name: limit - type: integer - - default: 0 - description: Offset - in: query - name: offset - type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: List exam-prep units for a catalog course - tags: - - exam-prep - post: - consumes: - - application/json - description: Unit under a catalog course (e.g. chapter title). Optional sort_order - assigns position within that catalog course (siblings at or after that index - are shifted); omit to append after the current highest sort_order in the catalog - course. - parameters: - - description: Catalog course ID - in: path - name: catalogCourseId - required: true - type: integer - - description: Unit - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateExamPrepUnitInput' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/domain.Response' - summary: Create exam-prep unit - tags: - - exam-prep - /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units/reorder: - put: - parameters: - - description: Catalog course ID - in: path - name: catalogCourseId - required: true - type: integer - - description: 'ordered_ids: every unit id in this catalog course, new order' - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.ReorderIDsRequest' - responses: {} - summary: Reorder units within a catalog course - tags: - - exam-prep - /api/v1/exam-prep/catalog-courses/{id}: - delete: - parameters: - - description: Catalog course ID - in: path - name: id - required: true - type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: Delete exam-prep catalog course - tags: - - exam-prep - get: - parameters: - - description: Catalog course ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: Get exam-prep catalog course by ID - tags: - - exam-prep - put: - consumes: - - application/json - parameters: - - description: Catalog course ID - in: path - name: id - required: true - type: integer - - description: Fields to update - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UpdateExamPrepCatalogCourseInput' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: Update exam-prep catalog course - tags: - - exam-prep - /api/v1/exam-prep/catalog-courses/reorder: - put: - consumes: - - application/json - parameters: - - description: 'ordered_ids: every catalog course id exactly once' - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.ReorderIDsRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Response' - summary: Reorder all exam-prep catalog courses - tags: - - exam-prep - /api/v1/exam-prep/lessons/{id}: - delete: - responses: {} - summary: Delete exam-prep lesson - tags: - - exam-prep - get: - responses: {} - summary: Get exam-prep lesson by ID - tags: - - exam-prep - put: - responses: {} - summary: Update exam-prep lesson - tags: - - exam-prep - /api/v1/exam-prep/lessons/{lessonId}/practices: - get: - parameters: - - description: Exam prep lesson ID - in: path - name: lessonId - required: true - type: integer - - default: 20 - description: Page size - in: query - name: limit - type: integer - - default: 0 - description: Offset - in: query - name: offset - type: integer - responses: {} - summary: List exam-prep practices for a lesson - tags: - - exam-prep - post: - parameters: - - description: Exam prep lesson ID (unit_module_lessons.id) - in: path - name: lessonId - required: true - type: integer - - description: Practice - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateExamPrepPracticeInput' - responses: {} - summary: Create exam-prep practice (under a lesson; uses shared question_sets) - tags: - - exam-prep - /api/v1/exam-prep/modules/{id}: - delete: - responses: {} - summary: Delete exam-prep module - tags: - - exam-prep - get: - responses: {} - summary: Get exam-prep module by ID - tags: - - exam-prep - put: - responses: {} - summary: Update exam-prep module - tags: - - exam-prep - /api/v1/exam-prep/modules/{moduleId}/lessons: - get: - parameters: - - description: Exam prep unit module ID - in: path - name: moduleId - required: true - type: integer - - default: 20 - description: Page size - in: query - name: limit - type: integer - - default: 0 - description: Offset - in: query - name: offset - type: integer - responses: {} - summary: List exam-prep lessons for a unit module - tags: - - exam-prep - post: - parameters: - - description: Exam prep unit module ID - in: path - name: moduleId - required: true - type: integer - - description: Lesson - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateExamPrepLessonInput' - responses: {} - summary: Create exam-prep lesson (under a unit module) - tags: - - exam-prep - /api/v1/exam-prep/modules/{moduleId}/lessons/reorder: - put: - responses: {} - summary: Reorder lessons within an exam-prep unit module - tags: - - exam-prep - /api/v1/exam-prep/practices/{id}: - delete: - parameters: - - description: Exam prep practice ID - in: path - name: id - required: true - type: integer - responses: {} - summary: Delete exam-prep practice - tags: - - exam-prep - get: - parameters: - - description: Exam prep practice ID - in: path - name: id - required: true - type: integer - responses: {} - summary: Get exam-prep practice by ID - tags: - - exam-prep - put: - parameters: - - description: Exam prep practice ID - in: path - name: id - required: true - type: integer - - description: Fields to update - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UpdateExamPrepPracticeInput' - responses: {} - summary: Update exam-prep practice - tags: - - exam-prep - /api/v1/exam-prep/units/{id}: - delete: - parameters: - - description: Unit ID - in: path - name: id - required: true - type: integer - responses: {} - summary: Delete exam-prep unit - tags: - - exam-prep - get: - parameters: - - description: Unit ID - in: path - name: id - required: true - type: integer - responses: {} - summary: Get exam-prep unit by ID - tags: - - exam-prep - put: - parameters: - - description: Unit ID - in: path - name: id - required: true - type: integer - - description: Fields to update - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UpdateExamPrepUnitInput' - responses: {} - summary: Update exam-prep unit - tags: - - exam-prep - /api/v1/exam-prep/units/{unitId}/modules: - get: - parameters: - - description: Unit ID - in: path - name: unitId - required: true - type: integer - responses: {} - summary: List exam-prep modules for a unit - tags: - - exam-prep - post: - parameters: - - description: Unit ID - in: path - name: unitId - required: true - type: integer - - description: Module - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateExamPrepModuleInput' - responses: {} - summary: Create exam-prep module - tags: - - exam-prep - /api/v1/exam-prep/units/{unitId}/modules/reorder: - put: - parameters: - - description: Unit ID - in: path - name: unitId - required: true - type: integer - - description: ordered_ids - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.ReorderIDsRequest' - responses: {} - summary: Reorder modules within a unit - tags: - - exam-prep /api/v1/faqs: get: description: Returns active FAQs for public/help center usage @@ -5159,6 +5869,52 @@ paths: summary: Upload an audio file tags: - files + /api/v1/files/complete-upload: + post: + consumes: + - application/json + description: Call after PUT upload to upload_url. Returns the same file metadata + shape as POST /files/upload. + parameters: + - description: Complete upload request + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.completePresignedUploadReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: Complete presigned MinIO upload + tags: + - files + /api/v1/files/presign-upload: + post: + consumes: + - application/json + description: Returns a short-lived PUT URL and object key. Upload the file with + HTTP PUT to upload_url using the same Content-Type, then call POST /files/complete-upload. + parameters: + - description: Presigned upload request + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.presignedUploadReq' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/domain.Response' + summary: Create presigned MinIO upload URL + tags: + - files /api/v1/files/refresh-url: post: consumes: @@ -5591,9 +6347,9 @@ paths: - lms /api/v1/lms/progress-summary: get: - description: Returns the learner's nested LMS hierarchy with the same access - progress data exposed on the individual program, course, module, and lesson - APIs. + description: Returns the learner's nested Learn English hierarchy (programs) + and exam-prep hierarchy (exam_prep) with the same access progress data exposed + on the individual content APIs. produces: - application/json responses: @@ -5605,7 +6361,7 @@ paths: description: Internal Server Error schema: $ref: '#/definitions/domain.ErrorResponse' - summary: Get my LMS progress summary + summary: Get my LMS and exam-prep progress summary tags: - lms /api/v1/logs: @@ -5744,7 +6500,55 @@ paths: summary: Create lesson tags: - lessons + /api/v1/modules/{moduleId}/lessons/reorder: + put: + parameters: + - description: Module ID + in: path + name: moduleId + required: true + type: integer + - description: 'ordered_ids: every lesson id in this module, in the new order' + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.ReorderIDsRequest' + responses: {} + summary: Reorder lessons within a module + tags: + - lessons /api/v1/notifications/{id}: + delete: + description: Deletes one in-app notification owned by the authenticated user. + parameters: + - description: Notification ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Delete a single in-app notification + tags: + - notifications get: description: Returns a single in-app notification. Users may only fetch their own notifications unless they have list-all access. @@ -5784,9 +6588,10 @@ paths: post: consumes: - multipart/form-data - description: Sends an email to specified user IDs, all users of a role, or direct - email addresses with optional image attachment. Optionally schedule for later - with scheduled_at (RFC3339). + description: Sends an email to specified user IDs, users of a platform role, + team member IDs, team members of a team_role, or direct email addresses with + optional image attachment. Optionally schedule for later with scheduled_at + (RFC3339). produces: - application/json responses: @@ -5805,6 +6610,63 @@ paths: summary: Send bulk email tags: - notifications + /api/v1/notifications/bulk-in-app: + post: + consumes: + - application/json + description: Creates in-app notifications for specified platform user IDs, users + matching a platform role, team member IDs, or team members matching a team_role. + Optionally schedule for later with scheduled_at (RFC3339). + parameters: + - description: Bulk in-app content + in: body + name: body + required: true + schema: + properties: + level: + type: string + message: + type: string + role: + type: string + scheduled_at: + type: string + team_member_ids: + items: + format: int64 + type: integer + type: array + team_role: + type: string + title: + type: string + type: + type: string + user_ids: + items: + format: int64 + type: integer + type: array + type: object + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Send bulk in-app notification + tags: + - notifications /api/v1/notifications/bulk-push: post: consumes: @@ -5899,6 +6761,37 @@ paths: summary: Send bulk SMS tags: - notifications + /api/v1/notifications/delete-in-app: + post: + consumes: + - application/json + description: Deletes in-app notifications by ID for the authenticated user. + Non-matching IDs are ignored. + parameters: + - description: Notification IDs + in: body + name: body + required: true + schema: + type: object + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Delete multiple in-app notifications + tags: + - notifications /api/v1/notifications/scheduled: get: description: Returns paginated scheduled notifications with optional status, @@ -6137,8 +7030,8 @@ paths: - payments /api/v1/payments/arifpay/success: get: - description: Displays the Rezina success page after ArifPay redirects - the learner back to the backend. + description: Displays the Rezina success page after ArifPay redirects the learner + back to the backend. parameters: - description: ArifPay session identifier in: query @@ -6188,10 +7081,86 @@ paths: summary: Chapa payment callback tags: - payments + /api/v1/payments/chapa/direct: + post: + consumes: + - application/json + description: Starts a Chapa Direct Charge (USSD push or OTP) for a subscription + plan without hosted checkout redirect. + parameters: + - description: Chapa direct charge request + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.initiateChapaDirectPaymentReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Initiate Chapa direct charge subscription payment + tags: + - payments + /api/v1/payments/chapa/direct/authorize: + post: + consumes: + - application/json + description: Completes OTP authorization for Chapa direct charge methods that + require it. + parameters: + - description: Chapa direct charge authorization request + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.authorizeChapaDirectPaymentReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Authorize Chapa direct charge with OTP + tags: + - payments + /api/v1/payments/chapa/direct/methods: + get: + description: Returns wallet methods supported by Chapa Direct Charge API (USSD + push and OTP flows). + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: Get Chapa direct charge payment methods + tags: + - payments /api/v1/payments/chapa/success: get: - description: Displays the Rezina success page after Chapa redirects - the learner to return_url + description: Displays the Rezina success page after Chapa redirects the learner + to return_url parameters: - description: Chapa transaction reference (tx_ref) in: query @@ -6461,11 +7430,28 @@ paths: tags: - personas /api/v1/practices: + get: + parameters: + - description: Page size (default 20, max 200) + in: query + name: limit + type: integer + - description: Page offset (default 0) + in: query + name: offset + type: integer + - description: When true, return only practices with no parent links (admin) + in: query + name: unlinked_only + type: boolean + responses: {} + tags: + - practices post: consumes: - application/json parameters: - - description: 'Practice (parent_kind: COURSE | MODULE | LESSON)' + - description: Practice (optional parents; link later via PUT /practices/:id/parents) in: body name: body required: true @@ -6502,7 +7488,7 @@ paths: name: id required: true type: integer - - description: Fields to update (parent is immutable) + - description: Practice metadata fields to update in: body name: body required: true @@ -6511,12 +7497,116 @@ paths: responses: {} tags: - practices + /api/v1/practices/{id}/full: + get: + description: Returns practice metadata, linked question set settings, and all + questions in the set (same shape as PUT /practices/{id}/full). + parameters: + - description: Practice ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Get LMS practice with question set and questions + tags: + - practices + put: + consumes: + - application/json + description: Updates practice metadata, linked question set settings, and syncs + questions in one request. Questions omitted from the questions array are removed + from the set (not deleted from the bank). + parameters: + - description: Practice ID + in: path + name: id + required: true + type: integer + - description: Full practice update payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.FullUpdatePracticeInput' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Full update LMS practice with question set and questions + tags: + - practices + /api/v1/practices/{id}/parents: + put: + consumes: + - application/json + parameters: + - description: Practice ID + in: path + name: id + required: true + type: integer + - description: Parent links (replaces all; use empty array to detach) + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.UpdatePracticeParentsInput' + responses: {} + tags: + - practices + /api/v1/practices/{id}/parents/{parentKind}/{parentId}: + delete: + parameters: + - description: Practice ID + in: path + name: id + required: true + type: integer + - description: Parent kind (COURSE, MODULE, LESSON) + in: path + name: parentKind + required: true + type: string + - description: Parent entity ID + in: path + name: parentId + required: true + type: integer + responses: {} + tags: + - practices /api/v1/practices/{practiceId}/questions: get: - description: Returns paginated questions for a practice(question-set), including - AUDIO fields + description: Returns paginated questions for an LMS practice, including shared + stimulus blocks and each question's effective dynamic payload parameters: - - description: Practice(question-set) ID + - description: LMS practice ID in: path name: practiceId required: true @@ -6843,7 +7933,7 @@ paths: get: description: Returns a paginated list of question sets filtered by type parameters: - - description: Set type (PRACTICE, INITIAL_ASSESSMENT, QUIZ, EXAM, SURVEY, CAPSTONE) + - description: Set type (PRACTICE, QUIZ, EXAM, SURVEY, CAPSTONE) in: query name: set_type required: true @@ -7121,7 +8211,8 @@ paths: - question-set-items /api/v1/question-sets/{setId}/questions: get: - description: Returns all questions in a question set with details + description: Returns all questions in a question set with contextual shared + stimulus data for linked LMS and exam-prep practices parameters: - description: Question Set ID in: path @@ -7149,7 +8240,8 @@ paths: post: consumes: - application/json - description: Links a question to a question set + description: Links a question to a question set. Omit display_order to append + after the current max; the assigned value is returned in the response. parameters: - description: Question Set ID in: path @@ -7526,6 +8618,117 @@ paths: summary: Search questions tags: - questions + /api/v1/questions/type-definition-groups: + get: + parameters: + - description: Filter by status (ACTIVE, INACTIVE) + in: query + name: status + type: string + - default: 20 + description: Page size (default 20, max 200) + in: query + name: limit + type: integer + - default: 0 + description: Page offset + in: query + name: offset + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: List question type definition groups + tags: + - questions + post: + consumes: + - application/json + parameters: + - description: Group payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.createQuestionTypeDefinitionGroupReq' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/domain.Response' + summary: Create question type definition group + tags: + - questions + /api/v1/questions/type-definition-groups/{id}: + delete: + parameters: + - description: Group id + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: Delete question type definition group + tags: + - questions + get: + parameters: + - description: Group id + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Get question type definition group with definitions + tags: + - questions + put: + consumes: + - application/json + parameters: + - description: Group id + in: path + name: id + required: true + type: integer + - description: Update group payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/handlers.updateQuestionTypeDefinitionGroupReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: Update question type definition group + tags: + - questions /api/v1/questions/type-definitions: get: parameters: @@ -7682,6 +8885,45 @@ paths: summary: Update reusable question-type definition tags: - questions + /api/v1/questions/type-definitions/{id}/practices: + get: + description: Returns LMS and exam-prep practices whose linked question set contains + at least one non-archived question matching the definition (by question_type_definition_id + or legacy question_type). + parameters: + - description: Question type definition id + in: path + name: id + required: true + type: integer + - default: 20 + description: Limit + in: query + name: limit + type: integer + - default: 0 + description: Offset + in: query + name: offset + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: List practices globally by question type definition + tags: + - questions /api/v1/questions/validate-question-type-definition: post: consumes: @@ -8253,12 +9495,16 @@ paths: - user /api/v1/subscription-plans: get: - description: Returns all subscription plans + description: 'Returns subscription plans. Optional category filter: EDUCATION.' parameters: - - description: Return only active plans + - description: Return only active plans (default true) in: query name: active_only type: boolean + - description: Filter by plan category (EDUCATION) + in: query + name: category + type: string produces: - application/json responses: @@ -8266,6 +9512,10 @@ paths: description: OK schema: $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' "500": description: Internal Server Error schema: @@ -8528,7 +9778,8 @@ paths: - subscriptions /api/v1/subscriptions/me: get: - description: Returns the authenticated user's active subscription + description: Returns all active subscriptions for the authenticated user (one + per plan category) produces: - application/json responses: @@ -8536,11 +9787,46 @@ paths: description: OK schema: $ref: '#/definitions/domain.Response' - "404": - description: Not Found + summary: Get active subscriptions + tags: + - subscriptions + /api/v1/subscriptions/request-checkout-link: + post: + consumes: + - application/json + description: Sends the standalone web checkout URL to the learner by email or + SMS (registration channel). Intended when mobile clients show a subscription-required + state. + parameters: + - description: Optional plan or category for deep link + in: body + name: body + schema: + $ref: '#/definitions/handlers.requestCheckoutLinkReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request schema: $ref: '#/definitions/domain.ErrorResponse' - summary: Get current subscription + "409": + description: Conflict + schema: + $ref: '#/definitions/domain.ErrorResponse' + "429": + description: Too Many Requests + schema: + $ref: '#/definitions/domain.ErrorResponse' + "503": + description: Service Unavailable + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Send web checkout link to learner tags: - subscriptions /api/v1/subscriptions/status: @@ -8821,6 +10107,50 @@ paths: summary: Get my team profile tags: - team + put: + consumes: + - application/json + description: Update the authenticated team member's own profile fields + parameters: + - description: Profile update payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.UpdateMyTeamProfileReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/domain.Response' + - properties: + data: + $ref: '#/definitions/domain.TeamMemberResponse' + type: object + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + security: + - Bearer: [] + summary: Update my team profile + tags: + - team /api/v1/team/members: get: consumes: @@ -9184,6 +10514,14 @@ paths: summary: Update team member status tags: - team + /api/v1/team/members/export: + get: + produces: + - text/csv + responses: {} + summary: Export team members as CSV (admin) + tags: + - team /api/v1/team/members/invite: post: consumes: @@ -9255,6 +10593,76 @@ paths: summary: Refresh team member tokens tags: - team + /api/v1/team/resetPassword: + post: + consumes: + - application/json + description: Completes team password reset using email + OTP from the reset + link. Public. + parameters: + - description: Reset payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.TeamResetPasswordReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Reset team member password + tags: + - team + /api/v1/team/sendResetCode: + post: + consumes: + - application/json + description: Sends a password-reset email with a link to the team member (admin + panel). Public. + parameters: + - description: Email + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.TeamSendPasswordResetReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Send team password reset link + tags: + - team /api/v1/team/stats: get: consumes: @@ -9289,6 +10697,31 @@ paths: summary: Get team member statistics tags: - team + /api/v1/team/verifyResetCode: + get: + description: Checks whether email+otp from a reset link are still valid without + consuming the OTP. Public. + parameters: + - description: Team member email + in: query + name: email + required: true + type: string + - description: Reset OTP from the email link + in: query + name: otp + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + summary: Verify team password reset link + tags: + - team /api/v1/tenant: get: consumes: @@ -9490,6 +10923,44 @@ paths: summary: Delete user by ID tags: - user + /api/v1/user/knowledge-level: + put: + consumes: + - application/json + description: Updates the authenticated learner's self-reported knowledge level. + parameters: + - description: Knowledge level + in: body + name: knowledge_level + required: true + schema: + $ref: '#/definitions/domain.UpdateKnowledgeLevelReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.Response' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.ErrorResponse' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/domain.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.ErrorResponse' + summary: Update user's knowledge level + tags: + - user /api/v1/user/me: delete: description: Starts account deletion with grace period before permanent purge @@ -9608,7 +11079,8 @@ paths: post: consumes: - application/json - description: Send reset code + description: Sends a password-reset OTP code by email or SMS for learner (mobile) + accounts. Email delivers the numeric code (not a link). parameters: - description: Send reset code in: body @@ -9758,7 +11230,8 @@ paths: in: query name: created_after type: string - - description: User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED) + - description: User account status filter (ACTIVE, PENDING, SUSPENDED, DEACTIVATED, + or INACTIVE for all non-ACTIVE statuses) in: query name: status type: string @@ -9793,6 +11266,14 @@ paths: summary: Get all users tags: - user + /api/v1/users/export: + get: + produces: + - text/csv + responses: {} + summary: Export users as CSV (admin) + tags: + - user /api/v1/users/summary: get: consumes: @@ -10202,8 +11683,8 @@ paths: - Vimeo /payment/success: get: - description: Displays the Rezina success page after Chapa redirects - the learner to return_url + description: Displays the Rezina success page after Chapa redirects the learner + to return_url parameters: - description: Chapa transaction reference (tx_ref) in: query diff --git a/gen/db/models.go b/gen/db/models.go index c646184d..c6f5a4c6 100644 --- a/gen/db/models.go +++ b/gen/db/models.go @@ -164,13 +164,6 @@ type GlobalSetting struct { UpdatedAt pgtype.Timestamptz `json:"updated_at"` } -type InitialAssessmentLevelThreshold struct { - Level string `json:"level"` - MinPercent int32 `json:"min_percent"` - DisplayOrder int32 `json:"display_order"` - UpdatedAt pgtype.Timestamptz `json:"updated_at"` -} - type Lesson struct { ID int64 `json:"id"` ModuleID int64 `json:"module_id"` @@ -503,6 +496,32 @@ type ReportedIssue struct { UpdatedAt pgtype.Timestamp `json:"updated_at"` } +type RetiredInitialAssessmentCompletion struct { + UserID int64 `json:"user_id"` + Completed bool `json:"completed"` +} + +type RetiredInitialAssessmentLevelThreshold struct { + Level string `json:"level"` + MinPercent int32 `json:"min_percent"` + DisplayOrder int32 `json:"display_order"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + +type RetiredInitialAssessmentQuestionSet struct { + QuestionSetID int64 `json:"question_set_id"` + SetType string `json:"set_type"` +} + +type RetiredUserInitialAssessmentProgress struct { + UserID int64 `json:"user_id"` + NextLevel string `json:"next_level"` + HighestPassedLevel pgtype.Text `json:"highest_passed_level"` + Completed bool `json:"completed"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` + SubjectID int64 `json:"subject_id"` +} + type Role struct { ID int64 `json:"id"` Name string `json:"name"` @@ -636,7 +655,6 @@ type User struct { LanguageGoal pgtype.Text `json:"language_goal"` LanguageChallange pgtype.Text `json:"language_challange"` FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` EmailVerified bool `json:"email_verified"` PhoneVerified bool `json:"phone_verified"` Status string `json:"status"` @@ -666,14 +684,6 @@ type UserAudioResponse struct { CreatedAt pgtype.Timestamptz `json:"created_at"` } -type UserInitialAssessmentProgress struct { - UserID int64 `json:"user_id"` - NextLevel string `json:"next_level"` - HighestPassedLevel pgtype.Text `json:"highest_passed_level"` - Completed bool `json:"completed"` - UpdatedAt pgtype.Timestamptz `json:"updated_at"` -} - type UserPracticeProgress struct { ID int64 `json:"id"` UserID int64 `json:"user_id"` diff --git a/gen/db/question_sets.sql.go b/gen/db/question_sets.sql.go index 285c0d5c..3cd5679a 100644 --- a/gen/db/question_sets.sql.go +++ b/gen/db/question_sets.sql.go @@ -132,79 +132,6 @@ func (q *Queries) DeleteQuestionSet(ctx context.Context, id int64) error { return err } -const GetInitialAssessmentSet = `-- name: GetInitialAssessmentSet :one -SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) = 'A1' -ORDER BY created_at DESC -LIMIT 1 -` - -func (q *Queries) GetInitialAssessmentSet(ctx context.Context) (QuestionSet, error) { - row := q.db.QueryRow(ctx, GetInitialAssessmentSet) - var i QuestionSet - err := row.Scan( - &i.ID, - &i.Title, - &i.Description, - &i.SetType, - &i.OwnerType, - &i.OwnerID, - &i.BannerImage, - &i.Persona, - &i.TimeLimitMinutes, - &i.PassingScore, - &i.ShuffleQuestions, - &i.Status, - &i.CreatedAt, - &i.UpdatedAt, - &i.DisplayOrder, - &i.IntroVideoUrl, - ) - return i, err -} - -const GetInitialAssessmentSetByLevel = `-- name: GetInitialAssessmentSetByLevel :one -SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) = $1::text -ORDER BY - CASE - WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0 - ELSE 1 - END, - created_at DESC -LIMIT 1 -` - -func (q *Queries) GetInitialAssessmentSetByLevel(ctx context.Context, level string) (QuestionSet, error) { - row := q.db.QueryRow(ctx, GetInitialAssessmentSetByLevel, level) - var i QuestionSet - err := row.Scan( - &i.ID, - &i.Title, - &i.Description, - &i.SetType, - &i.OwnerType, - &i.OwnerID, - &i.BannerImage, - &i.Persona, - &i.TimeLimitMinutes, - &i.PassingScore, - &i.ShuffleQuestions, - &i.Status, - &i.CreatedAt, - &i.UpdatedAt, - &i.DisplayOrder, - &i.IntroVideoUrl, - ) - return i, err -} - const GetPublishedQuestionSetsByOwner = `-- name: GetPublishedQuestionSetsByOwner :many SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url FROM question_sets @@ -466,35 +393,6 @@ func (q *Queries) GetUserPersonasByQuestionSetID(ctx context.Context, questionSe return items, nil } -const ListPublishedInitialAssessmentLevels = `-- name: ListPublishedInitialAssessmentLevels :many -SELECT DISTINCT UPPER(TRIM(description))::text AS level -FROM question_sets -WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2') -ORDER BY level -` - -func (q *Queries) ListPublishedInitialAssessmentLevels(ctx context.Context) ([]string, error) { - rows, err := q.db.Query(ctx, ListPublishedInitialAssessmentLevels) - if err != nil { - return nil, err - } - defer rows.Close() - var items []string - for rows.Next() { - var level string - if err := rows.Scan(&level); err != nil { - return nil, err - } - items = append(items, level) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const RemoveUserPersonaFromQuestionSet = `-- name: RemoveUserPersonaFromQuestionSet :exec DELETE FROM question_set_personas WHERE question_set_id = $1 diff --git a/gen/db/user.sql.go b/gen/db/user.sql.go index 55feec55..f13ab514 100644 --- a/gen/db/user.sql.go +++ b/gen/db/user.sql.go @@ -110,7 +110,7 @@ INSERT INTO users ( VALUES ( $1, $2, $3, $4, $5, $6, $7, $8 ) -RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified ` type CreateAppleUserParams struct { @@ -156,7 +156,6 @@ func (q *Queries) CreateAppleUser(ctx context.Context, arg CreateAppleUserParams &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -194,7 +193,7 @@ INSERT INTO users ( VALUES ( $1, $2, $3, $4, $5, $6, $7, true, $8 ) -RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified ` type CreateGoogleUserParams struct { @@ -240,7 +239,6 @@ func (q *Queries) CreateGoogleUser(ctx context.Context, arg CreateGoogleUserPara &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -285,7 +283,6 @@ INSERT INTO users ( language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -321,7 +318,6 @@ VALUES ( $22, $23, $24, - $25, CURRENT_TIMESTAMP ) RETURNING @@ -345,7 +341,6 @@ RETURNING language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -358,31 +353,30 @@ RETURNING ` type CreateUserParams struct { - FirstName pgtype.Text `json:"first_name"` - LastName pgtype.Text `json:"last_name"` - Gender pgtype.Text `json:"gender"` - BirthDay pgtype.Date `json:"birth_day"` - Email pgtype.Text `json:"email"` - PhoneNumber pgtype.Text `json:"phone_number"` - Role string `json:"role"` - Password []byte `json:"password"` - AgeGroup pgtype.Text `json:"age_group"` - EducationLevel pgtype.Text `json:"education_level"` - Country pgtype.Text `json:"country"` - Region pgtype.Text `json:"region"` - NickName pgtype.Text `json:"nick_name"` - Occupation pgtype.Text `json:"occupation"` - LearningGoal pgtype.Text `json:"learning_goal"` - LanguageGoal pgtype.Text `json:"language_goal"` - LanguageChallange pgtype.Text `json:"language_challange"` - FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` - EmailVerified bool `json:"email_verified"` - PhoneVerified bool `json:"phone_verified"` - Status string `json:"status"` - ProfileCompleted pgtype.Bool `json:"profile_completed"` - ProfilePictureUrl pgtype.Text `json:"profile_picture_url"` - PreferredLanguage pgtype.Text `json:"preferred_language"` + FirstName pgtype.Text `json:"first_name"` + LastName pgtype.Text `json:"last_name"` + Gender pgtype.Text `json:"gender"` + BirthDay pgtype.Date `json:"birth_day"` + Email pgtype.Text `json:"email"` + PhoneNumber pgtype.Text `json:"phone_number"` + Role string `json:"role"` + Password []byte `json:"password"` + AgeGroup pgtype.Text `json:"age_group"` + EducationLevel pgtype.Text `json:"education_level"` + Country pgtype.Text `json:"country"` + Region pgtype.Text `json:"region"` + NickName pgtype.Text `json:"nick_name"` + Occupation pgtype.Text `json:"occupation"` + LearningGoal pgtype.Text `json:"learning_goal"` + LanguageGoal pgtype.Text `json:"language_goal"` + LanguageChallange pgtype.Text `json:"language_challange"` + FavouriteTopic pgtype.Text `json:"favourite_topic"` + EmailVerified bool `json:"email_verified"` + PhoneVerified bool `json:"phone_verified"` + Status string `json:"status"` + ProfileCompleted pgtype.Bool `json:"profile_completed"` + ProfilePictureUrl pgtype.Text `json:"profile_picture_url"` + PreferredLanguage pgtype.Text `json:"preferred_language"` } type CreateUserRow struct { @@ -404,7 +398,6 @@ type CreateUserRow struct { LanguageGoal pgtype.Text `json:"language_goal"` LanguageChallange pgtype.Text `json:"language_challange"` FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` EmailVerified bool `json:"email_verified"` PhoneVerified bool `json:"phone_verified"` Status string `json:"status"` @@ -436,7 +429,6 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateU arg.LanguageGoal, arg.LanguageChallange, arg.FavouriteTopic, - arg.InitialAssessmentCompleted, arg.EmailVerified, arg.PhoneVerified, arg.Status, @@ -464,7 +456,6 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateU &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -510,7 +501,6 @@ SELECT language_goal, language_challange, favourite_topic, - initial_assessment_completed, email_verified, phone_verified, status, @@ -553,54 +543,53 @@ WHERE AND ($13::TEXT IS NULL OR LOWER(TRIM(COALESCE(learning_goal, ''))) = LOWER(TRIM($13::TEXT))) AND ($14::TEXT IS NULL OR LOWER(TRIM(COALESCE(knowledge_level, ''))) = LOWER(TRIM($14::TEXT))) AND ($15::BOOLEAN IS NULL OR profile_completed = $15::BOOLEAN) - AND ($16::BOOLEAN IS NULL OR initial_assessment_completed = $16::BOOLEAN) AND ( - $17::INT IS NULL - OR profile_completion_percentage >= $17::INT + $16::INT IS NULL + OR profile_completion_percentage >= $16::INT + ) + AND ($17::TIMESTAMPTZ IS NULL OR last_login >= $17::TIMESTAMPTZ) + AND ($18::TIMESTAMPTZ IS NULL OR last_login <= $18::TIMESTAMPTZ) + AND ( + $19::INT IS NULL + OR ( + last_login IS NOT NULL + AND last_login <= CURRENT_TIMESTAMP - ($19::INT || ' days')::INTERVAL + ) ) - AND ($18::TIMESTAMPTZ IS NULL OR last_login >= $18::TIMESTAMPTZ) - AND ($19::TIMESTAMPTZ IS NULL OR last_login <= $19::TIMESTAMPTZ) AND ( $20::INT IS NULL OR ( last_login IS NOT NULL - AND last_login <= CURRENT_TIMESTAMP - ($20::INT || ' days')::INTERVAL + AND last_login >= CURRENT_TIMESTAMP - ($20::INT || ' days')::INTERVAL ) ) AND ( $21::INT IS NULL OR ( - last_login IS NOT NULL - AND last_login >= CURRENT_TIMESTAMP - ($21::INT || ' days')::INTERVAL - ) + SELECT COUNT(*)::INT + FROM lms_user_lesson_progress ulp + WHERE ulp.user_id = users.id + ) >= $21::INT ) AND ( $22::INT IS NULL OR ( SELECT COUNT(*)::INT - FROM lms_user_lesson_progress ulp - WHERE ulp.user_id = users.id + FROM lms_user_module_progress ump + WHERE ump.user_id = users.id ) >= $22::INT ) AND ( - $23::INT IS NULL + $23::BOOLEAN IS NULL OR ( - SELECT COUNT(*)::INT - FROM lms_user_module_progress ump - WHERE ump.user_id = users.id - ) >= $23::INT - ) - AND ( - $24::BOOLEAN IS NULL - OR ( - $24::BOOLEAN = TRUE + $23::BOOLEAN = TRUE AND EXISTS ( SELECT 1 FROM payments p WHERE p.user_id = users.id AND p.status = 'SUCCESS' ) ) OR ( - $24::BOOLEAN = FALSE + $23::BOOLEAN = FALSE AND NOT EXISTS ( SELECT 1 FROM payments p WHERE p.user_id = users.id AND p.status = 'SUCCESS' @@ -608,27 +597,27 @@ WHERE ) ) AND ( - $25::BOOLEAN IS NULL + $24::BOOLEAN IS NULL OR EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP - AND us.auto_renew = $25::BOOLEAN + AND us.auto_renew = $24::BOOLEAN ) ) AND ( - $26::BIGINT IS NULL + $25::BIGINT IS NULL OR EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP - AND us.plan_id = $26::BIGINT + AND us.plan_id = $25::BIGINT ) ) AND ( - $27::TEXT IS NULL + $26::TEXT IS NULL OR EXISTS ( SELECT 1 FROM user_subscriptions us @@ -636,32 +625,32 @@ WHERE WHERE us.user_id = users.id AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP - AND UPPER(TRIM(sp.category)) = UPPER(TRIM($27::TEXT)) + AND UPPER(TRIM(sp.category)) = UPPER(TRIM($26::TEXT)) ) ) AND ( - $28::INT IS NULL + $27::INT IS NULL OR EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP - AND us.expires_at <= CURRENT_TIMESTAMP + ($28::INT || ' days')::INTERVAL + AND us.expires_at <= CURRENT_TIMESTAMP + ($27::INT || ' days')::INTERVAL ) ) AND ( - $29::TEXT IS NULL + $28::TEXT IS NULL OR EXISTS ( SELECT 1 FROM devices d WHERE d.user_id = users.id AND d.is_active = TRUE - AND LOWER(TRIM(COALESCE(d.platform, ''))) = LOWER(TRIM($29::TEXT)) + AND LOWER(TRIM(COALESCE(d.platform, ''))) = LOWER(TRIM($28::TEXT)) ) ) AND ( - $30::BOOLEAN IS NULL + $29::BOOLEAN IS NULL OR ( - $30::BOOLEAN = TRUE + $29::BOOLEAN = TRUE AND EXISTS ( SELECT 1 FROM devices d WHERE d.user_id = users.id @@ -670,7 +659,7 @@ WHERE ) ) OR ( - $30::BOOLEAN = FALSE + $29::BOOLEAN = FALSE AND NOT EXISTS ( SELECT 1 FROM devices d WHERE d.user_id = users.id @@ -680,9 +669,9 @@ WHERE ) ) AND ( - $31::TEXT IS NULL + $30::TEXT IS NULL OR ( - $31::TEXT = 'ACTIVE' + $30::TEXT = 'ACTIVE' AND EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id @@ -691,7 +680,7 @@ WHERE ) ) OR ( - $31::TEXT = 'PENDING' + $30::TEXT = 'PENDING' AND NOT EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id @@ -704,7 +693,7 @@ WHERE ) ) OR ( - $31::TEXT = 'Unsubscribed' + $30::TEXT = 'Unsubscribed' AND NOT EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id @@ -713,7 +702,7 @@ WHERE ) ) OR ( - $31::TEXT = 'EXPIRED' + $30::TEXT = 'EXPIRED' AND NOT EXISTS ( SELECT 1 FROM user_subscriptions us WHERE us.user_id = users.id @@ -736,44 +725,43 @@ WHERE ) ) ORDER BY created_at DESC -LIMIT $33::INT -OFFSET $32::INT +LIMIT $32::INT +OFFSET $31::INT ` type GetAllUsersParams struct { - Role pgtype.Text `json:"role"` - Status pgtype.Text `json:"status"` - Query pgtype.Text `json:"query"` - CreatedAfter pgtype.Timestamptz `json:"created_after"` - CreatedBefore pgtype.Timestamptz `json:"created_before"` - Country pgtype.Text `json:"country"` - Region pgtype.Text `json:"region"` - EducationLevel pgtype.Text `json:"education_level"` - Occupation pgtype.Text `json:"occupation"` - AgeGroup pgtype.Text `json:"age_group"` - FavouriteTopic pgtype.Text `json:"favourite_topic"` - LanguageGoal pgtype.Text `json:"language_goal"` - LearningGoal pgtype.Text `json:"learning_goal"` - KnowledgeLevel pgtype.Text `json:"knowledge_level"` - ProfileCompleted pgtype.Bool `json:"profile_completed"` - InitialAssessmentCompleted pgtype.Bool `json:"initial_assessment_completed"` - MinProfileCompletionPct pgtype.Int4 `json:"min_profile_completion_pct"` - LastLoginAfter pgtype.Timestamptz `json:"last_login_after"` - LastLoginBefore pgtype.Timestamptz `json:"last_login_before"` - DaysSinceLastLoginMin pgtype.Int4 `json:"days_since_last_login_min"` - DaysSinceLastLoginMax pgtype.Int4 `json:"days_since_last_login_max"` - MinLessonsCompleted pgtype.Int4 `json:"min_lessons_completed"` - MinModulesCompleted pgtype.Int4 `json:"min_modules_completed"` - HasEverPaid pgtype.Bool `json:"has_ever_paid"` - AutoRenew pgtype.Bool `json:"auto_renew"` - PlanID pgtype.Int8 `json:"plan_id"` - PlanCategory pgtype.Text `json:"plan_category"` - ExpiresWithinDays pgtype.Int4 `json:"expires_within_days"` - DevicePlatform pgtype.Text `json:"device_platform"` - HasActiveDevice pgtype.Bool `json:"has_active_device"` - SubscriptionStatus pgtype.Text `json:"subscription_status"` - Offset pgtype.Int4 `json:"offset"` - Limit pgtype.Int4 `json:"limit"` + Role pgtype.Text `json:"role"` + Status pgtype.Text `json:"status"` + Query pgtype.Text `json:"query"` + CreatedAfter pgtype.Timestamptz `json:"created_after"` + CreatedBefore pgtype.Timestamptz `json:"created_before"` + Country pgtype.Text `json:"country"` + Region pgtype.Text `json:"region"` + EducationLevel pgtype.Text `json:"education_level"` + Occupation pgtype.Text `json:"occupation"` + AgeGroup pgtype.Text `json:"age_group"` + FavouriteTopic pgtype.Text `json:"favourite_topic"` + LanguageGoal pgtype.Text `json:"language_goal"` + LearningGoal pgtype.Text `json:"learning_goal"` + KnowledgeLevel pgtype.Text `json:"knowledge_level"` + ProfileCompleted pgtype.Bool `json:"profile_completed"` + MinProfileCompletionPct pgtype.Int4 `json:"min_profile_completion_pct"` + LastLoginAfter pgtype.Timestamptz `json:"last_login_after"` + LastLoginBefore pgtype.Timestamptz `json:"last_login_before"` + DaysSinceLastLoginMin pgtype.Int4 `json:"days_since_last_login_min"` + DaysSinceLastLoginMax pgtype.Int4 `json:"days_since_last_login_max"` + MinLessonsCompleted pgtype.Int4 `json:"min_lessons_completed"` + MinModulesCompleted pgtype.Int4 `json:"min_modules_completed"` + HasEverPaid pgtype.Bool `json:"has_ever_paid"` + AutoRenew pgtype.Bool `json:"auto_renew"` + PlanID pgtype.Int8 `json:"plan_id"` + PlanCategory pgtype.Text `json:"plan_category"` + ExpiresWithinDays pgtype.Int4 `json:"expires_within_days"` + DevicePlatform pgtype.Text `json:"device_platform"` + HasActiveDevice pgtype.Bool `json:"has_active_device"` + SubscriptionStatus pgtype.Text `json:"subscription_status"` + Offset pgtype.Int4 `json:"offset"` + Limit pgtype.Int4 `json:"limit"` } type GetAllUsersRow struct { @@ -797,7 +785,6 @@ type GetAllUsersRow struct { LanguageGoal pgtype.Text `json:"language_goal"` LanguageChallange pgtype.Text `json:"language_challange"` FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` EmailVerified bool `json:"email_verified"` PhoneVerified bool `json:"phone_verified"` Status string `json:"status"` @@ -827,7 +814,6 @@ func (q *Queries) GetAllUsers(ctx context.Context, arg GetAllUsersParams) ([]Get arg.LearningGoal, arg.KnowledgeLevel, arg.ProfileCompleted, - arg.InitialAssessmentCompleted, arg.MinProfileCompletionPct, arg.LastLoginAfter, arg.LastLoginBefore, @@ -874,7 +860,6 @@ func (q *Queries) GetAllUsers(ctx context.Context, arg GetAllUsersParams) ([]Get &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -931,7 +916,7 @@ func (q *Queries) GetTotalUsers(ctx context.Context, role string) (int64, error) } const GetUserByAppleID = `-- name: GetUserByAppleID :one -SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified FROM users WHERE apple_id = $1 ` @@ -959,7 +944,6 @@ func (q *Queries) GetUserByAppleID(ctx context.Context, appleID pgtype.Text) (Us &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -1140,7 +1124,7 @@ func (q *Queries) GetUserByEmailPhone(ctx context.Context, arg GetUserByEmailPho } const GetUserByGoogleID = `-- name: GetUserByGoogleID :one -SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified FROM users WHERE google_id = $1 ` @@ -1168,7 +1152,6 @@ func (q *Queries) GetUserByGoogleID(ctx context.Context, googleID pgtype.Text) ( &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -1192,7 +1175,7 @@ func (q *Queries) GetUserByGoogleID(ctx context.Context, googleID pgtype.Text) ( } const GetUserByID = `-- name: GetUserByID :one -SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified FROM users WHERE id = $1 ` @@ -1220,7 +1203,6 @@ func (q *Queries) GetUserByID(ctx context.Context, id int64) (User, error) { &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -1278,7 +1260,7 @@ func (q *Queries) GetUserSummary(ctx context.Context) (GetUserSummaryRow, error) } const GetUsersByIDs = `-- name: GetUsersByIDs :many -SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified +SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified FROM users WHERE id = ANY($1::BIGINT[]) ` @@ -1312,7 +1294,6 @@ func (q *Queries) GetUsersByIDs(ctx context.Context, dollar_1 []int64) ([]User, &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.EmailVerified, &i.PhoneVerified, &i.Status, @@ -1432,7 +1413,6 @@ SELECT language_challange, favourite_topic, - initial_assessment_completed, profile_picture_url, preferred_language, email_verified, @@ -1479,7 +1459,6 @@ type SearchUserByNameOrPhoneRow struct { LanguageGoal pgtype.Text `json:"language_goal"` LanguageChallange pgtype.Text `json:"language_challange"` FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` ProfilePictureUrl pgtype.Text `json:"profile_picture_url"` PreferredLanguage pgtype.Text `json:"preferred_language"` EmailVerified bool `json:"email_verified"` @@ -1519,7 +1498,6 @@ func (q *Queries) SearchUserByNameOrPhone(ctx context.Context, arg SearchUserByN &i.LanguageGoal, &i.LanguageChallange, &i.FavouriteTopic, - &i.InitialAssessmentCompleted, &i.ProfilePictureUrl, &i.PreferredLanguage, &i.EmailVerified, @@ -1574,35 +1552,33 @@ SET language_goal = COALESCE($11, language_goal), language_challange = COALESCE($12, language_challange), favourite_topic = COALESCE($13, favourite_topic), - initial_assessment_completed = COALESCE($14, initial_assessment_completed), - profile_picture_url = COALESCE($15, profile_picture_url), - preferred_language = COALESCE($16, preferred_language), - gender = COALESCE($17, gender), - birth_day = COALESCE($18, birth_day), + profile_picture_url = COALESCE($14, profile_picture_url), + preferred_language = COALESCE($15, preferred_language), + gender = COALESCE($16, gender), + birth_day = COALESCE($17, birth_day), updated_at = CURRENT_TIMESTAMP -WHERE id = $19 +WHERE id = $18 ` type UpdateUserParams struct { - FirstName pgtype.Text `json:"first_name"` - LastName pgtype.Text `json:"last_name"` - KnowledgeLevel pgtype.Text `json:"knowledge_level"` - AgeGroup pgtype.Text `json:"age_group"` - EducationLevel pgtype.Text `json:"education_level"` - Country pgtype.Text `json:"country"` - Region pgtype.Text `json:"region"` - NickName pgtype.Text `json:"nick_name"` - Occupation pgtype.Text `json:"occupation"` - LearningGoal pgtype.Text `json:"learning_goal"` - LanguageGoal pgtype.Text `json:"language_goal"` - LanguageChallange pgtype.Text `json:"language_challange"` - FavouriteTopic pgtype.Text `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` - ProfilePictureUrl pgtype.Text `json:"profile_picture_url"` - PreferredLanguage pgtype.Text `json:"preferred_language"` - Gender pgtype.Text `json:"gender"` - BirthDay pgtype.Date `json:"birth_day"` - ID int64 `json:"id"` + FirstName pgtype.Text `json:"first_name"` + LastName pgtype.Text `json:"last_name"` + KnowledgeLevel pgtype.Text `json:"knowledge_level"` + AgeGroup pgtype.Text `json:"age_group"` + EducationLevel pgtype.Text `json:"education_level"` + Country pgtype.Text `json:"country"` + Region pgtype.Text `json:"region"` + NickName pgtype.Text `json:"nick_name"` + Occupation pgtype.Text `json:"occupation"` + LearningGoal pgtype.Text `json:"learning_goal"` + LanguageGoal pgtype.Text `json:"language_goal"` + LanguageChallange pgtype.Text `json:"language_challange"` + FavouriteTopic pgtype.Text `json:"favourite_topic"` + ProfilePictureUrl pgtype.Text `json:"profile_picture_url"` + PreferredLanguage pgtype.Text `json:"preferred_language"` + Gender pgtype.Text `json:"gender"` + BirthDay pgtype.Date `json:"birth_day"` + ID int64 `json:"id"` } // Note: profile_completed and profile_completion_percentage are computed by database trigger @@ -1621,7 +1597,6 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) error { arg.LanguageGoal, arg.LanguageChallange, arg.FavouriteTopic, - arg.InitialAssessmentCompleted, arg.ProfilePictureUrl, arg.PreferredLanguage, arg.Gender, diff --git a/internal/domain/initial_assessment.go b/internal/domain/initial_assessment.go deleted file mode 100644 index a7301641..00000000 --- a/internal/domain/initial_assessment.go +++ /dev/null @@ -1,449 +0,0 @@ -package domain - -import ( - "fmt" - "sort" - "strings" -) - -// CEFR placement levels returned by the initial assessment. -var InitialAssessmentCEFRLevels = []string{"A1", "A2", "B1", "B2", "C1", "C2"} - -// DefaultInitialAssessmentThresholds are seeded when the table is empty / on first install. -// min_percent is the pass mark for that CEFR level's question set (progressive placement). -func DefaultInitialAssessmentThresholds() []InitialAssessmentLevelThreshold { - return []InitialAssessmentLevelThreshold{ - {Level: "A1", MinPercent: 70, DisplayOrder: 1}, - {Level: "A2", MinPercent: 70, DisplayOrder: 2}, - {Level: "B1", MinPercent: 70, DisplayOrder: 3}, - {Level: "B2", MinPercent: 70, DisplayOrder: 4}, - {Level: "C1", MinPercent: 70, DisplayOrder: 5}, - {Level: "C2", MinPercent: 70, DisplayOrder: 6}, - } -} - -type InitialAssessmentLevelThreshold struct { - Level string `json:"level"` - MinPercent int `json:"min_percent"` - DisplayOrder int `json:"display_order"` -} - -type PlacementAnswerInput struct { - QuestionID int64 `json:"question_id"` - SelectedOptionIDs []int64 `json:"selected_option_ids,omitempty"` - TextAnswer *string `json:"text_answer,omitempty"` - DynamicAnswers []PlacementDynamicAnswerInput `json:"dynamic_answers,omitempty"` -} - -type PlacementDynamicAnswerInput struct { - ElementID string `json:"element_id"` - SelectedOptionIDs []string `json:"selected_option_ids,omitempty"` - TextAnswer *string `json:"text_answer,omitempty"` -} - -type PlacementQuestionResult struct { - QuestionID int64 `json:"question_id"` - QuestionType string `json:"question_type"` - Gradable bool `json:"gradable"` - Correct bool `json:"correct"` - PointsEarned int32 `json:"points_earned"` - PointsMax int32 `json:"points_max"` - Skipped bool `json:"skipped"` -} - -type PlacementAssessmentResult struct { - QuestionSetID int64 `json:"question_set_id"` - LevelAttempted string `json:"level_attempted"` - ScorePercent float64 `json:"score_percent"` - Passed bool `json:"passed"` - PassPercent int `json:"pass_percent"` - NextLevel *string `json:"next_level,omitempty"` - Completed bool `json:"completed"` - Level string `json:"level"` // final knowledge level when completed; else last passed / attempted context - PointsEarned int32 `json:"points_earned"` - PointsMax int32 `json:"points_max"` - GradableQuestions int `json:"gradable_questions"` - CorrectQuestions int `json:"correct_questions"` - SkippedUngradableQuestions int `json:"skipped_ungradable_questions"` - Questions []PlacementQuestionResult `json:"questions"` - KnowledgeLevel string `json:"knowledge_level,omitempty"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` -} - -// PlacementSession is the learner's progressive placement state. -type PlacementSession struct { - NextLevel string `json:"next_level,omitempty"` - HighestPassedLevel *string `json:"highest_passed_level,omitempty"` - Completed bool `json:"completed"` - KnowledgeLevel string `json:"knowledge_level,omitempty"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` - PublishedLevels []string `json:"published_levels"` -} - -// UserInitialAssessmentProgress persists in-progress progressive placement. -type UserInitialAssessmentProgress struct { - UserID int64 - NextLevel string - HighestPassedLevel *string - Completed bool -} - -func NormalizeCEFRLevel(level string) (string, error) { - normalized := strings.ToUpper(strings.TrimSpace(level)) - for _, allowed := range InitialAssessmentCEFRLevels { - if normalized == allowed { - return normalized, nil - } - } - return "", fmt.Errorf("level must be one of: %s", strings.Join(InitialAssessmentCEFRLevels, ", ")) -} - -// NextCEFRLevel returns the following CEFR band, or "" after C2. -func NextCEFRLevel(level string) string { - normalized, err := NormalizeCEFRLevel(level) - if err != nil { - return "" - } - for i, l := range InitialAssessmentCEFRLevels { - if l == normalized { - if i+1 < len(InitialAssessmentCEFRLevels) { - return InitialAssessmentCEFRLevels[i+1] - } - return "" - } - } - return "" -} - -// ValidateInitialAssessmentThresholds ensures every CEFR level is present once -// with a pass mark between 0 and 100. -func ValidateInitialAssessmentThresholds(rows []InitialAssessmentLevelThreshold) error { - if len(rows) != len(InitialAssessmentCEFRLevels) { - return fmt.Errorf("expected exactly %d thresholds (A1–C2)", len(InitialAssessmentCEFRLevels)) - } - - byLevel := make(map[string]InitialAssessmentLevelThreshold, len(rows)) - for _, row := range rows { - level, err := NormalizeCEFRLevel(row.Level) - if err != nil { - return err - } - if _, exists := byLevel[level]; exists { - return fmt.Errorf("duplicate threshold for level %s", level) - } - if row.MinPercent < 0 || row.MinPercent > 100 { - return fmt.Errorf("min_percent for %s must be between 0 and 100", level) - } - byLevel[level] = InitialAssessmentLevelThreshold{ - Level: level, - MinPercent: row.MinPercent, - DisplayOrder: row.DisplayOrder, - } - } - - for _, level := range InitialAssessmentCEFRLevels { - if _, ok := byLevel[level]; !ok { - return fmt.Errorf("missing threshold for level %s", level) - } - } - return nil -} - -// PassPercentForLevel returns the configured pass mark for a CEFR level set. -func PassPercentForLevel(level string, thresholds []InitialAssessmentLevelThreshold) (int, error) { - normalized, err := NormalizeCEFRLevel(level) - if err != nil { - return 0, err - } - if len(thresholds) == 0 { - thresholds = DefaultInitialAssessmentThresholds() - } - thresholds = mergeThresholdDefaults(thresholds) - for _, row := range thresholds { - if row.Level == normalized { - return row.MinPercent, nil - } - } - return 0, fmt.Errorf("missing threshold for level %s", normalized) -} - -// ResolveCEFRLevelFromScore is retained for legacy single-test banding. -// Progressive placement uses PassPercentForLevel instead. -func ResolveCEFRLevelFromScore(scorePercent float64, thresholds []InitialAssessmentLevelThreshold) (string, error) { - if len(thresholds) == 0 { - thresholds = DefaultInitialAssessmentThresholds() - } - if err := ValidateInitialAssessmentThresholds(thresholds); err != nil { - thresholds = mergeThresholdDefaults(thresholds) - if err := ValidateInitialAssessmentThresholds(thresholds); err != nil { - return "", err - } - } - - sorted := append([]InitialAssessmentLevelThreshold(nil), thresholds...) - sort.Slice(sorted, func(i, j int) bool { - return sorted[i].MinPercent < sorted[j].MinPercent - }) - - level := sorted[0].Level - for _, row := range sorted { - if scorePercent+1e-9 >= float64(row.MinPercent) { - level = row.Level - } - } - return level, nil -} - -func mergeThresholdDefaults(rows []InitialAssessmentLevelThreshold) []InitialAssessmentLevelThreshold { - byLevel := make(map[string]InitialAssessmentLevelThreshold) - for _, d := range DefaultInitialAssessmentThresholds() { - byLevel[d.Level] = d - } - for _, row := range rows { - level, err := NormalizeCEFRLevel(row.Level) - if err != nil { - continue - } - row.Level = level - byLevel[level] = row - } - out := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels)) - for i, level := range InitialAssessmentCEFRLevels { - row := byLevel[level] - if row.DisplayOrder <= 0 { - row.DisplayOrder = i + 1 - } - out = append(out, row) - } - return out -} - -// GradePlacementAnswers scores published placement questions against submitted answers. -// Auto-gradable: MCQ, TRUE_FALSE, SHORT_ANSWER, and DYNAMIC multiple-choice / option slots. -// AUDIO and other dynamic kinds are skipped (not counted in score denominator). -func GradePlacementAnswers( - questions []QuestionWithDetails, - answers []PlacementAnswerInput, -) PlacementAssessmentResult { - byID := make(map[int64]PlacementAnswerInput, len(answers)) - for _, a := range answers { - byID[a.QuestionID] = a - } - - result := PlacementAssessmentResult{ - Questions: make([]PlacementQuestionResult, 0, len(questions)), - } - - for _, q := range questions { - points := q.Points - if points <= 0 { - points = 1 - } - qr := PlacementQuestionResult{ - QuestionID: q.ID, - QuestionType: q.QuestionType, - PointsMax: points, - } - ans, answered := byID[q.ID] - - gradable, correct := gradeOnePlacementQuestion(q, ans, answered) - qr.Gradable = gradable - if !gradable { - qr.Skipped = true - result.SkippedUngradableQuestions++ - result.Questions = append(result.Questions, qr) - continue - } - - result.GradableQuestions++ - result.PointsMax += points - qr.Correct = correct - if correct { - qr.PointsEarned = points - result.PointsEarned += points - result.CorrectQuestions++ - } - if !answered { - qr.Skipped = true - } - result.Questions = append(result.Questions, qr) - } - - if result.PointsMax > 0 { - result.ScorePercent = (float64(result.PointsEarned) / float64(result.PointsMax)) * 100 - } - return result -} - -func gradeOnePlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) { - qType := strings.ToUpper(strings.TrimSpace(q.QuestionType)) - switch qType { - case "MCQ", "TRUE_FALSE": - return true, answered && gradeSelectedOptionIDs(q.Options, ans.SelectedOptionIDs) - case "SHORT_ANSWER": - text := "" - if ans.TextAnswer != nil { - text = *ans.TextAnswer - } - return true, answered && gradeShortAnswer(q.ShortAnswers, text) - case "DYNAMIC": - return gradeDynamicPlacementQuestion(q, ans, answered) - default: - // AUDIO and unknown types are not auto-graded in v1. - return false, false - } -} - -func gradeSelectedOptionIDs(options []QuestionOption, selected []int64) bool { - correctIDs := make(map[int64]struct{}) - for _, opt := range options { - if opt.IsCorrect { - correctIDs[opt.ID] = struct{}{} - } - } - if len(correctIDs) == 0 { - return false - } - if len(selected) != len(correctIDs) { - return false - } - seen := make(map[int64]struct{}, len(selected)) - for _, id := range selected { - if _, ok := correctIDs[id]; !ok { - return false - } - seen[id] = struct{}{} - } - return len(seen) == len(correctIDs) -} - -func gradeShortAnswer(acceptable []QuestionShortAnswer, given string) bool { - given = strings.TrimSpace(given) - if given == "" || len(acceptable) == 0 { - return false - } - for _, sa := range acceptable { - want := strings.TrimSpace(sa.AcceptableAnswer) - match := strings.ToUpper(strings.TrimSpace(sa.MatchType)) - switch match { - case string(MatchTypeContains): - if strings.Contains(strings.ToLower(given), strings.ToLower(want)) { - return true - } - case string(MatchTypeCaseInsensitive), "": - if strings.EqualFold(given, want) { - return true - } - default: // EXACT - if given == want { - return true - } - } - } - return false -} - -func gradeDynamicPlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) { - if q.DynamicPayload == nil { - return false, false - } - - type slotSpec struct { - kind string - correct []string - short []string - match string - } - - slots := make(map[string]slotSpec) - collect := func(els []DynamicElementInstance) { - for _, el := range els { - id := strings.TrimSpace(el.ID) - kind := strings.TrimSpace(el.Kind) - if id == "" { - continue - } - if isMultipleChoiceComponentKind(kind) { - correctOpts := extractCorrectDynamicOptionIDs(el.Value) - if len(correctOpts) == 0 { - continue - } - slots[id] = slotSpec{kind: kind, correct: correctOpts} - } - } - } - collect(q.DynamicPayload.Stimulus) - collect(q.DynamicPayload.Response) - - if len(slots) == 0 { - return false, false - } - - if !answered { - return true, false - } - - byElement := make(map[string]PlacementDynamicAnswerInput, len(ans.DynamicAnswers)) - for _, da := range ans.DynamicAnswers { - byElement[strings.TrimSpace(da.ElementID)] = da - } - - for id, spec := range slots { - da, ok := byElement[id] - if !ok { - return true, false - } - if isMultipleChoiceComponentKind(spec.kind) { - if !sameStringSet(spec.correct, da.SelectedOptionIDs) { - return true, false - } - } - } - return true, true -} - -func extractCorrectDynamicOptionIDs(value interface{}) []string { - m, ok := value.(map[string]interface{}) - if !ok { - return nil - } - rawOpts, ok := m["options"].([]interface{}) - if !ok { - return nil - } - var out []string - for _, o := range rawOpts { - om, ok := o.(map[string]interface{}) - if !ok { - continue - } - if c, _ := om["is_correct"].(bool); !c { - continue - } - id, _ := om["id"].(string) - id = strings.TrimSpace(id) - if id != "" { - out = append(out, id) - } - } - return out -} - -func sameStringSet(want, got []string) bool { - if len(want) != len(got) { - return false - } - set := make(map[string]struct{}, len(want)) - for _, w := range want { - set[strings.TrimSpace(w)] = struct{}{} - } - if len(set) != len(want) { - return false - } - for _, g := range got { - if _, ok := set[strings.TrimSpace(g)]; !ok { - return false - } - } - return true -} diff --git a/internal/domain/initial_assessment_test.go b/internal/domain/initial_assessment_test.go deleted file mode 100644 index d458db49..00000000 --- a/internal/domain/initial_assessment_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package domain - -import "testing" - -func TestPassPercentForLevel(t *testing.T) { - thresholds := DefaultInitialAssessmentThresholds() - got, err := PassPercentForLevel("B1", thresholds) - if err != nil { - t.Fatal(err) - } - if got != 70 { - t.Fatalf("got %d want 70", got) - } -} - -func TestValidateInitialAssessmentThresholds_allowsEqualPassMarks(t *testing.T) { - rows := DefaultInitialAssessmentThresholds() - if err := ValidateInitialAssessmentThresholds(rows); err != nil { - t.Fatal(err) - } -} - -func TestValidateInitialAssessmentThresholds_rejectsOutOfRange(t *testing.T) { - rows := DefaultInitialAssessmentThresholds() - rows[2].MinPercent = 101 - if err := ValidateInitialAssessmentThresholds(rows); err == nil { - t.Fatal("expected validation error") - } -} - -func TestNextCEFRLevel(t *testing.T) { - if got := NextCEFRLevel("A1"); got != "A2" { - t.Fatalf("got %s want A2", got) - } - if got := NextCEFRLevel("C2"); got != "" { - t.Fatalf("got %q want empty", got) - } -} - -func TestGradePlacementAnswers_mcqAndShort(t *testing.T) { - questions := []QuestionWithDetails{ - { - Question: Question{ID: 1, QuestionType: "MCQ", Points: 2}, - Options: []QuestionOption{ - {ID: 10, IsCorrect: true}, - {ID: 11, IsCorrect: false}, - }, - }, - { - Question: Question{ID: 2, QuestionType: "SHORT_ANSWER", Points: 1}, - ShortAnswers: []QuestionShortAnswer{ - {AcceptableAnswer: "hello", MatchType: "CASE_INSENSITIVE"}, - }, - }, - { - Question: Question{ID: 3, QuestionType: "AUDIO", Points: 5}, - }, - } - answers := []PlacementAnswerInput{ - {QuestionID: 1, SelectedOptionIDs: []int64{10}}, - {QuestionID: 2, TextAnswer: stringPtr("Hello")}, - } - got := GradePlacementAnswers(questions, answers) - if got.PointsMax != 3 { - t.Fatalf("points max=%d want 3", got.PointsMax) - } - if got.PointsEarned != 3 { - t.Fatalf("points earned=%d want 3", got.PointsEarned) - } - if got.SkippedUngradableQuestions != 1 { - t.Fatalf("skipped=%d want 1", got.SkippedUngradableQuestions) - } - if got.ScorePercent != 100 { - t.Fatalf("score=%v want 100", got.ScorePercent) - } -} - -func stringPtr(s string) *string { return &s } diff --git a/internal/domain/program.go b/internal/domain/program.go index e5b076f6..a9912140 100644 --- a/internal/domain/program.go +++ b/internal/domain/program.go @@ -4,18 +4,18 @@ import "time" // Program is the top-level container in the LMS hierarchy (e.g. tracks like Beginner / Intermediate / Advanced). type Program struct { - ID int64 `json:"id"` - Name string `json:"name"` - Description *string `json:"description,omitempty"` - Category string `json:"category"` - Thumbnail *string `json:"thumbnail,omitempty"` - SortOrder int `json:"sort_order"` + ID int64 `json:"id"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + Category string `json:"category"` + Thumbnail *string `json:"thumbnail,omitempty"` + SortOrder int `json:"sort_order"` PublishStatus ContentPublishStatus `json:"publish_status"` AccessTier ContentAccessTier `json:"access_tier"` EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"` CreatedAt time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Access *LMSEntityAccess `json:"access,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Access *LMSEntityAccess `json:"access,omitempty"` } // VisibleToLearners is true when the program appears in subscriber/catalog LMS APIs. @@ -26,7 +26,7 @@ func (p Program) VisibleToLearners() bool { type CreateProgramInput struct { Name string `json:"name" validate:"required"` Description *string `json:"description,omitempty"` - Category string `json:"category" validate:"required,oneof=LEARN_ENGLISH"` + Category string `json:"category" validate:"required,oneof=EDUCATION"` Thumbnail *string `json:"thumbnail,omitempty"` // SortOrder inserts at this global program order when set; omit to append after current max (sort_order uniqueness is enforced). SortOrder *int `json:"sort_order,omitempty" validate:"omitempty,min=0"` @@ -38,7 +38,7 @@ type CreateProgramInput struct { type UpdateProgramInput struct { Name *string `json:"name,omitempty"` Description *string `json:"description,omitempty"` - Category *string `json:"category,omitempty" validate:"omitempty,oneof=LEARN_ENGLISH"` + Category *string `json:"category,omitempty" validate:"omitempty,oneof=EDUCATION"` Thumbnail *string `json:"thumbnail,omitempty"` SortOrder *int `json:"sort_order,omitempty"` PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"` diff --git a/internal/domain/questions.go b/internal/domain/questions.go index 10c626a9..da013bc4 100644 --- a/internal/domain/questions.go +++ b/internal/domain/questions.go @@ -22,12 +22,11 @@ const ( type QuestionSetType string const ( - QuestionSetTypePractice QuestionSetType = "PRACTICE" - QuestionSetTypeInitialAssessment QuestionSetType = "INITIAL_ASSESSMENT" - QuestionSetTypeQuiz QuestionSetType = "QUIZ" - QuestionSetTypeExam QuestionSetType = "EXAM" - QuestionSetTypeSurvey QuestionSetType = "SURVEY" - QuestionSetTypeCapstone QuestionSetType = "CAPSTONE" + QuestionSetTypePractice QuestionSetType = "PRACTICE" + QuestionSetTypeQuiz QuestionSetType = "QUIZ" + QuestionSetTypeExam QuestionSetType = "EXAM" + QuestionSetTypeSurvey QuestionSetType = "SURVEY" + QuestionSetTypeCapstone QuestionSetType = "CAPSTONE" ) type PracticeAccessBlock struct { @@ -139,9 +138,9 @@ type QuestionSetQuestionTypeCount struct { // QuestionSetQuestionTypesSummary summarizes distinct question types in a question set (e.g. linked practice). type QuestionSetQuestionTypesSummary struct { - QuestionSetID int64 `json:"question_set_id"` + QuestionSetID int64 `json:"question_set_id"` QuestionTypes []QuestionSetQuestionTypeCount `json:"question_types"` - TotalQuestions int64 `json:"total_questions"` + TotalQuestions int64 `json:"total_questions"` } type QuestionSetItemWithQuestion struct { diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index 64537630..2b05db93 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -16,6 +16,8 @@ var ( type SubscriptionCategory string const ( + SubscriptionCategoryEducation SubscriptionCategory = "EDUCATION" + // SubscriptionCategoryLearnEnglish remains for historical plan and subscription records. SubscriptionCategoryLearnEnglish SubscriptionCategory = "LEARN_ENGLISH" SubscriptionCategoryIELTS SubscriptionCategory = "IELTS" SubscriptionCategoryDuolingo SubscriptionCategory = "DUOLINGO" @@ -37,9 +39,7 @@ var ExamPrepSubscriptionGateDisabled = true // IsValidSubscriptionCategory reports whether category is a known plan category. func IsValidSubscriptionCategory(category string) bool { switch normalizeSubscriptionCategory(category) { - case string(SubscriptionCategoryLearnEnglish), - string(SubscriptionCategoryIELTS), - string(SubscriptionCategoryDuolingo): + case string(SubscriptionCategoryEducation): return true default: return false @@ -48,7 +48,8 @@ func IsValidSubscriptionCategory(category string) bool { // IsLMSSubscriptionCategory reports plan categories that unlock Learn English (LMS) content. func IsLMSSubscriptionCategory(category string) bool { - return normalizeSubscriptionCategory(category) == string(SubscriptionCategoryLearnEnglish) + normalized := normalizeSubscriptionCategory(category) + return normalized == string(SubscriptionCategoryEducation) || normalized == string(SubscriptionCategoryLearnEnglish) } // IsExamPrepSubscriptionCategory reports plan categories that unlock exam-prep content. @@ -76,7 +77,7 @@ func SubscriptionGrantsContentAccess(subscriptionCategory, contentCategory strin sub := normalizeSubscriptionCategory(subscriptionCategory) content := normalizeSubscriptionCategory(contentCategory) if IsLMSContentCategory(content) { - return sub == string(SubscriptionCategoryLearnEnglish) + return IsLMSSubscriptionCategory(sub) } if IsExamPrepContentCategory(content) { return sub == content diff --git a/internal/domain/user.go b/internal/domain/user.go index 22d5e6ab..f230369a 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -76,14 +76,13 @@ type User struct { Region string // Profile fields - KnowledgeLevel string - InitialAssessmentCompleted bool - NickName string - Occupation string - LearningGoal string - LanguageGoal string - LanguageChallange string - FavouriteTopic string + KnowledgeLevel string + NickName string + Occupation string + LearningGoal string + LanguageGoal string + LanguageChallange string + FavouriteTopic string EmailVerified bool PhoneVerified bool @@ -116,13 +115,12 @@ type UserProfileResponse struct { Region string `json:"region,omitempty"` // Profile fields - InitialAssessmentCompleted bool `json:"initial_assessment_completed,omitempty"` - NickName string `json:"nick_name,omitempty"` - Occupation string `json:"occupation,omitempty"` - LearningGoal string `json:"learning_goal,omitempty"` - LanguageGoal string `json:"language_goal,omitempty"` - LanguageChallange string `json:"language_challange,omitempty"` - FavouriteTopic string `json:"favoutite_topic,omitempty"` + NickName string `json:"nick_name,omitempty"` + Occupation string `json:"occupation,omitempty"` + LearningGoal string `json:"learning_goal,omitempty"` + LanguageGoal string `json:"language_goal,omitempty"` + LanguageChallange string `json:"language_challange,omitempty"` + FavouriteTopic string `json:"favoutite_topic,omitempty"` EmailVerified bool `json:"email_verified"` PhoneVerified bool `json:"phone_verified"` @@ -183,15 +181,14 @@ type UserFilter struct { ExpiresWithinDays *int32 // Engagement / activity - LastLoginBefore ValidTime - LastLoginAfter ValidTime - DaysSinceLastLoginMin *int32 - DaysSinceLastLoginMax *int32 - ProfileCompleted *bool - InitialAssessmentCompleted *bool - MinLessonsCompleted *int32 - MinModulesCompleted *int32 - MinProfileCompletionPct *int32 + LastLoginBefore ValidTime + LastLoginAfter ValidTime + DaysSinceLastLoginMin *int32 + DaysSinceLastLoginMax *int32 + ProfileCompleted *bool + MinLessonsCompleted *int32 + MinModulesCompleted *int32 + MinProfileCompletionPct *int32 // Technical / deliverability (device table only; push permission, timezone, app version not stored) DevicePlatform string @@ -318,8 +315,6 @@ type UpdateUserReq struct { LanguageChallange string `json:"language_challange"` FavouriteTopic string `json:"favourite_topic"` - InitialAssessmentCompleted bool `json:"initial_assessment_completed"` - ProfilePictureURL string `json:"profile_picture_url"` PreferredLanguage string `json:"preferred_language"` } diff --git a/internal/ports/initial_assessment.go b/internal/ports/initial_assessment.go deleted file mode 100644 index 60050a43..00000000 --- a/internal/ports/initial_assessment.go +++ /dev/null @@ -1,6 +0,0 @@ -package ports - -// InitialAssessmentStore is now a marker interface. -// The initial assessment functionality uses the unified questions system. -// Use QuestionStore.GetInitialAssessmentSet() to get the initial assessment question set. -type InitialAssessmentStore interface{} diff --git a/internal/ports/questions.go b/internal/ports/questions.go index 27f7d907..a5a9086b 100644 --- a/internal/ports/questions.go +++ b/internal/ports/questions.go @@ -52,14 +52,6 @@ type QuestionStore interface { GetQuestionSetsByOwner(ctx context.Context, ownerType string, ownerID int64) ([]domain.QuestionSet, error) GetQuestionSetsByType(ctx context.Context, setType string, limit, offset int32) ([]domain.QuestionSet, int64, error) GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType string, ownerID int64) ([]domain.QuestionSet, error) - GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet, error) - GetInitialAssessmentSetByLevel(ctx context.Context, level string) (domain.QuestionSet, error) - ListPublishedInitialAssessmentLevels(ctx context.Context) ([]string, error) - ListInitialAssessmentLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error) - ReplaceInitialAssessmentLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) error - GetUserInitialAssessmentProgress(ctx context.Context, userID int64) (domain.UserInitialAssessmentProgress, error) - UpsertUserInitialAssessmentProgress(ctx context.Context, progress domain.UserInitialAssessmentProgress) error - ResetUserInitialAssessmentProgress(ctx context.Context, userID int64) error GetFirstIncompletePreviousPractice(ctx context.Context, userID int64, questionSetID int64) (*domain.PracticeAccessBlock, error) MarkPracticeCompleted(ctx context.Context, userID int64, questionSetID int64, scope domain.PracticeCompletionScope) error UpdateQuestionSet(ctx context.Context, id int64, input domain.CreateQuestionSetInput) error diff --git a/internal/ports/user.go b/internal/ports/user.go index d7ecfd9c..934cbdca 100644 --- a/internal/ports/user.go +++ b/internal/ports/user.go @@ -28,7 +28,6 @@ type UserStore interface { // userID int64, // ) (*dbgen.AssessmentAttempt, error) UpdateUserKnowledgeLevel(ctx context.Context, userID int64, knowledgeLevel string) error - CompleteInitialAssessment(ctx context.Context, userID int64, knowledgeLevel string) error // IsUserNameUnique(ctx context.Context, userName string) (bool, error) IsUserPending(ctx context.Context, userID int64) (bool, error) // GetUserByUserName( diff --git a/internal/repository/initial_assessment.go b/internal/repository/initial_assessment.go deleted file mode 100644 index d65061ff..00000000 --- a/internal/repository/initial_assessment.go +++ /dev/null @@ -1,12 +0,0 @@ -package repository - -import ( - "Rezina-Backend/internal/ports" -) - -// NewInitialAssessmentStore returns the Store which now delegates to the unified questions system -func NewInitialAssessmentStore(s *Store) ports.InitialAssessmentStore { return s } - -// The initial assessment functionality now uses the unified questions system. -// Use GetInitialAssessmentSet to get the initial assessment question set, -// then use the question set items to get the questions. diff --git a/internal/repository/initial_assessment_thresholds.go b/internal/repository/initial_assessment_thresholds.go deleted file mode 100644 index a8a6b924..00000000 --- a/internal/repository/initial_assessment_thresholds.go +++ /dev/null @@ -1,156 +0,0 @@ -package repository - -import ( - "context" - "fmt" - - "Rezina-Backend/internal/domain" - - "github.com/jackc/pgx/v5" -) - -func (s *Store) ListInitialAssessmentLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error) { - rows, err := s.conn.Query(ctx, ` - SELECT level, min_percent, display_order - FROM initial_assessment_level_thresholds - ORDER BY display_order ASC, level ASC - `) - if err != nil { - return nil, err - } - defer rows.Close() - - var out []domain.InitialAssessmentLevelThreshold - for rows.Next() { - var row domain.InitialAssessmentLevelThreshold - if err := rows.Scan(&row.Level, &row.MinPercent, &row.DisplayOrder); err != nil { - return nil, err - } - out = append(out, row) - } - if err := rows.Err(); err != nil { - return nil, err - } - if len(out) == 0 { - return domain.DefaultInitialAssessmentThresholds(), nil - } - return out, nil -} - -func (s *Store) ReplaceInitialAssessmentLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) error { - if err := domain.ValidateInitialAssessmentThresholds(rows); err != nil { - return err - } - - tx, err := s.conn.Begin(ctx) - if err != nil { - return err - } - defer tx.Rollback(ctx) - - if _, err := tx.Exec(ctx, `DELETE FROM initial_assessment_level_thresholds`); err != nil { - return err - } - - for i, level := range domain.InitialAssessmentCEFRLevels { - var row domain.InitialAssessmentLevelThreshold - for _, candidate := range rows { - normalized, err := domain.NormalizeCEFRLevel(candidate.Level) - if err != nil { - return err - } - if normalized == level { - row = candidate - row.Level = normalized - break - } - } - if row.Level == "" { - return fmt.Errorf("missing threshold for level %s", level) - } - displayOrder := row.DisplayOrder - if displayOrder <= 0 { - displayOrder = i + 1 - } - if _, err := tx.Exec(ctx, ` - INSERT INTO initial_assessment_level_thresholds (level, min_percent, display_order, updated_at) - VALUES ($1, $2, $3, NOW()) - `, row.Level, row.MinPercent, displayOrder); err != nil { - return err - } - } - - return tx.Commit(ctx) -} - -func (s *Store) CompleteInitialAssessment(ctx context.Context, userID int64, knowledgeLevel string) error { - level, err := domain.NormalizeCEFRLevel(knowledgeLevel) - if err != nil { - return err - } - cmd, err := s.conn.Exec(ctx, ` - UPDATE users - SET knowledge_level = $1, - initial_assessment_completed = TRUE, - updated_at = CURRENT_TIMESTAMP - WHERE id = $2 - `, level, userID) - if err != nil { - return err - } - if cmd.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil -} - -func (s *Store) GetUserInitialAssessmentProgress(ctx context.Context, userID int64) (domain.UserInitialAssessmentProgress, error) { - var row domain.UserInitialAssessmentProgress - err := s.conn.QueryRow(ctx, ` - SELECT user_id, next_level, highest_passed_level, completed - FROM user_initial_assessment_progress - WHERE user_id = $1 - `, userID).Scan(&row.UserID, &row.NextLevel, &row.HighestPassedLevel, &row.Completed) - if err != nil { - return domain.UserInitialAssessmentProgress{}, err - } - return row, nil -} - -func (s *Store) UpsertUserInitialAssessmentProgress(ctx context.Context, progress domain.UserInitialAssessmentProgress) error { - next, err := domain.NormalizeCEFRLevel(progress.NextLevel) - if err != nil { - return err - } - var highest *string - if progress.HighestPassedLevel != nil { - normalized, err := domain.NormalizeCEFRLevel(*progress.HighestPassedLevel) - if err != nil { - return err - } - highest = &normalized - } - _, err = s.conn.Exec(ctx, ` - INSERT INTO user_initial_assessment_progress (user_id, next_level, highest_passed_level, completed, updated_at) - VALUES ($1, $2, $3, $4, NOW()) - ON CONFLICT (user_id) DO UPDATE - SET next_level = EXCLUDED.next_level, - highest_passed_level = EXCLUDED.highest_passed_level, - completed = EXCLUDED.completed, - updated_at = NOW() - `, progress.UserID, next, highest, progress.Completed) - return err -} - -func (s *Store) ResetUserInitialAssessmentProgress(ctx context.Context, userID int64) error { - _, err := s.conn.Exec(ctx, ` - INSERT INTO user_initial_assessment_progress (user_id, next_level, highest_passed_level, completed, updated_at) - VALUES ($1, 'A1', NULL, FALSE, NOW()) - ON CONFLICT (user_id) DO UPDATE - SET next_level = 'A1', - highest_passed_level = NULL, - completed = FALSE, - updated_at = NOW() - `, userID) - return err -} diff --git a/internal/repository/questions.go b/internal/repository/questions.go index c9e5f5f2..1479ccec 100644 --- a/internal/repository/questions.go +++ b/internal/repository/questions.go @@ -1161,84 +1161,6 @@ func (s *Store) GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType s return result, nil } -func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet, error) { - return s.GetInitialAssessmentSetByLevel(ctx, "A1") -} - -func (s *Store) GetInitialAssessmentSetByLevel(ctx context.Context, level string) (domain.QuestionSet, error) { - normalized, err := domain.NormalizeCEFRLevel(level) - if err != nil { - return domain.QuestionSet{}, err - } - row := s.conn.QueryRow(ctx, ` - SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, - time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, - display_order, intro_video_url - FROM question_sets - WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) = $1 - ORDER BY - CASE - WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0 - ELSE 1 - END, - created_at DESC - LIMIT 1 - `, normalized) - - var ( - qs domain.QuestionSet - ownerType, banner, persona, introURL *string - ownerID *int64 - timeLimit, passing *int32 - displayOrder int32 - updatedAt *time.Time - ) - err = row.Scan( - &qs.ID, &qs.Title, &qs.Description, &qs.SetType, &ownerType, &ownerID, &banner, &persona, - &timeLimit, &passing, &qs.ShuffleQuestions, &qs.Status, &qs.CreatedAt, &updatedAt, - &displayOrder, &introURL, - ) - if err != nil { - return domain.QuestionSet{}, err - } - qs.OwnerType = ownerType - qs.OwnerID = ownerID - qs.BannerImage = banner - qs.Persona = persona - qs.TimeLimitMinutes = timeLimit - qs.PassingScore = passing - qs.UpdatedAt = updatedAt - qs.IntroVideoURL = introURL - return qs, nil -} - -func (s *Store) ListPublishedInitialAssessmentLevels(ctx context.Context) ([]string, error) { - rows, err := s.conn.Query(ctx, ` - SELECT DISTINCT UPPER(TRIM(description))::text AS level - FROM question_sets - WHERE set_type = 'INITIAL_ASSESSMENT' - AND status = 'PUBLISHED' - AND UPPER(TRIM(COALESCE(description, ''))) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2') - ORDER BY level - `) - if err != nil { - return nil, err - } - defer rows.Close() - - var out []string - for rows.Next() { - var level string - if err := rows.Scan(&level); err != nil { - return nil, err - } - out = append(out, level) - } - return out, rows.Err() -} - func (s *Store) GetFirstIncompletePreviousPractice(ctx context.Context, userID int64, questionSetID int64) (*domain.PracticeAccessBlock, error) { row, err := s.queries.GetFirstIncompletePreviousPractice(ctx, dbgen.GetFirstIncompletePreviousPracticeParams{ UserID: userID, diff --git a/internal/repository/user.go b/internal/repository/user.go index 8016656f..85b93a3d 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -564,7 +564,7 @@ func (s *Store) GetUserByGoogleID( ProfileCompleted: u.ProfileCompleted.Bool, ProfileCompletionPercentage: int(u.ProfileCompletionPercentage), ProfilePictureURL: u.ProfilePictureUrl.String, - PreferredLanguage: u.PreferredLanguage.String, + PreferredLanguage: u.PreferredLanguage.String, CreatedAt: u.CreatedAt.Time, UpdatedAt: updatedAt, @@ -583,39 +583,38 @@ func (s *Store) GetAllUsers( offset := int32(filter.Page * pageSize) params := dbgen.GetAllUsersParams{ - Role: userFilterText(filter.Role), - Status: userFilterText(filter.Status), - Query: userFilterText(filter.Query), - CreatedAfter: userFilterTime(filter.CreatedAfter), - CreatedBefore: userFilterTime(filter.CreatedBefore), - Country: userFilterText(filter.Country), - Region: userFilterText(filter.Region), - SubscriptionStatus: userFilterText(filter.SubscriptionStatus), - EducationLevel: userFilterText(filter.EducationLevel), - Occupation: userFilterText(filter.Occupation), - AgeGroup: userFilterText(filter.AgeGroup), - FavouriteTopic: userFilterText(filter.FavouriteTopic), - LanguageGoal: userFilterText(filter.LanguageGoal), - LearningGoal: userFilterText(filter.LearningGoal), - KnowledgeLevel: userFilterText(filter.KnowledgeLevel), - PlanCategory: userFilterText(filter.PlanCategory), - DevicePlatform: userFilterText(filter.DevicePlatform), - ProfileCompleted: userFilterBool(filter.ProfileCompleted), - InitialAssessmentCompleted: userFilterBool(filter.InitialAssessmentCompleted), - HasEverPaid: userFilterBool(filter.HasEverPaid), - AutoRenew: userFilterBool(filter.AutoRenew), - HasActiveDevice: userFilterBool(filter.HasActiveDevice), - PlanID: userFilterInt64(filter.PlanID), - ExpiresWithinDays: userFilterInt32(filter.ExpiresWithinDays), - DaysSinceLastLoginMin: userFilterInt32(filter.DaysSinceLastLoginMin), - DaysSinceLastLoginMax: userFilterInt32(filter.DaysSinceLastLoginMax), - MinLessonsCompleted: userFilterInt32(filter.MinLessonsCompleted), - MinModulesCompleted: userFilterInt32(filter.MinModulesCompleted), - MinProfileCompletionPct: userFilterInt32(filter.MinProfileCompletionPct), - LastLoginAfter: userFilterTime(filter.LastLoginAfter), - LastLoginBefore: userFilterTime(filter.LastLoginBefore), - Limit: pgtype.Int4{Int32: int32(pageSize), Valid: true}, - Offset: pgtype.Int4{Int32: offset, Valid: true}, + Role: userFilterText(filter.Role), + Status: userFilterText(filter.Status), + Query: userFilterText(filter.Query), + CreatedAfter: userFilterTime(filter.CreatedAfter), + CreatedBefore: userFilterTime(filter.CreatedBefore), + Country: userFilterText(filter.Country), + Region: userFilterText(filter.Region), + SubscriptionStatus: userFilterText(filter.SubscriptionStatus), + EducationLevel: userFilterText(filter.EducationLevel), + Occupation: userFilterText(filter.Occupation), + AgeGroup: userFilterText(filter.AgeGroup), + FavouriteTopic: userFilterText(filter.FavouriteTopic), + LanguageGoal: userFilterText(filter.LanguageGoal), + LearningGoal: userFilterText(filter.LearningGoal), + KnowledgeLevel: userFilterText(filter.KnowledgeLevel), + PlanCategory: userFilterText(filter.PlanCategory), + DevicePlatform: userFilterText(filter.DevicePlatform), + ProfileCompleted: userFilterBool(filter.ProfileCompleted), + HasEverPaid: userFilterBool(filter.HasEverPaid), + AutoRenew: userFilterBool(filter.AutoRenew), + HasActiveDevice: userFilterBool(filter.HasActiveDevice), + PlanID: userFilterInt64(filter.PlanID), + ExpiresWithinDays: userFilterInt32(filter.ExpiresWithinDays), + DaysSinceLastLoginMin: userFilterInt32(filter.DaysSinceLastLoginMin), + DaysSinceLastLoginMax: userFilterInt32(filter.DaysSinceLastLoginMax), + MinLessonsCompleted: userFilterInt32(filter.MinLessonsCompleted), + MinModulesCompleted: userFilterInt32(filter.MinModulesCompleted), + MinProfileCompletionPct: userFilterInt32(filter.MinProfileCompletionPct), + LastLoginAfter: userFilterTime(filter.LastLoginAfter), + LastLoginBefore: userFilterTime(filter.LastLoginBefore), + Limit: pgtype.Int4{Int32: int32(pageSize), Valid: true}, + Offset: pgtype.Int4{Int32: offset, Valid: true}, } rows, err := s.queries.GetAllUsers(ctx, params) @@ -934,7 +933,7 @@ func (s *Store) SearchUserByNameOrPhone( ProfileCompleted: u.ProfileCompleted.Bool, ProfileCompletionPercentage: int(u.ProfileCompletionPercentage), ProfilePictureURL: u.ProfilePictureUrl.String, - PreferredLanguage: u.PreferredLanguage.String, + PreferredLanguage: u.PreferredLanguage.String, CreatedAt: u.CreatedAt.Time, UpdatedAt: updatedAt, @@ -982,8 +981,6 @@ func (s *Store) UpdateUser( LanguageChallange: pgtype.Text{String: req.LanguageChallange, Valid: req.LanguageChallange != ""}, FavouriteTopic: pgtype.Text{String: req.FavouriteTopic, Valid: req.FavouriteTopic != ""}, - InitialAssessmentCompleted: req.InitialAssessmentCompleted, - ProfilePictureUrl: pgtype.Text{String: req.ProfilePictureURL, Valid: req.ProfilePictureURL != ""}, PreferredLanguage: pgtype.Text{String: req.PreferredLanguage, Valid: req.PreferredLanguage != ""}, @@ -1302,7 +1299,7 @@ func mapDBUser( PhoneVerified: userRes.PhoneVerified, Status: domain.UserStatus(userRes.Status), - ProfilePictureURL: userRes.ProfilePictureUrl.String, + ProfilePictureURL: userRes.ProfilePictureUrl.String, ProfileCompleted: userRes.ProfileCompleted.Bool, ProfileCompletionPercentage: int(userRes.ProfileCompletionPercentage), PreferredLanguage: userRes.PreferredLanguage.String, diff --git a/internal/services/assessment/helpers.go b/internal/services/assessment/helpers.go deleted file mode 100644 index ba5405bb..00000000 --- a/internal/services/assessment/helpers.go +++ /dev/null @@ -1,13 +0,0 @@ -package assessment - -import "database/sql" - -func toNullString(v *string) sql.NullString { - if v == nil { - return sql.NullString{} - } - return sql.NullString{ - String: *v, - Valid: true, - } -} diff --git a/internal/services/assessment/initial_assessment.go b/internal/services/assessment/initial_assessment.go deleted file mode 100644 index 1bea8a13..00000000 --- a/internal/services/assessment/initial_assessment.go +++ /dev/null @@ -1,46 +0,0 @@ -package assessment - -import ( - "Rezina-Backend/internal/domain" - "context" - "errors" - "strings" - - "github.com/jackc/pgx/v5" -) - -// CreateQuestion creates a question in the unified questions system. -// Initial assessment questions should be created through the unified questions API -// and then linked to the initial assessment question set. -func (s *Service) CreateQuestion( - ctx context.Context, - input domain.CreateQuestionInput, -) (domain.Question, error) { - return s.questionStore.CreateQuestion(ctx, input) -} - -// ListQuestions returns published questions for a CEFR placement level set. -// When level is empty, defaults to A1 for backward compatibility. -func (s *Service) ListQuestions(ctx context.Context, level string) ([]domain.QuestionWithDetails, error) { - if strings.TrimSpace(level) == "" { - level = "A1" - } - normalized, err := domain.NormalizeCEFRLevel(level) - if err != nil { - return nil, err - } - - _, questions, err := s.loadPublishedLevelQuestions(ctx, normalized) - if err != nil { - if errors.Is(err, ErrPlacementSetNotFound) || errors.Is(err, pgx.ErrNoRows) { - return nil, ErrPlacementSetNotFound - } - return nil, err - } - return questions, nil -} - -// GetQuestionByID returns a question with full details. -func (s *Service) GetQuestionByID(ctx context.Context, id int64) (domain.QuestionWithDetails, error) { - return s.questionStore.GetQuestionWithDetails(ctx, id) -} diff --git a/internal/services/assessment/placement.go b/internal/services/assessment/placement.go deleted file mode 100644 index 65d82f3e..00000000 --- a/internal/services/assessment/placement.go +++ /dev/null @@ -1,257 +0,0 @@ -package assessment - -import ( - "context" - "errors" - "fmt" - "strings" - - "Rezina-Backend/internal/domain" - - "github.com/jackc/pgx/v5" -) - -var ( - ErrPlacementSetNotFound = errors.New("published initial assessment set not found for level") - ErrNoGradableQuestions = errors.New("placement set has no auto-gradable questions") - ErrPlacementLevelRequired = errors.New("level is required") - ErrPlacementLevelMismatch = errors.New("level does not match the learner's next placement level") - ErrPlacementAlreadyComplete = errors.New("initial assessment already completed") -) - -func (s *Service) ListLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error) { - rows, err := s.questionStore.ListInitialAssessmentLevelThresholds(ctx) - if err != nil { - return nil, err - } - if len(rows) == 0 { - return domain.DefaultInitialAssessmentThresholds(), nil - } - return rows, nil -} - -func (s *Service) UpdateLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) ([]domain.InitialAssessmentLevelThreshold, error) { - if err := domain.ValidateInitialAssessmentThresholds(rows); err != nil { - return nil, err - } - if err := s.questionStore.ReplaceInitialAssessmentLevelThresholds(ctx, rows); err != nil { - return nil, err - } - return s.ListLevelThresholds(ctx) -} - -func (s *Service) GetPlacementSession(ctx context.Context, userID int64) (domain.PlacementSession, error) { - published, err := s.questionStore.ListPublishedInitialAssessmentLevels(ctx) - if err != nil { - return domain.PlacementSession{}, err - } - - progress, err := s.ensurePlacementProgress(ctx, userID) - if err != nil { - return domain.PlacementSession{}, err - } - - session := domain.PlacementSession{ - Completed: progress.Completed, - HighestPassedLevel: progress.HighestPassedLevel, - PublishedLevels: published, - InitialAssessmentCompleted: progress.Completed, - } - if progress.Completed { - if progress.HighestPassedLevel != nil { - session.KnowledgeLevel = *progress.HighestPassedLevel - } else { - session.KnowledgeLevel = "A1" - } - return session, nil - } - session.NextLevel = progress.NextLevel - return session, nil -} - -func (s *Service) ensurePlacementProgress(ctx context.Context, userID int64) (domain.UserInitialAssessmentProgress, error) { - progress, err := s.questionStore.GetUserInitialAssessmentProgress(ctx, userID) - if err == nil { - return progress, nil - } - if !errors.Is(err, pgx.ErrNoRows) { - return domain.UserInitialAssessmentProgress{}, err - } - progress = domain.UserInitialAssessmentProgress{ - UserID: userID, - NextLevel: "A1", - Completed: false, - } - if err := s.questionStore.UpsertUserInitialAssessmentProgress(ctx, progress); err != nil { - return domain.UserInitialAssessmentProgress{}, err - } - return progress, nil -} - -func (s *Service) loadPublishedLevelQuestions(ctx context.Context, level string) (domain.QuestionSet, []domain.QuestionWithDetails, error) { - normalized, err := domain.NormalizeCEFRLevel(level) - if err != nil { - return domain.QuestionSet{}, nil, err - } - set, err := s.questionStore.GetInitialAssessmentSetByLevel(ctx, normalized) - if err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return domain.QuestionSet{}, nil, ErrPlacementSetNotFound - } - return domain.QuestionSet{}, nil, err - } - - items, err := s.questionStore.GetPublishedQuestionsInSet(ctx, set.ID) - if err != nil { - return domain.QuestionSet{}, nil, err - } - if len(items) == 0 { - return domain.QuestionSet{}, nil, fmt.Errorf("%w: set is empty", ErrNoGradableQuestions) - } - - ids := make([]int64, 0, len(items)) - for _, item := range items { - ids = append(ids, item.QuestionID) - } - byID, err := s.questionStore.GetQuestionsWithDetailsByIDs(ctx, ids) - if err != nil { - return domain.QuestionSet{}, nil, err - } - questions := make([]domain.QuestionWithDetails, 0, len(items)) - for _, item := range items { - qwd, ok := byID[item.QuestionID] - if !ok { - continue - } - questions = append(questions, qwd) - } - if len(questions) == 0 { - return domain.QuestionSet{}, nil, ErrNoGradableQuestions - } - return set, questions, nil -} - -// SubmitPlacement grades answers for one CEFR level set and advances progressive placement. -// On fail (or when the next level set is unpublished), finalizes knowledge_level as the highest -// passed level (A1 if none). Passing C2 finalizes at C2. -func (s *Service) SubmitPlacement(ctx context.Context, userID int64, level string, answers []domain.PlacementAnswerInput) (domain.PlacementAssessmentResult, error) { - if strings.TrimSpace(level) == "" { - return domain.PlacementAssessmentResult{}, ErrPlacementLevelRequired - } - normalized, err := domain.NormalizeCEFRLevel(level) - if err != nil { - return domain.PlacementAssessmentResult{}, err - } - - progress, err := s.ensurePlacementProgress(ctx, userID) - if err != nil { - return domain.PlacementAssessmentResult{}, err - } - if progress.Completed { - return domain.PlacementAssessmentResult{}, ErrPlacementAlreadyComplete - } - if progress.NextLevel != normalized { - return domain.PlacementAssessmentResult{}, fmt.Errorf("%w: expected %s", ErrPlacementLevelMismatch, progress.NextLevel) - } - - set, questions, err := s.loadPublishedLevelQuestions(ctx, normalized) - if err != nil { - return domain.PlacementAssessmentResult{}, err - } - - graded := domain.GradePlacementAnswers(questions, answers) - graded.QuestionSetID = set.ID - graded.LevelAttempted = normalized - if graded.GradableQuestions == 0 { - return domain.PlacementAssessmentResult{}, ErrNoGradableQuestions - } - - thresholds, err := s.ListLevelThresholds(ctx) - if err != nil { - return domain.PlacementAssessmentResult{}, err - } - passPercent, err := domain.PassPercentForLevel(normalized, thresholds) - if err != nil { - return domain.PlacementAssessmentResult{}, err - } - graded.PassPercent = passPercent - graded.Passed = graded.ScorePercent+1e-9 >= float64(passPercent) - - highest := progress.HighestPassedLevel - if graded.Passed { - highest = &normalized - next := domain.NextCEFRLevel(normalized) - if next == "" { - graded.Completed = true - graded.Level = normalized - graded.KnowledgeLevel = normalized - graded.InitialAssessmentCompleted = true - progress.HighestPassedLevel = highest - progress.Completed = true - progress.NextLevel = normalized - if err := s.questionStore.UpsertUserInitialAssessmentProgress(ctx, progress); err != nil { - return domain.PlacementAssessmentResult{}, err - } - if err := s.userStore.CompleteInitialAssessment(ctx, userID, normalized); err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return domain.PlacementAssessmentResult{}, fmt.Errorf("user not found") - } - return domain.PlacementAssessmentResult{}, err - } - return graded, nil - } - - if _, err := s.questionStore.GetInitialAssessmentSetByLevel(ctx, next); err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return s.finalizePlacement(ctx, userID, progress, highest, graded) - } - return domain.PlacementAssessmentResult{}, err - } - - progress.HighestPassedLevel = highest - progress.NextLevel = next - progress.Completed = false - if err := s.questionStore.UpsertUserInitialAssessmentProgress(ctx, progress); err != nil { - return domain.PlacementAssessmentResult{}, err - } - graded.NextLevel = &next - graded.Completed = false - graded.Level = normalized - graded.InitialAssessmentCompleted = false - return graded, nil - } - - return s.finalizePlacement(ctx, userID, progress, highest, graded) -} - -func (s *Service) finalizePlacement( - ctx context.Context, - userID int64, - progress domain.UserInitialAssessmentProgress, - highest *string, - graded domain.PlacementAssessmentResult, -) (domain.PlacementAssessmentResult, error) { - final := "A1" - if highest != nil && *highest != "" { - final = *highest - } - graded.Completed = true - graded.Level = final - graded.KnowledgeLevel = final - graded.InitialAssessmentCompleted = true - graded.NextLevel = nil - - progress.HighestPassedLevel = highest - progress.Completed = true - progress.NextLevel = final - if err := s.questionStore.UpsertUserInitialAssessmentProgress(ctx, progress); err != nil { - return domain.PlacementAssessmentResult{}, err - } - if err := s.userStore.CompleteInitialAssessment(ctx, userID, final); err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return domain.PlacementAssessmentResult{}, fmt.Errorf("user not found") - } - return domain.PlacementAssessmentResult{}, err - } - return graded, nil -} diff --git a/internal/services/assessment/service.go b/internal/services/assessment/service.go deleted file mode 100644 index 03045c2e..00000000 --- a/internal/services/assessment/service.go +++ /dev/null @@ -1,28 +0,0 @@ -package assessment - -import ( - "Rezina-Backend/internal/config" - "Rezina-Backend/internal/ports" - notificationservice "Rezina-Backend/internal/services/notification" -) - -type Service struct { - userStore ports.UserStore - questionStore ports.QuestionStore - notificationSvc *notificationservice.Service - config *config.Config -} - -func NewService( - userStore ports.UserStore, - questionStore ports.QuestionStore, - notificationSvc *notificationservice.Service, - cfg *config.Config, -) *Service { - return &Service{ - userStore: userStore, - questionStore: questionStore, - notificationSvc: notificationSvc, - config: cfg, - } -} diff --git a/internal/services/learnernotifications/subscription.go b/internal/services/learnernotifications/subscription.go index 04cb674c..ab35d5bf 100644 --- a/internal/services/learnernotifications/subscription.go +++ b/internal/services/learnernotifications/subscription.go @@ -11,6 +11,8 @@ func subscriptionPackageLabel(planCategory string) string { switch strings.ToUpper(strings.TrimSpace(planCategory)) { case string(domain.SubscriptionCategoryLearnEnglish): return "Learn English" + case string(domain.SubscriptionCategoryEducation): + return "Education" case string(domain.SubscriptionCategoryIELTS): return "IELTS" case string(domain.SubscriptionCategoryDuolingo): @@ -25,6 +27,8 @@ func subscriptionActivatedMessage(planCategory, planName string) string { switch strings.ToUpper(strings.TrimSpace(planCategory)) { case string(domain.SubscriptionCategoryLearnEnglish): return "Your \"" + planName + "\" Learn English package is now active. Enjoy your learning journey!" + case string(domain.SubscriptionCategoryEducation): + return "Your \"" + planName + "\" education package is now active. Enjoy your learning journey!" case string(domain.SubscriptionCategoryIELTS): return "Your \"" + planName + "\" IELTS package is now active. Start preparing today!" case string(domain.SubscriptionCategoryDuolingo): diff --git a/internal/services/questions/service.go b/internal/services/questions/service.go index e03cd437..8a8bed2c 100644 --- a/internal/services/questions/service.go +++ b/internal/services/questions/service.go @@ -196,10 +196,6 @@ func (s *Service) GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType return s.questionStore.GetPublishedQuestionSetsByOwner(ctx, ownerType, ownerID) } -func (s *Service) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet, error) { - return s.questionStore.GetInitialAssessmentSet(ctx) -} - func (s *Service) GetFirstIncompletePreviousPractice(ctx context.Context, userID int64, questionSetID int64) (*domain.PracticeAccessBlock, error) { return s.questionStore.GetFirstIncompletePreviousPractice(ctx, userID, questionSetID) } diff --git a/internal/services/subscriptions/service.go b/internal/services/subscriptions/service.go index a1db115c..fe4db4bb 100644 --- a/internal/services/subscriptions/service.go +++ b/internal/services/subscriptions/service.go @@ -691,6 +691,7 @@ func (s *Service) GetAdminUserSubscriptionDetails(ctx context.Context, userID in } activeByCategory := map[string]bool{ + string(domain.SubscriptionCategoryEducation): false, string(domain.SubscriptionCategoryLearnEnglish): false, string(domain.SubscriptionCategoryIELTS): false, string(domain.SubscriptionCategoryDuolingo): false, diff --git a/internal/web_server/app.go b/internal/web_server/app.go index 11f35d7b..5caba391 100644 --- a/internal/web_server/app.go +++ b/internal/web_server/app.go @@ -3,12 +3,11 @@ package httpserver import ( dbgen "Rezina-Backend/gen/db" "Rezina-Backend/internal/config" - activitylogservice "Rezina-Backend/internal/services/activity_log" + activitylogservice "Rezina-Backend/internal/services/activity_log" "Rezina-Backend/internal/services/appversions" "Rezina-Backend/internal/services/arifpay" - "Rezina-Backend/internal/services/chapa" - "Rezina-Backend/internal/services/assessment" "Rezina-Backend/internal/services/authentication" + "Rezina-Backend/internal/services/chapa" cloudconvertservice "Rezina-Backend/internal/services/cloudconvert" "Rezina-Backend/internal/services/courses" "Rezina-Backend/internal/services/emailtemplates" @@ -20,7 +19,7 @@ import ( "Rezina-Backend/internal/services/lmsprogress" minioservice "Rezina-Backend/internal/services/minio" "Rezina-Backend/internal/services/modules" - notificationservice "Rezina-Backend/internal/services/notification" + notificationservice "Rezina-Backend/internal/services/notification" "Rezina-Backend/internal/services/personas" practicecontentservice "Rezina-Backend/internal/services/practicecontent" "Rezina-Backend/internal/services/practices" @@ -32,8 +31,8 @@ import ( "Rezina-Backend/internal/services/recommendation" "Rezina-Backend/internal/services/subscriptions" "Rezina-Backend/internal/services/team" - vimeoservice "Rezina-Backend/internal/services/vimeo" "Rezina-Backend/internal/services/videoengagement" + vimeoservice "Rezina-Backend/internal/services/vimeo" "Rezina-Backend/internal/services/settings" "Rezina-Backend/internal/services/transaction" @@ -54,56 +53,54 @@ import ( ) type App struct { - assessmentSvc *assessment.Service - questionsSvc *questions.Service - faqSvc *faqs.Service - appVersionSvc *appversions.Service - emailTemplateSvc *emailtemplates.Service - profileFieldOptionSvc *profilefieldoptions.Service - personaSvc *personas.Service - examPrepSvc *examprep.Service - programSvc *programs.Service - courseSvc *courses.Service - moduleSvc *modules.Service - lessonSvc *lessons.Service - lmsProgressSvc *lmsprogress.Service - practiceSvc *practices.Service - practiceContentSvc *practicecontentservice.Service - subscriptionsSvc *subscriptions.Service - arifpaySvc *arifpay.ArifpayService - chapaSvc *chapa.Service - issueReportingSvc *issuereporting.Service - vimeoSvc *vimeoservice.Service - teamSvc *team.Service - activityLogSvc *activitylogservice.Service - cloudConvertSvc *cloudconvertservice.Service - minioSvc *minioservice.Service - ratingSvc *ratingsservice.Service - fiber *fiber.App - recommendationSvc recommendation.RecommendationService - cfg *config.Config - logger *slog.Logger - NotidicationStore *notificationservice.Service - port int - settingSvc *settings.Service - authSvc *authentication.Service - userSvc *user.Service - transactionSvc *transaction.Service - validator *customvalidator.CustomValidator - JwtConfig jwtutil.JwtConfig - Logger *slog.Logger - mongoLoggerSvc *zap.Logger - analyticsDB *dbgen.Queries - rbacSvc *rbacservice.Service - videoEngagementSvc *videoengagement.Service - stopPurgeWorker context.CancelFunc - stopPaymentExpiryWorker context.CancelFunc + questionsSvc *questions.Service + faqSvc *faqs.Service + appVersionSvc *appversions.Service + emailTemplateSvc *emailtemplates.Service + profileFieldOptionSvc *profilefieldoptions.Service + personaSvc *personas.Service + examPrepSvc *examprep.Service + programSvc *programs.Service + courseSvc *courses.Service + moduleSvc *modules.Service + lessonSvc *lessons.Service + lmsProgressSvc *lmsprogress.Service + practiceSvc *practices.Service + practiceContentSvc *practicecontentservice.Service + subscriptionsSvc *subscriptions.Service + arifpaySvc *arifpay.ArifpayService + chapaSvc *chapa.Service + issueReportingSvc *issuereporting.Service + vimeoSvc *vimeoservice.Service + teamSvc *team.Service + activityLogSvc *activitylogservice.Service + cloudConvertSvc *cloudconvertservice.Service + minioSvc *minioservice.Service + ratingSvc *ratingsservice.Service + fiber *fiber.App + recommendationSvc recommendation.RecommendationService + cfg *config.Config + logger *slog.Logger + NotidicationStore *notificationservice.Service + port int + settingSvc *settings.Service + authSvc *authentication.Service + userSvc *user.Service + transactionSvc *transaction.Service + validator *customvalidator.CustomValidator + JwtConfig jwtutil.JwtConfig + Logger *slog.Logger + mongoLoggerSvc *zap.Logger + analyticsDB *dbgen.Queries + rbacSvc *rbacservice.Service + videoEngagementSvc *videoengagement.Service + stopPurgeWorker context.CancelFunc + stopPaymentExpiryWorker context.CancelFunc stopSubscriptionExpiryReminderWorker context.CancelFunc - learnerNotifSvc *learnernotifications.Service + learnerNotifSvc *learnernotifications.Service } func NewApp( - assessmentSvc *assessment.Service, questionsSvc *questions.Service, faqSvc *faqs.Service, appVersionSvc *appversions.Service, @@ -164,49 +161,48 @@ func NewApp( app.Static("/static", "./static") s := &App{ - assessmentSvc: assessmentSvc, - questionsSvc: questionsSvc, + questionsSvc: questionsSvc, faqSvc: faqSvc, appVersionSvc: appVersionSvc, emailTemplateSvc: emailTemplateSvc, profileFieldOptionSvc: profileFieldOptionSvc, - personaSvc: personaSvc, - examPrepSvc: examPrepSvc, - programSvc: programSvc, - courseSvc: courseSvc, - moduleSvc: moduleSvc, - lessonSvc: lessonSvc, - lmsProgressSvc: lmsProgressSvc, - practiceSvc: practiceSvc, - practiceContentSvc: practiceContentSvc, - subscriptionsSvc: subscriptionsSvc, - arifpaySvc: arifpaySvc, - chapaSvc: chapaSvc, - vimeoSvc: vimeoSvc, - teamSvc: teamSvc, - activityLogSvc: activityLogSvc, - cloudConvertSvc: cloudConvertSvc, - minioSvc: minioSvc, - ratingSvc: ratingSvc, - issueReportingSvc: issueReportingSvc, - fiber: app, - port: port, - settingSvc: settingSvc, - authSvc: authSvc, - validator: validator, - logger: logger, - JwtConfig: JwtConfig, - userSvc: userSvc, - transactionSvc: transactionSvc, - NotidicationStore: notidicationStore, - Logger: logger, - recommendationSvc: recommendationSvc, - cfg: cfg, - mongoLoggerSvc: mongoLoggerSvc, - analyticsDB: analyticsDB, - rbacSvc: rbacSvc, - videoEngagementSvc: videoEngagementSvc, - learnerNotifSvc: learnerNotifSvc, + personaSvc: personaSvc, + examPrepSvc: examPrepSvc, + programSvc: programSvc, + courseSvc: courseSvc, + moduleSvc: moduleSvc, + lessonSvc: lessonSvc, + lmsProgressSvc: lmsProgressSvc, + practiceSvc: practiceSvc, + practiceContentSvc: practiceContentSvc, + subscriptionsSvc: subscriptionsSvc, + arifpaySvc: arifpaySvc, + chapaSvc: chapaSvc, + vimeoSvc: vimeoSvc, + teamSvc: teamSvc, + activityLogSvc: activityLogSvc, + cloudConvertSvc: cloudConvertSvc, + minioSvc: minioSvc, + ratingSvc: ratingSvc, + issueReportingSvc: issueReportingSvc, + fiber: app, + port: port, + settingSvc: settingSvc, + authSvc: authSvc, + validator: validator, + logger: logger, + JwtConfig: JwtConfig, + userSvc: userSvc, + transactionSvc: transactionSvc, + NotidicationStore: notidicationStore, + Logger: logger, + recommendationSvc: recommendationSvc, + cfg: cfg, + mongoLoggerSvc: mongoLoggerSvc, + analyticsDB: analyticsDB, + rbacSvc: rbacSvc, + videoEngagementSvc: videoEngagementSvc, + learnerNotifSvc: learnerNotifSvc, } s.initAppRoutes() diff --git a/internal/web_server/content_access_middleware.go b/internal/web_server/content_access_middleware.go index b20b6180..bc6c7091 100644 --- a/internal/web_server/content_access_middleware.go +++ b/internal/web_server/content_access_middleware.go @@ -4,11 +4,11 @@ import ( "context" "Rezina-Backend/internal/domain" - lessonsvc "Rezina-Backend/internal/services/lessons" coursessvc "Rezina-Backend/internal/services/courses" + lessonsvc "Rezina-Backend/internal/services/lessons" modulesvc "Rezina-Backend/internal/services/modules" - programssvc "Rezina-Backend/internal/services/programs" practicessvc "Rezina-Backend/internal/services/practices" + programssvc "Rezina-Backend/internal/services/programs" "errors" "fmt" "strings" @@ -56,18 +56,18 @@ func (a *App) RequireLMSSubscriptionUnlessFree() fiber.Handler { return c.Next() } - active, err := a.subscriptionsSvc.HasActiveSubscriptionByCategory(c.Context(), userID, domain.SubscriptionCategoryLearnEnglish) + active, err := a.subscriptionsSvc.HasActiveSubscriptionByCategory(c.Context(), userID, domain.SubscriptionCategoryEducation) if err != nil { a.mongoLoggerSvc.Error("category subscription check failed", zap.Int64("userID", userID), - zap.String("category", string(domain.SubscriptionCategoryLearnEnglish)), + zap.String("category", string(domain.SubscriptionCategoryEducation)), zap.String("path", c.Path()), zap.Error(err), ) return fiber.NewError(fiber.StatusInternalServerError, "Failed to verify subscription") } if !active { - return fiber.NewError(fiber.StatusForbidden, fmt.Sprintf("An active %s subscription is required", humanizeSubscriptionCategory(domain.SubscriptionCategoryLearnEnglish))) + return fiber.NewError(fiber.StatusForbidden, fmt.Sprintf("An active %s subscription is required", humanizeSubscriptionCategory(domain.SubscriptionCategoryEducation))) } return c.Next() } diff --git a/internal/web_server/handlers/exam_prep_catalog_course_handler.go b/internal/web_server/handlers/exam_prep_catalog_course_handler.go index 944e9603..9f167da1 100644 --- a/internal/web_server/handlers/exam_prep_catalog_course_handler.go +++ b/internal/web_server/handlers/exam_prep_catalog_course_handler.go @@ -19,7 +19,6 @@ import ( // @Param body body domain.CreateExamPrepCatalogCourseInput true "Catalog course" // @Success 201 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse -// @Router /api/v1/exam-prep/catalog-courses [post] func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error { var req domain.CreateExamPrepCatalogCourseInput if err := c.BodyParser(&req); err != nil { @@ -57,7 +56,6 @@ func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error { // @Param limit query int false "Page size" default(20) // @Param offset query int false "Offset" default(0) // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses [get] func (h *Handler) ListExamPrepCatalogCourses(c *fiber.Ctx) error { limit, _ := strconv.Atoi(c.Query("limit", "20")) offset, _ := strconv.Atoi(c.Query("offset", "0")) @@ -97,7 +95,6 @@ func (h *Handler) ListExamPrepCatalogCourses(c *fiber.Ctx) error { // @Produce json // @Param body body domain.ReorderIDsRequest true "ordered_ids: every catalog course id exactly once" // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/reorder [put] func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error { var req domain.ReorderIDsRequest if err := c.BodyParser(&req); err != nil { @@ -137,7 +134,6 @@ func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error { // @Produce json // @Param id path int true "Catalog course ID" // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/{id} [get] func (h *Handler) GetExamPrepCatalogCourseByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -188,7 +184,6 @@ func (h *Handler) GetExamPrepCatalogCourseByID(c *fiber.Ctx) error { // @Param id path int true "Catalog course ID" // @Param body body domain.UpdateExamPrepCatalogCourseInput true "Fields to update" // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/{id} [put] func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -231,7 +226,6 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error { // @Tags exam-prep // @Param id path int true "Catalog course ID" // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/{id} [delete] func (h *Handler) DeleteExamPrepCatalogCourse(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/exam_prep_lesson_handler.go b/internal/web_server/handlers/exam_prep_lesson_handler.go index 5cd2b816..a7c37eb0 100644 --- a/internal/web_server/handlers/exam_prep_lesson_handler.go +++ b/internal/web_server/handlers/exam_prep_lesson_handler.go @@ -15,7 +15,6 @@ import ( // @Tags exam-prep // @Param moduleId path int true "Exam prep unit module ID" // @Param body body domain.CreateExamPrepLessonInput true "Lesson" -// @Router /api/v1/exam-prep/modules/{moduleId}/lessons [post] func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error { moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) if err != nil { @@ -65,7 +64,6 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error { // @Param moduleId path int true "Exam prep unit module ID" // @Param limit query int false "Page size" default(20) // @Param offset query int false "Offset" default(0) -// @Router /api/v1/exam-prep/modules/{moduleId}/lessons [get] func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error { moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) if err != nil { @@ -127,7 +125,6 @@ func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error { // ReorderExamPrepLessonsInUnitModule godoc // @Summary Reorder lessons within an exam-prep unit module // @Tags exam-prep -// @Router /api/v1/exam-prep/modules/{moduleId}/lessons/reorder [put] func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error { moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) if err != nil { @@ -178,7 +175,6 @@ func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error { // GetExamPrepLessonByID godoc // @Summary Get exam-prep lesson by ID // @Tags exam-prep -// @Router /api/v1/exam-prep/lessons/{id} [get] func (h *Handler) GetExamPrepLessonByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -228,7 +224,6 @@ func (h *Handler) GetExamPrepLessonByID(c *fiber.Ctx) error { // UpdateExamPrepLesson godoc // @Summary Update exam-prep lesson // @Tags exam-prep -// @Router /api/v1/exam-prep/lessons/{id} [put] func (h *Handler) UpdateExamPrepLesson(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -269,7 +264,6 @@ func (h *Handler) UpdateExamPrepLesson(c *fiber.Ctx) error { // DeleteExamPrepLesson godoc // @Summary Delete exam-prep lesson // @Tags exam-prep -// @Router /api/v1/exam-prep/lessons/{id} [delete] func (h *Handler) DeleteExamPrepLesson(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/exam_prep_module_handler.go b/internal/web_server/handlers/exam_prep_module_handler.go index a4f10850..9f4dfa80 100644 --- a/internal/web_server/handlers/exam_prep_module_handler.go +++ b/internal/web_server/handlers/exam_prep_module_handler.go @@ -15,7 +15,6 @@ import ( // @Tags exam-prep // @Param unitId path int true "Unit ID" // @Param body body domain.CreateExamPrepModuleInput true "Module" -// @Router /api/v1/exam-prep/units/{unitId}/modules [post] func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error { unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) if err != nil { @@ -63,7 +62,6 @@ func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error { // @Summary List exam-prep modules for a unit // @Tags exam-prep // @Param unitId path int true "Unit ID" -// @Router /api/v1/exam-prep/units/{unitId}/modules [get] func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error { unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) if err != nil { @@ -127,7 +125,6 @@ func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error { // @Tags exam-prep // @Param unitId path int true "Unit ID" // @Param body body domain.ReorderIDsRequest true "ordered_ids" -// @Router /api/v1/exam-prep/units/{unitId}/modules/reorder [put] func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error { unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) if err != nil { @@ -178,7 +175,6 @@ func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error { // GetExamPrepModuleByID godoc // @Summary Get exam-prep module by ID // @Tags exam-prep -// @Router /api/v1/exam-prep/modules/{id} [get] func (h *Handler) GetExamPrepModuleByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -228,7 +224,6 @@ func (h *Handler) GetExamPrepModuleByID(c *fiber.Ctx) error { // UpdateExamPrepModule godoc // @Summary Update exam-prep module // @Tags exam-prep -// @Router /api/v1/exam-prep/modules/{id} [put] func (h *Handler) UpdateExamPrepModule(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -269,7 +264,6 @@ func (h *Handler) UpdateExamPrepModule(c *fiber.Ctx) error { // DeleteExamPrepModule godoc // @Summary Delete exam-prep module // @Tags exam-prep -// @Router /api/v1/exam-prep/modules/{id} [delete] func (h *Handler) DeleteExamPrepModule(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/exam_prep_practice_handler.go b/internal/web_server/handlers/exam_prep_practice_handler.go index 90377c1d..6949e68d 100644 --- a/internal/web_server/handlers/exam_prep_practice_handler.go +++ b/internal/web_server/handlers/exam_prep_practice_handler.go @@ -14,7 +14,6 @@ import ( // @Summary Create exam-prep practice (optional parents; link later via PUT /exam-prep/practices/:id/parents) // @Tags exam-prep // @Param body body domain.CreateExamPrepPracticeInput true "Practice" -// @Router /api/v1/exam-prep/practices [post] func (h *Handler) CreateExamPrepPracticeFromInput(c *fiber.Ctx) error { var req domain.CreateExamPrepPracticeInput if err := c.BodyParser(&req); err != nil { @@ -54,7 +53,6 @@ func (h *Handler) CreateExamPrepPracticeFromInput(c *fiber.Ctx) error { // @Param limit query int false "Page size. Omit (with offset) to return all practices." // @Param offset query int false "Offset. Defaults to 0 when limit is provided; ignored semantics when both omitted (all rows)." // @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)" -// @Router /api/v1/exam-prep/practices [get] func (h *Handler) ListAllExamPrepPractices(c *fiber.Ctx) error { limit, offset, err := parseOptionalExamPrepPracticePagination(c) if err != nil { @@ -83,7 +81,6 @@ func (h *Handler) ListAllExamPrepPractices(c *fiber.Ctx) error { // @Tags exam-prep // @Param lessonId path int true "Exam prep lesson ID (unit_module_lessons.id)" // @Param body body domain.CreateExamPrepPracticeInput true "Practice" -// @Router /api/v1/exam-prep/lessons/{lessonId}/practices [post] func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error { lessonID, err := strconv.ParseInt(c.Params("lessonId"), 10, 64) if err != nil { @@ -130,7 +127,6 @@ func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error { // @Param lessonId path int true "Exam prep lesson ID" // @Param limit query int false "Page size. Omit to return all practices for the lesson." // @Param offset query int false "Offset (used when limit is provided)" -// @Router /api/v1/exam-prep/lessons/{lessonId}/practices [get] func (h *Handler) ListExamPrepPracticesByLesson(c *fiber.Ctx) error { lessonID, err := strconv.ParseInt(c.Params("lessonId"), 10, 64) if err != nil { @@ -164,7 +160,6 @@ func (h *Handler) ListExamPrepPracticesByLesson(c *fiber.Ctx) error { // @Summary Get exam-prep practice by ID // @Tags exam-prep // @Param id path int true "Exam prep practice ID" -// @Router /api/v1/exam-prep/practices/{id} [get] func (h *Handler) GetExamPrepPracticeByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -205,7 +200,6 @@ func (h *Handler) GetExamPrepPracticeByID(c *fiber.Ctx) error { // @Tags exam-prep // @Param id path int true "Exam prep practice ID" // @Param body body domain.UpdateExamPrepPracticeInput true "Fields to update" -// @Router /api/v1/exam-prep/practices/{id} [put] func (h *Handler) UpdateExamPrepPractice(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -254,7 +248,6 @@ func (h *Handler) UpdateExamPrepPractice(c *fiber.Ctx) error { // @Tags exam-prep // @Param id path int true "Exam prep practice ID" // @Param body body domain.UpdateExamPrepPracticeParentsInput true "Parent links (replaces all; use empty array to detach)" -// @Router /api/v1/exam-prep/practices/{id}/parents [put] func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -310,7 +303,6 @@ func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error { // @Param id path int true "Exam prep practice ID" // @Param parentKind path string true "Parent kind (CATALOG_COURSE, UNIT, LESSON)" // @Param parentId path int true "Parent entity ID" -// @Router /api/v1/exam-prep/practices/{id}/parents/{parentKind}/{parentId} [delete] func (h *Handler) UnlinkExamPrepPracticeParent(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -364,7 +356,6 @@ func (h *Handler) UnlinkExamPrepPracticeParent(c *fiber.Ctx) error { // @Summary Delete exam-prep practice // @Tags exam-prep // @Param id path int true "Exam prep practice ID" -// @Router /api/v1/exam-prep/practices/{id} [delete] func (h *Handler) DeleteExamPrepPractice(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -449,7 +440,6 @@ func (h *Handler) listExamPrepPracticesResponse(c *fiber.Ctx, items []domain.Exa // @Tags exam-prep // @Param catalogCourseId path int true "Exam prep catalog course ID" // @Param body body domain.CreateExamPrepPracticeInput true "Practice" -// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/practices [post] func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) if err != nil { @@ -481,7 +471,6 @@ func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error { // @Param catalogCourseId path int true "Exam prep catalog course ID" // @Param limit query int false "Page size. Omit to return all practices for the catalog course." // @Param offset query int false "Offset (used when limit is provided)" -// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/practices [get] func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) if err != nil { @@ -510,7 +499,6 @@ func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error { // @Tags exam-prep // @Param unitId path int true "Exam prep unit ID" // @Param body body domain.CreateExamPrepPracticeInput true "Practice" -// @Router /api/v1/exam-prep/units/{unitId}/practices [post] func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error { unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) if err != nil { @@ -542,7 +530,6 @@ func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error { // @Param unitId path int true "Exam prep unit ID" // @Param limit query int false "Page size. Omit to return all practices for the unit." // @Param offset query int false "Offset (used when limit is provided)" -// @Router /api/v1/exam-prep/units/{unitId}/practices [get] func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error { unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/exam_prep_unit_handler.go b/internal/web_server/handlers/exam_prep_unit_handler.go index a32ff4e2..ae2fb35b 100644 --- a/internal/web_server/handlers/exam_prep_unit_handler.go +++ b/internal/web_server/handlers/exam_prep_unit_handler.go @@ -19,7 +19,6 @@ import ( // @Param catalogCourseId path int true "Catalog course ID" // @Param body body domain.CreateExamPrepUnitInput true "Unit" // @Success 201 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units [post] func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) if err != nil { @@ -70,7 +69,6 @@ func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error { // @Param limit query int false "Page size" default(20) // @Param offset query int false "Offset" default(0) // @Success 200 {object} domain.Response -// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units [get] func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) if err != nil { @@ -134,7 +132,6 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error { // @Tags exam-prep // @Param catalogCourseId path int true "Catalog course ID" // @Param body body domain.ReorderIDsRequest true "ordered_ids: every unit id in this catalog course, new order" -// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units/reorder [put] func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) if err != nil { @@ -186,7 +183,6 @@ func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error { // @Summary Get exam-prep unit by ID // @Tags exam-prep // @Param id path int true "Unit ID" -// @Router /api/v1/exam-prep/units/{id} [get] func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -238,7 +234,6 @@ func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error { // @Tags exam-prep // @Param id path int true "Unit ID" // @Param body body domain.UpdateExamPrepUnitInput true "Fields to update" -// @Router /api/v1/exam-prep/units/{id} [put] func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -280,7 +275,6 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error { // @Summary Delete exam-prep unit // @Tags exam-prep // @Param id path int true "Unit ID" -// @Router /api/v1/exam-prep/units/{id} [delete] func (h *Handler) DeleteExamPrepUnit(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/export_filters.go b/internal/web_server/handlers/export_filters.go index 59b61b2d..e607d23c 100644 --- a/internal/web_server/handlers/export_filters.go +++ b/internal/web_server/handlers/export_filters.go @@ -56,9 +56,7 @@ func paymentListFilterFields(c *fiber.Ctx) (domain.PaymentListFilter, error) { } if v := strings.TrimSpace(c.Query("plan_category")); v != "" { cat := strings.ToUpper(v) - if cat != string(domain.SubscriptionCategoryLearnEnglish) && - cat != string(domain.SubscriptionCategoryIELTS) && - cat != string(domain.SubscriptionCategoryDuolingo) { + if !domain.IsValidSubscriptionCategory(cat) { return domain.PaymentListFilter{}, fmt.Errorf("invalid plan_category") } filter.PlanCategory = &cat @@ -189,10 +187,6 @@ func parseUserListFilter(c *fiber.Ctx) (domain.UserFilter, error) { if err != nil { return domain.UserFilter{}, err } - initialAssessmentCompleted, err := parseOptionalBoolQuery(c, "initial_assessment_completed") - if err != nil { - return domain.UserFilter{}, err - } minLessonsCompleted, err := parseOptionalInt32Query(c, "min_lessons_completed") if err != nil { return domain.UserFilter{}, err @@ -213,9 +207,7 @@ func parseUserListFilter(c *fiber.Ctx) (domain.UserFilter, error) { planCategory := strings.TrimSpace(c.Query("plan_category")) if planCategory != "" { cat := strings.ToUpper(planCategory) - if cat != string(domain.SubscriptionCategoryLearnEnglish) && - cat != string(domain.SubscriptionCategoryIELTS) && - cat != string(domain.SubscriptionCategoryDuolingo) { + if !domain.IsValidSubscriptionCategory(cat) { return domain.UserFilter{}, fmt.Errorf("invalid plan_category") } planCategory = cat @@ -227,37 +219,36 @@ func parseUserListFilter(c *fiber.Ctx) (domain.UserFilter, error) { } return domain.UserFilter{ - Role: c.Query("role"), - Status: c.Query("status"), - Country: strings.TrimSpace(c.Query("country")), - Region: strings.TrimSpace(c.Query("region")), - SubscriptionStatus: subscriptionStatusFilter, - EducationLevel: strings.TrimSpace(c.Query("education_level")), - Occupation: strings.TrimSpace(c.Query("occupation")), - AgeGroup: strings.TrimSpace(c.Query("age_group")), - FavouriteTopic: strings.TrimSpace(c.Query("favourite_topic")), - LanguageGoal: strings.TrimSpace(c.Query("language_goal")), - LearningGoal: strings.TrimSpace(c.Query("learning_goal")), - KnowledgeLevel: strings.TrimSpace(c.Query("knowledge_level")), - PlanID: planID, - PlanCategory: planCategory, - AutoRenew: autoRenew, - HasEverPaid: hasEverPaid, - ExpiresWithinDays: expiresWithinDays, - LastLoginBefore: lastLoginBefore, - LastLoginAfter: lastLoginAfter, - DaysSinceLastLoginMin: daysSinceLastLoginMin, - DaysSinceLastLoginMax: daysSinceLastLoginMax, - ProfileCompleted: profileCompleted, - InitialAssessmentCompleted: initialAssessmentCompleted, - MinLessonsCompleted: minLessonsCompleted, - MinModulesCompleted: minModulesCompleted, - MinProfileCompletionPct: minProfileCompletionPct, - DevicePlatform: devicePlatform, - HasActiveDevice: hasActiveDevice, - Query: c.Query("query"), - CreatedBefore: createdBefore, - CreatedAfter: createdAfter, + Role: c.Query("role"), + Status: c.Query("status"), + Country: strings.TrimSpace(c.Query("country")), + Region: strings.TrimSpace(c.Query("region")), + SubscriptionStatus: subscriptionStatusFilter, + EducationLevel: strings.TrimSpace(c.Query("education_level")), + Occupation: strings.TrimSpace(c.Query("occupation")), + AgeGroup: strings.TrimSpace(c.Query("age_group")), + FavouriteTopic: strings.TrimSpace(c.Query("favourite_topic")), + LanguageGoal: strings.TrimSpace(c.Query("language_goal")), + LearningGoal: strings.TrimSpace(c.Query("learning_goal")), + KnowledgeLevel: strings.TrimSpace(c.Query("knowledge_level")), + PlanID: planID, + PlanCategory: planCategory, + AutoRenew: autoRenew, + HasEverPaid: hasEverPaid, + ExpiresWithinDays: expiresWithinDays, + LastLoginBefore: lastLoginBefore, + LastLoginAfter: lastLoginAfter, + DaysSinceLastLoginMin: daysSinceLastLoginMin, + DaysSinceLastLoginMax: daysSinceLastLoginMax, + ProfileCompleted: profileCompleted, + MinLessonsCompleted: minLessonsCompleted, + MinModulesCompleted: minModulesCompleted, + MinProfileCompletionPct: minProfileCompletionPct, + DevicePlatform: devicePlatform, + HasActiveDevice: hasActiveDevice, + Query: c.Query("query"), + CreatedBefore: createdBefore, + CreatedAfter: createdAfter, }, nil } @@ -385,9 +376,7 @@ func parseUserSubscriptionAdminFilterFields(c *fiber.Ctx) (domain.UserSubscripti } if v := strings.TrimSpace(c.Query("plan_category")); v != "" { cat := strings.ToUpper(v) - if cat != string(domain.SubscriptionCategoryLearnEnglish) && - cat != string(domain.SubscriptionCategoryIELTS) && - cat != string(domain.SubscriptionCategoryDuolingo) { + if !domain.IsValidSubscriptionCategory(cat) { return domain.UserSubscriptionAdminFilter{}, fmt.Errorf("invalid plan_category") } filter.PlanCategory = &cat diff --git a/internal/web_server/handlers/handlers.go b/internal/web_server/handlers/handlers.go index 9f733747..2daf6879 100644 --- a/internal/web_server/handlers/handlers.go +++ b/internal/web_server/handlers/handlers.go @@ -6,12 +6,11 @@ import ( dbgen "Rezina-Backend/gen/db" "Rezina-Backend/internal/config" "Rezina-Backend/internal/domain" - activitylogservice "Rezina-Backend/internal/services/activity_log" + activitylogservice "Rezina-Backend/internal/services/activity_log" "Rezina-Backend/internal/services/appversions" "Rezina-Backend/internal/services/arifpay" - "Rezina-Backend/internal/services/chapa" - "Rezina-Backend/internal/services/assessment" "Rezina-Backend/internal/services/authentication" + "Rezina-Backend/internal/services/chapa" cloudconvertservice "Rezina-Backend/internal/services/cloudconvert" "Rezina-Backend/internal/services/courses" "Rezina-Backend/internal/services/emailtemplates" @@ -23,7 +22,7 @@ import ( "Rezina-Backend/internal/services/lmsprogress" minioservice "Rezina-Backend/internal/services/minio" "Rezina-Backend/internal/services/modules" - notificationservice "Rezina-Backend/internal/services/notification" + notificationservice "Rezina-Backend/internal/services/notification" "Rezina-Backend/internal/services/personas" practicecontentservice "Rezina-Backend/internal/services/practicecontent" "Rezina-Backend/internal/services/practices" @@ -35,8 +34,8 @@ import ( "Rezina-Backend/internal/services/recommendation" "Rezina-Backend/internal/services/subscriptions" "Rezina-Backend/internal/services/team" - vimeoservice "Rezina-Backend/internal/services/vimeo" "Rezina-Backend/internal/services/videoengagement" + vimeoservice "Rezina-Backend/internal/services/vimeo" // referralservice "Rezina-Backend/internal/services/referal" @@ -52,50 +51,48 @@ import ( ) type Handler struct { - assessmentSvc *assessment.Service - questionsSvc *questions.Service - faqSvc *faqs.Service - appVersionSvc *appversions.Service - emailTemplateSvc *emailtemplates.Service - profileFieldOptionSvc *profilefieldoptions.Service - personaSvc *personas.Service - examPrepSvc *examprep.Service - programSvc *programs.Service - courseSvc *courses.Service - moduleSvc *modules.Service - lessonSvc *lessons.Service - lmsProgressSvc *lmsprogress.Service - practiceSvc *practices.Service - practiceContentSvc *practicecontentservice.Service - subscriptionsSvc *subscriptions.Service - arifpaySvc *arifpay.ArifpayService - chapaSvc *chapa.Service - logger *slog.Logger - settingSvc *settings.Service - notificationSvc *notificationservice.Service - learnerNotifSvc *learnernotifications.Service - userSvc *user.Service - transactionSvc *transaction.Service - recommendationSvc recommendation.RecommendationService - authSvc *authentication.Service - vimeoSvc *vimeoservice.Service - teamSvc *team.Service - activityLogSvc *activitylogservice.Service - issueReportingSvc *issuereporting.Service - cloudConvertSvc *cloudconvertservice.Service - minioSvc *minioservice.Service - ratingSvc *ratingsservice.Service - rbacSvc *rbacservice.Service - videoEngagementSvc *videoengagement.Service - jwtConfig jwtutil.JwtConfig - validator *customvalidator.CustomValidator - Cfg *config.Config - mongoLoggerSvc *zap.Logger - analyticsDB *dbgen.Queries + questionsSvc *questions.Service + faqSvc *faqs.Service + appVersionSvc *appversions.Service + emailTemplateSvc *emailtemplates.Service + profileFieldOptionSvc *profilefieldoptions.Service + personaSvc *personas.Service + examPrepSvc *examprep.Service + programSvc *programs.Service + courseSvc *courses.Service + moduleSvc *modules.Service + lessonSvc *lessons.Service + lmsProgressSvc *lmsprogress.Service + practiceSvc *practices.Service + practiceContentSvc *practicecontentservice.Service + subscriptionsSvc *subscriptions.Service + arifpaySvc *arifpay.ArifpayService + chapaSvc *chapa.Service + logger *slog.Logger + settingSvc *settings.Service + notificationSvc *notificationservice.Service + learnerNotifSvc *learnernotifications.Service + userSvc *user.Service + transactionSvc *transaction.Service + recommendationSvc recommendation.RecommendationService + authSvc *authentication.Service + vimeoSvc *vimeoservice.Service + teamSvc *team.Service + activityLogSvc *activitylogservice.Service + issueReportingSvc *issuereporting.Service + cloudConvertSvc *cloudconvertservice.Service + minioSvc *minioservice.Service + ratingSvc *ratingsservice.Service + rbacSvc *rbacservice.Service + videoEngagementSvc *videoengagement.Service + jwtConfig jwtutil.JwtConfig + validator *customvalidator.CustomValidator + Cfg *config.Config + mongoLoggerSvc *zap.Logger + analyticsDB *dbgen.Queries } func New( - assessmentSvc *assessment.Service, questionsSvc *questions.Service, faqSvc *faqs.Service, appVersionSvc *appversions.Service, @@ -137,46 +134,45 @@ func New( analyticsDB *dbgen.Queries, ) *Handler { return &Handler{ - assessmentSvc: assessmentSvc, - questionsSvc: questionsSvc, + questionsSvc: questionsSvc, faqSvc: faqSvc, appVersionSvc: appVersionSvc, emailTemplateSvc: emailTemplateSvc, profileFieldOptionSvc: profileFieldOptionSvc, - personaSvc: personaSvc, - examPrepSvc: examPrepSvc, - programSvc: programSvc, - courseSvc: courseSvc, - moduleSvc: moduleSvc, - lessonSvc: lessonSvc, - lmsProgressSvc: lmsProgressSvc, - practiceSvc: practiceSvc, - practiceContentSvc: practiceContentSvc, - subscriptionsSvc: subscriptionsSvc, - arifpaySvc: arifpaySvc, - chapaSvc: chapaSvc, - logger: logger, - settingSvc: settingSvc, - notificationSvc: notificationSvc, - learnerNotifSvc: learnerNotifSvc, - validator: validator, - userSvc: userSvc, - transactionSvc: transactionSvc, - recommendationSvc: recommendationSvc, - authSvc: authSvc, - vimeoSvc: vimeoSvc, - teamSvc: teamSvc, - activityLogSvc: activityLogSvc, - issueReportingSvc: issueReportingSvc, - cloudConvertSvc: cloudConvertSvc, - minioSvc: minioSvc, - ratingSvc: ratingSvc, - rbacSvc: rbacSvc, - videoEngagementSvc: videoEngagementSvc, - jwtConfig: jwtConfig, - Cfg: cfg, - mongoLoggerSvc: mongoLoggerSvc, - analyticsDB: analyticsDB, + personaSvc: personaSvc, + examPrepSvc: examPrepSvc, + programSvc: programSvc, + courseSvc: courseSvc, + moduleSvc: moduleSvc, + lessonSvc: lessonSvc, + lmsProgressSvc: lmsProgressSvc, + practiceSvc: practiceSvc, + practiceContentSvc: practiceContentSvc, + subscriptionsSvc: subscriptionsSvc, + arifpaySvc: arifpaySvc, + chapaSvc: chapaSvc, + logger: logger, + settingSvc: settingSvc, + notificationSvc: notificationSvc, + learnerNotifSvc: learnerNotifSvc, + validator: validator, + userSvc: userSvc, + transactionSvc: transactionSvc, + recommendationSvc: recommendationSvc, + authSvc: authSvc, + vimeoSvc: vimeoSvc, + teamSvc: teamSvc, + activityLogSvc: activityLogSvc, + issueReportingSvc: issueReportingSvc, + cloudConvertSvc: cloudConvertSvc, + minioSvc: minioSvc, + ratingSvc: ratingSvc, + rbacSvc: rbacSvc, + videoEngagementSvc: videoEngagementSvc, + jwtConfig: jwtConfig, + Cfg: cfg, + mongoLoggerSvc: mongoLoggerSvc, + analyticsDB: analyticsDB, } } diff --git a/internal/web_server/handlers/initial_assessment.go b/internal/web_server/handlers/initial_assessment.go deleted file mode 100644 index 30a0dd1b..00000000 --- a/internal/web_server/handlers/initial_assessment.go +++ /dev/null @@ -1,414 +0,0 @@ -package handlers - -import ( - "Rezina-Backend/internal/domain" - "Rezina-Backend/internal/services/assessment" - "errors" - "fmt" - "strconv" - - "github.com/gofiber/fiber/v2" - "github.com/jackc/pgx/v5" -) - -// CreateAssessmentQuestion godoc -// @Summary Create assessment question -// @Description Creates a new assessment question using the unified questions system -// @Tags assessment-question -// @Accept json -// @Produce json -// @Param body body createQuestionReq true "Create question payload" -// @Success 201 {object} domain.Response -// @Failure 400 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/assessment/questions [post] -func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error { - var req createQuestionReq - if err := c.BodyParser(&req); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid request body", - Error: err.Error(), - }) - } - - questionType := normalizeRuntimeQuestionType(req.QuestionType) - questionText, err := resolveStoredQuestionText(questionType, req.QuestionText, req.DynamicPayload, "") - if err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid question_text", - Error: err.Error(), - }) - } - - var options []domain.CreateQuestionOptionInput - for _, opt := range req.Options { - options = append(options, domain.CreateQuestionOptionInput{ - OptionText: opt.OptionText, - OptionOrder: opt.OptionOrder, - IsCorrect: opt.IsCorrect, - }) - } - - var shortAnswers []domain.CreateShortAnswerInput - for _, sa := range req.ShortAnswers { - shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{ - AcceptableAnswer: sa.AcceptableAnswer, - MatchType: sa.MatchType, - }) - } - - input := domain.CreateQuestionInput{ - QuestionText: questionText, - QuestionType: questionType, - QuestionTypeDefinitionID: req.QuestionTypeDefinitionID, - DynamicPayload: req.DynamicPayload, - DifficultyLevel: req.DifficultyLevel, - Points: req.Points, - Explanation: req.Explanation, - Tips: req.Tips, - VoicePrompt: req.VoicePrompt, - SampleAnswerVoicePrompt: req.SampleAnswerVoicePrompt, - Status: req.Status, - Options: options, - ShortAnswers: shortAnswers, - } - - question, err := h.assessmentSvc.CreateQuestion(c.Context(), input) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to create assessment question", - Error: err.Error(), - }) - } - - h.recordActivity(c, domain.ActionAssessmentQuestionCreated, domain.ResourceAssessmentQuestion, &question.ID, fmt.Sprintf("Created assessment question ID: %d", question.ID), nil) - - return c.Status(fiber.StatusCreated).JSON(domain.Response{ - Message: "Assessment question created successfully", - StatusCode: fiber.StatusCreated, - Success: true, - Data: questionRes{ - ID: question.ID, - QuestionText: questionTextField(question.QuestionType, question.QuestionText), - QuestionType: question.QuestionType, - Status: question.Status, - CreatedAt: question.CreatedAt.String(), - }, - }) -} - -// ListAssessmentQuestions godoc -// @Summary List assessment questions for a CEFR level -// @Description Returns published questions from the INITIAL_ASSESSMENT set for the given CEFR level (default A1) -// @Tags assessment-question -// @Produce json -// @Param level query string false "CEFR level A1–C2 (default A1)" -// @Success 200 {array} domain.QuestionWithDetails -// @Failure 400 {object} domain.ErrorResponse -// @Failure 404 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/assessment/questions [get] -func (h *Handler) ListAssessmentQuestions(c *fiber.Ctx) error { - level := c.Query("level", "A1") - questions, err := h.assessmentSvc.ListQuestions(c.Context(), level) - if err != nil { - if errors.Is(err, assessment.ErrPlacementSetNotFound) { - return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ - Message: "Placement assessment not found for level", - Error: err.Error(), - }) - } - if _, normErr := domain.NormalizeCEFRLevel(level); normErr != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid level", - Error: normErr.Error(), - }) - } - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to fetch assessment questions", - Error: err.Error(), - }) - } - - catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context()) - var questionResponses []questionRes - for _, q := range questions { - res := buildQuestionRes(q, catalog) - for i := range res.Options { - res.Options[i].IsCorrect = false - } - res.ShortAnswers = nil - res.AudioCorrectAnswerText = nil - if res.DynamicPayload != nil { - res.DynamicPayload = scrubDynamicCorrectness(res.DynamicPayload) - } - questionResponses = append(questionResponses, res) - } - - return c.Status(fiber.StatusOK).JSON(domain.Response{ - Message: "Questions fetched successfully", - Data: questionResponses, - Success: true, - StatusCode: 200, - }) -} - -// GetAssessmentQuestionByID godoc -// @Summary Get assessment question by ID -// @Description Returns a single assessment question with its options or answer -// @Tags assessment-question -// @Produce json -// @Param id path int true "Question ID" -// @Success 200 {object} domain.QuestionWithDetails -// @Failure 400 {object} domain.ErrorResponse -// @Failure 404 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/assessment/questions/{id} [get] -func (h *Handler) GetAssessmentQuestionByID(c *fiber.Ctx) error { - idStr := c.Params("id") - id, err := strconv.ParseInt(idStr, 10, 64) - if err != nil || id <= 0 { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid question ID", - Error: "question ID must be a positive integer", - }) - } - - question, err := h.assessmentSvc.GetQuestionByID(c.Context(), id) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to fetch assessment question", - Error: err.Error(), - }) - } - - catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context()) - res := buildQuestionRes(question, catalog) - for i := range res.Options { - res.Options[i].IsCorrect = false - } - res.ShortAnswers = nil - res.AudioCorrectAnswerText = nil - if res.DynamicPayload != nil { - res.DynamicPayload = scrubDynamicCorrectness(res.DynamicPayload) - } - return c.Status(fiber.StatusOK).JSON(domain.Response{ - Message: "Question fetched successfully", - Data: res, - Success: true, - StatusCode: 200, - }) -} - -func scrubDynamicCorrectness(payload *domain.DynamicQuestionPayload) *domain.DynamicQuestionPayload { - if payload == nil { - return nil - } - clone := *payload - clone.Stimulus = scrubDynamicElements(payload.Stimulus) - clone.Response = scrubDynamicElements(payload.Response) - return &clone -} - -func scrubDynamicElements(els []domain.DynamicElementInstance) []domain.DynamicElementInstance { - if len(els) == 0 { - return els - } - out := make([]domain.DynamicElementInstance, len(els)) - for i, el := range els { - out[i] = el - m, ok := el.Value.(map[string]interface{}) - if !ok { - continue - } - rawOpts, ok := m["options"].([]interface{}) - if !ok { - continue - } - copied := make(map[string]interface{}, len(m)) - for k, v := range m { - copied[k] = v - } - opts := make([]interface{}, 0, len(rawOpts)) - for _, o := range rawOpts { - om, ok := o.(map[string]interface{}) - if !ok { - opts = append(opts, o) - continue - } - clean := make(map[string]interface{}, len(om)) - for k, v := range om { - if k == "is_correct" { - continue - } - clean[k] = v - } - opts = append(opts, clean) - } - copied["options"] = opts - out[i].Value = copied - } - return out -} - -type submitPlacementAssessmentReq struct { - Level string `json:"level" validate:"required"` - Answers []domain.PlacementAnswerInput `json:"answers"` -} - -// GetPlacementSession godoc -// @Summary Get progressive placement session -// @Description Returns the learner's next CEFR level to attempt and published levels -// @Tags assessment -// @Produce json -// @Success 200 {object} domain.Response -// @Failure 401 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/assessment/session [get] -func (h *Handler) GetPlacementSession(c *fiber.Ctx) error { - userID, ok := c.Locals("user_id").(int64) - if !ok || userID <= 0 { - return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ - Message: "Unauthorized", - Error: "user context required", - }) - } - session, err := h.assessmentSvc.GetPlacementSession(c.Context(), userID) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to load placement session", - Error: err.Error(), - }) - } - return c.JSON(domain.Response{ - Message: "Placement session fetched successfully", - Data: session, - Success: true, - }) -} - -// SubmitPlacementAssessment godoc -// @Summary Submit answers for one CEFR placement level -// @Description Grades the level set against its pass threshold, advances to the next level on pass, or finalizes knowledge_level on fail / C2 pass -// @Tags assessment -// @Accept json -// @Produce json -// @Param body body submitPlacementAssessmentReq true "Level + placement answers" -// @Success 200 {object} domain.Response -// @Failure 400 {object} domain.ErrorResponse -// @Failure 404 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/assessment/submit [post] -func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error { - userID, ok := c.Locals("user_id").(int64) - if !ok || userID <= 0 { - return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ - Message: "Unauthorized", - Error: "user context required", - }) - } - - var req submitPlacementAssessmentReq - if err := c.BodyParser(&req); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid request body", - Error: err.Error(), - }) - } - - result, err := h.assessmentSvc.SubmitPlacement(c.Context(), userID, req.Level, req.Answers) - if err != nil { - if errors.Is(err, assessment.ErrPlacementSetNotFound) || errors.Is(err, pgx.ErrNoRows) { - return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ - Message: "Placement assessment not found", - Error: err.Error(), - }) - } - if errors.Is(err, assessment.ErrNoGradableQuestions) { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Placement assessment has no gradable questions", - Error: err.Error(), - }) - } - if errors.Is(err, assessment.ErrPlacementLevelRequired) || - errors.Is(err, assessment.ErrPlacementLevelMismatch) || - errors.Is(err, assessment.ErrPlacementAlreadyComplete) { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Unable to submit placement assessment", - Error: err.Error(), - }) - } - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Unable to submit placement assessment", - Error: err.Error(), - }) - } - - h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &userID, - fmt.Sprintf("Placement level %s scored %.1f%% (passed=%v, completed=%v, knowledge_level=%s)", - result.LevelAttempted, result.ScorePercent, result.Passed, result.Completed, result.KnowledgeLevel), nil) - - return c.JSON(domain.Response{ - Message: "Placement assessment graded successfully", - Data: result, - Success: true, - }) -} - -// ListInitialAssessmentLevelThresholds godoc -// @Summary List per-level pass thresholds for placement -// @Tags assessment -// @Produce json -// @Success 200 {object} domain.Response -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/admin/assessment/level-thresholds [get] -func (h *Handler) ListInitialAssessmentLevelThresholds(c *fiber.Ctx) error { - rows, err := h.assessmentSvc.ListLevelThresholds(c.Context()) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to load level thresholds", - Error: err.Error(), - }) - } - return c.JSON(domain.Response{ - Message: "Level thresholds fetched successfully", - Data: rows, - Success: true, - }) -} - -type updateLevelThresholdsReq struct { - Thresholds []domain.InitialAssessmentLevelThreshold `json:"thresholds"` -} - -// UpdateInitialAssessmentLevelThresholds godoc -// @Summary Update per-level pass thresholds for placement -// @Tags assessment -// @Accept json -// @Produce json -// @Param body body updateLevelThresholdsReq true "Pass thresholds A1–C2 (min_percent)" -// @Success 200 {object} domain.Response -// @Failure 400 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/admin/assessment/level-thresholds [put] -func (h *Handler) UpdateInitialAssessmentLevelThresholds(c *fiber.Ctx) error { - var req updateLevelThresholdsReq - if err := c.BodyParser(&req); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid request body", - Error: err.Error(), - }) - } - rows, err := h.assessmentSvc.UpdateLevelThresholds(c.Context(), req.Thresholds) - if err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Unable to update level thresholds", - Error: err.Error(), - }) - } - return c.JSON(domain.Response{ - Message: "Level thresholds updated successfully", - Data: rows, - Success: true, - }) -} diff --git a/internal/web_server/handlers/lms_progress_handler.go b/internal/web_server/handlers/lms_progress_handler.go index fcf17a9e..aeb90831 100644 --- a/internal/web_server/handlers/lms_progress_handler.go +++ b/internal/web_server/handlers/lms_progress_handler.go @@ -268,7 +268,7 @@ func (h *Handler) listAllPrograms(ctx context.Context, publishedOnly bool) ([]do offset int32 ) for { - items, total, err := h.programSvc.List(ctx, publishedOnly, string(domain.SubscriptionCategoryLearnEnglish), lmsProgressSummaryPageSize, offset) + items, total, err := h.programSvc.List(ctx, publishedOnly, string(domain.SubscriptionCategoryEducation), lmsProgressSummaryPageSize, offset) if err != nil { return nil, err } diff --git a/internal/web_server/handlers/payments_admin.go b/internal/web_server/handlers/payments_admin.go index abf9ad98..270b7f64 100644 --- a/internal/web_server/handlers/payments_admin.go +++ b/internal/web_server/handlers/payments_admin.go @@ -78,7 +78,7 @@ type listAdminPaymentsRes struct { // @Param provider query string false "Payment provider (CHAPA, ARIFPAY)" // @Param payment_method query string false "Alias for provider" // @Param currency query string false "Currency code (e.g. ETB)" -// @Param plan_category query string false "Plan category (LEARN_ENGLISH, IELTS, DUOLINGO)" +// @Param plan_category query string false "Plan category (EDUCATION)" // @Param reference query string false "Search session_id, nonce, or transaction_id" // @Param created_from query string false "Created at from (RFC3339 or YYYY-MM-DD)" // @Param created_to query string false "Created at to (exclusive, RFC3339 or YYYY-MM-DD)" diff --git a/internal/web_server/handlers/practice_full_update_handler.go b/internal/web_server/handlers/practice_full_update_handler.go index 9f1cfd4d..62c66749 100644 --- a/internal/web_server/handlers/practice_full_update_handler.go +++ b/internal/web_server/handlers/practice_full_update_handler.go @@ -240,7 +240,6 @@ func (h *Handler) GetLmsPracticeFull(c *fiber.Ctx) error { // @Success 200 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse -// @Router /api/v1/exam-prep/practices/{id}/full [get] func (h *Handler) GetExamPrepPracticeFull(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { @@ -382,7 +381,6 @@ func (h *Handler) UpdateLmsPracticeFull(c *fiber.Ctx) error { // @Success 200 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse -// @Router /api/v1/exam-prep/practices/{id}/full [put] func (h *Handler) UpdateExamPrepPracticeFull(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { diff --git a/internal/web_server/handlers/program_handler.go b/internal/web_server/handlers/program_handler.go index a47254b7..7a778b9a 100644 --- a/internal/web_server/handlers/program_handler.go +++ b/internal/web_server/handlers/program_handler.go @@ -2,8 +2,8 @@ package handlers import ( "Rezina-Backend/internal/domain" - "Rezina-Backend/internal/services/programs" lmsprogress "Rezina-Backend/internal/services/lmsprogress" + "Rezina-Backend/internal/services/programs" "context" "errors" "strconv" @@ -74,7 +74,7 @@ func (h *Handler) ListPrograms(c *fiber.Ctx) error { role := c.Locals("role").(domain.Role) category := "" if role.IsCustomerLearnerRole() { - category = string(domain.SubscriptionCategoryLearnEnglish) + category = string(domain.SubscriptionCategoryEducation) } items, total, err := h.programSvc.List(c.Context(), publishedOnly, category, int32(limit), int32(offset)) if err != nil { diff --git a/internal/web_server/handlers/questions.go b/internal/web_server/handlers/questions.go index fa31b5cb..eacc35d6 100644 --- a/internal/web_server/handlers/questions.go +++ b/internal/web_server/handlers/questions.go @@ -757,7 +757,7 @@ func (h *Handler) DeleteQuestion(c *fiber.Ctx) error { type createQuestionSetReq struct { Title string `json:"title" validate:"required"` Description *string `json:"description"` - SetType string `json:"set_type" validate:"required,oneof=PRACTICE INITIAL_ASSESSMENT QUIZ EXAM SURVEY CAPSTONE"` + SetType string `json:"set_type" validate:"required,oneof=PRACTICE QUIZ EXAM SURVEY CAPSTONE"` OwnerType *string `json:"owner_type"` OwnerID *int64 `json:"owner_id"` BannerImage *string `json:"banner_image"` @@ -792,38 +792,6 @@ type listQuestionSetsRes struct { TotalCount int64 `json:"total_count"` } -var validInitialAssessmentLevels = map[string]struct{}{ - "A1": {}, - "A2": {}, - "B1": {}, - "B2": {}, - "C1": {}, - "C2": {}, -} - -// normalizeInitialAssessmentDescription stores the CEFR band for per-level placement sets. -func normalizeInitialAssessmentDescription(description *string) string { - if description == nil { - return "" - } - text := strings.TrimSpace(*description) - if text == "" { - return "" - } - upper := strings.ToUpper(text) - if _, ok := validInitialAssessmentLevels[upper]; ok { - return upper - } - return text -} - -func requireInitialAssessmentCEFRDescription(description string) error { - if _, err := domain.NormalizeCEFRLevel(description); err != nil { - return fmt.Errorf("INITIAL_ASSESSMENT description must be a CEFR level (A1–C2)") - } - return nil -} - func isSequenceGatedPractice(set domain.QuestionSet) bool { if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) || set.OwnerType == nil { return false @@ -882,22 +850,6 @@ func (h *Handler) CreateQuestionSet(c *fiber.Ctx) error { Error: err.Error(), }) } - if strings.EqualFold(req.SetType, string(domain.QuestionSetTypeInitialAssessment)) { - normalized := normalizeInitialAssessmentDescription(req.Description) - if err := requireInitialAssessmentCEFRDescription(normalized); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid placement level", - Error: err.Error(), - }) - } - req.Description = &normalized - if req.OwnerType == nil || strings.TrimSpace(*req.OwnerType) == "" { - standalone := "STANDALONE" - req.OwnerType = &standalone - req.OwnerID = nil - } - } - input := domain.CreateQuestionSetInput{ Title: req.Title, Description: req.Description, @@ -1017,7 +969,7 @@ func (h *Handler) GetQuestionSetByID(c *fiber.Ctx) error { // @Description Returns a paginated list of question sets filtered by type // @Tags question-sets // @Produce json -// @Param set_type query string true "Set type (PRACTICE, INITIAL_ASSESSMENT, QUIZ, EXAM, SURVEY, CAPSTONE)" +// @Param set_type query string true "Set type (PRACTICE, QUIZ, EXAM, SURVEY, CAPSTONE)" // @Param limit query int false "Limit" default(10) // @Param offset query int false "Offset" default(0) // @Success 200 {object} domain.Response @@ -1196,21 +1148,6 @@ func (h *Handler) UpdateQuestionSet(c *fiber.Ctx) error { title = *req.Title } - if strings.EqualFold(existingSet.SetType, string(domain.QuestionSetTypeInitialAssessment)) { - effectiveDescription := existingSet.Description - if req.Description != nil { - effectiveDescription = req.Description - } - normalized := normalizeInitialAssessmentDescription(effectiveDescription) - if err := requireInitialAssessmentCEFRDescription(normalized); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid placement level", - Error: err.Error(), - }) - } - req.Description = &normalized - } - status := req.Status if status == nil { status = &existingSet.Status diff --git a/internal/web_server/handlers/subscription_checkout_link.go b/internal/web_server/handlers/subscription_checkout_link.go index df1e0159..d779a93c 100644 --- a/internal/web_server/handlers/subscription_checkout_link.go +++ b/internal/web_server/handlers/subscription_checkout_link.go @@ -90,7 +90,7 @@ func (h *Handler) RequestSubscriptionCheckoutLink(c *fiber.Ctx) error { if cat != "" && !domain.IsValidSubscriptionCategory(cat) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid category", - Error: "category must be one of: LEARN_ENGLISH, IELTS, DUOLINGO", + Error: "category must be EDUCATION", }) } planCategory = cat diff --git a/internal/web_server/handlers/subscriptions.go b/internal/web_server/handlers/subscriptions.go index 1d0c5e61..bcbf07c5 100644 --- a/internal/web_server/handlers/subscriptions.go +++ b/internal/web_server/handlers/subscriptions.go @@ -22,7 +22,7 @@ const duplicateSubscriptionPlanPeriodMessage = "Only one subscription plan is al type createPlanReq struct { Name string `json:"name" validate:"required"` Description *string `json:"description"` - Category string `json:"category" validate:"required,oneof=LEARN_ENGLISH IELTS DUOLINGO"` + Category string `json:"category" validate:"required,oneof=EDUCATION"` DurationValue int32 `json:"duration_value"` DurationUnit string `json:"duration_unit"` Price float64 `json:"price" validate:"gte=0"` @@ -35,7 +35,7 @@ type createPlanReq struct { type updatePlanReq struct { Name *string `json:"name"` Description *string `json:"description"` - Category *string `json:"category" validate:"omitempty,oneof=LEARN_ENGLISH IELTS DUOLINGO"` + Category *string `json:"category" validate:"omitempty,oneof=EDUCATION"` DurationValue *int32 `json:"duration_value"` DurationUnit *string `json:"duration_unit"` Price *float64 `json:"price"` @@ -198,11 +198,11 @@ func (h *Handler) CreateSubscriptionPlan(c *fiber.Ctx) error { // ListSubscriptionPlans godoc // @Summary List subscription plans -// @Description Returns subscription plans. Optional category filter: LEARN_ENGLISH, IELTS, or DUOLINGO. +// @Description Returns subscription plans. Optional category filter: EDUCATION. // @Tags subscriptions // @Produce json // @Param active_only query bool false "Return only active plans (default true)" -// @Param category query string false "Filter by plan category (LEARN_ENGLISH, IELTS, DUOLINGO)" +// @Param category query string false "Filter by plan category (EDUCATION)" // @Success 200 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse @@ -216,7 +216,7 @@ func (h *Handler) ListSubscriptionPlans(c *fiber.Ctx) error { if !domain.IsValidSubscriptionCategory(normalized) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid category", - Error: "category must be one of: LEARN_ENGLISH, IELTS, DUOLINGO", + Error: "category must be EDUCATION", }) } categoryFilter = &normalized diff --git a/internal/web_server/handlers/user.go b/internal/web_server/handlers/user.go index f6f07a28..05002902 100644 --- a/internal/web_server/handlers/user.go +++ b/internal/web_server/handlers/user.go @@ -184,7 +184,7 @@ func (h *Handler) UpdateUser(c *fiber.Ctx) error { // UpdateUserKnowledgeLevel godoc // @Summary Update user's knowledge level -// @Description Updates the authenticated learner's knowledge level (legacy manual path). Prefer POST /assessment/submit for graded placement. +// @Description Updates the authenticated learner's self-reported knowledge level. // @Tags user // @Accept json // @Produce json @@ -548,7 +548,6 @@ func (h *Handler) GetAllUsers(c *fiber.Ctx) error { EducationLevel: u.EducationLevel, Country: u.Country, Region: u.Region, - InitialAssessmentCompleted: u.InitialAssessmentCompleted, NickName: u.NickName, Occupation: u.Occupation, LearningGoal: u.LearningGoal, @@ -1843,14 +1842,13 @@ func (h *Handler) GetUserByID(c *fiber.Ctx) error { } return "" }(), - LearningGoal: user.LearningGoal, - LanguageGoal: user.LanguageGoal, - LanguageChallange: user.LanguageChallange, - Gender: user.Gender, - InitialAssessmentCompleted: user.InitialAssessmentCompleted, - NickName: user.NickName, - Occupation: user.Occupation, - FavouriteTopic: user.FavouriteTopic, + LearningGoal: user.LearningGoal, + LanguageGoal: user.LanguageGoal, + LanguageChallange: user.LanguageChallange, + Gender: user.Gender, + NickName: user.NickName, + Occupation: user.Occupation, + FavouriteTopic: user.FavouriteTopic, // UserName: user.UserName, Email: user.Email, PhoneNumber: user.PhoneNumber, diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index 05640e16..d8dd68af 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -13,7 +13,6 @@ import ( func (a *App) initAppRoutes() { h := handlers.New( - a.assessmentSvc, a.questionsSvc, a.faqSvc, a.appVersionSvc, @@ -92,53 +91,6 @@ func (a *App) initAppRoutes() { groupV1.Put("/programs/:id", a.authMiddleware, a.RequirePermission("programs.update"), h.UpdateProgram) groupV1.Delete("/programs/:id", a.authMiddleware, a.RequirePermission("programs.delete"), h.DeleteProgram) - // Exam prep (schema exam_prep — separate from LMS Learn English). Students need an active subscription. - examPrep := groupV1.Group("/exam-prep", a.authMiddleware, a.RequireExamPrepSubscription()) - examPrep.Post("/catalog-courses", a.RequirePermission("exam_prep.catalog_courses.create"), h.CreateExamPrepCatalogCourse) - examPrep.Get("/catalog-courses", a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses) - examPrep.Put("/catalog-courses/reorder", a.RequirePermission("exam_prep.catalog_courses.reorder"), h.ReorderExamPrepCatalogCourses) - examPrep.Get("/catalog-courses/:id", a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID) - examPrep.Put("/catalog-courses/:id", a.RequirePermission("exam_prep.catalog_courses.update"), h.UpdateExamPrepCatalogCourse) - examPrep.Delete("/catalog-courses/:id", a.RequirePermission("exam_prep.catalog_courses.delete"), h.DeleteExamPrepCatalogCourse) - examPrep.Post("/catalog-courses/:catalogCourseId/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForCatalogCourse) - examPrep.Get("/catalog-courses/:catalogCourseId/practices", a.RequirePermission("exam_prep.practices.list_by_catalog_course"), h.ListExamPrepPracticesByCatalogCourse) - - examPrep.Post("/catalog-courses/:catalogCourseId/units", a.RequirePermission("exam_prep.units.create"), h.CreateExamPrepUnit) - examPrep.Get("/catalog-courses/:catalogCourseId/units", a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse) - examPrep.Put("/catalog-courses/:catalogCourseId/units/reorder", a.RequirePermission("exam_prep.units.reorder"), h.ReorderExamPrepUnitsInCatalogCourse) - - examPrep.Post("/units/:unitId/modules", a.RequirePermission("exam_prep.modules.create"), h.CreateExamPrepModule) - examPrep.Get("/units/:unitId/modules", a.RequirePermission("exam_prep.modules.list"), h.ListExamPrepModulesByUnit) - examPrep.Put("/units/:unitId/modules/reorder", a.RequirePermission("exam_prep.modules.reorder"), h.ReorderExamPrepModulesInUnit) - - examPrep.Post("/modules/:moduleId/lessons", a.RequirePermission("exam_prep.lessons.create"), h.CreateExamPrepLesson) - examPrep.Get("/modules/:moduleId/lessons", a.RequirePermission("exam_prep.lessons.list_by_module"), h.ListExamPrepLessonsByUnitModule) - examPrep.Put("/modules/:moduleId/lessons/reorder", a.RequirePermission("exam_prep.lessons.reorder"), h.ReorderExamPrepLessonsInUnitModule) - examPrep.Post("/lessons/:lessonId/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPractice) - examPrep.Get("/lessons/:lessonId/practices", a.RequirePermission("exam_prep.practices.list_by_lesson"), h.ListExamPrepPracticesByLesson) - examPrep.Post("/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeFromInput) - examPrep.Get("/practices", a.RequirePermission("exam_prep.practices.list"), h.ListAllExamPrepPractices) - examPrep.Get("/practices/:id", a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeByID) - examPrep.Get("/practices/:id/full", a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull) - examPrep.Put("/practices/:id", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice) - examPrep.Put("/practices/:id/parents", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents) - examPrep.Delete("/practices/:id/parents/:parentKind/:parentId", a.RequirePermission("exam_prep.practices.update"), h.UnlinkExamPrepPracticeParent) - examPrep.Put("/practices/:id/full", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull) - examPrep.Delete("/practices/:id", a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice) - examPrep.Get("/lessons/:id", a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID) - examPrep.Put("/lessons/:id", a.RequirePermission("exam_prep.lessons.update"), h.UpdateExamPrepLesson) - examPrep.Delete("/lessons/:id", a.RequirePermission("exam_prep.lessons.delete"), h.DeleteExamPrepLesson) - - examPrep.Get("/modules/:id", a.RequirePermission("exam_prep.modules.get"), h.GetExamPrepModuleByID) - examPrep.Put("/modules/:id", a.RequirePermission("exam_prep.modules.update"), h.UpdateExamPrepModule) - examPrep.Delete("/modules/:id", a.RequirePermission("exam_prep.modules.delete"), h.DeleteExamPrepModule) - - examPrep.Get("/units/:id", a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID) - examPrep.Put("/units/:id", a.RequirePermission("exam_prep.units.update"), h.UpdateExamPrepUnit) - examPrep.Delete("/units/:id", a.RequirePermission("exam_prep.units.delete"), h.DeleteExamPrepUnit) - examPrep.Post("/units/:unitId/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForUnit) - examPrep.Get("/units/:unitId/practices", a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListExamPrepPracticesByUnit) - // Courses groupV1.Post("/programs/:id/courses", a.authMiddleware, a.RequirePermission("courses.create"), h.CreateCourse) groupV1.Put("/programs/:id/courses/reorder", a.authMiddleware, a.RequirePermission("courses.reorder"), h.ReorderCoursesInProgram) @@ -194,13 +146,6 @@ func (a *App) initAppRoutes() { groupV1.Post("/questions/audio-answer", a.authMiddleware, h.SubmitAudioAnswer) // Assessment questions (public list) + authenticated submit - groupV1.Post("/assessment/questions", h.CreateAssessmentQuestion) - groupV1.Get("/assessment/questions", h.ListAssessmentQuestions) - groupV1.Get("/assessment/questions/:id", h.GetAssessmentQuestionByID) - groupV1.Get("/assessment/session", a.authMiddleware, h.GetPlacementSession) - groupV1.Post("/assessment/submit", a.authMiddleware, h.SubmitPlacementAssessment) - groupV1.Get("/admin/assessment/level-thresholds", a.authMiddleware, a.RequirePermission("settings.get"), h.ListInitialAssessmentLevelThresholds) - groupV1.Put("/admin/assessment/level-thresholds", a.authMiddleware, a.RequirePermission("settings.update"), h.UpdateInitialAssessmentLevelThresholds) // Questions groupV1.Post("/questions", a.authMiddleware, a.RequirePermission("questions.create"), h.CreateQuestion)