From f3fa551be41104890266a40ad31b40c45322dda2 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sun, 14 Jun 2026 03:46:22 -0700 Subject: [PATCH] feat: add PUT /team/me self-service profile update and admin docs Let team members update their own profile without admin routes, seed team.profile.update_mine RBAC, and add FAQ/personas/ratings admin integration guides. Co-authored-by: Cursor --- .../000085_team_profile_update_mine.down.sql | 15 + .../000085_team_profile_update_mine.up.sql | 14 + docs/faq-admin-panel-integration.md | 155 ++- docs/personas-admin-panel-integration.md | 930 ++++++++++++++++++ docs/ratings-admin-panel-integration.md | 768 +++++++++++++++ internal/domain/team.go | 15 + internal/services/rbac/seeds.go | 9 +- internal/services/team/team.go | 24 + internal/web_server/handlers/team_handler.go | 68 ++ internal/web_server/routes.go | 1 + 10 files changed, 1979 insertions(+), 20 deletions(-) create mode 100644 db/migrations/000085_team_profile_update_mine.down.sql create mode 100644 db/migrations/000085_team_profile_update_mine.up.sql create mode 100644 docs/personas-admin-panel-integration.md create mode 100644 docs/ratings-admin-panel-integration.md diff --git a/db/migrations/000085_team_profile_update_mine.down.sql b/db/migrations/000085_team_profile_update_mine.down.sql new file mode 100644 index 00000000..bfd453a8 --- /dev/null +++ b/db/migrations/000085_team_profile_update_mine.down.sql @@ -0,0 +1,15 @@ +DELETE FROM role_permissions rp +USING roles r, permissions p +WHERE rp.role_id = r.id + AND rp.permission_id = p.id + AND r.name IN ('INSTRUCTOR', 'SUPPORT') + AND p.key IN ('team.profile.get_mine', 'team.profile.update_mine', 'team.members.change_password'); + +DELETE FROM role_permissions rp +USING roles r, permissions p +WHERE rp.role_id = r.id + AND rp.permission_id = p.id + AND r.name = 'ADMIN' + AND p.key = 'team.profile.update_mine'; + +DELETE FROM permissions WHERE key = 'team.profile.update_mine'; diff --git a/db/migrations/000085_team_profile_update_mine.up.sql b/db/migrations/000085_team_profile_update_mine.up.sql new file mode 100644 index 00000000..81e78ec8 --- /dev/null +++ b/db/migrations/000085_team_profile_update_mine.up.sql @@ -0,0 +1,14 @@ +INSERT INTO permissions (key, name, description, group_name) VALUES + ('team.profile.update_mine', 'Update My Team Profile', 'Update own team profile', 'Team') +ON CONFLICT (key) DO UPDATE SET + name = EXCLUDED.name, + description = EXCLUDED.description, + group_name = EXCLUDED.group_name; + +INSERT INTO role_permissions (role_id, permission_id) +SELECT r.id, p.id +FROM roles r +CROSS JOIN permissions p +WHERE r.name IN ('ADMIN', 'INSTRUCTOR', 'SUPPORT') + AND p.key IN ('team.profile.get_mine', 'team.profile.update_mine', 'team.members.change_password') +ON CONFLICT DO NOTHING; diff --git a/docs/faq-admin-panel-integration.md b/docs/faq-admin-panel-integration.md index 9affcc29..41c11db6 100644 --- a/docs/faq-admin-panel-integration.md +++ b/docs/faq-admin-panel-integration.md @@ -9,18 +9,19 @@ This guide documents how to integrate the **FAQ management** feature into the Yi 1. [Feature overview](#feature-overview) 2. [Architecture](#architecture) 3. [Authentication & permissions](#authentication--permissions) -4. [Data model](#data-model) -5. [Response envelopes](#response-envelopes) -6. [Admin API reference](#admin-api-reference) -7. [Public API reference (preview only)](#public-api-reference-preview-only) -8. [Publish workflow (ACTIVE / INACTIVE)](#publish-workflow-active--inactive) -9. [Categories & display order](#categories--display-order) -10. [Recommended admin UI screens](#recommended-admin-ui-screens) -11. [TypeScript types & API client](#typescript-types--api-client) -12. [Error handling](#error-handling) -13. [Integration checklist](#integration-checklist) -14. [Limitations & future work](#limitations--future-work) -15. [Quick reference](#quick-reference) +4. [RBAC setup & troubleshooting 403](#rbac-setup--troubleshooting-403) +5. [Data model](#data-model) +6. [Response envelopes](#response-envelopes) +7. [Admin API reference](#admin-api-reference) +8. [Public API reference (preview only)](#public-api-reference-preview-only) +9. [Publish workflow (ACTIVE / INACTIVE)](#publish-workflow-active--inactive) +10. [Categories & display order](#categories--display-order) +11. [Recommended admin UI screens](#recommended-admin-ui-screens) +12. [TypeScript types & API client](#typescript-types--api-client) +13. [Error handling](#error-handling) +14. [Integration checklist](#integration-checklist) +15. [Limitations & future work](#limitations--future-work) +16. [Quick reference](#quick-reference) --- @@ -68,7 +69,9 @@ flowchart LR PublicRoutes --> FAQsTable ``` -- **Migration:** `000059_faqs` +- **Migrations:** + - `000059_faqs` — `faqs` table + - `000084_faq_rbac_permissions` — `faqs.*` permission keys + role assignments for `ADMIN` and `INSTRUCTOR` - **Postman collection:** `postman/FAQ-Management.postman_collection.json` --- @@ -78,10 +81,19 @@ flowchart LR All admin FAQ endpoints require: ```http -Authorization: Bearer +Authorization: Bearer Content-Type: application/json ``` +### How to obtain a token + +| Login flow | Endpoint | Typical use | +|------------|----------|-------------| +| **Team member (recommended for admin panel)** | `POST /api/v1/team/login` | Staff accounts in `team_members` | +| **Platform admin user** | `POST /api/v1/auth/admin-login` | Users with `users.role` = `ADMIN` or `SUPER_ADMIN` | + +Use the **`access_token`** from the login response on every admin FAQ request. Do not use a learner (`STUDENT` / `OPEN_LEARNER`) token. + ### RBAC permission keys | Action | Permission | HTTP | @@ -92,11 +104,113 @@ Content-Type: application/json | Update FAQ | `faqs.update` | `PUT /admin/faqs/:id` | | Delete FAQ | `faqs.delete` | `DELETE /admin/faqs/:id` | -These permissions are included in the default **ADMIN** role bundle after RBAC seeding. +### Default roles with FAQ access + +After RBAC seeding (startup or sync), these **system roles** include all `faqs.*` permissions by default: + +| RBAC role | FAQ admin access | +|-----------|------------------| +| `ADMIN` | Full access (also bypasses permission checks in middleware) | +| `SUPER_ADMIN` | Full access (bypass) | +| `INSTRUCTOR` | Full access via assigned `faqs.*` permissions | + +Roles such as `STUDENT`, `OPEN_LEARNER`, and `SUPPORT` do **not** receive FAQ admin permissions by default. + +Custom roles created in the RBAC UI must be assigned `faqs.list`, `faqs.get`, etc. explicitly. + +### Team role → JWT `Role` mapping + +Team login embeds a platform **`Role`** in the JWT (decode at [jwt.io](https://jwt.io) and check the `Role` claim). This is what the API uses for RBAC—not the display label in the admin UI. + +| `team_role` (team_members) | JWT `Role` | FAQ admin | +|----------------------------|------------|-----------| +| `SUPER_ADMIN` | `SUPER_ADMIN` | Allowed (bypass) | +| `ADMIN` | `ADMIN` | Allowed (bypass) | +| `CONTENT_MANAGER` | `ADMIN` | Allowed (bypass) | +| `FINANCE`, `HR`, `ANALYST` | `ADMIN` | Allowed (bypass) | +| `INSTRUCTOR` | `INSTRUCTOR` | Allowed if `faqs.*` seeded (default after `000084`) | +| `SUPPORT_AGENT` | `SUPPORT` | **Denied** unless permissions added manually | ### UI gating -Hide or disable FAQ menu items / buttons when the logged-in team member lacks the corresponding permission. A `403` from the API means missing permission. +Hide or disable FAQ menu items / buttons when the logged-in user lacks the corresponding permission. A `403` with message `"You don't have permission to access this resource"` means the JWT role does not have the required permission key (see [RBAC setup & troubleshooting 403](#rbac-setup--troubleshooting-403)). + +--- + +## RBAC setup & troubleshooting 403 + +If `GET /api/v1/admin/faqs` returns **403 Forbidden**, work through the steps below. + +### 1. Confirm the JWT role + +Decode the Bearer token and inspect **`Role`**: + +```json +{ "UserId": 42, "Role": "ADMIN", ... } +``` + +- `ADMIN` / `SUPER_ADMIN` → should always succeed on current backend builds. +- `INSTRUCTOR` → succeeds after migration `000084` (or RBAC sync) assigns `faqs.*`. +- `SUPPORT`, `STUDENT`, etc. → expected 403 for FAQ admin routes. + +**Fix:** Log in with a team account whose `team_role` maps to `ADMIN` or `INSTRUCTOR`, or assign `faqs.*` to the user’s RBAC role. + +### 2. Apply migrations + +Ensure both FAQ migrations have run on the target database: + +```bash +# however your deploy runs migrations, e.g.: +migrate -path db/migrations -database "$DATABASE_URL" up +``` + +Required versions: + +- `000059` — FAQ table +- `000084` — inserts `faqs.*` permissions and links them to `ADMIN` and `INSTRUCTOR` + +### 3. Sync RBAC permissions (no full redeploy) + +If the API is already running but FAQ permissions were added after deploy, call: + +```http +POST /api/v1/rbac/permissions/sync +Authorization: Bearer +``` + +This endpoint: + +1. Upserts all permission definitions from code (including `faqs.*`) +2. Adds any **missing** default role-permission links (does not remove existing ones) +3. Reloads the in-memory RBAC cache + +Then **re-login** to obtain a fresh access token. + +### 4. Restart the API (alternative) + +On startup the server runs `SeedPermissions`, `SeedDefaultRolePermissions`, and reloads the RBAC cache. A restart after deploying FAQ code achieves the same result as step 3 for permission definitions and default role links. + +### 5. Assign permissions to custom roles + +For non-system roles, use the RBAC admin UI or API: + +```http +GET /api/v1/rbac/permissions +GET /api/v1/rbac/roles/{id}/permissions +PUT /api/v1/rbac/roles/{id}/permissions +``` + +Include permission IDs for: `faqs.list`, `faqs.get`, `faqs.create`, `faqs.update`, `faqs.delete`. + +### Common mistakes + +| Mistake | Symptom | +|---------|---------| +| Using learner token | 403 on all admin routes | +| Old access token after RBAC sync | 403 until re-login | +| Migration `000084` not applied | `INSTRUCTOR` gets 403; permissions missing in DB | +| `SUPPORT_AGENT` team account | 403 unless `faqs.*` granted to `SUPPORT` role | +| Calling API before deploy/restart | 404 or 403 depending on environment | --- @@ -694,7 +808,7 @@ const { data, isLoading, error } = useQuery({ |------|-------------------|-----------------| | `400` | Validation failed / Failed to create FAQ | Show field errors from `error` | | `401` | Unauthorized | Redirect to login | -| `403` | Forbidden | Show “No permission” | +| `403` | Forbidden — `You don't have permission to access this resource` | Show “No permission”; verify JWT `Role`, migrations `000084`, and [RBAC sync](#rbac-setup--troubleshooting-403) | | `404` | FAQ not found | Toast + redirect to list | | `500` | Failed to list/get FAQ | Generic error + retry | @@ -707,8 +821,11 @@ Always parse `error` field when present for detail. ### Backend / access - [ ] Migration `000059_faqs` applied -- [ ] RBAC seeded; admin role has `faqs.*` permissions -- [ ] Team member can obtain Bearer token for admin API +- [ ] Migration `000084_faq_rbac_permissions` applied +- [ ] RBAC seeded (`faqs.*` on `ADMIN` and `INSTRUCTOR`; or custom role configured) +- [ ] Team member or platform admin can obtain Bearer token (`POST /team/login` or `POST /auth/admin-login`) +- [ ] JWT `Role` is `ADMIN`, `SUPER_ADMIN`, or `INSTRUCTOR` (or another role with `faqs.list`) +- [ ] If permissions were added after deploy: `POST /rbac/permissions/sync` run and user re-logged in ### Admin panel — navigation diff --git a/docs/personas-admin-panel-integration.md b/docs/personas-admin-panel-integration.md new file mode 100644 index 00000000..23a47ad3 --- /dev/null +++ b/docs/personas-admin-panel-integration.md @@ -0,0 +1,930 @@ +# LMS Personas — Admin Panel Integration Guide + +This guide documents how to integrate the **LMS persona catalog** into the Yimaru admin panel. Personas are coach/character profiles (name, description, avatar, gender) stored centrally and linked to **practice shells** in Learn English (LMS) and exam-prep via `persona_id`. + +> **Naming note:** This feature is **`/api/v1/personas`** (catalog rows in `lms_personas`). It is **not** the same as **question-set user personas** (`/question-sets/:id/personas`), which assign real users to a question set for role-play scenarios. Both are covered below; the admin **Personas** menu usually means the catalog. + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [Architecture](#architecture) +3. [Authentication & permissions](#authentication--permissions) +4. [RBAC setup & troubleshooting 403](#rbac-setup--troubleshooting-403) +5. [Data model](#data-model) +6. [Response envelopes](#response-envelopes) +7. [Persona catalog API reference](#persona-catalog-api-reference) +8. [Linking personas to practices](#linking-personas-to-practices) +9. [Recommended admin UI screens](#recommended-admin-ui-screens) +10. [TypeScript types & API client](#typescript-types--api-client) +11. [Question-set user personas (separate feature)](#question-set-user-personas-separate-feature) +12. [Error handling](#error-handling) +13. [Integration checklist](#integration-checklist) +14. [Limitations & future work](#limitations--future-work) +15. [Quick reference](#quick-reference) + +--- + +## Feature overview + +| Capability | Admin panel | Learner app | +|------------|-------------|-------------| +| Create / edit / delete catalog personas | Yes — `/personas` CRUD | No | +| List personas (picker / management) | Yes | Uses practice payload (`persona_id` resolved server-side) | +| Assign persona to practice | Yes — `persona_id` on practice create/update | Sees persona in practice content | +| Upload profile image via persona API | **No** — URL string only | Displays `profile_picture` URL | +| Deactivate persona (hide from pickers) | Yes — `is_active: false` | Inactive personas excluded when `active_only=true` | + +### Default seeded personas (migration `000063`) + +After migration, three catalog rows are inserted with stable IDs: + +| ID | Name | Description | +|----|------|-------------| +| `1` | Friendly Coach | Warm, encouraging tutor for everyday conversational practice. | +| `2` | Exam Coach | Structured, exam-style guidance and clear checkpoints. | +| `3` | Story Narrator | Story-led scenarios with character-driven prompts. | + +Use `GET /personas?active_only=false` to verify seeds in a new environment. + +--- + +## Architecture + +```mermaid +flowchart LR + subgraph AdminPanel["Admin panel"] + PersonaList[Persona list / CRUD] + PersonaForm[Create / edit form] + PracticeEditor[Practice editor persona picker] + end + + subgraph API["Yimaru API"] + PersonaRoutes["/api/v1/personas CRUD"] + LmsPractice["/api/v1/practices*"] + EpPractice["/api/v1/exam-prep/practices*"] + end + + subgraph DB["PostgreSQL"] + PersonasTable["lms_personas"] + LmsPractices["lms_practices.persona_id"] + EpPractices["exam_prep.lesson_practices.persona_id"] + end + + PersonaList --> PersonaRoutes + PersonaForm --> PersonaRoutes + PracticeEditor --> PersonaRoutes + PracticeEditor --> LmsPractice + PracticeEditor --> EpPractice + PersonaRoutes --> PersonasTable + LmsPractice --> LmsPractices + EpPractice --> EpPractices + LmsPractices --> PersonasTable + EpPractices --> PersonasTable +``` + +- **Migrations:** + - `000063_lms_personas` — table, seeds, FK on `lms_practices` and `exam_prep.lesson_practices` (`ON DELETE SET NULL`) + - `000064_lms_personas_profile_picture` — renames `avatar_url` → `profile_picture` + - `000065_lms_personas_gender` — adds `gender` column +- **Postman:** `postman/LMS-Personas.postman_collection.json` +- **Handlers:** `internal/web_server/handlers/lms_persona_handler.go` +- **Service:** `internal/services/personas/service.go` + +Routes live at **`/api/v1/personas`** (not under `/admin/`). Staff authenticate with team or platform admin tokens. + +--- + +## Authentication & permissions + +All persona catalog endpoints require: + +```http +Authorization: Bearer +Content-Type: application/json +``` + +### How to obtain a token + +| Login flow | Endpoint | Typical use | +|------------|----------|-------------| +| **Team member (recommended)** | `POST /api/v1/team/login` | Admin panel staff | +| **Platform admin** | `POST /api/v1/auth/admin-login` | `users.role` = `ADMIN` / `SUPER_ADMIN` | + +### RBAC permission keys (catalog) + +| Action | Permission | HTTP | +|--------|------------|------| +| List personas | `personas.list` | `GET /personas` | +| Get one persona | `personas.get` | `GET /personas/:id` | +| Create persona | `personas.create` | `POST /personas` | +| Update persona | `personas.update` | `PUT /personas/:id` | +| Delete persona | `personas.delete` | `DELETE /personas/:id` | + +### Default role access + +| Role | Catalog CRUD | +|------|----------------| +| `ADMIN` | Full (middleware bypass) | +| `SUPER_ADMIN` | Full (bypass) | +| `INSTRUCTOR` | Full (`personas.*` in seeds) | +| `SUPPORT` | **Read only** (`personas.list`, `personas.get`) | +| `STUDENT` / `OPEN_LEARNER` | No persona admin permissions by default | + +### UI gating + +- Show **Personas** menu when user has `personas.list` (or is `ADMIN` / `SUPER_ADMIN`). +- Hide create/edit/delete for roles with list/get only. +- Practice editor persona dropdown: call `GET /personas?active_only=true` (requires `personas.list`). + +--- + +## RBAC setup & troubleshooting 403 + +If persona endpoints return **403 Forbidden**: + +1. **Decode JWT `Role`** — confirm staff role (`ADMIN`, `INSTRUCTOR`, etc.). +2. **Apply migrations** — `SELECT to_regclass('public.lms_personas');` must not be `NULL`. +3. **Sync RBAC:** + ```http + POST /api/v1/rbac/permissions/sync + Authorization: Bearer + ``` +4. **Re-login** after sync. +5. For custom roles, assign `personas.list`, `personas.create`, etc. via RBAC UI. + +--- + +## Data model + +### Persona object (`data` in responses) + +```json +{ + "id": 1, + "name": "Friendly Coach", + "description": "Warm, encouraging tutor for everyday conversational practice.", + "profile_picture": null, + "gender": null, + "is_active": true, + "created_at": "2026-04-01T10:00:00Z", + "updated_at": null +} +``` + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `id` | int64 | — | Primary key | +| `name` | string | Yes (create) | Display name; trimmed; cannot be empty on create/update | +| `description` | string \| null | No | Longer bio / coaching style text | +| `profile_picture` | string \| null | No | **Image URL** (HTTPS or MinIO public URL). Key always present in JSON (`null` when unset) | +| `gender` | string \| null | No | Free-text label (e.g. `female`, `male`). Key always present (`null` when unset) | +| `is_active` | boolean | No | Default `true` on create. Inactive personas hidden when listing with `active_only=true` | +| `created_at` | string (time) | — | Server timestamp | +| `updated_at` | string \| null | — | Set on first update | + +### Create body (`CreateLmsPersonaInput`) + +```json +{ + "name": "Business Mentor", + "description": "Formal tone for workplace English.", + "profile_picture": "https://cdn.example.com/personas/business-mentor.png", + "gender": "neutral", + "is_active": true +} +``` + +| Field | Validation | +|-------|------------| +| `name` | Required, non-empty after trim | +| `description` | Optional | +| `profile_picture` | Optional URL string | +| `gender` | Optional; whitespace-only omitted on create | +| `is_active` | Optional; defaults to `true` | + +### Update body (`UpdateLmsPersonaInput`) + +All fields optional — **partial update**. Only sent fields change. + +```json +{ + "name": "Business Mentor (Updated)", + "is_active": false +} +``` + +| Behavior | Detail | +|----------|--------| +| Clear `gender` | Send `"gender": ""` (stored as empty string) | +| Clear `description` / `profile_picture` | Send `""` for that field | +| Omit field | Unchanged | + +### List payload (`data` for `GET /personas`) + +```json +{ + "personas": [ /* persona objects */ ], + "total_count": 3, + "limit": 20, + "offset": 0 +} +``` + +Sort order: **`name ASC`, then `created_at DESC`**. + +--- + +## Response envelopes + +### Success (`domain.Response`) + +```json +{ + "message": "Persona created successfully", + "data": { }, + "success": true, + "status_code": 201 +} +``` + +Rely on **HTTP status code** as source of truth. + +### Error (`domain.ErrorResponse`) + +```json +{ + "message": "Validation failed", + "error": "name is required" +} +``` + +--- + +## Persona catalog API reference + +Base path: `{API_BASE_URL}/api/v1` + +### 1. List personas + +``` +GET /personas +Permission: personas.list +``` + +#### Query parameters + +| Param | Default | Description | +|-------|---------|-------------| +| `active_only` | `true` | Pass `false` to include inactive personas. Any value other than literal `false` keeps active-only filter | +| `limit` | `20` | Page size (max **200** server-side) | +| `offset` | `0` | Pagination offset | + +#### Example — admin management table (all personas) + +```http +GET /api/v1/personas?active_only=false&limit=50&offset=0 +Authorization: Bearer +``` + +#### Example — practice editor dropdown (active only) + +```http +GET /api/v1/personas?active_only=true&limit=200&offset=0 +Authorization: Bearer +``` + +#### Response `200` + +```json +{ + "message": "Personas retrieved successfully", + "data": { + "personas": [ + { + "id": 1, + "name": "Friendly Coach", + "description": "Warm, encouraging tutor...", + "profile_picture": null, + "gender": null, + "is_active": true, + "created_at": "2026-04-01T10:00:00.000000 +0000 UTC", + "updated_at": null + } + ], + "total_count": 3, + "limit": 50, + "offset": 0 + }, + "success": true, + "status_code": 200 +} +``` + +--- + +### 2. Get persona by ID + +``` +GET /personas/:id +Permission: personas.get +``` + +#### Example + +```http +GET /api/v1/personas/1 +Authorization: Bearer +``` + +#### Response `200` + +Returns single persona in `data`. + +#### Errors + +| HTTP | When | +|------|------| +| `400` | Invalid ID | +| `404` | Persona not found | +| `403` | Missing permission | + +--- + +### 3. Create persona + +``` +POST /personas +Permission: personas.create +``` + +#### Example + +```http +POST /api/v1/personas +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Postman Coach", + "description": "Smoke-test persona from admin panel", + "profile_picture": "https://cdn.example.com/personas/postman-coach.png", + "gender": "female", + "is_active": true +} +``` + +#### Response `201` + +```json +{ + "message": "Persona created successfully", + "data": { + "id": 4, + "name": "Postman Coach", + "description": "Smoke-test persona from admin panel", + "profile_picture": "https://cdn.example.com/personas/postman-coach.png", + "gender": "female", + "is_active": true, + "created_at": "...", + "updated_at": null + }, + "success": true, + "status_code": 201 +} +``` + +#### Errors + +| HTTP | When | +|------|------| +| `400` | Validation failed / empty name | +| `403` | Missing `personas.create` | + +--- + +### 4. Update persona + +``` +PUT /personas/:id +Permission: personas.update +``` + +Partial update — include only fields to change. + +#### Example — deactivate + +```http +PUT /api/v1/personas/4 +Authorization: Bearer +Content-Type: application/json + +{ + "is_active": false +} +``` + +#### Response `200` + +```json +{ + "message": "Persona updated successfully", + "data": { /* updated persona */ } +} +``` + +#### Errors + +| HTTP | When | +|------|------| +| `400` | Empty `name` on update | +| `404` | Persona not found | + +--- + +### 5. Delete persona + +``` +DELETE /personas/:id +Permission: personas.delete +``` + +Hard delete from `lms_personas`. + +#### Database side effect + +Foreign keys on practices use **`ON DELETE SET NULL`**: + +- `lms_practices.persona_id` → cleared when persona deleted +- `exam_prep.lesson_practices.persona_id` → cleared when persona deleted + +Learner-facing practices remain; they simply lose the assigned coach until re-linked. + +#### Example + +```http +DELETE /api/v1/personas/4 +Authorization: Bearer +``` + +#### Response `200` + +```json +{ + "message": "Persona deleted successfully", + "success": true, + "status_code": 200 +} +``` + +**Note:** Delete currently returns **200 even if the ID does not exist** (no row-affected check). Prefer confirming ID via `GET` first, or refresh the list after delete. + +Show a confirmation dialog in the admin UI — deletion affects any practices that referenced this persona. + +--- + +## Linking personas to practices + +Personas are **not embedded** in practice JSON. Practices store **`persona_id`** (FK to `lms_personas.id`). + +### LMS (Learn English) practices + +When creating or updating an LMS practice, set `persona_id`: + +```http +PUT /api/v1/practices/:id +Authorization: Bearer +Content-Type: application/json + +{ + "persona_id": 1 +} +``` + +Or on create: + +```http +POST /api/v1/practices +Content-Type: application/json + +{ + "parent_kind": "LESSON", + "parent_id": 42, + "question_set_id": 10, + "persona_id": 2, + "title": "Speaking practice" +} +``` + +Clear assignment: send `"persona_id": null` or omit on update depending on your practice update API semantics (check practice handler — `persona_id` uses COALESCE on update). + +**Validation:** If `persona_id` is set to a non-existent catalog ID, practice create/update returns an error (`persona not found`). + +### Exam-prep practices + +Same field on exam-prep practice endpoints: + +```http +PUT /api/v1/exam-prep/practices/:id +Content-Type: application/json + +{ + "persona_id": 2 +} +``` + +Permissions: `exam_prep.practices.create` / `exam_prep.practices.update` (not `personas.*` alone). + +### Admin UI pattern — persona picker + +1. On practice create/edit screen load: + ```http + GET /api/v1/personas?active_only=true&limit=200&offset=0 + ``` +2. Render `