RezinaLMS-BackEnd/docs/practice-stimulus-blocks-admin-panel-integration.md
2026-10-19 17:59:34 +03:00

38 KiB
Raw Blame History

Practice Stimulus Blocks — Admin Panel Integration Guide

This guide documents how to integrate practice-level shared stimulus blocks into the Rezina admin panel practice authoring flow. Stimulus blocks let authors define one shared passage, audio clip, or instruction set that multiple dynamic questions in the same practice can reference — the primary use case is IELTS-style listening/reading sections where several questions share a single stimulus.

Scope (Phase 1): Blocks live on the practice (practice_stimulus_blocks), not on global question-type definition groups. Questions link via stimulus_block_key on set membership (question_set_items). The API returns both the stored per-question dynamic_payload and a computed effective_dynamic_payload (block stimulus + question stimulus merged). Use authoring_profile on the practice shell to switch admin UI modes (STANDALONE vs IELTS_SHARED_STIMULUS).


Table of contents

  1. Feature overview
  2. Concepts: blocks, keys, and merge rules
  3. Architecture
  4. Prerequisites (backend)
  5. Authentication & permissions
  6. Data model
  7. Response envelopes
  8. Primary API: full practice save/load
  9. Authoring profiles
  10. Dynamic payload split: block vs question
  11. Recommended admin UI changes
  12. Form state & serialization
  13. Client-side validation (mirror backend)
  14. TypeScript types & helpers
  15. React integration patterns
  16. IELTS listening example (end-to-end)
  17. Error handling
  18. Learner app note
  19. Integration checklist
  20. Limitations
  21. Quick reference

Feature overview

Capability Admin panel Learner app
Define shared stimulus at practice level Yes (new) Reads merged stimulus per question
Link questions to a block via stimulus_block_key Yes (new) Uses effective_dynamic_payload
Store question-only response fields separately Yes Response always from question payload
Override block stimulus per question (same element id) Yes Merged server-side
authoring_profile to switch UI mode Yes (new) N/A (authoring metadata)
Manage blocks outside full practice save No (Phase 1) N/A

What problem this solves

Before: Every dynamic question stored its full dynamic_payload.stimulus[] independently. For IELTS listening, authors duplicated the same audio URL and passage across 5–10 questions.

After: Authors create stimulus blocks once per practice:

Block "listening-section-1"
  └── stimulus: [ AUDIO_PROMPT, TEXT_PASSAGE, INSTRUCTION ]

Question 1  stimulus_block_key = "listening-section-1"  response: [ MULTIPLE_CHOICE ]
Question 2  stimulus_block_key = "listening-section-1"  response: [ SHORT_ANSWER ]
Question 3  stimulus_block_key = "listening-section-1"  response: [ MULTIPLE_CHOICE ]

The learner (and admin preview) render effective_dynamic_payload, not the raw stored question stimulus alone.

Relationship to other features

Feature Purpose Overlap
Stimulus blocks (this guide) Shared content within one practice Use for IELTS shared audio/passage
Question associations (associated_question_id) Sequential section gating Orthogonal — combine both
Question type definition groups Catalog organization Not for shared content
Dynamic question types Builder-defined stimulus/response Block stimulus must use valid stimulus kinds

Concepts: blocks, keys, and merge rules

Practice-level fields

Field Location Values Purpose
authoring_profile practice object STANDALONE, IELTS_SHARED_STIMULUS Hints which admin editor layout to use
stimulus_blocks[] Top-level on full practice payload Array of blocks Shared stimulus definitions

Stimulus block fields

Field Type Required Notes
block_key string Yes Client-stable identifier within the practice. Pattern: ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$
display_order number No Sort order in admin UI. Defaults to 1-based index in stimulus_blocks array on save
stimulus DynamicElementInstance[] Yes (may be []) Shared stimulus elements only — no response elements

Question membership fields

Field Type Notes
stimulus_block_key string | null References block_key on the same practice. null/omit = standalone question
dynamic_payload object Stored question payload. Stimulus may be empty when block supplies it
effective_dynamic_payload object Read-only. Merged stimulus + question response for rendering

Merge algorithm (effective_dynamic_payload)

