-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainPage.js
More file actions
628 lines (537 loc) · 20.4 KB
/
mainPage.js
File metadata and controls
628 lines (537 loc) · 20.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
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
let expenseChart;
let categoryExpenses = {
'Bills' : 0,
'Food' : 0,
'Transport' : 0,
'Shopping' : 0,
'Others' : 0
};
account = {
balance: 0.00,
income: 0.00,
expense: 0.00
}
function Income(){
if(document.getElementById("amount").value == "" || document.getElementById("amount").value<0){
document.getElementById("transactionAlert").textContent = "Please enter valid amount!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
if(document.getElementById("description").value == ""){
document.getElementById("transactionAlert").textContent = "Please enter description!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
if(document.getElementById("category").value == ""){
document.getElementById("transactionAlert").textContent = "Please select category!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
validateDate();
amount = document.getElementById("amount").value;
account.balance += parseFloat(amount);
account.income += parseFloat(amount);
document.getElementById("balance").innerHTML = "₹ " + account.balance.toFixed(2);
document.getElementById("income").innerHTML = "₹ " + account.income.toFixed(2);
document.getElementById("expense").innerHTML = "₹ " + account.expense.toFixed(2);
updateTransaction("Income", amount);
}
function Expense(){
if(document.getElementById("amount").value == "" || document.getElementById("amount").value<0 ){
document.getElementById("transactionAlert").textContent = "Please enter valid amount!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
if(document.getElementById("description").value == ""){
document.getElementById("transactionAlert").textContent = "Please enter description!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
if(document.getElementById("category").value == ""){
document.getElementById("transactionAlert").textContent = "Please select category!";
document.getElementById("transactionAlert").style.display = "block";
return;
}
else{
document.getElementById("transactionAlert").style.display = "none";
}
if(!validateDate()){
return
}
amount = document.getElementById("amount").value;
const category = document.getElementById("category").value;
account.balance -= parseFloat(amount);
account.expense += parseFloat(amount);
document.getElementById("balance").innerHTML = "₹ " + account.balance.toFixed(2);
document.getElementById("income").innerHTML = "₹ " + account.income.toFixed(2);
document.getElementById("expense").innerHTML = "₹ " + account.expense.toFixed(2);
updateTransaction("Expense", amount);
updateBudgetBar();
if (document.getElementById("budgetBar").style.width === "100%") {
document.getElementById("budgetAlert").textContent = "You have exceeded your budget limit! Please review your expenses.";
document.getElementById("budgetAlert").style.display = "block";
}
else{
document.getElementById("budgetAlert").style.display = "none";
}
if (categoryExpenses.hasOwnProperty(category)) {
categoryExpenses[category] += parseFloat(amount);
} else if (category === 'Salary' || category === 'Business') {
// Skip income categories
} else {
categoryExpenses['Others'] += parseFloat(amount);
}
updateExpenseChart();
}
function updateTransaction(transactionType, amount){
description = document.getElementById("description").value;
category = document.getElementById("category").value;
let dateInput = document.getElementById("date").value;
var table = document.getElementById("transactionTable");
var row = table.insertRow(1);
let displayDate;
if (dateInput){
let dateParts = dateInput.split('-');
displayDate = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
} else {
var today = new Date();
displayDate = today.getDate() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + today.getFullYear();
}
// Insert cells for date, type, and amount
var dateCell = row.insertCell(0);
var typeCell = row.insertCell(1);
var categoryCell = row.insertCell(2);
var descriptionCell = row.insertCell(3);
var amountCell = row.insertCell(4);
dateCell.innerHTML = displayDate;
typeCell.innerHTML = transactionType;
categoryCell.innerHTML = category;
descriptionCell.innerHTML = description;
amountCell.innerHTML = "₹ " + amount;
if(transactionType === "Income") {
typeCell.className = "income-type";
amountCell.className = "income-amount";
} else {
typeCell.className = "expense-type";
amountCell.className = "expense-amount";
}
document.getElementById("amount").value = "";
document.getElementById("amount").focus();
}
function toggleTheme() {
document.body.classList.toggle('dark-theme');
// Save theme preference
const isDarkTheme = document.body.classList.contains('dark-theme');
localStorage.setItem('darkTheme', isDarkTheme);
// Update chart colors if it exists
if (expenseChart) {
expenseChart.destroy();
updateExpenseChart();
}
}
// Restore theme preference on page load
document.addEventListener('DOMContentLoaded', function() {
const isDarkTheme = localStorage.getItem('darkTheme') === 'true';
if (isDarkTheme) {
document.body.classList.add('dark-theme');
}
});
let monthlyBudget = 0;
function openBudgetModal() {
document.getElementById("budgetModal").style.display = "block";
}
function setBudget() {
const budgetInput = document.getElementById("budgetInput").value;
if (budgetInput === '' || parseFloat(budgetInput) <= 0 || isNaN(budgetInput)) {
document.getElementById("modalAlert").textContent = "Please enter a valid budget amount!";
document.getElementById("modalAlert").style.display = "block";
return;
}
monthlyBudget = parseFloat(budgetInput);
document.getElementById("budgetTotal").textContent = `of ₹${monthlyBudget.toFixed(2)}`;
document.getElementById("budgetModal").style.display = "none";
updateBudgetBar();
if (document.getElementById("budgetBar").style.width === "100%") {
document.getElementById("budgetAlert").textContent = "You have exceeded your budget limit! Please review your expenses.";
document.getElementById("budgetAlert").style.display = "block";
}
else{
document.getElementById("budgetAlert").style.display = "none";
}
}
function updateBudgetBar() {
const percentage = (account.expense / monthlyBudget) * 100;
const budgetBar = document.getElementById("budgetBar");
budgetBar.style.width = `${Math.min(percentage, 100)}%`;
document.getElementById('budgetSpent').textContent = `₹${account.expense.toFixed(2)}`;
if (percentage <= 50) {
budgetBar.style.background = '#2ecc71';
} else if (percentage <= 75) {
budgetBar.style.background = '#f1c40f';
} else {
budgetBar.style.background = '#e74c3c';
}
}
window.onclick = function(event) {
const modal = document.getElementById("budgetModal");
if (event.target === modal) {
modal.style.display = "none";
}
}
function updateExpenseChart() {
const ctx = document.getElementById('expenseChart').getContext('2d');
const isDarkTheme = document.body.classList.contains('dark-theme');
if (expenseChart) {
expenseChart.destroy();
}
expenseChart = new Chart(ctx, {
type: 'pie',
data: {
labels: Object.keys(categoryExpenses),
datasets: [{
data: Object.values(categoryExpenses),
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56',
'#4BC0C0',
'#9966FF'
],
hoverBackgroundColor: [
'#FF4F72',
'#2091E8',
'#FFB41F',
'#3AA9A9',
'#8851FF'
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: isDarkTheme ? '#e2e8f0' : '#333333'
}
},
title: {
display: true,
text: 'Expense Distribution by Category',
color: isDarkTheme ? '#e2e8f0' : '#333333',
font: {
size: 16
}
}
}
}
});
}
document.addEventListener('DOMContentLoaded', function() {
updateExpenseChart();
});
function validateDate() {
const dateInput = document.getElementById("date");
const selectedDate = new Date(dateInput.value);
const today = new Date();
if (selectedDate > today) {
document.getElementById("transactionAlert").textContent = "Date cannot be in the future!";
document.getElementById("transactionAlert").style.display = "block";
return false;
}
document.getElementById("transactionAlert").style.display = "none";
return true;
}
function exportData() {
const data = {
account: account,
categoryExpenses: categoryExpenses,
transactions: getTransactionHistory()
};
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'expense-tracker-data.json';
a.click();
}
function importData(file) {
const reader = new FileReader();
reader.onload = function(e) {
const data = JSON.parse(e.target.result);
account = data.account;
categoryExpenses = data.categoryExpenses;
loadTransactionHistory(data.transactions);
updateUI();
saveToLocalStorage();
};
reader.readAsText(file);
}
// Add to mainPage.js
function searchTransactions(query) {
const table = document.getElementById("transactionTable");
const rows = table.getElementsByTagName("tr");
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
const text = row.textContent.toLowerCase();
row.style.display = text.includes(query.toLowerCase()) ? "" : "none";
}
}
function filterTransactions(type) {
const table = document.getElementById("transactionTable");
const rows = table.getElementsByTagName("tr");
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
const transactionType = row.cells[1].textContent;
row.style.display = (type === 'all' || transactionType === type) ? "" : "none";
}
}
function getTransactionHistory() {
const table = document.getElementById("transactionTable");
const transactions = [];
// Start from 1 to skip header row
for(let i = 1; i < table.rows.length; i++) {
const row = table.rows[i];
transactions.push({
date: row.cells[0].textContent,
type: row.cells[1].textContent,
category: row.cells[2].textContent,
description: row.cells[3].textContent,
amount: row.cells[4].textContent.replace('₹ ', '')
});
}
return transactions;
}
function loadTransactionHistory(transactions) {
// Clear existing transactions except header
const table = document.getElementById("transactionTable");
while(table.rows.length > 1) {
table.deleteRow(1);
}
// Load new transactions
transactions.forEach(transaction => {
const row = table.insertRow(1);
const dateCell = row.insertCell(0);
const typeCell = row.insertCell(1);
const categoryCell = row.insertCell(2);
const descriptionCell = row.insertCell(3);
const amountCell = row.insertCell(4);
dateCell.textContent = transaction.date;
typeCell.textContent = transaction.type;
categoryCell.textContent = transaction.category;
descriptionCell.textContent = transaction.description;
amountCell.textContent = '₹ ' + transaction.amount;
if(transaction.type === "Income") {
typeCell.className = "income-type";
amountCell.className = "income-amount";
} else {
typeCell.className = "expense-type";
amountCell.className = "expense-amount";
}
});
}
function updateUI() {
document.getElementById("balance").innerHTML = "₹ " + account.balance.toFixed(2);
document.getElementById("income").innerHTML = "₹ " + account.income.toFixed(2);
document.getElementById("expense").innerHTML = "₹ " + account.expense.toFixed(2);
updateExpenseChart();
updateBudgetBar();
}
function saveToLocalStorage() {
const data = {
account: account,
categoryExpenses: categoryExpenses,
transactions: getTransactionHistory()
};
localStorage.setItem('expenseTrackerData', JSON.stringify(data));
}
function sortTable(n) {
const table = document.getElementById("transactionTable");
let rows = table.rows;
let switching = true;
let direction = "asc";
let shouldSwitch, i;
while (switching) {
switching = false;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
const x = rows[i].getElementsByTagName("TD")[n];
const y = rows[i + 1].getElementsByTagName("TD")[n];
if (!x || !y) continue;
let xValue = x.innerHTML.trim();
let yValue = y.innerHTML.trim();
// Special handling for date and amount columns
if (n === 0) { // Date column
const xDate = convertDateToTimestamp(xValue);
const yDate = convertDateToTimestamp(yValue);
shouldSwitch = direction === "asc" ? xDate > yDate : xDate < yDate;
} else if (n === 4) { // Amount column
const xAmount = parseFloat(xValue.replace('₹ ', ''));
const yAmount = parseFloat(yValue.replace('₹ ', ''));
shouldSwitch = direction === "asc" ? xAmount > yAmount : xAmount < yAmount;
} else {
shouldSwitch = direction === "asc" ? xValue > yValue : xValue < yValue;
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
break;
}
}
if (!switching && direction === "asc") {
direction = "desc";
switching = true;
}
}
}
function convertDateToTimestamp(dateStr) {
const [day, month, year] = dateStr.split('-');
return new Date(`${year}-${month}-${day}`).getTime();
}
// Check authentication at the start
document.addEventListener('DOMContentLoaded', function() {
// First check if user is logged in
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (!currentUser) {
window.location.href = 'login.html';
return;
}
// Initialize user profile
initializeProfile(currentUser);
// Initialize theme
const isDarkTheme = localStorage.getItem('darkTheme') === 'true';
if (isDarkTheme) {
document.body.classList.add('dark-theme');
}
// Initialize existing functionality
updateExpenseChart();
});
function initializeProfile(user) {
const profileInitials = document.getElementById('profileInitials');
const profileName = document.getElementById('profileName');
// Set initials
const initials = user.name.split(' ')
.map(n => n[0])
.join('')
.toUpperCase();
profileInitials.textContent = initials;
// Set name
profileName.textContent = user.name;
}
function toggleProfileMenu() {
const menu = document.getElementById('profileMenu');
menu.classList.toggle('hidden');
// Close menu when clicking outside
const closeMenu = (e) => {
if (!e.target.closest('.profile-preview') && !e.target.closest('.profile-menu')) {
menu.classList.add('hidden');
document.removeEventListener('click', closeMenu);
}
};
setTimeout(() => {
document.addEventListener('click', closeMenu);
}, 0);
}
function editProfile() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const modal = document.getElementById('profileModal');
const nameInput = document.getElementById('editName');
const emailInput = document.getElementById('editEmail');
nameInput.value = currentUser.name;
emailInput.value = currentUser.email;
modal.style.display = 'block';
}
function handleProfileEdit(event) {
event.preventDefault();
const nameInput = document.getElementById('editName');
const emailInput = document.getElementById('editEmail');
const errorElement = document.getElementById('profileError');
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const users = JSON.parse(localStorage.getItem('users'));
// Check if email is taken by another user
if (emailInput.value !== currentUser.email) {
const emailTaken = users.some(u => u.email === emailInput.value && u.email !== currentUser.email);
if (emailTaken) {
errorElement.textContent = 'Email is already taken';
return false;
}
}
// Update user in users array
const userIndex = users.findIndex(u => u.email === currentUser.email);
users[userIndex] = {
...currentUser,
name: nameInput.value,
email: emailInput.value
};
// Update storage
localStorage.setItem('users', JSON.stringify(users));
localStorage.setItem('currentUser', JSON.stringify(users[userIndex]));
// Update UI
initializeProfile(users[userIndex]);
document.getElementById('profileModal').style.display = 'none';
return false;
}
function changePassword() {
document.getElementById('passwordModal').style.display = 'block';
}
function handlePasswordChange(event) {
event.preventDefault();
const currentPassword = document.getElementById('currentPassword').value;
const newPassword = document.getElementById('newPassword').value;
const confirmNewPassword = document.getElementById('confirmNewPassword').value;
const errorElement = document.getElementById('passwordError');
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const users = JSON.parse(localStorage.getItem('users'));
// Validate current password
if (currentPassword !== currentUser.password) {
errorElement.textContent = 'Current password is incorrect';
return false;
}
// Validate new password
if (newPassword.length < 6) {
errorElement.textContent = 'New password must be at least 6 characters long';
return false;
}
if (newPassword !== confirmNewPassword) {
errorElement.textContent = 'New passwords do not match';
return false;
}
// Update password
const userIndex = users.findIndex(u => u.email === currentUser.email);
users[userIndex].password = newPassword;
currentUser.password = newPassword;
// Update storage
localStorage.setItem('users', JSON.stringify(users));
localStorage.setItem('currentUser', JSON.stringify(currentUser));
// Close modal
document.getElementById('passwordModal').style.display = 'none';
return false;
}
function logout() {
localStorage.removeItem('currentUser');
window.location.href = 'login.html';
}
// Add this to close modals when clicking outside
window.onclick = function(event) {
const modals = document.getElementsByClassName('modal');
for (const modal of modals) {
if (event.target === modal) {
modal.style.display = 'none';
}
}
};