RezinaLMS-BackEnd/docs/practice-create-nullable-parents-admin-panel-integration.md
2026-06-18 05:02:13 -07:00

16 KiB

Create Practice with Nullable parents — Admin Panel Guide

This guide explains how the admin panel should create LMS practices when parents is optional. You can create a practice shell first (linked only to a question set), then attach it to courses, modules, and/or lessons later.

Scope: POST /api/v1/practices (Learn English LMS). Exam-prep creation is unchanged.

Related guides:


Table of contents

  1. Summary
  2. When to use nullable parents
  3. End-to-end create flow
  4. Authentication & permissions
  5. Request contract
  6. Create variants
  7. Response contract
  8. Link parents after create
  9. Recommended admin UI
  10. TypeScript types & helpers
  11. React example
  12. Error handling
  13. Integration checklist
  14. Quick reference

Summary

Topic Behavior
Required on create question_set_id only
parents on create Optional — omit, null, or an array
Response when unlinked "parents": null
Response when linked "parents": [{ "parent_kind", "parent_id" }, …]
Link after create PUT /api/v1/practices/:id/parents
Add questions after create PUT /api/v1/practices/:id/full

The nullable parents field supports a two-phase authoring model:

  1. Phase 1 — Shell: create practice + question set reference (no hierarchy links yet).
  2. Phase 2 — Placement: attach to one or more courses/modules/lessons when the author is ready.
  3. Phase 3 — Content: add story metadata and questions via full practice save.

When to use nullable parents

Scenario parents on create Link later
Author builds questions first, picks placement later null / omit Yes
“New practice” from global admin menu (no context) null / omit Yes
“Add practice” from a lesson page [{ LESSON, id }] optional Add more via /parents
Reuse same shell in multiple locations at once Array of parents Rarely needed
Legacy single-parent create parent_kind + parent_id N/A

An unlinked practice (parents: null) is valid for admins but will not appear in course/module/lesson practice lists until parents are set.


End-to-end create flow

sequenceDiagram
    participant UI as Admin panel
    participant API as Yimaru API

    Note over UI,API: Optional — create question set first
    UI->>API: POST /question-sets
    API-->>UI: question_set_id

    Note over UI,API: Phase 1 — practice shell (parents optional)
    UI->>API: POST /practices { question_set_id, parents: null }
    API-->>UI: 201 { id, parents: null, question_set_id }

    Note over UI,API: Phase 2 — attach hierarchy (when ready)
    UI->>API: PUT /practices/:id/parents { parents: [...] }
    API-->>UI: 200 { id, parents: [...] }

    Note over UI,API: Phase 3 — questions & story
    UI->>API: PUT /practices/:id/full { practice, question_set, questions }
    API-->>UI: 200 full practice payload

Minimal steps

  1. Ensure a question set exists (create one or pick existing).
  2. POST /api/v1/practices with question_set_id and parents: null (or omit parents).
  3. Store returned practice.id.
  4. When placement is known, PUT /api/v1/practices/:id/parents.
  5. Open the question editor and PUT /api/v1/practices/:id/full.

Authentication & permissions

Authorization: Bearer <access_token>
Content-Type: application/json
Action Permission Endpoint
Create practice practices.create POST /api/v1/practices
Attach / update parents practices.update PUT /api/v1/practices/:id/parents
Add questions practices.update PUT /api/v1/practices/:id/full

Request contract

POST /api/v1/practices

POST /api/v1/practices
Authorization: Bearer <token>
Content-Type: application/json

Body fields

Field Type Required Notes
question_set_id number Yes Must exist in question_sets
parents array | null No Omit or null = unlinked shell
parent_kind string No Legacy fallback: COURSE | MODULE | LESSON
parent_id number No Legacy fallback; use with parent_kind
title string No
story_description string No
story_image string No URL
persona_id number No lms_personas.id
quick_tips string No
publish_status string No DRAFT or PUBLISHED; default PUBLISHED

