-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddExpense.html
More file actions
489 lines (441 loc) · 21.4 KB
/
addExpense.html
File metadata and controls
489 lines (441 loc) · 21.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Expense Page</title>
<link rel="stylesheet" href="addexpense.css">
</head>
<body>
<header>
<h2>Daily Expenses</h2>
</header>
<button type="button" class="buyPremiumBtn" id="buyPremiumRazor" onclick="">Buy Premium</button>
<div id="premiumUserText"></div>
<div id="premiumUserLBDivBtn"></div>
<div class="formExpense">
<form onsubmit="submitData(event);">
<label for="money">Enter Money :</label>
<input type="number" name="money" id="inputMoney" required>
<label for="description">Enter Description :</label>
<input type="text" name="description" id="inputDescription" required>
<select id="options">
<option value="food">Food</option>
<option value="petrol">Petrol</option>
<option value="salary">Salary</option>
<option value="bill">Bill</option>
<option value="electricity">Electricity</option>
<option value="maintenance">Maintenance</option>
<option value="insurance">Insurance</option>
<option value="rent">Rent</option>
</select>
<button type="submit">Add Expense</button>
</form>
</div>
<div id="message">
</div>
<h2 style="margin-left: 25px;margin-bottom: 10px;">Expenses List</h2>
<div id="addedExpenses" style="margin: 20px;">
<ol id="olExpenses"></ol>
<div id="paginationButttons"></div>
<label>Number Of Rows : </label>
<select id="numberOfRows">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<hr>
<div>
<h2 id="leaderBoard-header" style="margin-left: 25px;margin-bottom:10px;"></h2>
<ol id="LeaderBoardsList"></ol>
</div>
<hr>
<div id="downloadExpenseBtnDiv">
<button type="button" onclick="downloadEpense();" id="downloadexpense">Download Expense Data</button>
</div>
<hr>
<h2 style="margin-left: 25px;margin-bottom: 10px;">Downloaded Expenses List</h2>
<div id="downloadedExpenses" style="margin: 20px;">
<table id="downloadTable">
<thead>
<tr>
<th>URL</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<hr>
<script>
//event listener for buy premium button razorpay
document.getElementById('buyPremiumRazor').onclick = async (e) => {
console.log('inside buy Premium expense');
const token = localStorage.getItem('token');
console.log('token:' + token);
try {
const response = await axios.get(`http://localhost:3000/purchase/premiummembership`, {
headers: {
"Authorization": token
}
});
console.log('Razorpay response:', response);
const options = {
'key': response.data.key_id,//key id generated from dashboard
'order_id': response.data.order.id, // for one time payement
//to handle the success payement
'handler': async function (response) {
await axios.post(`http://localhost:3000/purchase/updatetransactionstatus`, {
order_id: options.order_id,
payment_id: response.razorpay_payment_id,
},
{ headers: { "Authorization": token } });
alert('You are a premium user now');
document.getElementById('buyPremiumRazor').style.visibility = 'hidden';
document.getElementById('premiumUserText').innerHTML = 'You are a premium user';
}
}
var rzp1 = new Razorpay(options);
rzp1.open();
e.preventDefault();
rzp1.on('payment.failed', function (response) {
console.log('rzp1 response = ' + JSON.stringify(response));
alert(response.error.description);
window.location.href = 'addExpense.html';
})
}
catch (error) {
console.log('Unhandled error:', error);
alert('Something went wrong');
}
}//buyPremiumBtn
//to decode the token
function parseJWT(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
//function to hide the premium button and display the text
function showPremiumuser() {
document.getElementById('buyPremiumRazor').style.visibility = 'hidden';
document.getElementById('premiumUserText').innerHTML = 'You are a premium user';
}
//function to display the leader board details to premium user
function printPremiumLeaderBoardDetails(data) {
const LeaderBoardsListContainer = document.getElementById('LeaderBoardsList');
console.log('name = ' + data.name);
console.log('totalExpenses = ' + data.totalExpenses);
const LBli = document.createElement('li');
const text = document.createTextNode(`Name : ${data.name} - Total Cost : ${data.totalExpenses}`);
LBli.appendChild(text);
LeaderBoardsListContainer.appendChild(LBli);
}//printPremiumLeaderBoardDetails
//to show LeaderBoard
async function showLeaderBoards(val) {
console.log('user id = ' + val.id);
const token = localStorage.getItem('token');
try {
const response = await axios.get(`http://localhost:3000/premium/showLeaderBoard`, {
headers: {
"Authorization": token
}
});
console.log('showLeaderBoards response = ' + JSON.stringify(response));
for (let i = 0; i < response.data.length; i++) {
printPremiumLeaderBoardDetails(response.data[i]);
}
}
catch (error) {
console.log('Unhandled error:', error);
}
}// showLeaderBoards
//function to display the downloaded files by the user
function printAllDownloads(data) {
// console.log('id = ' + data.id);
// console.log('file url = ' + data.URL);
const downloadTable = document.getElementById('downloadTable');
// Create a table row
const newRow = downloadTable.insertRow();
// Insert cells into the row
const fileCell = newRow.insertCell(0);
// Populate the cells with data
fileCell.textContent = data.URL;
}//printAllDownloads
//to print the expense data in list
function printAllExpenses(data) {
console.log('inside printAllExpenses');
// console.log('data = ' + data.id);
// console.log('money = ' + data.money);
// console.log('description = ' + data.description);
// console.log('options = ' + data.options);
const olExpenses = document.getElementById('olExpenses');
const li = document.createElement('li');
const text = document.createTextNode(`Money : ${data.money}, Description : ${data.description},, Options : ${data.options}`);
li.appendChild(text);
const deleteBTN = document.createElement('button');
deleteBTN.id = data.id;
deleteBTN.setAttribute('value', 'Delete');
deleteBTN.textContent = 'Delete';
li.appendChild(deleteBTN);
deleteBTN.addEventListener('click', () => {
deleteExpense(data.id);
})
olExpenses.appendChild(li);
}//printAllExpenses
//global scope so that other functions can also access this variable
let selectedRowOption = 5;
//to get the expense data and to check user is premium or not
document.addEventListener('DOMContentLoaded', async () => {
console.log('inside DOMContentLoaded expense');
const token = localStorage.getItem('token');
console.log('token:' + token);
const decodeToken = parseJWT(token);
console.log('decodeToken:' + JSON.stringify(decodeToken));
const isAdmin = decodeToken.ispremiumuser;
if (isAdmin) {
//if the user is premium then the buy premium will stay hidden and the you are a premium user will be shown
showPremiumuser();
const LBdiv = document.getElementById('leaderBoard-header').innerText = 'LeaderBoard List';
const premiumUserDIV = document.getElementById('premiumUserLBDivBtn');
const showLBtn = document.createElement('button');
showLBtn.setAttribute('type', 'button');
showLBtn.id = decodeToken.userid;
const buttonText = document.createTextNode('Show LeaderBoard');
showLBtn.appendChild(buttonText);
showLBtn.setAttribute('onclick', 'showLeaderBoards(this)');
showLBtn.style.padding = '5px';
showLBtn.style.fontSize = 'small';
showLBtn.style.marginTop = '20px';
showLBtn.style.marginLeft = '20px';
premiumUserDIV.appendChild(showLBtn);
}
//to pagination
let currentPage = 1;
let numberOfRows = document.getElementById('numberOfRows');
//if the user does not select the rows the this function will get called
await fetchExpenseDataPagination(selectedRowOption, currentPage);
const olExpenses = document.getElementById('olExpenses');
numberOfRows.addEventListener('change', async () => {
console.log('inside DOMContentLoaded addEventListener change');
selectedRowOption = numberOfRows.value;
console.log('selectedRowOption = ' + selectedRowOption);
//if the user select the rows the this function will get called
// -5 because if you select 10 as number of rows then number of records will be 15 not 10 records
olExpenses.innerHTML = '';
await fetchExpenseDataPagination(selectedRowOption, currentPage);
})
try {
//get files for download
const res = await axios.get('http://localhost:3000/expense/getFiles', { headers: { "Authorization": token } })
console.log('inside getFiles');
// console.log('res = ', JSON.stringify(res));
showMessage(res.data.message, 'succesMessage');
for (let i = 0; i < res.data.downloadFiles.length; i++) {
printAllDownloads(res.data.downloadFiles[i]);
}
}
catch (error) {
console.log('Unhandled error:', error);
}
})//DOMContentLoaded
//function to get the number of expenses records after user selects number of rows
async function fetchExpenseDataPagination(selectedRowOption, currentPage) {
console.log('inside fetchExpenseDataPagination');
const token = localStorage.getItem('token');
try {
const response = await axios.get(`http://localhost:3000/expense/get-expense?page=${currentPage}&numberOfRows=${selectedRowOption}`, {
headers: {
"Authorization": token
}
});
//to print the expense data
const expenseData = response.data.expenses;
for (let i = 0; i < expenseData.length; i++) {
printAllExpenses(expenseData[i]);
}
handleNavigationButtons(response.data);
}
catch (error) {
console.log('Unhandled error:', error);
}
}//fetchExpenseDataPagination
// Function to handle pagination buttons
function handleNavigationButtons({ currentPage, hasNextPage, nextPage, hasPreviousPage, previousPage, lastPage }) {
console.log('inside andleNavigationButtons');
console.log('currentPage = ' + currentPage);
console.log('hasNextPage = ' + hasNextPage);
console.log('nextPage = ' + nextPage);
console.log('hasPreviousPage = ' + hasPreviousPage);
console.log('previousPage = ' + previousPage);
console.log('lastPage = ' + lastPage);
console.log('selectedRowOption = ' + selectedRowOption);
const paginationButttons = document.getElementById('paginationButttons');
const olExpenses = document.getElementById('olExpenses');
paginationButttons.innerHTML = '';
if (hasPreviousPage) {
const prevButton = document.createElement('button');
prevButton.innerHTML = `<h3>${previousPage}</h3>`;
prevButton.style.marginRight = '15px';
prevButton.addEventListener('click', function () {
olExpenses.innerHTML = '';
getExpenses(previousPage);
});
paginationButttons.appendChild(prevButton);
}
const currentButton = document.createElement('button');
currentButton.innerHTML = `<h4>${currentPage}</h4>`;
currentButton.style.marginRight = '15px';
currentButton.addEventListener('click', function () {
location.reload();
});
paginationButttons.appendChild(currentButton);
if (hasNextPage) {
const nextButton = document.createElement('button');
nextButton.innerHTML = `<h4>${nextPage}</h4>`;
nextButton.style.marginRight = '15px';
nextButton.addEventListener('click', function () {
olExpenses.innerHTML = '';
getExpenses(nextPage);
});
paginationButttons.appendChild(nextButton);
}
}//handleNavigationButtons
//to get the pages and print as pagination
async function getExpenses(page) {
console.log('inside getExpenses');
console.log('selectedRowOption = ' + selectedRowOption);
const token = localStorage.getItem('token');
const response = await axios.get(`http://localhost:3000/expense/get-expense?page=${page}
&numberOfRows=${selectedRowOption}`, {
headers: {
"Authorization": token
}
});
//to print the expense data
const expenseData = response.data.expenses;
for (let i = 0; i < expenseData.length; i++) {
printAllExpenses(expenseData[i]);
}
handleNavigationButtons(response.data);
}
//function to show download option and daily weekly expenses
async function downloadEpense() {
console.log('inside download function');
try {
const token = localStorage.getItem('token');
const res = await axios.get('http://localhost:3000/expense/download', { headers: { "Authorization": token } })
// console.log('res = ', JSON.stringify(res));
var a = document.createElement("a");
a.href = res.data.fileUrl;
a.download = 'myexpense.csv';
a.click();
showMessage('Download Started', 'succesMessage');
}
catch (error) {
if (error.response.status === 401) {
console.log("error message = " + error.response.data.message);
showMessage(error.response.data.message, 'failureMessage');
}
else if (error.response.status === 400) {
console.log("error message = " + error.response.data.error.message);
showMessage(error.response.data.error.message, 'failureMessage');
}
else {
console.log("error message = " + error);
showMessage(error, 'failureMessage');
}
}
}//downloadEpense
//function to display the message
function showMessage(msgText, className) {
const msg = document.getElementById('message');
const div = document.createElement('div');
const textNode = document.createTextNode(msgText);
div.appendChild(textNode);
msg.appendChild(div);
msg.classList.add(className);
setTimeout(() => {
msg.classList.remove(className);
msg.removeChild(div);
}, 2000);
}
async function submitData(event) {
event.preventDefault();
console.log('inside submitData expense');
// Get values from the form
const money = document.getElementById('inputMoney').value;
const description = document.getElementById('inputDescription').value;
const options = document.getElementById('options').value;
console.log('money = ' + money);
console.log('description = ' + description);
console.log('options = ' + options);
const obj = {
money: money,
description: description,
options: options
}
try {
const token = localStorage.getItem('token');
console.log('token:' + token);
const response = await axios.post(`http://localhost:3000/expense/add-expense`, obj, {
headers: {
"Authorization": token
}
});
console.log('response data = ' + JSON.stringify(response.data));
console.log('money = ' + response.data.newExpenseData.money);
console.log('description = ' + response.data.newExpenseData.description);
console.log('options = ' + response.data.newExpenseData.options);
document.getElementById('inputMoney').value = "";
document.getElementById('inputDescription').value = "";
document.getElementById('options').value = "";
showMessage(response.data.message, 'succesMessage');
printAllExpenses(response.data.newExpenseData);
}
catch (error) {
//to handle the output response errors
if (error.response && error.response.status == 400) {
console.log('Error object:', error.response.data.message);
showMessage(error.response.data.message, 'failureMessage');
} else {
console.log('Unhandled error:', error);
// Handle other errors here
}
}
}//submitData
async function deleteExpense(id) {
console.log('id:', id);
console.log('inside deleteExpense expense');
//to delete data from backend
const token = localStorage.getItem('token');
try {
const response = await axios.delete(`http://localhost:3000/expense/delete-expense/${id}`, { headers: { "Authorization": token } });
console.log('response:', response);
showMessage(response.data.message, 'succesMessage');
}
catch (error) {
//to handle the output response errors
if (error.response && error.response.status == 400) {
console.log('Error object:', error.response.data.message);
} else {
console.log('Unhandled error:', error);
}
}
//to delete data from frotend
const parentele = document.getElementById(id).parentNode;
olExpenses.removeChild(parentele);
}//deleteExpense
</script>
<!-- axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- razorpay -->
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</body>
</html>