Implemented in domain.MergeEffectiveDynamicPayload:

  1. Start with all elements from the linked block's stimulus[] (in order).
  2. Append elements from the question's dynamic_payload.stimulus[].
  3. If a question element has the same id as a block element, the question version wins (override).
  4. response[] always comes from the question's stored dynamic_payload only.
flowchart LR
    subgraph Block["Block listening-section-1"]
        B1["AUDIO_PROMPT id=audio_1"]
        B2["TEXT_PASSAGE id=passage_1"]
    end

    subgraph Question["Question stored payload"]
        Q1["stimulus: []"]
        Q2["response: MULTIPLE_CHOICE"]
    end

    subgraph Effective["effective_dynamic_payload"]
        E1["AUDIO_PROMPT id=audio_1"]
        E2["TEXT_PASSAGE id=passage_1"]
        E3["response: MULTIPLE_CHOICE"]
    end

    Block --> Effective
    Question --> Effective

Visual: practice editor layout (IELTS mode)

┌─────────────────────────────────────────────────────────────┐
│ Practice: IELTS Listening Mock 1                            │
│ authoring_profile: IELTS_SHARED_STIMULUS                    │
├─────────────────────────────────────────────────────────────┤
│ Stimulus blocks                                             │
│  ┌─ Block: listening-section-1 ─────────────────────────┐ │
│  │  [AUDIO_PROMPT] [INSTRUCTION] [TEXT_PASSAGE]         │ │
│  └──────────────────────────────────────────────────────┘ │
│  ┌─ Block: listening-section-2 ─────────────────────────┐ │
│  │  [AUDIO_PROMPT]                                       │ │
│  └──────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Questions                                                   │
│  Q1  block: listening-section-1   [MCQ response editor]   │
│  Q2  block: listening-section-1   [MCQ response editor]   │
│  Q3  block: listening-section-2   [SHORT_ANSWER editor]   │
└─────────────────────────────────────────────────────────────┘

Architecture

flowchart TB
    subgraph AdminPanel["Admin panel"]
        ProfileToggle[authoring_profile selector]
        BlockEditor[Stimulus block editor]
        QuestionEditor[Per-question response editor]
        SaveBtn[Save practice]
    end

    subgraph API["Rezina API"]
        GetFull["GET /practices/:id/full"]
        PutFull["PUT /practices/:id/full"]
        GetEpFull["GET /exam-prep/practices/:id/full"]
        PutEpFull["PUT /exam-prep/practices/:id/full"]
    end

    subgraph DB["PostgreSQL"]
        PSB["practice_stimulus_blocks"]
        QSI["question_set_items.stimulus_block_key"]
        Q["questions.dynamic_payload"]
    end

    ProfileToggle --> BlockEditor
    BlockEditor --> QuestionEditor
    SaveBtn --> PutFull
    SaveBtn --> PutEpFull
    GetFull --> BlockEditor
    PutFull --> PSB
    PutFull --> QSI
    PutFull --> Q
    PutFull --> GetFull
  • Migration: 000095_practice_stimulus_blocks — practice_stimulus_blocks, authoring_profile, stimulus_block_key.
  • Domain: internal/domain/practice_stimulus_block.go — validation, merge.
  • Sync: internal/services/practicecontent/stimulus_sync.go, question_sync.go.
  • Handlers: internal/web_server/handlers/practice_full_update_handler.go.

Prerequisites (backend)

Before testing from the admin panel:

  1. Run database migrations (includes 000095):

    docker compose up migrate
    
  2. Confirm tables/columns exist:

    \d practice_stimulus_blocks
    \d question_set_items   -- stimulus_block_key
    \d lms_practices        -- authoring_profile
    
  3. Redeploy API on the branch that includes commit 9b504b8 or later.


Authentication & permissions

Use a team member or platform admin token:

Authorization: Bearer <access_token>
Content-Type: application/json

LMS practices (Learn English)

Action Permission HTTP
Load practice + blocks + questions practices.get GET /api/v1/practices/:id/full
Save practice + blocks + questions practices.update PUT /api/v1/practices/:id/full

Exam-prep practices

