-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
986 lines (882 loc) · 48.1 KB
/
Copy pathindex.html
File metadata and controls
986 lines (882 loc) · 48.1 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Advanced budget calculator with multiple budgeting methods">
<meta name="theme-color" content="#3b82f6">
<title>Budget Pro - Smart Financial Management</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
font-family: 'Inter', sans-serif;
}
.slide-enter {
animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.badge {
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.card-hover {
transition: all 0.3s ease;
}
.card-hover:hover {
transform: translateY(-5px);
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body class="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 min-h-screen transition-colors duration-300">
<nav class="bg-white dark:bg-gray-800 shadow-lg sticky top-0 z-50 transition-colors duration-300">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<div class="flex items-center space-x-3">
<span class="text-3xl">💰</span>
<h1 class="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">Budget Pro</h1>
</div>
<div class="flex items-center space-x-4">
<button id="themeToggle" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition">
<span class="text-2xl" id="themeIcon">🌙</span>
</button>
<button id="exportBtn" class="hidden sm:flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
<span>📊</span>
<span>Export</span>
</button>
</div>
</div>
</div>
</nav>
<div class="max-w-7xl mx-auto px-4 py-8">
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 slide-enter card-hover">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-600 dark:text-gray-400 font-medium">Total Income</p>
<p class="text-3xl font-bold text-green-600 dark:text-green-400 mt-1" id="totalIncome">$0.00</p>
</div>
<div class="bg-green-100 dark:bg-green-900 p-4 rounded-xl">
<span class="text-4xl">💵</span>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 slide-enter card-hover">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-600 dark:text-gray-400 font-medium">Total Expenses</p>
<p class="text-3xl font-bold text-red-600 dark:text-red-400 mt-1" id="totalExpenses">$0.00</p>
</div>
<div class="bg-red-100 dark:bg-red-900 p-4 rounded-xl">
<span class="text-4xl">💸</span>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 slide-enter card-hover">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-600 dark:text-gray-400 font-medium">Balance</p>
<p class="text-3xl font-bold text-blue-600 dark:text-blue-400 mt-1" id="balance">$0.00</p>
</div>
<div class="bg-blue-100 dark:bg-blue-900 p-4 rounded-xl">
<span class="text-4xl">💰</span>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 slide-enter card-hover">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-600 dark:text-gray-400 font-medium">Achievements</p>
<p class="text-3xl font-bold text-purple-600 dark:text-purple-400 mt-1" id="badgeCount">0</p>
</div>
<div class="bg-purple-100 dark:bg-purple-900 p-4 rounded-xl">
<span class="text-4xl">🏆</span>
</div>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl mb-8 overflow-hidden">
<div class="flex overflow-x-auto">
<button class="tab-btn active px-6 py-4 font-semibold border-b-2 border-blue-600 text-blue-600 dark:text-blue-400 whitespace-nowrap" data-tab="dashboard">📊 Dashboard</button>
<button class="tab-btn px-6 py-4 font-semibold text-gray-600 dark:text-gray-400 hover:text-blue-600 whitespace-nowrap" data-tab="income">💵 Income</button>
<button class="tab-btn px-6 py-4 font-semibold text-gray-600 dark:text-gray-400 hover:text-blue-600 whitespace-nowrap" data-tab="expenses">💸 Expenses</button>
<button class="tab-btn px-6 py-4 font-semibold text-gray-600 dark:text-gray-400 hover:text-blue-600 whitespace-nowrap" data-tab="budget">🎯 Budget</button>
<button class="tab-btn px-6 py-4 font-semibold text-gray-600 dark:text-gray-400 hover:text-blue-600 whitespace-nowrap" data-tab="settings">⚙️ Settings</button>
</div>
</div>
<div id="tabContent">
<div class="tab-content active" data-content="dashboard">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Spending by Category</h3>
<canvas id="categoryChart"></canvas>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Income vs Expenses</h3>
<canvas id="trendChart"></canvas>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Budget Breakdown</h3>
<canvas id="budgetChart"></canvas>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">🏆 Achievements</h3>
<div id="achievementsList" class="space-y-2 max-h-64 overflow-y-auto"></div>
</div>
</div>
</div>
<div class="tab-content hidden" data-content="income">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 mb-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Add Income</h3>
<form id="incomeForm" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<input type="text" id="incomeSource" placeholder="Source (e.g., Salary)" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<input type="number" id="incomeAmount" placeholder="Amount" step="0.01" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<input type="date" id="incomeDate" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<button type="submit" class="px-6 py-3 bg-green-600 text-white rounded-xl hover:bg-green-700 transition font-semibold">Add Income</button>
</form>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Income History</h3>
<div class="overflow-x-auto">
<table class="w-full">
<thead>
<tr class="border-b border-gray-200 dark:border-gray-700">
<th class="text-left py-3 px-4 text-gray-600 dark:text-gray-400">Date</th>
<th class="text-left py-3 px-4 text-gray-600 dark:text-gray-400">Source</th>
<th class="text-right py-3 px-4 text-gray-600 dark:text-gray-400">Amount</th>
<th class="text-right py-3 px-4 text-gray-600 dark:text-gray-400">Actions</th>
</tr>
</thead>
<tbody id="incomeList" class="text-gray-800 dark:text-gray-300"></tbody>
</table>
</div>
</div>
</div>
<div class="tab-content hidden" data-content="expenses">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 mb-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Add Expense</h3>
<form id="expenseForm" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
<input type="text" id="expenseDescription" placeholder="Description" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<input type="number" id="expenseAmount" placeholder="Amount" step="0.01" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<select id="expenseCategory" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<option value="">Select Category</option>
<option value="Housing">🏠 Housing</option>
<option value="Food">🍔 Food</option>
<option value="Transportation">🚗 Transportation</option>
<option value="Entertainment">🎮 Entertainment</option>
<option value="Healthcare">🏥 Healthcare</option>
<option value="Shopping">🛍️ Shopping</option>
<option value="Bills">📄 Bills</option>
<option value="Other">📦 Other</option>
</select>
<input type="date" id="expenseDate" required class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white">
<button type="submit" class="px-6 py-3 bg-red-600 text-white rounded-xl hover:bg-red-700 transition font-semibold">Add Expense</button>
</form>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6">
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-3">
<h3 class="text-xl font-bold text-gray-800 dark:text-white">Expense History</h3>
<input type="text" id="expenseSearch" placeholder="🔍 Search..." class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-xl dark:bg-gray-700 dark:text-white w-full sm:w-64">
</div>
<div class="overflow-x-auto">
<table class="w-full">
<thead>
<tr class="border-b border-gray-200 dark:border-gray-700">
<th class="text-left py-3 px-4 text-gray-600 dark:text-gray-400">Date</th>
<th class="text-left py-3 px-4 text-gray-600 dark:text-gray-400">Description</th>
<th class="text-left py-3 px-4 text-gray-600 dark:text-gray-400">Category</th>
<th class="text-right py-3 px-4 text-gray-600 dark:text-gray-400">Amount</th>
<th class="text-right py-3 px-4 text-gray-600 dark:text-gray-400">Actions</th>
</tr>
</thead>
<tbody id="expenseList" class="text-gray-800 dark:text-gray-300"></tbody>
</table>
</div>
</div>
</div>
<div class="tab-content hidden" data-content="budget">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 mb-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Select Budget Method</h3>
<select id="budgetMethod" class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl text-lg dark:bg-gray-700 dark:text-white">
<option value="50-30-20">50/30/20 Rule</option>
<option value="zero-based">Zero-Based Budgeting</option>
<option value="envelope">Envelope Method</option>
<option value="pay-yourself">Pay Yourself First</option>
</select>
<div id="budgetMethodDescription" class="mt-4 p-4 bg-blue-50 dark:bg-blue-900 rounded-xl text-gray-700 dark:text-gray-300"></div>
</div>
<div id="budgetDetails" class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6"></div>
</div>
<div class="tab-content hidden" data-content="settings">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Currency & Locale</h3>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Currency</label>
<select id="currencySelect" class="w-full px-4 py-3 border rounded-xl dark:bg-gray-700 dark:text-white">
<option value="USD">USD - US Dollar ($)</option>
<option value="EUR">EUR - Euro (€)</option>
<option value="GBP">GBP - British Pound (£)</option>
<option value="JPY">JPY - Japanese Yen (¥)</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Date Format</label>
<select id="dateFormat" class="w-full px-4 py-3 border rounded-xl dark:bg-gray-700 dark:text-white">
<option value="en-US">MM/DD/YYYY (US)</option>
<option value="en-GB">DD/MM/YYYY (UK)</option>
<option value="ja-JP">YYYY/MM/DD (ISO)</option>
</select>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 card-hover">
<h3 class="text-xl font-bold mb-4 text-gray-800 dark:text-white">Data Management</h3>
<div class="space-y-3">
<button id="exportCSV" class="w-full px-4 py-3 bg-green-600 text-white rounded-xl hover:bg-green-700 transition font-semibold">📥 Export to CSV</button>
<button id="exportPDF" class="w-full px-4 py-3 bg-red-600 text-white rounded-xl hover:bg-red-700 transition font-semibold">📄 Export to PDF</button>
<button id="clearData" class="w-full px-4 py-3 bg-gray-600 text-white rounded-xl hover:bg-gray-700 transition font-semibold">🗑️ Clear All Data</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Application State - This stores all our data
const state = {
income: [],
expenses: [],
budgetMethod: '50-30-20',
currency: 'USD',
dateFormat: 'en-US',
theme: 'light',
achievements: []
};
// Currency symbols for formatting
const currencySymbols = {
USD: '$',
EUR: '€',
GBP: '£',
JPY: '¥'
};
// Budget method descriptions
const budgetDescriptions = {
'50-30-20': 'Allocate 50% to needs, 30% to wants, and 20% to savings.',
'zero-based': 'Every dollar is assigned a job. Income minus expenses equals zero.',
'envelope': 'Allocate cash to different spending categories.',
'pay-yourself': 'Set aside savings first, then budget the rest.'
};
// Chart instances
let categoryChart, trendChart, budgetChart;
// Initialize the app when page loads
function init() {
console.log('Initializing Budget Pro...');
loadState();
setupEventListeners();
setTodayDate();
initCharts();
updateUI();
checkAchievements();
console.log('App initialized successfully!');
}
// Load saved data from localStorage
function loadState() {
try {
const saved = localStorage.getItem('budgetProData');
if (saved) {
const parsed = JSON.parse(saved);
Object.assign(state, parsed);
console.log('Loaded state:', state);
}
} catch (error) {
console.error('Error loading state:', error);
}
applyTheme();
}
// Save data to localStorage
function saveState() {
try {
localStorage.setItem('budgetProData', JSON.stringify(state));
console.log('State saved');
} catch (error) {
console.error('Error saving state:', error);
}
}
// Set today's date in date inputs
function setTodayDate() {
const today = new Date().toISOString().split('T')[0];
document.getElementById('incomeDate').value = today;
document.getElementById('expenseDate').value = today;
}
// Setup all event listeners
function setupEventListeners() {
// Tab navigation
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => switchTab(e.target.dataset.tab));
});
// Forms
document.getElementById('incomeForm').addEventListener('submit', addIncome);
document.getElementById('expenseForm').addEventListener('submit', addExpense);
// Theme toggle
document.getElementById('themeToggle').addEventListener('click', toggleTheme);
// Budget method
document.getElementById('budgetMethod').addEventListener('change', (e) => {
state.budgetMethod = e.target.value;
saveState();
updateBudgetDetails();
});
// Settings
document.getElementById('currencySelect').addEventListener('change', (e) => {
state.currency = e.target.value;
saveState();
updateUI();
});
document.getElementById('dateFormat').addEventListener('change', (e) => {
state.dateFormat = e.target.value;
saveState();
updateUI();
});
// Export buttons
document.getElementById('exportCSV').addEventListener('click', exportCSV);
document.getElementById('exportPDF').addEventListener('click', exportPDF);
document.getElementById('exportBtn').addEventListener('click', exportCSV);
document.getElementById('clearData').addEventListener('click', clearAllData);
// Search
document.getElementById('expenseSearch').addEventListener('input', filterExpenses);
console.log('Event listeners setup complete');
}
// Switch between tabs
function switchTab(tabName) {
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active', 'border-blue-600', 'text-blue-600', 'dark:text-blue-400');
btn.classList.add('text-gray-600', 'dark:text-gray-400');
});
const activeBtn = document.querySelector(`[data-tab="${tabName}"]`);
activeBtn.classList.add('active', 'border-blue-600', 'text-blue-600', 'dark:text-blue-400');
activeBtn.classList.remove('text-gray-600', 'dark:text-gray-400');
// Update content
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.add('hidden');
content.classList.remove('active');
});
const activeContent = document.querySelector(`[data-content="${tabName}"]`);
activeContent.classList.remove('hidden');
activeContent.classList.add('active');
if (tabName === 'budget') {
updateBudgetDetails();
}
}
// Add income entry
function addIncome(e) {
e.preventDefault();
const income = {
id: Date.now(),
source: document.getElementById('incomeSource').value,
amount: parseFloat(document.getElementById('incomeAmount').value),
date: document.getElementById('incomeDate').value,
timestamp: new Date().toISOString()
};
state.income.push(income);
saveState();
updateUI();
checkAchievements();
e.target.reset();
setTodayDate();
showNotification('Income added successfully! 💰', 'success');
}
// Delete income entry
function deleteIncome(id) {
if (confirm('Delete this income entry?')) {
state.income = state.income.filter(i => i.id !== id);
saveState();
updateUI();
}
}
// Render income list
function renderIncomeList() {
const list = document.getElementById('incomeList');
if (state.income.length === 0) {
list.innerHTML = '<tr><td colspan="4" class="text-center py-8 text-gray-500 dark:text-gray-400">No income entries yet. Add your first one above!</td></tr>';
return;
}
list.innerHTML = state.income
.sort((a, b) => new Date(b.date) - new Date(a.date))
.map(income => `
<tr class="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 transition">
<td class="py-3 px-4">${formatDate(income.date)}</td>
<td class="py-3 px-4">${escapeHtml(income.source)}</td>
<td class="py-3 px-4 text-right font-semibold text-green-600 dark:text-green-400">${formatCurrency(income.amount)}</td>
<td class="py-3 px-4 text-right">
<button onclick="window.deleteIncome(${income.id})" class="text-red-600 hover:text-red-800 font-semibold">Delete</button>
</td>
</tr>
`).join('');
}
// Add expense entry
function addExpense(e) {
e.preventDefault();
const expense = {
id: Date.now(),
description: document.getElementById('expenseDescription').value,
amount: parseFloat(document.getElementById('expenseAmount').value),
category: document.getElementById('expenseCategory').value,
date: document.getElementById('expenseDate').value,
timestamp: new Date().toISOString()
};
state.expenses.push(expense);
saveState();
updateUI();
checkAchievements();
e.target.reset();
setTodayDate();
showNotification('Expense added successfully! 📝', 'success');
}
// Delete expense entry
function deleteExpense(id) {
if (confirm('Delete this expense?')) {
state.expenses = state.expenses.filter(e => e.id !== id);
saveState();
updateUI();
}
}
// Filter expenses by search
function filterExpenses() {
const query = document.getElementById('expenseSearch').value.toLowerCase();
const filtered = state.expenses.filter(e =>
e.description.toLowerCase().includes(query) ||
e.category.toLowerCase().includes(query)
);
renderExpenseList(filtered);
}
// Render expense list
function renderExpenseList(expenses = state.expenses) {
const list = document.getElementById('expenseList');
if (expenses.length === 0) {
list.innerHTML = '<tr><td colspan="5" class="text-center py-8 text-gray-500 dark:text-gray-400">No expenses found.</td></tr>';
return;
}
list.innerHTML = expenses
.sort((a, b) => new Date(b.date) - new Date(a.date))
.map(expense => `
<tr class="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 transition">
<td class="py-3 px-4">${formatDate(expense.date)}</td>
<td class="py-3 px-4">${escapeHtml(expense.description)}</td>
<td class="py-3 px-4">${expense.category}</td>
<td class="py-3 px-4 text-right font-semibold text-red-600 dark:text-red-400">${formatCurrency(expense.amount)}</td>
<td class="py-3 px-4 text-right">
<button onclick="window.deleteExpense(${expense.id})" class="text-red-600 hover:text-red-800 font-semibold">Delete</button>
</td>
</tr>
`).join('');
}
// Update budget method details display
function updateBudgetDetails() {
const method = state.budgetMethod;
const descEl = document.getElementById('budgetMethodDescription');
const detailsEl = document.getElementById('budgetDetails');
descEl.innerHTML = `<p class="text-sm">${budgetDescriptions[method]}</p>`;
const totalIncome = calculateTotalIncome();
const totalExpenses = calculateTotalExpenses();
let content = '';
switch(method) {
case '50-30-20':
const needs = totalIncome * 0.5;
const wants = totalIncome * 0.3;
const savings = totalIncome * 0.2;
content = `
<h4 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">50/30/20 Budget Allocation</h4>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="p-6 bg-green-50 dark:bg-green-900 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">Needs (50%)</p>
<p class="text-3xl font-bold text-green-600 dark:text-green-400">${formatCurrency(needs)}</p>
</div>
<div class="p-6 bg-blue-50 dark:bg-blue-900 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">Wants (30%)</p>
<p class="text-3xl font-bold text-blue-600 dark:text-blue-400">${formatCurrency(wants)}</p>
</div>
<div class="p-6 bg-purple-50 dark:bg-purple-900 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">Savings (20%)</p>
<p class="text-3xl font-bold text-purple-600 dark:text-purple-400">${formatCurrency(savings)}</p>
</div>
</div>
`;
break;
case 'zero-based':
const remaining = totalIncome - totalExpenses;
content = `
<h4 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">Zero-Based Budget</h4>
<div class="space-y-4">
<div class="flex justify-between items-center p-4 bg-green-50 dark:bg-green-900 rounded-xl">
<span class="text-gray-700 dark:text-gray-300 font-medium">Total Income</span>
<span class="font-bold text-xl text-green-600 dark:text-green-400">${formatCurrency(totalIncome)}</span>
</div>
<div class="flex justify-between items-center p-4 bg-red-50 dark:bg-red-900 rounded-xl">
<span class="text-gray-700 dark:text-gray-300 font-medium">Total Allocated</span>
<span class="font-bold text-xl text-red-600 dark:text-red-400">${formatCurrency(totalExpenses)}</span>
</div>
<div class="flex justify-between items-center p-4 ${remaining === 0 ? 'bg-green-50 dark:bg-green-900' : 'bg-yellow-50 dark:bg-yellow-900'} rounded-xl">
<span class="text-gray-700 dark:text-gray-300 font-medium">Unallocated</span>
<span class="font-bold text-xl ${remaining === 0 ? 'text-green-600 dark:text-green-400' : 'text-yellow-600 dark:text-yellow-400'}">${formatCurrency(remaining)}</span>
</div>
</div>
`;
break;
case 'envelope':
const categoryTotals = {};
state.expenses.forEach(e => {
categoryTotals[e.category] = (categoryTotals[e.category] || 0) + e.amount;
});
content = `
<h4 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">Category Spending</h4>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
${Object.entries(categoryTotals).map(([cat, amt]) => `
<div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">${cat}</p>
<p class="text-2xl font-bold text-gray-800 dark:text-white">${formatCurrency(amt)}</p>
</div>
`).join('')}
</div>
`;
break;
case 'pay-yourself':
const savingsGoal = totalIncome * 0.2;
const afterSavings = totalIncome - savingsGoal;
content = `
<h4 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">Pay Yourself First</h4>
<div class="space-y-4">
<div class="p-6 bg-purple-50 dark:bg-purple-900 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">Savings Goal (20%)</p>
<p class="text-3xl font-bold text-purple-600 dark:text-purple-400">${formatCurrency(savingsGoal)}</p>
</div>
<div class="p-6 bg-blue-50 dark:bg-blue-900 rounded-xl">
<p class="text-sm text-gray-600 dark:text-gray-300 mb-1">Available to Spend</p>
<p class="text-3xl font-bold text-blue-600 dark:text-blue-400">${formatCurrency(afterSavings)}</p>
</div>
</div>
`;
break;
}
detailsEl.innerHTML = content;
}
// Calculate total income
function calculateTotalIncome() {
return state.income.reduce((sum, i) => sum + i.amount, 0);
}
// Calculate total expenses
function calculateTotalExpenses() {
return state.expenses.reduce((sum, e) => sum + e.amount, 0);
}
// Calculate balance
function calculateBalance() {
return calculateTotalIncome() - calculateTotalExpenses();
}
// Update all UI elements
function updateUI() {
const totalIncome = calculateTotalIncome();
const totalExpenses = calculateTotalExpenses();
const balance = calculateBalance();
document.getElementById('totalIncome').textContent = formatCurrency(totalIncome);
document.getElementById('totalExpenses').textContent = formatCurrency(totalExpenses);
document.getElementById('balance').textContent = formatCurrency(balance);
document.getElementById('badgeCount').textContent = state.achievements.length;
renderIncomeList();
renderExpenseList();
updateCharts();
renderAchievements();
updateBudgetDetails();
document.getElementById('currencySelect').value = state.currency;
document.getElementById('dateFormat').value = state.dateFormat;
document.getElementById('budgetMethod').value = state.budgetMethod;
}
// Initialize charts
function initCharts() {
const isDark = state.theme === 'dark';
const textColor = isDark ? '#9ca3af' : '#4b5563';
const gridColor = isDark ? '#374151' : '#e5e7eb';
Chart.defaults.color = textColor;
Chart.defaults.borderColor = gridColor;
const categoryCtx = document.getElementById('categoryChart').getContext('2d');
categoryChart = new Chart(categoryCtx, {
type: 'doughnut',
data: { labels: [], datasets: [{ data: [], backgroundColor: [] }] },
options: {
responsive: true,
plugins: {
legend: { position: 'bottom', labels: { color: textColor } }
}
}
});
const trendCtx = document.getElementById('trendChart').getContext('2d');
trendChart = new Chart(trendCtx, {
type: 'bar',
data: { labels: [], datasets: [] },
options: {
responsive: true,
scales: {
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } },
x: { ticks: { color: textColor }, grid: { color: gridColor } }
},
plugins: {
legend: { labels: { color: textColor } }
}
}
});
const budgetCtx = document.getElementById('budgetChart').getContext('2d');
budgetChart = new Chart(budgetCtx, {
type: 'pie',
data: { labels: [], datasets: [{ data: [], backgroundColor: [] }] },
options: {
responsive: true,
plugins: {
legend: { position: 'bottom', labels: { color: textColor } }
}
}
});
updateCharts();
}
// Update all charts
function updateCharts() {
updateCategoryChart();
updateTrendChart();
updateBudgetChart();
}
// Update category spending chart
function updateCategoryChart() {
const categoryTotals = {};
state.expenses.forEach(e => {
categoryTotals[e.category] = (categoryTotals[e.category] || 0) + e.amount;
});
const colors = ['#ef4444', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ec4899', '#6366f1', '#14b8a6'];
categoryChart.data.labels = Object.keys(categoryTotals);
categoryChart.data.datasets[0].data = Object.values(categoryTotals);
categoryChart.data.datasets[0].backgroundColor = colors.slice(0, Object.keys(categoryTotals).length);
categoryChart.update();
}
// Update trend chart
function updateTrendChart() {
const last6Months = [];
const now = new Date();
for (let i = 5; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
last6Months.push(d.toISOString().slice(0, 7));
}
const incomeByMonth = {};
const expensesByMonth = {};
last6Months.forEach(m => {
incomeByMonth[m] = 0;
expensesByMonth[m] = 0;
});
state.income.forEach(i => {
const month = i.date.slice(0, 7);
if (incomeByMonth.hasOwnProperty(month)) {
incomeByMonth[month] += i.amount;
}
});
state.expenses.forEach(e => {
const month = e.date.slice(0, 7);
if (expensesByMonth.hasOwnProperty(month)) {
expensesByMonth[month] += e.amount;
}
});
trendChart.data.labels = last6Months.map(m => {
const parts = m.split('-');
const date = new Date(parts[0], parts[1] - 1);
return date.toLocaleDateString(state.dateFormat, { month: 'short' });
});
trendChart.data.datasets = [
{
label: 'Income',
data: last6Months.map(m => incomeByMonth[m]),
backgroundColor: '#10b981'
},
{
label: 'Expenses',
data: last6Months.map(m => expensesByMonth[m]),
backgroundColor: '#ef4444'
}
];
trendChart.update();
}
// Update budget breakdown chart
function updateBudgetChart() {
const totalIncome = calculateTotalIncome();
if (state.budgetMethod === '50-30-20') {
budgetChart.data.labels = ['Needs (50%)', 'Wants (30%)', 'Savings (20%)'];
budgetChart.data.datasets[0].data = [
totalIncome * 0.5,
totalIncome * 0.3,
totalIncome * 0.2
];
budgetChart.data.datasets[0].backgroundColor = ['#10b981', '#3b82f6', '#8b5cf6'];
} else {
const totalExpenses = calculateTotalExpenses();
const balance = totalIncome - totalExpenses;
budgetChart.data.labels = ['Expenses', 'Remaining'];
budgetChart.data.datasets[0].data = [totalExpenses, balance > 0 ? balance : 0];
budgetChart.data.datasets[0].backgroundColor = ['#ef4444', '#10b981'];
}
budgetChart.update();
}
// Achievement definitions
const achievementDefinitions = [
{ id: 'first_income', name: 'First Income', desc: 'Log your first income', icon: '💵', check: () => state.income.length >= 1 },
{ id: 'first_expense', name: 'First Expense', desc: 'Log your first expense', icon: '📝', check: () => state.expenses.length >= 1 },
{ id: 'positive_balance', name: 'In The Black', desc: 'Maintain positive balance', icon: '✅', check: () => calculateBalance() > 0 },
{ id: 'saver_100', name: 'Century Saver', desc: 'Save $100 or more', icon: '💯', check: () => calculateBalance() >= 100 },
{ id: 'saver_1000', name: 'Grand Saver', desc: 'Save $1000 or more', icon: '🏆', check: () => calculateBalance() >= 1000 },
{ id: 'expense_tracker', name: 'Expense Tracker', desc: 'Log 50 expenses', icon: '📊', check: () => state.expenses.length >= 50 }
];
// Check for new achievements
function checkAchievements() {
achievementDefinitions.forEach(achievement => {
if (achievement.check() && !state.achievements.find(a => a.id === achievement.id)) {
state.achievements.push({
id: achievement.id,
name: achievement.name,
earnedAt: new Date().toISOString()
});
showNotification(`🏆 Achievement: ${achievement.name}!`, 'success');
saveState();
}
});
}
// Render achievements list
function renderAchievements() {
const list = document.getElementById('achievementsList');
const earned = state.achievements.map(a => a.id);
list.innerHTML = achievementDefinitions.map(ach => {
const isEarned = earned.includes(ach.id);
return `
<div class="flex items-center space-x-3 p-3 rounded-xl ${isEarned ? 'bg-yellow-50 dark:bg-yellow-900' : 'bg-gray-100 dark:bg-gray-700'} ${isEarned ? 'badge' : 'opacity-50'}">
<span class="text-3xl">${ach.icon}</span>
<div class="flex-1">
<p class="font-semibold text-gray-800 dark:text-white">${ach.name}</p>
<p class="text-sm text-gray-600 dark:text-gray-400">${ach.desc}</p>
</div>
${isEarned ? '<span class="text-yellow-500 text-2xl">✓</span>' : ''}
</div>
`;
}).join('');
}
// Toggle theme
function toggleTheme() {
state.theme = state.theme === 'light' ? 'dark' : 'light';
applyTheme();
saveState();
initCharts();
}
// Apply theme
function applyTheme() {
if (state.theme === 'dark') {
document.documentElement.classList.add('dark');
document.getElementById('themeIcon').textContent = '☀️';
} else {
document.documentElement.classList.remove('dark');
document.getElementById('themeIcon').textContent = '🌙';
}
}
// Export to CSV
function exportCSV() {
const headers = ['Date', 'Type', 'Description', 'Category', 'Amount'];
const rows = [
...state.income.map(i => [i.date, 'Income', i.source, '', i.amount]),
...state.expenses.map(e => [e.date, 'Expense', e.description, e.category, -e.amount])
].sort((a, b) => new Date(b[0]) - new Date(a[0]));
const csv = [headers, ...rows].map(row => row.join(',')).join('\n');
downloadFile(csv, 'budget_export.csv', 'text/csv');
showNotification('CSV exported! 📥', 'success');
}
// Export to PDF
function exportPDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.setFontSize(20);
doc.text('Budget Pro Report', 20, 20);
doc.setFontSize(12);
doc.text(`Date: ${new Date().toLocaleDateString()}`, 20, 30);
let y = 45;
doc.text(`Total Income: ${formatCurrency(calculateTotalIncome())}`, 20, y);
y += 10;
doc.text(`Total Expenses: ${formatCurrency(calculateTotalExpenses())}`, 20, y);
y += 10;
doc.text(`Balance: ${formatCurrency(calculateBalance())}`, 20, y);
doc.save('budget_report.pdf');
showNotification('PDF exported! 📄', 'success');
}
// Download file helper
function downloadFile(content, filename, type) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// Clear all data
function clearAllData() {
if (confirm('Delete ALL data? This cannot be undone!')) {
localStorage.clear();
location.reload();
}
}
// Format currency
function formatCurrency(amount) {
const symbol = currencySymbols[state.currency] || '$';
return `${symbol}${Math.abs(amount).toFixed(2)}`;
}
// Format date
function formatDate(dateStr) {
const date = new Date(dateStr + 'T00:00:00');
return date.toLocaleDateString(state.dateFormat);
}
// Escape HTML to prevent XSS
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Show notification
function showNotification(message, type = 'info') {
const colors = {
success: 'bg-green-500',
warning: 'bg-yellow-500',
error: 'bg-red-500',
info: 'bg-blue-500'
};
const notification = document.createElement('div');
notification.className = `fixed top-20 right-4 ${colors[type]} text-white px-6 py-4 rounded-xl shadow-2xl z-50 slide-enter max-w-sm`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.3s';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Make functions available globally for onclick handlers
window.deleteIncome = deleteIncome;
window.deleteExpense = deleteExpense;
// Start the app when DOM is ready
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>