[5.1] Super Admin View

1. Front Matter

  • Title: Super Admin View

  • Author: scorevi/dyorgie (Backend/Frontend)

  • Reviewers: scorevi/dyorgie (Backend/Frontend)

  • Created: April 2026

  • Status: Approved

  • References:

    • Issue: [5.1] Super Admin View

    • Milestone: [5] Dashboards


2. Introduction & Goals

  • Problem Summary: Platform administrators need a centralized control panel to manage all system operations including user management, agency oversight, AI configuration, system health monitoring, branding customization, and gamification settings.

  • Goals:

    • Provide comprehensive user management (role changes, suspension, deletion)

    • Enable agency administration (creation, editing, budget allocation)

    • Display real-time system health metrics and token usage tracking

    • Manage platform-wide AI configuration (Gemini API keys and models)

    • Configure platform branding and SMTP settings

    • Administer global gamification achievements

    • Ensure secure role-based access control with RLS policies

  • Non-Goals:

    • Individual learner progress tracking

    • Quest content moderation interface

    • Real-time collaborative admin features

    • Cross-platform analytics integration

  • Glossary:

    • RLS: Row Level Security - Database-level access control

    • Token Budget: Monthly AI token allocation per agency

    • Gemini Config: Google AI API configuration and model settings

    • SMTP: Email server configuration for platform communications

    • Agency Plan: Subscription tier (free, pro, enterprise, custom)


3. High-Level Architecture

  • System Diagram:

image.png
  • Technologies Used:

    • Supabase - Database with RLS policies for admin tables

    • Clerk - Authentication and user role management

    • Shadcn UI - Form components (Dialog, Combobox, Select)

    • Recharts - Token usage visualization

    • WebSocket - Real-time system health updates

    • Next.js Server Actions - Gemini configuration management

    • React Hook Form + Zod - Form validation


4. Detailed Design & Implementation

  • Data Model / Schema:

app_users Table:

Column

Type

Description

id

UUID PK

User ID

clerk_id

TEXT

Clerk authentication ID

email

TEXT

User email

role

TEXT

ADMIN, AGENCY, CREATOR, REVIEWER, LEARNER

status

TEXT

Active, Suspended

created_at

TIMESTAMPTZ

Account creation time

agencies Table:

Column

Type

Description

id

UUID PK

Agency ID

name

TEXT

Agency name

owner_id

UUID FK

Reference to app_users

owner_clerk_id

TEXT

Clerk ID of owner

plan

TEXT

free, pro, enterprise, custom

status

TEXT

active, inactive, suspended, trial

monthly_token_budget

INTEGER

AI token allocation

contact_email

TEXT

Primary contact

metadata

JSONB

Additional settings

token_usage Table:

Column

Type

Description

id

UUID PK

Usage record ID

agency_id

UUID FK

Agency reference

month

TEXT

YYYY-MM format

tokens_used

INTEGER

Monthly usage

budget

INTEGER

Monthly allocation

estimated_cost_usd

NUMERIC

Cost estimate

model_breakdown

JSONB

Usage by model

feature_breakdown

JSONB

Usage by feature

token_usage_events Table:

Column

Type

Description

id

UUID PK

Event ID

user_clerk_id

TEXT

User who triggered event

agency_id

UUID FK

Agency reference

model

TEXT

AI model used

input_tokens

INTEGER

Prompt tokens

output_tokens

INTEGER

Response tokens

total_tokens

INTEGER

Combined count

feature

TEXT

Feature using AI

cost_usd

NUMERIC

Event cost

cached

BOOLEAN

Cache hit status

timestamp

TIMESTAMPTZ

Event time

gemini_config Table:

Column

Type

Description

id

UUID PK

Config ID

api_key

TEXT

Gemini API key (encrypted)

model_name

TEXT

Selected model

temperature

NUMERIC

0.0-2.0 range

is_active

BOOLEAN

Active config flag

test_connection_status

TEXT

Last test result

global_achievements Table:

Column

Type

Description

id

UUID PK

Achievement ID

title

TEXT

Achievement name

