feat: add per-parent practice unlink endpoints for LMS and exam-prep
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>
This commit is contained in:
parent
dd82a1b27f
commit
218c09c904
|
|
@ -7,6 +7,12 @@ RETURNING *;
|
|||
DELETE FROM exam_prep.practice_parents
|
||||
WHERE practice_id = $1;
|
||||
|
||||
-- name: DeleteExamPrepPracticeParent :execrows
|
||||
DELETE FROM exam_prep.practice_parents
|
||||
WHERE practice_id = $1
|
||||
AND parent_kind = $2
|
||||
AND parent_id = $3;
|
||||
|
||||
-- name: ListExamPrepPracticeParentsByPracticeID :many
|
||||
SELECT *
|
||||
FROM exam_prep.practice_parents
|
||||
|
|
|
|||
|
|
@ -7,6 +7,12 @@ RETURNING *;
|
|||
DELETE FROM lms_practice_parents
|
||||
WHERE practice_id = $1;
|
||||
|
||||
-- name: DeleteLmsPracticeParent :execrows
|
||||
DELETE FROM lms_practice_parents
|
||||
WHERE practice_id = $1
|
||||
AND parent_kind = $2
|
||||
AND parent_id = $3;
|
||||
|
||||
-- name: ListLmsPracticeParentsByPracticeID :many
|
||||
SELECT *
|
||||
FROM lms_practice_parents
|
||||
|
|
|
|||
883
docs/practice-parent-unlink-admin-panel-integration.md
Normal file
883
docs/practice-parent-unlink-admin-panel-integration.md
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
# 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` |
|
||||
|
|
@ -49,6 +49,27 @@ func (q *Queries) CountExamPrepPracticesByParentExcludingPractice(ctx context.Co
|
|||
return column_1, err
|
||||
}
|
||||
|
||||
const DeleteExamPrepPracticeParent = `-- name: DeleteExamPrepPracticeParent :execrows
|
||||
DELETE FROM exam_prep.practice_parents
|
||||
WHERE practice_id = $1
|
||||
AND parent_kind = $2
|
||||
AND parent_id = $3
|
||||
`
|
||||
|
||||
type DeleteExamPrepPracticeParentParams struct {
|
||||
PracticeID int64 `json:"practice_id"`
|
||||
ParentKind string `json:"parent_kind"`
|
||||
ParentID int64 `json:"parent_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteExamPrepPracticeParent(ctx context.Context, arg DeleteExamPrepPracticeParentParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, DeleteExamPrepPracticeParent, arg.PracticeID, arg.ParentKind, arg.ParentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const DeleteExamPrepPracticeParentsByPracticeID = `-- name: DeleteExamPrepPracticeParentsByPracticeID :exec
|
||||
DELETE FROM exam_prep.practice_parents
|
||||
WHERE practice_id = $1
|
||||
|
|
|
|||
|
|
@ -49,6 +49,27 @@ func (q *Queries) CountLmsPracticesByParentExcludingPractice(ctx context.Context
|
|||
return column_1, err
|
||||
}
|
||||
|
||||
const DeleteLmsPracticeParent = `-- name: DeleteLmsPracticeParent :execrows
|
||||
DELETE FROM lms_practice_parents
|
||||
WHERE practice_id = $1
|
||||
AND parent_kind = $2
|
||||
AND parent_id = $3
|
||||
`
|
||||
|
||||
type DeleteLmsPracticeParentParams struct {
|
||||
PracticeID int64 `json:"practice_id"`
|
||||
ParentKind string `json:"parent_kind"`
|
||||
ParentID int64 `json:"parent_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteLmsPracticeParent(ctx context.Context, arg DeleteLmsPracticeParentParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, DeleteLmsPracticeParent, arg.PracticeID, arg.ParentKind, arg.ParentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const DeleteLmsPracticeParentsByPracticeID = `-- name: DeleteLmsPracticeParentsByPracticeID :exec
|
||||
DELETE FROM lms_practice_parents
|
||||
WHERE practice_id = $1
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
package domain
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ExamPrepParentKind identifies which exam-prep hierarchy entity a practice is linked to.
|
||||
type ExamPrepParentKind string
|
||||
|
|
@ -11,6 +14,20 @@ const (
|
|||
ExamPrepParentKindLesson ExamPrepParentKind = "LESSON"
|
||||
)
|
||||
|
||||
// ParseExamPrepParentKind maps API/path input to a supported exam-prep parent kind.
|
||||
func ParseExamPrepParentKind(raw string) (ExamPrepParentKind, bool) {
|
||||
switch strings.TrimSpace(strings.ToUpper(raw)) {
|
||||
case string(ExamPrepParentKindCatalogCourse):
|
||||
return ExamPrepParentKindCatalogCourse, true
|
||||
case string(ExamPrepParentKindUnit):
|
||||
return ExamPrepParentKindUnit, true
|
||||
case string(ExamPrepParentKindLesson):
|
||||
return ExamPrepParentKindLesson, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// ExamPrepPracticeParent links a practice to a catalog course, unit, or lesson.
|
||||
type ExamPrepPracticeParent struct {
|
||||
Kind ExamPrepParentKind `json:"parent_kind"`
|
||||
|
|
|
|||
|
|
@ -14,6 +14,20 @@ const (
|
|||
ParentKindLesson ParentKind = "LESSON"
|
||||
)
|
||||
|
||||
// ParsePracticeParentKind maps API/path input to a supported parent kind.
|
||||
func ParsePracticeParentKind(raw string) (ParentKind, bool) {
|
||||
switch strings.TrimSpace(strings.ToUpper(raw)) {
|
||||
case string(ParentKindCourse):
|
||||
return ParentKindCourse, true
|
||||
case string(ParentKindModule):
|
||||
return ParentKindModule, true
|
||||
case string(ParentKindLesson):
|
||||
return ParentKindLesson, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// PracticeParent links a practice to a course, module, or lesson.
|
||||
type PracticeParent struct {
|
||||
Kind ParentKind `json:"parent_kind"`
|
||||
|
|
|
|||
44
internal/domain/practice_parent_kind_test.go
Normal file
44
internal/domain/practice_parent_kind_test.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
package domain
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParsePracticeParentKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
raw string
|
||||
want ParentKind
|
||||
ok bool
|
||||
}{
|
||||
{"COURSE", ParentKindCourse, true},
|
||||
{"course", ParentKindCourse, true},
|
||||
{" MODULE ", ParentKindModule, true},
|
||||
{"LESSON", ParentKindLesson, true},
|
||||
{"UNIT", "", false},
|
||||
{"", "", false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got, ok := ParsePracticeParentKind(tc.raw)
|
||||
if ok != tc.ok || got != tc.want {
|
||||
t.Fatalf("ParsePracticeParentKind(%q) = (%q, %v), want (%q, %v)", tc.raw, got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseExamPrepParentKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
raw string
|
||||
want ExamPrepParentKind
|
||||
ok bool
|
||||
}{
|
||||
{"CATALOG_COURSE", ExamPrepParentKindCatalogCourse, true},
|
||||
{"catalog_course", ExamPrepParentKindCatalogCourse, true},
|
||||
{"UNIT", ExamPrepParentKindUnit, true},
|
||||
{"LESSON", ExamPrepParentKindLesson, true},
|
||||
{"MODULE", "", false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got, ok := ParseExamPrepParentKind(tc.raw)
|
||||
if ok != tc.ok || got != tc.want {
|
||||
t.Fatalf("ParseExamPrepParentKind(%q) = (%q, %v), want (%q, %v)", tc.raw, got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -16,5 +16,6 @@ type ExamPrepPracticeStore interface {
|
|||
CountExamPrepPracticesByParentExcludingPractice(ctx context.Context, kind domain.ExamPrepParentKind, parentID, excludePracticeID int64) (int64, error)
|
||||
UpdateExamPrepLessonPractice(ctx context.Context, id int64, input domain.UpdateExamPrepPracticeInput) (domain.ExamPrepPractice, error)
|
||||
ReplaceExamPrepPracticeParents(ctx context.Context, practiceID int64, parents []domain.ExamPrepPracticeParent) error
|
||||
DeleteExamPrepPracticeParent(ctx context.Context, practiceID int64, parent domain.ExamPrepPracticeParent) (bool, error)
|
||||
DeleteExamPrepLessonPractice(ctx context.Context, id int64) error
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ type LmsPracticeStore interface {
|
|||
ListAllLmsPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.Practice, int64, error)
|
||||
UpdateLmsPractice(ctx context.Context, id int64, input domain.UpdatePracticeInput) (domain.Practice, error)
|
||||
ReplaceLmsPracticeParents(ctx context.Context, practiceID int64, parents []domain.PracticeParent) error
|
||||
DeleteLmsPracticeParent(ctx context.Context, practiceID int64, parent domain.PracticeParent) (bool, error)
|
||||
DeleteLmsPractice(ctx context.Context, id int64) error
|
||||
CountLmsPracticesByParent(ctx context.Context, kind domain.ParentKind, parentID int64) (int64, error)
|
||||
CountLmsPracticesByParentExcludingPractice(ctx context.Context, kind domain.ParentKind, parentID, practiceID int64) (int64, error)
|
||||
|
|
|
|||
|
|
@ -271,6 +271,18 @@ func (s *Store) ReplaceExamPrepPracticeParents(ctx context.Context, practiceID i
|
|||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteExamPrepPracticeParent(ctx context.Context, practiceID int64, parent domain.ExamPrepPracticeParent) (bool, error) {
|
||||
rows, err := s.queries.DeleteExamPrepPracticeParent(ctx, dbgen.DeleteExamPrepPracticeParentParams{
|
||||
PracticeID: practiceID,
|
||||
ParentKind: string(parent.Kind),
|
||||
ParentID: parent.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s *Store) CountExamPrepPracticesByParent(ctx context.Context, kind domain.ExamPrepParentKind, parentID int64) (int64, error) {
|
||||
return s.queries.CountExamPrepPracticesByParent(ctx, dbgen.CountExamPrepPracticesByParentParams{
|
||||
ParentKind: string(kind),
|
||||
|
|
|
|||
|
|
@ -380,6 +380,18 @@ func (s *Store) ReplaceLmsPracticeParents(ctx context.Context, practiceID int64,
|
|||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteLmsPracticeParent(ctx context.Context, practiceID int64, parent domain.PracticeParent) (bool, error) {
|
||||
rows, err := s.queries.DeleteLmsPracticeParent(ctx, dbgen.DeleteLmsPracticeParentParams{
|
||||
PracticeID: practiceID,
|
||||
ParentKind: string(parent.Kind),
|
||||
ParentID: parent.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteLmsPractice(ctx context.Context, id int64) error {
|
||||
return s.queries.DeleteLmsPractice(ctx, id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ var ErrLessonNotFound = errors.New("exam prep lesson not found")
|
|||
var ErrPracticeNotFound = errors.New("exam prep practice not found")
|
||||
var ErrQuestionSetNotFound = errors.New("question set not found")
|
||||
var ErrInvalidExamPrepPracticeParent = errors.New("parent_kind and parent_id do not match an allowed exam prep parent")
|
||||
var ErrExamPrepPracticeParentLinkNotFound = errors.New("practice is not linked to that parent")
|
||||
|
||||
// examPrepStore is implemented by *repository.Store (catalog courses, units, modules, lessons, practices, personas).
|
||||
type examPrepStore interface {
|
||||
|
|
@ -535,6 +536,28 @@ func (s *Service) UpdateExamPrepPracticeParents(ctx context.Context, id int64, i
|
|||
return s.store.GetExamPrepLessonPracticeByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) UnlinkExamPrepPracticeParent(ctx context.Context, id int64, parent domain.ExamPrepPracticeParent) (domain.ExamPrepPractice, error) {
|
||||
kind, ok := domain.ParseExamPrepParentKind(string(parent.Kind))
|
||||
if !ok || parent.ID <= 0 {
|
||||
return domain.ExamPrepPractice{}, ErrInvalidExamPrepPracticeParent
|
||||
}
|
||||
parent.Kind = kind
|
||||
if _, err := s.store.GetExamPrepLessonPracticeByID(ctx, id); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ExamPrepPractice{}, ErrPracticeNotFound
|
||||
}
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
deleted, err := s.store.DeleteExamPrepPracticeParent(ctx, id, parent)
|
||||
if err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
if !deleted {
|
||||
return domain.ExamPrepPractice{}, ErrExamPrepPracticeParentLinkNotFound
|
||||
}
|
||||
return s.store.GetExamPrepLessonPracticeByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) GetExamPrepPracticeByID(ctx context.Context, id int64) (domain.ExamPrepPractice, error) {
|
||||
p, err := s.store.GetExamPrepLessonPracticeByID(ctx, id)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ var (
|
|||
ErrQuestionSetNotFound = errors.New("question set not found")
|
||||
ErrInvalidPracticeParent = errors.New("parent_kind and parent_id do not match an allowed parent")
|
||||
ErrPracticeParentLimitExceeded = errors.New("this course, module, or lesson already has a practice")
|
||||
ErrPracticeParentLinkNotFound = errors.New("practice is not linked to that parent")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
|
|
@ -267,6 +268,29 @@ func (s *Service) UpdateParents(ctx context.Context, id int64, in domain.UpdateP
|
|||
return s.practices.GetLmsPracticeByID(ctx, id)
|
||||
}
|
||||
|
||||
// UnlinkParent removes a single course/module/lesson link from a practice.
|
||||
func (s *Service) UnlinkParent(ctx context.Context, id int64, parent domain.PracticeParent) (domain.Practice, error) {
|
||||
kind, ok := domain.ParsePracticeParentKind(string(parent.Kind))
|
||||
if !ok || parent.ID <= 0 {
|
||||
return domain.Practice{}, ErrInvalidPracticeParent
|
||||
}
|
||||
parent.Kind = kind
|
||||
if _, err := s.practices.GetLmsPracticeByID(ctx, id); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Practice{}, ErrPracticeNotFound
|
||||
}
|
||||
return domain.Practice{}, err
|
||||
}
|
||||
deleted, err := s.practices.DeleteLmsPracticeParent(ctx, id, parent)
|
||||
if err != nil {
|
||||
return domain.Practice{}, err
|
||||
}
|
||||
if !deleted {
|
||||
return domain.Practice{}, ErrPracticeParentLinkNotFound
|
||||
}
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -294,6 +294,62 @@ func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
// UnlinkExamPrepPracticeParent godoc
|
||||
// @Summary Unlink one exam-prep practice parent
|
||||
// @Tags exam-prep
|
||||
// @Param id path int true "Exam prep practice ID"
|
||||
// @Param parentKind path string true "Parent kind (CATALOG_COURSE, UNIT, LESSON)"
|
||||
// @Param parentId path int true "Parent entity ID"
|
||||
// @Router /api/v1/exam-prep/practices/{id}/parents/{parentKind}/{parentId} [delete]
|
||||
func (h *Handler) UnlinkExamPrepPracticeParent(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(),
|
||||
})
|
||||
}
|
||||
parentID, err := strconv.ParseInt(c.Params("parentId"), 10, 64)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid parent id",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
kind, ok := domain.ParseExamPrepParentKind(c.Params("parentKind"))
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid parent kind",
|
||||
Error: "parent_kind must be CATALOG_COURSE, UNIT, or LESSON",
|
||||
})
|
||||
}
|
||||
p, err := h.examPrepSvc.UnlinkExamPrepPracticeParent(c.Context(), id, domain.ExamPrepPracticeParent{Kind: kind, ID: parentID})
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, examprep.ErrPracticeNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrExamPrepPracticeParentLinkNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||
Message: "Practice is not linked to that parent",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to unlink practice parent",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Unlinked exam prep practice parent "+string(kind)+": "+p.Title, nil)
|
||||
return c.JSON(domain.Response{
|
||||
Message: "Practice parent unlinked successfully",
|
||||
Data: p,
|
||||
Success: true,
|
||||
StatusCode: fiber.StatusOK,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteExamPrepPractice godoc
|
||||
// @Summary Delete exam-prep practice
|
||||
// @Tags exam-prep
|
||||
|
|
|
|||
|
|
@ -366,6 +366,52 @@ func (h *Handler) UpdatePracticeParents(c *fiber.Ctx) error {
|
|||
return c.JSON(domain.Response{Message: "Practice parents updated successfully", Data: p, Success: true, StatusCode: fiber.StatusOK})
|
||||
}
|
||||
|
||||
// UnlinkPracticeParent godoc
|
||||
// @Tags practices
|
||||
// @Param id path int true "Practice ID"
|
||||
// @Param parentKind path string true "Parent kind (COURSE, MODULE, LESSON)"
|
||||
// @Param parentId path int true "Parent entity ID"
|
||||
// @Router /api/v1/practices/{id}/parents/{parentKind}/{parentId} [delete]
|
||||
func (h *Handler) UnlinkPracticeParent(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()})
|
||||
}
|
||||
parentID, err := strconv.ParseInt(c.Params("parentId"), 10, 64)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent id", Error: err.Error()})
|
||||
}
|
||||
kind, ok := domain.ParsePracticeParentKind(c.Params("parentKind"))
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid parent kind",
|
||||
Error: "parent_kind must be COURSE, MODULE, or LESSON",
|
||||
})
|
||||
}
|
||||
p, err := h.practiceSvc.UnlinkParent(c.Context(), id, domain.PracticeParent{Kind: kind, ID: parentID})
|
||||
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, practices.ErrInvalidPracticeParent):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
|
||||
case errors.Is(err, practices.ErrPracticeParentLinkNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||
Message: "Practice is not linked to that parent",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to unlink practice parent", 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, "Unlinked practice parent "+string(kind)+": "+p.Title, nil, &ip, &ua)
|
||||
return c.JSON(domain.Response{Message: "Practice parent unlinked successfully", Data: p, Success: true, StatusCode: fiber.StatusOK})
|
||||
}
|
||||
|
||||
// DeletePractice godoc
|
||||
// @Tags practices
|
||||
// @Param id path int true "Practice ID"
|
||||
|
|
|
|||
|
|
@ -122,6 +122,7 @@ func (a *App) initAppRoutes() {
|
|||
examPrep.Get("/practices/:id/full", a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull)
|
||||
examPrep.Put("/practices/:id", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice)
|
||||
examPrep.Put("/practices/:id/parents", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents)
|
||||
examPrep.Delete("/practices/:id/parents/:parentKind/:parentId", a.RequirePermission("exam_prep.practices.update"), h.UnlinkExamPrepPracticeParent)
|
||||
examPrep.Put("/practices/:id/full", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull)
|
||||
examPrep.Delete("/practices/:id", a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice)
|
||||
examPrep.Get("/lessons/:id", a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID)
|
||||
|
|
@ -171,6 +172,7 @@ func (a *App) initAppRoutes() {
|
|||
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.Delete("/practices/:id/parents/:parentKind/:parentId", a.authMiddleware, a.RequirePermission("practices.update"), h.UnlinkPracticeParent)
|
||||
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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user