Feature Owner: scorevi (Sean Patrick Caintic)
Module: Dashboards
Priority: P0
Sprint #12: Fully Implemented & Deployed
Date: 2026-06-29
EXECUTIVE SUMMARY
What is this feature?
Top-level platform administration dashboard with 8 sub-pages: Dashboard, System Health, Settings, Manage Users, Branding, Agencies, Subscription, and Gamification. Protected by server-side authenticateRole('ADMIN') in app/admin/layout.tsx. Admin layout renders AdminLayoutClient.tsx with UnifiedSidebar(userRole="admin") wrapped in BrandingProvider and AgencyStatusProvider.
Why does it matter?
Platform operations require a single control panel. Admins manage users, agencies, billing, and platform configuration from one interface. Without it, every administrative action requires direct database access or scattered tools.
What's the MVP scope?
Fully deployed. User CRUD (role change, suspend, delete). Agency CRUD (create, edit, delete, transfer ownership). System health monitoring. Gemini AI config. Branding/SMTP config. Gamification management. All destructive actions behind re-auth.
1. USER PAIN POINT & SOLUTION
Current State (Without Feature)
Platform operations teams would need SQL access or multiple disjointed admin tools. No unified view of users, agencies, or system health.
Pain Point
Emotional: "I manage a platform but can't see who's using it or how."
Functional: No user/agency management interface.
Business Impact: Operational overhead; inability to scale support.
Future State (With Feature)
Single dashboard with all platform controls. Manage users in a table. Create agencies. Monitor token usage. Configure AI models. All destructive actions behind re-auth.
Marketing Hook
"One dashboard. Full platform control. Every action auditable."
2. 4D FRAMEWORK MAPPING
Diagnose
System Health page shows token usage, agency activity via real-time Supabase subscriptions.
Design
Manage Users and Agencies pages provide CRUD interfaces for platform entities.
Develop
Gamification management (badges, triggers) supports the Develop phase. Settings page configures Gemini AI, branding, and platform-wide options.
Deliver
Not directly applicable.
3. USER FLOWS
Entry Point
Admin signs in → auto-routed to /admin. Layout guard authenticateRole('ADMIN') in app/admin/layout.tsx verifies permission.
Success Criteria
Admin navigates between all 8 sub-pages. Performs user/agency management. System health data visible.
Main Flow (Happy Path)
Manage Users:
Admin navigates to
/admin/manage-usersTable displays all users with role, status, agency
Change role →
POST /api/admin/change-rolewithreauthTokenin bodySuspend user →
POST /api/admin/suspend-user(uses rawNextResponse.jsonfor success,ApiResponseHelper.handleError()for errors)Delete user →
DELETE /api/admin/delete-userwithreauthToken(116-line route)
Manage Agencies:
Admin navigates to
/admin/agenciesCreate agency:
POST /api/admin/agencies— only POST handler exists (no GET)Manage members:
PATCH/DELETE /api/admin/agencies/[id]/members— both usememberIdfrom request body (not URL param), validated withz.string().uuid()
System Health:
Admin navigates to
/admin/system-healthToken usage chart via
TokenUsageChart.tsxfor current monthReal-time Supabase subscriptions for live data
Edge Cases
No data: Empty user/agency lists show empty state.
API error: Fetch failure → error toast with retry.
Permission denied: Non-admin accessing
/admin→ redirected to actual role dashboard.
Decision Points
Sensitive actions (delete-user, change-role, suspend-user) require
reauthTokenin request body.
4. INFORMATION ARCHITECTURE
Primary Information (Always visible)
Dashboard: Admin analytics via
AdminAnalytics.tsx.Manage Users: User table with search, role badges, status indicators.
Agencies: Agency table via
AgencyList.tsxwith member counts, budget, status.Settings:
GeminiConfigForm.tsx,PlatformConfigForm.tsx.Branding:
BrandingTabs.tsx.
Secondary Information
Token usage details via
GeminiConfigForm.tsx.Agency member lists (expandable).
Actions
Primary CTA: "Add User", "Create Agency", "Save Settings".
Secondary Actions: "Edit", "Delete", "Suspend/Unsuspend", "Transfer Ownership" (all require re-auth via ReAuthModal.tsx).
5. WIREFRAMES
Excluded — UI is fully developed (8 sub-pages, 10+ components).
6. WIREFLOWS
Excluded.
7. PROTOTYPE
Excluded — production deployed.
8. BACKEND SCHEMA
Database Tables Accessed
Table | Used For |
|---|---|
| User management, role changes, suspend/delete |
| Agency CRUD, ownership management |
| Member listing, invite, remove via |
| Sensitive action tokens |
| AI configuration |
| Token usage tracking |
9. API ENDPOINTS
GET /api/admin/analytics (role counts + active quests)GET /api/admin/system-health (token usage daily — uses inline ApiResponse class, NOT ApiResponseHelper)GET /api/admin/list-users?mode=picker|membersGET /api/admin/gemini/api-key (key status + models)POST /api/admin/gemini/api-key (actions: reload, clear-cache, validate — NO DELETE handler)POST /api/admin/change-role (reauthToken required — 74 lines)DELETE /api/admin/delete-user (reauthToken required — 116 lines)POST /api/admin/suspend-user (MIXED pattern: auth checks use raw NextResponse.json, errors use ApiResponseHelper.handleError(), success uses raw NextResponse.json — NOT fully standardized — 44 lines)POST /api/admin/unsuspend-userPOST /api/admin/agencies (create agency — only POST, NO GET handler)PATCH /api/admin/agencies/[id] (edit / ownership transfer)DELETE /api/admin/agencies/[id] (requires reauth)GET /api/admin/agencies/[id]/members (list agency members)PATCH /api/admin/agencies/[id]/members (memberId in body, z.string().uuid())DELETE /api/admin/agencies/[id]/members (memberId in body, z.string().uuid())POST /api/admin/sync-users (sync from Clerk)POST /api/admin/reauth (issue re-auth token)GET /api/admin/platform-config (fair-share budget calc)
All routes require authenticateRole('ADMIN').
10. DATA REQUIREMENTS
Frontend Needs
User list with role, status, agency.
Agency list with owner, members, budget.
Token usage chart data.
Re-auth token for sensitive operations.
Caching Strategy
AdminAnalyticsfetches fresh on mount (no cache).
11. PERFORMANCE CONSIDERATIONS
Database Optimization
Indexed queries on
app_users.role,app_users.status.Paginated user lists.
API Response Time
Target: <500ms for dashboard data.
Who can access this feature?
ADMIN role only. Server-side layout guard authenticateRole('ADMIN') in app/admin/layout.tsx.
Layout redirects non-admins to their actual role dashboard. Sensitive actions require re-auth token (see [0.5]).
Data Validation
All inputs validated with Zod before processing.
13. ERROR HANDLING
Error | How Handled |
|---|---|
Non-admin access | Redirect to actual role dashboard |
Re-auth required |
|
Invalid role change | Validation error with valid roles listed |
Cannot delete admin | Blocked: "Cannot delete admin users" |
Ownership transfer |
|
Known issue: /api/admin/suspend-user has MIXED usage — auth checks use raw NextResponse.json, error paths use ApiResponseHelper.handleError(), success uses raw NextResponse.json({success:true}). /api/admin/system-health uses inline ApiResponse class, NOT ApiResponseHelper. Neither is fully standardized per [W1.4].
14. TESTING CHECKLIST
Happy Path
□ Admin sees all 8 sub-pages
□ Change user role → re-auth → success
□ Create agency → appears in list via POST /api/admin/agencies
□ System health chart renders
Edge Cases
□ Non-admin → redirected
□ Delete admin user → blocked
□ Suspend/unsuspend → status updates correctly
□ Re-auth expires → action blocked
15. OPEN QUESTIONS
/api/admin/system-healthuses inlineApiResponseclass — should be refactored toApiResponseHelperper [W1.4]./api/admin/suspend-userhas mixed response patterns — needs standardization./api/admin/agencies/has no GET handler — admin agency list is constructed from client-side state or other endpoints.
16. OUT OF SCOPE (v1.1+)
Advanced analytics dashboard with export.
Admin notification center.
Bulk user import/export.
17. SUCCESS METRICS
All admin actions completed without SQL access.
Audit trail coverage: 100% of destructive actions logged.
18. DEPENDENCIES
This feature depends on:
[0.1] Secure Login + [0.5] Re-Auth + [6.1.1] RBAC.
[10.1] Gemini Configuration — managed via admin settings.
[5.3] System Health & Monitoring — sub-page within admin dashboard.
These features depend on this:
[5.2] Agency Admin View — admin manages agencies.
[5.3] System Health & Monitoring — admin sub-page.
19. TIMELINE & OWNERSHIP
Sprint #12: Already deployed.
Backend: scorevi
Frontend: scorevi
Estimated Completion: Complete.
Document Version
1.0 - Initial version - 2026-06-29 08:19 UTC
1.1 - Added Document Version section and update author to have full name - 2026-06-29 08:46 UTC