-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpense.html
More file actions
636 lines (579 loc) · 24.7 KB
/
Copy pathexpense.html
File metadata and controls
636 lines (579 loc) · 24.7 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
629
630
631
632
633
634
635
636
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./db.js"></script>
<title>ShareHive - Expense Tracker</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
/* --- Base & Theme (Unchanged) --- */
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
:root {
--bg-color: #f9f9f9;
--text-color: #222;
--primary-color: #0077ff;
--sidebar-bg: #ffffff;
--card-bg: #ffffff;
--border-color: #e0e0e0;
--shadow-color: rgba(0,0,0,0.05);
--danger-color: #f44336;
--success-color: #4caf50;
}
body.dark {
--bg-color: #1e1e1e;
--text-color: #f0f0f0;
--sidebar-bg: #2c2c2c;
--card-bg: #333333;
--border-color: #444;
--shadow-color: rgba(0,0,0,0.2);
}
/* --- Navbar & Sidebar (Unchanged) --- */
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 10px 20px; background: var(--primary-color); color: white; }
.navbar h1 { font-size: 20px; }
.toggle-btn { background: white; border: none; color: var(--primary-color); padding: 5px 10px; border-radius: 5px; cursor: pointer; font-weight: bold; }
.container { display: flex; height: calc(100vh - 50px); }
.sidebar { width: 220px; background: var(--sidebar-bg); padding: 20px; overflow-y: auto; border-right: 1px solid var(--border-color); }
.sidebar h2 { font-size: 16px; margin-bottom: 10px; }
.sidebar a { display: block; text-decoration: none; color: var(--text-color); padding: 8px 10px; border-radius: 5px; margin-bottom: 5px; }
.sidebar a:hover { background: var(--primary-color); color: white; }
/* --- Modern Dashboard Layout --- */
.main { flex: 1; padding: 25px; overflow-y: auto; }
.main-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.main-header h2 { font-size: 24px; margin: 0; }
.add-expense-btn {
padding: 10px 20px; border: none; background: var(--primary-color);
color: white; border-radius: 8px; cursor: pointer; font-weight: bold; font-size: 16px;
}
.dashboard-grid {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 25px;
}
/* Summary Cards */
.summary-cards {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin-bottom: 10px;
}
.summary-card {
background: var(--card-bg);
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 12px var(--shadow-color);
}
.summary-card h3 { font-size: 14px; color: #888; margin-bottom: 8px; font-weight: normal; }
body.dark .summary-card h3 { color: #aaa; }
.summary-card .value { font-size: 24px; font-weight: bold; }
.summary-card .value.total { color: var(--danger-color); }
.summary-card .value.highest { color: var(--primary-color); }
/* Transactions Panel */
.transactions-panel {
background: var(--card-bg);
border-radius: 12px;
box-shadow: 0 4px 12px var(--shadow-color);
padding: 20px;
}
.filters-container {
display: flex;
gap: 15px;
margin-bottom: 20px;
align-items: center;
}
.filters-container select {
padding: 8px;
border-radius: 8px;
border: 1px solid var(--border-color);
background: var(--bg-color);
color: var(--text-color);
flex-grow: 1;
}
.transaction-list { list-style: none; padding: 0; }
.transaction-item {
display: flex;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid var(--border-color);
}
.transaction-item:last-child { border-bottom: none; }
.category-icon {
width: 40px; height: 40px;
border-radius: 50%;
display: grid; place-items: center;
margin-right: 15px;
font-size: 18px;
}
.transaction-details { flex-grow: 1; }
.transaction-details h4 { font-size: 16px; font-weight: 600; }
.transaction-details small { font-size: 12px; color: #888; }
body.dark .transaction-details small { color: #aaa; }
.transaction-amount { font-size: 16px; font-weight: bold; margin-right: 15px; }
.actions button { background: none; border: none; cursor: pointer; font-size: 18px; padding: 5px; color: #888; }
body.dark .actions button { color: #aaa; }
/* Insights Panel */
.insights-panel { display: flex; flex-direction: column; gap: 25px; }
.chart-container {
background: var(--card-bg);
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 12px var(--shadow-color);
}
.chart-container h3 { font-size: 16px; margin-bottom: 15px; text-align: center; }
/* Modal */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: none; justify-content: center; align-items: center; }
.modal { background: var(--bg-color); padding: 25px; border-radius: 12px; width: 90%; max-width: 500px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.modal-header h2 { margin: 0; }
.modal-header .close-btn { font-size: 24px; background: none; border: none; cursor: pointer; color: var(--text-color); }
.form { display: flex; flex-direction: column; gap: 15px; }
.form input, .form select {
width: 100%; padding: 12px; font-size: 14px;
border: 1px solid var(--border-color); border-radius: 8px;
background: var(--card-bg); color: var(--text-color);
}
.form button { padding: 12px; border: none; background: var(--primary-color); color: white; border-radius: 8px; cursor: pointer; font-weight: bold; font-size: 16px; }
</style>
</head>
<body>
<!-- Navbar -->
<div class="navbar">
<h1>🐝 ShareHive - Expense Tracker</h1>
<button class="toggle-btn" onclick="toggleTheme()">🌙</button>
</div>
<div class="container">
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar content remains the same -->
<h2>Menu</h2>
<a href="index.html">🏠 Dashboard</a>
<a href="notes.html">📝 Notes</a>
<a href="bookmarks.html">🔖 Bookmarks</a>
<a href="videos.html">🎬 Video Links</a>
<a href="expense.html"><b>💰 Expense Tracker</b></a>
<a href="planner.html">📅 Planner</a>
<a href="uploads.html">📂 Upload Files</a>
<a href="projects.html">📌 Projects</a>
<a href="watchlist.html">🎥 Watchlist</a>
<a href="courses.html">📚 Courses</a>
<a href="profile.html">👤 Profile</a>
<a href="settings.html">⚙️ Settings</a>
<hr>
<a href="about.html">ℹ️ About</a>
<a href="help.html">❓ Help</a>
<a href="faq.html">❔ FAQ</a>
<a href="blog.html">📰 Blog</a>
<a href="contact.html">✉️ Contact</a>
<a href="join.html">🤝 Join Us</a>
<a href="report.html">🐞 Report</a>
<a href="privacy.html">📜 Privacy & Policy</a>
<a href="community.html">🌍 Community</a>
</div>
<!-- Main Content -->
<div class="main">
<div class="main-header">
<h2>Expense Dashboard</h2>
<button class="add-expense-btn" id="addExpenseBtn">➕ Add Expense</button>
</div>
<div class="summary-cards">
<div class="summary-card">
<h3>Total Spend</h3>
<p class="value total" id="totalSpend">$0.00</p>
</div>
<div class="summary-card">
<h3>Transactions</h3>
<p class="value" id="transactionCount">0</p>
</div>
<div class="summary-card">
<h3>Average Cost</h3>
<p class="value" id="averageCost">$0.00</p>
</div>
<div class="summary-card">
<h3>Highest Expense</h3>
<p class="value highest" id="highestExpense">$0.00</p>
</div>
</div>
<div class="dashboard-grid">
<div class="transactions-panel">
<div class="filters-container">
<select id="timeFilter">
<option value="month">This Month</option>
<option value="last-month">Last Month</option>
<option value="year">This Year</option>
<option value="all">All Time</option>
</select>
<select id="categoryFilter">
<option value="all">All Categories</option>
<!-- Categories loaded dynamically -->
</select>
</div>
<ul class="transaction-list" id="transactionList">
<!-- Transactions loaded dynamically -->
</ul>
</div>
<div class="insights-panel">
<div class="chart-container">
<h3>Category Breakdown</h3>
<canvas id="expensePieChart"></canvas>
</div>
<div class="chart-container">
<h3>Monthly Trends</h3>
<canvas id="expenseBarChart"></canvas>
</div>
</div>
</div>
</div>
</div>
<!-- Add/Edit Expense Modal -->
<div class="modal-overlay" id="expenseModal">
<div class="modal">
<div class="modal-header">
<h2 id="modalTitle">Add New Expense</h2>
<button class="close-btn" id="closeModalBtn">×</button>
</div>
<div class="form">
<input type="text" id="title" placeholder="Expense title (e.g., Coffee with team)">
<input type="number" id="amount" placeholder="Amount" step="0.01">
<input type="text" id="category" placeholder="Category (e.g., Food, Transport)" list="category-list">
<datalist id="category-list"></datalist>
<input type="date" id="date">
<button id="saveBtn">Save Expense</button>
</div>
</div>
</div>
<script>
// 🌙 Dark Mode
const toggleBtn = document.querySelector('.toggle-btn');
function toggleTheme() {
document.body.classList.toggle("dark");
const isDark = document.body.classList.contains("dark");
localStorage.setItem("theme", isDark ? "dark" : "light");
toggleBtn.textContent = isDark ? '☀️' : '🌙';
}
if (localStorage.getItem("theme") === "dark") {
document.body.classList.add("dark");
toggleBtn.textContent = '☀️';
}
const DB_NAME = "ShareHiveDB";
const TARGET_VERSION = 22;
const REQUIRED_STORES = [
"notes","bookmarks","videos","todos","expenses","planner","wiki",
"uploads","projects","watchlist","courses","profile","community"
];
let db = null;
let dbReady = null;
// open DB and create any missing stores in onupgradeneeded
function openAndEnsure(versionTarget = TARGET_VERSION) {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, versionTarget);
req.onupgradeneeded = (e) => {
const d = e.target.result;
REQUIRED_STORES.forEach(name => {
if (!d.objectStoreNames.contains(name)) {
d.createObjectStore(name, { keyPath: "id", autoIncrement: true });
}
});
if (!d.objectStoreNames.contains("expense_categories")) {
d.createObjectStore("expense_categories", { keyPath: "name" });
}
};
req.onsuccess = (e) => {
db = e.target.result;
db.onversionchange = () => { db.close(); console.warn("DB version change detected, connection closed"); };
resolve(db);
};
req.onerror = (e) => reject(e.target.error || e);
});
}
// ensure all required stores exist; if not, reopen with higher version to create them
async function ensureStoresExist() {
if (!db) await openAndEnsure(TARGET_VERSION);
const missing = REQUIRED_STORES.filter(s => !db.objectStoreNames.contains(s));
const needExpenseCategories = !db.objectStoreNames.contains("expense_categories");
if (missing.length === 0 && !needExpenseCategories) return;
// close and bump version to force onupgradeneeded
const newVersion = (db && db.version ? db.version + 1 : TARGET_VERSION + 1);
if (db) db.close();
await openAndEnsure(newVersion);
}
// initialize DB on page load
dbReady = (async () => {
try {
await openAndEnsure(TARGET_VERSION);
// If stores are missing because DB created earlier with different schema, upgrade
await ensureStoresExist();
if (typeof loadInitialData === "function") loadInitialData();
} catch (err) {
console.error("DB init error (expense):", err);
}
})();
// --- Modal Handling ---
const modal = document.getElementById('expenseModal');
const addExpenseBtn = document.getElementById('addExpenseBtn');
const closeModalBtn = document.getElementById('closeModalBtn');
const saveBtn = document.getElementById('saveBtn');
const modalTitle = document.getElementById('modalTitle');
const form = {
title: document.getElementById('title'),
amount: document.getElementById('amount'),
category: document.getElementById('category'),
date: document.getElementById('date'),
};
function openModal(expense = null) {
if (expense) { // Editing
modalTitle.textContent = 'Edit Expense';
saveBtn.textContent = 'Update Expense';
saveBtn.dataset.editId = expense.id;
form.title.value = expense.title;
form.amount.value = expense.amount;
form.category.value = expense.category;
form.date.value = expense.date;
} else { // Adding new
modalTitle.textContent = 'Add New Expense';
saveBtn.textContent = 'Save Expense';
delete saveBtn.dataset.editId;
form.title.value = '';
form.amount.value = '';
form.category.value = '';
form.date.valueAsDate = new Date(); // Default to today
}
modal.style.display = 'flex';
}
function closeModal() { modal.style.display = 'none'; }
addExpenseBtn.onclick = () => openModal();
closeModalBtn.onclick = closeModal;
modal.onclick = (e) => { if (e.target === modal) closeModal(); };
// --- Data Loading and Rendering ---
const categoryColors = {};
const colorPalette = ["#0077ff", "#4caf50", "#ff9800", "#9c27b0", "#f44336", "#795548", "#e91e63", "#2196f3"];
let colorIndex = 0;
function getCategoryColor(category) {
if (!categoryColors[category]) {
categoryColors[category] = colorPalette[colorIndex % colorPalette.length];
colorIndex++;
}
return categoryColors[category];
}
function getCategoryIcon(category) {
const icons = { Food: '🍔', Transport: '🚗', Shopping: '🛍️', Bills: '🧾', Entertainment: '🎬', Health: '💊' };
return icons[category] || category.charAt(0).toUpperCase();
}
async function loadInitialData() {
await populateCategoryFilters();
await displayDashboard();
}
async function populateCategoryFilters() {
return new Promise((resolve, reject) => {
const tx = db.transaction("expense_categories", "readonly");
const store = tx.objectStore("expense_categories");
const req = store.getAll();
req.onsuccess = () => {
const categories = req.result.map(c => c.name).sort();
const filterSelect = document.getElementById('categoryFilter');
const datalist = document.getElementById('category-list');
filterSelect.innerHTML = '<option value="all">All Categories</option>';
datalist.innerHTML = '';
categories.forEach(name => {
filterSelect.innerHTML += `<option value="${name}">${name}</option>`;
datalist.innerHTML += `<option value="${name}">`;
});
resolve();
};
req.onerror = () => reject(req.error);
});
}
async function displayDashboard() {
const tx = db.transaction("expenses", "readonly");
const req = tx.objectStore("expenses").getAll();
req.onsuccess = () => {
let expenses = req.result;
// 1. Apply Filters
const timeFilter = document.getElementById('timeFilter').value;
const categoryFilter = document.getElementById('categoryFilter').value;
const now = new Date();
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const firstDayOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
let filteredExpenses = expenses.filter(exp => {
const expDate = new Date(exp.date);
let timeMatch = false;
if (timeFilter === 'all') timeMatch = true;
if (timeFilter === 'month' && expDate >= firstDayOfMonth) timeMatch = true;
if (timeFilter === 'last-month' && expDate >= firstDayOfLastMonth && expDate < firstDayOfMonth) timeMatch = true;
if (timeFilter === 'year' && expDate >= firstDayOfYear) timeMatch = true;
const categoryMatch = categoryFilter === 'all' || exp.category === categoryFilter;
return timeMatch && categoryMatch;
});
// Sort by most recent
filteredExpenses.sort((a, b) => new Date(b.date) - new Date(a.date));
// 2. Update Summary Cards
const total = filteredExpenses.reduce((sum, exp) => sum + exp.amount, 0);
const count = filteredExpenses.length;
const average = count > 0 ? total / count : 0;
const highest = filteredExpenses.reduce((max, exp) => Math.max(max, exp.amount), 0);
document.getElementById('totalSpend').textContent = `$${total.toFixed(2)}`;
document.getElementById('transactionCount').textContent = count;
document.getElementById('averageCost').textContent = `$${average.toFixed(2)}`;
document.getElementById('highestExpense').textContent = `$${highest.toFixed(2)}`;
// 3. Render Transaction List
const listEl = document.getElementById('transactionList');
listEl.innerHTML = '';
if (filteredExpenses.length === 0) {
listEl.innerHTML = `<li style="text-align: center; padding: 20px; color: #888;">No transactions found.</li>`;
} else {
filteredExpenses.forEach(exp => {
const li = document.createElement('li');
li.className = 'transaction-item';
li.innerHTML = `
<div class="category-icon" style="background-color: ${getCategoryColor(exp.category)}; color: white;">
${getCategoryIcon(exp.category)}
</div>
<div class="transaction-details">
<h4>${exp.title}</h4>
<small>${exp.category} • ${new Date(exp.date).toLocaleDateString()}</small>
</div>
<span class="transaction-amount">$${exp.amount.toFixed(2)}</span>
<div class="actions">
<button onclick="editExpense(${exp.id})" title="Edit">✏️</button>
<button onclick="deleteExpense(${exp.id})" title="Delete">🗑️</button>
</div>
`;
listEl.appendChild(li);
});
}
// 4. Update Charts
updateCharts(filteredExpenses, expenses); // Pass all expenses for trend chart
};
}
// --- CRUD Operations ---
saveBtn.onclick = async () => {
console.log("Save button clicked.");
await dbReady; // wait for DB ready
try {
await ensureStoresExist(); // ensure stores present (may upgrade DB)
} catch (err) {
console.error("Failed to ensure DB stores:", err);
alert("Database schema error. See console.");
return;
}
if (!db) {
console.error("IndexedDB not initialized yet. 'db' object is null.");
alert("Database is not ready. Please try again in a moment.");
return;
}
const title = form.title.value.trim();
const amountRaw = form.amount.value.trim();
const amount = amountRaw === "" ? NaN : Number(parseFloat(amountRaw));
const category = form.category.value.trim();
const date = form.date.value;
if (!title || isNaN(amount) || !category || !date) {
alert("Please fill all fields correctly.");
return;
}
const editId = saveBtn.dataset.editId;
let tx;
try {
tx = db.transaction(["expenses", "expense_categories"], "readwrite");
} catch (e) {
console.error("Failed to create transaction:", e);
// Attempt one upgrade then retry once
try {
await ensureStoresExist();
tx = db.transaction(["expenses", "expense_categories"], "readwrite");
} catch (err) {
console.error("Retry failed to create transaction:", err);
alert("Failed to create database transaction. See console.");
return;
}
}
const expensesStore = tx.objectStore("expenses");
const categoriesStore = tx.objectStore("expense_categories");
tx.onerror = (e) => {
console.error("Transaction error saving expense:", e.target.error);
alert(`Failed to save expense: ${e.target.error?.message || "Unknown error"}. Check console.`);
};
tx.onabort = (e) => {
console.error("Transaction aborted:", e);
alert("Transaction aborted while saving expense.");
};
const expenseData = { title, amount: Number(amount), category, date, updatedAt: new Date().toISOString() };
try {
if (editId) {
expenseData.id = Number(editId);
expensesStore.put(expenseData);
} else {
if ('id' in expenseData) delete expenseData.id;
expensesStore.add(expenseData);
}
categoriesStore.put({ name: category });
tx.oncomplete = () => {
console.log("Transaction completed successfully. Expense saved.");
closeModal();
if (typeof loadInitialData === "function") loadInitialData();
};
} catch (err) {
console.error("Unexpected error during IndexedDB operation:", err);
alert("Failed to save (unexpected error). Check console.");
}
};
function editExpense(id) {
const tx = db.transaction("expenses", "readonly");
const req = tx.objectStore("expenses").get(id);
req.onsuccess = () => openModal(req.result);
}
function deleteExpense(id) {
if (!confirm("Are you sure you want to delete this expense?")) return;
const tx = db.transaction("expenses", "readwrite");
tx.objectStore("expenses").delete(id);
tx.oncomplete = displayDashboard;
}
// --- Chart Logic ---
let pieChart, barChart;
function updateCharts(filteredExpenses, allExpenses) {
const pieCtx = document.getElementById("expensePieChart").getContext("2d");
const barCtx = document.getElementById("expenseBarChart").getContext("2d");
// Pie chart (category breakdown of filtered data)
const categoryTotals = filteredExpenses.reduce((acc, exp) => {
acc[exp.category] = (acc[exp.category] || 0) + exp.amount;
return acc;
}, {});
const pieData = {
labels: Object.keys(categoryTotals),
datasets: [{
data: Object.values(categoryTotals),
backgroundColor: Object.keys(categoryTotals).map(cat => getCategoryColor(cat))
}]
};
if (pieChart) pieChart.destroy();
pieChart = new Chart(pieCtx, { type: "doughnut", data: pieData, options: { responsive: true, plugins: { legend: { display: false } } } });
// Bar chart (monthly trends of all data for context)
const monthlyTotals = allExpenses.reduce((acc, exp) => {
const month = exp.date.slice(0, 7); // YYYY-MM
acc[month] = (acc[month] || 0) + exp.amount;
return acc;
}, {});
const months = Object.keys(monthlyTotals).sort().slice(-6); // Last 6 months
const barData = {
labels: months,
datasets: [{
label: "Monthly Spending",
data: months.map(m => monthlyTotals[m]),
backgroundColor: "#0077ff",
borderRadius: 4
}]
};
if (barChart) barChart.destroy();
barChart = new Chart(barCtx, { type: "bar", data: barData, options: { responsive: true, scales: { y: { beginAtZero: true } } } });
}
// --- Event Listeners ---
document.getElementById('timeFilter').addEventListener('change', displayDashboard);
document.getElementById('categoryFilter').addEventListener('change', displayDashboard);
</script>
</body>
</html>