RezinaLMS-BackEnd/docs/practice-multi-parent-admin-panel-integration.md
2026-10-19 17:59:34 +03:00

26 KiB
Raw Blame History

Practice Multi-Parent Links — Admin Panel Integration Guide

This guide documents how to update the Rezina admin panel practice creation and editing flow for multi-parent LMS practices. A single practice can now be linked to multiple courses, modules, lessons, or any combination of those hierarchy nodes.

Scope: LMS (/api/v1/practices) only. Exam-prep practices are unchanged — they still attach to exactly one unit_module_lesson_id.

Related:


Table of contents

  1. Feature overview
  2. Breaking changes for the admin panel
  3. Concepts: parents, kinds, and constraints
  4. Architecture
  5. Prerequisites (backend)
  6. Authentication & permissions
  7. Data model
  8. Response envelopes
  9. Create practice
  10. Update practice parents
  11. Update practice shell (metadata only)
  12. Full practice load/save (questions)
  13. List & read endpoints
  14. Recommended admin UI changes
  15. Form state & serialization
  16. Client-side validation
  17. TypeScript types & helpers
  18. React integration patterns
  19. Error handling
  20. Integration checklist
  21. Limitations
  22. Quick reference

Feature overview

Capability Before After
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
Exam-prep parent model Single lesson Unchanged

What problem this solves

Content teams often reuse the same practice shell (story, persona, question set) in more than one place — for example:

  • The same capstone practice linked to Module A and Module B
  • A shared review practice attached to Lesson 3 and directly to Course 1
  • One question set surfaced from both a lesson and a module entry point

Previously the admin had to duplicate practices (and question sets) to achieve this. Now one practice ID can be parented by multiple hierarchy nodes.


Breaking changes for the admin panel

Update any code that reads or writes practice parent fields.

Removed from Practice responses

Old field Replacement
parent_kind parents[].parent_kind
parent_id parents[].parent_id

Create request — preferred shape

{
  "parents": [
    { "parent_kind": "LESSON", "parent_id": 42 },
    { "parent_kind": "COURSE", "parent_id": 7 }
  ],
  "question_set_id": 100
}

Create request — legacy (still supported)

If parents is omitted, the API accepts the old single-parent fields:

{
  "parent_kind": "LESSON",
  "parent_id": 42,
  "question_set_id": 100
}

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 — 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

PracticeParent

Field Type Values
parent_kind string COURSE | MODULE | LESSON
parent_id number ID of the course, module, or lesson row

Rules

  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.
  5. Mixed kinds are allowed — e.g. one COURSE parent and two LESSON parents on the same practice.
  6. List endpoints filter by direct parent kind — GET /courses/:id/practices returns practices with a COURSE parent equal to :id, not practices that only appear in the course via a lesson parent.

Visual diagram

flowchart TB
    subgraph PracticeP["Practice #55 (one question set)"]
        QS[Question set + questions]
    end

    L12["Lesson 12"]
    L18["Lesson 18"]
    C7["Course 7"]

    L12 -->|parent_kind LESSON| PracticeP
    L18 -->|parent_kind LESSON| PracticeP
    C7 -->|parent_kind COURSE| PracticeP

Architecture

flowchart TB
    subgraph AdminPanel["Admin panel"]
        CreateForm[Practice create form]
        ParentPicker[Multi-parent picker]
        ShellEdit[Practice settings tab]
        QuestionEditor[Question editor]
    end

    subgraph API["Rezina API"]
        PostPractice["POST /practices"]
        PutParents["PUT /practices/:id/parents"]
        GetFull["GET /practices/:id/full"]
        PutFull["PUT /practices/:id/full"]
    end

    subgraph DB["PostgreSQL"]
        LP["lms_practices"]
        LPP["lms_practice_parents"]
    end

    CreateForm --> ParentPicker
    ParentPicker --> PostPractice
    ShellEdit --> PutParents
    QuestionEditor --> PutFull
    GetFull --> QuestionEditor
    PostPractice --> LP
    PostPractice --> LPP
    PutParents --> LPP
  • Migration: 000089_lms_practice_parents — junction table; migrates legacy columns; drops course_id / module_id / lesson_id from lms_practices.
  • Domain: internal/domain/practice.go — PracticeParent, parents[] on Practice.
  • Service: internal/services/practices/service.go — validates parents, enforces per-entity uniqueness.
  • Repository: internal/repository/lms_practices.go — transactional create + parent inserts; replace parents on update.