Action Permission HTTP
Load exam_prep.practices.get GET /api/v1/exam-prep/practices/:id/full
Save exam_prep.practices.update PUT /api/v1/exam-prep/practices/:id/full

Phase 1: Stimulus blocks are only manageable via full practice GET/PUT. Granular question-set item routes do not expose stimulus_block_key yet.


Data model

Database

practice_stimulus_blocks

Column Type Notes
practice_kind varchar LMS or EXAM_PREP
practice_id bigint Practice shell ID
block_key varchar(64) Unique per (practice_kind, practice_id)
stimulus jsonb []DynamicElementInstance
display_order int Admin sort order

lms_practices / exam_prep.lesson_practices

Column Type Default
authoring_profile varchar(40) STANDALONE

question_set_items

Column Type Notes
stimulus_block_key varchar(64) NULL References block_key within same practice

Stimulus component kinds (block stimulus[])

Valid values for elements in block stimulus (from question-type builder):

Kind Typical use in blocks
QUESTION_TEXT Rare in blocks; usually per-question
PREP_TIME Shared prep countdown
INSTRUCTION Section instructions
AUDIO_PROMPT Shared listening audio (URL)
TEXT_PASSAGE Shared reading passage
IMAGE Shared diagram
MATCHING_INPUTS Shared matching prompt data
SELECT_MISSING_WORDS Shared word-bank passage
TABLE Shared table data
PDF_ATTACHMENT Shared PDF URL

Response kinds (MULTIPLE_CHOICE, SHORT_ANSWER, AUDIO_RESPONSE, etc.) belong in question dynamic_payload.response[], not in blocks.

JSON shapes

interface DynamicElementInstance {
  id: string;
  kind: string;
  value?: unknown;
  meta?: Record<string, unknown>;
}

interface DynamicQuestionPayload {
  stimulus: DynamicElementInstance[];
  response: DynamicElementInstance[];
}

interface PracticeStimulusBlock {
  id?: number;           // present after save; omit on create
  block_key: string;
  display_order: number;
  stimulus: DynamicElementInstance[];
}

interface PracticeShell {
  id: number;
  title: string;
  question_set_id: number;
  authoring_profile: "STANDALONE" | "IELTS_SHARED_STIMULUS";
  // ...existing practice fields
}

Response envelopes

Success:

{
  "message": "Practice retrieved successfully",
  "data": { },
  "success": true,
  "status_code": 200
}

Validation error (invalid block):

{
  "message": "Invalid stimulus block",
  "error": "invalid stimulus block: stimulus_block_key \"missing\" does not match a stimulus block on this practice"
}

Primary API: full practice save/load

Load practice (LMS)

GET /api/v1/practices/:id/full
Authorization: Bearer <token>

Response data shape (relevant parts):

{
  "practice": {
    "id": 12,
    "title": "IELTS Listening Mock 1",
    "question_set_id": 55,
    "authoring_profile": "IELTS_SHARED_STIMULUS",
    "publish_status": "PUBLISHED"
  },
  "question_set": {
    "id": 55,
    "title": "Listening set",
    "question_count": 3
  },
  "stimulus_blocks": [
    {
      "id": 1,
      "block_key": "listening-section-1",
      "display_order": 1,
      "stimulus": [
        {
          "id": "audio_1",
          "kind": "AUDIO_PROMPT",
          "value": "https://cdn.example.com/listening-part1.mp3"
        },
        {
          "id": "instruction_1",
          "kind": "INSTRUCTION",
          "value": "Listen and answer questions 1–3."
        }
      ]
    }
  ],
  "questions": [
    {
      "id": 201,
      "display_order": 1,
      "stimulus_block_key": "listening-section-1",
      "question_type": "DYNAMIC",
      "question_type_definition_id": 42,
      "dynamic_payload": {
        "stimulus": [],
        "response": [
          {
            "id": "mcq_1",
            "kind": "MULTIPLE_CHOICE",
            "value": {
              "options": [
                { "option_text": "A", "option_order": 1, "is_correct": true },
                { "option_text": "B", "option_order": 2, "is_correct": false }
              ]
            }
          }
        ]
      },
      "effective_dynamic_payload": {
        "stimulus": [
          {
            "id": "audio_1",
            "kind": "AUDIO_PROMPT",
            "value": "https://cdn.example.com/listening-part1.mp3"
          },
          {
            "id": "instruction_1",
            "kind": "INSTRUCTION",
            "value": "Listen and answer questions 1–3."
          }
        ],
        "response": [
          {
            "id": "mcq_1",
            "kind": "MULTIPLE_CHOICE",
            "value": {
              "options": [
                { "option_text": "A", "option_order": 1, "is_correct": true },
                { "option_text": "B", "option_order": 2, "is_correct": false }
              ]
            }
          }
        ]
      }
    }
  ]
}

