-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
496 lines (439 loc) · 15.1 KB
/
main.js
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
const welcome = document.querySelector(".logo");
const username = document.querySelector("#username");
const lBtn = document.getElementById("lbtn");
const ul = document.querySelector("ul");
const inputBox = document.querySelector("#inputbox");
const feedback = document.querySelector(".feedback");
const feedback1 = document.querySelector(".feedback1");
const addBtn = document.querySelector("#addbtn");
const regFormDiv = document.querySelector(".regformdiv");
const regForm = document.querySelector("#regform");
const submitBtn = document.querySelector("#submitbtn");
const score1 = document.querySelector(".score1");
const score2 = document.querySelector(".score2");
const score3 = document.querySelector(".score3");
const score4 = document.querySelector(".score4");
let ctasks = 0;
let cdone = 0;
let cundone = 0;
let cpercent = 0;
if (localStorage.getItem("curuser") === null) {
localStorage.setItem("curuser", "none");
}
// Print welcome info
if (localStorage.getItem("curuser") != "none") {
welcome.style.visibility = "visible";
username.innerText = localStorage.getItem("username");
lBtn.innerText = "Logout";
lBtn.style.backgroundColor = "red";
} else {
welcome.style.visibility = "hidden";
lBtn.innerText = "Login";
lBtn.style.backgroundColor = "blue";
}
// Onload call get Todos and display
getTodos();
// Fetch the todos from db ==================================================
function getTodos() {
// const url = "http://127.0.0.1:8000/api/todos";
const url = "https://polar-island-98797.herokuapp.com/api/todos";
fetch(url)
.then((res) => res.json())
.then((data) => {
if (data) {
// Refresh scoreboard count
score1.innerText = data.length;
const doneArr = data.filter((item) => item.status != 0);
score2.innerText = doneArr.length;
score3.innerText = score1.innerText - score2.innerText;
score4.innerText = (
(score2.innerText / score1.innerText) *
100
).toFixed(1);
showTodos(data);
} else {
feedback.innerText = "... you have no scheduled tasks for now.";
}
})
.catch(
(err) =>
(feedback.innerText =
"Bad request or server temporarily down. Try again later.")
);
}
// ==== Display Scoreboard counts
// End of fetch and display section ==========================================
addBtn.addEventListener("click", addTask);
function addTask() {
if (inputBox.value == "" || inputBox.value == 0) {
inputBox.value = "";
notify("Please enter a task in the input box.");
} else {
// const posturl = "http://127.0.0.1:8000/api/todos";
const posturl = "https://polar-island-98797.herokuapp.com/api/todos";
const payload = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: localStorage.getItem("curuser"),
},
body: JSON.stringify({
task: inputBox.value,
status: 0,
}),
};
fetch(posturl, payload)
.then((response) => response.json())
.then((resdata) => {
if (resdata.statuscode == 200) {
getTodos();
} else if ((resdata.message = "Unauthenticated.")) {
notify(
"You are " +
resdata.message +
" Please login to have access to add a Todo."
);
}
})
.catch((err) =>
notify("Bad request or server may be temporarily down. Try again.")
);
}
}
// ====== Display Todos Map function =============================
function showTodos(tdarray) {
ul.innerText = "";
tdarray.map((todo) => {
const li = document.createElement("li");
const p = document.createElement("p");
p.innerText = todo["task"];
li.appendChild(p);
const div1 = document.createElement("div");
const doneBtn = document.createElement("button");
doneBtn.innerText = "Undone";
doneBtn.classList.add("donebtn");
if (todo["status"] == 1) {
doneBtn.classList.add("donebtngreen");
doneBtn.innerText = "Done";
doneBtn.style.border = "1px solid white";
li.style.backgroundColor = "green";
}
div1.appendChild(doneBtn);
const editBtn = document.createElement("button");
editBtn.innerText = "Edit";
editBtn.classList.add("editbtn");
div1.appendChild(editBtn);
const delBtn = document.createElement("button");
delBtn.innerText = "Del";
delBtn.classList.add("delbtn");
div1.appendChild(delBtn);
li.appendChild(div1);
li.classList.add("liclass");
ul.appendChild(li);
inputBox.value = "";
// delBtn ======================================================
delBtn.onclick = function () {
// Send Delete request to db
// const delurl = `http://127.0.0.1:8000/api/todos/${todo["id"]}`;
const delurl = `https://polar-island-98797.herokuapp.com/api/todos/${todo["id"]}`;
const payload = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: localStorage.getItem("curuser"),
},
};
fetch(delurl, payload)
.then((response) => response.json())
.then((resdata) => {
if (resdata.message == "Unauthenticated.") {
notify(
"You are " +
resdata.message +
" You need to be logged in to have delete access."
);
} else {
if (resdata == 1) {
// notify("Todo deleted successfully");
} else {
notify("Todo delete failed. Please try again.");
}
// location.reload();
getTodos();
}
})
.catch((err) => notify("Bad request. Try again."));
};
// EditBtn ====================================================
editBtn.addEventListener("click", () => {
if (editBtn.innerText == "Edit") {
inputBox.value = p.innerText;
editBtn.innerText = "Save";
addBtn.disabled = true;
addBtn.style.backgroundColor = "grey";
// addBtn.innerText = "disabled";
} else {
if (inputBox.value == "" || inputBox.value == 0) {
inputBox.value = "";
notify("Please enter a task in the input box.");
} else {
const completed = 0;
updateTodo(todo["id"], completed, inputBox.value);
}
}
});
function returnebtn() {
editBtn.innerText = "Edit";
inputBox.value = "";
getTodos();
}
// End of editBtn section ====================================
// Done Btn ====================================================
doneBtn.addEventListener("click", () => {
if (doneBtn.innerText == "Undone") {
const completed1 = 1;
updateTodo(todo["id"], completed1, p.innerText);
} else {
const completed2 = 0;
updateTodo(todo["id"], completed2, p.innerText);
}
});
// End of Done Btn section ====================================
});
}
// Search Todos =============================================
function searchTodos() {
let searchitem = inputBox.value;
if (searchitem == "" || searchitem == 0) {
inputBox.value = "";
notify("Please enter a searchitem in the input box.");
} else {
// const searchurl = `http://127.0.0.1:8000/api/todos/search/${searchitem}`;
const searchurl = `https://polar-island-98797.herokuapp.com/api/todos/search/${searchitem}`;
const payload = {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
};
fetch(searchurl)
.then((response) => response.json())
.then((resdata) => {
if (resdata.length > 0) {
ul.innerText = "";
showTodos(resdata);
} else {
ul.innerText = "";
ul.innerHTML = '<li class="liclass">No match found</li>';
}
})
.catch((err) => notify("Failed. There is an issue with the request."));
}
}
// Upadte Todo function ========================================
function updateTodo(todoid, statusState, tasktxt) {
// const updateurl = `http://127.0.0.1:8000/api/todos/${todoid}`;
const updateurl = `https://polar-island-98797.herokuapp.com/api/todos/${todoid}`;
const payload = {
method: "PUT",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: localStorage.getItem("curuser"),
},
body: JSON.stringify({
task: tasktxt,
status: statusState,
}),
};
fetch(updateurl, payload)
.then((response) => response.json())
.then((resdata) => {
if (resdata == 1) {
// doneBtn.style.backgroundColor = 'green';
// doneBtn.innerText = "Done"
getTodos();
} else if (resdata == 0) {
notify("Todo could not be updated. Please try again.");
} else if (resdata.message == "Unauthenticated.") {
notify(
"You are " +
resdata.message +
" Please login to have access to update a Todo."
);
addBtn.disabled = false;
addBtn.style.backgroundColor = "#4785ff";
getTodos();
}
})
.catch((err) => notify("Bad request. Try again."));
}
// =======================================================================
// Registration & Login handler ==========================================
// =======================================================================
regForm.addEventListener("submit", regNewUser);
function regNewUser(e) {
e.preventDefault();
// let formData = new FormData()
const name = document.getElementById("nameinp").value;
const email = document.getElementById("emailinp").value;
const password = document.getElementById("passinp").value;
const password2 = document.getElementById("passinp2").value;
// Handle Registration ============================================
if (submitBtn.value == "Register") {
if (password != password2) {
notify1("Passwords does not match.");
} else {
// const regposturl = "http://127.0.0.1:8000/api/register";
const regposturl =
"https://polar-island-98797.herokuapp.com/api/register";
const payload = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
name: name,
email: email,
password: password,
}),
};
fetch(regposturl, payload)
.then((response) => response.json())
.then((regdata) => {
if (regdata.statuscode == 201) {
notify1("New User Registration successful. Please Login.");
displayLoginForm();
} else if (regdata.statuscode == 402) {
notify1(regdata.message);
} else {
notify1(
regdata.errors.email + "Please register with another email."
);
}
})
.catch((err) => notify1("Bad request. Try again."));
}
} else {
// Handle Login ===================================================
if (!email || !password) {
notify1("Please fill email and password.");
} else {
// const logposturl = "http://127.0.0.1:8000/api/login";
const logposturl = "https://polar-island-98797.herokuapp.com/api/login";
const payload = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
};
fetch(logposturl, payload)
.then((response) => response.json())
.then((logdata) => {
if (logdata.statuscode == 200) {
// Add Bearer to the token
const btoken = `Bearer ${logdata.token}`;
localStorage.setItem("curuser", btoken);
localStorage.setItem("username", logdata.user.name);
lBtn.innerText = "Logout";
welcome.style.visibility = "visible";
username.innerText = logdata.user.name;
regFormDiv.style.display = "none";
document.getElementById("todoarea").style.display = "block";
} else {
notify1("Wrong email or password. Please try again.");
}
})
.catch((err) => notify1("Bad request. Try again."));
}
}
}
// Show Registration form ======================================
function showRegForm() {
if (lBtn.innerText == "Login") {
regFormDiv.style.display = "block";
document.getElementById("nameinp").style.display = "block";
document.getElementById("passinp2").style.display = "block";
document.getElementById("submitbtn").value = "Register";
document.getElementById("todoarea").style.display = "none";
} else {
notify("A user is already logged in. Please log the user out first.");
}
}
// =========================================================
// Handle Logout & Show Login form ===========================
function showLoginForm() {
if (lBtn.innerText == "Logout") {
// console.log("logged out");
// console.log(localStorage.getItem('curuser'));
// const logoposturl = "http://127.0.0.1:8000/api/logout";
const logoposturl = "https://polar-island-98797.herokuapp.com/api/logout";
const payload = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: localStorage.getItem("curuser"),
// Authorization: 'Bearer 17|rFuhKYiD9Z1F6hsoBNbomZSwL2EIaC9aT44jWB6T';
},
};
fetch(logoposturl, payload)
.then((response) => response.json())
.then((logdata) => {
if (logdata.statuscode == 200) {
localStorage.setItem("curuser", "none");
localStorage.setItem("username", "none");
lBtn.innerText = "Login";
welcome.style.visibility = "hidden";
} else if (logdata.message == "Unauthenticated.") {
notify(`You are ${logdata.message}`);
} else {
notify("You are already logged out");
}
})
.catch((err) => notify("Bad request. Try again."));
} else {
displayLoginForm();
}
}
// Display Login form
function displayLoginForm() {
regFormDiv.style.display = "block";
document.getElementById("nameinp").style.display = "none";
document.getElementById("passinp2").style.display = "none";
document.getElementById("submitbtn").value = "Login";
document.getElementById("todoarea").style.display = "none";
}
// Close registration or login form
function closeForm() {
regFormDiv.style.display = "none";
document.getElementById("todoarea").style.display = "block";
}
// Error feedback notification handler
function notify(txt) {
feedback.innerText = txt;
feedback.style.visibility = "visible";
setTimeout(() => {
feedback.style.visibility = "hidden";
}, 3000);
}
function notify1(txt) {
feedback1.innerText = txt;
feedback1.style.visibility = "visible";
setTimeout(() => {
feedback1.style.visibility = "hidden";
feedback1.style.position = "absolute";
}, 3000);
}
// Handle Enter key to add new todo
addEventListener("keypress", (e) => {
if (e.keyCode == 13) addTask();
});