Prerequisites (backend)

Before testing from the admin panel:

  1. Run database migrations (includes 000089):

    docker compose up migrate
    
  2. Redeploy or restart the API on a build that includes multi-parent support.

  3. Confirm the junction table exists:

    \d lms_practice_parents
    
  4. Confirm legacy columns are gone from lms_practices:

    \d lms_practices
    -- should NOT list course_id, module_id, lesson_id
    

Authentication & permissions

Use a team member or platform admin token:

Authorization: Bearer <access_token>
Content-Type: application/json

LMS practice shell (parents + metadata)

Action Permission HTTP
Create practice practices.create POST /api/v1/practices
Get practice shell practices.get GET /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

Practice content (questions)

Action Permission HTTP
Load practice + questions practices.get GET /api/v1/practices/:id/full
Save practice + questions practices.update PUT /api/v1/practices/:id/full

Parent links use PUT /api/v1/practices/:id/parents only — not PUT .../full or PUT /practices/:id.


Data model

Practice (response)

When no parents are linked, parents is JSON null (not []).

{
  "id": 55,
  "parents": [
    { "parent_kind": "LESSON", "parent_id": 12 },
    { "parent_kind": "LESSON", "parent_id": 18 },
    { "parent_kind": "COURSE", "parent_id": 7 }
  ],
  "title": "Module capstone",
  "story_description": "…",
  "story_image": "https://…",
  "persona_id": 3,
  "question_set_id": 100,
  "publish_status": "PUBLISHED",
  "quick_tips": "…",
  "created_at": "2026-06-18T10:00:00Z",
  "updated_at": "2026-06-18T11:00:00Z"
}

access is included for learner roles only; admin tokens typically receive access: null.

CreatePracticeInput

Field Required Notes
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
title No Defaults to empty string
story_description No
story_image No
persona_id No Must exist in lms_personas when set
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

Shell metadata only — does not include parents.

Field Notes
title, story_description, … Same as before
publish_status DRAFT / PUBLISHED

Response envelopes

Success (create / get / update shell)

{
  "success": true,
  "status_code": 201,
  "message": "Practice created successfully",
  "data": { /* Practice */ }
}

Success (list)

{
  "success": true,
  "status_code": 200,
  "message": "Practices retrieved successfully",
  "data": {
    "practices": [ /* Practice[] — each includes parents */ ],
    "total_count": 1,
    "limit": 20,
    "offset": 0
  }
}

Error

{
  "message": "This course, module, or lesson already has a practice",
  "error": "this course, module, or lesson already has a practice"
}

Create practice

POST /api/v1/practices
Authorization: Bearer <token>
Content-Type: application/json
{
  "parents": null,
  "question_set_id": 100,
  "title": "Draft practice shell",
  "publish_status": "DRAFT"
}

Equivalent: omit parents entirely.

Example — multiple parents

{
  "parents": [
    { "parent_kind": "MODULE", "parent_id": 9 },
    { "parent_kind": "LESSON", "parent_id": 42 }
  ],
  "title": "Shared review",
  "question_set_id": 100,
  "publish_status": "DRAFT"
}

Example — launched from a lesson page (legacy-compatible)

When the user clicks “Add practice” on Lesson 42, pre-fill one parent but allow adding more before submit:

{
  "parents": [
    { "parent_kind": "LESSON", "parent_id": 42 }
  ],
  "question_set_id": 100
}

Equivalent legacy body (still works):

{
  "parent_kind": "LESSON",
  "parent_id": 42,
  "question_set_id": 100
}

Typical admin create flow

sequenceDiagram
    participant UI as Admin UI
    participant API as API

    UI->>API: POST /question-sets (optional — create empty practice set first)
    API-->>UI: 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 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 parents

PUT /api/v1/practices/:id/parents
Authorization: Bearer <token>
Content-Type: application/json
{
  "parents": [
    { "parent_kind": "COURSE", "parent_id": 7 },
    { "parent_kind": "LESSON", "parent_id": 42 }
  ]
}

