forked from PRAteek-singHWY/hackoctoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
448 lines (417 loc) Β· 14.2 KB
/
App.js
File metadata and controls
448 lines (417 loc) Β· 14.2 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
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [expenses, setExpenses] = useState([]);
const [description, setDescription] = useState("");
const [amount, setAmount] = useState("");
const [category, setCategory] = useState("General");
const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
const [editId, setEditId] = useState(null);
const [filter, setFilter] = useState("all");
const [searchTerm, setSearchTerm] = useState("");
const [sortBy, setSortBy] = useState("date");
const [budget, setBudget] = useState(1000);
const [showToast, setShowToast] = useState(false);
const [toastMessage, setToastMessage] = useState("");
// Categories with colors
const categories = [
{ value: "Food", color: "#FF6B6B", icon: "π" },
{ value: "Transport", color: "#4ECDC4", icon: "π" },
{ value: "Shopping", color: "#45B7D1", icon: "ποΈ" },
{ value: "Entertainment", color: "#96CEB4", icon: "π¬" },
{ value: "Bills", color: "#FFEAA7", icon: "π" },
{ value: "Health", color: "#DDA0DD", icon: "π₯" },
{ value: "Travel", color: "#98D8C8", icon: "βοΈ" },
{ value: "General", color: "#B2B2B2", icon: "π¦" }
];
// Load expenses from localStorage on component mount
useEffect(() => {
const savedExpenses = localStorage.getItem('expenses');
const savedBudget = localStorage.getItem('budget');
if (savedExpenses) {
setExpenses(JSON.parse(savedExpenses));
}
if (savedBudget) {
setBudget(parseFloat(savedBudget));
}
}, []);
// Save expenses to localStorage whenever expenses change
useEffect(() => {
localStorage.setItem('expenses', JSON.stringify(expenses));
}, [expenses]);
// Save budget to localStorage
useEffect(() => {
localStorage.setItem('budget', budget.toString());
}, [budget]);
// Show toast notification
const showNotification = (message) => {
setToastMessage(message);
setShowToast(true);
setTimeout(() => setShowToast(false), 3000);
};
// Add new expense
const addExpense = () => {
if (!description.trim() || !amount || amount <= 0) {
showNotification("Please enter valid description and amount!");
return;
}
if (editId !== null) {
const updatedExpenses = expenses.map((expense) =>
expense.id === editId
? { ...expense, description, amount: parseFloat(amount), category, date }
: expense
);
setExpenses(updatedExpenses);
setEditId(null);
showNotification("Expense updated successfully! π°");
} else {
const newExpense = {
id: Date.now(),
description: description.trim(),
amount: parseFloat(amount),
category,
date,
createdAt: new Date().toISOString()
};
setExpenses([newExpense, ...expenses]);
showNotification("Expense added successfully! β
");
}
resetFields();
};
// Delete expense with confirmation
const deleteExpense = (id) => {
if (window.confirm("Are you sure you want to delete this expense?")) {
setExpenses(expenses.filter((expense) => expense.id !== id));
showNotification("Expense deleted! ποΈ");
}
};
// Edit expense
const editExpense = (id) => {
const expense = expenses.find((expense) => expense.id === id);
setDescription(expense.description);
setAmount(expense.amount.toString());
setCategory(expense.category);
setDate(expense.date);
setEditId(id);
showNotification("Editing expense... βοΈ");
};
// Reset input fields
const resetFields = () => {
setDescription("");
setAmount("");
setCategory("General");
setDate(new Date().toISOString().split('T')[0]);
};
// Cancel edit
const cancelEdit = () => {
setEditId(null);
resetFields();
showNotification("Edit cancelled");
};
// Filter and sort expenses
const filteredAndSortedExpenses = expenses
.filter(expense => {
const matchesFilter = filter === "all" || expense.category === filter;
const matchesSearch = expense.description.toLowerCase().includes(searchTerm.toLowerCase());
return matchesFilter && matchesSearch;
})
.sort((a, b) => {
switch (sortBy) {
case "amount":
return b.amount - a.amount;
case "date":
return new Date(b.date) - new Date(a.date);
case "category":
return a.category.localeCompare(b.category);
default:
return new Date(b.createdAt) - new Date(a.createdAt);
}
});
// Calculate totals
const totalExpenses = expenses.reduce((acc, expense) => acc + expense.amount, 0);
const remainingBudget = budget - totalExpenses;
const budgetPercentage = (totalExpenses / budget) * 100;
// Calculate category totals
const categoryTotals = categories.map(cat => ({
...cat,
total: expenses
.filter(exp => exp.category === cat.value)
.reduce((sum, exp) => sum + exp.amount, 0)
}));
// Format currency
const formatCurrency = (amount) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(amount);
};
// Format date
const formatDate = (dateString) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
};
return (
<div className="App">
{/* Toast Notification */}
{showToast && (
<div className="toast show">
{toastMessage}
</div>
)}
<h1>π° Expense Tracker</h1>
{/* Budget Section */}
<div className="budget-section">
<div className="budget-input">
<label>Monthly Budget:</label>
<input
type="number"
value={budget}
onChange={(e) => setBudget(parseFloat(e.target.value) || 0)}
min="0"
step="10"
/>
</div>
<div className="budget-progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{
width: `${Math.min(budgetPercentage, 100)}%`,
background: budgetPercentage > 80 ? 'var(--danger-gradient)' :
budgetPercentage > 60 ? 'var(--secondary-gradient)' : 'var(--success-gradient)'
}}
></div>
</div>
<div className="budget-stats">
<span>Spent: {formatCurrency(totalExpenses)}</span>
<span>Remaining: {formatCurrency(remainingBudget)}</span>
<span>{budgetPercentage.toFixed(1)}% of budget</span>
</div>
</div>
</div>
{/* Expense Form */}
<div className="form fade-in">
<div className="input-group">
<input
type="text"
placeholder="What did you spend on?"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="slide-in"
/>
<input
type="number"
placeholder="Amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
min="0"
step="0.01"
className="slide-in"
/>
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="slide-in"
/>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
className="slide-in"
>
{categories.map(cat => (
<option key={cat.value} value={cat.value}>
{cat.icon} {cat.value}
</option>
))}
</select>
</div>
<div className="button-group">
<button onClick={addExpense} className={editId !== null ? "secondary" : ""}>
{editId !== null ? "πΎ Update Expense" : "β Add Expense"}
</button>
{editId !== null && (
<button onClick={cancelEdit} className="secondary">
β Cancel
</button>
)}
</div>
</div>
{/* Controls Section */}
<div className="controls">
<div className="search-box">
<i className="fas fa-search"></i>
<input
type="text"
placeholder="Search expenses..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<select
value={filter}
onChange={(e) => setFilter(e.target.value)}
className="filter-select"
>
<option value="all">All Categories</option>
{categories.map(cat => (
<option key={cat.value} value={cat.value}>
{cat.icon} {cat.value}
</option>
))}
</select>
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
className="sort-select"
>
<option value="date">Sort by Date</option>
<option value="amount">Sort by Amount</option>
<option value="category">Sort by Category</option>
</select>
</div>
{/* Category Summary */}
<div className="category-summary">
<h2>π Spending by Category</h2>
<div className="category-badges">
{categoryTotals.map(cat => (
<div
key={cat.value}
className={`category-badge ${filter === cat.value ? 'active' : ''}`}
onClick={() => setFilter(cat.value)}
style={{
background: cat.total > 0 ? cat.color : 'var(--glass-bg)',
color: cat.total > 0 ? 'white' : 'var(--text-secondary)'
}}
>
<span className="category-icon">{cat.icon}</span>
<span className="category-name">{cat.value}</span>
<span className="category-amount">{formatCurrency(cat.total)}</span>
</div>
))}
</div>
</div>
{/* Expense List */}
<div className="expense-list">
<h2>
π Your Expenses
<span className="expense-count">({filteredAndSortedExpenses.length})</span>
</h2>
{filteredAndSortedExpenses.length === 0 ? (
<div className="empty-state">
<i className="fas fa-receipt"></i>
<p>No expenses found</p>
<p className="empty-subtitle">
{expenses.length === 0
? "Add your first expense to get started!"
: "Try changing your filters or search term"}
</p>
</div>
) : (
<ul>
{filteredAndSortedExpenses.map((expense) => {
const categoryInfo = categories.find(cat => cat.value === expense.category);
return (
<li key={expense.id} className="fade-in">
<div className="expense-info">
<div className="expense-main">
<span className="expense-name">{expense.description}</span>
<span className="expense-amount">{formatCurrency(expense.amount)}</span>
</div>
<div className="expense-meta">
<span
className="expense-category"
style={{ background: categoryInfo?.color }}
>
{categoryInfo?.icon} {expense.category}
</span>
<span className="expense-date">{formatDate(expense.date)}</span>
</div>
</div>
<div className="expense-actions">
<button
onClick={() => editExpense(expense.id)}
className="edit-btn"
>
βοΈ Edit
</button>
<button
onClick={() => deleteExpense(expense.id)}
className="delete-btn"
>
ποΈ Delete
</button>
</div>
</li>
);
})}
</ul>
)}
</div>
{/* Financial Summary */}
<div className="summary">
<h2>π° Financial Summary</h2>
<div className="summary-content">
<div className="summary-item">
<h3>Total Expenses</h3>
<div className="amount">{formatCurrency(totalExpenses)}</div>
</div>
<div className="summary-item">
<h3>Monthly Budget</h3>
<div className="amount">{formatCurrency(budget)}</div>
</div>
<div className="summary-item">
<h3>Remaining</h3>
<div
className="amount"
style={{
color: remainingBudget < 0 ? '#e74c3c' : '#27ae60'
}}
>
{formatCurrency(remainingBudget)}
</div>
</div>
<div className="summary-item">
<h3>Average Daily</h3>
<div className="amount">
{formatCurrency(totalExpenses / new Date().getDate())}
</div>
</div>
</div>
</div>
{/* Quick Actions */}
<div className="quick-actions">
<button
onClick={() => {
if (expenses.length > 0 && window.confirm("Clear all expenses?")) {
setExpenses([]);
showNotification("All expenses cleared! π§Ή");
}
}}
className="secondary"
>
π§Ή Clear All
</button>
<button
onClick={() => {
const dataStr = JSON.stringify(expenses, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "expenses-backup.json";
link.click();
showNotification("Expenses exported! π€");
}}
className="secondary"
>
π€ Export Data
</button>
</div>
</div>
);
}
export default App;