-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashboard.html
794 lines (675 loc) · 23.5 KB
/
dashboard.html
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
<!-- dashboard.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dashboard</title>
<style>
/* Reset default margin and padding */
body,
header,
nav,
ul,
li,
footer,
h1,
p {
margin: 0;
padding: 0;
font-family: 'Barlow', sans-serif;
}
* {
box-sizing: border-box;
}
nav {
background-color: #333;
color: white;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.nav-links {
display: flex;
align-items: center;
}
.nav-links a {
color: white;
text-decoration: none;
margin: 0 10px;
}
#home {
padding: 8px 16px;
text-decoration: none;
cursor: pointer;
position: absolute;
top: 15px;
font-size: 20px;
font-weight: 600;
}
#home:hover {
color: #4caf50;
}
#postButton {
position: absolute;
top: 15px;
right: 310px;
}
#galleryButton {
position: absolute;
top: 15px;
right: 210px;
}
#messageButton {
padding: 8px 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
position: absolute;
top: 15px;
right: 100px;
}
#logoutButton {
padding: 8px 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
position: absolute;
top: 15px;
right: 10px;
}
h2,
#totalData,
#addUserButton,
#searchInput,
#totalPerson {
margin: 10px;
}
h2 {
margin-top: 55px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th,
td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
form {
display: none;
}
label {
display: block;
margin-bottom: 8px;
}
/* Update the input width and padding */
input,
select {
width: 50%; /* Adjust the width as needed */
padding: 6px; /* Adjust the padding as needed */
box-sizing: border-box;
}
/* Adjust the button styling */
button {
background-color: #4caf50;
color: #fff;
padding: 8px 16px; /* Adjust the padding as needed */
border: none;
border-radius: 4px;
cursor: pointer;
}
button#delete {
background-color: rgb(214, 0, 0);
color: #fff;
padding: 8px 16px; /* Adjust the padding as needed */
border: none;
border-radius: 4px;
cursor: pointer;
}
/* Style the modal container */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 50%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
/* Style the modal content */
.modal-content {
background-color: #fefefe;
margin: 10% auto;
padding: 10px;
border: 1px solid #888;
width: 80%;
border-radius: 8px;
}
/* Style the close button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Logout button on the right side -->
<a id="home" href="/dashboard.html">VWF</a>
<div class="nav-links">
<a href="/admingallery.html"
><button id="galleryButton">Gallery</button></a
>
<a href="/posts.html"><button id="postButton">Post</button></a>
<button id="logoutButton">Logout</button>
<a href="/message.html"><button id="messageButton">Message</button></a>
</div>
<h2>Hello, Admin</h2>
<div id="totalData"></div>
<!-- Add a modal container -->
<div id="userModal" class="modal">
<div class="modal-content">
<span class="close" onclick="hideUserModal()">×</span>
<!-- Your existing form code goes here -->
<form id="userForm" style="display: block" onsubmit="submitForm(event)">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<label for="username">Email:</label>
<input type="text" id="username" name="username" />
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="Select Gender">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label for="address">Address:</label>
<input type="text" id="address" name="address" />
<label for="guardianName">Guardian Name:</label>
<input type="text" id="guardian_name" name="guardian_name" />
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" />
<label for="role">Role:</label>
<select id="role" name="role">
<option value="Select Role">Select Role</option>
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="child">Child</option>
</select>
<br />
<br />
<button type="submit">Submit</button>
</form>
</div>
</div>
<div id="singleUserModal" class="modal">
<div class="modal-content">
<span class="close" onclick="hideSingleUserModal()">×</span>
<!-- Your existing form code goes here -->
<form
id="userForm"
style="display: block"
onsubmit="submitUserForm(event)"
>
<label for="name">Name:</label>
<input type="text" id="singleName" name="name" />
<label for="username">Email:</label>
<input type="text" id="singleUserName" name="username" />
<label for="gender">Gender:</label>
<select id="singleGender" name="gender">
<option value="Select Gender">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label for="address">Address:</label>
<input type="text" id="singleAddress" name="address" />
<label for="guardianName">Guardian Name:</label>
<input type="text" id="single_guardian_name" name="guardian_name" />
<label for="phone">Phone:</label>
<input type="text" id="singlePhone" name="phone" />
<label for="role">Role:</label>
<select id="singleRole" name="role">
<option value="Select Role">Select Role</option>
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="child">Child</option>
</select>
<input type="hidden" id="userId" name="userId" value="" />
<br />
<br />
<!-- ... (existing form elements) ... -->
<button type="submit">Update</button>
</form>
</div>
</div>
<!-- Add User button -->
<button id="addUserButton">Add User</button> <br />
<!-- Add a search input field with onkeyup attribute -->
<input
type="text"
id="searchInput"
oninput="fetchTotalPerson()"
placeholder="Search by name or guardian name"
onkeyup="handleKeyPress(event)"
/>
<button onclick="fetchTotalPerson()">Search</button>
<h2 id="totalPerson">Total Persons</h2>
<table id="personsTable">
<thead>
<tr>
<th>Name</th>
<th>Guardian Name</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Role</th>
<th>Gender</th>
<th>Action</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="config.js"></script>
<script>
const backendUrl = window.config.backendUrl;
const frontendUrl = window.config.frontendUrl;
const token = localStorage.getItem('token');
async function checkAuthentication() {
try {
const response = await fetch(`${backendUrl}/check-auth`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
});
if (!response.ok) {
console.log(
'Authentication failed. Response status:',
response.status
);
console.log('Response text:', await response.text());
if (response.status === 401) {
// Handle token refresh or ask the user to log in again
console.log(
'Token expired or invalid. Redirecting to login page.'
);
localStorage.removeItem('token');
} else {
// Handle other cases as needed
console.log(
'Other authentication failure. Redirecting to login page.'
);
localStorage.removeItem('token');
}
}
} catch (error) {
console.error('Error fetching data:', error);
console.log('Redirecting to login page due to an error');
localStorage.removeItem('token');
}
if (
!localStorage.getItem('token') &&
window.location.pathname !== '/admin.html'
) {
console.log('Redirecting to login page');
window.location.href = `${frontendUrl}/admin.html`;
return;
}
}
// Call the checkAuthentication function when the page loads
checkAuthentication();
async function fetchTotalPersonData() {
try {
const response = await fetch(`${backendUrl}/api/v1/users`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
});
if (response.ok) {
const data = await response.json();
const admins = data.result.find((person) => person.role == 'admin');
const adminsCount = admins?.count ? admins.count : 0;
const staffs = data.result.find((person) => person.role == 'staff');
const staffsCount = staffs?.count ? staffs.count : 0;
const childrens = data.result.find(
(person) => person.role == 'child'
);
const childrensCount = childrens?.count ? childrens.count : 0;
const totalDataElement = document.getElementById('totalData');
totalDataElement.innerHTML = `Total Admins: ${adminsCount}, Total Staffs: ${staffsCount}, Total Children: ${childrensCount}`;
} else {
console.error(
'Error fetching total children:',
response.statusText
);
}
} catch (error) {
console.error('Error fetching total children:', error);
}
}
// Call the fetchTotalChildren function when the page loads
fetchTotalPersonData();
async function fetchTotalPerson() {
try {
const response = await fetch(`${backendUrl}/api/v1/users/all`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
});
if (response.ok) {
let res;
let data;
res = await response.json();
data = res;
const users = data.users;
let searchTerm;
searchTerm = document.getElementById('searchInput').value.trim();
if (searchTerm) {
data = users.filter(
(user) =>
user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.guardian_name
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
} else {
data = users;
}
const totalPersonElement = document.getElementById('totalPerson');
totalPersonElement.innerHTML = `Total Person: ${data.length}`;
const personsTableBody = document.querySelector(
'#personsTable tbody'
);
personsTableBody.innerHTML = '';
data.forEach((person) => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${person.name}</td>
<td>${
person.guardian_name ? person.guardian_name : 'Not Found'
}</td>
<td>${person.address ? person.address : 'Not Found'}</td>
<td>${person.phone}</td>
<td>${person.username}</td>
<td>${person.role}</td>
<td>${person.gender}</td>
<td><button onclick="editPerson('${
person._id
}')">Edit</button></td>
<td>${
person.role !== 'admin'
? `<button id="delete" onclick="deletePerson('${person._id}')">Del</button>`
: ''
}</td>`;
personsTableBody.appendChild(row);
});
} else {
console.error(
'Error fetching total children:',
response.statusText
);
}
} catch (error) {
console.error('Error fetching total children:', error);
}
}
// Call the fetchTotalChildren function when the page loads
fetchTotalPerson();
// Function to show the modal
function showUserModal() {
const userModal = document.getElementById('userModal');
userModal.style.display = 'block';
}
// Function to hide the modal
function hideUserModal() {
const userModal = document.getElementById('userModal');
userModal.style.display = 'none';
}
// Function to show the modal
function singleUserModal() {
const userModal = document.getElementById('singleUserModal');
userModal.style.display = 'block';
}
// Function to hide the modal
function hideSingleUserModal() {
console.log('clicked');
const userModal = document.getElementById('singleUserModal');
userModal.style.display = 'none';
}
// Click event listener for the "Add User" button
const addUserButton = document.getElementById('addUserButton');
addUserButton.addEventListener('click', showUserModal);
// Click event listener for the close button in the modal
const closeButton = document.querySelector('#userModal .close');
closeButton.addEventListener('click', hideUserModal);
// Click event listener for the close button in the modal
const closeSingleUserEditButton = document.querySelector(
'#singleUserModal .close'
);
closeSingleUserEditButton.addEventListener('click', hideSingleUserModal);
// Click event listener for the form's submit button (to hide the modal after submission)
const submitButton = document.querySelector(
'#userForm button[type="submit"]'
);
submitButton.addEventListener('click', hideUserModal);
// Function to handle form submission
async function submitForm(event) {
event.preventDefault(); // Prevent the default form submission
const nameField = document.getElementById('name');
const genderField = document.getElementById('gender');
const roleField = document.getElementById('role');
if (!nameField.value.trim()) {
alert('Name is required'); // You can customize the validation error handling
return; // Stop form submission if validation fails
}
if (genderField.value === 'Select Gender') {
alert('Gender is required'); // You can customize the validation error handling
return; // Stop form submission if validation fails
}
if (roleField.value === 'Select Role') {
alert('Role is required'); // You can customize the validation error handling
return; // Stop form submission if validation fails
}
// Validate the "email" field
const emailField = document.getElementById('username');
const emailValue = emailField.value.trim();
// Regular expression for a simple email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailValue && !emailRegex.test(emailValue)) {
alert('Please enter a valid email address'); // You can customize the validation error handling
return; // Stop form submission if validation fails
}
// Retrieve form data
const formData = {
name: document.getElementById('name').value,
username: document.getElementById('username').value,
gender: document.getElementById('gender').value,
address: document.getElementById('address').value,
guardian_name: document.getElementById('guardian_name').value,
phone: document.getElementById('phone').value,
role: document.getElementById('role').value,
};
try {
const response = await fetch(`${backendUrl}/api/v1/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(formData),
credentials: 'include',
});
if (response.ok) {
alert('Person added successfully');
// Refresh the data after successful submission
window.location.href = `${frontendUrl}/dashboard.html`;
} else {
console.error('Error submitting form:', response.statusText);
}
} catch (error) {
console.error('Error submitting form:', error);
}
}
// Function to handle editing a person
async function editPerson(personId) {
try {
const response = await fetch(
`${backendUrl}/api/v1/users/${personId}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
}
);
if (response.ok) {
const userData = await response.json();
// Populate the form in the modal with the retrieved data
document.getElementById('singleName').value = userData.user.name;
document.getElementById('singleUserName').value =
userData.user.username;
document.getElementById('singleGender').value =
userData.user.gender;
document.getElementById('singleAddress').value =
userData.user.address;
document.getElementById('single_guardian_name').value =
userData.user.guardian_name;
document.getElementById('singlePhone').value = userData.user.phone;
document.getElementById('singleRole').value = userData.user.role;
// Set the userId in the hidden input field
document.getElementById('userId').value = userData.user._id;
// Show the modal
singleUserModal();
} else {
console.error('Error fetching user data:', response.statusText);
}
} catch (error) {
console.error('Error fetching user data:', error);
}
}
async function submitUserForm(event) {
event.preventDefault();
// Extract user details from the form
const userId = document.getElementById('userId').value;
const formData = {
name: document.getElementById('singleName').value,
username: document.getElementById('singleUserName').value,
gender: document.getElementById('singleGender').value,
address: document.getElementById('singleAddress').value,
guardian_name: document.getElementById('single_guardian_name').value,
phone: document.getElementById('singlePhone').value,
role: document.getElementById('singleRole').value,
};
try {
let response;
if (userId) {
// It's an update, send a PATCH request
response = await fetch(`${backendUrl}/api/v1/users/${userId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
credentials: 'include',
body: JSON.stringify(formData),
});
}
if (response.ok) {
alert('Person updated successfully');
// Handle success, e.g., redirect to the dashboard
window.location.href = `${frontendUrl}/dashboard.html`;
} else {
console.error('Error submitting form:', response.statusText);
}
} catch (error) {
console.error('Error submitting form:', error);
}
}
// Delete User
async function deletePerson(personId) {
// Display a confirmation dialog
const isConfirmed = confirm(
'Are you sure you want to delete this user?'
);
if (isConfirmed) {
try {
const response = await fetch(
`${backendUrl}/api/v1/users/${personId}`,
{
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
}
);
if (response.ok) {
window.location.href = `${frontendUrl}/dashboard.html`;
} else {
console.error('Error deleting user:', response.statusText);
}
} catch (error) {
console.error('Error deleting user:', error);
}
}
}
async function logout() {
try {
const response = await fetch(`${backendUrl}/logout`, {
method: 'GET',
credentials: 'include',
});
if (response.ok) {
// Redirect to the login page after successful logout
localStorage.setItem('token', '');
window.location.href = `${frontendUrl}/admin.html`;
} else {
console.error('Error logging out:', response.statusText);
}
} catch (error) {
console.error('Error logging out:', error);
}
}
// Add click event listener to the logout button
const logoutButton = document.getElementById('logoutButton');
logoutButton.addEventListener('click', logout);
// Function to handle key press in the search input
function handleKeyPress(event) {
if (event.key === 'Enter') {
// If Enter key is pressed, trigger the filterTable function
fetchTotalPerson();
}
}
</script>
</body>
</html>