Detach from all hierarchy nodes

{
  "parents": []
}

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)

PUT /api/v1/practices/:id

Omit parents — use the dedicated /parents route above.

{
  "title": "Updated title",
  "publish_status": "PUBLISHED"
}

Full practice load/save (questions)

Parent links appear in the practice object returned by full load, but cannot be changed via full save.

GET /api/v1/practices/:id/full
PUT /api/v1/practices/:id/full

GET response shape (abbreviated)

{
  "data": {
    "practice": {
      "id": 55,
      "parents": [
        { "parent_kind": "LESSON", "parent_id": 42 }
      ],
      "title": "…",
      "question_set_id": 100
    },
    "question_set": { /* … */ },
    "questions": [ /* … */ ]
  }
}

PUT — shell section (no parents)

{
  "practice": {
    "title": "New title",
    "publish_status": "PUBLISHED"
  },
  "question_set": { "status": "PUBLISHED" },
  "questions": [ /* … */ ]
}

To edit where the practice appears in the hierarchy, call PUT /api/v1/practices/:id/parents.


List & read endpoints

Each list route returns practices that have a direct parent of the matching kind:

Endpoint Returns practices where…
GET /api/v1/courses/:id/practices parents contains { parent_kind: "COURSE", parent_id: :id }
GET /api/v1/modules/:id/practices parents contains { parent_kind: "MODULE", parent_id: :id }
GET /api/v1/lessons/:id/practices parents contains { parent_kind: "LESSON", parent_id: :id }

Query params: limit (default 20, max 200), offset.

Global lookup by question type

GET /api/v1/questions/type-definitions/:id/practices returns LMS rows with parents (exam-prep rows still use exam_prep_lesson_id).


1. Replace single-parent controls

Old UI New UI
Radio: Course / Module / Lesson + one ID picker Multi-row parent list with kind + searchable entity picker
Read practice.parent_kind Read practice.parents
Disable parent after create Allow edit via Practice settings → Locations (PUT /practices/:id)

2. “Locations” or “Attached to” section

Show all parents as chips with hierarchy context, e.g.:

  • Course: Algebra I
  • Module: Unit 3
  • Lesson: Factoring intro

Actions:

  • Add location — append row; validate entity not already used by another practice
  • Remove location — drop from local list (must keep ≥ 1 parent on save)
  • Save locations — PUT /practices/:id with full parents array

3. Contextual create

When opening create from a lesson/module/course page:

  1. Pre-populate parents with that entity.
  2. Show “Also attach to…” to add more parents before first save.
  3. Still require question_set_id (create set inline or pick existing).

4. Practice picker / duplicate detection

Before adding parent { kind, id }, optionally call the list endpoint for that entity:

GET /api/v1/lessons/42/practices?limit=1

If total_count > 0 and the returned practice id ≠ current practice, warn that the lesson already has a practice.

5. Breadcrumbs & navigation

A practice with multiple parents may appear in several admin navigation paths. Use parents to render all entry points, not a single breadcrumb.


Form state & serialization

Suggested editor state

type PracticeParentKind = "COURSE" | "MODULE" | "LESSON";

interface PracticeParent {
  parent_kind: PracticeParentKind;
  parent_id: number;
}

interface PracticeCreateFormState {
  parents: PracticeParent[];
  question_set_id: number | null;
  title: string;
  publish_status: "DRAFT" | "PUBLISHED";
  // … story, persona, tips
}

interface PracticeShellState extends PracticeCreateFormState {
  id: number;
}

Create payload mapper

function toCreatePracticePayload(state: PracticeCreateFormState) {
  return {
    parents: dedupeParents(state.parents),
    question_set_id: state.question_set_id!,
    title: state.title || undefined,
    publish_status: state.publish_status,
  };
}

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;
  });
}

Normalizing API → form (migration from old clients)

function parentsFromPractice(practice: {
  parents?: PracticeParent[];
  parent_kind?: PracticeParentKind;
  parent_id?: number;
}): PracticeParent[] {
  if (practice.parents?.length) return practice.parents;
  if (practice.parent_kind && practice.parent_id) {
    return [{ parent_kind: practice.parent_kind, parent_id: practice.parent_id }];
  }
  return [];
}

