RezinaLMS-BackEnd/docs/practice-create-nullable-parents-admin-panel-integration.md
Yared Yemane 75fb913704 feat: support nullable parents for exam-prep practices
Add POST/GET /exam-prep/practices and PUT .../parents mirroring the LMS shell-then-link flow. Update admin panel integration guide and exam_prep.practices.list permission.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 08:07:01 -07:00

794 lines
24 KiB
Markdown

# Create Practice with Nullable `parents` — Admin Panel Guide
This guide explains how the admin panel should **create practices** when `parents` is **optional** — for both **Learn English (LMS)** and **Exam Prep**. You can create a practice shell first (linked only to a question set), then attach it to hierarchy nodes later.
> **Scope:** `POST /api/v1/practices` (LMS) and `POST /api/v1/exam-prep/practices` (Exam Prep). Nested create routes under catalog courses, units, and lessons still work; see [Exam Prep](#exam-prep).
>
> **Related guides:**
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — multi-parent editing, list endpoints, LMS constraints
> - [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md) — adding questions after the shell exists
---
## Table of contents
1. [Summary](#summary)
2. [When to use nullable parents](#when-to-use-nullable-parents)
3. [End-to-end create flow](#end-to-end-create-flow)
4. [Authentication & permissions](#authentication--permissions)
5. [Request contract](#request-contract)
6. [Create variants](#create-variants)
7. [Response contract](#response-contract)
8. [Link parents after create](#link-parents-after-create)
9. [Recommended admin UI](#recommended-admin-ui)
10. [TypeScript types & helpers](#typescript-types--helpers)
11. [React example](#react-example)
12. [Error handling](#error-handling)
13. [Integration checklist](#integration-checklist)
14. [Quick reference](#quick-reference)
15. [Exam Prep](#exam-prep)
---
## Summary
| Topic | LMS | Exam Prep |
|-------|-----|-----------|
| Required on create | `question_set_id` | `question_set_id` |
| `parents` on create | **Optional** — omit, `null`, or array | **Optional** — omit, `null`, or array |
| Response when unlinked | `"parents": null` | `"parents": null` |
| Create endpoint | `POST /api/v1/practices` | `POST /api/v1/exam-prep/practices` |
| Link after create | `PUT /api/v1/practices/:id/parents` | `PUT /api/v1/exam-prep/practices/:id/parents` |
| Add questions after create | `PUT /api/v1/practices/:id/full` | `PUT /api/v1/exam-prep/practices/:id/full` |
| Parent kinds | `COURSE`, `MODULE`, `LESSON` | `CATALOG_COURSE`, `UNIT`, `LESSON` |
| One practice per parent | **Yes** (409 conflict) | **No** — multiple practices per parent allowed |
| List unlinked (admin) | `GET /api/v1/practices?unlinked_only=true` | `GET /api/v1/exam-prep/practices?unlinked_only=true` |
The sections below through [Quick reference](#quick-reference) describe **LMS** unless noted. [Exam Prep](#exam-prep) mirrors the same flow with exam-prep paths and parent kinds.
The nullable `parents` field supports a **two-phase authoring** model:
1. **Phase 1 — Shell:** create practice + question set reference (no hierarchy links yet).
2. **Phase 2 — Placement:** attach to one or more courses/modules/lessons when the author is ready.
3. **Phase 3 — Content:** add story metadata and questions via full practice save.
---
## When to use nullable parents
| Scenario | `parents` on create | Link later |
|----------|---------------------|------------|
| Author builds questions first, picks placement later | `null` / omit | Yes |
| “New practice” from global admin menu (no context) | `null` / omit | Yes |
| “Add practice” from a lesson page | `[{ LESSON, id }]` optional | Add more via `/parents` |
| Reuse same shell in multiple locations at once | Array of parents | Rarely needed |
| Legacy single-parent create | `parent_kind` + `parent_id` | N/A |
An unlinked practice (`parents: null`) is valid for admins but **will not appear** in course/module/lesson practice lists until parents are set.
---
## End-to-end create flow
```mermaid
sequenceDiagram
participant UI as Admin panel
participant API as Yimaru API
Note over UI,API: Optional — create question set first
UI->>API: POST /question-sets
API-->>UI: question_set_id
Note over UI,API: Phase 1 — practice shell (parents optional)
UI->>API: POST /practices { question_set_id, parents: null }
API-->>UI: 201 { id, parents: null, question_set_id }
Note over UI,API: Phase 2 — attach hierarchy (when ready)
UI->>API: PUT /practices/:id/parents { parents: [...] }
API-->>UI: 200 { id, parents: [...] }
Note over UI,API: Phase 3 — questions & story
UI->>API: PUT /practices/:id/full { practice, question_set, questions }
API-->>UI: 200 full practice payload
```
### Minimal steps
1. Ensure a **question set** exists (create one or pick existing).
2. **POST /api/v1/practices** with `question_set_id` and `parents: null` (or omit `parents`).
3. Store returned `practice.id`.
4. When placement is known, **PUT /api/v1/practices/:id/parents**.
5. Open the question editor and **PUT /api/v1/practices/:id/full**.
---
## Authentication & permissions
```http
Authorization: Bearer <access_token>
Content-Type: application/json
```
| Action | Permission | Endpoint |
|--------|------------|----------|
| Create practice | `practices.create` | `POST /api/v1/practices` |
| Attach / update parents | `practices.update` | `PUT /api/v1/practices/:id/parents` |
| Add questions | `practices.update` | `PUT /api/v1/practices/:id/full` |
---
## Request contract
### `POST /api/v1/practices`
```http
POST /api/v1/practices
Authorization: Bearer <token>
Content-Type: application/json
```
### Body fields
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `question_set_id` | `number` | **Yes** | Must exist in `question_sets` |
| `parents` | `array \| null` | No | Omit or `null` = unlinked shell |
| `parent_kind` | `string` | No | Legacy fallback: `COURSE` \| `MODULE` \| `LESSON` |
| `parent_id` | `number` | No | Legacy fallback; use with `parent_kind` |
| `title` | `string` | No | |
| `story_description` | `string` | No | |
| `story_image` | `string` | No | URL |
| `persona_id` | `number` | No | `lms_personas.id` |
| `quick_tips` | `string` | No | |
| `publish_status` | `string` | No | `DRAFT` or `PUBLISHED`; default `PUBLISHED` |
### `parents` item shape
| Field | Type | Values |
|-------|------|--------|
| `parent_kind` | `string` | `COURSE`, `MODULE`, `LESSON` |
| `parent_id` | `number` | ID of that entity |
### Semantics of `parents`
| Input | Meaning |
|-------|---------|
| Field omitted | Unlinked practice |
| `"parents": null` | Unlinked practice |
| `"parents": []` | Unlinked practice (empty array is deduped to no links) |
| `"parents": [{ … }]` | Create with one or more links immediately |
| Legacy `parent_kind` + `parent_id` | Single link when `parents` is omitted |
> **Note:** If you send **both** `parents` and legacy `parent_kind`/`parent_id`, `parents` wins when it is non-null.
---
## Create variants
### 1. Unlinked shell (recommended for “create first, place later”)
```json
{
"parents": null,
"question_set_id": 100,
"title": "New practice",
"publish_status": "DRAFT"
}
```
Equivalent payloads:
```json
{
"question_set_id": 100,
"title": "New practice",
"publish_status": "DRAFT"
}
```
### 2. Create with one parent (from lesson/module/course page)
```json
{
"parents": [
{ "parent_kind": "LESSON", "parent_id": 42 }
],
"question_set_id": 100,
"publish_status": "DRAFT"
}
```
### 3. Create with multiple parents
```json
{
"parents": [
{ "parent_kind": "MODULE", "parent_id": 9 },
{ "parent_kind": "LESSON", "parent_id": 42 }
],
"question_set_id": 100,
"title": "Shared capstone"
}
```
### 4. Legacy single-parent (backward compatible)
```json
{
"parent_kind": "LESSON",
"parent_id": 42,
"question_set_id": 100
}
```
### 5. Full metadata at create (still unlinked)
```json
{
"parents": null,
"question_set_id": 100,
"title": "Listening drill",
"story_description": "You arrive at the market…",
"story_image": "https://cdn.example/story.png",
"persona_id": 3,
"quick_tips": "Listen twice before answering.",
"publish_status": "DRAFT"
}
```
---
## Response contract
### Success — `201 Created`
```json
{
"success": true,
"status_code": 201,
"message": "Practice created successfully",
"data": {
"id": 55,
"parents": null,
"title": "New practice",
"question_set_id": 100,
"publish_status": "DRAFT",
"created_at": "2026-06-18T12:00:00Z"
}
}
```
When parents were provided at create:
```json
{
"data": {
"id": 56,
"parents": [
{ "parent_kind": "LESSON", "parent_id": 42 }
],
"question_set_id": 100,
"publish_status": "DRAFT"
}
}
```
**Important:** `parents` is JSON `null` when there are no links — not `[]`.
### Error — common cases
| HTTP | `message` | Cause |
|------|-----------|-------|
| 400 | `Validation failed` | Missing `question_set_id` |
| 404 | `Question set not found` | Invalid `question_set_id` |
| 404 | `Course not found` / `Module not found` / `Lesson not found` | Bad `parent_id` in `parents` |
| 409 | `This course, module, or lesson already has a practice` | Parent entity already linked elsewhere |
| 403 | Permission denied | Missing `practices.create` |
---
## Link parents after create
When the practice was created with `parents: null`, attach hierarchy nodes with:
```http
PUT /api/v1/practices/:id/parents
Authorization: Bearer <token>
Content-Type: application/json
```
```json
{
"parents": [
{ "parent_kind": "LESSON", "parent_id": 42 },
{ "parent_kind": "COURSE", "parent_id": 7 }
]
}
```
- Replaces **all** links on each call.
- Use `"parents": []` to detach completely (practice becomes unlinked again).
- Requires `practices.update`.
See [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md#update-practice-parents) for full parent-editing rules and conflict handling.
---
## Recommended admin UI
### Create wizard (nullable parents)
```mermaid
flowchart TD
A[Start: New practice] --> B{Question set?}
B -->|Create new| C[POST /question-sets]
B -->|Pick existing| D[Select question_set_id]
C --> E[POST /practices parents null]
D --> E
E --> F{Attach locations now?}
F -->|No| G[Open question editor]
F -->|Yes| H[PUT /practices/:id/parents]
H --> G
G --> I[PUT /practices/:id/full]
```
### UI rules
1. **Do not require** a course/module/lesson picker on the first create step.
2. Show **“Locations (optional)”** — collapsed by default when starting from the global menu.
3. When opened from a lesson page, **pre-fill** one parent row but allow skip.
4. After create, if `parents === null`, show a banner: *“Not attached to any course, module, or lesson yet.”*
5. Provide **“Attach to…”** action → calls `PUT /practices/:id/parents`.
6. Disable “Publish to learners” messaging until at least one parent is set (optional product rule).
### What not to do
- Do not send `parents` on `PUT /practices/:id/full` — that endpoint ignores parent links.
- Do not expect the practice to appear in `GET /lessons/:id/practices` until a `LESSON` parent exists.
---
## TypeScript types & helpers
```typescript
type ParentKind = "COURSE" | "MODULE" | "LESSON";
interface PracticeParent {
parent_kind: ParentKind;
parent_id: number;
}
interface CreatePracticeInput {
question_set_id: number;
parents?: PracticeParent[] | null;
parent_kind?: ParentKind;
parent_id?: number;
title?: string;
story_description?: string;
story_image?: string;
persona_id?: number;
quick_tips?: string;
publish_status?: "DRAFT" | "PUBLISHED";
}
interface Practice {
id: number;
parents: PracticeParent[] | null;
question_set_id: number;
title: string;
publish_status: "DRAFT" | "PUBLISHED";
created_at: string;
updated_at?: string | null;
}
interface ApiResponse<T> {
success: boolean;
status_code: number;
message: string;
data: T;
}
```
```typescript
/** Build create payload; parents null unless user selected locations. */
function buildCreatePracticePayload(input: {
questionSetId: number;
parents?: PracticeParent[] | null;
title?: string;
publishStatus?: "DRAFT" | "PUBLISHED";
}): CreatePracticeInput {
const parents =
input.parents && input.parents.length > 0 ? dedupeParents(input.parents) : null;
return {
question_set_id: input.questionSetId,
parents,
title: input.title,
publish_status: input.publishStatus ?? "DRAFT",
};
}
function dedupeParents(parents: PracticeParent[]): PracticeParent[] {
const seen = new Set<string>();
return parents.filter((p) => {
if (!p.parent_kind || p.parent_id <= 0) return false;
const key = `${p.parent_kind}:${p.parent_id}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function isPracticeUnlinked(practice: Practice): boolean {
return practice.parents == null || practice.parents.length === 0;
}
```
---
## React example
```typescript
const API_BASE = import.meta.env.VITE_API_URL;
async function createUnlinkedPractice(
questionSetId: number,
token: string,
meta?: { title?: string }
): Promise<Practice> {
const res = await fetch(`${API_BASE}/api/v1/practices`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
parents: null,
question_set_id: questionSetId,
title: meta?.title ?? "",
publish_status: "DRAFT",
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message || body.error || `Create failed (${res.status})`);
}
const json: ApiResponse<Practice> = await res.json();
return json.data;
}
async function attachPracticeParents(
practiceId: number,
parents: PracticeParent[],
token: string
): Promise<Practice> {
const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/parents`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ parents: dedupeParents(parents) }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message || body.error || `Attach failed (${res.status})`);
}
const json: ApiResponse<Practice> = await res.json();
return json.data;
}
// Typical flow
async function createPracticeWorkflow(questionSetId: number, token: string) {
const practice = await createUnlinkedPractice(questionSetId, token, {
title: "Untitled practice",
});
// … author adds questions via PUT /practices/:id/full …
// … when ready, attach to lesson 42 …
const linked = await attachPracticeParents(
practice.id,
[{ parent_kind: "LESSON", parent_id: 42 }],
token
);
return linked;
}
```
---
## Error handling
| User action | API result | Suggested UI |
|-------------|------------|--------------|
| Create without `question_set_id` | 400 validation | Block submit; highlight question set field |
| Create with taken lesson parent | 409 conflict | Toast: “This lesson already has a practice” *(LMS only)* |
| Attach invalid module id | 404 | Refresh hierarchy picker data |
| Create unlinked, user expects lesson list | Practice missing from list | Explain “Attach to lesson first” |
Always show the API `error` string when present.
---
## Integration checklist
### Create flow
- [ ] `POST /practices` works with `parents` omitted or `null`
- [ ] Only `question_set_id` is required in the create form
- [ ] Response `data.parents` handled as `null` or array
- [ ] Unlinked practices show clear “not attached” state in UI
### Post-create
- [ ] `PUT /practices/:id/parents` wired for “Attach to…” / Locations step
- [ ] `PUT /practices/:id/full` used for questions (not parents)
- [ ] Lesson/course/module list pages refresh after parents are attached
### QA
- [ ] Create `parents: null` → response `parents: null` → not in lesson list
- [ ] `PUT /parents` with lesson → appears in `GET /lessons/:id/practices`
- [ ] Create with parents at once still works
- [ ] Legacy `parent_kind` + `parent_id` still works
- [ ] 409 when attaching to entity that already has another practice *(LMS only; Exam Prep allows multiple practices per parent)*
---
## Quick reference (LMS)
```bash
# 1. Create unlinked shell
curl -s -X POST "$API/api/v1/practices" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"parents": null,
"question_set_id": 100,
"title": "Draft practice",
"publish_status": "DRAFT"
}'
# 2. Attach to lesson 42 (use id from step 1)
curl -s -X PUT "$API/api/v1/practices/55/parents" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"parents": [{ "parent_kind": "LESSON", "parent_id": 42 }]
}'
```
| Step | Method | Path | `parents` |
|------|--------|------|-----------|
| Create shell | `POST` | `/api/v1/practices` | `null` / omit / optional array |
| Attach locations | `PUT` | `/api/v1/practices/:id/parents` | required array |
| Add questions | `PUT` | `/api/v1/practices/:id/full` | not used |
---
## Exam Prep
Exam Prep uses the same **two-phase authoring** model as LMS: create an unlinked shell, attach catalog course / unit / lesson parents when ready, then save questions via the full endpoint.
### Endpoints
| Action | Permission | Endpoint |
|--------|------------|----------|
| Create practice | `exam_prep.practices.create` | `POST /api/v1/exam-prep/practices` |
| List practices (incl. unlinked) | `exam_prep.practices.list` | `GET /api/v1/exam-prep/practices` |
| Attach / update parents | `exam_prep.practices.update` | `PUT /api/v1/exam-prep/practices/:id/parents` |
| Add questions | `exam_prep.practices.update` | `PUT /api/v1/exam-prep/practices/:id/full` |
Nested create routes (parent from URL when `parents` is omitted in body):
| Context | `POST` |
|---------|--------|
| Catalog course | `/api/v1/exam-prep/catalog-courses/:catalogCourseId/practices` |
| Unit | `/api/v1/exam-prep/units/:unitId/practices` |
| Lesson | `/api/v1/exam-prep/lessons/:lessonId/practices` |
If the request body includes `parents` (non-null), that array is used and the URL parent is ignored.
### Request body (`POST /api/v1/exam-prep/practices`)
Same shape as LMS, with exam-prep parent kinds:
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `question_set_id` | `number` | **Yes** | Must exist in `question_sets` |
| `parents` | `array \| null` | No | Omit or `null` = unlinked shell |
| `parent_kind` | `string` | No | Legacy: `CATALOG_COURSE` \| `UNIT` \| `LESSON` |
| `parent_id` | `number` | No | Legacy; use with `parent_kind` |
| `title`, `story_description`, `story_image`, `persona_id`, `quick_tips`, `publish_status` | | No | Same as LMS |
### `parents` item shape (Exam Prep)
| Field | Type | Values |
|-------|------|--------|
| `parent_kind` | `string` | `CATALOG_COURSE`, `UNIT`, `LESSON` |
| `parent_id` | `number` | ID of that exam-prep entity |
### Create variants
**Unlinked shell:**
```json
{
"parents": null,
"question_set_id": 100,
"title": "New exam prep practice",
"publish_status": "DRAFT"
}
```
**Create with unit parent:**
```json
{
"parents": [
{ "parent_kind": "UNIT", "parent_id": 5 }
],
"question_set_id": 100,
"publish_status": "DRAFT"
}
```
### Link parents after create
```http
PUT /api/v1/exam-prep/practices/:id/parents
Authorization: Bearer <token>
Content-Type: application/json
```
```json
{
"parents": [
{ "parent_kind": "LESSON", "parent_id": 42 },
{ "parent_kind": "CATALOG_COURSE", "parent_id": 7 }
]
}
```
- Replaces **all** links on each call.
- Use `"parents": []` to detach completely.
- **No 409 conflict** when a catalog course, unit, or lesson already has other practices (multiple practices per parent are allowed).
### List unlinked practices (admin)
```http
GET /api/v1/exam-prep/practices?unlinked_only=true&limit=20&offset=0
Authorization: Bearer <token>
```
Requires `exam_prep.practices.list`. Only users who can manage exam-prep practices should pass `unlinked_only=true` (same pattern as LMS).
### TypeScript (Exam Prep)
```typescript
type ExamPrepParentKind = "CATALOG_COURSE" | "UNIT" | "LESSON";
interface ExamPrepPracticeParent {
parent_kind: ExamPrepParentKind;
parent_id: number;
}
interface CreateExamPrepPracticeInput {
question_set_id: number;
parents?: ExamPrepPracticeParent[] | null;
parent_kind?: ExamPrepParentKind;
parent_id?: number;
title?: string;
story_description?: string;
story_image?: string;
persona_id?: number;
quick_tips?: string;
publish_status?: "DRAFT" | "PUBLISHED";
}
```
```typescript
async function createUnlinkedExamPrepPractice(
questionSetId: number,
token: string,
meta?: { title?: string }
) {
const res = await fetch(`${API_BASE}/api/v1/exam-prep/practices`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
parents: null,
question_set_id: questionSetId,
title: meta?.title ?? "",
publish_status: "DRAFT",
}),
});
if (!res.ok) throw new Error((await res.json()).message);
return (await res.json()).data;
}
async function attachExamPrepPracticeParents(
practiceId: number,
parents: ExamPrepPracticeParent[],
token: string
) {
const res = await fetch(
`${API_BASE}/api/v1/exam-prep/practices/${practiceId}/parents`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ parents }),
}
);
if (!res.ok) throw new Error((await res.json()).message);
return (await res.json()).data;
}
```
### Exam Prep — error handling
| HTTP | `message` | Cause |
|------|-----------|-------|
| 400 | `Validation failed` | Missing `question_set_id` |
| 404 | `Question set not found` | Invalid `question_set_id` |
| 404 | `Catalog course not found` / `Unit not found` / `Lesson not found` | Bad `parent_id` |
| 400 | `Invalid parent` | Unknown `parent_kind` |
| 403 | Permission denied | Missing `exam_prep.practices.create` or `exam_prep.practices.update` |
> Exam Prep does **not** return 409 for “parent already has a practice”.
### Exam Prep — integration checklist
- [ ] `POST /exam-prep/practices` works with `parents` omitted or `null`
- [ ] `GET /exam-prep/practices?unlinked_only=true` lists shells awaiting placement
- [ ] `PUT /exam-prep/practices/:id/parents` wired for “Attach to…” step
- [ ] `PUT /exam-prep/practices/:id/full` used for questions (not parents)
- [ ] Nested routes (`/catalog-courses/.../practices`, etc.) still work when opened from hierarchy pages
- [ ] UI uses `CATALOG_COURSE` / `UNIT` / `LESSON` — not LMS `COURSE` / `MODULE`
### Exam Prep — quick reference
```bash
# 1. Create unlinked shell
curl -s -X POST "$API/api/v1/exam-prep/practices" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"parents": null,
"question_set_id": 100,
"title": "Draft exam prep practice",
"publish_status": "DRAFT"
}'
# 2. Attach to lesson 42 (use id from step 1)
curl -s -X PUT "$API/api/v1/exam-prep/practices/55/parents" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"parents": [{ "parent_kind": "LESSON", "parent_id": 42 }]
}'
# 3. List unlinked practices (admin)
curl -s "$API/api/v1/exam-prep/practices?unlinked_only=true" \
-H "Authorization: Bearer $TOKEN"
```
| Step | Method | Path | `parents` |
|------|--------|------|-----------|
| Create shell | `POST` | `/api/v1/exam-prep/practices` | `null` / omit / optional array |
| Attach locations | `PUT` | `/api/v1/exam-prep/practices/:id/parents` | required array |
| Add questions | `PUT` | `/api/v1/exam-prep/practices/:id/full` | not used |
| List unlinked | `GET` | `/api/v1/exam-prep/practices?unlinked_only=true` | — |