swiftops-backend / docs /dev /dashboards /PLATFORM_ADMIN_DASHBOARD_FIX.md
kamau1's picture
chore: migrate to useast organize the docs, delete redundant migrations
c4f7e3e
# Platform Admin Dashboard - Bug Fix Summary
## Issue Identified
The dashboard was failing to load with a **404 error** on `/api/v1/audit-logs` because the audit logs API endpoint was not implemented, even though the models and services existed.
## Changes Made
### 1. Created Audit Logs API (`src/app/api/v1/audit_logs.py`)
**New Endpoints:**
- `GET /api/v1/audit-logs` - List all audit logs with filtering and pagination
- Query params: `skip`, `limit`, `user_id`, `action`, `entity_type`, `search`, `start_date`, `end_date`
- Platform Admin only
- `GET /api/v1/audit-logs/{audit_log_id}` - Get specific audit log
- Platform Admin only
- `GET /api/v1/audit-logs/user/{user_id}` - Get all logs for a specific user
- Platform Admin only
- `GET /api/v1/audit-logs/export/csv` - Export audit logs as CSV
- Query params: `start_date`, `end_date`
- Platform Admin only
**Features:**
- Pagination support (up to 1000 records per request)
- Advanced filtering (by user, action, entity type, date range)
- Full-text search in description and user email
- CSV export functionality
- Proper authorization (platform_admin role required)
### 2. Created Audit Log Schemas (`src/app/schemas/audit_log.py`)
**New Schemas:**
- `AuditLogBase` - Base schema
- `AuditLogResponse` - Full audit log response
- `AuditLogListResponse` - Paginated list response
- `AuditLogFilter` - Filter options
### 3. Created Analytics/Statistics API (`src/app/api/v1/analytics.py`)
**New Endpoint:**
- `GET /api/v1/analytics/platform-admin/dashboard` - Comprehensive dashboard statistics
**Returns:**
```json
{
"users": {
"total": 12,
"active": 10,
"inactive": 2,
"by_role": {
"platform_admin": 1,
"client_admin": 3,
"field_agent": 5,
"dispatcher": 3
}
},
"organizations": {
"clients": {
"total": 8,
"active": 7,
"inactive": 1
},
"contractors": {
"total": 5,
"active": 4,
"inactive": 1
}
},
"tickets": {
"total": 150,
"by_status": {
"pending": 20,
"assigned": 30,
"in_progress": 25,
"completed": 75
},
"by_type": {
"installation": 80,
"support": 50,
"infrastructure": 20
}
},
"projects": {
"total": 12,
"active": 5
},
"assignments": {
"total": 200,
"active": 45
},
"recent_activity": [
{
"id": "uuid",
"user_email": "admin@example.com",
"action": "create",
"entity_type": "ticket",
"description": "Created new installation ticket",
"created_at": "2025-11-17T20:45:00"
}
// ... up to 10 recent items
],
"system_health": {
"new_users_last_30_days": 5,
"new_tickets_last_30_days": 45
}
}
```
### 4. Updated API Router (`src/app/api/v1/router.py`)
- Added `audit_logs` import and router registration
- Added `analytics` import and router registration
## Testing the Fix
### 1. Start the Backend
```powershell
cd d:\atomio\swiftops-backend
python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 7860
```
### 2. Test Audit Logs Endpoint
```bash
# List audit logs (with auth token)
curl -H "Authorization: Bearer YOUR_TOKEN" \
"https://kamau1-swiftops-backend.hf.space/api/v1/audit-logs?skip=0&limit=100"
# Filter by action
curl -H "Authorization: Bearer YOUR_TOKEN" \
"https://kamau1-swiftops-backend.hf.space/api/v1/audit-logs?action=create&limit=50"
# Export as CSV
curl -H "Authorization: Bearer YOUR_TOKEN" \
"https://kamau1-swiftops-backend.hf.space/api/v1/audit-logs/export/csv"
```
### 3. Test Dashboard Statistics
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
"https://kamau1-swiftops-backend.hf.space/api/v1/analytics/platform-admin/dashboard"
```
## Frontend Integration
### Update Your Dashboard Component
**Before (was failing):**
```typescript
// This was returning 404
const auditLogs = await api.get('/api/v1/audit-logs?skip=0&limit=100');
```
**After (will work now):**
```typescript
// Audit logs endpoint now exists
const auditLogs = await api.get('/api/v1/audit-logs?skip=0&limit=100');
// Also use the new dashboard statistics endpoint
const stats = await api.get('/api/v1/analytics/platform-admin/dashboard');
```
### Recommended Dashboard Data Fetching
```typescript
const fetchDashboardData = async () => {
try {
setLoading(true);
// Get comprehensive statistics
const statsResponse = await api.get('/api/v1/analytics/platform-admin/dashboard');
setStats(statsResponse.data);
// Get recent audit logs (already included in stats, but can fetch separately if needed)
const auditLogsResponse = await api.get('/api/v1/audit-logs?skip=0&limit=100');
setAuditLogs(auditLogsResponse.data);
// These endpoints were already working:
const clients = await api.get('/api/v1/clients?skip=0&limit=100');
const contractors = await api.get('/api/v1/contractors?skip=0&limit=100');
const users = await api.get('/api/v1/users?skip=0&limit=100');
setLoading(false);
} catch (error) {
console.error('Dashboard error:', error);
setError('Failed to load dashboard data');
setLoading(false);
}
};
```
## What's Now Available
### ✅ Working Endpoints
1. `/api/v1/auth/me` - Get current user (was already working)
2. `/api/v1/clients` - List clients (was already working)
3. `/api/v1/contractors` - List contractors (was already working)
4. `/api/v1/users` - List users (was already working)
5. `/api/v1/audit-logs` - **NEW** List/filter/export audit logs
6. `/api/v1/analytics/platform-admin/dashboard` - **NEW** Dashboard statistics
### Dashboard Features You Can Now Build
1. **Statistics Cards**
- Total users, active users, users by role
- Total organizations (clients + contractors)
- Ticket statistics (by status, by type)
- Project and assignment counts
2. **Recent Activity Feed**
- Last 10 audit log entries
- Shows who did what and when
3. **System Health Metrics**
- New users in last 30 days
- New tickets in last 30 days
4. **Audit Logs Page**
- Full audit trail with filtering
- Search by user, action, entity type
- Date range filtering
- CSV export for compliance
## Next Steps
1. **Restart your backend** to load the new endpoints
2. **Update your frontend** to use the new `/api/v1/analytics/platform-admin/dashboard` endpoint
3. **Test the audit logs page** with the new `/api/v1/audit-logs` endpoint
4. **Remove the 404 error handling** since the endpoint now exists
## Authorization Note
All these endpoints require:
- Valid JWT token in `Authorization: Bearer <token>` header
- User must have `platform_admin` role
- The role check is enforced via `@require_role(["platform_admin"])` decorator
If you get 403 Forbidden errors, verify the user's role in the database.