-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
361 lines (312 loc) Β· 11.5 KB
/
script.js
File metadata and controls
361 lines (312 loc) Β· 11.5 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
class ExpenseTracker {
constructor() {
this.expenses = this.loadExpenses();
this.chart = null;
this.initializeApp();
}
initializeApp() {
this.bindEvents();
this.setDefaultDate();
this.updateDisplay();
this.initializeChart();
}
bindEvents() {
document.getElementById('expense-form').addEventListener('submit', (e) => {
e.preventDefault();
this.addExpense();
});
document.getElementById('filter-category').addEventListener('change', (e) => {
this.filterExpenses(e.target.value);
});
this.addClearAllButton();
}
setDefaultDate() {
const today = new Date().toISOString().split('T')[0];
document.getElementById('date').value = today;
}
addExpense() {
const description = document.getElementById('description').value.trim();
const amount = parseFloat(document.getElementById('amount').value);
const category = document.getElementById('category').value;
const date = document.getElementById('date').value;
if (!description || !amount || !category || !date) {
this.showNotification('Please fill in all fields', 'error');
return;
}
if (amount <= 0) {
this.showNotification('Amount must be greater than 0', 'error');
return;
}
const expense = {
id: Date.now(),
description,
amount,
category,
date,
timestamp: new Date().toISOString()
};
this.expenses.unshift(expense);
this.saveExpenses();
this.updateDisplay();
this.clearForm();
this.showNotification('Expense added successfully!', 'success');
document.getElementById('expense-form').classList.add('form-submitted');
setTimeout(() => {
document.getElementById('expense-form').classList.remove('form-submitted');
}, 600);
}
deleteExpense(id) {
if (confirm('Are you sure you want to delete this expense?')) {
this.expenses = this.expenses.filter(expense => expense.id !== id);
this.saveExpenses();
this.updateDisplay();
this.showNotification('Expense deleted successfully!', 'success');
}
}
filterExpenses(category) {
const filteredExpenses = category ?
this.expenses.filter(expense => expense.category === category) :
this.expenses;
this.displayExpenses(filteredExpenses);
}
updateDisplay() {
this.displayExpenses(this.expenses);
this.updateStats();
this.updateChart();
}
displayExpenses(expenses) {
const expenseList = document.getElementById('expense-list');
if (expenses.length === 0) {
expenseList.innerHTML = `
<div class="empty-state">
<p>No expenses found. ${this.expenses.length === 0 ? 'Add your first expense to get started!' : 'Try changing the filter.'}</p>
</div>
`;
return;
}
expenseList.innerHTML = expenses.map(expense => `
<div class="expense-item category-${expense.category}">
<div class="expense-details">
<div class="expense-description">${expense.description}</div>
<div class="expense-meta">
<span class="expense-category">${this.getCategoryIcon(expense.category)} ${this.getCategoryName(expense.category)}</span>
<span>${this.formatDate(expense.date)}</span>
</div>
</div>
<div class="expense-amount">$${expense.amount.toFixed(2)}</div>
<button class="delete-btn" onclick="expenseTracker.deleteExpense(${expense.id})">
Delete
</button>
</div>
`).join('');
}
updateStats() {
const totalExpenses = this.expenses.reduce((sum, expense) => sum + expense.amount, 0);
const expenseCount = this.expenses.length;
const avgExpense = expenseCount > 0 ? totalExpenses / expenseCount : 0;
const topCategory = this.getTopCategory();
document.getElementById('total-balance').textContent = totalExpenses.toFixed(2);
document.getElementById('total-expenses').textContent = `$${totalExpenses.toFixed(2)}`;
document.getElementById('expense-count').textContent = expenseCount;
document.getElementById('avg-expense').textContent = `$${avgExpense.toFixed(2)}`;
document.getElementById('top-category').textContent = topCategory;
}
getTopCategory() {
if (this.expenses.length === 0) return 'None';
const categoryTotals = {};
this.expenses.forEach(expense => {
categoryTotals[expense.category] = (categoryTotals[expense.category] || 0) + expense.amount;
});
const topCategory = Object.keys(categoryTotals).reduce((a, b) =>
categoryTotals[a] > categoryTotals[b] ? a : b
);
return this.getCategoryName(topCategory);
}
initializeChart() {
const ctx = document.getElementById('expense-chart').getContext('2d');
this.chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [],
datasets: [{
data: [],
backgroundColor: [
'#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4',
'#feca57', '#ff9ff3', '#54a0ff', '#5f27cd'
],
borderWidth: 2,
borderColor: '#fff'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
labels: {
padding: 20,
usePointStyle: true
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.parsed;
const total = context.dataset.data.reduce((a, b) => a + b, 0);
const percentage = ((value / total) * 100).toFixed(1);
return `${label}: $${value.toFixed(2)} (${percentage}%)`;
}
}
}
}
}
});
}
updateChart() {
if (!this.chart) return;
const categoryTotals = {};
this.expenses.forEach(expense => {
categoryTotals[expense.category] = (categoryTotals[expense.category] || 0) + expense.amount;
});
const labels = Object.keys(categoryTotals).map(cat => this.getCategoryName(cat));
const data = Object.values(categoryTotals);
this.chart.data.labels = labels;
this.chart.data.datasets[0].data = data;
this.chart.update();
}
getCategoryName(category) {
const categories = {
food: 'Food & Dining',
transport: 'Transportation',
shopping: 'Shopping',
entertainment: 'Entertainment',
bills: 'Bills & Utilities',
health: 'Healthcare',
education: 'Education',
other: 'Other'
};
return categories[category] || category;
}
getCategoryIcon(category) {
const icons = {
food: 'π',
transport: 'π',
shopping: 'ποΈ',
entertainment: 'π¬',
bills: 'π‘',
health: 'π₯',
education: 'π',
other: 'π¦'
};
return icons[category] || 'π¦';
}
formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
}
clearForm() {
document.getElementById('expense-form').reset();
this.setDefaultDate();
}
showNotification(message, type = 'success') {
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
Object.assign(notification.style, {
position: 'fixed',
top: '20px',
right: '20px',
padding: '15px 20px',
borderRadius: '8px',
color: 'white',
fontWeight: '600',
zIndex: '1000',
animation: 'slideInRight 0.3s ease',
backgroundColor: type === 'success' ? '#4caf50' : '#f44336'
});
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
addClearAllButton() {
const clearAllBtn = document.createElement('button');
clearAllBtn.textContent = 'Clear All Expenses';
clearAllBtn.className = 'btn';
clearAllBtn.style.marginTop = '20px';
clearAllBtn.style.background = 'linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%)';
clearAllBtn.addEventListener('click', () => {
if (this.expenses.length === 0) {
this.showNotification('No expenses to clear', 'error');
return;
}
if (confirm('Are you sure you want to delete all expenses? This action cannot be undone.')) {
this.expenses = [];
this.saveExpenses();
this.updateDisplay();
this.showNotification('All expenses cleared!', 'success');
}
});
document.querySelector('.stats-section').appendChild(clearAllBtn);
}
saveExpenses() {
try {
} catch (error) {
console.error('Error saving expenses:', error);
}
}
loadExpenses() {
try {
return [];
} catch (error) {
console.error('Error loading expenses:', error);
return [];
}
}
exportData() {
const dataStr = JSON.stringify(this.expenses, null, 2);
const dataBlob = new Blob([dataStr], {type: 'application/json'});
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = 'expenses.json';
link.click();
URL.revokeObjectURL(url);
}
}
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(100%);
opacity: 0;
}
}
`;
document.head.appendChild(style);
const expenseTracker = new ExpenseTracker();