Save practice (LMS)

PUT /api/v1/practices/:id/full
Authorization: Bearer <token>
Content-Type: application/json

Request body (full example):

{
  "practice": {
    "title": "IELTS Listening Mock 1",
    "authoring_profile": "IELTS_SHARED_STIMULUS",
    "publish_status": "PUBLISHED"
  },
  "question_set": {
    "status": "PUBLISHED",
    "shuffle_questions": false
  },
  "stimulus_blocks": [
    {
      "block_key": "listening-section-1",
      "display_order": 1,
      "stimulus": [
        {
          "id": "audio_1",
          "kind": "AUDIO_PROMPT",
          "value": "https://cdn.example.com/listening-part1.mp3"
        },
        {
          "id": "instruction_1",
          "kind": "INSTRUCTION",
          "value": "Listen and answer questions 1–3."
        }
      ]
    }
  ],
  "questions": [
    {
      "id": 201,
      "display_order": 1,
      "stimulus_block_key": "listening-section-1",
      "question_type": "DYNAMIC",
      "question_type_definition_id": 42,
      "dynamic_payload": {
        "stimulus": [],
        "response": [
          {
            "id": "mcq_1",
            "kind": "MULTIPLE_CHOICE",
            "value": {
              "options": [
                { "option_text": "A", "option_order": 1, "is_correct": true },
                { "option_text": "B", "option_order": 2, "is_correct": false }
              ]
            }
          }
        ]
      }
    },
    {
      "display_order": 2,
      "stimulus_block_key": "listening-section-1",
      "question_type": "DYNAMIC",
      "question_type_definition_id": 43,
      "dynamic_payload": {
        "stimulus": [],
        "response": [
          {
            "id": "mcq_2",
            "kind": "MULTIPLE_CHOICE",
            "value": { "options": [] }
          }
        ]
      }
    }
  ]
}

Field reference (save)

Field Location On save Notes
authoring_profile practice Optional STANDALONE or IELTS_SHARED_STIMULUS
stimulus_blocks top-level Optional See sync semantics below
block_key per block Required Unique within practice
display_order per block Optional Defaults to array index + 1
stimulus per block Required Array (may be empty [])
stimulus_block_key per question Optional Must match a block in same request or existing DB blocks
dynamic_payload per question Required for DYNAMIC Stimulus may be [] when block supplies required elements
effective_dynamic_payload per question Do not send Response-only

Sync semantics

stimulus_blocks in PUT body Behavior
Omitted (undefined) Existing blocks unchanged
[] (empty array) Deletes all blocks on the practice
Non-empty array Upserts listed blocks; deletes any DB blocks whose block_key is not in the array

Questions omitted from questions[] are still removed from the set (unchanged from existing full-save behavior).

Block sync runs before question sync so stimulus_block_key validation sees the updated block list in the same request.

Exam-prep equivalent

LMS Exam-prep
GET /api/v1/practices/:id/full GET /api/v1/exam-prep/practices/:id/full
PUT /api/v1/practices/:id/full PUT /api/v1/exam-prep/practices/:id/full

Payload shape is identical (domain.FullUpdatePracticeInput).


Authoring profiles

Profile Admin UI intent Block editor
STANDALONE Learn English / Duolingo-style Hidden or collapsed — each question owns full dynamic_payload
IELTS_SHARED_STIMULUS IELTS section authoring Prominent block editor + per-question response-only panels

authoring_profile is metadata for the admin panel. The API does not enforce different validation rules per profile in Phase 1 — blocks and keys work regardless of profile value.

