-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
500 lines (417 loc) · 15.3 KB
/
client.js
File metadata and controls
500 lines (417 loc) · 15.3 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
// TrackFi Client Side JavaScript
// This file handles the user interface
// Simple comments added in a first-year CS style:
// - short sentences
// - explain what each part does in plain words
// - not too fancy, just helpful for beginners
// Variables to store data
// currentUser: name of the logged-in user (string)
// transactions: array that holds all transaction objects
// nextId: simple counter to give each new transaction a unique id
// currentEditId: id of the transaction currently being edited (or null)
let currentUser = '';
let transactions = [];
let nextId = 1;
let currentEditId = null;
// Get audio elements
// These are audio tags in the HTML. They might be missing files,
// but it's ok: the app will still work without sound.
const successSound = document.getElementById('successSound');
const errorSound = document.getElementById('errorSound');
// When page loads, setup everything
// This runs after the HTML is ready.
document.addEventListener('DOMContentLoaded', function() {
// set up event listeners and restore saved data
setupButtons();
loadData();
});
// Setup all button clicks
function setupButtons() {
// Add event listeners to buttons and links
// This makes the page interactive when you click things.
// Login button: when clicked, try to log the user in
document.getElementById('loginBtn').addEventListener('click', handleLogin);
// Navigation buttons: make top nav and other buttons switch views
let navLinks = document.querySelectorAll('.nav-link');
for (let i = 0; i < navLinks.length; i++) {
navLinks[i].addEventListener('click', function(e) {
e.preventDefault(); // stop the default link behavior
let page = this.getAttribute('data-page');
goToPage(page);
});
}
// Dashboard action buttons (they also have data-page attributes)
let actionButtons = document.querySelectorAll('[data-page]');
for (let i = 0; i < actionButtons.length; i++) {
if (!actionButtons[i].classList.contains('nav-link')) {
actionButtons[i].addEventListener('click', function() {
let page = this.getAttribute('data-page');
goToPage(page);
});
}
}
// Save buttons for income and expense forms
document.getElementById('saveIncomeBtn').addEventListener('click', addIncome);
document.getElementById('saveExpenseBtn').addEventListener('click', addExpense);
// Reset all data button
document.getElementById('resetBtn').addEventListener('click', resetAll);
// Category filter dropdown: when it changes, update summary list
document.getElementById('categoryFilter').addEventListener('change', filterByCategory);
// Modal buttons (edit modal)
document.querySelector('.close').addEventListener('click', closeEditModal);
document.getElementById('saveEditBtn').addEventListener('click', saveEdit);
}
// Handle login
function handleLogin() {
// Get the name from input and show the dashboard if it's valid
let userName = document.getElementById('userName').value;
// simple check: name must not be empty
if (userName === '') {
playError();
alert('Please enter your name');
return;
}
// store user and update greeting text
currentUser = userName;
document.getElementById('userGreeting').textContent = 'Hello, ' + userName;
// Switch views: hide login and show dashboard
document.getElementById('loginPage').classList.remove('active');
document.getElementById('dashboardPage').classList.add('active');
// refresh numbers and lists
updateDashboard();
}
// Navigate to different pages
function goToPage(pageName) {
// Change which nav link looks active and which view is visible
let navLinks = document.querySelectorAll('.nav-link');
for (let i = 0; i < navLinks.length; i++) {
navLinks[i].classList.remove('active');
if (navLinks[i].getAttribute('data-page') === pageName) {
navLinks[i].classList.add('active');
}
}
// hide all views then show the one we want
let views = document.querySelectorAll('.view');
for (let i = 0; i < views.length; i++) {
views[i].classList.remove('active');
}
document.getElementById(pageName + 'View').classList.add('active');
// if user opened the summary page, refresh the list with the selected filter
if (pageName === 'summary') {
filterByCategory();
}
}
// Add income transaction
function addIncome() {
// Read inputs from the form, validate, and add a new income transaction
let name = document.getElementById('incomeName').value;
let amount = parseFloat(document.getElementById('incomeAmount').value);
let description = document.getElementById('incomeDescription').value;
// Check if valid, show error and stop if not
if (!checkValid(name, amount)) {
return;
}
// make the transaction object and add it to the list
let newTransaction = {
id: nextId,
type: 'income',
name: name,
amount: amount,
description: description,
category: null
};
nextId = nextId + 1;
transactions.push(newTransaction);
// play a sound, clear the form, save locally and show changes
playSuccess();
clearIncomeForm();
saveData();
updateDashboard();
goToPage('dashboard');
}
// Add expense transaction
function addExpense() {
// Read inputs and add an expense transaction
let name = document.getElementById('expenseName').value;
let amount = parseFloat(document.getElementById('expenseAmount').value);
let category = document.getElementById('expenseCategory').value;
let description = document.getElementById('expenseDescription').value;
// Validate inputs first
if (!checkValid(name, amount)) {
return;
}
// make the expense object
let newTransaction = {
id: nextId,
type: 'expense',
name: name,
amount: amount,
description: description,
category: category
};
nextId = nextId + 1;
transactions.push(newTransaction);
// give feedback and save
playSuccess();
clearExpenseForm();
saveData();
updateDashboard();
goToPage('dashboard');
}
// Check if inputs are valid
function checkValid(name, amount) {
// Simple validation: name must not be empty, amount must be a positive number
if (name === '') {
playError();
alert('Please enter a name');
return false;
}
if (isNaN(amount) || amount <= 0) {
playError();
alert('Please enter a valid amount greater than 0');
return false;
}
return true;
}
// Calculate totals from transactions
function calculateTotals(transactionList) {
// Add up all incomes and expenses and return totals
let income = 0;
let expenses = 0;
for (let i = 0; i < transactionList.length; i++) {
if (transactionList[i].type === 'income') {
income = income + transactionList[i].amount;
} else {
expenses = expenses + transactionList[i].amount;
}
}
let balance = income - expenses; // how much money is left
return {
balance: balance,
income: income,
expenses: expenses
};
}
// Update dashboard display
function updateDashboard() {
// Update the numbers on the dashboard and refresh the list of transactions
let totals = calculateTotals(transactions);
document.getElementById('totalBalance').textContent = '$' + totals.balance.toFixed(2);
document.getElementById('totalIncome').textContent = '$' + totals.income.toFixed(2);
document.getElementById('totalExpenses').textContent = '$' + totals.expenses.toFixed(2);
// show recent transactions
showTransactions();
}
// Show transactions on dashboard
function showTransactions() {
// Display recent transactions on the dashboard
let list = document.getElementById('transactionsList');
if (transactions.length === 0) {
list.innerHTML = '<div class="empty-state">No transactions yet. Add your first transaction!</div>';
return;
}
list.innerHTML = '';
// Show last 5 transactions (most recent first)
let startIndex = transactions.length - 5;
if (startIndex < 0) {
startIndex = 0;
}
for (let i = transactions.length - 1; i >= startIndex; i--) {
let transaction = transactions[i];
let div = createTransactionDiv(transaction);
list.appendChild(div);
}
}
// Create HTML for one transaction
function createTransactionDiv(transaction) {
// Make a DOM element that shows one transaction
let div = document.createElement('div');
div.className = 'transaction-item ' + transaction.type;
// show category as a small badge if it exists
let categoryBadge = '';
if (transaction.category) {
categoryBadge = '<span class="category-badge">' + transaction.category + '</span>';
}
let sign = transaction.type === 'income' ? '+' : '-';
// Use template string to build inner HTML for the item
div.innerHTML = `
<div class="transaction-info">
<h4>${transaction.name}${categoryBadge}</h4>
<p>${transaction.description || 'No description'}</p>
</div>
<span class="transaction-amount">${sign}$${transaction.amount.toFixed(2)}</span>
<div class="transaction-actions">
<button class="edit-btn" onclick="openEditModal(${transaction.id})">Edit</button>
<button class="delete-btn" onclick="deleteTransaction(${transaction.id})">Delete</button>
</div>
`;
return div;
}
// Delete a transaction
function deleteTransaction(id) {
// Ask the user before deleting
if (!confirm('Are you sure you want to delete this transaction?')) {
return;
}
// Find the transaction in the array and remove it
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].id === id) {
transactions.splice(i, 1);
break;
}
}
// save changes and update UI
saveData();
updateDashboard();
}
// Open edit modal
function openEditModal(id) {
// Open the modal to edit a transaction. Fill the form with current values.
// Find the transaction by id
let transaction = null;
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].id === id) {
transaction = transactions[i];
break;
}
}
if (transaction === null) {
// nothing to edit
return;
}
currentEditId = id;
// fill form fields with the transaction data
document.getElementById('editName').value = transaction.name;
document.getElementById('editAmount').value = transaction.amount;
document.getElementById('editDescription').value = transaction.description || '';
let categoryGroup = document.getElementById('editCategoryGroup');
if (transaction.type === 'expense') {
categoryGroup.style.display = 'block';
document.getElementById('editCategory').value = transaction.category;
} else {
categoryGroup.style.display = 'none';
}
// show the modal
document.getElementById('editModal').classList.add('active');
}
// Close edit modal
function closeEditModal() {
// hide the modal and clear current edit id
document.getElementById('editModal').classList.remove('active');
currentEditId = null;
}
// Save edited transaction
function saveEdit() {
// Save changes made in the edit modal back to the transactions array
let name = document.getElementById('editName').value;
let amount = parseFloat(document.getElementById('editAmount').value);
let description = document.getElementById('editDescription').value;
// validate inputs
if (!checkValid(name, amount)) {
return;
}
// find and update the right transaction
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].id === currentEditId) {
transactions[i].name = name;
transactions[i].amount = amount;
transactions[i].description = description;
if (transactions[i].type === 'expense') {
transactions[i].category = document.getElementById('editCategory').value;
}
break;
}
}
// close modal, save locally and update UI
closeEditModal();
saveData();
updateDashboard();
}
// Reset all transactions
function resetAll() {
// Remove all transactions after confirming with the user
if (!confirm('Are you sure you want to delete all transactions? This cannot be undone.')) {
return;
}
transactions = [];
nextId = 1;
saveData();
updateDashboard();
}
// Filter transactions by category
function filterByCategory() {
// Show transactions that match the selected category in the summary view
let category = document.getElementById('categoryFilter').value;
let list = document.getElementById('summaryTransactionsList');
let filtered = [];
if (category === 'all') {
filtered = transactions;
} else {
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].category === category) {
filtered.push(transactions[i]);
}
}
}
if (filtered.length === 0) {
list.innerHTML = '<div class="empty-state">No transactions found for this category.</div>';
return;
}
list.innerHTML = '';
for (let i = filtered.length - 1; i >= 0; i--) {
let div = createTransactionDiv(filtered[i]);
list.appendChild(div);
}
}
// Format currency
function formatCurrency(amount) {
// Return a string like "$12.34". Always show positive number with $ sign.
return '$' + Math.abs(amount).toFixed(2);
}
// Clear income form
function clearIncomeForm() {
document.getElementById('incomeName').value = '';
document.getElementById('incomeAmount').value = '';
document.getElementById('incomeDescription').value = '';
}
// Clear expense form
function clearExpenseForm() {
document.getElementById('expenseName').value = '';
document.getElementById('expenseAmount').value = '';
document.getElementById('expenseDescription').value = '';
document.getElementById('expenseCategory').value = 'food';
}
// Play success sound
function playSuccess() {
successSound.currentTime = 0;
successSound.play();
}
// Play error sound
function playError() {
errorSound.currentTime = 0;
errorSound.play();
}
// Save data to localStorage (acts like server storage)
function saveData() {
localStorage.setItem('transactions', JSON.stringify(transactions));
localStorage.setItem('nextId', nextId);
}
// Load data from localStorage
function loadData() {
let saved = localStorage.getItem('transactions');
if (saved) {
transactions = JSON.parse(saved);
}
let savedId = localStorage.getItem('nextId');
if (savedId) {
nextId = parseInt(savedId);
}
}
// Functions for testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
calculateTotals: calculateTotals,
checkValid: checkValid,
formatCurrency: formatCurrency
};
}