parents item shape

Field Type Values
parent_kind string COURSE, MODULE, LESSON
parent_id number ID of that entity

Semantics of parents

Input Meaning
Field omitted Unlinked practice
"parents": null Unlinked practice
"parents": [] Unlinked practice (empty array is deduped to no links)
"parents": [{ … }] Create with one or more links immediately
Legacy parent_kind + parent_id Single link when parents is omitted

Note: If you send both parents and legacy parent_kind/parent_id, parents wins when it is non-null.


Create variants

{
  "parents": null,
  "question_set_id": 100,
  "title": "New practice",
  "publish_status": "DRAFT"
}

Equivalent payloads:

{
  "question_set_id": 100,
  "title": "New practice",
  "publish_status": "DRAFT"
}

2. Create with one parent (from lesson/module/course page)

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

3. Create with multiple parents

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

4. Legacy single-parent (backward compatible)

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

5. Full metadata at create (still unlinked)

{
  "parents": null,
  "question_set_id": 100,
  "title": "Listening drill",
  "story_description": "You arrive at the market…",
  "story_image": "https://cdn.example/story.png",
  "persona_id": 3,
  "quick_tips": "Listen twice before answering.",
  "publish_status": "DRAFT"
}

Response contract

Success — 201 Created

{
  "success": true,
  "status_code": 201,
  "message": "Practice created successfully",
  "data": {
    "id": 55,
    "parents": null,
    "title": "New practice",
    "question_set_id": 100,
    "publish_status": "DRAFT",
    "created_at": "2026-06-18T12:00:00Z"
  }
}

When parents were provided at create:

{
  "data": {
    "id": 56,
    "parents": [
      { "parent_kind": "LESSON", "parent_id": 42 }
    ],
    "question_set_id": 100,
    "publish_status": "DRAFT"
  }
}

Important: parents is JSON null when there are no links — not [].

Error — common cases

HTTP message Cause
400 Validation failed Missing question_set_id
404 Question set not found Invalid question_set_id
404 Course not found / Module not found / Lesson not found Bad parent_id in parents
409 This course, module, or lesson already has a practice Parent entity already linked elsewhere
403 Permission denied Missing practices.create

When the practice was created with parents: null, attach hierarchy nodes with:

PUT /api/v1/practices/:id/parents
Authorization: Bearer <token>
Content-Type: application/json
{
  "parents": [
    { "parent_kind": "LESSON", "parent_id": 42 },
    { "parent_kind": "COURSE", "parent_id": 7 }
  ]
}
  • Replaces all links on each call.
  • Use "parents": [] to detach completely (practice becomes unlinked again).
  • Requires practices.update.

See practice-multi-parent-admin-panel-integration.md for full parent-editing rules and conflict handling.


Create wizard (nullable parents)

flowchart TD
    A[Start: New practice] --> B{Question set?}
    B -->|Create new| C[POST /question-sets]
    B -->|Pick existing| D[Select question_set_id]
    C --> E[POST /practices parents null]
    D --> E
    E --> F{Attach locations now?}
    F -->|No| G[Open question editor]
    F -->|Yes| H[PUT /practices/:id/parents]
    H --> G
    G --> I[PUT /practices/:id/full]

UI rules

  1. Do not require a course/module/lesson picker on the first create step.
  2. Show “Locations (optional)” — collapsed by default when starting from the global menu.
  3. When opened from a lesson page, pre-fill one parent row but allow skip.
  4. After create, if parents === null, show a banner: “Not attached to any course, module, or lesson yet.”
  5. Provide “Attach to…” action → calls PUT /practices/:id/parents.
  6. Disable “Publish to learners” messaging until at least one parent is set (optional product rule).

What not to do

  • Do not send parents on PUT /practices/:id/full — that endpoint ignores parent links.
  • Do not expect the practice to appear in GET /lessons/:id/practices until a LESSON parent exists.

TypeScript types & helpers

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

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

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

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