Recommended UX:

  1. On practice create, default STANDALONE.
  2. Offer toggle: “Use shared stimulus sections (IELTS mode)” → sets IELTS_SHARED_STIMULUS and reveals block UI.
  3. Persist profile on every full save via practice.authoring_profile.

Dynamic payload split: block vs question

What goes in the block

Put shared, section-level content in stimulus_blocks[].stimulus:

  • Listening audio (AUDIO_PROMPT)
  • Reading passage (TEXT_PASSAGE)
  • Section instructions (INSTRUCTION)
  • Shared images, tables, PDFs

What stays on the question

Put per-question content in questions[].dynamic_payload:

  • response[] — always here (MCQ options, short answer, timers, etc.)
  • stimulus[] — only when:
    • Question has no stimulus_block_key (standalone mode), or
    • Question needs to override a block element (same id), or
    • Question adds extra stimulus beyond the block

Validation on save

For DYNAMIC questions with question_type_definition_id, the backend validates against the question type definition using the merged payload (block + question). Therefore:

  • Required stimulus schema elements can be satisfied entirely by the block.
  • Question dynamic_payload.stimulus may be [] when stimulus_block_key is set.

Per-question override example

Block defines audio_1. Question 2 needs a different instruction without changing the block for other questions:

{
  "stimulus_block_key": "listening-section-1",
  "dynamic_payload": {
    "stimulus": [
      {
        "id": "instruction_1",
        "kind": "INSTRUCTION",
        "value": "Answer question 2 only."
      }
    ],
    "response": [ /* ... */ ]
  }
}

effective_dynamic_payload uses the question's instruction_1 instead of the block's.


1. Practice settings: authoring profile

Control Maps to
Toggle / select “IELTS shared stimulus mode” practice.authoring_profile

2. Stimulus block panel (IELTS mode)

UI element Purpose
Block list (ordered) Maps to stimulus_blocks[]
Add block Generates new block_key (e.g. section-${n})
Block stimulus builder Edits stimulus[] using same component picker as dynamic questions
Delete block Remove from array; clear stimulus_block_key on affected questions before save

3. Question row changes

UI element Purpose
Block dropdown Sets stimulus_block_key (null = standalone)
Response-only editor When block selected, hide shared stimulus fields; edit dynamic_payload.response only
Preview pane Render effective_dynamic_payload from last GET or local merge

4. Standalone mode (STANDALONE)

Keep existing dynamic question editor — full dynamic_payload on each question. Do not require stimulus_blocks.

5. Block key generation

function suggestBlockKey(existing: PracticeStimulusBlock[]): string {
  let n = existing.length + 1;
  let key = `section-${n}`;
  const keys = new Set(existing.map((b) => b.block_key));
  while (keys.has(key)) {
    n += 1;
    key = `section-${n}`;
  }
  return key;
}

6. Warn before deleting a block

If any question references block_key, prompt author to reassign or clear stimulus_block_key before save.


Form state & serialization

Suggested editor state

interface PracticeEditorState {
  practice: {
    title: string;
    authoring_profile: "STANDALONE" | "IELTS_SHARED_STIMULUS";
    publish_status?: string;
    persona_id?: number | null;
  };
  questionSet: {
    status?: string;
    shuffle_questions?: boolean;
  };
  stimulusBlocks: EditableStimulusBlock[];
  questions: EditablePracticeQuestion[];
}

interface EditableStimulusBlock {
  block_key: string;
  display_order: number;
  stimulus: DynamicElementInstance[];
}

interface EditablePracticeQuestion {
  id?: number;
  display_order: number;
  stimulus_block_key: string | null;
  associated_question_id?: number | null;
  question_type: string;
  question_type_definition_id?: number;
  dynamic_payload?: DynamicQuestionPayload;
  // ...existing fields
}

Load: API → form state

