-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
248 lines (227 loc) · 8.02 KB
/
script.js
File metadata and controls
248 lines (227 loc) · 8.02 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
// Define the base URL for the backend
const BASE_URL = 'http://eco-passport.qatar.cmu.edu:8080'; // Change this to your backend URL
let currentTab = 'users';
// Set the token in localStorage
function setToken() {
const token = document.getElementById('auth-token').value;
if (token) {
localStorage.setItem('authToken', token);
alert('Token set successfully!');
} else {
alert('Please enter a valid token.');
}
}
// Get the token from localStorage
function getToken() {
return localStorage.getItem('authToken');
}
// Helper function to make authenticated fetch requests
async function fetchWithAuth(url, options = {}) {
const token = getToken();
if (!token) {
alert('No token found. Please set the token first.');
return;
}
const headers = {
...options.headers,
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
};
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}
// Fetch and display users
async function fetchUsers() {
try {
const users = await fetchWithAuth(`${BASE_URL}/users/`);
const table = document.getElementById('users-table').getElementsByTagName('tbody')[0];
table.innerHTML = '';
users.forEach(user => {
const row = table.insertRow();
row.innerHTML = `
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.role}</td>
<td>
<button onclick="openUserModal(${user.id})">Edit</button>
<button onclick="deleteUser(${user.id})">Delete</button>
</td>
`;
});
} catch (error) {
console.error('Failed to fetch users:', error);
alert('Failed to fetch users. Please check your token and try again.');
}
}
// Fetch and display events
async function fetchEvents() {
try {
const events = await fetchWithAuth(`${BASE_URL}/events/`);
const table = document.getElementById('events-table').getElementsByTagName('tbody')[0];
table.innerHTML = '';
events.forEach(event => {
const row = table.insertRow();
row.innerHTML = `
<td>${event.id}</td>
<td>${event.name}</td>
<td>${event.location}</td>
<td>${event.start_time}</td>
<td>
<button onclick="openEventModal(${event.id})">Edit</button>
<button onclick="deleteEvent(${event.id})">Delete</button>
</td>
`;
});
} catch (error) {
console.error('Failed to fetch events:', error);
alert('Failed to fetch events. Please check your token and try again.');
}
}
// Show the selected tab
function showTab(tabName) {
currentTab = tabName;
document.querySelectorAll('.tab-content').forEach(tab => {
tab.style.display = 'none';
});
document.getElementById(tabName).style.display = 'block';
if (tabName === 'users') fetchUsers();
else if (tabName === 'events') fetchEvents();
}
// Open user modal for editing or adding
async function openUserModal(userId) {
try {
const modal = document.getElementById('user-modal');
const form = document.getElementById('user-form');
if (userId) {
const user = await fetchWithAuth(`${BASE_URL}/users/${userId}`);
document.getElementById('user-id').value = user.id;
document.getElementById('name').value = user.name;
document.getElementById('email').value = user.email;
document.getElementById('role').value = user.role;
document.getElementById('user-modal-title').innerText = 'Edit User';
} else {
form.reset();
document.getElementById('user-modal-title').innerText = 'Add User';
}
modal.style.display = 'block';
} catch (error) {
console.error('Failed to fetch user:', error);
alert('Failed to fetch user details. Please check your token and try again.');
}
}
// Close user modal
function closeUserModal() {
document.getElementById('user-modal').style.display = 'none';
}
// Save user (add or update)
document.getElementById('user-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const userId = document.getElementById('user-id').value;
const user = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
role: document.getElementById('role').value,
};
const method = userId ? 'PUT' : 'POST';
const url = userId ? `${BASE_URL}/users/${userId}` : `${BASE_URL}/users/`;
await fetchWithAuth(url, {
method,
body: JSON.stringify(user),
});
closeUserModal();
fetchUsers();
} catch (error) {
console.error('Failed to save user:', error);
alert('Failed to save user. Please check your token and try again.');
}
});
// Delete user
async function deleteUser(userId) {
try {
await fetchWithAuth(`${BASE_URL}/users/${userId}`, { method: 'DELETE' });
fetchUsers();
} catch (error) {
console.error('Failed to delete user:', error);
alert('Failed to delete user. Please check your token and try again.');
}
}
// Open event modal for editing or adding
// Open event modal for editing or adding
async function openEventModal(eventId) {
try {
const modal = document.getElementById('event-modal');
const form = document.getElementById('event-form');
if (eventId) {
const event = await fetchWithAuth(`${BASE_URL}/events/${eventId}`);
document.getElementById('event-id').value = event.id;
document.getElementById('event-name').value = event.name;
document.getElementById('location').value = event.location;
document.getElementById('start-time').value = event.start_time ? event.start_time.slice(0, 16) : ''; // Convert to datetime-local format
document.getElementById('end-time').value = event.end_time ? event.end_time.slice(0, 16) : ''; // Convert to datetime-local format
document.getElementById('event-modal-title').innerText = 'Edit Event';
} else {
form.reset();
document.getElementById('event-modal-title').innerText = 'Add Event';
}
modal.style.display = 'block';
} catch (error) {
console.error('Failed to fetch event:', error);
alert('Failed to fetch event details. Please check your token and try again.');
}
}
// Close event modal
function closeEventModal() {
document.getElementById('event-modal').style.display = 'none';
}
// Save event (add or update)
document.getElementById('event-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const eventId = document.getElementById('event-id').value;
const startTime = document.getElementById('start-time').value;
const endTime = document.getElementById('end-time').value;
// Validate start and end times
if ((startTime && !endTime) || (!startTime && endTime)) {
alert('Both start time and end time must be provided or left empty.');
return;
}
if (startTime && endTime && new Date(startTime) >= new Date(endTime)) {
alert('Start time must be before end time.');
return;
}
const event = {
name: document.getElementById('event-name').value,
location: document.getElementById('location').value,
start_time: startTime ? new Date(startTime).toISOString() : null, // Convert to RFC3339 format
end_time: endTime ? new Date(endTime).toISOString() : null, // Convert to RFC3339 format
};
const method = eventId ? 'PATCH' : 'POST';
const url = eventId ? `${BASE_URL}/events/${eventId}` : `${BASE_URL}/events/`;
await fetchWithAuth(url, {
method,
body: JSON.stringify(event),
});
closeEventModal();
fetchEvents();
} catch (error) {
console.error('Failed to save event:', error);
alert('Failed to save event. Please check your token and try again.');
}
});
// Delete event
async function deleteEvent(eventId) {
try {
await fetchWithAuth(`${BASE_URL}/events/${eventId}`, { method: 'DELETE' });
fetchEvents();
} catch (error) {
console.error('Failed to delete event:', error);
alert('Failed to delete event. Please check your token and try again.');
}
}
// Initialize
showTab(currentTab);