interface ApiResponse<T> {
  success: boolean;
  status_code: number;
  message: string;
  data: T;
}
/** Build create payload; parents null unless user selected locations. */
function buildCreatePracticePayload(input: {
  questionSetId: number;
  parents?: PracticeParent[] | null;
  title?: string;
  publishStatus?: "DRAFT" | "PUBLISHED";
}): CreatePracticeInput {
  const parents =
    input.parents && input.parents.length > 0 ? dedupeParents(input.parents) : null;

  return {
    question_set_id: input.questionSetId,
    parents,
    title: input.title,
    publish_status: input.publishStatus ?? "DRAFT",
  };
}

function dedupeParents(parents: PracticeParent[]): PracticeParent[] {
  const seen = new Set<string>();
  return parents.filter((p) => {
    if (!p.parent_kind || p.parent_id <= 0) return false;
    const key = `${p.parent_kind}:${p.parent_id}`;
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

function isPracticeUnlinked(practice: Practice): boolean {
  return practice.parents == null || practice.parents.length === 0;
}

React example

const API_BASE = import.meta.env.VITE_API_URL;

async function createUnlinkedPractice(
  questionSetId: number,
  token: string,
  meta?: { title?: string }
): Promise<Practice> {
  const res = await fetch(`${API_BASE}/api/v1/practices`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      parents: null,
      question_set_id: questionSetId,
      title: meta?.title ?? "",
      publish_status: "DRAFT",
    }),
  });

  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.message || body.error || `Create failed (${res.status})`);
  }

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

async function attachPracticeParents(
  practiceId: number,
  parents: PracticeParent[],
  token: string
): Promise<Practice> {
  const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/parents`, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ parents: dedupeParents(parents) }),
  });

  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.message || body.error || `Attach failed (${res.status})`);
  }

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

// Typical flow
async function createPracticeWorkflow(questionSetId: number, token: string) {
  const practice = await createUnlinkedPractice(questionSetId, token, {
    title: "Untitled practice",
  });

  // … author adds questions via PUT /practices/:id/full …

  // … when ready, attach to lesson 42 …
  const linked = await attachPracticeParents(
    practice.id,
    [{ parent_kind: "LESSON", parent_id: 42 }],
    token
  );

  return linked;
}

Error handling

User action API result Suggested UI
Create without question_set_id 400 validation Block submit; highlight question set field
Create with taken lesson parent 409 conflict Toast: “This lesson already has a practice”
Attach invalid module id 404 Refresh hierarchy picker data
Create unlinked, user expects lesson list Practice missing from list Explain “Attach to lesson first”

Always show the API error string when present.


Integration checklist

Create flow

  • POST /practices works with parents omitted or null
  • Only question_set_id is required in the create form
  • Response data.parents handled as null or array
  • Unlinked practices show clear “not attached” state in UI

Post-create

  • PUT /practices/:id/parents wired for “Attach to…” / Locations step
  • PUT /practices/:id/full used for questions (not parents)
  • Lesson/course/module list pages refresh after parents are attached

QA

  • Create parents: null → response parents: null → not in lesson list
  • PUT /parents with lesson → appears in GET /lessons/:id/practices
  • Create with parents at once still works
  • Legacy parent_kind + parent_id still works
  • 409 when attaching to entity that already has another practice

Quick reference

# 1. Create unlinked shell
curl -s -X POST "$API/api/v1/practices" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "parents": null,
    "question_set_id": 100,
    "title": "Draft practice",
    "publish_status": "DRAFT"
  }'

# 2. Attach to lesson 42 (use id from step 1)
curl -s -X PUT "$API/api/v1/practices/55/parents" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "parents": [{ "parent_kind": "LESSON", "parent_id": 42 }]
  }'
Step Method Path parents
Create shell POST /api/v1/practices null / omit / optional array
Attach locations PUT /api/v1/practices/:id/parents required array
Add questions PUT /api/v1/practices/:id/full not used