function mapFullPracticeToState(data: PracticeFullResponse): PracticeEditorState {
  return {
    practice: {
      title: data.practice.title as string,
      authoring_profile: (data.practice.authoring_profile as string) ?? "STANDALONE",
      publish_status: data.practice.publish_status as string,
      persona_id: data.practice.persona_id as number | null,
    },
    questionSet: {
      status: data.question_set.status as string,
      shuffle_questions: data.question_set.shuffle_questions as boolean,
    },
    stimulusBlocks: (data.stimulus_blocks ?? []).map((b) => ({
      block_key: b.block_key,
      display_order: b.display_order,
      stimulus: b.stimulus ?? [],
    })),
    questions: data.questions.map((q) => ({
      id: q.id,
      display_order: q.display_order ?? 1,
      stimulus_block_key: q.stimulus_block_key ?? null,
      associated_question_id: q.associated_question_id ?? null,
      question_type: q.question_type,
      question_type_definition_id: q.question_type_definition_id,
      dynamic_payload: q.dynamic_payload,
      // ...map other fields
    })),
  };
}

Save: form state → API

function mapStateToSavePayload(state: PracticeEditorState): FullUpdatePracticeInput {
  const useBlocks = state.practice.authoring_profile === "IELTS_SHARED_STIMULUS";

  return {
    practice: {
      title: state.practice.title,
      authoring_profile: state.practice.authoring_profile,
      publish_status: state.practice.publish_status,
      persona_id: state.practice.persona_id,
    },
    question_set: state.questionSet,
  stimulus_blocks: useBlocks
      ? state.stimulusBlocks.map((b, i) => ({
          block_key: b.block_key,
          display_order: b.display_order ?? i + 1,
          stimulus: b.stimulus,
        }))
      : [], // empty array clears blocks when switching away from IELTS mode
    questions: state.questions.map((q) => ({
      ...(q.id != null ? { id: q.id } : {}),
      display_order: q.display_order,
      stimulus_block_key: q.stimulus_block_key ?? undefined,
      associated_question_id: q.associated_question_id,
      question_type: q.question_type,
      question_type_definition_id: q.question_type_definition_id,
      dynamic_payload: q.dynamic_payload,
    })),
  };
}

Switching STANDALONE → IELTS_SHARED_STIMULUS: Start with empty stimulus_blocks, let author create blocks, then assign keys to questions.

Switching IELTS_SHARED_STIMULUS → STANDALONE: Send stimulus_blocks: [] and clear stimulus_block_key on questions. Consider copying effective_dynamic_payload.stimulus into each question's stored payload before switch (client-side migration).


Client-side validation (mirror backend)

Validate before save:

Block rules

Rule Error message (suggested)
block_key empty "Block key is required."
block_key invalid chars "Block key must start with a letter or digit and contain only letters, digits, _, -."
Duplicate block_key in array "Duplicate block key: …"
Unknown kind in stimulus "Invalid stimulus component kind: …"
const BLOCK_KEY_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;

function validateStimulusBlocks(blocks: EditableStimulusBlock[]): string | null {
  const seen = new Set<string>();
  for (const block of blocks) {
    const key = block.block_key.trim();
    if (!key) return "Block key is required.";
    if (!BLOCK_KEY_RE.test(key)) return `Invalid block key: ${block.block_key}`;
    if (seen.has(key)) return `Duplicate block key: ${key}`;
    seen.add(key);
  }
  return null;
}

Question ↔ block reference rules

Rule Error message (suggested)
stimulus_block_key set but key not in stimulus_blocks "Question references unknown block: …"
stimulus_block_key empty string Treat as null or reject
function validateStimulusBlockKeys(
  blocks: EditableStimulusBlock[],
  questions: EditablePracticeQuestion[]
): string | null {
  const keys = new Set(blocks.map((b) => b.block_key.trim()));
  for (const q of questions) {
    const key = q.stimulus_block_key?.trim();
    if (!key) continue;
    if (!keys.has(key)) {
      return `Question references unknown stimulus block: ${key}`;
    }
  }
  return null;
}

Dynamic payload (with merge preview)

When validating a dynamic question linked to a block, merge locally before checking required schema fields:

