docs: add question type practices list admin panel integration guide
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
8d46581485
commit
085a9a3db4
|
|
@ -0,0 +1,757 @@
|
|||
# Question Type Definition — Practices List Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **`GET /api/v1/questions/type-definitions/:id/practices`** into the Yimaru **admin panel**. Use it for the **“Practices using this definition”** modal on the Question types page: list every LMS and exam-prep practice whose question set contains at least one non-archived question of that type, show where each practice is attached in the hierarchy, and link editors into the correct practice shell.
|
||||
|
||||
> **Scope:** Admin read-only listing from question type definitions. Practice create/edit, parent attach/detach, and question authoring are covered in related guides.
|
||||
>
|
||||
> **Related:**
|
||||
> - [question-type-definition-groups-admin-panel-integration.md](./question-type-definition-groups-admin-panel-integration.md) — definition CRUD and groups
|
||||
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — LMS `parents` attach/replace
|
||||
> - [practice-parent-unlink-admin-panel-integration.md](./practice-parent-unlink-admin-panel-integration.md) — per-parent unlink
|
||||
> - [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md) — full practice question editor
|
||||
|
||||
---
|
||||
|
||||
## Table of contents
|
||||
|
||||
1. [Feature overview](#feature-overview)
|
||||
2. [When to use this endpoint](#when-to-use-this-endpoint)
|
||||
3. [Architecture](#architecture)
|
||||
4. [Authentication & permissions](#authentication--permissions)
|
||||
5. [API reference](#api-reference)
|
||||
6. [Response model](#response-model)
|
||||
7. [Parent / location fields (critical)](#parent--location-fields-critical)
|
||||
8. [Matching rules](#matching-rules)
|
||||
9. [Visibility & draft practices](#visibility--draft-practices)
|
||||
10. [Recommended admin UI](#recommended-admin-ui)
|
||||
11. [Displaying location labels](#displaying-location-labels)
|
||||
12. [Navigation: Edit practice](#navigation-edit-practice)
|
||||
13. [TypeScript types & API client](#typescript-types--api-client)
|
||||
14. [React integration patterns](#react-integration-patterns)
|
||||
15. [Pagination](#pagination)
|
||||
16. [Empty & error states](#empty--error-states)
|
||||
17. [Testing checklist](#testing-checklist)
|
||||
18. [Integration checklist](#integration-checklist)
|
||||
19. [Limitations](#limitations)
|
||||
20. [Quick reference](#quick-reference)
|
||||
|
||||
---
|
||||
|
||||
## Feature overview
|
||||
|
||||
| Capability | Detail |
|
||||
|------------|--------|
|
||||
| Global practice lookup | Find **all** practices (LMS + exam-prep) using a given question type definition |
|
||||
| Cross-product | Single response merges `lms_practices` and `exam_prep.lesson_practices` |
|
||||
| Match count | Each row includes `matching_question_count` (non-archived questions of this type in the practice’s set) |
|
||||
| LMS locations | `parents` — `COURSE`, `MODULE`, `LESSON` (multi-parent supported) |
|
||||
| Exam-prep locations | `exam_prep_parents` — `CATALOG_COURSE`, `UNIT`, `LESSON` |
|
||||
| Legacy field | `exam_prep_lesson_id` — populated only when a `LESSON` parent exists (backward compatibility) |
|
||||
|
||||
### What problem this solves
|
||||
|
||||
From the Question types admin page, content teams need to answer:
|
||||
|
||||
- Which practices already use **Audio Conversation** (or any builder definition)?
|
||||
- Where is each practice attached — course, lesson, catalog course, unit?
|
||||
- How many questions of this type does each practice contain?
|
||||
- Is a practice **unlinked** (no hierarchy parents) or attached somewhere?
|
||||
|
||||
This endpoint powers the modal that lists those practices without navigating course/unit/lesson trees manually.
|
||||
|
||||
---
|
||||
|
||||
## When to use this endpoint
|
||||
|
||||
| Use this endpoint | Do **not** use it for |
|
||||
|-------------------|----------------------|
|
||||
| “Practices using this definition” modal | Listing practices on a specific course/module/lesson page |
|
||||
| Impact analysis before changing a question type | Full practice load with questions (`GET .../practices/:id/full`) |
|
||||
| Finding unlinked shells that happen to use a type | Creating a practice (`POST .../practices`) |
|
||||
|
||||
**Hierarchy-scoped lists** (unchanged):
|
||||
|
||||
| Scope | Endpoint |
|
||||
|-------|----------|
|
||||
| LMS course | `GET /api/v1/courses/:id/practices` |
|
||||
| LMS module | `GET /api/v1/modules/:id/practices` |
|
||||
| LMS lesson | `GET /api/v1/lessons/:id/practices` |
|
||||
| Exam-prep catalog course | `GET /api/v1/exam-prep/catalog-courses/:id/practices` |
|
||||
| Exam-prep unit | `GET /api/v1/exam-prep/units/:id/practices` |
|
||||
| Exam-prep lesson | `GET /api/v1/exam-prep/lessons/:id/practices` |
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin UI (Question types)
|
||||
participant API as API
|
||||
participant DB as Database
|
||||
|
||||
UI->>API: GET /questions/type-definitions/37
|
||||
API-->>UI: definition { id, key, display_name, ... }
|
||||
|
||||
UI->>API: GET /questions/type-definitions/37/practices?limit=10&offset=0
|
||||
API->>DB: Match questions by definition_id or legacy question_type
|
||||
API->>DB: UNION lms_practices + exam_prep.lesson_practices
|
||||
API->>DB: Batch load lms_practice_parents + exam_prep.practice_parents
|
||||
API-->>UI: { practices[], total_count, ... }
|
||||
|
||||
UI->>UI: Render rows with location from parents / exam_prep_parents
|
||||
```
|
||||
|
||||
### Backend touchpoints
|
||||
|
||||
| Layer | Location |
|
||||
|-------|----------|
|
||||
| Route | `GET /api/v1/questions/type-definitions/:id/practices` |
|
||||
| Handler | `ListPracticesByQuestionTypeDefinition` — `internal/web_server/handlers/question_type_builder.go` |
|
||||
| Service | `questions.Service.ListPracticesByQuestionTypeDefinition` |
|
||||
| SQL | `db/query/practices_by_question_type.sql` |
|
||||
| Domain | `internal/domain/practice_by_question_type.go` |
|
||||
| Repository | `internal/repository/questions.go` — batch parent hydration |
|
||||
|
||||
---
|
||||
|
||||
## Authentication & permissions
|
||||
|
||||
```http
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
| Action | Permission |
|
||||
|--------|------------|
|
||||
| List practices by question type | `practices.list` |
|
||||
|
||||
Team members and platform admins with `practices.list` can call this endpoint. Learner tokens may also receive results, but only **published** practices (see [Visibility](#visibility--draft-practices)).
|
||||
|
||||
---
|
||||
|
||||
## API reference
|
||||
|
||||
### List practices for a question type definition
|
||||
|
||||
```http
|
||||
GET /api/v1/questions/type-definitions/:id/practices
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
#### Path parameters
|
||||
|
||||
| Param | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | int64 | Question type definition ID (`question_type_definitions.id`) |
|
||||
|
||||
#### Query parameters
|
||||
|
||||
| Param | Default | Max | Description |
|
||||
|-------|---------|-----|-------------|
|
||||
| `limit` | `20` | `200` | Page size |
|
||||
| `offset` | `0` | — | Rows to skip |
|
||||
|
||||
#### Example request
|
||||
|
||||
```http
|
||||
GET /api/v1/questions/type-definitions/37/practices?limit=10&offset=0
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
#### Success response `200 OK`
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"status_code": 200,
|
||||
"message": "Practices retrieved successfully",
|
||||
"data": {
|
||||
"question_type_definition_id": 37,
|
||||
"practices": [
|
||||
{
|
||||
"practice_kind": "EXAM_PREP",
|
||||
"practice_id": 47,
|
||||
"question_set_id": 225,
|
||||
"title": "test",
|
||||
"story_description": "test",
|
||||
"publish_status": "PUBLISHED",
|
||||
"parents": null,
|
||||
"exam_prep_parents": [
|
||||
{ "parent_kind": "CATALOG_COURSE", "parent_id": 3 }
|
||||
],
|
||||
"matching_question_count": 1,
|
||||
"created_at": "2026-02-07T05:34:48Z",
|
||||
"updated_at": "2026-02-07T05:35:00Z"
|
||||
},
|
||||
{
|
||||
"practice_kind": "EXAM_PREP",
|
||||
"practice_id": 92,
|
||||
"question_set_id": 160,
|
||||
"title": "Talking About Places in Town",
|
||||
"publish_status": "PUBLISHED",
|
||||
"parents": null,
|
||||
"exam_prep_parents": [
|
||||
{ "parent_kind": "LESSON", "parent_id": 35 }
|
||||
],
|
||||
"exam_prep_lesson_id": 35,
|
||||
"matching_question_count": 4,
|
||||
"created_at": "2026-05-26T08:51:19Z"
|
||||
},
|
||||
{
|
||||
"practice_kind": "LMS",
|
||||
"practice_id": 91,
|
||||
"question_set_id": 159,
|
||||
"title": "The Ultimate Challenge: Putting Your English to the Test (A1 Capstone)",
|
||||
"publish_status": "PUBLISHED",
|
||||
"parents": [
|
||||
{ "parent_kind": "COURSE", "parent_id": 2 }
|
||||
],
|
||||
"matching_question_count": 15,
|
||||
"created_at": "2026-05-26T01:42:15Z"
|
||||
}
|
||||
],
|
||||
"total_count": 53,
|
||||
"limit": 10,
|
||||
"offset": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Error responses
|
||||
|
||||
| HTTP | `message` | Cause |
|
||||
|------|-----------|-------|
|
||||
| **400** | `Invalid id` | Non-positive or non-numeric `:id` |
|
||||
| **404** | `Question type definition not found` | Unknown definition ID |
|
||||
| **401** / **403** | — | Missing token or `practices.list` permission |
|
||||
| **500** | `Failed to list practices` | Server error |
|
||||
|
||||
---
|
||||
|
||||
## Response model
|
||||
|
||||
### `PracticesByQuestionTypeDefinitionSummary` (`data`)
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `question_type_definition_id` | number | Echo of path `:id` |
|
||||
| `practices` | array | Practice rows (may be empty) |
|
||||
| `total_count` | number | Total matches across LMS + exam-prep (for pagination) |
|
||||
| `limit` | number | Applied page size |
|
||||
| `offset` | number | Applied offset |
|
||||
|
||||
### `PracticeByQuestionTypeDefinition` (each item in `practices`)
|
||||
|
||||
| Field | Type | When present |
|
||||
|-------|------|--------------|
|
||||
| `practice_kind` | `"LMS"` \| `"EXAM_PREP"` | Always |
|
||||
| `practice_id` | number | Always — use with `practice_kind` for edit links |
|
||||
| `question_set_id` | number | Always |
|
||||
| `title` | string | Always |
|
||||
| `story_description` | string \| omitted | Optional |
|
||||
| `story_image` | string \| omitted | Optional |
|
||||
| `persona_id` | number \| omitted | Optional |
|
||||
| `quick_tips` | string \| omitted | Optional |
|
||||
| `publish_status` | `"DRAFT"` \| `"PUBLISHED"` | Always |
|
||||
| `parents` | array \| `null` | **LMS only** — hierarchy links |
|
||||
| `exam_prep_parents` | array \| `null` | **Exam-prep only** — hierarchy links |
|
||||
| `exam_prep_lesson_id` | number \| omitted | Exam-prep — set when a `LESSON` parent exists |
|
||||
| `matching_question_count` | number | Count of matching non-archived questions in the set |
|
||||
| `created_at` | ISO datetime | Always |
|
||||
| `updated_at` | ISO datetime \| omitted | When shell was last updated |
|
||||
|
||||
---
|
||||
|
||||
## Parent / location fields (critical)
|
||||
|
||||
The admin modal **must** branch on `practice_kind`. Using only `exam_prep_lesson_id` for exam-prep rows will show **“Unlinked”** for catalog-course and unit attachments.
|
||||
|
||||
### LMS (`practice_kind === "LMS"`)
|
||||
|
||||
Read **`parents`**:
|
||||
|
||||
```json
|
||||
"parents": [
|
||||
{ "parent_kind": "COURSE", "parent_id": 2 },
|
||||
{ "parent_kind": "LESSON", "parent_id": 42 }
|
||||
]
|
||||
```
|
||||
|
||||
- `null` or missing → practice has **no** LMS hierarchy links (unlinked shell).
|
||||
- Multiple entries are valid (multi-parent).
|
||||
|
||||
### Exam-prep (`practice_kind === "EXAM_PREP"`)
|
||||
|
||||
Read **`exam_prep_parents`** (primary):
|
||||
|
||||
```json
|
||||
"exam_prep_parents": [
|
||||
{ "parent_kind": "CATALOG_COURSE", "parent_id": 3 }
|
||||
]
|
||||
```
|
||||
|
||||
| `parent_kind` | Entity |
|
||||
|---------------|--------|
|
||||
| `CATALOG_COURSE` | `exam_prep.catalog_courses.id` |
|
||||
| `UNIT` | `exam_prep.units.id` |
|
||||
| `LESSON` | `exam_prep.unit_module_lessons.id` |
|
||||
|
||||
- `null` or `[]` → exam-prep practice is **unlinked**.
|
||||
- **`exam_prep_lesson_id`** is a convenience duplicate when a `LESSON` parent exists. **Do not** use it as the sole source of truth.
|
||||
|
||||
### Common bug (fixed in backend)
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
|---------|-------|-----|
|
||||
| Catalog-course practice shows **Unlinked** | UI only checked `exam_prep_lesson_id` | Read `exam_prep_parents` for `CATALOG_COURSE` / `UNIT` |
|
||||
|
||||
---
|
||||
|
||||
## Matching rules
|
||||
|
||||
A practice appears in the list when its **question set** contains at least one **non-archived** question that matches the definition:
|
||||
|
||||
1. **Primary:** `questions.question_type_definition_id = :id`
|
||||
2. **Legacy fallback:** `question_type_definition_id IS NULL` and `questions.question_type` matches the definition’s resolved runtime type (e.g. `audio_conversation_type` for an audio conversation definition). `DYNAMIC` definitions do not use legacy fallback.
|
||||
|
||||
`matching_question_count` is the number of such questions in that practice’s set (not necessarily all questions in the set).
|
||||
|
||||
Practices with **zero** matching questions after archival are excluded.
|
||||
|
||||
---
|
||||
|
||||
## Visibility & draft practices
|
||||
|
||||
`published_only` is set server-side from the caller’s role:
|
||||
|
||||
| Caller | `published_only` | Sees draft practices? |
|
||||
|--------|------------------|------------------------|
|
||||
| Learner / student roles | `true` | **No** — only `PUBLISHED` |
|
||||
| Users **without** `practices.create` or `practices.update` | `true` | **No** |
|
||||
| Content managers with `practices.create` or `practices.update` | `false` | **Yes** — includes `DRAFT` |
|
||||
|
||||
Admin panel users with practice edit permissions should see draft rows and can show a **DRAFT** badge (as in the screenshot).
|
||||
|
||||
---
|
||||
|
||||
## Recommended admin UI
|
||||
|
||||
### Modal: “Practices using this definition”
|
||||
|
||||
Triggered from a question type row (e.g. **Audio Conversation · #37**).
|
||||
|
||||
**Header**
|
||||
|
||||
- Title: `Practices using this definition`
|
||||
- Subtitle: `{display_name} · #{definition_id} · {key}` from `GET /questions/type-definitions/:id`
|
||||
- **+ Create practice** — navigates to create flow with this definition context (implementation-specific; often create question set + practice shell)
|
||||
|
||||
**Each row**
|
||||
|
||||
| Column / area | Source |
|
||||
|---------------|--------|
|
||||
| Title | `title` |
|
||||
| Meta line | `practice #{practice_id} · set #{question_set_id} · {location}` |
|
||||
| Description | `story_description` (truncate) |
|
||||
| Created | `created_at` |
|
||||
| Status | `publish_status` badge |
|
||||
| Match count | `{matching_question_count} matching question(s)` |
|
||||
| Action | **Edit practice** — route by `practice_kind` |
|
||||
|
||||
**Location segment** — use [Displaying location labels](#displaying-location-labels); never show red **Unlinked** when `exam_prep_parents` or `parents` has entries.
|
||||
|
||||
**Footer**
|
||||
|
||||
- `Showing {offset+1}-{min(offset+limit, total_count)} of {total_count}`
|
||||
- Rows-per-page selector (`limit`)
|
||||
- Previous / Next (`offset`)
|
||||
|
||||
---
|
||||
|
||||
## Displaying location labels
|
||||
|
||||
### Helper (recommended)
|
||||
|
||||
```typescript
|
||||
type LmsParentKind = "COURSE" | "MODULE" | "LESSON";
|
||||
type ExamPrepParentKind = "CATALOG_COURSE" | "UNIT" | "LESSON";
|
||||
|
||||
interface PracticeParent {
|
||||
parent_kind: LmsParentKind;
|
||||
parent_id: number;
|
||||
}
|
||||
|
||||
interface ExamPrepPracticeParent {
|
||||
parent_kind: ExamPrepParentKind;
|
||||
parent_id: number;
|
||||
}
|
||||
|
||||
interface PracticeByQuestionTypeDefinition {
|
||||
practice_kind: "LMS" | "EXAM_PREP";
|
||||
practice_id: number;
|
||||
question_set_id: number;
|
||||
title: string;
|
||||
parents?: PracticeParent[] | null;
|
||||
exam_prep_parents?: ExamPrepPracticeParent[] | null;
|
||||
exam_prep_lesson_id?: number | null;
|
||||
matching_question_count: number;
|
||||
publish_status: "DRAFT" | "PUBLISHED";
|
||||
created_at: string;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
function formatLmsParentLabel(parent: PracticeParent): string {
|
||||
switch (parent.parent_kind) {
|
||||
case "COURSE":
|
||||
return `Course #${parent.parent_id}`;
|
||||
case "MODULE":
|
||||
return `Module #${parent.parent_id}`;
|
||||
case "LESSON":
|
||||
return `Lesson #${parent.parent_id}`;
|
||||
default:
|
||||
return `${parent.parent_kind} #${parent.parent_id}`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatExamPrepParentLabel(parent: ExamPrepPracticeParent): string {
|
||||
switch (parent.parent_kind) {
|
||||
case "CATALOG_COURSE":
|
||||
return `Catalog course #${parent.parent_id}`;
|
||||
case "UNIT":
|
||||
return `Unit #${parent.parent_id}`;
|
||||
case "LESSON":
|
||||
return `Lesson #${parent.parent_id}`;
|
||||
default:
|
||||
return `${parent.parent_kind} #${parent.parent_id}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Single-line location for the practice meta row (e.g. "Course #2 · Lesson #42"). */
|
||||
export function formatPracticeLocation(row: PracticeByQuestionTypeDefinition): string {
|
||||
if (row.practice_kind === "LMS") {
|
||||
const parents = row.parents ?? [];
|
||||
if (parents.length === 0) return "Unlinked";
|
||||
return parents.map(formatLmsParentLabel).join(" · ");
|
||||
}
|
||||
|
||||
const parents = row.exam_prep_parents ?? [];
|
||||
if (parents.length > 0) {
|
||||
return parents.map(formatExamPrepParentLabel).join(" · ");
|
||||
}
|
||||
|
||||
// Backward compat: old API responses before exam_prep_parents hydration
|
||||
if (row.exam_prep_lesson_id != null) {
|
||||
return `Lesson #${row.exam_prep_lesson_id}`;
|
||||
}
|
||||
|
||||
return "Unlinked";
|
||||
}
|
||||
```
|
||||
|
||||
### Resolving human-readable names (optional enhancement)
|
||||
|
||||
IDs alone (`Course #2`) match the current screenshot. To show titles:
|
||||
|
||||
1. Collect unique parent IDs per kind from the current page.
|
||||
2. Batch-fetch catalog courses, units, lessons, courses, modules via existing admin list/get APIs.
|
||||
3. Replace `#2` with `Algebra I` in the label.
|
||||
|
||||
Cache results per session to avoid N+1 calls on pagination.
|
||||
|
||||
### Styling **Unlinked**
|
||||
|
||||
Use muted/warning styling only when `formatPracticeLocation` returns `"Unlinked"`. Do **not** key off `exam_prep_lesson_id === null` alone for exam-prep rows.
|
||||
|
||||
---
|
||||
|
||||
## Navigation: Edit practice
|
||||
|
||||
Route using **`practice_kind`** + **`practice_id`**:
|
||||
|
||||
| `practice_kind` | Edit destination (examples) |
|
||||
|-----------------|----------------------------|
|
||||
| `LMS` | `/admin/lms/practices/{practice_id}` or `GET /api/v1/practices/{practice_id}/full` editor |
|
||||
| `EXAM_PREP` | `/admin/exam-prep/practices/{practice_id}` or `GET /api/v1/exam-prep/practices/{practice_id}/full` |
|
||||
|
||||
```typescript
|
||||
function practiceEditorPath(row: PracticeByQuestionTypeDefinition): string {
|
||||
if (row.practice_kind === "EXAM_PREP") {
|
||||
return `/admin/exam-prep/practices/${row.practice_id}`;
|
||||
}
|
||||
return `/admin/lms/practices/${row.practice_id}`;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TypeScript types & API client
|
||||
|
||||
```typescript
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
status_code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
interface PracticesByQuestionTypeDefinitionSummary {
|
||||
question_type_definition_id: number;
|
||||
practices: PracticeByQuestionTypeDefinition[];
|
||||
total_count: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export async function listPracticesByQuestionTypeDefinition(
|
||||
definitionId: number,
|
||||
token: string,
|
||||
options?: { limit?: number; offset?: number }
|
||||
): Promise<PracticesByQuestionTypeDefinitionSummary> {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.limit != null) params.set("limit", String(options.limit));
|
||||
if (options?.offset != null) params.set("offset", String(options.offset));
|
||||
|
||||
const qs = params.toString();
|
||||
const url = `${API_BASE}/api/v1/questions/type-definitions/${definitionId}/practices${
|
||||
qs ? `?${qs}` : ""
|
||||
}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
const body = (await res.json().catch(() => ({}))) as ApiResponse<PracticesByQuestionTypeDefinitionSummary> & {
|
||||
message?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(body.message || body.error || `List failed (${res.status})`);
|
||||
}
|
||||
|
||||
return body.data;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## React integration patterns
|
||||
|
||||
### Modal with pagination
|
||||
|
||||
```tsx
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
listPracticesByQuestionTypeDefinition,
|
||||
formatPracticeLocation,
|
||||
type PracticeByQuestionTypeDefinition,
|
||||
} from "@/api/question-type-practices";
|
||||
|
||||
interface Props {
|
||||
definitionId: number;
|
||||
definitionLabel: string;
|
||||
token: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function PracticesUsingDefinitionModal({
|
||||
definitionId,
|
||||
definitionLabel,
|
||||
token,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const [rows, setRows] = useState<PracticeByQuestionTypeDefinition[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await listPracticesByQuestionTypeDefinition(definitionId, token, {
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
setRows(data.practices);
|
||||
setTotal(data.total_count);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Failed to load practices");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [definitionId, token, limit, offset]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<dialog open>
|
||||
<header>
|
||||
<h2>Practices using this definition</h2>
|
||||
<p>{definitionLabel}</p>
|
||||
</header>
|
||||
|
||||
{loading && <p>Loading…</p>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
|
||||
{!loading && !error && (
|
||||
<ul>
|
||||
{rows.map((row) => (
|
||||
<li key={`${row.practice_kind}-${row.practice_id}`}>
|
||||
<strong>{row.title}</strong>
|
||||
<div>
|
||||
practice #{row.practice_id} · set #{row.question_set_id} ·{" "}
|
||||
<span data-unlinked={formatPracticeLocation(row) === "Unlinked"}>
|
||||
{formatPracticeLocation(row)}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
{row.matching_question_count} matching question
|
||||
{row.matching_question_count === 1 ? "" : "s"}
|
||||
</div>
|
||||
<a href={practiceEditorPath(row)}>Edit practice</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<footer>
|
||||
<span>
|
||||
Showing {total === 0 ? 0 : offset + 1}-
|
||||
{Math.min(offset + limit, total)} of {total}
|
||||
</span>
|
||||
<select
|
||||
value={limit}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setLimit(Number(e.target.value));
|
||||
}}
|
||||
>
|
||||
<option value={10}>10</option>
|
||||
<option value={20}>20</option>
|
||||
<option value={50}>50</option>
|
||||
</select>
|
||||
<button disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - limit))}>
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
disabled={offset + limit >= total}
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
<button type="button" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
</footer>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
| Param | Behavior |
|
||||
|-------|----------|
|
||||
| `limit` | Clamped to **1–200** server-side; default **20** |
|
||||
| `offset` | Zero-based; clamped to **≥ 0** |
|
||||
| `total_count` | Total matching practices (LMS + exam-prep combined) |
|
||||
| Sort order | `created_at DESC` (newest first) |
|
||||
|
||||
```typescript
|
||||
const pageCount = Math.ceil(total_count / limit);
|
||||
const currentPage = Math.floor(offset / limit) + 1;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Empty & error states
|
||||
|
||||
| State | UI |
|
||||
|-------|-----|
|
||||
| `practices.length === 0` | “No practices use this question type yet.” + **Create practice** CTA |
|
||||
| Definition not found (404) | Close modal; toast “Question type not found” |
|
||||
| Network / 500 | Retry button + error message |
|
||||
|
||||
---
|
||||
|
||||
## Testing checklist
|
||||
|
||||
### API / data
|
||||
|
||||
- [ ] LMS practice with `COURSE` parent → `parents` populated; location not “Unlinked”
|
||||
- [ ] Exam-prep practice with `CATALOG_COURSE` only → `exam_prep_parents` has entry; **not** “Unlinked”
|
||||
- [ ] Exam-prep practice with `UNIT` parent → `exam_prep_parents` shows `UNIT`
|
||||
- [ ] Exam-prep practice with `LESSON` parent → `exam_prep_parents` + `exam_prep_lesson_id` set
|
||||
- [ ] Unlinked practice (no parents) → `parents` / `exam_prep_parents` null; location **Unlinked**
|
||||
- [ ] `matching_question_count` matches non-archived questions of this type
|
||||
- [ ] Draft practice visible for admin with `practices.update`; hidden for learner token
|
||||
- [ ] Pagination: `total_count` stable across pages
|
||||
|
||||
### Admin UI
|
||||
|
||||
- [ ] Modal opens from question type row with correct definition id
|
||||
- [ ] Meta line uses `formatPracticeLocation` (not `exam_prep_lesson_id` alone)
|
||||
- [ ] **Edit practice** opens correct LMS vs exam-prep editor
|
||||
- [ ] DRAFT badge when `publish_status === "DRAFT"`
|
||||
- [ ] Pagination controls update `offset` / `limit`
|
||||
|
||||
---
|
||||
|
||||
## Integration checklist
|
||||
|
||||
- [ ] Wire `GET /api/v1/questions/type-definitions/:id/practices` to “Practices using this definition” modal
|
||||
- [ ] Pass `limit` and `offset` for pagination
|
||||
- [ ] Branch location display on `practice_kind`
|
||||
- [ ] LMS: read `parents`
|
||||
- [ ] Exam-prep: read **`exam_prep_parents`** (required for catalog course / unit)
|
||||
- [ ] Use `exam_prep_lesson_id` only as fallback for legacy responses
|
||||
- [ ] Show **Unlinked** only when no parents of either kind
|
||||
- [ ] Route **Edit practice** by `practice_kind` + `practice_id`
|
||||
- [ ] Show `matching_question_count` in row
|
||||
- [ ] Permission: caller needs `practices.list`
|
||||
- [ ] (Optional) Resolve parent IDs to display names via hierarchy APIs
|
||||
|
||||
---
|
||||
|
||||
## Limitations
|
||||
|
||||
| Topic | Detail |
|
||||
|-------|--------|
|
||||
| Combined sort | LMS and exam-prep rows share one list sorted by `created_at` |
|
||||
| No parent names in API | Response includes parent **IDs** only; resolve titles client-side if needed |
|
||||
| No filter by `practice_kind` | Cannot request LMS-only or exam-prep-only via query param |
|
||||
| Legacy questions | Unlinked `question_type` (non-DYNAMIC) still matches if runtime type maps to definition |
|
||||
| Archived questions | Do not count toward inclusion or `matching_question_count` |
|
||||
| Exam-prep modules | No `MODULE` parent kind — module context is via `LESSON` under `unit_modules` |
|
||||
| Swagger | Regenerate OpenAPI if your pipeline requires handler annotations in the spec |
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
|
||||
```http
|
||||
GET /api/v1/questions/type-definitions/:id/practices?limit=10&offset=0
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**Permission:** `practices.list`
|
||||
|
||||
| `practice_kind` | Location field | Parent kinds |
|
||||
|-----------------|----------------|--------------|
|
||||
| `LMS` | `parents` | `COURSE`, `MODULE`, `LESSON` |
|
||||
| `EXAM_PREP` | `exam_prep_parents` | `CATALOG_COURSE`, `UNIT`, `LESSON` |
|
||||
|
||||
| Field | Purpose |
|
||||
|-------|---------|
|
||||
| `matching_question_count` | Badge: “N matching questions” |
|
||||
| `exam_prep_lesson_id` | Legacy; prefer `exam_prep_parents` |
|
||||
| `publish_status` | `DRAFT` / `PUBLISHED` badge |
|
||||
Loading…
Reference in New Issue
Block a user