Use this helper during rollout if cached responses might still have the old shape.


Client-side validation

Mirror server rules before submit:

Rule Error message (suggested)
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.”
On parent add: optional occupancy check “This lesson already has another practice.”

Server remains authoritative for entity existence (404) and uniqueness (409).


TypeScript types & helpers

interface ApiResponse<T> {
  success: boolean;
  status_code: number;
  message: string;
  data: T;
}

interface Practice {
  id: number;
  parents: PracticeParent[] | null;
  title: string;
  story_description?: string | null;
  story_image?: string | null;
  persona_id?: number | null;
  question_set_id: number;
  publish_status: "DRAFT" | "PUBLISHED";
  quick_tips?: string | null;
  created_at: string;
  updated_at?: string | null;
}

interface CreatePracticeInput {
  parents?: PracticeParent[] | null;
  parent_kind?: PracticeParentKind;
  parent_id?: number;
  question_set_id: number;
  title?: string;
  story_description?: string;
  story_image?: string;
  persona_id?: number;
  quick_tips?: string;
  publish_status?: "DRAFT" | "PUBLISHED";
}

interface UpdatePracticeParentsInput {
  parents: PracticeParent[];
}

interface UpdatePracticeInput {
  title?: string;
  story_description?: string;
  story_image?: string;
  persona_id?: number;
  question_set_id?: number;
  quick_tips?: string;
  publish_status?: "DRAFT" | "PUBLISHED";
}

React integration patterns

Create practice with multiple parents

async function createPractice(
  payload: CreatePracticeInput,
  token: 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(payload),
  });

  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;
}

Update locations only

async function updatePracticeParents(
  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 || `Update failed (${res.status})`);
  }

  const json: ApiResponse<Practice> = await res.json();
  return json.data;
}

Load full editor (parents read-only in question save)

async function loadPracticeFull(practiceId: number, token: string) {
  const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/full`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error(`Load failed (${res.status})`);
  const json = await res.json();
  return json.data as {
    practice: Practice;
    question_set: unknown;
    questions: unknown[];
  };
}

Keep practice.parents in shell state; persist parent changes with PUT .../parents, not with PUT .../full.


Error handling

HTTP message Typical cause Admin UI action
400 Invalid parent No parents resolved, bad kind, empty list Highlight parent picker
400 Validation failed Malformed body Show field errors
404 Course not found / Module not found / Lesson not found Stale ID in picker Refresh hierarchy data
404 Question set not found Invalid question_set_id Re-link question set
404 Persona not found Invalid persona_id Fix persona selection
409 This course, module, or lesson already has a practice Parent already linked elsewhere Pick a different entity or edit the other practice
403 Permission denied Missing practices.create / practices.update RBAC message

Always surface the API error string when present.


Integration checklist

Data & API

  • Migration 000089 applied in target environments
  • 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
  • List pages still use course/module/lesson scoped list endpoints; expect same practice ID if multi-parented

UI

  • Multi-row parent picker on create
  • “Locations” panel on practice settings with add/remove
  • Contextual pre-fill when creating from hierarchy page
  • Conflict toast on 409 (parent already taken)
  • Breadcrumbs / back-links support multiple parents

QA scenarios

  • Create with one parent (parity with old flow)
  • Create with course + two lessons
  • Update parents: add a module link to existing practice
  • Update parents: remove one link, keep others
  • Attempt to attach lesson that already has another practice → 409
  • List by lesson shows practice when lesson is one of several parents
  • Full save of questions does not clear or alter parents
  • Draft practice with multiple parents; publish via shell update

Limitations

Topic Behavior
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 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.)

Quick reference

Task Method Path Body highlights
Create practice POST /api/v1/practices question_set_id; parents optional/null
Get shell GET /api/v1/practices/:id —
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 —
List on module GET /api/v1/modules/:id/practices —
List on lesson GET /api/v1/lessons/:id/practices —

Minimal create example

curl -s -X POST "$API/api/v1/practices" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "parents": [
      { "parent_kind": "LESSON", "parent_id": 42 },
      { "parent_kind": "MODULE", "parent_id": 9 }
    ],
    "question_set_id": 100,
    "title": "Shared practice",
    "publish_status": "DRAFT"
  }'