function mergeEffectivePayload(
  blockStimulus: DynamicElementInstance[],
  questionPayload?: DynamicQuestionPayload
): DynamicQuestionPayload {
  // Mirror server MergeEffectiveDynamicPayload — see internal/domain/practice_stimulus_block.go
  const stimulus = [...blockStimulus];
  const byId = new Map(stimulus.map((el, i) => [el.id?.trim(), i]));
  for (const el of questionPayload?.stimulus ?? []) {
    const id = el.id?.trim();
    if (id && byId.has(id)) {
      stimulus[byId.get(id)!] = el;
    } else {
      stimulus.push(el);
    }
  }
  return {
    stimulus,
    response: questionPayload?.response ?? [],
  };
}

TypeScript types & helpers

export interface ApiResponse<T> {
  message: string;
  data: T;
  success?: boolean;
  status_code?: number;
}

export interface FullUpdateStimulusBlockItem {
  block_key: string;
  display_order?: number;
  stimulus: DynamicElementInstance[];
}

export interface FullUpdatePracticeQuestionItem {
  id?: number;
  display_order?: number;
  stimulus_block_key?: string | null;
  associated_question_id?: number | null;
  question_type?: string;
  question_type_definition_id?: number;
  dynamic_payload?: DynamicQuestionPayload;
  // ...match existing editor fields
}

export interface FullUpdatePracticeInput {
  practice?: {
    title?: string;
    story_description?: string;
    persona_id?: number | null;
    publish_status?: string;
    authoring_profile?: "STANDALONE" | "IELTS_SHARED_STIMULUS";
  };
  question_set?: {
    title?: string;
    shuffle_questions?: boolean;
    status?: string;
  };
  stimulus_blocks?: FullUpdateStimulusBlockItem[];
  questions?: FullUpdatePracticeQuestionItem[];
}

export interface PracticeFullResponse {
  practice: {
    id: number;
    authoring_profile: string;
    question_set_id: number;
    [key: string]: unknown;
  };
  question_set: Record<string, unknown>;
  stimulus_blocks: PracticeStimulusBlock[];
  questions: Array<{
    id: number;
    display_order?: number;
    stimulus_block_key?: string | null;
    dynamic_payload?: DynamicQuestionPayload;
    effective_dynamic_payload?: DynamicQuestionPayload;
    question_type: string;
    [key: string]: unknown;
  }>;
}

React integration patterns

Block dropdown on question card

function StimulusBlockField({
  question,
  blocks,
  onChange,
}: {
  question: EditablePracticeQuestion;
  blocks: EditableStimulusBlock[];
  onChange: (patch: Partial<EditablePracticeQuestion>) => void;
}) {
  return (
    <label>
      Shared stimulus block
      <select
        value={question.stimulus_block_key ?? ""}
        onChange={(e) =>
          onChange({
            stimulus_block_key: e.target.value ? e.target.value : null,
          })
        }
      >
        <option value="">None (standalone)</option>
        {blocks
          .sort((a, b) => a.display_order - b.display_order)
          .map((b) => (
            <option key={b.block_key} value={b.block_key}>
              {b.block_key}
            </option>
          ))}
      </select>
    </label>
  );
}

Save handler

