Adds DELETE /practices/:id/parents/:parentKind/:parentId and exam-prep equivalent so admins can remove one location link without replacing the full parents array. Includes admin panel integration guide and parent kind parse tests. Co-authored-by: Cursor <cursoragent@cursor.com>
884 lines
27 KiB
Markdown
884 lines
27 KiB
Markdown
# Practice Per-Parent Unlink — Admin Panel Integration Guide
|
||
|
||
This guide documents how to integrate the **per-parent unlink** API into the Yimaru **admin panel**. Content editors can remove a single course, module, lesson, unit, or catalog-course link from a practice **without** sending the full replacement `parents` array and **without** deleting the practice shell or its questions.
|
||
|
||
> **Scope:** Both **LMS** (`/api/v1/practices`) and **exam-prep** (`/api/v1/exam-prep/practices`).
|
||
>
|
||
> **Related:**
|
||
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — multi-parent attach, bulk replace via `PUT .../parents`
|
||
> - [practice-create-nullable-parents-admin-panel-integration.md](./practice-create-nullable-parents-admin-panel-integration.md) — creating unlinked practice shells
|
||
> - [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md) — question editor inside a practice
|
||
> - [practice-stimulus-blocks-admin-panel-integration.md](./practice-stimulus-blocks-admin-panel-integration.md) — IELTS shared stimulus blocks (orthogonal to parent links)
|
||
|
||
---
|
||
|
||
## Table of contents
|
||
|
||
1. [Feature overview](#feature-overview)
|
||
2. [When to use unlink vs bulk replace](#when-to-use-unlink-vs-bulk-replace)
|
||
3. [Architecture](#architecture)
|
||
4. [Authentication & permissions](#authentication--permissions)
|
||
5. [API reference — LMS](#api-reference--lms)
|
||
6. [API reference — exam-prep](#api-reference--exam-prep)
|
||
7. [Response envelopes](#response-envelopes)
|
||
8. [Behavior & side effects](#behavior--side-effects)
|
||
9. [Recommended admin UI changes](#recommended-admin-ui-changes)
|
||
10. [Contextual unlink flows](#contextual-unlink-flows)
|
||
11. [TypeScript types & API client](#typescript-types--api-client)
|
||
12. [React integration patterns](#react-integration-patterns)
|
||
13. [Optimistic UI & state sync](#optimistic-ui--state-sync)
|
||
14. [Error handling](#error-handling)
|
||
15. [Testing checklist](#testing-checklist)
|
||
16. [Integration checklist](#integration-checklist)
|
||
17. [Limitations](#limitations)
|
||
18. [Quick reference](#quick-reference)
|
||
|
||
---
|
||
|
||
## Feature overview
|
||
|
||
| Capability | Before (bulk only) | After (per-parent unlink) |
|
||
|------------|-------------------|---------------------------|
|
||
| Remove one parent, keep others | Send `PUT .../parents` with filtered array | **`DELETE .../parents/:parentKind/:parentId`** |
|
||
| Detach from all parents | `PUT .../parents` with `"parents": []` | Still supported; or call DELETE once per parent |
|
||
| Delete practice entirely | `DELETE .../practices/:id` | Unchanged — unlink is **not** delete |
|
||
| Practice shell after last unlink | `parents: null` | Same — practice becomes **unlinked** |
|
||
| Learner visibility on entity | Practice disappears from that course/module/lesson list | Same — list endpoints filter by direct parent link |
|
||
|
||
### What problem this solves
|
||
|
||
Multi-parent practices often need **surgical** edits:
|
||
|
||
- Remove a practice from **Lesson 12** but keep it on **Course 7**
|
||
- Detach from a **unit** in exam-prep while the practice remains on another **lesson**
|
||
- Unlink from the page the editor is currently viewing without re-serializing the entire parent picker state
|
||
|
||
Previously the admin had to:
|
||
|
||
1. Read current `practice.parents`
|
||
2. Filter out the row to remove
|
||
3. `PUT .../parents` with the remaining array
|
||
|
||
That is error-prone when the UI has unsaved parent-picker changes. The DELETE endpoint makes **one parent removal** a single, idempotent server operation.
|
||
|
||
---
|
||
|
||
## When to use unlink vs bulk replace
|
||
|
||
| Scenario | Recommended API |
|
||
|----------|-----------------|
|
||
| User clicks **Remove** on one location chip | `DELETE .../parents/:parentKind/:parentId` |
|
||
| User reorders or rewrites the whole locations list in a form | `PUT .../parents` with full `parents` array |
|
||
| User clicks **Detach from everywhere** | `PUT .../parents` with `{ "parents": [] }` **or** DELETE each chip in sequence |
|
||
| User adds a new parent | `PUT .../parents` with expanded array (409 if target already taken) |
|
||
| Create flow — first attach | `POST .../practices` with `parents`, or `PUT .../parents` after create |
|
||
|
||
**Rule of thumb:** use **DELETE** for incremental removal; use **PUT** for additive or wholesale replacement.
|
||
|
||
---
|
||
|
||
## Architecture
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
subgraph AdminUI["Admin panel"]
|
||
Chips["Location chips"]
|
||
Confirm["Confirm dialog"]
|
||
end
|
||
|
||
subgraph API["Yimaru API"]
|
||
DelLMS["DELETE /practices/:id/parents/:kind/:parentId"]
|
||
DelEP["DELETE /exam-prep/practices/:id/parents/:kind/:parentId"]
|
||
Put["PUT .../parents"]
|
||
end
|
||
|
||
subgraph DB["Database"]
|
||
LPP["lms_practice_parents"]
|
||
EPP["exam_prep.practice_parents"]
|
||
end
|
||
|
||
Chips --> Confirm
|
||
Confirm --> DelLMS
|
||
Confirm --> DelEP
|
||
DelLMS --> LPP
|
||
DelEP --> EPP
|
||
Chips -. bulk edit .-> Put
|
||
```
|
||
|
||
### Backend touchpoints
|
||
|
||
| Layer | LMS | Exam-prep |
|
||
|-------|-----|-----------|
|
||
| Route | `internal/web_server/routes.go` | same |
|
||
| Handler | `UnlinkPracticeParent` | `UnlinkExamPrepPracticeParent` |
|
||
| Service | `practices.Service.UnlinkParent` | `examprep.Service.UnlinkExamPrepPracticeParent` |
|
||
| Repository | `DeleteLmsPracticeParent` | `DeleteExamPrepPracticeParent` |
|
||
| SQL | `DeleteLmsPracticeParent` | `DeleteExamPrepPracticeParent` |
|
||
| Domain parsers | `ParsePracticeParentKind` | `ParseExamPrepParentKind` |
|
||
|
||
No new migration is required — the feature deletes rows from existing junction tables.
|
||
|
||
---
|
||
|
||
## Authentication & permissions
|
||
|
||
Use a **team member** or **platform admin** bearer token:
|
||
|
||
```http
|
||
Authorization: Bearer <access_token>
|
||
```
|
||
|
||
No request body is required for unlink.
|
||
|
||
| System | Action | Permission |
|
||
|--------|--------|------------|
|
||
| LMS | Unlink one parent | `practices.update` |
|
||
| Exam-prep | Unlink one parent | `exam_prep.practices.update` |
|
||
|
||
Unlink uses the **same permission** as `PUT .../parents`. Users who can edit parent links can unlink them.
|
||
|
||
---
|
||
|
||
## API reference — LMS
|
||
|
||
### Unlink one parent
|
||
|
||
```http
|
||
DELETE /api/v1/practices/:id/parents/:parentKind/:parentId
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Path parameters
|
||
|
||
| Param | Type | Description |
|
||
|-------|------|-------------|
|
||
| `id` | int64 | LMS practice ID (`lms_practices.id`) |
|
||
| `parentKind` | string | `COURSE`, `MODULE`, or `LESSON` (case-insensitive) |
|
||
| `parentId` | int64 | ID of the course, module, or lesson row |
|
||
|
||
#### Example — remove course link only
|
||
|
||
```http
|
||
DELETE /api/v1/practices/55/parents/COURSE/7
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Example — remove lesson link
|
||
|
||
```http
|
||
DELETE /api/v1/practices/55/parents/lesson/42
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Success response `200 OK`
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"status_code": 200,
|
||
"message": "Practice parent unlinked successfully",
|
||
"data": {
|
||
"id": 55,
|
||
"parents": [
|
||
{ "parent_kind": "LESSON", "parent_id": 42 }
|
||
],
|
||
"title": "Module capstone",
|
||
"question_set_id": 100,
|
||
"publish_status": "PUBLISHED",
|
||
"authoring_profile": "STANDALONE",
|
||
"created_at": "2026-06-18T10:00:00Z",
|
||
"updated_at": "2026-06-26T14:30:00Z"
|
||
}
|
||
}
|
||
```
|
||
|
||
When the last parent is removed, `data.parents` is JSON **`null`** (not `[]`).
|
||
|
||
#### Sequence — unlink one of two parents
|
||
|
||
```mermaid
|
||
sequenceDiagram
|
||
participant UI as Admin UI
|
||
participant API as API
|
||
|
||
UI->>API: GET /practices/55
|
||
API-->>UI: parents: [COURSE/7, LESSON/42]
|
||
|
||
UI->>UI: User confirms "Remove from Course 7"
|
||
UI->>API: DELETE /practices/55/parents/COURSE/7
|
||
API-->>UI: 200, parents: [LESSON/42]
|
||
|
||
UI->>UI: Update chips from response.data.parents
|
||
```
|
||
|
||
---
|
||
|
||
## API reference — exam-prep
|
||
|
||
### Unlink one parent
|
||
|
||
```http
|
||
DELETE /api/v1/exam-prep/practices/:id/parents/:parentKind/:parentId
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Path parameters
|
||
|
||
| Param | Type | Description |
|
||
|-------|------|-------------|
|
||
| `id` | int64 | Exam-prep practice ID (`exam_prep.lesson_practices.id`) |
|
||
| `parentKind` | string | `CATALOG_COURSE`, `UNIT`, or `LESSON` (case-insensitive) |
|
||
| `parentId` | int64 | Catalog course, unit, or `unit_module_lesson` ID |
|
||
|
||
> **Note:** Exam-prep has **no `MODULE` parent kind**. Practices under a module are linked via **lessons** (`LESSON`) or higher levels (`UNIT`, `CATALOG_COURSE`).
|
||
|
||
#### Example — remove unit link
|
||
|
||
```http
|
||
DELETE /api/v1/exam-prep/practices/88/parents/UNIT/15
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Example — remove catalog course link
|
||
|
||
```http
|
||
DELETE /api/v1/exam-prep/practices/88/parents/CATALOG_COURSE/3
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
#### Success response `200 OK`
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"status_code": 200,
|
||
"message": "Practice parent unlinked successfully",
|
||
"data": {
|
||
"id": 88,
|
||
"parents": [
|
||
{ "parent_kind": "LESSON", "parent_id": 201 }
|
||
],
|
||
"title": "Reading drill",
|
||
"question_set_id": 450,
|
||
"publish_status": "PUBLISHED",
|
||
"authoring_profile": "IELTS_SHARED_STIMULUS",
|
||
"created_at": "2026-06-10T08:00:00Z",
|
||
"updated_at": "2026-06-26T14:35:00Z"
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Response envelopes
|
||
|
||
### Success
|
||
|
||
Always returns the **updated practice shell** in `data`, including the current `parents` array (or `null`).
|
||
|
||
| Field | Notes |
|
||
|-------|-------|
|
||
| `success` | `true` |
|
||
| `status_code` | `200` |
|
||
| `message` | `"Practice parent unlinked successfully"` |
|
||
| `data` | Full `Practice` or `ExamPrepPractice` object |
|
||
|
||
### Error
|
||
|
||
```json
|
||
{
|
||
"message": "Practice is not linked to that parent",
|
||
"error": "practice is not linked to that parent"
|
||
}
|
||
```
|
||
|
||
See [Error handling](#error-handling) for the full status-code matrix.
|
||
|
||
---
|
||
|
||
## Behavior & side effects
|
||
|
||
### What unlink does
|
||
|
||
1. Deletes **one row** from `lms_practice_parents` or `exam_prep.practice_parents`.
|
||
2. Leaves the practice row, question set, questions, and stimulus blocks **unchanged**.
|
||
3. Returns the practice with remaining parents.
|
||
4. Records an activity log entry (`PracticeUpdated` / `ExamPrepPracticeUpdated`).
|
||
|
||
### What unlink does **not** do
|
||
|
||
- Does **not** delete the practice (`DELETE .../practices/:id` is separate).
|
||
- Does **not** delete the question set or questions.
|
||
- Does **not** cascade to other parent links on the same practice.
|
||
- Does **not** validate that at least one parent remains — **zero parents is allowed** (unlinked practice).
|
||
|
||
### List endpoint impact
|
||
|
||
After unlinking from an entity, the practice **no longer appears** in that entity’s practice list:
|
||
|
||
| Endpoint | Stops listing practice when… |
|
||
|----------|------------------------------|
|
||
| `GET /api/v1/courses/:id/practices` | `COURSE` link removed |
|
||
| `GET /api/v1/modules/:id/practices` | `MODULE` link removed |
|
||
| `GET /api/v1/lessons/:id/practices` | `LESSON` link removed |
|
||
| `GET /api/v1/exam-prep/catalog-courses/:id/practices` | `CATALOG_COURSE` link removed |
|
||
| `GET /api/v1/exam-prep/units/:id/practices` | `UNIT` link removed |
|
||
| `GET /api/v1/exam-prep/lessons/:id/practices` | `LESSON` link removed |
|
||
|
||
Find fully unlinked practices globally:
|
||
|
||
```http
|
||
GET /api/v1/practices?unlinked_only=true
|
||
GET /api/v1/exam-prep/practices?unlinked_only=true
|
||
```
|
||
|
||
### Idempotency note
|
||
|
||
Calling DELETE for a parent that is **already unlinked** returns **404** (`Practice is not linked to that parent`). The UI should treat this as “already removed” and refresh from `GET .../practices/:id` rather than showing a hard error.
|
||
|
||
---
|
||
|
||
## Recommended admin UI changes
|
||
|
||
### 1. Per-chip **Remove** action (primary integration)
|
||
|
||
In the **Locations** / **Attached to** section (see multi-parent guide), add a remove control on each chip:
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────┐
|
||
│ Attached to │
|
||
│ │
|
||
│ [Course: Algebra I ×] │
|
||
│ [Lesson: Factoring intro ×] │
|
||
│ │
|
||
│ [ + Add location ] │
|
||
└─────────────────────────────────────────────────────────┘
|
||
```
|
||
|
||
**On × click:**
|
||
|
||
1. Show confirmation: *“Remove this practice from Algebra I? The practice will remain available at other locations.”*
|
||
2. On confirm → `DELETE .../parents/COURSE/:courseId`
|
||
3. On success → replace local `practice.parents` with `response.data.parents`
|
||
4. If `parents` becomes `null`, show badge **Unlinked** and link to global practice list
|
||
|
||
**Do not** require a separate **Save locations** click for removal when using DELETE — the server is updated immediately.
|
||
|
||
### 2. Distinguish **Remove location** vs **Delete practice**
|
||
|
||
| Action | API | User-facing copy |
|
||
|--------|-----|------------------|
|
||
| Remove location | `DELETE .../parents/...` | “Remove from this course/lesson…” |
|
||
| Delete practice | `DELETE .../practices/:id` | “Delete practice permanently” |
|
||
|
||
Use different button styles (secondary vs destructive) and confirmation copy.
|
||
|
||
### 3. Last-parent removal
|
||
|
||
When removing the **last** chip:
|
||
|
||
- Confirm: *“This practice will not appear in any course, module, or lesson until re-attached. Questions are kept.”*
|
||
- After success, `parents` is `null` — navigate or show link: **View in unlinked practices**
|
||
|
||
### 4. Bulk locations editor (optional)
|
||
|
||
If the admin UI still has a **Save all locations** form that rewrites the full array:
|
||
|
||
- **Remove chip locally** → mark dirty → save via `PUT .../parents`
|
||
- **Or** switch remove to immediate `DELETE` and only use `PUT` for **Add location**
|
||
|
||
Prefer immediate DELETE for removes to avoid clobbering concurrent edits.
|
||
|
||
### 5. Disable unlink when read-only
|
||
|
||
Hide × buttons when the user lacks `practices.update` / `exam_prep.practices.update`.
|
||
|
||
---
|
||
|
||
## Contextual unlink flows
|
||
|
||
### A. From a lesson detail page
|
||
|
||
The page shows a practice card because `GET /lessons/:id/practices` returned it.
|
||
|
||
```http
|
||
DELETE /api/v1/practices/:practiceId/parents/LESSON/:lessonId
|
||
```
|
||
|
||
After success:
|
||
|
||
- Remove the practice card from the lesson page
|
||
- Optionally toast: *“Practice removed from this lesson”* with link *“Open practice”* (still exists if other parents remain)
|
||
|
||
### B. From exam-prep unit page
|
||
|
||
If the practice is attached at **unit** level:
|
||
|
||
```http
|
||
DELETE /api/v1/exam-prep/practices/:id/parents/UNIT/:unitId
|
||
```
|
||
|
||
If attached only via a **lesson** under the unit, unlink the lesson parent instead (there is no module-level parent).
|
||
|
||
### C. From practice settings editor
|
||
|
||
Show all parents from `GET /practices/:id` or `GET /practices/:id/full` → `practice.parents`. Each chip gets its own DELETE target.
|
||
|
||
### D. “Detach from everywhere”
|
||
|
||
Either:
|
||
|
||
```http
|
||
PUT /api/v1/practices/:id/parents
|
||
Content-Type: application/json
|
||
|
||
{ "parents": [] }
|
||
```
|
||
|
||
Or loop DELETE for each chip (N requests). Prefer **single PUT with `[]`** for bulk detach-all.
|
||
|
||
---
|
||
|
||
## TypeScript types & API client
|
||
|
||
### Types
|
||
|
||
```typescript
|
||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||
|
||
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 Practice {
|
||
id: number;
|
||
parents: PracticeParent[] | null;
|
||
title: string;
|
||
question_set_id: number;
|
||
publish_status: "DRAFT" | "PUBLISHED";
|
||
authoring_profile?: string;
|
||
created_at: string;
|
||
updated_at?: string | null;
|
||
}
|
||
|
||
interface ExamPrepPractice {
|
||
id: number;
|
||
parents: ExamPrepPracticeParent[] | null;
|
||
title: string;
|
||
question_set_id: number;
|
||
publish_status: "DRAFT" | "PUBLISHED";
|
||
authoring_profile?: string;
|
||
created_at: string;
|
||
updated_at?: string | null;
|
||
}
|
||
|
||
interface ApiResponse<T> {
|
||
success: boolean;
|
||
status_code: number;
|
||
message: string;
|
||
data: T;
|
||
}
|
||
|
||
interface ApiErrorBody {
|
||
message?: string;
|
||
error?: string;
|
||
}
|
||
```
|
||
|
||
### URL builder
|
||
|
||
`parent_kind` values are passed as path segments. Use uppercase canonical values; the API accepts any case.
|
||
|
||
```typescript
|
||
function lmsPracticeParentUnlinkPath(
|
||
practiceId: number,
|
||
parent: PracticeParent
|
||
): string {
|
||
const kind = parent.parent_kind.toUpperCase();
|
||
return `/api/v1/practices/${practiceId}/parents/${kind}/${parent.parent_id}`;
|
||
}
|
||
|
||
function examPrepPracticeParentUnlinkPath(
|
||
practiceId: number,
|
||
parent: ExamPrepPracticeParent
|
||
): string {
|
||
const kind = parent.parent_kind.toUpperCase();
|
||
return `/api/v1/exam-prep/practices/${practiceId}/parents/${kind}/${parent.parent_id}`;
|
||
}
|
||
```
|
||
|
||
### LMS client
|
||
|
||
```typescript
|
||
export class PracticeParentUnlinkError extends Error {
|
||
constructor(
|
||
message: string,
|
||
public readonly status: number,
|
||
public readonly body?: ApiErrorBody
|
||
) {
|
||
super(message);
|
||
this.name = "PracticeParentUnlinkError";
|
||
}
|
||
}
|
||
|
||
export async function unlinkLmsPracticeParent(
|
||
practiceId: number,
|
||
parent: PracticeParent,
|
||
token: string
|
||
): Promise<Practice> {
|
||
const path = lmsPracticeParentUnlinkPath(practiceId, parent);
|
||
const res = await fetch(`${API_BASE}${path}`, {
|
||
method: "DELETE",
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
});
|
||
|
||
const body = (await res.json().catch(() => ({}))) as ApiResponse<Practice> & ApiErrorBody;
|
||
|
||
if (!res.ok) {
|
||
throw new PracticeParentUnlinkError(
|
||
body.message || body.error || `Unlink failed (${res.status})`,
|
||
res.status,
|
||
body
|
||
);
|
||
}
|
||
|
||
return body.data;
|
||
}
|
||
```
|
||
|
||
### Exam-prep client
|
||
|
||
```typescript
|
||
export async function unlinkExamPrepPracticeParent(
|
||
practiceId: number,
|
||
parent: ExamPrepPracticeParent,
|
||
token: string
|
||
): Promise<ExamPrepPractice> {
|
||
const path = examPrepPracticeParentUnlinkPath(practiceId, parent);
|
||
const res = await fetch(`${API_BASE}${path}`, {
|
||
method: "DELETE",
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
});
|
||
|
||
const body = (await res.json().catch(() => ({}))) as ApiResponse<ExamPrepPractice> & ApiErrorBody;
|
||
|
||
if (!res.ok) {
|
||
throw new PracticeParentUnlinkError(
|
||
body.message || body.error || `Unlink failed (${res.status})`,
|
||
res.status,
|
||
body
|
||
);
|
||
}
|
||
|
||
return body.data;
|
||
}
|
||
```
|
||
|
||
### Unified helper (LMS vs exam-prep mode flag)
|
||
|
||
```typescript
|
||
type PracticeMode = "lms" | "exam_prep";
|
||
|
||
export async function unlinkPracticeParent(
|
||
mode: PracticeMode,
|
||
practiceId: number,
|
||
parent: PracticeParent | ExamPrepPracticeParent,
|
||
token: string
|
||
): Promise<Practice | ExamPrepPractice> {
|
||
if (mode === "lms") {
|
||
return unlinkLmsPracticeParent(practiceId, parent as PracticeParent, token);
|
||
}
|
||
return unlinkExamPrepPracticeParent(
|
||
practiceId,
|
||
parent as ExamPrepPracticeParent,
|
||
token
|
||
);
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## React integration patterns
|
||
|
||
### Location chip with unlink
|
||
|
||
```tsx
|
||
import { useState } from "react";
|
||
import { unlinkLmsPracticeParent, PracticeParentUnlinkError } from "@/api/practices";
|
||
|
||
interface LocationChipProps {
|
||
practiceId: number;
|
||
parent: { parent_kind: "COURSE" | "MODULE" | "LESSON"; parent_id: number };
|
||
label: string;
|
||
token: string;
|
||
onUpdated: (practice: Practice) => void;
|
||
}
|
||
|
||
export function LmsLocationChip({
|
||
practiceId,
|
||
parent,
|
||
label,
|
||
token,
|
||
onUpdated,
|
||
}: LocationChipProps) {
|
||
const [loading, setLoading] = useState(false);
|
||
|
||
async function handleRemove() {
|
||
const ok = window.confirm(
|
||
`Remove this practice from ${label}? Other locations are unaffected.`
|
||
);
|
||
if (!ok) return;
|
||
|
||
setLoading(true);
|
||
try {
|
||
const practice = await unlinkLmsPracticeParent(practiceId, parent, token);
|
||
onUpdated(practice);
|
||
} catch (e) {
|
||
if (e instanceof PracticeParentUnlinkError && e.status === 404) {
|
||
// Stale UI — parent already removed
|
||
onUpdated(await refetchPractice(practiceId, token));
|
||
return;
|
||
}
|
||
alert(e instanceof Error ? e.message : "Failed to unlink");
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<span className="location-chip">
|
||
{label}
|
||
<button
|
||
type="button"
|
||
aria-label={`Remove from ${label}`}
|
||
disabled={loading}
|
||
onClick={handleRemove}
|
||
>
|
||
×
|
||
</button>
|
||
</span>
|
||
);
|
||
}
|
||
```
|
||
|
||
### Parent list container
|
||
|
||
```tsx
|
||
function PracticeLocationsSection({ practice, token, onPracticeChange }: {
|
||
practice: Practice;
|
||
token: string;
|
||
onPracticeChange: (p: Practice) => void;
|
||
}) {
|
||
const parents = practice.parents ?? [];
|
||
|
||
if (parents.length === 0) {
|
||
return (
|
||
<div className="muted">
|
||
Not attached to any course, module, or lesson.{" "}
|
||
<a href={`/admin/practices/${practice.id}/locations`}>Add location</a>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div className="location-list">
|
||
{parents.map((p) => (
|
||
<LmsLocationChip
|
||
key={`${p.parent_kind}-${p.parent_id}`}
|
||
practiceId={practice.id}
|
||
parent={p}
|
||
label={formatParentLabel(p)} // resolve course/module/lesson title
|
||
token={token}
|
||
onUpdated={onPracticeChange}
|
||
/>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
```
|
||
|
||
### Exam-prep variant
|
||
|
||
Same pattern; use `unlinkExamPrepPracticeParent` and `ExamPrepParentKind` labels (`Catalog course`, `Unit`, `Lesson`).
|
||
|
||
---
|
||
|
||
## Optimistic UI & state sync
|
||
|
||
### Recommended: pessimistic update (simpler)
|
||
|
||
1. User confirms remove
|
||
2. Show spinner on chip
|
||
3. Await DELETE
|
||
4. Replace state from `response.data`
|
||
|
||
This avoids rollback complexity and matches the server’s source of truth.
|
||
|
||
### Optional: optimistic update
|
||
|
||
```typescript
|
||
function removeParentOptimistic(
|
||
practice: Practice,
|
||
target: PracticeParent
|
||
): Practice {
|
||
const parents = (practice.parents ?? []).filter(
|
||
(p) =>
|
||
!(
|
||
p.parent_kind === target.parent_kind &&
|
||
p.parent_id === target.parent_id
|
||
)
|
||
);
|
||
return {
|
||
...practice,
|
||
parents: parents.length > 0 ? parents : null,
|
||
};
|
||
}
|
||
```
|
||
|
||
On API failure, restore previous `practice` snapshot. On 404, treat as success and refetch.
|
||
|
||
### Keep full editor in sync
|
||
|
||
If the practice question editor loads via `GET .../full`, updating `practice.parents` in shell state after unlink is enough — **no** `PUT .../full` call is needed.
|
||
|
||
---
|
||
|
||
## Error handling
|
||
|
||
| HTTP | `message` (typical) | Cause | Admin UI action |
|
||
|------|---------------------|-------|-----------------|
|
||
| **400** | `Invalid practice id` | Bad `:id` path segment | Fix routing |
|
||
| **400** | `Invalid parent id` | Bad `:parentId` path segment | Fix routing |
|
||
| **400** | `Invalid parent kind` | Unsupported `parentKind` | Show dev error; check URL builder |
|
||
| **401** | Unauthorized | Missing/expired token | Redirect to login |
|
||
| **403** | Forbidden | Missing `practices.update` | Hide unlink control |
|
||
| **404** | `Practice not found` | Practice deleted elsewhere | Navigate away |
|
||
| **404** | `Practice is not linked to that parent` | Stale chip / double click | Refetch practice; remove chip silently |
|
||
| **500** | `Failed to unlink practice parent` | Server error | Toast + retry |
|
||
|
||
### Example error mapper
|
||
|
||
```typescript
|
||
export function mapUnlinkError(err: PracticeParentUnlinkError): string {
|
||
switch (err.status) {
|
||
case 403:
|
||
return "You don't have permission to change practice locations.";
|
||
case 404:
|
||
return err.body?.message?.includes("not linked")
|
||
? "This location was already removed."
|
||
: "Practice not found.";
|
||
case 400:
|
||
return err.body?.message || "Invalid location.";
|
||
default:
|
||
return err.message || "Could not remove location.";
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Testing checklist
|
||
|
||
### LMS
|
||
|
||
- [ ] Practice with two parents → DELETE one → `GET /practices/:id` shows only remaining parent
|
||
- [ ] DELETE last parent → `parents` is `null`; `GET /practices?unlinked_only=true` includes practice
|
||
- [ ] `GET /courses/:id/practices` no longer lists practice after course unlink
|
||
- [ ] Invalid kind `DELETE .../parents/UNIT/1` → 400
|
||
- [ ] DELETE same parent twice → second call 404
|
||
- [ ] User without `practices.update` → 403
|
||
|
||
### Exam-prep
|
||
|
||
- [ ] `DELETE .../parents/CATALOG_COURSE/:id` works with underscore kind in path
|
||
- [ ] `DELETE .../parents/LESSON/:id` removes lesson link only
|
||
- [ ] No module parent kind in UI (unlink lesson under module, not module row)
|
||
- [ ] Activity log shows practice updated after unlink
|
||
|
||
### UI
|
||
|
||
- [ ] Confirm dialog copy distinguishes unlink vs delete practice
|
||
- [ ] Chips update without full page reload
|
||
- [ ] Lesson detail page removes card after contextual unlink
|
||
- [ ] Unlinked state shows re-attach entry point
|
||
|
||
---
|
||
|
||
## Integration checklist
|
||
|
||
- [ ] Add **Remove** (×) on each location chip in LMS practice settings
|
||
- [ ] Add **Remove** on each location chip in exam-prep practice settings
|
||
- [ ] Wire `DELETE /practices/:id/parents/:parentKind/:parentId` (LMS)
|
||
- [ ] Wire `DELETE /exam-prep/practices/:id/parents/:parentKind/:parentId` (exam-prep)
|
||
- [ ] Use uppercase `parent_kind` in URL path (`CATALOG_COURSE`, not `catalog-course`)
|
||
- [ ] On success, set local state from `response.data.parents` (handle `null`)
|
||
- [ ] Handle 404 “not linked” as stale UI refresh
|
||
- [ ] Contextual **Remove from this lesson/course/unit** on hierarchy detail pages
|
||
- [ ] Keep **Add location** on `PUT .../parents` (or create flow)
|
||
- [ ] Keep **Detach everywhere** as `PUT .../parents` with `[]` or multi-DELETE
|
||
- [ ] Do not confuse with `DELETE .../practices/:id`
|
||
- [ ] Permission-gate unlink buttons on `practices.update` / `exam_prep.practices.update`
|
||
|
||
---
|
||
|
||
## Limitations
|
||
|
||
| Topic | Detail |
|
||
|-------|--------|
|
||
| Exam-prep modules | No `MODULE` parent kind — unlink at lesson, unit, or catalog course level |
|
||
| Bulk remove N parents | N DELETE calls vs one `PUT` with `[]`; prefer PUT for “detach all” |
|
||
| Re-link after unlink | Use `PUT .../parents` with expanded array; 409 if target entity already has another practice |
|
||
| Learner progress | Unlinking does not delete completion records; confirm product expectation separately |
|
||
| `PUT .../full` | Still does not accept `parents` — unlink is only via DELETE or `PUT .../parents` |
|
||
| Swagger | Regenerate OpenAPI docs if your pipeline requires handler annotations in the spec |
|
||
|
||
---
|
||
|
||
## Quick reference
|
||
|
||
### LMS
|
||
|
||
```http
|
||
DELETE /api/v1/practices/:id/parents/:parentKind/:parentId
|
||
```
|
||
|
||
| `parentKind` | Entity |
|
||
|--------------|--------|
|
||
| `COURSE` | `courses.id` |
|
||
| `MODULE` | `modules.id` |
|
||
| `LESSON` | `lessons.id` |
|
||
|
||
Permission: `practices.update`
|
||
|
||
### Exam-prep
|
||
|
||
```http
|
||
DELETE /api/v1/exam-prep/practices/:id/parents/:parentKind/:parentId
|
||
```
|
||
|
||
| `parentKind` | Entity |
|
||
|--------------|--------|
|
||
| `CATALOG_COURSE` | `exam_prep.catalog_courses.id` |
|
||
| `UNIT` | `exam_prep.units.id` |
|
||
| `LESSON` | `exam_prep.unit_module_lessons.id` |
|
||
|
||
Permission: `exam_prep.practices.update`
|
||
|
||
### Related endpoints (unchanged)
|
||
|
||
| Action | LMS | Exam-prep |
|
||
|--------|-----|-----------|
|
||
| Replace all parents | `PUT /api/v1/practices/:id/parents` | `PUT /api/v1/exam-prep/practices/:id/parents` |
|
||
| Detach all | `PUT` with `{ "parents": [] }` | same |
|
||
| Delete practice | `DELETE /api/v1/practices/:id` | `DELETE /api/v1/exam-prep/practices/:id` |
|
||
| List unlinked | `GET /api/v1/practices?unlinked_only=true` | `GET /api/v1/exam-prep/practices?unlinked_only=true` |
|