Add associated_question_id on question set items so authors can group practice questions into ordered sections. Expose prerequisite_question_ids on read APIs for client-side gating, validate associations on save, and document admin panel integration. Co-authored-by: Cursor <cursoragent@cursor.com>
837 lines
26 KiB
Markdown
837 lines
26 KiB
Markdown
# Practice Question Associations — Admin Panel Integration Guide
|
||
|
||
This guide documents how to integrate **question associations** into the Yimaru admin panel practice authoring flow. Associations let content authors group questions into **sequential sections** within a practice. Learners must complete earlier sections (in `display_order`) before later ones unlock.
|
||
|
||
> **Scope:** This feature adds `associated_question_id` on question set membership (`question_set_items`). It works alongside existing `display_order`. There is **no server-side per-question progress table** — the API returns `prerequisite_question_ids` so the **learner app** (or admin preview) can gate access client-side.
|
||
|
||
---
|
||
|
||
## Table of contents
|
||
|
||
1. [Feature overview](#feature-overview)
|
||
2. [Concepts: sections, anchors, and prerequisites](#concepts-sections-anchors-and-prerequisites)
|
||
3. [Architecture](#architecture)
|
||
4. [Prerequisites (backend)](#prerequisites-backend)
|
||
5. [Authentication & permissions](#authentication--permissions)
|
||
6. [Data model](#data-model)
|
||
7. [Response envelopes](#response-envelopes)
|
||
8. [Primary API: full practice save/load](#primary-api-full-practice-saveload)
|
||
9. [Granular question-set item APIs](#granular-question-set-item-apis)
|
||
10. [Recommended admin UI changes](#recommended-admin-ui-changes)
|
||
11. [Form state & serialization](#form-state--serialization)
|
||
12. [Client-side validation (mirror backend)](#client-side-validation-mirror-backend)
|
||
13. [TypeScript types & helpers](#typescript-types--helpers)
|
||
14. [React integration patterns](#react-integration-patterns)
|
||
15. [Error handling](#error-handling)
|
||
16. [Learner app note](#learner-app-note)
|
||
17. [Integration checklist](#integration-checklist)
|
||
18. [Limitations](#limitations)
|
||
19. [Quick reference](#quick-reference)
|
||
|
||
---
|
||
|
||
## Feature overview
|
||
|
||
| Capability | Admin panel | Learner app |
|
||
|------------|-------------|-------------|
|
||
| Set `display_order` per question in a practice | Yes (existing) | Uses order for presentation |
|
||
| Set `associated_question_id` per question | **Yes (new)** | Uses for section gating |
|
||
| Server tracks per-question completion | **No** | Client tracks locally / on submit |
|
||
| Read computed `prerequisite_question_ids` | Yes (in GET responses) | Yes — gate question access |
|
||
| Create associations for brand-new questions in one save | Yes | N/A |
|
||
|
||
### What problem this solves
|
||
|
||
Without associations, all questions in a practice are effectively one flat list ordered by `display_order`. With associations, authors can define **blocks**:
|
||
|
||
- **Section 1:** Questions 1–3 must be done in order.
|
||
- **Section 2:** Unlocks only after section 1 is fully complete.
|
||
- **Section 3:** Another independent block, and so on.
|
||
|
||
Authors express this by marking the **first question of each section** as a **section anchor** (`associated_question_id: null`) and linking follow-up questions in that section to the anchor’s question `id`.
|
||
|
||
---
|
||
|
||
## Concepts: sections, anchors, and prerequisites
|
||
|
||
### Fields on each question in a practice
|
||
|
||
| Field | Type | Meaning |
|
||
|-------|------|---------|
|
||
| `display_order` | `number` | Sort position within the practice (1-based typical). Controls presentation order. |
|
||
| `associated_question_id` | `number \| null` | If set, this question belongs to the section whose **anchor** is that question ID. If `null`, this question **is** a section anchor (starts a new block). |
|
||
|
||
### Example layout
|
||
|
||
| Question ID | display_order | associated_question_id | Role |
|
||
|-------------|---------------|------------------------|------|
|
||
| `101` | 1 | `null` | Anchor — section A |
|
||
| `102` | 2 | `101` | Section A, step 2 |
|
||
| `103` | 3 | `101` | Section A, step 3 |
|
||
| `104` | 4 | `null` | Anchor — section B |
|
||
| `105` | 5 | `104` | Section B, step 2 |
|
||
|
||
### Unlock rules (for learner gating)
|
||
|
||
The API computes `prerequisite_question_ids` for each question. A learner should not open question **Q** until every ID in `prerequisite_question_ids` is considered “completed” by the client.
|
||
|
||
**Anchor question** (`associated_question_id` is `null`):
|
||
|
||
- Prerequisites = all other questions in the set with **lower** `display_order`.
|
||
|
||
**Associated question** (`associated_question_id` = anchor ID):
|
||
|
||
- Prerequisites = all questions with `display_order` **before the anchor’s** `display_order` (previous sections), **plus** all questions in the **same section** with lower `display_order` (including the anchor).
|
||
|
||
### Visual diagram
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
subgraph SectionA["Section A (anchor: Q101)"]
|
||
Q101["Q101 order=1"]
|
||
Q102["Q102 order=2"]
|
||
Q103["Q103 order=3"]
|
||
Q101 --> Q102 --> Q103
|
||
end
|
||
|
||
subgraph SectionB["Section B (anchor: Q104)"]
|
||
Q104["Q104 order=4"]
|
||
Q105["Q105 order=5"]
|
||
Q104 --> Q105
|
||
end
|
||
|
||
SectionA -->|"all of A complete"| SectionB
|
||
```
|
||
|
||
---
|
||
|
||
## Architecture
|
||
|
||
```mermaid
|
||
flowchart TB
|
||
subgraph AdminPanel["Admin panel"]
|
||
PracticeEditor[Practice question editor]
|
||
SectionUI[Section / association controls]
|
||
SaveBtn[Save practice]
|
||
end
|
||
|
||
subgraph API["Yimaru 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"]
|
||
QSI["question_set_items.associated_question_id"]
|
||
end
|
||
|
||
PracticeEditor --> SectionUI
|
||
SaveBtn --> PutFull
|
||
SaveBtn --> PutEpFull
|
||
GetFull --> PracticeEditor
|
||
GetEpFull --> PracticeEditor
|
||
PutFull --> QSI
|
||
PutEpFull --> QSI
|
||
```
|
||
|
||
- **Migration:** `000088_question_set_item_associations` — adds `associated_question_id` to `question_set_items`.
|
||
- **Domain logic:** `internal/domain/question_set_item.go` — validation + `PrerequisiteQuestionIDs`.
|
||
- **Sync:** `internal/services/practicecontent/question_sync.go` — applies associations on full practice update (two-pass for new questions).
|
||
- **Handlers:** `internal/web_server/handlers/practice_full_update_handler.go`, `questions.go`.
|
||
|
||
---
|
||
|
||
## Prerequisites (backend)
|
||
|
||
Before testing from the admin panel:
|
||
|
||
1. Run database migrations (includes `000088`):
|
||
|
||
```bash
|
||
docker compose up migrate
|
||
```
|
||
|
||
2. Regenerate sqlc / redeploy API if you are on a dev branch that added this feature.
|
||
|
||
3. Confirm `question_set_items` has column `associated_question_id`:
|
||
|
||
```sql
|
||
\d question_set_items
|
||
```
|
||
|
||
---
|
||
|
||
## Authentication & permissions
|
||
|
||
Use a **team member** or **platform admin** token:
|
||
|
||
```http
|
||
Authorization: Bearer <access_token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
### LMS practices (Learn English)
|
||
|
||
| Action | Permission | HTTP |
|
||
|--------|------------|------|
|
||
| Load practice + questions | `practices.get` | `GET /api/v1/practices/:id/full` |
|
||
| Save practice + 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` |
|
||
|
||
### Granular question-set routes (optional)
|
||
|
||
| Action | Permission | HTTP |
|
||
|--------|------------|------|
|
||
| Add question to set | `question_set_items.add` | `POST /api/v1/question-sets/:setId/questions` |
|
||
| Update order + association | `question_set_items.update_order` | `PUT /api/v1/question-sets/:setId/questions/:questionId/order` |
|
||
| List questions in set | `question_set_items.list` | `GET /api/v1/question-sets/:setId/questions` |
|
||
|
||
The admin practice editor should prefer **`/practices/:id/full`** so metadata, question set settings, and all questions sync in one request.
|
||
|
||
---
|
||
|
||
## Data model
|
||
|
||
### Database
|
||
|
||
Table `question_set_items`:
|
||
|
||
| Column | Type | Notes |
|
||
|--------|------|-------|
|
||
| `set_id` | `bigint` | Question set linked to practice |
|
||
| `question_id` | `bigint` | Question bank row |
|
||
| `display_order` | `int` | Sort order in set |
|
||
| `associated_question_id` | `bigint NULL` | FK → `questions(id)`, `ON DELETE SET NULL` |
|
||
|
||
### JSON on each question (admin + learner list responses)
|
||
|
||
```typescript
|
||
interface PracticeQuestion {
|
||
id: number;
|
||
display_order?: number;
|
||
associated_question_id?: number | null;
|
||
prerequisite_question_ids?: number[];
|
||
// ...existing question fields (question_type, options, dynamic_payload, etc.)
|
||
}
|
||
```
|
||
|
||
- **`associated_question_id`** — what the author configured.
|
||
- **`prerequisite_question_ids`** — read-only, computed by API for gating. Do not send on save; the backend recalculates on read.
|
||
|
||
---
|
||
|
||
## Response envelopes
|
||
|
||
Success:
|
||
|
||
```json
|
||
{
|
||
"message": "Practice updated successfully",
|
||
"data": { },
|
||
"success": true,
|
||
"status_code": 200
|
||
}
|
||
```
|
||
|
||
Validation error (invalid association):
|
||
|
||
```json
|
||
{
|
||
"message": "Invalid question association",
|
||
"error": "invalid question association: associated question 102 must have a lower display_order than question 101"
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Primary API: full practice save/load
|
||
|
||
### Load practice (LMS)
|
||
|
||
```http
|
||
GET /api/v1/practices/:id/full
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Response `data` shape (relevant parts):**
|
||
|
||
```json
|
||
{
|
||
"practice": { "id": 12, "title": "...", "question_set_id": 55, "persona_id": 1 },
|
||
"question_set": { "id": 55, "title": "...", "question_count": 5 },
|
||
"questions": [
|
||
{
|
||
"id": 101,
|
||
"display_order": 1,
|
||
"associated_question_id": null,
|
||
"prerequisite_question_ids": [],
|
||
"question_type": "MCQ",
|
||
"options": []
|
||
},
|
||
{
|
||
"id": 102,
|
||
"display_order": 2,
|
||
"associated_question_id": 101,
|
||
"prerequisite_question_ids": [101],
|
||
"question_type": "MCQ",
|
||
"options": []
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
### Save practice (LMS)
|
||
|
||
```http
|
||
PUT /api/v1/practices/:id/full
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body (questions portion):**
|
||
|
||
```json
|
||
{
|
||
"practice": {
|
||
"title": "Listening drill",
|
||
"publish_status": "PUBLISHED"
|
||
},
|
||
"question_set": {
|
||
"shuffle_questions": false,
|
||
"status": "PUBLISHED"
|
||
},
|
||
"questions": [
|
||
{
|
||
"id": 101,
|
||
"display_order": 1,
|
||
"associated_question_id": null,
|
||
"question_type": "MCQ",
|
||
"question_text": "First prompt",
|
||
"options": [
|
||
{ "option_text": "A", "option_order": 1, "is_correct": true },
|
||
{ "option_text": "B", "option_order": 2, "is_correct": false }
|
||
]
|
||
},
|
||
{
|
||
"id": 102,
|
||
"display_order": 2,
|
||
"associated_question_id": 101,
|
||
"question_type": "MCQ",
|
||
"question_text": "Follow-up prompt",
|
||
"options": []
|
||
},
|
||
{
|
||
"display_order": 3,
|
||
"associated_question_id": 101,
|
||
"question_type": "SHORT_ANSWER",
|
||
"question_text": "New question in same section",
|
||
"short_answers": [{ "acceptable_answer": "hello", "match_type": "EXACT" }]
|
||
},
|
||
{
|
||
"display_order": 4,
|
||
"associated_question_id": null,
|
||
"question_type": "AUDIO",
|
||
"voice_prompt": "minio://audio/uuid.mp3",
|
||
"audio_correct_answer_text": "expected transcript"
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
| Field | On save | Notes |
|
||
|-------|---------|-------|
|
||
| `id` | Optional | Omit to **create** a new question. Include to **update** existing. |
|
||
| `display_order` | Recommended | Defaults to 1-based index in `questions` array if omitted. |
|
||
| `associated_question_id` | Optional | `null` or omit = section anchor. Must be a **persisted** question ID in the same practice. |
|
||
| `prerequisite_question_ids` | **Do not send** | Response-only. |
|
||
|
||
### 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`).
|
||
|
||
### Sync semantics (important for admin save)
|
||
|
||
- Questions **omitted** from the `questions` array are **removed from the set** (not deleted from the global question bank).
|
||
- On save, the backend:
|
||
1. Creates/updates question content.
|
||
2. Sets `display_order` on membership.
|
||
3. Validates all associations together.
|
||
4. Applies `associated_question_id` in a second pass (so new questions can reference other new questions in the **same** save, as long as the anchor already has an `id` from a prior save or appears earlier with an `id`).
|
||
|
||
**New questions without `id` cannot be used as `associated_question_id` targets until after the first save assigns IDs.** UI should only offer anchors from questions that already have `id`, or re-save after creation.
|
||
|
||
---
|
||
|
||
## Granular question-set item APIs
|
||
|
||
Use these only if the admin panel manages question sets **outside** the full practice editor.
|
||
|
||
### Add question to set
|
||
|
||
```http
|
||
POST /api/v1/question-sets/:setId/questions
|
||
```
|
||
|
||
```json
|
||
{
|
||
"question_id": 201,
|
||
"display_order": 3,
|
||
"associated_question_id": 101
|
||
}
|
||
```
|
||
|
||
### Update order and association
|
||
|
||
```http
|
||
PUT /api/v1/question-sets/:setId/questions/:questionId/order
|
||
```
|
||
|
||
```json
|
||
{
|
||
"display_order": 3,
|
||
"associated_question_id": 101
|
||
}
|
||
```
|
||
|
||
To clear an association (make question a section anchor), send `"associated_question_id": null`.
|
||
|
||
---
|
||
|
||
## Recommended admin UI changes
|
||
|
||
### 1. Extend the practice question list row
|
||
|
||
For each question in the practice editor, show:
|
||
|
||
| UI element | Purpose |
|
||
|------------|---------|
|
||
| Drag handle / order index | Maps to `display_order` |
|
||
| **Section** badge | “Anchor” vs “Part of section {n}” |
|
||
| **Section anchor** dropdown | Sets `associated_question_id` (`null` = this row is anchor) |
|
||
| Prerequisites preview (read-only) | Optional tooltip listing `prerequisite_question_ids` for author QA |
|
||
|
||
### 2. Section anchor dropdown options
|
||
|
||
Populate from questions in the **same practice** that are anchors:
|
||
|
||
```typescript
|
||
function anchorOptions(questions: EditablePracticeQuestion[], currentId?: number) {
|
||
return questions
|
||
.filter((q) => q.id != null && q.id !== currentId)
|
||
.filter((q) => q.associated_question_id == null) // only anchors
|
||
.sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0))
|
||
.map((q) => ({
|
||
value: q.id!,
|
||
label: `Q${q.display_order} — ${summarizeQuestion(q)}`,
|
||
}));
|
||
}
|
||
```
|
||
|
||
For a question that **is** an anchor, hide the dropdown or show “This question starts a section” with a control to convert it to an associated question.
|
||
|
||
### 3. “Start new section” action
|
||
|
||
When the author clicks **Add section** or **Start new section**:
|
||
|
||
1. Insert a new question (or mark existing) with `associated_question_id: null`.
|
||
2. Subsequent questions added under that section default to `associated_question_id: <anchorId>`.
|
||
|
||
### 4. Reorder behavior
|
||
|
||
When `display_order` changes via drag-and-drop:
|
||
|
||
1. Renumber `display_order` for all rows.
|
||
2. Revalidate associations client-side (anchor must still have lower order than associated questions).
|
||
3. If invalid, snap back or auto-clear invalid `associated_question_id`.
|
||
|
||
### 5. Authoring preview (optional)
|
||
|
||
Use `prerequisite_question_ids` from the last GET response (or compute locally with the same rules) to simulate locked/unlocked states in a preview mode. No extra API is required.
|
||
|
||
---
|
||
|
||
## Form state & serialization
|
||
|
||
### Suggested editable row type
|
||
|
||
```typescript
|
||
interface EditablePracticeQuestion {
|
||
/** Present after first save or when loaded from API */
|
||
id?: number;
|
||
display_order: number;
|
||
/** null = section anchor */
|
||
associated_question_id: number | null;
|
||
question_type: string;
|
||
question_text?: string;
|
||
question_type_definition_id?: number;
|
||
dynamic_payload?: DynamicQuestionPayload;
|
||
options?: CreateQuestionOptionInput[];
|
||
short_answers?: CreateShortAnswerInput[];
|
||
audio_correct_answer_text?: string;
|
||
// ...other fields your editor already uses
|
||
}
|
||
```
|
||
|
||
### Load: API → form state
|
||
|
||
```typescript
|
||
function mapApiQuestionToEditable(q: PracticeQuestion): EditablePracticeQuestion {
|
||
return {
|
||
id: q.id,
|
||
display_order: q.display_order ?? 1,
|
||
associated_question_id: q.associated_question_id ?? null,
|
||
question_type: q.question_type,
|
||
question_text: q.question_text,
|
||
question_type_definition_id: q.question_type_definition_id,
|
||
dynamic_payload: q.dynamic_payload,
|
||
options: q.options,
|
||
short_answers: q.short_answers,
|
||
audio_correct_answer_text: q.audio_correct_answer_text,
|
||
};
|
||
}
|
||
```
|
||
|
||
### Save: form state → API
|
||
|
||
```typescript
|
||
function mapEditableToSaveItem(q: EditablePracticeQuestion): FullUpdatePracticeQuestionItem {
|
||
return {
|
||
...(q.id != null ? { id: q.id } : {}),
|
||
display_order: q.display_order,
|
||
associated_question_id: q.associated_question_id,
|
||
question_type: q.question_type,
|
||
question_text: q.question_text,
|
||
question_type_definition_id: q.question_type_definition_id,
|
||
dynamic_payload: q.dynamic_payload,
|
||
options: q.options,
|
||
short_answers: q.short_answers,
|
||
audio_correct_answer_text: q.audio_correct_answer_text,
|
||
};
|
||
}
|
||
```
|
||
|
||
Send the full practice payload:
|
||
|
||
```typescript
|
||
await api.put(`/api/v1/practices/${practiceId}/full`, {
|
||
practice: { title, publish_status, persona_id },
|
||
question_set: { status: "PUBLISHED", shuffle_questions: false },
|
||
questions: editableQuestions.map(mapEditableToSaveItem),
|
||
});
|
||
```
|
||
|
||
---
|
||
|
||
## Client-side validation (mirror backend)
|
||
|
||
Validate **before** save to avoid round trips. Rules match `domain.ValidateQuestionSetAssociations`:
|
||
|
||
| Rule | Error message (suggested) |
|
||
|------|---------------------------|
|
||
| `associated_question_id === question.id` | “A question cannot be associated with itself.” |
|
||
| Target ID not in practice list | “Associated question must belong to this practice.” |
|
||
| Target is not an anchor (it has its own `associated_question_id`) | “Associated question must be a section anchor.” |
|
||
| Target `display_order` ≥ this question’s `display_order` | “Section anchor must appear before this question.” |
|
||
|
||
```typescript
|
||
function validateAssociations(questions: EditablePracticeQuestion[]): string | null {
|
||
const byId = new Map<number, EditablePracticeQuestion>();
|
||
for (const q of questions) {
|
||
if (q.id != null) byId.set(q.id, q);
|
||
}
|
||
|
||
for (const q of questions) {
|
||
if (q.associated_question_id == null || q.id == null) continue;
|
||
const assocId = q.associated_question_id;
|
||
if (assocId === q.id) return "A question cannot be associated with itself.";
|
||
const anchor = byId.get(assocId);
|
||
if (!anchor) return "Associated question must belong to this practice.";
|
||
if (anchor.associated_question_id != null) {
|
||
return "Associated question must be a section anchor.";
|
||
}
|
||
if ((anchor.display_order ?? 0) >= (q.display_order ?? 0)) {
|
||
return "Section anchor must appear before this question.";
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
```
|
||
|
||
Skip association targets that only exist as new rows without `id` — show inline hint: “Save once to link new questions to this section.”
|
||
|
||
---
|
||
|
||
## TypeScript types & helpers
|
||
|
||
```typescript
|
||
export interface ApiResponse<T> {
|
||
message: string;
|
||
data: T;
|
||
success?: boolean;
|
||
status_code?: number;
|
||
}
|
||
|
||
export interface FullUpdatePracticeQuestionItem {
|
||
id?: number;
|
||
display_order?: number;
|
||
associated_question_id?: number | null;
|
||
question_text?: string;
|
||
question_type?: string;
|
||
question_type_definition_id?: number;
|
||
dynamic_payload?: unknown;
|
||
options?: Array<{
|
||
option_text: string;
|
||
option_order?: number;
|
||
is_correct: boolean;
|
||
}>;
|
||
short_answers?: Array<{
|
||
acceptable_answer: string;
|
||
match_type?: string;
|
||
}>;
|
||
audio_correct_answer_text?: string;
|
||
// ...match existing editor fields
|
||
}
|
||
|
||
export interface FullUpdatePracticeInput {
|
||
practice?: {
|
||
title?: string;
|
||
story_description?: string;
|
||
persona_id?: number | null;
|
||
publish_status?: string;
|
||
};
|
||
question_set?: {
|
||
title?: string;
|
||
shuffle_questions?: boolean;
|
||
status?: string;
|
||
intro_video_url?: string;
|
||
};
|
||
questions?: FullUpdatePracticeQuestionItem[];
|
||
}
|
||
|
||
export interface PracticeFullResponse {
|
||
practice: Record<string, unknown>;
|
||
question_set: Record<string, unknown>;
|
||
questions: Array<{
|
||
id: number;
|
||
display_order?: number;
|
||
associated_question_id?: number | null;
|
||
prerequisite_question_ids?: number[];
|
||
question_type: string;
|
||
[key: string]: unknown;
|
||
}>;
|
||
}
|
||
```
|
||
|
||
### Optional: compute prerequisites in the admin preview
|
||
|
||
If you need live preview before save, port the same logic the API uses (`PrerequisiteQuestionIDs` in `internal/domain/question_set_item.go`). After save, prefer API-returned `prerequisite_question_ids`.
|
||
|
||
---
|
||
|
||
## React integration patterns
|
||
|
||
### Minimal section control on a question card
|
||
|
||
```tsx
|
||
function QuestionAssociationField({
|
||
question,
|
||
allQuestions,
|
||
onChange,
|
||
}: {
|
||
question: EditablePracticeQuestion;
|
||
allQuestions: EditablePracticeQuestion[];
|
||
onChange: (patch: Partial<EditablePracticeQuestion>) => void;
|
||
}) {
|
||
const isAnchor = question.associated_question_id == null;
|
||
const anchors = allQuestions.filter(
|
||
(q) => q.id != null && q.id !== question.id && q.associated_question_id == null
|
||
);
|
||
|
||
return (
|
||
<div>
|
||
<label>
|
||
<input
|
||
type="checkbox"
|
||
checked={isAnchor}
|
||
onChange={(e) =>
|
||
onChange({ associated_question_id: e.target.checked ? null : anchors[0]?.id ?? null })
|
||
}
|
||
/>
|
||
Starts a new section
|
||
</label>
|
||
|
||
{!isAnchor && (
|
||
<select
|
||
value={question.associated_question_id ?? ""}
|
||
onChange={(e) =>
|
||
onChange({
|
||
associated_question_id: e.target.value ? Number(e.target.value) : null,
|
||
})
|
||
}
|
||
>
|
||
<option value="">Select section anchor</option>
|
||
{anchors.map((a) => (
|
||
<option key={a.id} value={a.id}>
|
||
Q{a.display_order} (id {a.id})
|
||
</option>
|
||
))}
|
||
</select>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
```
|
||
|
||
### Save handler
|
||
|
||
```typescript
|
||
async function savePractice(practiceId: number, state: PracticeEditorState, token: string) {
|
||
const err = validateAssociations(state.questions);
|
||
if (err) throw new Error(err);
|
||
|
||
const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/full`, {
|
||
method: "PUT",
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
},
|
||
body: JSON.stringify({
|
||
practice: state.practice,
|
||
question_set: state.questionSet,
|
||
questions: state.questions.map(mapEditableToSaveItem),
|
||
}),
|
||
});
|
||
|
||
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 new question `id` values and association fields stay in sync.
|
||
|
||
---
|
||
|
||
## Error handling
|
||
|
||
| HTTP | `message` | Typical cause | Admin UI action |
|
||
|------|-----------|---------------|-----------------|
|
||
| 400 | `Invalid question association` | Broken anchor reference or order | Highlight offending row; show `error` detail |
|
||
| 400 | `Invalid question item` | Missing `question_type`, bad dynamic payload, etc. | Existing question validation |
|
||
| 404 | `Practice not found` | Wrong ID | Navigate away |
|
||
| 403 | Permission denied | Missing `practices.update` | RBAC message |
|
||
|
||
Always display API `error` string when present — it includes the specific rule that failed.
|
||
|
||
---
|
||
|
||
## Learner app note
|
||
|
||
The admin panel **configures** associations; the learner app **enforces** them without server progress tracking:
|
||
|
||
1. `GET /api/v1/practices/:practiceId/questions` (paginated) or full practice payload includes `prerequisite_question_ids` per question.
|
||
2. The client marks questions complete locally (or on answer submit).
|
||
3. A question is enterable only when every ID in `prerequisite_question_ids` is complete.
|
||
|
||
Admin authors can verify structure using the same fields in GET responses — no separate preview API is required.
|
||
|
||
---
|
||
|
||
## Integration checklist
|
||
|
||
### Data & API
|
||
|
||
- [ ] Migration `000088` applied in target environments
|
||
- [ ] Practice load (`GET .../full`) maps `associated_question_id` into editor state
|
||
- [ ] Practice save (`PUT .../full`) sends `associated_question_id` per question
|
||
- [ ] Do **not** send `prerequisite_question_ids` on save
|
||
- [ ] After save, refresh question list from response (new `id` values)
|
||
|
||
### UI
|
||
|
||
- [ ] Section anchor control per question row
|
||
- [ ] “Start new section” defaults `associated_question_id: null`
|
||
- [ ] Associated questions pick anchor from dropdown (anchors only)
|
||
- [ ] Drag-and-drop reorder updates `display_order` and revalidates
|
||
- [ ] Client-side validation before save
|
||
- [ ] Inline error for invalid association (400 from API)
|
||
|
||
### QA scenarios
|
||
|
||
- [ ] Single-section practice — all anchors, all `associated_question_id: null` (behaves like flat sequential list)
|
||
- [ ] Two sections — complete validation on save
|
||
- [ ] Reorder anchor above its dependents — save rejected or client blocked
|
||
- [ ] Associate to non-anchor question — rejected
|
||
- [ ] Create new questions + associations in **one** save (anchor has existing `id`)
|
||
- [ ] Create brand-new practice: first save creates IDs; second save can link new rows to first anchor
|
||
- [ ] Exam-prep practice editor — same fields on `exam-prep/.../full` routes
|
||
- [ ] GET response shows expected `prerequisite_question_ids` for learner QA
|
||
|
||
---
|
||
|
||
## Limitations
|
||
|
||
| Topic | Current behavior |
|
||
|-------|------------------|
|
||
| Server-side question progress | Not implemented — client gates access |
|
||
| `associated_question_id` targets | Must be question **IDs** in the same set |
|
||
| New question as anchor for same-save children | Anchor must have `id` (from load or prior save) |
|
||
| Cross-practice associations | Not supported |
|
||
| Branching / skip paths | Only linear sections + order within section |
|
||
| `shuffle_questions` on question set | May conflict with authored order — document for authors |
|
||
|
||
---
|
||
|
||
## 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` |
|
||
|
||
### Per-question fields
|
||
|
||
| Field | Direction | Description |
|
||
|-------|-----------|-------------|
|
||
| `display_order` | Read/write | Sort position |
|
||
| `associated_question_id` | Read/write | `null` = section anchor; else anchor question ID |
|
||
| `prerequisite_question_ids` | Read-only | Computed unlock list for clients |
|
||
|
||
### Validation rules (save)
|
||
|
||
1. Associated ID must exist in the same practice question list.
|
||
2. Associated ID must point to an **anchor** (`associated_question_id` is null).
|
||
3. Anchor `display_order` must be **less than** dependent `display_order`.
|
||
4. No self-association.
|
||
|
||
### Example two-section payload (minimal)
|
||
|
||
```json
|
||
{
|
||
"questions": [
|
||
{ "id": 1, "display_order": 1, "associated_question_id": null },
|
||
{ "id": 2, "display_order": 2, "associated_question_id": 1 },
|
||
{ "id": 3, "display_order": 3, "associated_question_id": null },
|
||
{ "id": 4, "display_order": 4, "associated_question_id": 3 }
|
||
]
|
||
}
|
||
```
|