Support progressive placement with one assessment set per CEFR level.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9f10bc161d
commit
34307d7717
16
db/migrations/000102_initial_assessment_per_level.down.sql
Normal file
16
db/migrations/000102_initial_assessment_per_level.down.sql
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level;
|
||||
DROP TABLE IF EXISTS user_initial_assessment_progress;
|
||||
|
||||
-- Restore previous banding-style defaults (best-effort).
|
||||
UPDATE initial_assessment_level_thresholds AS t
|
||||
SET min_percent = v.min_percent, updated_at = NOW()
|
||||
FROM (
|
||||
VALUES
|
||||
('A1', 0),
|
||||
('A2', 17),
|
||||
('B1', 34),
|
||||
('B2', 51),
|
||||
('C1', 68),
|
||||
('C2', 85)
|
||||
) AS v(level, min_percent)
|
||||
WHERE t.level = v.level;
|
||||
76
db/migrations/000102_initial_assessment_per_level.up.sql
Normal file
76
db/migrations/000102_initial_assessment_per_level.up.sql
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
-- Progressive placement: one INITIAL_ASSESSMENT question set per CEFR level (description = A1–C2).
|
||||
-- Threshold min_percent becomes the pass mark for that level's set.
|
||||
|
||||
-- Normalize legacy single "PLACEMENT" / empty sets onto A1, keep at most one published A1.
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
id,
|
||||
ROW_NUMBER() OVER (
|
||||
ORDER BY
|
||||
CASE WHEN UPPER(TRIM(status)) = 'PUBLISHED' THEN 0 ELSE 1 END,
|
||||
created_at DESC
|
||||
) AS rn
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
)
|
||||
UPDATE question_sets qs
|
||||
SET
|
||||
description = 'A1',
|
||||
status = CASE
|
||||
WHEN ranked.rn = 1 THEN qs.status
|
||||
WHEN UPPER(TRIM(qs.status)) = 'PUBLISHED' THEN 'DRAFT'
|
||||
ELSE qs.status
|
||||
END,
|
||||
updated_at = NOW()
|
||||
FROM ranked
|
||||
WHERE qs.id = ranked.id
|
||||
AND (
|
||||
qs.description IS NULL
|
||||
OR TRIM(qs.description) = ''
|
||||
OR UPPER(TRIM(qs.description)) = 'PLACEMENT'
|
||||
OR UPPER(TRIM(qs.description)) NOT IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
|
||||
);
|
||||
|
||||
WITH pubs AS (
|
||||
SELECT
|
||||
id,
|
||||
UPPER(TRIM(description)) AS level,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY UPPER(TRIM(description))
|
||||
ORDER BY created_at DESC
|
||||
) AS rn
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND UPPER(TRIM(status)) = 'PUBLISHED'
|
||||
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
|
||||
)
|
||||
UPDATE question_sets qs
|
||||
SET status = 'DRAFT', updated_at = NOW()
|
||||
FROM pubs
|
||||
WHERE qs.id = pubs.id
|
||||
AND pubs.rn > 1;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS 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');
|
||||
|
||||
-- Pass marks for each level set (replaces single-test score banding defaults).
|
||||
UPDATE initial_assessment_level_thresholds
|
||||
SET min_percent = 70, updated_at = NOW();
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_initial_assessment_progress (
|
||||
user_id BIGINT PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
next_level VARCHAR(8) NOT NULL DEFAULT 'A1',
|
||||
highest_passed_level VARCHAR(8),
|
||||
completed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT user_initial_assessment_progress_next_level_check
|
||||
CHECK (UPPER(TRIM(next_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')),
|
||||
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')
|
||||
)
|
||||
);
|
||||
|
|
@ -77,9 +77,32 @@ 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,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# Initial Placement Assessment — Client App Integration Guide
|
||||
|
||||
This guide documents how to integrate the **initial placement assessment** into the Yimaru **learner mobile app** (iOS / Android / React Native / Flutter). The feature loads a published placement question set, collects learner answers, grades them on the server, maps the score to a CEFR level (**A1–C2**), and persists that level on the user profile.
|
||||
This guide documents how to integrate the **initial placement assessment** into the Yimaru **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 (placement set, questions, CEFR thresholds) is managed in **Yimaru Admin** under **Content → Initial assessment** and is out of scope for the mobile client.
|
||||
> **Scope:** Learner-facing placement flow only. Admin configuration (per-level sets, questions, pass thresholds) is managed in **Yimaru Admin** under **Content → Initial assessment** and is out of scope for the mobile client.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -36,21 +36,23 @@ This guide documents how to integrate the **initial placement assessment** into
|
|||
| Capability | Client app | Backend |
|
||||
|------------|------------|---------|
|
||||
| Decide whether to show placement | Read `initial_assessment_completed` / `knowledge_level` from profile | Stored on `users` |
|
||||
| Load placement questions | `GET /api/v1/assessment/questions` | Published `INITIAL_ASSESSMENT` set + **published** questions only |
|
||||
| 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 | `POST /api/v1/assessment/submit` (**auth required**) | Grades MCQ / True-False (and short-answer / dynamic MC if present), maps % → A1–C2 |
|
||||
| Persist result | Use submit response | Sets `knowledge_level` + `initial_assessment_completed = true` |
|
||||
| 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. A single placement test (not one set per CEFR level).
|
||||
2. Questions authored in admin as **Multiple choice** or **True / False** (recommended / supported for auto-scoring in the product UI).
|
||||
3. A percentage score and a CEFR band **A1–C2** based on admin-configurable thresholds.
|
||||
4. Their profile `knowledge_level` updated to that CEFR code (e.g. `"B1"`).
|
||||
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)).
|
||||
|
|
@ -59,13 +61,12 @@ This guide documents how to integrate the **initial placement assessment** into
|
|||
|
||||
## How placement content is selected
|
||||
|
||||
Backend selection rules (no set ID is passed by the client):
|
||||
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%).
|
||||
|
||||
1. **Question set:** newest **PUBLISHED** `question_sets` row with `set_type = 'INITIAL_ASSESSMENT'`, preferring `owner_type` standalone / null.
|
||||
2. **Questions:** only items in that set whose question `status = 'PUBLISHED'` (`GetPublishedQuestionsInSet`).
|
||||
3. **Submit:** grades against the same published set + published questions; unanswered / wrong answers simply earn 0 points.
|
||||
|
||||
If the set is draft, empty, or has no published questions, list may return `[]` and submit will fail with a clear error.
|
||||
If a level’s set is draft, empty, or has no published questions, list/submit for that level fails.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -73,12 +74,12 @@ If the set is draft, empty, or has no published questions, list may return `[]`
|
|||
|
||||
Before the app can run a successful placement flow:
|
||||
|
||||
1. Run backend migration that creates `initial_assessment_level_thresholds` (and defaults A1–C2).
|
||||
1. Run migrations through `000102_initial_assessment_per_level` (thresholds + progress + unique published-per-level).
|
||||
2. In Admin → **Initial assessment**:
|
||||
- Ensure one placement set exists and is **Published** (“Live for learners”).
|
||||
- Add MCQ / True-False questions.
|
||||
- Toggle each question to **Published** (draft questions never appear in the app).
|
||||
3. Optionally configure **Score thresholds** (defaults: A1=0%, A2=17%, B1=34%, B2=51%, C1=68%, C2=85%).
|
||||
- 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.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -94,15 +95,18 @@ sequenceDiagram
|
|||
API-->>App: initial_assessment_completed, profile fields
|
||||
|
||||
alt not completed
|
||||
App->>API: GET /assessment/questions
|
||||
API->>DB: published INITIAL_ASSESSMENT set + published questions
|
||||
API-->>App: questions (correct answers scrubbed)
|
||||
App->>API: GET /assessment/session (auth)
|
||||
API-->>App: next_level, published_levels
|
||||
|
||||
App->>App: Collect answers (option IDs)
|
||||
|
||||
App->>API: POST /assessment/submit { answers } (auth)
|
||||
API->>DB: grade, resolve CEFR, update user
|
||||
API-->>App: score_percent, level, knowledge_level, per-question results
|
||||
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
|
||||
|
|
@ -116,13 +120,14 @@ sequenceDiagram
|
|||
|
||||
| Endpoint | Auth |
|
||||
|----------|------|
|
||||
| `GET /api/v1/assessment/questions` | **Public** (no bearer token required today) |
|
||||
| `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 (`Authorization: Bearer <access_token>`) |
|
||||
| `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:** Still call list/submit only after login so the same user who takes the test receives the CEFR update. Submit without a valid session returns `401`.
|
||||
**Recommendation:** Drive the flow from `GET /assessment/session` after login. Submit without a valid session returns `401`.
|
||||
|
||||
Base URL pattern:
|
||||
|
||||
|
|
@ -219,13 +224,34 @@ Shuffle: if the published set has `shuffle_questions = true`, the list API curre
|
|||
|
||||
## API reference
|
||||
|
||||
### 1. List placement questions
|
||||
### 1. Placement session
|
||||
|
||||
```http
|
||||
GET /api/v1/assessment/questions
|
||||
GET /api/v1/assessment/session
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
**Auth:** optional (public).
|
||||
**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)).
|
||||
|
||||
|
|
@ -236,11 +262,11 @@ GET /api/v1/assessment/questions
|
|||
- `audio_correct_answer_text` removed.
|
||||
- Dynamic payload option `is_correct` keys stripped.
|
||||
|
||||
**Empty array:** no published set/questions — show “Placement not available” and contact support / retry.
|
||||
**404:** no published set for that level.
|
||||
|
||||
---
|
||||
|
||||
### 2. Get one placement question
|
||||
### 3. Get one placement question
|
||||
|
||||
```http
|
||||
GET /api/v1/assessment/questions/{id}
|
||||
|
|
@ -252,7 +278,7 @@ Same scrubbing as list. Useful for deep links; most apps only need the list endp
|
|||
|
||||
---
|
||||
|
||||
### 3. Submit placement assessment (primary)
|
||||
### 4. Submit one CEFR level (primary)
|
||||
|
||||
```http
|
||||
POST /api/v1/assessment/submit
|
||||
|
|
@ -264,6 +290,7 @@ Content-Type: application/json
|
|||
|
||||
```json
|
||||
{
|
||||
"level": "A1",
|
||||
"answers": [
|
||||
{
|
||||
"question_id": 303,
|
||||
|
|
@ -279,43 +306,60 @@ Content-Type: application/json
|
|||
|
||||
| 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:**
|
||||
**Success `data` example (continue):**
|
||||
|
||||
```json
|
||||
{
|
||||
"question_set_id": 42,
|
||||
"score_percent": 66.67,
|
||||
"level": "B1",
|
||||
"points_earned": 4,
|
||||
"points_max": 6,
|
||||
"gradable_questions": 6,
|
||||
"correct_questions": 4,
|
||||
"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,
|
||||
"knowledge_level": "B1",
|
||||
"initial_assessment_completed": true,
|
||||
"questions": [
|
||||
{
|
||||
"question_id": 303,
|
||||
"question_type": "MCQ",
|
||||
"gradable": true,
|
||||
"correct": true,
|
||||
"points_earned": 1,
|
||||
"points_max": 1,
|
||||
"skipped": false
|
||||
}
|
||||
]
|
||||
"questions": [],
|
||||
"initial_assessment_completed": false
|
||||
}
|
||||
```
|
||||
|
||||
**Side effects on success:**
|
||||
**Success `data` example (finalized):**
|
||||
|
||||
- `users.knowledge_level` ← CEFR level (`A1`…`C2`)
|
||||
```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:**
|
||||
|
|
@ -443,25 +487,16 @@ Rules:
|
|||
|
||||
## Scoring & CEFR mapping
|
||||
|
||||
Server-side (authoritative):
|
||||
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** (`skipped_ungradable_questions`) and do not affect the percentage denominator.
|
||||
3. `score_percent = points_earned / points_max * 100`.
|
||||
4. CEFR = highest configured level whose `min_percent <= score_percent`.
|
||||
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.
|
||||
|
||||
Default thresholds (if admin table empty):
|
||||
|
||||
| Level | Min % |
|
||||
|-------|------:|
|
||||
| A1 | 0 |
|
||||
| A2 | 17 |
|
||||
| B1 | 34 |
|
||||
| B2 | 51 |
|
||||
| C1 | 68 |
|
||||
| C2 | 85 |
|
||||
|
||||
The mobile app should **display** `level` / `knowledge_level` from the submit response, not recompute bands locally (admin may change thresholds).
|
||||
The mobile app should display `passed`, `next_level`, and final `knowledge_level` from the submit response — do not recompute locally.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -10,14 +10,15 @@ import (
|
|||
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: 0, DisplayOrder: 1},
|
||||
{Level: "A2", MinPercent: 17, DisplayOrder: 2},
|
||||
{Level: "B1", MinPercent: 34, DisplayOrder: 3},
|
||||
{Level: "B2", MinPercent: 51, DisplayOrder: 4},
|
||||
{Level: "C1", MinPercent: 68, DisplayOrder: 5},
|
||||
{Level: "C2", MinPercent: 85, DisplayOrder: 6},
|
||||
{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},
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -52,18 +53,41 @@ type PlacementQuestionResult struct {
|
|||
|
||||
type PlacementAssessmentResult struct {
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
LevelAttempted string `json:"level_attempted"`
|
||||
ScorePercent float64 `json:"score_percent"`
|
||||
Level string `json:"level"`
|
||||
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"`
|
||||
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 {
|
||||
|
|
@ -74,8 +98,25 @@ func NormalizeCEFRLevel(level string) (string, error) {
|
|||
return "", fmt.Errorf("level must be one of: %s", strings.Join(InitialAssessmentCEFRLevels, ", "))
|
||||
}
|
||||
|
||||
// ValidateInitialAssessmentThresholds ensures every CEFR level is present once,
|
||||
// mins are ordered ascending, and A1 starts at 0.
|
||||
// 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))
|
||||
|
|
@ -100,36 +141,39 @@ func ValidateInitialAssessmentThresholds(rows []InitialAssessmentLevelThreshold)
|
|||
}
|
||||
}
|
||||
|
||||
ordered := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels))
|
||||
for i, level := range InitialAssessmentCEFRLevels {
|
||||
row, ok := byLevel[level]
|
||||
if !ok {
|
||||
for _, level := range InitialAssessmentCEFRLevels {
|
||||
if _, ok := byLevel[level]; !ok {
|
||||
return fmt.Errorf("missing threshold for level %s", level)
|
||||
}
|
||||
if row.DisplayOrder <= 0 {
|
||||
row.DisplayOrder = i + 1
|
||||
}
|
||||
ordered = append(ordered, row)
|
||||
}
|
||||
|
||||
if ordered[0].MinPercent != 0 {
|
||||
return fmt.Errorf("A1 min_percent must be 0")
|
||||
}
|
||||
for i := 1; i < len(ordered); i++ {
|
||||
if ordered[i].MinPercent <= ordered[i-1].MinPercent {
|
||||
return fmt.Errorf("%s min_percent must be greater than %s", ordered[i].Level, ordered[i-1].Level)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveCEFRLevelFromScore returns the highest level whose min_percent <= scorePercent.
|
||||
// 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 {
|
||||
// tolerate legacy/unsorted rows by sorting and filling defaults for missing
|
||||
thresholds = mergeThresholdDefaults(thresholds)
|
||||
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
|
||||
return "", err
|
||||
|
|
|
|||
|
|
@ -2,40 +2,41 @@ package domain
|
|||
|
||||
import "testing"
|
||||
|
||||
func TestResolveCEFRLevelFromScore(t *testing.T) {
|
||||
func TestPassPercentForLevel(t *testing.T) {
|
||||
thresholds := DefaultInitialAssessmentThresholds()
|
||||
cases := []struct {
|
||||
score float64
|
||||
want string
|
||||
}{
|
||||
{0, "A1"},
|
||||
{16.9, "A1"},
|
||||
{17, "A2"},
|
||||
{50, "B1"},
|
||||
{51, "B2"},
|
||||
{84.9, "C1"},
|
||||
{85, "C2"},
|
||||
{100, "C2"},
|
||||
got, err := PassPercentForLevel("B1", thresholds)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := ResolveCEFRLevelFromScore(tc.score, thresholds)
|
||||
if err != nil {
|
||||
t.Fatalf("score %.1f: %v", tc.score, err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("score %.1f: got %s want %s", tc.score, got, tc.want)
|
||||
}
|
||||
if got != 70 {
|
||||
t.Fatalf("got %d want 70", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateInitialAssessmentThresholds_rejectsUnordered(t *testing.T) {
|
||||
func TestValidateInitialAssessmentThresholds_allowsEqualPassMarks(t *testing.T) {
|
||||
rows := DefaultInitialAssessmentThresholds()
|
||||
rows[2].MinPercent = 10
|
||||
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{
|
||||
{
|
||||
|
|
|
|||
|
|
@ -53,8 +53,13 @@ type QuestionStore interface {
|
|||
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) error
|
||||
UpdateQuestionSet(ctx context.Context, id int64, input domain.CreateQuestionSetInput) error
|
||||
|
|
|
|||
|
|
@ -103,3 +103,54 @@ func (s *Store) CompleteInitialAssessment(ctx context.Context, userID int64, kno
|
|||
}
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1162,6 +1162,14 @@ func (s *Store) GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType s
|
|||
}
|
||||
|
||||
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,
|
||||
|
|
@ -1169,6 +1177,7 @@ func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet
|
|||
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
|
||||
|
|
@ -1176,7 +1185,7 @@ func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet
|
|||
END,
|
||||
created_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
`, normalized)
|
||||
|
||||
var (
|
||||
qs domain.QuestionSet
|
||||
|
|
@ -1186,7 +1195,7 @@ func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet
|
|||
displayOrder int32
|
||||
updatedAt *time.Time
|
||||
)
|
||||
err := row.Scan(
|
||||
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,
|
||||
|
|
@ -1205,6 +1214,31 @@ func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet
|
|||
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,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,10 @@ package assessment
|
|||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// CreateQuestion creates a question in the unified questions system.
|
||||
|
|
@ -15,39 +19,25 @@ func (s *Service) CreateQuestion(
|
|||
return s.questionStore.CreateQuestion(ctx, input)
|
||||
}
|
||||
|
||||
// ListQuestions returns questions from the initial assessment set.
|
||||
func (s *Service) ListQuestions(ctx context.Context) ([]domain.QuestionWithDetails, error) {
|
||||
// Get the initial assessment set
|
||||
set, err := s.questionStore.GetInitialAssessmentSet(ctx)
|
||||
// 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
|
||||
}
|
||||
|
||||
// Get all questions in the set
|
||||
items, err := s.questionStore.GetPublishedQuestionsInSet(ctx, set.ID)
|
||||
_, questions, err := s.loadPublishedLevelQuestions(ctx, normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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 nil, err
|
||||
}
|
||||
|
||||
result := make([]domain.QuestionWithDetails, 0, len(items))
|
||||
for _, item := range items {
|
||||
qwd, ok := byID[item.QuestionID]
|
||||
if !ok {
|
||||
continue
|
||||
if errors.Is(err, ErrPlacementSetNotFound) || errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrPlacementSetNotFound
|
||||
}
|
||||
result = append(result, qwd)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
return questions, nil
|
||||
}
|
||||
|
||||
// GetQuestionByID returns a question with full details.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"Yimaru-Backend/internal/domain"
|
||||
|
||||
|
|
@ -11,8 +12,11 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
ErrPlacementSetNotFound = errors.New("published initial assessment set not found")
|
||||
ErrNoGradableQuestions = errors.New("placement set has no auto-gradable questions")
|
||||
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) {
|
||||
|
|
@ -36,34 +40,84 @@ func (s *Service) UpdateLevelThresholds(ctx context.Context, rows []domain.Initi
|
|||
return s.ListLevelThresholds(ctx)
|
||||
}
|
||||
|
||||
// SubmitPlacement grades answers against the published placement set, maps score to CEFR,
|
||||
// and persists knowledge_level + initial_assessment_completed on the user.
|
||||
func (s *Service) SubmitPlacement(ctx context.Context, userID int64, answers []domain.PlacementAnswerInput) (domain.PlacementAssessmentResult, error) {
|
||||
set, err := s.questionStore.GetInitialAssessmentSet(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.PlacementAssessmentResult{}, ErrPlacementSetNotFound
|
||||
return domain.QuestionSet{}, nil, ErrPlacementSetNotFound
|
||||
}
|
||||
return domain.PlacementAssessmentResult{}, err
|
||||
return domain.QuestionSet{}, nil, err
|
||||
}
|
||||
|
||||
items, err := s.questionStore.GetPublishedQuestionsInSet(ctx, set.ID)
|
||||
if err != nil {
|
||||
return domain.PlacementAssessmentResult{}, err
|
||||
return domain.QuestionSet{}, nil, err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return domain.PlacementAssessmentResult{}, fmt.Errorf("%w: set is empty", ErrNoGradableQuestions)
|
||||
return domain.QuestionSet{}, nil, fmt.Errorf("%w: set is empty", ErrNoGradableQuestions)
|
||||
}
|
||||
|
||||
questions := make([]domain.QuestionWithDetails, 0, len(items))
|
||||
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.PlacementAssessmentResult{}, err
|
||||
return domain.QuestionSet{}, nil, err
|
||||
}
|
||||
questions := make([]domain.QuestionWithDetails, 0, len(items))
|
||||
for _, item := range items {
|
||||
qwd, ok := byID[item.QuestionID]
|
||||
if !ok {
|
||||
|
|
@ -72,11 +126,42 @@ func (s *Service) SubmitPlacement(ctx context.Context, userID int64, answers []d
|
|||
questions = append(questions, qwd)
|
||||
}
|
||||
if len(questions) == 0 {
|
||||
return domain.PlacementAssessmentResult{}, ErrNoGradableQuestions
|
||||
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
|
||||
}
|
||||
|
|
@ -85,20 +170,88 @@ func (s *Service) SubmitPlacement(ctx context.Context, userID int64, answers []d
|
|||
if err != nil {
|
||||
return domain.PlacementAssessmentResult{}, err
|
||||
}
|
||||
level, err := domain.ResolveCEFRLevelFromScore(graded.ScorePercent, thresholds)
|
||||
passPercent, err := domain.PassPercentForLevel(normalized, thresholds)
|
||||
if err != nil {
|
||||
return domain.PlacementAssessmentResult{}, err
|
||||
}
|
||||
graded.Level = level
|
||||
graded.KnowledgeLevel = level
|
||||
graded.InitialAssessmentCompleted = true
|
||||
graded.PassPercent = passPercent
|
||||
graded.Passed = graded.ScorePercent+1e-9 >= float64(passPercent)
|
||||
|
||||
if err := s.userStore.CompleteInitialAssessment(ctx, userID, level); err != nil {
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -98,16 +98,32 @@ func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error {
|
|||
}
|
||||
|
||||
// ListAssessmentQuestions godoc
|
||||
// @Summary List assessment questions
|
||||
// @Description Returns all active assessment questions from the initial assessment set
|
||||
// @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 {
|
||||
questions, err := h.assessmentSvc.ListQuestions(c.Context())
|
||||
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(),
|
||||
|
|
@ -236,16 +252,48 @@ func scrubDynamicElements(els []domain.DynamicElementInstance) []domain.DynamicE
|
|||
}
|
||||
|
||||
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 initial placement assessment answers
|
||||
// @Description Grades answers against the published placement set, maps the score to A1–C2 using admin thresholds, and updates the learner knowledge_level
|
||||
// @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 "Placement answers"
|
||||
// @Param body body submitPlacementAssessmentReq true "Level + placement answers"
|
||||
// @Success 200 {object} domain.Response
|
||||
// @Failure 400 {object} domain.ErrorResponse
|
||||
// @Failure 404 {object} domain.ErrorResponse
|
||||
|
|
@ -268,7 +316,7 @@ func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
result, err := h.assessmentSvc.SubmitPlacement(c.Context(), userID, req.Answers)
|
||||
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{
|
||||
|
|
@ -282,6 +330,14 @@ func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error {
|
|||
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(),
|
||||
|
|
@ -289,7 +345,8 @@ func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error {
|
|||
}
|
||||
|
||||
h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &userID,
|
||||
fmt.Sprintf("Completed initial assessment with level %s (%.1f%%)", result.Level, result.ScorePercent), nil)
|
||||
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",
|
||||
|
|
@ -299,7 +356,7 @@ func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error {
|
|||
}
|
||||
|
||||
// ListInitialAssessmentLevelThresholds godoc
|
||||
// @Summary List CEFR score thresholds for placement
|
||||
// @Summary List per-level pass thresholds for placement
|
||||
// @Tags assessment
|
||||
// @Produce json
|
||||
// @Success 200 {object} domain.Response
|
||||
|
|
@ -325,11 +382,11 @@ type updateLevelThresholdsReq struct {
|
|||
}
|
||||
|
||||
// UpdateInitialAssessmentLevelThresholds godoc
|
||||
// @Summary Update CEFR score thresholds for placement
|
||||
// @Summary Update per-level pass thresholds for placement
|
||||
// @Tags assessment
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body updateLevelThresholdsReq true "Thresholds A1–C2"
|
||||
// @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
|
||||
|
|
|
|||
|
|
@ -799,24 +799,29 @@ var validInitialAssessmentLevels = map[string]struct{}{
|
|||
"C2": {},
|
||||
}
|
||||
|
||||
// normalizeInitialAssessmentDescription stores the CEFR band for per-level placement sets.
|
||||
func normalizeInitialAssessmentDescription(description *string) string {
|
||||
if description == nil {
|
||||
return "PLACEMENT"
|
||||
return ""
|
||||
}
|
||||
text := strings.TrimSpace(*description)
|
||||
if text == "" {
|
||||
return "PLACEMENT"
|
||||
return ""
|
||||
}
|
||||
upper := strings.ToUpper(text)
|
||||
if _, ok := validInitialAssessmentLevels[upper]; ok {
|
||||
return upper
|
||||
}
|
||||
if strings.EqualFold(upper, "PLACEMENT") {
|
||||
return "PLACEMENT"
|
||||
}
|
||||
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
|
||||
|
|
@ -877,6 +882,12 @@ func (h *Handler) CreateQuestionSet(c *fiber.Ctx) 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"
|
||||
|
|
@ -1189,6 +1200,12 @@ func (h *Handler) UpdateQuestionSet(c *fiber.Ctx) error {
|
|||
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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -197,6 +197,7 @@ func (a *App) initAppRoutes() {
|
|||
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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user