RezinaLMS-BackEnd/docs/initial-assessment-client-app-integration.md

24 KiB
Raw Blame History

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.

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.


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 placement questions GET /api/v1/assessment/questions Published INITIAL_ASSESSMENT set + published questions only
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

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

What the client must not do

  • Do not grade answers locally for the official result — always call POST /assessment/submit.
  • 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

Backend selection rules (no set ID is passed by the client):

  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.


Prerequisites (ops / admin)

Before the app can run a successful placement flow:

  1. Run backend migration that creates initial_assessment_level_thresholds (and defaults A1–C2).
  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%).

Architecture

sequenceDiagram
    participant App as Mobile app
    participant API as Yimaru 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/questions
        API->>DB: published INITIAL_ASSESSMENT set + published questions
        API-->>App: questions (correct answers scrubbed)

        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

        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/questions Public (no bearer token required today)
GET /api/v1/assessment/questions/:id Public
POST /api/v1/assessment/submit Required — learner JWT (Authorization: Bearer <access_token>)
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.

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. List placement questions

GET /api/v1/assessment/questions

Auth: optional (public).

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.

Empty array: no published set/questions — show “Placement not available” and contact support / retry.


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


3. Submit placement assessment (primary)

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

Body:

{
  "answers": [
    {
      "question_id": 303,
      "selected_option_ids": [1201]
    },
    {
      "question_id": 304,
      "selected_option_ids": [1210]
    }
  ]
}
Field Required Description
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:

{
  "question_set_id": 42,
  "score_percent": 66.67,
  "level": "B1",
  "points_earned": 4,
  "points_max": 6,
  "gradable_questions": 6,
  "correct_questions": 4,
  "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
    }
  ]
}

Side effects on success:

  • users.knowledge_level ← CEFR level (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

Server-side (authoritative):

  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.

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


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.