-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
594 lines (512 loc) · 20.8 KB
/
Copy pathscript.js
File metadata and controls
594 lines (512 loc) · 20.8 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
// Global variables
let allMonthsData = {}; // Stores { "January 2024": { transactions: [], income: 200, savingsGoal: 3000, currentSavings: 500 } }
let currentMonth = "January 2026";
let budgetChart = null;
// Month names for navigation
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
loadAllData();
setupMonthDropdown();
showPage('transactions');
updateBillCountdown();
setInterval(updateBillCountdown, 86400000); // 24 hours
});
// Load all data from localStorage
function loadAllData() {
const saved = localStorage.getItem('budgetMonthsData');
if (saved) {
allMonthsData = JSON.parse(saved);
}
// Initialize current month if it doesn't exist
if (!allMonthsData[currentMonth]) {
allMonthsData[currentMonth] = {
transactions: [],
income: 200,
savingsGoal: 3000,
currentSavings: 500
};
saveAllData();
}
loadCurrentMonth();
}
// Save all data to localStorage
function saveAllData() {
localStorage.setItem('budgetMonthsData', JSON.stringify(allMonthsData));
}
// Setup month dropdown
function setupMonthDropdown() {
const dropdown = document.getElementById('monthDropdown');
dropdown.innerHTML = '';
// Get all months that have data, sorted chronologically
const existingMonths = Object.keys(allMonthsData).sort((a, b) => {
// Sort by year, then month
const [monthA, yearA] = a.split(' ');
const [monthB, yearB] = b.split(' ');
if (yearA !== yearB) return parseInt(yearA) - parseInt(yearB);
return months.indexOf(monthA) - months.indexOf(monthB);
});
// If no months exist, just show current month
if (existingMonths.length === 0) {
existingMonths.push(currentMonth);
}
// Add options to dropdown
existingMonths.forEach(month => {
const option = document.createElement('option');
option.value = month;
option.textContent = month;
if (month === currentMonth) {
option.selected = true;
}
dropdown.appendChild(option);
});
updateMonthInfo();
}
// Update month info display
function updateMonthInfo() {
const monthData = allMonthsData[currentMonth];
const transactionCount = monthData?.transactions?.length || 0;
const totalSpent = monthData?.transactions?.reduce((sum, t) => sum + t.amount, 0) || 0;
document.getElementById('monthInfo').innerHTML = `
${transactionCount} transactions • Total: $${totalSpent.toFixed(2)} •
${transactionCount > 0 ? 'Data saved' : 'Add your first transaction'}
`;
}
// Switch to a different month
function switchMonth(month) {
currentMonth = month;
loadCurrentMonth();
// If on dashboard page, update it
if (document.getElementById('dashboard').style.display !== 'none') {
updateDashboardFromTransactions();
}
updateMonthInfo();
}
// Load current month's data
function loadCurrentMonth() {
const monthData = allMonthsData[currentMonth];
if (!monthData) return;
// Update transaction list
renderTransactions();
// Update dashboard inputs
document.getElementById('monthlyIncome').value = monthData.income || 200;
document.getElementById('savingsGoal').value = monthData.savingsGoal || 3000;
document.getElementById('currentSavings').value = monthData.currentSavings || 500;
// Update month display
document.getElementById('transactionMonthTitle').textContent = currentMonth + " Transactions";
document.getElementById('dashboardMonthTitle').textContent = currentMonth + " Dashboard";
// Update dropdown selection
const dropdown = document.getElementById('monthDropdown');
if (dropdown) {
dropdown.value = currentMonth;
}
// Update dashboard
updateDashboardFromTransactions();
updateMonthInfo();
}
// Add a new month
function addNewMonth() {
// Get all existing months to find the latest
const existingMonths = Object.keys(allMonthsData);
let latestMonth = "January 2026";
let latestYear = 2026;
let latestMonthIndex = 0;
// Find the latest month
existingMonths.forEach(month => {
const [monthName, yearStr] = month.split(' ');
const year = parseInt(yearStr);
const monthIndex = months.indexOf(monthName);
if (year > latestYear || (year === latestYear && monthIndex > latestMonthIndex)) {
latestYear = year;
latestMonthIndex = monthIndex;
latestMonth = month;
}
});
// Calculate next month
const [latestMonthName, latestYearStr] = latestMonth.split(' ');
const nextMonthIndex = (months.indexOf(latestMonthName) + 1) % 12;
const nextYear = parseInt(latestYearStr) + (nextMonthIndex === 0 ? 1 : 0);
const newMonthName = months[nextMonthIndex] + " " + nextYear;
// Create new month if it doesn't exist
if (!allMonthsData[newMonthName]) {
allMonthsData[newMonthName] = {
transactions: [],
income: allMonthsData[latestMonth]?.income || 200, // Copy income from previous month
savingsGoal: allMonthsData[latestMonth]?.savingsGoal || 3000,
currentSavings: allMonthsData[latestMonth]?.currentSavings || 500
};
saveAllData();
setupMonthDropdown();
}
// Switch to new month
switchMonth(newMonthName);
}
// Page navigation
function showPage(pageId) {
// Hide all pages
document.querySelectorAll('.transaction-page, .dashboard-page').forEach(page => {
page.style.display = 'none';
});
// Show selected page
document.getElementById(pageId).style.display = 'block';
// Update navigation buttons
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`.nav-btn[onclick="showPage('${pageId}')"]`).classList.add('active');
// If showing dashboard, update it
if (pageId === 'dashboard') {
updateDashboardFromTransactions();
}
}
// Transaction Management
function addTransaction() {
const description = document.getElementById('description').value.trim();
const category = document.getElementById('category').value;
const amount = parseFloat(document.getElementById('amount').value);
if (!description || isNaN(amount) || amount <= 0) {
alert('Please enter a description and valid amount.');
return;
}
const transaction = {
id: Date.now(), // Unique ID
description: description,
category: category,
amount: amount,
date: new Date().toLocaleDateString('en-CA') // YYYY-MM-DD format
};
// Add to current month's transactions
allMonthsData[currentMonth].transactions.push(transaction);
saveAllData();
renderTransactions();
// Clear form
document.getElementById('description').value = '';
document.getElementById('amount').value = '';
// Auto-switch to dashboard after adding
showPage('dashboard');
}
function deleteTransaction(id) {
allMonthsData[currentMonth].transactions =
allMonthsData[currentMonth].transactions.filter(t => t.id !== id);
saveAllData();
renderTransactions();
updateDashboardFromTransactions();
updateMonthInfo();
}
function renderTransactions() {
const container = document.getElementById('transactionsList');
container.innerHTML = '';
const monthData = allMonthsData[currentMonth];
const transactions = monthData?.transactions || [];
let total = 0;
// Calculate category totals for summary
const categoryTotals = {};
const categoryNames = {
'tuition': 'Tuition',
'phone': 'Phone Bill',
'groceries': 'Groceries',
'transport': 'Transportation',
'textbooks': 'Textbooks',
'eating': 'Eating Out',
'extra': 'Extra Spending'
};
transactions.forEach(transaction => {
total += transaction.amount;
// Track category total
if (!categoryTotals[transaction.category]) {
categoryTotals[transaction.category] = 0;
}
categoryTotals[transaction.category] += transaction.amount;
// Create transaction item
const categoryClass = `category-${transaction.category}`;
const item = document.createElement('div');
item.className = 'transaction-item';
item.innerHTML = `
<div class="transaction-description">
<div>${transaction.description}</div>
<div style="font-size: 0.8rem; color: #888;">${transaction.date}</div>
</div>
<div class="transaction-category ${categoryClass}">
${categoryNames[transaction.category]}
</div>
<div class="transaction-amount">
$${transaction.amount.toFixed(2)}
</div>
<button class="delete-btn" onclick="deleteTransaction(${transaction.id})">
Delete
</button>
`;
container.appendChild(item);
});
// Update totals
document.getElementById('monthlyTotal').textContent = `$${total.toFixed(2)}`;
// Update summary stats
updateMonthSummary(transactions, total, categoryTotals);
}
// Update month summary statistics
function updateMonthSummary(transactions, total, categoryTotals) {
const transactionCount = transactions.length;
document.getElementById('monthTransactionCount').textContent = transactionCount;
// Calculate daily average (assuming 30 days in month)
const dailyAverage = transactionCount > 0 ? total / 30 : 0;
document.getElementById('monthDailyAverage').textContent = `$${dailyAverage.toFixed(2)}`;
// Find top spending category
let topCategory = 'None';
let topAmount = 0;
for (const [category, amount] of Object.entries(categoryTotals)) {
if (amount > topAmount) {
topAmount = amount;
topCategory = category;
}
}
const categoryDisplayNames = {
'tuition': 'Tuition',
'phone': 'Phone',
'groceries': 'Groceries',
'transport': 'Transport',
'textbooks': 'Textbooks',
'eating': 'Eating Out',
'extra': 'Extra'
};
document.getElementById('monthTopCategory').textContent =
topCategory !== 'None' ? categoryDisplayNames[topCategory] : 'None';
// Calculate remaining budget
const income = allMonthsData[currentMonth]?.income || 0;
const remaining = income - total;
document.getElementById('monthRemainingBudget').textContent = `$${remaining.toFixed(2)}`;
}
// Update dashboard based on transactions
function updateDashboardFromTransactions() {
const monthData = allMonthsData[currentMonth];
if (!monthData) return;
// Save current income and savings values
monthData.income = parseFloat(document.getElementById('monthlyIncome').value) || 200;
monthData.savingsGoal = parseFloat(document.getElementById('savingsGoal').value) || 3000;
monthData.currentSavings = parseFloat(document.getElementById('currentSavings').value) || 500;
saveAllData();
// Reset all category totals
const categoryTotals = {
tuition: 0,
phone: 0,
groceries: 0,
transport: 0,
textbooks: 0,
eating: 0,
extra: 0
};
// Sum up transactions by category
monthData.transactions.forEach(transaction => {
categoryTotals[transaction.category] += transaction.amount;
});
// Update dashboard inputs
document.getElementById('tuition').value = categoryTotals.tuition;
document.getElementById('phoneBill').value = categoryTotals.phone;
document.getElementById('groceries').value = categoryTotals.groceries;
document.getElementById('transportation').value = categoryTotals.transport;
document.getElementById('textbooks').value = categoryTotals.textbooks;
document.getElementById('eatingOut').value = categoryTotals.eating;
document.getElementById('extraSpending').value = categoryTotals.extra;
// Recalculate budget
calculateBudget();
}
// Budget calculations
function calculateBudget() {
// Get input values
const income = parseFloat(document.getElementById('monthlyIncome').value) || 0;
const tuition = parseFloat(document.getElementById('tuition').value) || 0;
const phone = parseFloat(document.getElementById('phoneBill').value) || 0;
const groceries = parseFloat(document.getElementById('groceries').value) || 0;
const transport = parseFloat(document.getElementById('transportation').value) || 0;
const books = parseFloat(document.getElementById('textbooks').value) || 0;
const eatingOut = parseFloat(document.getElementById('eatingOut').value) || 0;
const extra = parseFloat(document.getElementById('extraSpending').value) || 0;
const savingsGoal = parseFloat(document.getElementById('savingsGoal').value) || 0;
const currentSavings = parseFloat(document.getElementById('currentSavings').value) || 0;
// Calculate totals
const totalNeeds = tuition + phone + groceries + transport + books;
const totalWants = eatingOut + extra;
const totalExpenses = totalNeeds + totalWants;
const remaining = income - totalExpenses;
const availableAfterNeeds = income - totalNeeds;
// Calculate percentages
const wantsPercent = income > 0 ? (totalWants / income) * 100 : 0;
const savingsPercent = savingsGoal > 0 ? (currentSavings / savingsGoal) * 100 : 0;
const suggestedSavings = remaining > 0 ? remaining * 0.2 : 0; // Suggest saving 20%
// Update display values
document.getElementById('totalIncome').textContent = formatCurrency(income);
document.getElementById('totalExpenses').textContent = formatCurrency(totalExpenses);
document.getElementById('remainingAmount').textContent = formatCurrency(remaining);
document.getElementById('suggestedSavings').textContent = formatCurrency(suggestedSavings);
document.getElementById('availableAfterNeeds').textContent = formatCurrency(availableAfterNeeds);
document.getElementById('needsTotal').textContent = formatCurrency(totalNeeds);
document.getElementById('wantsTotal').textContent = formatCurrency(totalWants);
// Update progress bars
document.getElementById('wantsPercent').textContent = wantsPercent.toFixed(1) + '%';
document.getElementById('wantsProgress').style.width = Math.min(wantsPercent, 100) + '%';
document.getElementById('savingsPercent').textContent = savingsPercent.toFixed(1) + '%';
document.getElementById('savingsProgress').style.width = Math.min(savingsPercent, 100) + '%';
// Update status indicators
updateStatusIndicators(income, remaining, wantsPercent, totalWants, totalNeeds);
// Update chart
updateChart(totalNeeds, totalWants, remaining);
}
// Update status indicators with colors
function updateStatusIndicators(income, remaining, wantsPercent, totalWants, totalNeeds) {
// Income status
const incomeStatus = document.getElementById('incomeStatus');
incomeStatus.textContent = income > 0 ? 'ACTIVE' : 'NO INCOME';
incomeStatus.className = income > 0 ? 'status-indicator status-good' : 'status-indicator status-bad';
// Needs status
const needsStatus = document.getElementById('needsStatus');
const needsPercent = income > 0 ? (totalNeeds / income) * 100 : 0;
if (needsPercent <= 50) {
needsStatus.textContent = 'ON TRACK';
needsStatus.className = 'status-indicator status-good';
} else if (needsPercent <= 70) {
needsStatus.textContent = 'WATCH';
needsStatus.className = 'status-indicator status-warning';
} else {
needsStatus.textContent = 'HIGH';
needsStatus.className = 'status-indicator status-bad';
}
// Wants status
const wantsStatus = document.getElementById('wantsStatus');
const wantsWarning = document.getElementById('wantsWarning');
if (wantsPercent <= 10) {
wantsStatus.textContent = 'LOW';
wantsStatus.className = 'status-indicator status-good';
wantsWarning.style.display = 'none';
} else if (wantsPercent <= 15) {
wantsStatus.textContent = 'WATCH';
wantsStatus.className = 'status-indicator status-warning';
wantsWarning.style.display = 'block';
} else {
wantsStatus.textContent = 'HIGH';
wantsStatus.className = 'status-indicator status-bad';
wantsWarning.style.display = 'block';
}
// Savings status
const savingsStatus = document.getElementById('savingsStatus');
if (remaining > 0) {
savingsStatus.textContent = 'ON TRACK';
savingsStatus.className = 'status-indicator status-good';
} else {
savingsStatus.textContent = 'DEFICIT';
savingsStatus.className = 'status-indicator status-bad';
}
}
// Update bill countdown
function updateBillCountdown() {
const today = new Date();
const currentYear = today.getFullYear();
const currentMonthIndex = today.getMonth();
let dueDate = new Date(currentYear, currentMonthIndex, 13);
// If 13th has passed this month, use next month
if (today.getDate() > 13) {
dueDate = new Date(currentYear, currentMonthIndex + 1, 13);
}
const diffTime = dueDate - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
document.getElementById('billCountdown').textContent = diffDays;
// Color code based on days left
const countdownElement = document.getElementById('billCountdown');
if (diffDays <= 0) {
countdownElement.style.color = '#FFFFFF';
} else if (diffDays <= 3) {
countdownElement.style.color = '#FFFFFF';
} else {
countdownElement.style.color = '#FFFFFF';
}
}
// Create/update chart
function updateChart(needs, wants, remaining) {
const ctx = document.getElementById('budgetChart').getContext('2d');
// Destroy existing chart if it exists
if (budgetChart) {
budgetChart.destroy();
}
budgetChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Needs', 'Wants', 'Remaining'],
datasets: [{
data: [needs, wants, remaining > 0 ? remaining : 0],
backgroundColor: [
'#FFFFFF', // Needs - White
'#FF0000', // Wants - Red
'#00FF00' // Remaining - Green
],
borderColor: '#000000',
borderWidth: 2,
hoverOffset: 15
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
labels: {
color: '#FFFFFF',
padding: 20,
font: {
size: 14
}
}
},
tooltip: {
callbacks: {
label: function(context) {
let label = context.label || '';
if (label) {
label += ': ';
}
label += formatCurrency(context.raw);
return label;
}
}
}
}
}
});
}
// Reset current month's data
function resetCurrentMonth() {
if (confirm(`Reset all data for ${currentMonth}? This cannot be undone.`)) {
allMonthsData[currentMonth] = {
transactions: [],
income: 200,
savingsGoal: 3000,
currentSavings: 500
};
saveAllData();
loadCurrentMonth();
}
}
// Helper function to format currency
function formatCurrency(amount) {
return '$' + amount.toFixed(2);
}
// Auto-calculate when inputs change
const inputs = document.querySelectorAll('#monthlyIncome, #savingsGoal, #currentSavings');
inputs.forEach(input => {
input.addEventListener('input', function() {
// Save to current month's data
const monthData = allMonthsData[currentMonth];
if (monthData) {
if (this.id === 'monthlyIncome') {
monthData.income = parseFloat(this.value) || 200;
} else if (this.id === 'savingsGoal') {
monthData.savingsGoal = parseFloat(this.value) || 3000;
} else if (this.id === 'currentSavings') {
monthData.currentSavings = parseFloat(this.value) || 500;
}
saveAllData();
}
calculateBudget();
});
});