Adapt LMS backend for makeup education

This commit is contained in:
Yared Yemane 2026-10-20 13:41:40 +03:00
parent 2134b953ab
commit a1f012774e
62 changed files with 9489 additions and 6132 deletions

View File

@ -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

View File

@ -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,

View File

@ -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'),

View File

@ -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');

View File

@ -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;

View File

@ -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;

View File

@ -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);

View File

@ -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'));

View File

@ -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');

View File

@ -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;

View File

@ -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;

View File

@ -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,

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -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 <token>
```
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 <access_token>
```
**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 <access_token>
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 <token>
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<T> {
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<T>(
path: string,
opts: RequestInit & { token?: string } = {},
): Promise<T> {
const headers: Record<string, string> = {
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<PlacementQuestion[]>("/assessment/questions");
}
export function submitPlacement(token: string, answers: PlacementAnswer[]) {
return api<PlacementSubmitResult>("/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<PlacementQuestion[]>([]);
const [answers, setAnswers] = useState<Record<number, number>>({}); // questionId → optionId
const [result, setResult] = useState<PlacementSubmitResult | null>(null);
const [error, setError] = useState<string | null>(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.

View File

@ -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.

View File

@ -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 |

View File

@ -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.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -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"`

View File

@ -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

View File

@ -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,

View File

@ -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
}

View File

@ -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 }

View File

@ -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"`

View File

@ -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 {

View File

@ -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

View File

@ -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"`
}

View File

@ -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{}

View File

@ -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

View File

@ -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(

View File

@ -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.

View File

@ -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
}

View File

@ -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,

View File

@ -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,

View File

@ -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,
}
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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,
}
}

View File

@ -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):

View File

@ -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)
}

View File

@ -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,

View File

@ -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()

View File

@ -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()
}

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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,
}
}

View File

@ -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,
})
}

View File

@ -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
}

View File

@ -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)"

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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,

View File

@ -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)