async function savePractice(practiceId: number, state: PracticeEditorState, token: string) {
  const blockErr = validateStimulusBlocks(state.stimulusBlocks);
  if (blockErr) throw new Error(blockErr);
  const keyErr = validateStimulusBlockKeys(state.stimulusBlocks, state.questions);
  if (keyErr) throw new Error(keyErr);

  const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/full`, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(mapStateToSavePayload(state)),
  });

  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.error || body.message || `Save failed (${res.status})`);
  }

  const json: ApiResponse<PracticeFullResponse> = await res.json();
  return json.data;
}

After save, replace local state from the response so effective_dynamic_payload, block id values, and question id values stay in sync.


IELTS listening example (end-to-end)

Scenario: One audio clip, three multiple-choice questions.

  1. Set practice.authoring_profile = "IELTS_SHARED_STIMULUS".
  2. Add block listening-part-1 with AUDIO_PROMPT + INSTRUCTION.
  3. Add three DYNAMIC questions, each with stimulus_block_key: "listening-part-1" and only response in dynamic_payload.
  4. PUT /api/v1/practices/:id/full with stimulus_blocks + questions.
  5. GET confirms identical effective_dynamic_payload.stimulus on all three questions and different response on each.

Error handling

HTTP message Typical cause Admin UI action
400 Invalid stimulus block Bad block_key, unknown reference, duplicate key Highlight block or question row; show error detail
400 Invalid question item Merged dynamic payload fails definition validation Fix response or block stimulus
400 Invalid question association Unrelated association error See associations guide
404 Practice not found Wrong ID Navigate away
403 Permission denied Missing practices.update RBAC message

Always display API error string when present.


Learner app note

The learner app should render effective_dynamic_payload (or merge client-side with the same rules) when stimulus_block_key is set:

  1. Load practice questions via paginated list or full practice endpoint.
  2. If effective_dynamic_payload is present in the response, use it for rendering.
  3. If not present (older clients), fetch stimulus_blocks from full practice cache or merge locally from block map + dynamic_payload.

Response submission still uses the question id — blocks are not separate answer targets.


Integration checklist

Data & API

  • Migration 000095 applied in target environments
  • Practice load maps authoring_profile, stimulus_blocks, stimulus_block_key
  • Practice save sends stimulus_blocks when in IELTS mode
  • Sending stimulus_blocks: [] clears blocks (understood before mode switch)
  • Omitting stimulus_blocks on partial saves preserves existing blocks
  • Do not send effective_dynamic_payload on save
  • After save, refresh from response

UI

  • authoring_profile toggle switches editor layout
  • Block editor for shared stimulus[]
  • Per-question stimulus_block_key dropdown
  • Response-only panel when block assigned (IELTS mode)
  • Preview uses effective_dynamic_payload or local merge
  • Client-side block + key validation before save
  • Delete-block guard when questions reference key

QA scenarios

  • Standalone practice — no blocks, no keys (backward compatible)
  • IELTS practice — one block, multiple questions share audio
  • Per-question override of block element by id
  • Duplicate block_key in save — rejected
  • Question references missing block_key — rejected
  • stimulus_blocks: [] removes all blocks
  • Omit stimulus_blocks on question-only save — blocks preserved
  • Dynamic validation passes with empty question stimulus when block satisfies schema
  • Exam-prep .../exam-prep/practices/:id/full — same behavior
  • Combine with associated_question_id section gating

Limitations

Topic Phase 1 behavior
Granular question-set APIs stimulus_block_key not on POST/PUT question-sets/.../questions
Cross-practice blocks Not supported — blocks are scoped to one practice
Block reuse across practices Copy via admin UI / duplicate practice (future)
authoring_profile enforcement Metadata only — no server-side UI switching
Learner paginated question list Confirm effective_dynamic_payload is exposed on your learner route; full practice GET always includes it
Versioning / draft blocks No separate publish state — blocks save with practice

Quick reference

Full practice (preferred for admin editor)

Action LMS Exam-prep
Load GET /api/v1/practices/:id/full GET /api/v1/exam-prep/practices/:id/full
Save PUT /api/v1/practices/:id/full PUT /api/v1/exam-prep/practices/:id/full

Key fields

Field Direction Description
practice.authoring_profile Read/write STANDALONE or IELTS_SHARED_STIMULUS
stimulus_blocks[] Read/write Practice-level shared stimulus
stimulus_block_key Read/write Question → block link
dynamic_payload Read/write Stored per-question payload
effective_dynamic_payload Read-only Merged render payload

stimulus_blocks sync

PUT body Result
Omitted No change
[] Delete all blocks
[...] Upsert listed; delete unlisted

Minimal IELTS payload

{
  "practice": { "authoring_profile": "IELTS_SHARED_STIMULUS" },
  "stimulus_blocks": [
    {
      "block_key": "section-1",
      "stimulus": [
        { "id": "audio_1", "kind": "AUDIO_PROMPT", "value": "https://cdn.example.com/a.mp3" }
      ]
    }
  ],
  "questions": [
    {
      "id": 10,
      "display_order": 1,
      "stimulus_block_key": "section-1",
      "question_type": "DYNAMIC",
      "question_type_definition_id": 42,
      "dynamic_payload": { "stimulus": [], "response": [{ "id": "r1", "kind": "MULTIPLE_CHOICE", "value": {} }] }
    }
  ]
}