feat: optional parents on practice create and PUT parents endpoint

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-06-18 05:02:13 -07:00
parent e67f666815
commit 12d4e49cea
10 changed files with 793 additions and 97 deletions

View File

@ -0,0 +1,565 @@
# Create Practice with Nullable `parents` — Admin Panel Guide
This guide explains how the admin panel should **create LMS practices** when `parents` is **optional**. You can create a practice shell first (linked only to a question set), then attach it to courses, modules, and/or lessons later.
> **Scope:** `POST /api/v1/practices` (Learn English LMS). Exam-prep creation is unchanged.
>
> **Related guides:**
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — multi-parent editing, list endpoints, 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)
---
## Summary
| Topic | Behavior |
|-------|----------|
| Required on create | `question_set_id` only |
| `parents` on create | **Optional** — omit, `null`, or an array |
| Response when unlinked | `"parents": null` |
| Response when linked | `"parents": [{ "parent_kind", "parent_id" }, …]` |
| Link after create | `PUT /api/v1/practices/:id/parents` |
| Add questions after create | `PUT /api/v1/practices/:id/full` |
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” |
| 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
---
## Quick reference
```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 |

View File

@ -4,7 +4,9 @@ This guide documents how to update the Yimaru **admin panel practice creation an
> **Scope:** LMS (`/api/v1/practices`) only. **Exam-prep** practices are unchanged — they still attach to exactly one `unit_module_lesson_id`.
>
> **Related:** Question authoring inside a practice (sections, `associated_question_id`) is documented in [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md).
> **Related:**
> - [practice-create-nullable-parents-admin-panel-integration.md](./practice-create-nullable-parents-admin-panel-integration.md) — focused guide for creating practices with `parents: null`
> - [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md) — question sections inside a practice
---
@ -19,18 +21,19 @@ This guide documents how to update the Yimaru **admin panel practice creation an
7. [Data model](#data-model)
8. [Response envelopes](#response-envelopes)
9. [Create practice](#create-practice)
10. [Update practice shell (including parents)](#update-practice-shell-including-parents)
11. [Full practice load/save (questions)](#full-practice-loadsave-questions)
12. [List & read endpoints](#list--read-endpoints)
13. [Recommended admin UI changes](#recommended-admin-ui-changes)
14. [Form state & serialization](#form-state--serialization)
15. [Client-side validation](#client-side-validation)
16. [TypeScript types & helpers](#typescript-types--helpers)
17. [React integration patterns](#react-integration-patterns)
18. [Error handling](#error-handling)
19. [Integration checklist](#integration-checklist)
20. [Limitations](#limitations)
21. [Quick reference](#quick-reference)
10. [Update practice parents](#update-practice-parents)
11. [Update practice shell (metadata only)](#update-practice-shell-metadata-only)
12. [Full practice load/save (questions)](#full-practice-loadsave-questions)
13. [List & read endpoints](#list--read-endpoints)
14. [Recommended admin UI changes](#recommended-admin-ui-changes)
15. [Form state & serialization](#form-state--serialization)
16. [Client-side validation](#client-side-validation)
17. [TypeScript types & helpers](#typescript-types--helpers)
18. [React integration patterns](#react-integration-patterns)
19. [Error handling](#error-handling)
20. [Integration checklist](#integration-checklist)
21. [Limitations](#limitations)
22. [Quick reference](#quick-reference)
---
@ -38,7 +41,7 @@ This guide documents how to update the Yimaru **admin panel practice creation an
| Capability | Before | After |
|------------|--------|-------|
| Parents per LMS practice | Exactly one (`parent_kind` + `parent_id`) | **One or many** via `parents[]` |
| Parents per LMS practice | Exactly one (`parent_kind` + `parent_id`) | **Zero or many** via nullable `parents` |
| Mix course + module + lesson on same practice | Not allowed | **Allowed** |
| Same practice appears in multiple lesson catalogs | Not allowed | **Allowed** (one row, many parent links) |
| Each course/module/lesson can own a practice | One practice max | **Still one practice max per entity** |
@ -91,14 +94,14 @@ If `parents` is omitted, the API accepts the old single-parent fields:
}
```
### Where parents are **not** updated
### Where parents are updated
`PUT /api/v1/practices/:id/full` updates story metadata, question set settings, and questions — **it does not accept `parents`**. Parent links are managed through:
- `POST /api/v1/practices` (create)
- `PUT /api/v1/practices/:id` (shell update, including `parents`)
- `POST /api/v1/practices` (create — `parents` optional / null)
- `PUT /api/v1/practices/:id/parents` (**dedicated** parent replacement endpoint)
---
`PUT /api/v1/practices/:id` updates shell metadata only (title, persona, publish status, etc.) — not parents.
## Concepts: parents, kinds, and constraints
@ -111,7 +114,7 @@ If `parents` is omitted, the API accepts the old single-parent fields:
### Rules
1. **At least one parent** is required on create (via `parents` or legacy `parent_kind` + `parent_id`).
1. **At least one parent** is required only when you choose to send `parents` on create — omit or set `parents: null` to create an unlinked practice shell.
2. **Duplicates are ignored** — sending the same `(parent_kind, parent_id)` twice is deduplicated server-side.
3. **One practice per parent entity** — each course, module, or lesson can still be linked to **at most one** practice. Assigning a parent that is already taken returns **409 Conflict**.
4. **A practice may have many parents** — the inverse is not limited.
@ -150,7 +153,7 @@ flowchart TB
subgraph API["Yimaru API"]
PostPractice["POST /practices"]
PutPractice["PUT /practices/:id"]
PutParents["PUT /practices/:id/parents"]
GetFull["GET /practices/:id/full"]
PutFull["PUT /practices/:id/full"]
end
@ -162,12 +165,12 @@ flowchart TB
CreateForm --> ParentPicker
ParentPicker --> PostPractice
ShellEdit --> PutPractice
ShellEdit --> PutParents
QuestionEditor --> PutFull
GetFull --> QuestionEditor
PostPractice --> LP
PostPractice --> LPP
PutPractice --> LPP
PutParents --> LPP
```
- **Migration:** `000089_lms_practice_parents` — junction table; migrates legacy columns; drops `course_id` / `module_id` / `lesson_id` from `lms_practices`.
@ -219,7 +222,8 @@ Content-Type: application/json
|--------|------------|------|
| Create practice | `practices.create` | `POST /api/v1/practices` |
| Get practice shell | `practices.get` | `GET /api/v1/practices/:id` |
| Update shell (incl. parents) | `practices.update` | `PUT /api/v1/practices/:id` |
| Update parent links | `practices.update` | `PUT /api/v1/practices/:id/parents` |
| Update shell metadata | `practices.update` | `PUT /api/v1/practices/:id` |
| Delete practice | `practices.delete` | `DELETE /api/v1/practices/:id` |
| List by course / module / lesson | `practices.list` | `GET /api/v1/courses\|modules\|lessons/:id/practices` |
@ -230,7 +234,7 @@ Content-Type: application/json
| Load practice + questions | `practices.get` | `GET /api/v1/practices/:id/full` |
| Save practice + questions | `practices.update` | `PUT /api/v1/practices/:id/full` |
Parent links are **not** part of the `/full` payload — keep parent editing on the shell create/update routes above.
Parent links use **`PUT /api/v1/practices/:id/parents`** only — not `PUT .../full` or `PUT /practices/:id`.
---
@ -238,6 +242,8 @@ Parent links are **not** part of the `/full` payload — keep parent editing on
### `Practice` (response)
When no parents are linked, `parents` is JSON **`null`** (not `[]`).
```json
{
"id": 55,
@ -264,7 +270,7 @@ Parent links are **not** part of the `/full` payload — keep parent editing on
| Field | Required | Notes |
|-------|----------|-------|
| `parents` | Preferred | Non-empty array of `{ parent_kind, parent_id }` |
| `parents` | No | `null`, omitted, or array of `{ parent_kind, parent_id }` |
| `parent_kind` | Legacy fallback | Use with `parent_id` when `parents` omitted |
| `parent_id` | Legacy fallback | Use with `parent_kind` when `parents` omitted |
| `question_set_id` | **Yes** | Must reference an existing question set |
@ -275,13 +281,18 @@ Parent links are **not** part of the `/full` payload — keep parent editing on
| `quick_tips` | No | |
| `publish_status` | No | `DRAFT` or `PUBLISHED`; omit → `PUBLISHED` |
### `UpdatePracticeParentsInput`
| Field | Required | Notes |
|-------|----------|-------|
| `parents` | **Yes** | Full replacement list; use `[]` to detach from all hierarchy nodes |
### `UpdatePracticeInput`
All fields optional. When `parents` is present, it **replaces the entire parent set** (not a merge).
Shell metadata only — **does not include `parents`**.
| Field | Notes |
|-------|-------|
| `parents` | Full replacement list |
| `title`, `story_description`, … | Same as before |
| `publish_status` | `DRAFT` / `PUBLISHED` |
@ -335,6 +346,19 @@ Authorization: Bearer <token>
Content-Type: application/json
```
### Example — create without parents (link later)
```json
{
"parents": null,
"question_set_id": 100,
"title": "Draft practice shell",
"publish_status": "DRAFT"
}
```
Equivalent: omit `parents` entirely.
### Example — multiple parents
```json
@ -382,23 +406,27 @@ sequenceDiagram
UI->>API: POST /question-sets (optional — create empty practice set first)
API-->>UI: question_set_id
UI->>API: POST /practices { parents, question_set_id, title, … }
API-->>UI: practice { id, parents, question_set_id }
UI->>API: POST /practices { question_set_id } (parents null)
API-->>UI: practice { id, parents: null }
UI->>API: PUT /practices/:id/parents { parents: [...] }
API-->>UI: practice { id, parents: [...] }
UI->>API: PUT /practices/:id/full { questions, question_set, practice }
API-->>UI: full practice payload
```
1. Create or select a **question set** (`question_set_id`).
2. **POST /practices** with `parents` + `question_set_id`.
3. Navigate to the question editor; use **PUT /practices/:id/full** for questions (see associations guide).
2. **POST /practices** with `question_set_id` (and optional `parents`).
3. **PUT /practices/:id/parents** when ready to attach hierarchy locations.
4. Navigate to the question editor; use **PUT /practices/:id/full** for questions (see associations guide).
---
## Update practice shell (including parents)
## Update practice parents
```http
PUT /api/v1/practices/:id
PUT /api/v1/practices/:id/parents
Authorization: Bearer <token>
Content-Type: application/json
```
@ -414,11 +442,27 @@ Content-Type: application/json
}
```
Sending `parents: []` is rejected (invalid parent). To change parents, send the **full desired list**.
### Detach from all hierarchy nodes
### Update metadata only (parents unchanged)
```json
{
"parents": []
}
```
Omit `parents` from the body:
### Conflict when retargeting a taken parent
If Lesson 99 already has a different practice, adding it to this practice’s `parents` returns **409** with message `This course, module, or lesson already has a practice`.
---
## Update practice shell (metadata only)
```http
PUT /api/v1/practices/:id
```
Omit parents — use the dedicated `/parents` route above.
```json
{
@ -427,10 +471,6 @@ Omit `parents` from the body:
}
```
### Conflict when retargeting a taken parent
If Lesson 99 already has a different practice, adding it to this practice’s `parents` returns **409** with message `This course, module, or lesson already has a practice`.
---
## Full practice load/save (questions)
@ -474,7 +514,7 @@ PUT /api/v1/practices/:id/full
}
```
To edit **where** the practice appears in the hierarchy, call `PUT /api/v1/practices/:id` with `parents` — either from a dedicated “Locations” tab or before/after a full save.
To edit **where** the practice appears in the hierarchy, call `PUT /api/v1/practices/:id/parents`.
---
@ -619,7 +659,7 @@ Mirror server rules before submit:
| Rule | Error message (suggested) |
|------|---------------------------|
| `parents.length >= 1` on create | “Select at least one course, module, or lesson.” |
| `parents.length >= 1` on create when linking at create time | “Select at least one course, module, or lesson.” |
| Each `parent_id > 0` | “Pick a valid parent for each row.” |
| No duplicate `(kind, id)` | “The same location is listed twice.” |
| `question_set_id` set on create | “Link a question set before creating the practice.” |
@ -641,7 +681,7 @@ interface ApiResponse<T> {
interface Practice {
id: number;
parents: PracticeParent[];
parents: PracticeParent[] | null;
title: string;
story_description?: string | null;
story_image?: string | null;
@ -654,7 +694,7 @@ interface Practice {
}
interface CreatePracticeInput {
parents?: PracticeParent[];
parents?: PracticeParent[] | null;
parent_kind?: PracticeParentKind;
parent_id?: number;
question_set_id: number;
@ -666,8 +706,11 @@ interface CreatePracticeInput {
publish_status?: "DRAFT" | "PUBLISHED";
}
interface UpdatePracticeParentsInput {
parents: PracticeParent[];
}
interface UpdatePracticeInput {
parents?: PracticeParent[];
title?: string;
story_description?: string;
story_image?: string;
@ -716,7 +759,7 @@ async function updatePracticeParents(
parents: PracticeParent[],
token: string
): Promise<Practice> {
const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}`, {
const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/parents`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
@ -752,7 +795,7 @@ async function loadPracticeFull(practiceId: number, token: string) {
}
```
Keep `practice.parents` in shell state; persist parent changes with `updatePracticeParents`, not with `PUT .../full`.
Keep `practice.parents` in shell state; persist parent changes with `PUT .../parents`, not with `PUT .../full`.
---
@ -777,9 +820,9 @@ Always surface the API `error` string when present.
### Data & API
- [ ] Migration `000089` applied in target environments
- [ ] Create form sends `parents[]` (or legacy fields only during transition)
- [ ] All reads use `practice.parents` instead of `parent_kind` / `parent_id`
- [ ] Parent edits use `PUT /api/v1/practices/:id` — **not** `PUT .../full`
- [ ] Create form allows `parents: null` / omitted (unlinked shell)
- [ ] All reads treat `practice.parents` as `null` or an array
- [ ] Parent edits use `PUT /api/v1/practices/:id/parents` — **not** `PUT .../full` or `PUT /practices/:id`
- [ ] Full editor (`GET/PUT .../full`) unchanged for questions — see [associations guide](./practice-question-associations-admin-panel-integration.md)
- [ ] List pages still use course/module/lesson scoped list endpoints; expect same practice ID if multi-parented
@ -810,7 +853,7 @@ Always surface the API `error` string when present.
|-------|----------|
| Exam-prep practices | Still **one** `unit_module_lesson_id` per practice; this guide does not apply |
| One practice per entity | A given course, module, or lesson cannot be parent to two different practices |
| Full update payload | `parents` not supported on `PUT .../full` |
| Full update payload | `parents` not supported on `PUT .../full` or `PUT /practices/:id` |
| Indirect course listing | `GET /courses/:id/practices` does **not** include practices only linked via lessons inside that course — add an explicit `COURSE` parent if the practice should appear on the course list |
| Progression | Completing a multi-parent practice can trigger rollups for **each** parent scope (lesson module, direct course, etc.) |
@ -820,9 +863,10 @@ Always surface the API `error` string when present.
| Task | Method | Path | Body highlights |
|------|--------|------|-----------------|
| Create practice | `POST` | `/api/v1/practices` | `parents`, `question_set_id` |
| Create practice | `POST` | `/api/v1/practices` | `question_set_id`; `parents` optional/null |
| Get shell | `GET` | `/api/v1/practices/:id` | — |
| Update shell + parents | `PUT` | `/api/v1/practices/:id` | `parents` replaces all links |
| Update parent links | `PUT` | `/api/v1/practices/:id/parents` | `parents` replaces all links |
| Update shell metadata | `PUT` | `/api/v1/practices/:id` | no `parents` |
| Load questions | `GET` | `/api/v1/practices/:id/full` | `data.practice.parents` |
| Save questions | `PUT` | `/api/v1/practices/:id/full` | no `parents` |
| List on course | `GET` | `/api/v1/courses/:id/practices` | — |

View File

@ -45,10 +45,26 @@ func PracticePublishStatusFromDB(raw string) PracticePublishStatus {
return ParsePracticePublishStatusInput(raw)
}
// Practice is question-set content (story, persona, tips) linked to one or more courses, modules, or lessons.
// PracticeParentsPtr returns nil when there are no parents (JSON null); otherwise a pointer to the slice.
func PracticeParentsPtr(parents []PracticeParent) *[]PracticeParent {
if len(parents) == 0 {
return nil
}
return &parents
}
// PracticeParentsDeref returns an empty slice when parents is nil.
func PracticeParentsDeref(parents *[]PracticeParent) []PracticeParent {
if parents == nil {
return nil
}
return *parents
}
// Practice is question-set content (story, persona, tips) linked to zero or more courses, modules, or lessons.
type Practice struct {
ID int64 `json:"id"`
Parents []PracticeParent `json:"parents"`
Parents *[]PracticeParent `json:"parents"`
Title string `json:"title"`
StoryDescription *string `json:"story_description,omitempty"`
StoryImage *string `json:"story_image,omitempty"`
@ -72,8 +88,8 @@ func (p Practice) VisibleToLearners() bool {
}
type CreatePracticeInput struct {
// Parents is the preferred way to attach a practice to one or more hierarchy entities.
Parents []PracticeParent `json:"parents,omitempty" validate:"omitempty,dive"`
// Parents optionally attaches the practice to hierarchy entities. Omit or null to create unlinked.
Parents *[]PracticeParent `json:"parents" validate:"omitempty,dive"`
// ParentKind and ParentID are accepted for backward compatibility when parents is omitted.
ParentKind ParentKind `json:"parent_kind,omitempty" validate:"omitempty,oneof=COURSE MODULE LESSON"`
ParentID int64 `json:"parent_id,omitempty" validate:"omitempty,gt=0"`
@ -89,8 +105,8 @@ type CreatePracticeInput struct {
// ResolvedParents returns deduplicated parents from parents or the legacy single-parent fields.
func (in CreatePracticeInput) ResolvedParents() []PracticeParent {
if len(in.Parents) > 0 {
return dedupePracticeParents(in.Parents)
if in.Parents != nil {
return DedupePracticeParents(*in.Parents)
}
if in.ParentKind != "" && in.ParentID > 0 {
return []PracticeParent{{Kind: in.ParentKind, ID: in.ParentID}}
@ -98,7 +114,13 @@ func (in CreatePracticeInput) ResolvedParents() []PracticeParent {
return nil
}
func dedupePracticeParents(parents []PracticeParent) []PracticeParent {
// UpdatePracticeParentsInput replaces all parent links on an existing practice.
type UpdatePracticeParentsInput struct {
Parents []PracticeParent `json:"parents" validate:"required,dive"`
}
// DedupePracticeParents removes invalid and duplicate parent entries.
func DedupePracticeParents(parents []PracticeParent) []PracticeParent {
seen := make(map[PracticeParent]struct{}, len(parents))
out := make([]PracticeParent, 0, len(parents))
for _, p := range parents {
@ -115,7 +137,6 @@ func dedupePracticeParents(parents []PracticeParent) []PracticeParent {
}
type UpdatePracticeInput struct {
Parents []PracticeParent `json:"parents,omitempty" validate:"omitempty,dive"`
Title *string `json:"title,omitempty"`
StoryDescription *string `json:"story_description,omitempty"`
StoryImage *string `json:"story_image,omitempty"`

View File

@ -14,7 +14,7 @@ type PracticeByQuestionTypeDefinition struct {
PersonaID *int64 `json:"persona_id,omitempty"`
QuickTips *string `json:"quick_tips,omitempty"`
PublishStatus PracticePublishStatus `json:"publish_status"`
Parents []PracticeParent `json:"parents,omitempty"`
Parents *[]PracticeParent `json:"parents"`
ExamPrepLessonID *int64 `json:"exam_prep_lesson_id,omitempty"`
MatchingQuestionCount int64 `json:"matching_question_count"`
CreatedAt time.Time `json:"created_at"`

View File

@ -59,7 +59,7 @@ func lmsPracticeParentsFromDB(rows []dbgen.LmsPracticeParent) []domain.PracticeP
func lmsPracticeToDomain(p dbgen.LmsPractice, parents []domain.PracticeParent) domain.Practice {
out := domain.Practice{
ID: p.ID,
Parents: parents,
Parents: domain.PracticeParentsPtr(parents),
Title: p.Title,
QuestionSetID: p.QuestionSetID,
PublishStatus: domain.PracticePublishStatusFromDB(p.PublishStatus),
@ -89,18 +89,19 @@ func (s *Store) attachParentsToPractices(ctx context.Context, practices []domain
return practices, nil
}
ids := make([]int64, len(practices))
indexByID := make(map[int64]int, len(practices))
for i, p := range practices {
ids[i] = p.ID
indexByID[p.ID] = i
}
rows, err := s.queries.ListLmsPracticeParentsByPracticeIDs(ctx, ids)
if err != nil {
return nil, err
}
accum := make(map[int64][]domain.PracticeParent, len(practices))
for _, row := range rows {
idx := indexByID[row.PracticeID]
practices[idx].Parents = append(practices[idx].Parents, lmsPracticeParentFromDB(row))
accum[row.PracticeID] = append(accum[row.PracticeID], lmsPracticeParentFromDB(row))
}
for i, p := range practices {
practices[i].Parents = domain.PracticeParentsPtr(accum[p.ID])
}
return practices, nil
}

View File

@ -1332,7 +1332,7 @@ func practiceByQuestionTypeRowToDomain(r dbgen.ListPracticesByQuestionTypeDefini
UpdatedAt: timePtr(r.UpdatedAt),
}
if r.PracticeKind == "LMS" {
out.Parents = parents
out.Parents = domain.PracticeParentsPtr(parents)
} else if r.ExamPrepLessonID.Valid {
id := r.ExamPrepLessonID.Int64
out.ExamPrepLessonID = &id

View File

@ -101,10 +101,7 @@ func (s *Service) validateParent(ctx context.Context, parent domain.PracticePare
return nil
}
func (s *Service) validateParents(ctx context.Context, parents []domain.PracticeParent) error {
if len(parents) == 0 {
return ErrInvalidPracticeParent
}
func (s *Service) validateParentList(ctx context.Context, parents []domain.PracticeParent) error {
for _, parent := range parents {
if err := s.validateParent(ctx, parent); err != nil {
return err
@ -142,11 +139,13 @@ func (s *Service) Create(ctx context.Context, in domain.CreatePracticeInput) (do
}
}
parents := in.ResolvedParents()
if err := s.validateParents(ctx, parents); err != nil {
return domain.Practice{}, err
}
if err := s.ensureParentsAvailable(ctx, parents, 0); err != nil {
return domain.Practice{}, err
if len(parents) > 0 {
if err := s.validateParentList(ctx, parents); err != nil {
return domain.Practice{}, err
}
if err := s.ensureParentsAvailable(ctx, parents, 0); err != nil {
return domain.Practice{}, err
}
}
p, err := s.practices.CreateLmsPractice(ctx, in, parents)
if err != nil && repository.IsUniqueViolation(err) {
@ -227,21 +226,6 @@ func (s *Service) Update(ctx context.Context, id int64, input domain.UpdatePract
return domain.Practice{}, err
}
}
if input.Parents != nil {
parents := domain.CreatePracticeInput{Parents: input.Parents}.ResolvedParents()
if err := s.validateParents(ctx, parents); err != nil {
return domain.Practice{}, err
}
if err := s.ensureParentsAvailable(ctx, parents, id); err != nil {
return domain.Practice{}, err
}
if err := s.practices.ReplaceLmsPracticeParents(ctx, id, parents); err != nil {
if repository.IsUniqueViolation(err) {
return domain.Practice{}, ErrPracticeParentLimitExceeded
}
return domain.Practice{}, err
}
}
p, err := s.practices.UpdateLmsPractice(ctx, id, input)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@ -252,6 +236,32 @@ func (s *Service) Update(ctx context.Context, id int64, input domain.UpdatePract
return p, nil
}
// UpdateParents replaces all course/module/lesson links for a practice.
func (s *Service) UpdateParents(ctx context.Context, id int64, in domain.UpdatePracticeParentsInput) (domain.Practice, error) {
if _, err := s.practices.GetLmsPracticeByID(ctx, id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.Practice{}, ErrPracticeNotFound
}
return domain.Practice{}, err
}
parents := domain.DedupePracticeParents(in.Parents)
if len(parents) > 0 {
if err := s.validateParentList(ctx, parents); err != nil {
return domain.Practice{}, err
}
if err := s.ensureParentsAvailable(ctx, parents, id); err != nil {
return domain.Practice{}, err
}
}
if err := s.practices.ReplaceLmsPracticeParents(ctx, id, parents); err != nil {
if repository.IsUniqueViolation(err) {
return domain.Practice{}, ErrPracticeParentLimitExceeded
}
return domain.Practice{}, err
}
return s.practices.GetLmsPracticeByID(ctx, id)
}
func (s *Service) Delete(ctx context.Context, id int64) error {
if _, err := s.practices.GetLmsPracticeByID(ctx, id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {

View File

@ -327,12 +327,12 @@ func (a *App) lmsEffectiveTierForPractice(ctx context.Context, practiceID int64)
if err != nil {
return "", false, err
}
if len(practice.Parents) == 0 {
if len(domain.PracticeParentsDeref(practice.Parents)) == 0 {
return "", false, nil
}
var tier domain.ContentAccessTier
okAny := false
for _, parent := range practice.Parents {
var tier domain.ContentAccessTier
for _, parent := range domain.PracticeParentsDeref(practice.Parents) {
var (
parentTier domain.ContentAccessTier
ok bool

View File

@ -17,7 +17,7 @@ import (
// CreatePractice godoc
// @Tags practices
// @Accept json
// @Param body body domain.CreatePracticeInput true "Practice (parents array and/or legacy parent_kind + parent_id)"
// @Param body body domain.CreatePracticeInput true "Practice (optional parents; link later via PUT /practices/:id/parents)"
// @Router /api/v1/practices [post]
func (h *Handler) CreatePractice(c *fiber.Ctx) error {
var req domain.CreatePracticeInput
@ -244,7 +244,7 @@ func practiceAccessForQuestionSet(set domain.QuestionSet) *domain.PracticeAccess
// UpdatePractice godoc
// @Tags practices
// @Param id path int true "Practice ID"
// @Param body body domain.UpdatePracticeInput true "Fields to update (parent is immutable)"
// @Param body body domain.UpdatePracticeInput true "Practice metadata fields to update"
// @Router /api/v1/practices/{id} [put]
func (h *Handler) UpdatePractice(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
@ -277,6 +277,60 @@ func (h *Handler) UpdatePractice(c *fiber.Ctx) error {
return c.JSON(domain.Response{Message: "Practice updated successfully", Data: p, Success: true, StatusCode: fiber.StatusOK})
}
// UpdatePracticeParents godoc
// @Tags practices
// @Accept json
// @Param id path int true "Practice ID"
// @Param body body domain.UpdatePracticeParentsInput true "Parent links (replaces all; use empty array to detach)"
// @Router /api/v1/practices/{id}/parents [put]
func (h *Handler) UpdatePracticeParents(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid practice id", Error: err.Error()})
}
var req domain.UpdatePracticeParentsInput
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
if valErrs, ok := h.validator.Validate(c, req); !ok {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Validation failed",
Error: firstValidationError(valErrs),
})
}
p, err := h.practiceSvc.UpdateParents(c.Context(), id, req)
if err != nil {
switch {
case errors.Is(err, practices.ErrPracticeNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found", Error: err.Error()})
case errors.Is(err, courses.ErrCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Course not found", Error: err.Error()})
case errors.Is(err, modules.ErrModuleNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Module not found", Error: err.Error()})
case errors.Is(err, lessons.ErrLessonNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: err.Error()})
case errors.Is(err, practices.ErrInvalidPracticeParent):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
case errors.Is(err, practices.ErrPracticeParentLimitExceeded):
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
Message: "This course, module, or lesson already has a practice",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to update practice parents", Error: err.Error()})
}
actorID := c.Locals("user_id").(int64)
actorRole := string(c.Locals("role").(domain.Role))
ip := c.IP()
ua := c.Get("User-Agent")
rid := p.ID
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionPracticeUpdated, domain.ResourcePractice, &rid, "Updated practice parents: "+p.Title, nil, &ip, &ua)
return c.JSON(domain.Response{Message: "Practice parents updated successfully", Data: p, Success: true, StatusCode: fiber.StatusOK})
}
// DeletePractice godoc
// @Tags practices
// @Param id path int true "Practice ID"

View File

@ -162,6 +162,7 @@ func (a *App) initAppRoutes() {
groupV1.Post("/practices", a.authMiddleware, a.RequirePermission("practices.create"), h.CreatePractice)
groupV1.Get("/practices/:id", a.authMiddleware, a.RequireLMSSubscriptionUnlessFree(), a.RequirePermission("practices.get"), h.GetPractice)
groupV1.Get("/practices/:id/full", a.authMiddleware, a.RequireLMSSubscriptionUnlessFree(), a.RequirePermission("practices.get"), h.GetLmsPracticeFull)
groupV1.Put("/practices/:id/parents", a.authMiddleware, a.RequirePermission("practices.update"), h.UpdatePracticeParents)
groupV1.Put("/practices/:id", a.authMiddleware, a.RequirePermission("practices.update"), h.UpdatePractice)
groupV1.Put("/practices/:id/full", a.authMiddleware, a.RequirePermission("practices.update"), h.UpdateLmsPracticeFull)
groupV1.Delete("/practices/:id", a.authMiddleware, a.RequirePermission("practices.delete"), h.DeletePractice)