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

23 KiB
Raw Permalink Blame History

Ratings & App Reviews — Admin Panel Integration Guide

This guide documents how to integrate ratings and app reviews into the Rezina 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
  2. Architecture
  3. Authentication & permissions
  4. RBAC setup & troubleshooting 403
  5. Data model
  6. Target types
  7. Response envelopes
  8. Admin API reference
  9. Enriching ratings with user profiles
  10. Pagination & dashboard patterns
  11. Recommended admin UI screens
  12. TypeScript types & API client
  13. Error handling
  14. Integration checklist
  15. Limitations & future work
  16. 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

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["Rezina 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:

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

SELECT to_regclass('public.ratings');

If NULL, run database migrations.

3. Sync RBAC permissions

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)

{
  "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)

{
  "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)

{
  "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)

{
  "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 }):

{
  "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

GET /api/v1/ratings/summary?target_type=app&target_id=0
Authorization: Bearer <team_access_token>

Response 200

{
  "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

GET /api/v1/ratings?target_type=app&target_id=0&limit=20&offset=0
Authorization: Bearer <team_access_token>

Response 200

{
  "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).
  • 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)

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)

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)

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.

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_ids (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.

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

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

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)

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

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

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>