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 <cursoragent@cursor.com>
This commit is contained in:
parent
10babe06f6
commit
f3fa551be4
15
db/migrations/000085_team_profile_update_mine.down.sql
Normal file
15
db/migrations/000085_team_profile_update_mine.down.sql
Normal file
|
|
@ -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';
|
||||
14
db/migrations/000085_team_profile_update_mine.up.sql
Normal file
14
db/migrations/000085_team_profile_update_mine.up.sql
Normal file
|
|
@ -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;
|
||||
|
|
@ -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 <team_member_access_token>
|
||||
Authorization: Bearer <access_token>
|
||||
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 <admin_or_super_admin_token>
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
|
|
|
|||
930
docs/personas-admin-panel-integration.md
Normal file
930
docs/personas-admin-panel-integration.md
Normal file
|
|
@ -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 <access_token>
|
||||
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 <admin_token>
|
||||
```
|
||||
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 <team_access_token>
|
||||
```
|
||||
|
||||
#### Example — practice editor dropdown (active only)
|
||||
|
||||
```http
|
||||
GET /api/v1/personas?active_only=true&limit=200&offset=0
|
||||
Authorization: Bearer <team_access_token>
|
||||
```
|
||||
|
||||
#### 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 <team_access_token>
|
||||
```
|
||||
|
||||
#### 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 <team_access_token>
|
||||
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 <team_access_token>
|
||||
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 <team_access_token>
|
||||
```
|
||||
|
||||
#### 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 <token>
|
||||
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 `<select>` or searchable list: `{ id, name, profile_picture }`.
|
||||
3. Save selected `id` as `persona_id` on practice save.
|
||||
4. Optional: show persona preview card using `GET /personas/:id`.
|
||||
|
||||
### Profile picture upload workflow
|
||||
|
||||
The persona API accepts a **URL string only**. Typical admin flow:
|
||||
|
||||
1. Upload image via your existing asset pipeline (MinIO / media upload used elsewhere in admin).
|
||||
2. Paste resulting public URL into `profile_picture` on create/update.
|
||||
|
||||
There is **no** `multipart/form-data` upload on `POST /personas`.
|
||||
|
||||
---
|
||||
|
||||
## Recommended admin UI screens
|
||||
|
||||
### 1. Persona catalog list
|
||||
|
||||
**Route:** `/admin/personas`
|
||||
|
||||
| Column | Source |
|
||||
|--------|--------|
|
||||
| Avatar | `profile_picture` thumbnail or placeholder |
|
||||
| Name | `name` |
|
||||
| Gender | `gender` or "—" |
|
||||
| Status | Badge: Active / Inactive (`is_active`) |
|
||||
| Updated | `updated_at` |
|
||||
| Actions | Edit, Delete |
|
||||
|
||||
**Filters:**
|
||||
|
||||
- Toggle "Show inactive" → `active_only=false`
|
||||
- Pagination via `limit` / `offset` and `total_count`
|
||||
|
||||
**Actions:**
|
||||
|
||||
- **New persona** → create form → `POST /personas`
|
||||
- **Edit** → `GET /personas/:id` + `PUT /personas/:id`
|
||||
- **Deactivate** → `PUT` with `is_active: false` (prefer over delete if practices still reference it)
|
||||
- **Delete** → confirm modal → `DELETE /personas/:id`
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ Personas [+ New persona] │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ [ ] Show inactive │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ Avatar │ Name │ Gender │ Status │ Actions │
|
||||
│ (img) │ Friendly Coach │ — │ Active │ Edit · Delete │
|
||||
│ (img) │ Exam Coach │ — │ Active │ Edit · Delete │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ ← Prev Page 1 of 1 Next → │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 2. Create / edit persona form
|
||||
|
||||
| Field | Input type | API field |
|
||||
|-------|------------|-----------|
|
||||
| Name | Text (required) | `name` |
|
||||
| Description | Textarea | `description` |
|
||||
| Profile picture | URL input + image preview (optional file upload elsewhere) | `profile_picture` |
|
||||
| Gender | Text or select | `gender` |
|
||||
| Active | Toggle | `is_active` |
|
||||
|
||||
Validate non-empty name client-side before submit.
|
||||
|
||||
### 3. Practice editor integration
|
||||
|
||||
Add **Coach / Persona** dropdown to LMS and exam-prep practice forms:
|
||||
|
||||
- Load options from `GET /personas?active_only=true`
|
||||
- Display persona name + thumbnail in dropdown
|
||||
- Persist `persona_id` on practice save
|
||||
- Show warning if selected persona is later deactivated (still linked until admin changes practice)
|
||||
|
||||
---
|
||||
|
||||
## TypeScript types & API client
|
||||
|
||||
### Types
|
||||
|
||||
```typescript
|
||||
export interface LmsPersona {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
profile_picture: string | null;
|
||||
gender: string | null;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface PersonaListData {
|
||||
personas: LmsPersona[];
|
||||
total_count: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface CreatePersonaInput {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
profile_picture?: string | null;
|
||||
gender?: string | null;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdatePersonaInput {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
profile_picture?: string | null;
|
||||
gender?: string | null;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
message: string;
|
||||
data: T;
|
||||
success?: boolean;
|
||||
status_code?: number;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
error?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Example client (fetch)
|
||||
|
||||
```typescript
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
function authHeaders(token: string): HeadersInit {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
export async function listPersonas(
|
||||
token: string,
|
||||
options: { activeOnly?: boolean; limit?: number; offset?: number } = {}
|
||||
): Promise<PersonaListData> {
|
||||
const qs = new URLSearchParams({
|
||||
active_only: String(options.activeOnly !== false),
|
||||
limit: String(options.limit ?? 20),
|
||||
offset: String(options.offset ?? 0),
|
||||
});
|
||||
const res = await fetch(`${API_BASE}/api/v1/personas?${qs}`, {
|
||||
headers: authHeaders(token),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<PersonaListData> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
export async function getPersona(token: string, id: number): Promise<LmsPersona> {
|
||||
const res = await fetch(`${API_BASE}/api/v1/personas/${id}`, {
|
||||
headers: authHeaders(token),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<LmsPersona> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
export async function createPersona(
|
||||
token: string,
|
||||
input: CreatePersonaInput
|
||||
): Promise<LmsPersona> {
|
||||
const res = await fetch(`${API_BASE}/api/v1/personas`, {
|
||||
method: "POST",
|
||||
headers: authHeaders(token),
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<LmsPersona> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
export async function updatePersona(
|
||||
token: string,
|
||||
id: number,
|
||||
input: UpdatePersonaInput
|
||||
): Promise<LmsPersona> {
|
||||
const res = await fetch(`${API_BASE}/api/v1/personas/${id}`, {
|
||||
method: "PUT",
|
||||
headers: authHeaders(token),
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<LmsPersona> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
export async function deletePersona(token: string, id: number): Promise<void> {
|
||||
const res = await fetch(`${API_BASE}/api/v1/personas/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: authHeaders(token),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
}
|
||||
|
||||
/** Options for practice editor dropdown */
|
||||
export async function listActivePersonasForPicker(token: string): Promise<LmsPersona[]> {
|
||||
const data = await listPersonas(token, { activeOnly: true, limit: 200, offset: 0 });
|
||||
return data.personas;
|
||||
}
|
||||
```
|
||||
|
||||
### React Query example
|
||||
|
||||
```typescript
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
export function usePersonas(page: number, includeInactive: boolean, token: string) {
|
||||
const limit = 20;
|
||||
return useQuery({
|
||||
queryKey: ["personas", page, includeInactive],
|
||||
queryFn: () =>
|
||||
listPersonas(token, {
|
||||
activeOnly: !includeInactive,
|
||||
limit,
|
||||
offset: page * limit,
|
||||
}),
|
||||
enabled: !!token,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreatePersona(token: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (input: CreatePersonaInput) => createPersona(token, input),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["personas"] }),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Question-set user personas (separate feature)
|
||||
|
||||
Some speaking / role-play question sets assign **platform users** as dialogue characters. This uses a different table (`question_set_personas`) and routes under **question sets**, not the LMS persona catalog.
|
||||
|
||||
| Action | Permission | HTTP |
|
||||
|--------|------------|------|
|
||||
| List user personas on set | `question_set_personas.list` | `GET /question-sets/:setId/personas` |
|
||||
| Add user to set | `question_set_personas.add` | `POST /question-sets/:setId/personas` |
|
||||
| Remove user from set | `question_set_personas.remove` | `DELETE /question-sets/:setId/personas/:userId` |
|
||||
|
||||
#### Add body
|
||||
|
||||
```json
|
||||
{
|
||||
"user_id": 1001,
|
||||
"display_order": 1
|
||||
}
|
||||
```
|
||||
|
||||
Response rows include user profile fields (name, email, etc.) for display in question-set authoring UI.
|
||||
|
||||
**Do not confuse:**
|
||||
|
||||
| Concept | Table / API | Purpose |
|
||||
|---------|-------------|---------|
|
||||
| **LMS persona catalog** | `lms_personas`, `/personas` | Fictional coach/character profile on practice shell |
|
||||
| **Question-set user persona** | `question_set_personas`, `/question-sets/:id/personas` | Real user cast for a specific question set |
|
||||
|
||||
The admin **Personas** menu item typically manages the **catalog** only. Question-set persona assignment belongs on the **question set / practice content** authoring screen.
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
| HTTP | Typical cause | Admin UI action |
|
||||
|------|---------------|-----------------|
|
||||
| `400` | Invalid ID, validation (`name` required / empty) | Show field errors from `error` |
|
||||
| `401` | Missing/expired token | Redirect to login |
|
||||
| `403` | Missing RBAC permission | "No permission" message |
|
||||
| `404` | Persona not found (`GET` / `PUT`) | Toast + redirect to list |
|
||||
| `500` | Server error | Generic error + retry |
|
||||
|
||||
### Practice save with invalid `persona_id`
|
||||
|
||||
When linking a practice to a deleted or invalid persona ID, the practice API may return **400/404** with `persona not found`. Refresh the persona picker and re-select.
|
||||
|
||||
### Empty list
|
||||
|
||||
| Scenario | UI |
|
||||
|----------|-----|
|
||||
| Seeds missing (migration not run) | Error state + DevOps note |
|
||||
| All inactive with `active_only=true` | "No active personas" + link to show inactive |
|
||||
| New environment | Prompt to create first persona |
|
||||
|
||||
---
|
||||
|
||||
## Integration checklist
|
||||
|
||||
### Backend / access
|
||||
|
||||
- [ ] Migrations `000063`–`000065` applied
|
||||
- [ ] Default personas visible (`GET /personas?active_only=false`)
|
||||
- [ ] Staff token with `personas.list` (+ create/update/delete as needed)
|
||||
- [ ] RBAC sync run if permissions missing
|
||||
|
||||
### Persona catalog screens
|
||||
|
||||
- [ ] List with pagination (`total_count`, `limit`, `offset`)
|
||||
- [ ] "Show inactive" filter (`active_only=false`)
|
||||
- [ ] Create form → `POST /personas`
|
||||
- [ ] Edit form → `GET /personas/:id` + `PUT /personas/:id`
|
||||
- [ ] Delete with confirmation → `DELETE /personas/:id`
|
||||
- [ ] Deactivate via `is_active: false` documented for content team
|
||||
|
||||
### Practice integration
|
||||
|
||||
- [ ] Persona dropdown on LMS practice create/edit
|
||||
- [ ] Persona dropdown on exam-prep practice create/edit
|
||||
- [ ] `persona_id` saved on practice payload
|
||||
- [ ] Profile picture URL workflow documented for content authors
|
||||
|
||||
### QA scenarios
|
||||
|
||||
- [ ] Create persona → appears in list and practice picker
|
||||
- [ ] Deactivate persona → hidden from `active_only=true` picker
|
||||
- [ ] Delete persona → practices lose `persona_id` but remain editable
|
||||
- [ ] Assign persona to practice → learner practice shows coach (client-dependent)
|
||||
- [ ] `INSTRUCTOR` can CRUD; `SUPPORT` read-only
|
||||
- [ ] Invalid `persona_id` on practice rejected with clear error
|
||||
|
||||
---
|
||||
|
||||
## Limitations & future work
|
||||
|
||||
| Topic | Current behavior |
|
||||
|-------|------------------|
|
||||
| No `/admin/personas` prefix | Use `/api/v1/personas` |
|
||||
| No image upload on persona API | URL string only |
|
||||
| Delete idempotency | `DELETE` returns 200 even if ID missing |
|
||||
| No soft delete | Hard delete; use `is_active: false` to retire |
|
||||
| No usage count API | Cannot show "used by N practices" without custom queries |
|
||||
| No reorder API | List sorted by name |
|
||||
| Gender free text | No enum validation |
|
||||
| Question-set personas | Separate API; not merged into catalog UI |
|
||||
| Legacy `question_sets.persona` text field | Old string column on question sets — distinct from `persona_id` on practices |
|
||||
|
||||
### Suggested future endpoints
|
||||
|
||||
- `GET /admin/personas` with usage counts
|
||||
- `POST /personas/:id/profile-picture` multipart upload
|
||||
- Soft delete / archive flag with restore
|
||||
- `GET /personas/:id/practices` — reverse lookup
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Method | Path | Permission | Purpose |
|
||||
|--------|------|------------|---------|
|
||||
| `GET` | `/api/v1/personas` | `personas.list` | List catalog (paginated) |
|
||||
| `GET` | `/api/v1/personas/:id` | `personas.get` | Get one |
|
||||
| `POST` | `/api/v1/personas` | `personas.create` | Create |
|
||||
| `PUT` | `/api/v1/personas/:id` | `personas.update` | Update |
|
||||
| `DELETE` | `/api/v1/personas/:id` | `personas.delete` | Delete (practices SET NULL) |
|
||||
|
||||
### Practice assignment (LMS)
|
||||
|
||||
| Method | Path | Field |
|
||||
|--------|------|-------|
|
||||
| `POST` / `PUT` | `/api/v1/practices*` | `persona_id` |
|
||||
|
||||
### Practice assignment (exam-prep)
|
||||
|
||||
| Method | Path | Field |
|
||||
|--------|------|-------|
|
||||
| `POST` / `PUT` | `/api/v1/exam-prep/practices*` | `persona_id` |
|
||||
|
||||
### List for picker
|
||||
|
||||
```http
|
||||
GET /api/v1/personas?active_only=true&limit=200&offset=0
|
||||
Authorization: Bearer <team_access_token>
|
||||
```
|
||||
768
docs/ratings-admin-panel-integration.md
Normal file
768
docs/ratings-admin-panel-integration.md
Normal file
|
|
@ -0,0 +1,768 @@
|
|||
# Ratings & App Reviews — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **ratings and app reviews** into the Yimaru admin panel. Learners submit star ratings and optional text reviews from the mobile/web app; the admin panel **monitors and analyzes** that feedback.
|
||||
|
||||
> **Important:** There are **no** dedicated `/api/v1/admin/ratings*` routes today. Admin features use the shared authenticated **`/api/v1/ratings*`** endpoints with staff RBAC permissions. Submission and deletion are **learner-scoped** (own rating only).
|
||||
|
||||
---
|
||||
|
||||
## 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. [Target types](#target-types)
|
||||
7. [Response envelopes](#response-envelopes)
|
||||
8. [Admin API reference](#admin-api-reference)
|
||||
9. [Enriching ratings with user profiles](#enriching-ratings-with-user-profiles)
|
||||
10. [Pagination & dashboard patterns](#pagination--dashboard-patterns)
|
||||
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)
|
||||
|
||||
---
|
||||
|
||||
## Feature overview
|
||||
|
||||
The ratings system stores **1–5 star ratings** with an optional **text review** per user per target.
|
||||
|
||||
| Capability | Admin panel | Mobile / learner app |
|
||||
|------------|-------------|----------------------|
|
||||
| Submit / update rating | No (learner only) | Yes — `POST /ratings` |
|
||||
| Delete rating | No (own rating only) | Yes — `DELETE /ratings/:id` |
|
||||
| List reviews for a target | Yes — `GET /ratings` | Yes (same endpoint) |
|
||||
| Average stars & count | Yes — `GET /ratings/summary` | Yes |
|
||||
| Moderate / hide reviews | **Not supported** | — |
|
||||
| Admin-only delete | **Not supported** | — |
|
||||
|
||||
### Primary admin use case: **App reviews**
|
||||
|
||||
For the admin “App reviews” or “Feedback” screen, use:
|
||||
|
||||
- `target_type=app`
|
||||
- `target_id=0` (ignored by API; always stored as `0` for app ratings)
|
||||
|
||||
### Secondary use cases (legacy)
|
||||
|
||||
The API also supports ratings for **`course`** and **`sub_course`** targets (legacy content model). Admin panels can add tabs or filters per target type if product still surfaces those IDs.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph LearnerApp["Learner app"]
|
||||
Submit[POST /ratings]
|
||||
MyRating[GET /ratings/me]
|
||||
end
|
||||
|
||||
subgraph AdminPanel["Admin panel"]
|
||||
Dashboard[Summary KPIs]
|
||||
ReviewList[Review list table]
|
||||
UserLink[User profile lookup]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
RatingsRoutes["/api/v1/ratings*"]
|
||||
UserRoutes["/api/v1/user/single/:id"]
|
||||
end
|
||||
|
||||
subgraph DB["PostgreSQL"]
|
||||
RatingsTable["ratings table"]
|
||||
UsersTable["users table"]
|
||||
end
|
||||
|
||||
Submit --> RatingsRoutes
|
||||
MyRating --> RatingsRoutes
|
||||
Dashboard --> RatingsRoutes
|
||||
ReviewList --> RatingsRoutes
|
||||
UserLink --> UserRoutes
|
||||
RatingsRoutes --> RatingsTable
|
||||
UserRoutes --> UsersTable
|
||||
```
|
||||
|
||||
- **Migration:** `000017_ratings` — creates `ratings` table and indexes
|
||||
- **Handlers:** `internal/web_server/handlers/ratings.go`
|
||||
- **Service:** `internal/services/ratings/service.go`
|
||||
- **Swagger:** `/api/v1/ratings*` under tag `ratings`
|
||||
|
||||
There is **no** separate admin handler, service, or Postman collection for ratings at this time.
|
||||
|
||||
---
|
||||
|
||||
## Authentication & permissions
|
||||
|
||||
All rating endpoints require authentication:
|
||||
|
||||
```http
|
||||
Authorization: Bearer <access_token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### How to obtain a token (admin panel)
|
||||
|
||||
| Login flow | Endpoint | Use |
|
||||
|------------|----------|-----|
|
||||
| **Team member (recommended)** | `POST /api/v1/team/login` | Staff accounts in `team_members` |
|
||||
| **Platform admin** | `POST /api/v1/auth/admin-login` | Users with `users.role` = `ADMIN` / `SUPER_ADMIN` |
|
||||
|
||||
Use the **`access_token`** from the login response. Learner tokens work for read endpoints if the learner role has permissions, but the admin panel should use **staff tokens**.
|
||||
|
||||
### RBAC permission keys
|
||||
|
||||
| Action | Permission | HTTP | Admin panel |
|
||||
|--------|------------|------|-------------|
|
||||
| List ratings for target | `ratings.list_by_target` | `GET /ratings` | **Primary** — review table |
|
||||
| Rating summary (KPIs) | `ratings.summary` | `GET /ratings/summary` | **Primary** — dashboard header |
|
||||
| Submit rating | `ratings.submit` | `POST /ratings` | Not used in admin UI |
|
||||
| Get my rating | `ratings.get_mine` | `GET /ratings/me` | Not used in admin UI |
|
||||
| List my ratings | `ratings.list_mine` | `GET /ratings/me/all` | Not used in admin UI |
|
||||
| Delete rating | `ratings.delete` | `DELETE /ratings/:id` | **Not for admin** — deletes caller’s own row only |
|
||||
|
||||
### Default role access
|
||||
|
||||
| Role | List & summary | Submit | Delete others’ reviews |
|
||||
|------|----------------|--------|-------------------------|
|
||||
| `ADMIN` | Yes (bypass) | Yes | No |
|
||||
| `SUPER_ADMIN` | Yes (bypass) | Yes | No |
|
||||
| `INSTRUCTOR` | Yes | Yes | No |
|
||||
| `STUDENT` / `OPEN_LEARNER` | Yes | Yes | No |
|
||||
| `SUPPORT` | Yes (read only) | No | No |
|
||||
|
||||
`ADMIN` and `SUPER_ADMIN` always pass RBAC checks in middleware regardless of explicit permission rows.
|
||||
|
||||
### UI gating
|
||||
|
||||
- Show **App reviews** menu when the user has `ratings.list_by_target` (or role is `ADMIN` / `SUPER_ADMIN`).
|
||||
- Hide “Submit review” actions in admin — those belong in the learner app.
|
||||
- Do **not** show “Delete review” in admin unless backend adds an admin delete endpoint.
|
||||
|
||||
---
|
||||
|
||||
## RBAC setup & troubleshooting 403
|
||||
|
||||
If rating endpoints return **403 Forbidden**:
|
||||
|
||||
### 1. Check JWT `Role`
|
||||
|
||||
Decode the Bearer token. Staff roles (`ADMIN`, `SUPER_ADMIN`, `INSTRUCTOR`, `SUPPORT`) should have list/summary access per the table above.
|
||||
|
||||
### 2. Ensure migration `000017` is applied
|
||||
|
||||
```sql
|
||||
SELECT to_regclass('public.ratings');
|
||||
```
|
||||
|
||||
If `NULL`, run database migrations.
|
||||
|
||||
### 3. Sync RBAC permissions
|
||||
|
||||
```http
|
||||
POST /api/v1/rbac/permissions/sync
|
||||
Authorization: Bearer <admin_or_super_admin_token>
|
||||
```
|
||||
|
||||
Then re-login for a fresh token.
|
||||
|
||||
### 4. Grant permissions to custom roles
|
||||
|
||||
Use RBAC APIs to assign at minimum:
|
||||
|
||||
- `ratings.list_by_target`
|
||||
- `ratings.summary`
|
||||
|
||||
---
|
||||
|
||||
## Data model
|
||||
|
||||
### Rating object (`data` in responses)
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 42,
|
||||
"user_id": 1001,
|
||||
"target_type": "app",
|
||||
"target_id": 0,
|
||||
"stars": 5,
|
||||
"review": "Excellent app, very helpful lessons!",
|
||||
"created_at": "2026-05-01 10:30:00.123456 +0000 UTC",
|
||||
"updated_at": "2026-05-01 10:30:00.123456 +0000 UTC"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | int64 | Primary key |
|
||||
| `user_id` | int64 | Learner who submitted the rating (`users.id`) |
|
||||
| `target_type` | string | `app`, `course`, or `sub_course` |
|
||||
| `target_id` | int64 | `0` for app; course/sub_course ID otherwise |
|
||||
| `stars` | int16 | 1–5 inclusive |
|
||||
| `review` | string \| null | Optional free-text review |
|
||||
| `created_at` | string | First submission time |
|
||||
| `updated_at` | string | Last update time (upsert updates this) |
|
||||
|
||||
### Database constraints
|
||||
|
||||
- **One rating per user per target:** `UNIQUE (user_id, target_type, target_id)`
|
||||
- **Stars range:** `CHECK (stars >= 1 AND stars <= 5)`
|
||||
- **Review:** nullable `TEXT` — no max length enforced in DB (consider client-side limits)
|
||||
|
||||
### Summary object (`data` for `/ratings/summary`)
|
||||
|
||||
```json
|
||||
{
|
||||
"total_count": 128,
|
||||
"average_stars": 4.35
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_count` | int64 | Number of ratings for the target |
|
||||
| `average_stars` | float64 | Arithmetic mean of `stars` (0 if no ratings) |
|
||||
|
||||
---
|
||||
|
||||
## Target types
|
||||
|
||||
| `target_type` | `target_id` | Meaning | Admin panel |
|
||||
|---------------|-------------|---------|-------------|
|
||||
| `app` | `0` (always) | Overall app rating/review | **Default tab** |
|
||||
| `course` | LMS course ID | Legacy course rating | Optional filter |
|
||||
| `sub_course` | Sub-course ID | Legacy sub-course rating | Optional filter |
|
||||
|
||||
For **app** ratings, always pass `target_id=0` in query strings. The API normalizes app requests to `target_id=0` even if you pass another value.
|
||||
|
||||
List sort order: **`created_at DESC`** (newest reviews first).
|
||||
|
||||
---
|
||||
|
||||
## Response envelopes
|
||||
|
||||
### Success (`domain.Response`)
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Ratings retrieved successfully",
|
||||
"data": [],
|
||||
"success": true,
|
||||
"status_code": 200
|
||||
}
|
||||
```
|
||||
|
||||
Note: rely on **HTTP status code** as source of truth; some responses omit or zero `success` / `status_code`.
|
||||
|
||||
### Error (`domain.ErrorResponse`)
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Failed to retrieve ratings",
|
||||
"error": "detailed error when present"
|
||||
}
|
||||
```
|
||||
|
||||
### List response shape
|
||||
|
||||
`GET /ratings` returns **`data` as a JSON array** of rating objects (not wrapped in `{ ratings, total_count }`):
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Ratings retrieved successfully",
|
||||
"data": [
|
||||
{ "id": 1, "user_id": 1001, "target_type": "app", "target_id": 0, "stars": 5, "review": "Great!" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Use **`GET /ratings/summary`** for `total_count` when building paginated UI (see below).
|
||||
|
||||
---
|
||||
|
||||
## Admin API reference
|
||||
|
||||
Base path: `{API_BASE_URL}/api/v1`
|
||||
|
||||
### 1. Get rating summary (dashboard KPIs)
|
||||
|
||||
```
|
||||
GET /ratings/summary
|
||||
Permission: ratings.summary
|
||||
```
|
||||
|
||||
#### Query parameters
|
||||
|
||||
| Param | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `target_type` | Yes | `app`, `course`, or `sub_course` |
|
||||
| `target_id` | Yes* | Target ID; use `0` for `app` |
|
||||
|
||||
#### Example — app reviews dashboard
|
||||
|
||||
```http
|
||||
GET /api/v1/ratings/summary?target_type=app&target_id=0
|
||||
Authorization: Bearer <team_access_token>
|
||||
```
|
||||
|
||||
#### Response `200`
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Rating summary retrieved successfully",
|
||||
"data": {
|
||||
"total_count": 128,
|
||||
"average_stars": 4.35
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Errors
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | Invalid `target_type` or `target_id` |
|
||||
| `403` | Missing `ratings.summary` permission |
|
||||
| `500` | Server error |
|
||||
|
||||
---
|
||||
|
||||
### 2. List ratings / reviews (paginated table)
|
||||
|
||||
```
|
||||
GET /ratings
|
||||
Permission: ratings.list_by_target
|
||||
```
|
||||
|
||||
#### Query parameters
|
||||
|
||||
| Param | Required | Default | Description |
|
||||
|-------|----------|---------|-------------|
|
||||
| `target_type` | Yes | — | `app`, `course`, or `sub_course` |
|
||||
| `target_id` | Yes* | — | Use `0` for `app` |
|
||||
| `limit` | No | `20` | Page size |
|
||||
| `offset` | No | `0` | Rows to skip |
|
||||
|
||||
#### Example — first page of app reviews
|
||||
|
||||
```http
|
||||
GET /api/v1/ratings?target_type=app&target_id=0&limit=20&offset=0
|
||||
Authorization: Bearer <team_access_token>
|
||||
```
|
||||
|
||||
#### Response `200`
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Ratings retrieved successfully",
|
||||
"data": [
|
||||
{
|
||||
"id": 42,
|
||||
"user_id": 1001,
|
||||
"target_type": "app",
|
||||
"target_id": 0,
|
||||
"stars": 5,
|
||||
"review": "Love the practice exercises.",
|
||||
"created_at": "2026-05-10 14:22:01.000000 +0000 UTC",
|
||||
"updated_at": "2026-05-10 14:22:01.000000 +0000 UTC"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Errors
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | Invalid query params |
|
||||
| `403` | Missing `ratings.list_by_target` |
|
||||
| `500` | Server error |
|
||||
|
||||
#### Admin UI notes
|
||||
|
||||
- Display `stars` as star icons (1–5).
|
||||
- Show `review` or “—” when null/empty.
|
||||
- Show `user_id` and link to user profile (see [Enriching ratings with user profiles](#enriching-ratings-with-user-profiles)).
|
||||
- Format timestamps client-side; server returns Go-style time strings.
|
||||
|
||||
---
|
||||
|
||||
### 3. Endpoints not used by admin panel
|
||||
|
||||
Documented for completeness — **do not** wire these as admin moderation tools without backend changes.
|
||||
|
||||
#### Submit rating (learner)
|
||||
|
||||
```http
|
||||
POST /api/v1/ratings
|
||||
Permission: ratings.submit
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"target_type": "app",
|
||||
"stars": 5,
|
||||
"review": "Optional text"
|
||||
}
|
||||
```
|
||||
|
||||
- Upserts: same user + target replaces existing stars/review.
|
||||
- `target_id` omitted or any value for `app` → stored as `0`.
|
||||
|
||||
#### Get my rating (learner)
|
||||
|
||||
```http
|
||||
GET /api/v1/ratings/me?target_type=app&target_id=0
|
||||
Permission: ratings.get_mine
|
||||
```
|
||||
|
||||
Returns **404** if the authenticated user has not rated that target.
|
||||
|
||||
#### Delete rating (learner own only)
|
||||
|
||||
```http
|
||||
DELETE /api/v1/ratings/42
|
||||
Permission: ratings.delete
|
||||
```
|
||||
|
||||
Deletes only if `ratings.user_id = authenticated user_id`. **Staff cannot delete learner reviews** with the current API.
|
||||
|
||||
---
|
||||
|
||||
## Enriching ratings with user profiles
|
||||
|
||||
Rating rows include **`user_id` only** — no email, name, or avatar. For admin tables, fetch user details separately.
|
||||
|
||||
### Recommended: user detail lookup
|
||||
|
||||
```http
|
||||
GET /api/v1/user/single/:id
|
||||
Authorization: Bearer <team_access_token>
|
||||
Permission: users.get
|
||||
```
|
||||
|
||||
Use this to display learner name, email, and profile fields in the review table. Cache results in the admin UI to avoid N+1 requests on large pages.
|
||||
|
||||
### Optional: batch strategy
|
||||
|
||||
There is **no** bulk “users by IDs” endpoint in the ratings flow. Options:
|
||||
|
||||
1. **Lazy load** — fetch user on row expand / click.
|
||||
2. **Parallel fetch** — `Promise.all` for visible `user_id`s (cap concurrency).
|
||||
3. **Future backend** — request a dedicated admin list endpoint that joins `users` (not implemented today).
|
||||
|
||||
---
|
||||
|
||||
## Pagination & dashboard patterns
|
||||
|
||||
### Problem
|
||||
|
||||
`GET /ratings` does **not** return `total_count` in the response body. The SQL layer has `CountRatingsByTarget`, but it is not exposed in the handler.
|
||||
|
||||
### Recommended pattern
|
||||
|
||||
1. Call **`GET /ratings/summary`** once for KPIs and **`total_count`**.
|
||||
2. Call **`GET /ratings`** with `limit` / `offset` for the current page.
|
||||
3. Compute pages: `totalPages = ceil(total_count / limit)`.
|
||||
|
||||
```typescript
|
||||
const limit = 20;
|
||||
const offset = page * limit;
|
||||
|
||||
const [summary, listRes] = await Promise.all([
|
||||
fetch(`${API}/api/v1/ratings/summary?target_type=app&target_id=0`, { headers }),
|
||||
fetch(`${API}/api/v1/ratings?target_type=app&target_id=0&limit=${limit}&offset=${offset}`, { headers }),
|
||||
]);
|
||||
|
||||
const { total_count, average_stars } = (await summary.json()).data;
|
||||
const reviews = (await listRes.json()).data;
|
||||
```
|
||||
|
||||
### Dashboard widgets
|
||||
|
||||
| Widget | Source |
|
||||
|--------|--------|
|
||||
| Average rating | `summary.average_stars` (round to 1 decimal) |
|
||||
| Total reviews | `summary.total_count` |
|
||||
| Star distribution | **Not available** — compute client-side from full export or future API |
|
||||
| Recent reviews table | `GET /ratings` page 0 |
|
||||
|
||||
### Client-side filters (today)
|
||||
|
||||
Server does **not** support filtering by stars, date range, or review text. Admin panel can:
|
||||
|
||||
- Filter **current page** only (limited), or
|
||||
- Fetch larger pages and filter locally (not scalable), or
|
||||
- Wait for future admin search API
|
||||
|
||||
---
|
||||
|
||||
## Recommended admin UI screens
|
||||
|
||||
### 1. App reviews dashboard
|
||||
|
||||
**Route example:** `/admin/app-reviews`
|
||||
|
||||
**On load:**
|
||||
|
||||
1. `GET /ratings/summary?target_type=app&target_id=0`
|
||||
2. `GET /ratings?target_type=app&target_id=0&limit=20&offset=0`
|
||||
|
||||
**Layout:**
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ App Reviews │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ ★ 4.3 average │ 128 total reviews │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ Stars │ Review │ User │ Date │
|
||||
│ ★★★★★ │ Love the app... │ Jane D. │ May 10 │
|
||||
│ ★★★☆☆ │ Good but crashes… │ User #1002 │ May 9 │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ ← Prev Page 1 of 7 Next → │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 2. Target type tabs (optional)
|
||||
|
||||
If product still rates courses/sub-courses:
|
||||
|
||||
| Tab | Query |
|
||||
|-----|-------|
|
||||
| App | `target_type=app&target_id=0` |
|
||||
| Course | `target_type=course&target_id={courseId}` |
|
||||
| Sub-course | `target_type=sub_course&target_id={subCourseId}` |
|
||||
|
||||
Course/sub-course tabs need a course picker or deep-link from course admin screens.
|
||||
|
||||
### 3. User-centric view (optional)
|
||||
|
||||
From **Users → user detail**, show whether the user left an app review:
|
||||
|
||||
- Not available as a dedicated admin endpoint.
|
||||
- Workaround: not practical without `GET /ratings?user_id=` (not implemented).
|
||||
- Learner-only: `GET /ratings/me/all` returns the **authenticated** user’s ratings, not arbitrary users.
|
||||
|
||||
---
|
||||
|
||||
## TypeScript types & API client
|
||||
|
||||
### Types
|
||||
|
||||
```typescript
|
||||
export type RatingTargetType = "app" | "course" | "sub_course";
|
||||
|
||||
export interface Rating {
|
||||
id: number;
|
||||
user_id: number;
|
||||
target_type: RatingTargetType;
|
||||
target_id: number;
|
||||
stars: number;
|
||||
review: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface RatingSummary {
|
||||
total_count: number;
|
||||
average_stars: number;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
message: string;
|
||||
data: T;
|
||||
success?: boolean;
|
||||
status_code?: number;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
error?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Example client (fetch)
|
||||
|
||||
```typescript
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
function authHeaders(token: string): HeadersInit {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRatingSummary(
|
||||
token: string,
|
||||
targetType: RatingTargetType,
|
||||
targetId = 0
|
||||
): Promise<RatingSummary> {
|
||||
const qs = new URLSearchParams({
|
||||
target_type: targetType,
|
||||
target_id: String(targetType === "app" ? 0 : targetId),
|
||||
});
|
||||
const res = await fetch(`${API_BASE}/api/v1/ratings/summary?${qs}`, {
|
||||
headers: authHeaders(token),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<RatingSummary> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
export async function listRatingsByTarget(
|
||||
token: string,
|
||||
targetType: RatingTargetType,
|
||||
options: { targetId?: number; limit?: number; offset?: number } = {}
|
||||
): Promise<Rating[]> {
|
||||
const qs = new URLSearchParams({
|
||||
target_type: targetType,
|
||||
target_id: String(targetType === "app" ? 0 : (options.targetId ?? 0)),
|
||||
limit: String(options.limit ?? 20),
|
||||
offset: String(options.offset ?? 0),
|
||||
});
|
||||
const res = await fetch(`${API_BASE}/api/v1/ratings?${qs}`, {
|
||||
headers: authHeaders(token),
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
const body: ApiResponse<Rating[]> = await res.json();
|
||||
return body.data;
|
||||
}
|
||||
|
||||
/** App reviews dashboard helper */
|
||||
export async function loadAppReviewsPage(
|
||||
token: string,
|
||||
page: number,
|
||||
pageSize = 20
|
||||
): Promise<{ summary: RatingSummary; reviews: Rating[] }> {
|
||||
const offset = page * pageSize;
|
||||
const [summary, reviews] = await Promise.all([
|
||||
getRatingSummary(token, "app"),
|
||||
listRatingsByTarget(token, "app", { limit: pageSize, offset }),
|
||||
]);
|
||||
return { summary, reviews };
|
||||
}
|
||||
```
|
||||
|
||||
### React Query example
|
||||
|
||||
```typescript
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
export function useAppReviews(page: number, token: string) {
|
||||
return useQuery({
|
||||
queryKey: ["app-reviews", page],
|
||||
queryFn: () => loadAppReviewsPage(token, page, 20),
|
||||
enabled: !!token,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
| HTTP | Typical `message` | Admin UI action |
|
||||
|------|-------------------|-----------------|
|
||||
| `400` | Invalid `target_type` / `target_id` / `limit` | Fix query params |
|
||||
| `401` | Unauthorized | Redirect to login |
|
||||
| `403` | Forbidden | Show “No permission”; check RBAC / JWT role |
|
||||
| `404` | Rating not found | Only on `GET /ratings/me` (learner) |
|
||||
| `500` | Failed to retrieve ratings | Toast + retry |
|
||||
|
||||
Always read the `error` field when present.
|
||||
|
||||
### Empty states
|
||||
|
||||
| Condition | UI |
|
||||
|-----------|-----|
|
||||
| `total_count === 0` | “No app reviews yet” |
|
||||
| `summary` OK but `data: []` on last page | Normal — offset past end; go to previous page |
|
||||
| `review === null` | Show em dash or “No written review” |
|
||||
|
||||
---
|
||||
|
||||
## Integration checklist
|
||||
|
||||
### Backend / access
|
||||
|
||||
- [ ] Migration `000017_ratings` applied (`SELECT to_regclass('public.ratings')` not null)
|
||||
- [ ] Staff token via `POST /team/login` or `POST /auth/admin-login`
|
||||
- [ ] Role has `ratings.list_by_target` and `ratings.summary` (or `ADMIN` / `SUPER_ADMIN`)
|
||||
- [ ] Optional: `users.get` for enriching review table with names
|
||||
|
||||
### Admin panel — navigation
|
||||
|
||||
- [ ] Add “App reviews” / “Ratings” menu item (gate on `ratings.list_by_target`)
|
||||
- [ ] Do **not** expose submit/delete for staff unless product adds admin APIs
|
||||
|
||||
### Dashboard
|
||||
|
||||
- [ ] `GET /ratings/summary?target_type=app&target_id=0` for KPIs
|
||||
- [ ] Display average stars (1 decimal) and total count
|
||||
|
||||
### Review list
|
||||
|
||||
- [ ] `GET /ratings?target_type=app&target_id=0&limit=&offset=`
|
||||
- [ ] Pagination using `summary.total_count`
|
||||
- [ ] Star display, review text, user link, date column
|
||||
- [ ] Optional user profile fetch via `GET /user/single/:id`
|
||||
|
||||
### QA scenarios
|
||||
|
||||
- [ ] Dashboard loads with 0 reviews (empty state)
|
||||
- [ ] Dashboard loads with existing reviews (correct count/average)
|
||||
- [ ] Pagination next/prev works across multiple pages
|
||||
- [ ] `SUPPORT` staff can view but not submit (if tested)
|
||||
- [ ] 403 shown when role lacks permissions
|
||||
- [ ] Review with null `review` renders correctly
|
||||
|
||||
---
|
||||
|
||||
## Limitations & future work
|
||||
|
||||
| Topic | Current behavior | Admin impact |
|
||||
|-------|------------------|--------------|
|
||||
| No `/admin/ratings` routes | Shared learner endpoints | Use documented query params |
|
||||
| No admin delete | `DELETE` is own-user only | No moderation delete in UI |
|
||||
| No hide/flag workflow | All reviews always visible | No approve/reject |
|
||||
| List lacks `total_count` | Use `/summary` separately | Two API calls per page view |
|
||||
| No star histogram API | Only average + count | Build client-side or request backend |
|
||||
| No search/filter API | Full table scan not available | Client filters limited |
|
||||
| No user join in list | Only `user_id` | Extra `users.get` calls |
|
||||
| Legacy targets only | `course`, `sub_course` — not programs/modules | Map product IDs carefully |
|
||||
| No analytics integration | Ratings absent from analytics dashboard | Manual reporting only |
|
||||
| No integration tests/docs | Swagger only | This guide fills admin gap |
|
||||
|
||||
### Suggested future backend endpoints (not implemented)
|
||||
|
||||
If product needs full admin moderation, consider:
|
||||
|
||||
- `GET /admin/ratings` — list with filters, user join, `total_count`
|
||||
- `DELETE /admin/ratings/:id` — staff moderation
|
||||
- `GET /admin/ratings/summary` — star distribution histogram
|
||||
- `GET /admin/users/:id/ratings` — reviews by user
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Method | Path | Permission | Admin purpose |
|
||||
|--------|------|------------|---------------|
|
||||
| `GET` | `/api/v1/ratings/summary` | `ratings.summary` | KPIs (avg + count) |
|
||||
| `GET` | `/api/v1/ratings` | `ratings.list_by_target` | Paginated review list |
|
||||
| `GET` | `/api/v1/user/single/:id` | `users.get` | Resolve reviewer name |
|
||||
| `POST` | `/api/v1/ratings` | `ratings.submit` | Learner only |
|
||||
| `DELETE` | `/api/v1/ratings/:id` | `ratings.delete` | Learner own only |
|
||||
|
||||
### App reviews query template
|
||||
|
||||
```http
|
||||
GET /api/v1/ratings/summary?target_type=app&target_id=0
|
||||
GET /api/v1/ratings?target_type=app&target_id=0&limit=20&offset=0
|
||||
Authorization: Bearer <team_access_token>
|
||||
```
|
||||
|
|
@ -170,6 +170,21 @@ type CreateTeamMemberReq struct {
|
|||
Permissions []string `json:"permissions"`
|
||||
}
|
||||
|
||||
// UpdateMyTeamProfileReq is the self-service profile update payload (fields visible on GET /team/me).
|
||||
type UpdateMyTeamProfileReq struct {
|
||||
TeamMemberID int64 `json:"-"`
|
||||
UpdatedBy int64 `json:"-"`
|
||||
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Department string `json:"department"`
|
||||
JobTitle string `json:"job_title"`
|
||||
ProfilePictureURL string `json:"profile_picture_url"`
|
||||
Bio string `json:"bio"`
|
||||
WorkPhone string `json:"work_phone"`
|
||||
}
|
||||
|
||||
type UpdateTeamMemberReq struct {
|
||||
TeamMemberID int64 `json:"-"`
|
||||
UpdatedBy int64 `json:"-"`
|
||||
|
|
|
|||
|
|
@ -286,6 +286,7 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
|
||||
// Team
|
||||
{Key: "team.profile.get_mine", Name: "Get My Team Profile", Description: "Get own team profile", GroupName: "Team"},
|
||||
{Key: "team.profile.update_mine", Name: "Update My Team Profile", Description: "Update own team profile", GroupName: "Team"},
|
||||
{Key: "team.stats", Name: "Get Team Stats", Description: "Get team member statistics", GroupName: "Team"},
|
||||
{Key: "team.members.list", Name: "List Team Members", Description: "List all team members", GroupName: "Team"},
|
||||
{Key: "team.members.create", Name: "Create Team Member", Description: "Create a team member", GroupName: "Team"},
|
||||
|
|
@ -495,7 +496,7 @@ var DefaultRolePermissions = map[string][]string{
|
|||
"vimeo.uploads.pull", "vimeo.uploads.tus",
|
||||
|
||||
// Team (full access)
|
||||
"team.profile.get_mine", "team.stats", "team.members.list", "team.members.create", "team.members.invite",
|
||||
"team.profile.get_mine", "team.profile.update_mine", "team.stats", "team.members.list", "team.members.create", "team.members.invite",
|
||||
"team.members.get", "team.members.update", "team.members.update_status", "team.members.delete", "team.members.change_password",
|
||||
"team.invitations.list", "team.invitations.resend", "team.invitations.revoke",
|
||||
|
||||
|
|
@ -584,6 +585,9 @@ var DefaultRolePermissions = map[string][]string{
|
|||
// Ratings
|
||||
"ratings.submit", "ratings.list_by_target", "ratings.summary", "ratings.get_mine", "ratings.list_mine", "ratings.delete",
|
||||
|
||||
// Team (own profile)
|
||||
"team.profile.get_mine", "team.profile.update_mine", "team.members.change_password",
|
||||
|
||||
// Auth
|
||||
"auth.logout",
|
||||
},
|
||||
|
|
@ -639,6 +643,9 @@ var DefaultRolePermissions = map[string][]string{
|
|||
// Ratings (read)
|
||||
"ratings.list_by_target", "ratings.summary", "ratings.get_mine", "ratings.list_mine",
|
||||
|
||||
// Team (own profile)
|
||||
"team.profile.get_mine", "team.profile.update_mine", "team.members.change_password",
|
||||
|
||||
// Auth
|
||||
"auth.logout",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -103,6 +103,30 @@ func (s *Service) UpdateTeamMember(ctx context.Context, req domain.UpdateTeamMem
|
|||
return s.teamStore.UpdateTeamMember(ctx, req)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateMyTeamProfile(ctx context.Context, req domain.UpdateMyTeamProfileReq) (domain.TeamMember, error) {
|
||||
if _, err := s.teamStore.GetTeamMemberByID(ctx, req.TeamMemberID); err != nil {
|
||||
return domain.TeamMember{}, err
|
||||
}
|
||||
|
||||
err := s.teamStore.UpdateTeamMember(ctx, domain.UpdateTeamMemberReq{
|
||||
TeamMemberID: req.TeamMemberID,
|
||||
UpdatedBy: req.UpdatedBy,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
PhoneNumber: req.PhoneNumber,
|
||||
Department: req.Department,
|
||||
JobTitle: req.JobTitle,
|
||||
ProfilePictureURL: req.ProfilePictureURL,
|
||||
Bio: req.Bio,
|
||||
WorkPhone: req.WorkPhone,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.TeamMember{}, err
|
||||
}
|
||||
|
||||
return s.teamStore.GetTeamMemberByID(ctx, req.TeamMemberID)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateTeamMemberStatus(ctx context.Context, req domain.UpdateTeamMemberStatusReq) error {
|
||||
if !domain.TeamMemberStatus(req.Status).IsValid() {
|
||||
return domain.ErrInvalidTeamMemberStatus
|
||||
|
|
|
|||
|
|
@ -911,6 +911,74 @@ func (h *Handler) GetMyTeamProfile(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
// UpdateMyTeamProfile godoc
|
||||
// @Summary Update my team profile
|
||||
// @Description Update the authenticated team member's own profile fields
|
||||
// @Tags team
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param body body domain.UpdateMyTeamProfileReq true "Profile update payload"
|
||||
// @Success 200 {object} domain.Response{data=domain.TeamMemberResponse}
|
||||
// @Failure 400 {object} domain.ErrorResponse
|
||||
// @Failure 401 {object} domain.ErrorResponse
|
||||
// @Failure 404 {object} domain.ErrorResponse
|
||||
// @Failure 500 {object} domain.ErrorResponse
|
||||
// @Router /api/v1/team/me [put]
|
||||
func (h *Handler) UpdateMyTeamProfile(c *fiber.Ctx) error {
|
||||
memberID, ok := c.Locals("user_id").(int64)
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid user context",
|
||||
Error: "User ID not found in request context",
|
||||
})
|
||||
}
|
||||
|
||||
var req domain.UpdateMyTeamProfileReq
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to update profile",
|
||||
Error: "Invalid request body: " + err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
req.TeamMemberID = memberID
|
||||
req.UpdatedBy = memberID
|
||||
|
||||
member, err := h.teamSvc.UpdateMyTeamProfile(c.Context(), req)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTeamMemberNotFound) {
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||
Message: "Team member not found",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
h.mongoLoggerSvc.Error("Failed to update team member profile",
|
||||
zap.Int64("member_id", memberID),
|
||||
zap.Int("status_code", fiber.StatusInternalServerError),
|
||||
zap.Error(err),
|
||||
zap.Time("timestamp", time.Now()),
|
||||
)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to update profile",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
actorRole := string(c.Locals("role").(domain.Role))
|
||||
ip := c.IP()
|
||||
ua := c.Get("User-Agent")
|
||||
meta, _ := json.Marshal(map[string]interface{}{"member_id": memberID})
|
||||
go h.activityLogSvc.RecordAction(context.Background(), &memberID, &actorRole, domain.ActionTeamMemberUpdated, domain.ResourceTeamMember, &memberID, "Updated own team profile", meta, &ip, &ua)
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||
Message: "Profile updated successfully",
|
||||
Data: toTeamMemberResponse(&member),
|
||||
Success: true,
|
||||
StatusCode: fiber.StatusOK,
|
||||
})
|
||||
}
|
||||
|
||||
func toTeamMemberResponse(m *domain.TeamMember) domain.TeamMemberResponse {
|
||||
resp := domain.TeamMemberResponse{
|
||||
ID: m.ID,
|
||||
|
|
|
|||
|
|
@ -441,6 +441,7 @@ func (a *App) initAppRoutes() {
|
|||
teamGroup.Get("/invitations/verify", h.VerifyTeamInvitation)
|
||||
teamGroup.Post("/invitations/accept", h.AcceptTeamInvitation)
|
||||
teamGroup.Get("/me", a.authMiddleware, a.RequirePermission("team.profile.get_mine"), h.GetMyTeamProfile)
|
||||
teamGroup.Put("/me", a.authMiddleware, a.RequirePermission("team.profile.update_mine"), h.UpdateMyTeamProfile)
|
||||
teamGroup.Get("/stats", a.authMiddleware, a.RequirePermission("team.stats"), h.GetTeamMemberStats)
|
||||
teamGroup.Get("/members", a.authMiddleware, a.RequirePermission("team.members.list"), h.GetAllTeamMembers)
|
||||
teamGroup.Post("/members/invite", a.authMiddleware, a.RequirePermission("team.members.invite"), h.InviteTeamMember)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user