description

TEXT

Achievement details

badge_url

TEXT

Badge image URL

criteria

JSONB

Unlock criteria

is_active

BOOLEAN

Enabled status

  • API Specification:

User Management:

  • GET /api/admin/list-users - List all users with role filtering

  • POST /api/admin/change-role - Change user role

    • Request: { clerkId: string, newRole: "ADMIN" | "AGENCY" | "CREATOR" | "REVIEWER" | "LEARNER" }

  • POST /api/admin/suspend-user - Suspend user account

    • Request: { clerkId: string }

  • POST /api/admin/unsuspend-user - Reactivate user

    • Request: { clerkId: string }

  • DELETE /api/admin/delete-user - Permanently delete user

    • Request: { clerkId: string, password: string }

Agency Management:

  • GET /api/agency/list - List all agencies

  • POST /api/admin/agencies - Create new agency

    • Request: { name: string, ownerClerkId: string, plan: string, monthlyTokenBudget: number }

  • PATCH /api/admin/agencies/[id] - Update agency

    • Request: { name?, plan?, status?, monthlyTokenBudget? }

  • DELETE /api/admin/agencies/[id] - Delete agency

  • GET /api/admin/agencies/[id]/members - Get agency members

System Monitoring:

  • GET /api/admin/system-health - System health metrics

    • Response: { tokenUsage: [], monthlyBudget: number, totalUsers: number, activeAgencies: number }

  • GET /api/admin/analytics - Platform analytics

    • Response: { userCounts: { total, byRole }, agencyCounts: { total, byPlan }, questCounts }

AI Configuration (Server Actions):

  • getGeminiConfig() - Retrieve current configuration

  • updateGeminiConfig(data) - Update API key and model

  • testGeminiConnection() - Validate API connectivity

Branding:

  • GET /api/admin/branding/load - Load branding settings

  • POST /api/admin/branding/save - Save branding

  • POST /api/admin/branding/upload-logo - Upload logo

  • DELETE /api/admin/branding/delete-logo - Delete logo

  • POST /api/admin/branding/smtp/test - Test SMTP config

  • POST /api/admin/branding/email/test-* - Test email templates

Gamification:

  • GET /api/admin/global-achievements - List achievements

  • POST /api/admin/global-achievements - Create achievement

  • PATCH /api/admin/global-achievements/[id] - Update achievement

  • DELETE /api/admin/global-achievements/[id] - Delete achievement

  • POST /api/admin/global-achievements/badge/route.ts - Upload badge

  • Logic & Workflows:

User Role Management:

  1. Admin navigates to Manage Users page

  2. User list loads with role and status badges

  3. Admin clicks user row → modal opens

  4. Admin selects new role from dropdown

  5. Confirmation dialog appears for role change

  6. API updates both Clerk metadata and app_users.role

  7. Success toast displays and list refreshes

Agency Budget Allocation:

  • Free Plan: 100,000 tokens/month

  • Pro Plan: 500,000 tokens/month

  • Enterprise Plan: 1,000,000 tokens/month

  • Custom Plan: Admin-defined limit

Token Usage Tracking Flow:

  1. User triggers AI feature (validator, generator, etc.)

  2. Event recorded in token_usage_events table

  3. Monthly aggregation updated in token_usage table

  4. Real-time update sent via WebSocket

  5. System Health dashboard updates chart

  6. Cost calculated using gemini_pricing table

  7. Agency notified if approaching budget limit

Gemini Configuration Flow:

  1. Admin opens AI Configuration section

  2. Current config loaded (API key masked)

  3. Admin enters new API key or selects model

  4. Test connection button validates credentials

  5. On success → save configuration

  6. gemini_config.is_active flag set

  7. All AI features use new configuration

Security & Access Control:

  • All admin routes protected via authenticateRole('ADMIN') middleware

  • RLS policies enforce app_users.role = 'ADMIN' checks

  • API keys masked in UI (show first 4 + last 4 characters)

  • Password confirmation required for destructive actions

  • Clerk webhook syncs role changes across systems

  • Key Files:

