RezinaLMS-BackEnd/docs/initial-assessment-client-app-integration.md
2026-10-19 17:59:34 +03:00

26 KiB
Raw Blame History

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
  2. How placement content is selected
  3. Prerequisites (ops / admin)
  4. Architecture
  5. Authentication
  6. Response envelopes
  7. User profile flags
  8. Recommended UX flow
  9. API reference
  10. Question payload shapes
  11. Building answer payloads
  12. Scoring & CEFR mapping
  13. Legacy knowledge-level endpoint
  14. TypeScript types
  15. Example API client
  16. React Native integration patterns
  17. Error handling
  18. Edge cases & product rules
  19. Integration checklist
  20. 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).

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

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:

{API_BASE_URL}/api/v1/...

Example:

Authorization: Bearer eyJhbGciOi...
Content-Type: application/json

Response envelopes

Successful responses typically look like:

{
  "message": "Questions fetched successfully",
  "data": [ /* payload */ ],
  "success": true,
  "status_code": 200,
  "metadata": null
}

Errors:

{
  "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:

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

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.


  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

GET /api/v1/assessment/session
Authorization: Bearer <access_token>

Success data:

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

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

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

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)

POST /api/v1/assessment/submit
Authorization: Bearer <access_token>
Content-Type: application/json

Body:

{
  "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):

{
  "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):

{
  "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:

{
  "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:

{
  "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:
{
  "question_id": 303,
  "dynamic_answers": [
    {
      "element_id": "multiple_choice_1",
      "selected_option_ids": ["a"]
    }
  ]
}

Building answer payloads

Single-select MCQ / True-False (flat options)

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

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

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

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

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

idle → loadingQuestions → inProgress → submitting → result
                     ↘ error

Minimal hook sketch

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

{ "answers": [{ "question_id": 1, "selected_option_ids": [10] }] }

Success highlights:

{
  "score_percent": 70,
  "level": "B1",
  "knowledge_level": "B1",
  "initial_assessment_completed": true
}

CEFR levels: A1, A2, B1, B2, C1, C2.


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.