forked from taranjeetsingh9/PetConnectBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
577 lines (516 loc) · 22.4 KB
/
admin.html
File metadata and controls
577 lines (516 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Admin Dashboard - PetConnect</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-100">
<!-- Header -->
<div class="bg-white shadow mb-6">
<div class="max-w-7xl mx-auto flex justify-between items-center p-4">
<h1 class="text-2xl font-bold text-indigo-700">Admin Dashboard - PetConnect</h1>
<div class="flex items-center space-x-4">
<span id="adminInfo" class="text-gray-600">Loading...</span>
<button id="logoutBtn" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded">
Logout
</button>
<button onclick="window.location.href='user-profile.html'"
class="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700">
👤 My Profile
</button>
</div>
</div>
</div>
<div class="max-w-7xl mx-auto p-6">
<!-- Stats Overview -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="bg-white p-6 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Total Users</h3>
<p id="totalUsers" class="text-3xl font-bold text-indigo-600">-</p>
</div>
<div class="bg-white p-6 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Total Pets</h3>
<p id="totalPets" class="text-3xl font-bold text-green-600">-</p>
</div>
<div class="bg-white p-6 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Adoption Requests</h3>
<p id="totalAdoptions" class="text-3xl font-bold text-yellow-600">-</p>
</div>
<div class="bg-white p-6 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Organizations</h3>
<p id="totalOrganizations" class="text-3xl font-bold text-purple-600">-</p>
</div>
</div>
<!-- Navigation Tabs -->
<div class="bg-white rounded-lg shadow-lg mb-6">
<div class="border-b">
<nav class="flex -mb-px">
<button id="tabAnalytics" class="py-4 px-6 font-medium border-b-2 border-indigo-600 text-indigo-600">
📊 Analytics
</button>
<button id="tabUsers" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
👥 User Management
</button>
<button id="tabOrganizations" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
🏢 Organizations
</button>
<button id="tabActivityLogs" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
📋 Activity Logs
</button>
<button id="tabSystem" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
🔧 System Health
</button>
</nav>
</div>
<!-- Tab Content -->
<div class="p-6">
<!-- Analytics Tab -->
<div id="contentAnalytics">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-white p-4 rounded-lg border">
<h3 class="text-lg font-semibold mb-4">User Distribution</h3>
<canvas id="userChart" width="400" height="200"></canvas>
</div>
<div class="bg-white p-4 rounded-lg border">
<h3 class="text-lg font-semibold mb-4">Pet Status Distribution</h3>
<canvas id="petChart" width="400" height="200"></canvas>
</div>
</div>
</div>
<!-- Users Tab -->
<div id="contentUsers" class="hidden">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold">User Management</h2>
<div class="flex space-x-2">
<input type="text" id="userSearch" placeholder="Search users..." class="border p-2 rounded">
<select id="roleFilter" class="border p-2 rounded">
<option value="all">All Roles</option>
<option value="adopter">Adopter</option>
<option value="staff">Staff</option>
<option value="vet">Vet</option>
<option value="trainer">Trainer</option>
<option value="admin">Admin</option>
</select>
</div>
</div>
<div id="usersList" class="space-y-4">
<!-- Users will be loaded here -->
</div>
</div>
<!-- Organizations Tab -->
<div id="contentOrganizations" class="hidden">
<h2 class="text-xl font-semibold mb-4">Organization Management</h2>
<div id="organizationsList" class="space-y-4">
<!-- Organizations will be loaded here -->
</div>
</div>
<!-- Activity Logs Tab -->
<div id="contentActivityLogs" class="hidden">
<h2 class="text-xl font-semibold mb-4">Activity Logs</h2>
<div class="overflow-x-auto">
<table class="min-w-full table-auto border-collapse border border-gray-200">
<thead>
<tr class="bg-indigo-100 text-gray-800">
<th class="border p-2">User</th>
<th class="border p-2">Role</th>
<th class="border p-2">Action</th>
<th class="border p-2">Target</th>
<th class="border p-2">Details</th>
<th class="border p-2">Timestamp</th>
</tr>
</thead>
<tbody id="activityTableBody">
<tr><td colspan="6" class="text-center p-4 text-gray-500">Loading logs...</td></tr>
</tbody>
</table>
</div>
</div>
<!-- System Health Tab -->
<div id="contentSystem" class="hidden">
<h2 class="text-xl font-semibold mb-4">System Health</h2>
<div id="systemHealth" class="space-y-4">
<!-- System health info will be loaded here -->
</div>
</div>
</div>
</div>
</div>
<!-- Loading Overlay -->
<div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg shadow-lg">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
<p class="mt-3 text-gray-600">Loading...</p>
</div>
</div>
<script src="utils.js"></script>
<script>
const ADMIN_API_URL = 'http://localhost:5001/api/admin';
let adminToken = localStorage.getItem('adminToken') || localStorage.getItem('token');
let currentUser = JSON.parse(localStorage.getItem('user') || '{}');
// Initialize dashboard
document.addEventListener('DOMContentLoaded', function() {
if (!adminToken) {
alert('No authentication token found. Please login as admin.');
window.location.href = 'auth.html';
return;
}
// Verify user is admin
if (currentUser.role !== 'admin') {
alert('Access denied. Admin role required.');
window.location.href = 'index.html';
return;
}
document.getElementById('adminInfo').textContent = `Welcome, ${currentUser.name || 'Admin'} | ${currentUser.email || ''}`;
setupTabNavigation();
loadInitialData();
});
function setupTabNavigation() {
const tabs = ['tabAnalytics', 'tabUsers', 'tabOrganizations', 'tabActivityLogs', 'tabSystem'];
const contents = ['contentAnalytics', 'contentUsers', 'contentOrganizations', 'contentActivityLogs', 'contentSystem'];
tabs.forEach(tabId => {
document.getElementById(tabId).addEventListener('click', function() {
// Update tab styles
tabs.forEach(t => {
const tab = document.getElementById(t);
tab.classList.remove('border-indigo-600', 'text-indigo-600');
tab.classList.add('text-gray-500');
});
this.classList.add('border-indigo-600', 'text-indigo-600');
this.classList.remove('text-gray-500');
// Show corresponding content
contents.forEach(contentId => {
document.getElementById(contentId).classList.add('hidden');
});
const contentId = 'content' + tabId.replace('tab', '');
document.getElementById(contentId).classList.remove('hidden');
// Load data when tab is clicked
if (tabId === 'tabUsers') {
loadUsers();
} else if (tabId === 'tabOrganizations') {
loadOrganizations();
} else if (tabId === 'tabActivityLogs') {
loadActivityLogs();
} else if (tabId === 'tabSystem') {
loadSystemHealth();
}
});
});
}
async function loadInitialData() {
showLoading();
try {
await loadAnalytics();
} catch (error) {
console.error('Error loading initial data:', error);
alert('Failed to load data. Please check your connection.');
} finally {
hideLoading();
}
}
async function loadAnalytics() {
try {
const response = await fetch(`${ADMIN_API_URL}/analytics`, {
headers: { 'x-auth-token': adminToken }
});
if (!response.ok) throw new Error('Failed to fetch analytics');
const data = await response.json();
if (data.success) {
const analytics = data.analytics.overview;
// Update stats
document.getElementById('totalUsers').textContent = analytics.totalUsers;
document.getElementById('totalPets').textContent = analytics.totalPets;
document.getElementById('totalAdoptions').textContent = analytics.totalAdoptionRequests;
document.getElementById('totalOrganizations').textContent = analytics.totalOrganizations;
// Create charts
createUserChart(data.analytics.userDistribution);
createPetChart(data.analytics.petDistribution);
}
} catch (error) {
console.error('Error loading analytics:', error);
}
}
function createUserChart(userDistribution) {
const ctx = document.getElementById('userChart').getContext('2d');
const labels = userDistribution.map(item => item._id);
const data = userDistribution.map(item => item.count);
new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: [
'#4F46E5', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom'
}
}
}
});
}
function createPetChart(petDistribution) {
const ctx = document.getElementById('petChart').getContext('2d');
const labels = petDistribution.map(item => item._id);
const data = petDistribution.map(item => item.count);
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Pets',
data: data,
backgroundColor: '#4F46E5'
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
async function loadUsers() {
try {
const response = await fetch(`${ADMIN_API_URL}/users`, {
headers: { 'x-auth-token': adminToken }
});
if (!response.ok) throw new Error('Failed to fetch users');
const data = await response.json();
const container = document.getElementById('usersList');
if (data.success && data.users.length > 0) {
container.innerHTML = data.users.map(user => `
<div class="bg-white border rounded-lg p-4 flex justify-between items-center">
<div>
<h3 class="font-semibold text-indigo-700">${user.name || 'No Name'}</h3>
<p class="text-gray-600">${user.email}</p>
<div class="flex space-x-2 mt-2">
<span class="px-2 py-1 bg-gray-100 text-gray-800 text-sm rounded">${user.role}</span>
<span class="px-2 py-1 ${user.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'} text-sm rounded">
${user.status || 'active'}
</span>
</div>
</div>
<div class="space-x-2">
<button onclick="updateUserRole('${user._id}')" class="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">
Change Role
</button>
${user._id !== currentUser._id ? `
<button onclick="deleteUser('${user._id}')" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
Delete
</button>
` : ''}
</div>
</div>
`).join('');
} else {
container.innerHTML = '<p class="text-center text-gray-500 py-4">No users found</p>';
}
} catch (error) {
console.error('Error loading users:', error);
document.getElementById('usersList').innerHTML = '<p class="text-center text-red-500 py-4">Error loading users</p>';
}
}
async function loadOrganizations() {
try {
const response = await fetch(`${ADMIN_API_URL}/organizations`, {
headers: { 'x-auth-token': adminToken }
});
if (!response.ok) throw new Error('Failed to fetch organizations');
const data = await response.json();
const container = document.getElementById('organizationsList');
if (data.success && data.organizations.length > 0) {
container.innerHTML = data.organizations.map(org => `
<div class="bg-white border rounded-lg p-4">
<h3 class="font-semibold text-indigo-700">${org.name}</h3>
<p class="text-gray-600">Type: ${org.type}</p>
${org.contact ? `
<div class="mt-2 text-sm text-gray-600">
<p><strong>Contact:</strong></p>
${org.contact.email ? `<p>Email: ${org.contact.email}</p>` : ''}
${org.contact.phone ? `<p>Phone: ${org.contact.phone}</p>` : ''}
${org.contact.address ? `<p>Address: ${org.contact.address}</p>` : ''}
${typeof org.contact === 'string' ? `<p>${org.contact}</p>` : ''}
</div>
` : ''}
</div>
`).join('');} else{
container.innerHTML = '<p class="text-center text-gray-500 py-4">No organizations found</p>';
}
} catch (error) {
console.error('Error loading organizations:', error);
document.getElementById('organizationsList').innerHTML = '<p class="text-center text-red-500 py-4">Error loading organizations</p>';
}
}
async function loadActivityLogs() {
try {
const response = await fetch(`${ADMIN_API_URL}/activity-logs`, {
headers: { 'x-auth-token': adminToken }
});
if (!response.ok) throw new Error('Failed to fetch activity logs');
const data = await response.json();
const tableBody = document.getElementById('activityTableBody');
if (data.success && data.logs.length > 0) {
tableBody.innerHTML = data.logs.map(log => `
<tr class="border-b hover:bg-gray-50">
<td class="border p-2">${log.user?.name || "Unknown"}</td>
<td class="border p-2">${log.user?.role || "N/A"}</td>
<td class="border p-2 font-medium text-indigo-700">${log.action}</td>
<td class="border p-2">${log.target || "-"}</td>
<td class="border p-2">${log.details || "-"}</td>
<td class="border p-2 text-gray-500">${new Date(log.createdAt).toLocaleString()}</td>
</tr>
`).join('');
} else {
tableBody.innerHTML = '<tr><td colspan="6" class="text-center p-4 text-gray-500">No activity logs found</td></tr>';
}
} catch (error) {
console.error('Error loading activity logs:', error);
document.getElementById('activityTableBody').innerHTML = '<tr><td colspan="6" class="text-center p-4 text-red-500">Error loading logs</td></tr>';
}
}
async function loadSystemHealth() {
try {
const response = await fetch(`${ADMIN_API_URL}/system-health`, {
headers: { 'x-auth-token': adminToken }
});
if (!response.ok) throw new Error('Failed to fetch system health');
const data = await response.json();
const container = document.getElementById('systemHealth');
if (data.success) {
container.innerHTML = `
<div class="bg-white border rounded-lg p-4">
<h3 class="font-semibold mb-2">System Status</h3>
<div class="space-y-2">
<div class="flex justify-between">
<span>Database:</span>
<span class="px-2 py-1 ${data.healthChecks.database === 'healthy' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'} rounded">
${data.healthChecks.database}
</span>
</div>
<div class="flex justify-between">
<span>Authentication:</span>
<span class="px-2 py-1 ${data.healthChecks.authentication === 'healthy' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'} rounded">
${data.healthChecks.authentication}
</span>
</div>
<div class="flex justify-between">
<span>Server Uptime:</span>
<span>${Math.floor(data.uptime / 60)} minutes</span>
</div>
<div class="flex justify-between">
<span>Last Check:</span>
<span>${new Date(data.timestamp).toLocaleString()}</span>
</div>
</div>
</div>
`;
}
} catch (error) {
console.error('Error loading system health:', error);
document.getElementById('systemHealth').innerHTML = '<p class="text-center text-red-500 py-4">Error loading system health</p>';
}
}
// Utility functions
function updateUserRole(userId) {
const newRole = prompt('Enter new role (adopter, staff, vet, trainer, admin):');
if (newRole && ['adopter', 'staff', 'vet', 'trainer', 'admin'].includes(newRole)) {
// Implement role update functionality
alert(`Would update user ${userId} to role: ${newRole}`);
}
}
function deleteUser(userId) {
if (confirm('Are you sure you want to delete this user?')) {
// Implement delete functionality
alert(`Would delete user: ${userId}`);
}
}
function showLoading() {
document.getElementById('loadingOverlay').classList.remove('hidden');
}
function hideLoading() {
document.getElementById('loadingOverlay').classList.add('hidden');
}
// Logout functionality
document.getElementById('logoutBtn').addEventListener('click', () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = 'auth.html';
});
// Utility functions
async function updateUserRole(userId) {
const newRole = prompt('Enter new role (adopter, staff, vet, trainer, admin):');
if (newRole && ['adopter', 'staff', 'vet', 'trainer', 'admin'].includes(newRole)) {
showLoading();
try {
const response = await fetch(`${ADMIN_API_URL}/users/${userId}/role`, {
method: 'PATCH',
headers: {
'x-auth-token': adminToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({ role: newRole })
});
const data = await response.json();
if (data.success) {
alert('✅ User role updated successfully!');
loadUsers(); // Refresh the list
} else {
throw new Error(data.msg || 'Failed to update role');
}
} catch (error) {
console.error('Error updating role:', error);
alert('❌ Failed to update user role: ' + error.message);
} finally {
hideLoading();
}
} else if (newRole) {
alert('Invalid role. Please use: adopter, staff, vet, trainer, admin');
}
}
async function deleteUser(userId) {
console.log('🔍 Delete function called for user:', userId);
console.log('🔍 Admin token exists:', !!adminToken);
console.log('🔍 Current user ID:', currentUser.id);
if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
console.log('🚀 Sending DELETE request for user:', userId);
showLoading();
try {
const response = await fetch(`${ADMIN_API_URL}/users/${userId}`, {
method: 'DELETE',
headers: {
'x-auth-token': adminToken
}
});
console.log('📡 Response status:', response.status);
console.log('📡 Response headers:', response.headers);
const data = await response.json();
console.log('📡 Response data:', data);
if (data.success) {
alert('✅ User deleted successfully!');
loadUsers(); // Refresh the list
} else {
throw new Error(data.msg || 'Failed to delete user');
}
} catch (error) {
console.error('❌ Error deleting user:', error);
alert('❌ Failed to delete user: ' + error.message);
} finally {
hideLoading();
}
}
}
</script>
</body>
</html>