Pages:

  • app/admin/page.tsx - Main dashboard

  • app/admin/manage-users/page.tsx - User management

  • app/admin/agencies/page.tsx - Agency management

  • app/admin/system-health/page.tsx - Health monitoring

  • app/admin/branding/page.tsx - Branding settings

  • app/admin/gamification/page.tsx - Gamification config

  • app/admin/subscription/page.tsx - Subscription management

  • app/admin/layout.tsx - Admin layout with sidebar

Components:

  • components/admin/AdminAnalytics.tsx - Dashboard analytics

  • components/admin/GeminiConfigForm.tsx - AI configuration

  • components/admin/TokenUsageChart.tsx - Usage visualization

  • components/admin/AgencyList.tsx - Agency listing

  • components/admin/BrandingTabs.tsx - Branding interface

  • components/admin/ThemeCustomizer.tsx - Theme settings

  • components/admin/manage-users/ChangeRoleModal.tsx - Role change UI

  • components/admin/manage-users/SuspendUserModal.tsx - Suspension UI

  • components/admin/manage-users/DeleteUserModal.tsx - Deletion UI

API Routes:

  • app/api/admin/list-users/route.ts

  • app/api/admin/change-role/route.ts

  • app/api/admin/suspend-user/route.ts

  • app/api/admin/unsuspend-user/route.ts

  • app/api/admin/delete-user/route.ts

  • app/api/admin/agencies/route.ts

  • app/api/admin/agencies/[id]/route.ts

  • app/api/admin/system-health/route.ts

  • app/api/admin/analytics/route.ts

  • app/api/admin/global-achievements/route.ts

  • app/api/admin/branding/*/route.ts

Utilities:

  • lib/auth/authenticateRole.ts - Role verification

  • constants/getNavGroups.ts - Admin navigation structure


5. Infrastructure & Operations

  • Dependencies:

    • Supabase DB - Admin tables with RLS policies

    • Clerk - User authentication and role management

    • Gemini API - AI model configuration

    • Supabase Storage - Logo and badge uploads

    • WebSocket - Real-time system health updates

  • Monitoring & Alerting:

    • Token usage tracked per agency in real-time

    • System health dashboard monitors AI spending

    • Email alerts when agencies approach budget limits (future enhancement)

    • Gemini connection status monitoring

  • Deployment Plan:

    1. Run database migrations for admin tables and RLS policies

    2. Configure Clerk admin role in production

    3. Deploy admin UI components and API routes

    4. Initialize default Gemini configuration

    5. Set up WebSocket server for real-time updates

    6. No feature flags needed (role-based access control)


6. Testing & Quality Assurance

  • Test Strategy:

    • Manual: User role changes, agency creation, token tracking

    • Integration: RLS policy enforcement, API authentication

    • Security: Role-based access verification, API key masking

    • Performance: Token usage event ingestion at scale

  • Known Limitations:

    • Single active Gemini configuration (no A/B testing)

    • Logo upload limited to 2MB

    • No real-time collaboration between admins

    • Token usage aggregation has ~5 minute delay

    • Agency owner cannot be changed after creation (requires new agency)

    • Deletion is permanent (no soft delete for users)


7. Maintenance & Support

  • Troubleshooting:

    • Token usage not updating → Check WebSocket connection status

    • Role change fails → Verify Clerk webhook configuration

    • Gemini API errors → Test connection and validate API key

    • RLS policy blocks admin → Verify app_users.role = 'ADMIN' in database

    • Agency creation fails → Check for duplicate owner (one agency per owner)

    • User deletion blocked → Ensure password confirmation provided

    • SMTP test fails → Verify email settings and firewall rules

  • Changelog:

    • 1.0 (Apr 2026): Initial comprehensive super admin implementation

      • User management (role changes, suspension, deletion)

      • Agency administration with budget allocation

      • System health monitoring with real-time token tracking

      • Gemini AI configuration management

      • Platform branding and SMTP settings

      • Global gamification administration


Document Version

1.0 - Approved, Feature deployed to production, 04/28/2026


Was this article helpful?