-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBudgetTracker.py
More file actions
2197 lines (1858 loc) · 85.3 KB
/
Copy pathBudgetTracker.py
File metadata and controls
2197 lines (1858 loc) · 85.3 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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# budget_tracker.py
"""
Budget Tracking Application
A Streamlit-based application for tracking business expenses and managing budgets.
Features:
- Bank statement import (PDF and Excel)
- Transaction management
- Budget tracking
- Payment request management
- Financial analytics
- Expense categorization
"""
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, time, timedelta
import os
from pathlib import Path
import numpy as np
from io import BytesIO
import sqlite3
from decimal import Decimal
import pdfplumber
import re
from time import sleep
class BankStatementParser:
"""Handles parsing of bank statements in various formats"""
def __init__(self):
self.supported_banks = ['HDFC']
def clean_amount(self, amount_str):
"""Clean amount strings and convert to float"""
try:
if pd.isna(amount_str) or amount_str is None or amount_str == '':
return 0.0
if isinstance(amount_str, (int, float)):
return float(amount_str)
amount_str = str(amount_str).strip()
amount_str = ''.join(c for c in amount_str if c.isdigit() or c == '.')
return float(amount_str) if amount_str else 0.0
except Exception as e:
print(f"Error cleaning amount {amount_str}: {str(e)}")
return 0.0
def parse_date(self, date_val):
"""Parse date values from various formats"""
try:
if isinstance(date_val, datetime):
return date_val
if isinstance(date_val, str):
date_str = date_val.strip()
try:
return datetime.strptime(date_str, '%d/%m/%y')
except ValueError:
try:
return datetime.strptime(date_str, '%d/%m/%Y')
except ValueError:
print(f"Could not parse date: {date_str}")
return None
return None
except Exception as e:
print(f"Error parsing date {date_val}: {str(e)}")
return None
def parse_excel_statement(self, file_content):
"""Parse bank statement in Excel format"""
try:
print("\nProcessing Excel file...")
df = pd.read_excel(BytesIO(file_content))
# Find header row
header_row = None
for idx, row in df.iterrows():
row_text = ' '.join(str(x).lower() for x in row.values)
if ('date' in row_text and 'narration' in row_text and
('withdrawal' in row_text or 'debit' in row_text)):
header_row = idx
break
if header_row is None:
raise ValueError("Could not find transaction table header")
df.columns = df.iloc[header_row]
df = df.iloc[header_row + 1:].reset_index(drop=True)
df.columns = df.columns.str.strip().str.lower()
# Find required columns
date_col = next(col for col in df.columns if 'date' in col.lower() and 'value' not in col.lower())
narration_col = next(col for col in df.columns if 'narration' in col.lower())
ref_col = next(col for col in df.columns if 'ref' in col.lower() or 'chq' in col.lower())
withdrawal_col = next(col for col in df.columns if 'withdrawal' in col.lower() or 'debit' in col.lower())
deposit_col = next(col for col in df.columns if 'deposit' in col.lower() or 'credit' in col.lower())
balance_col = next(col for col in df.columns if 'balance' in col.lower())
transactions = []
current_description = ''
for idx, row in df.iterrows():
try:
if 'statement summary' in str(row[narration_col]).lower():
break
date_val = row[date_col]
if pd.isna(date_val):
if current_description:
current_description += ' ' + str(row[narration_col])
continue
date_obj = self.parse_date(date_val)
if not date_obj:
continue
description = (current_description + ' ' + str(row[narration_col])
if current_description else str(row[narration_col]))
current_description = ''
withdrawal = self.clean_amount(row[withdrawal_col])
deposit = self.clean_amount(row[deposit_col])
balance = self.clean_amount(row[balance_col])
transaction = {
'date': date_obj,
'description': description.strip(),
'reference': str(row[ref_col]).strip(),
'type': 'debit' if withdrawal > 0 else 'credit',
'amount': withdrawal if withdrawal > 0 else deposit,
'balance': balance
}
transactions.append(transaction)
except Exception as e:
print(f"Error processing row {idx}: {str(e)}")
continue
if not transactions:
raise ValueError("No valid transactions found in the statement")
return pd.DataFrame(transactions)
except Exception as e:
raise ValueError(f"Error processing Excel statement: {str(e)}")
def parse_pdf_statement(self, file):
"""Parse bank statement in PDF format"""
try:
transactions = []
with pdfplumber.open(file) as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
if not table:
continue
header_found = False
for row_idx, row in enumerate(table):
row = [str(cell).strip() if cell is not None else '' for cell in row]
row_text = ' '.join(row).lower()
if ('date' in row_text and 'narration' in row_text and
('withdrawal' in row_text or 'debit' in row_text)):
header_found = True
continue
if not header_found:
continue
try:
if not row[0] or 'statement summary' in ' '.join(row).lower():
continue
date_obj = self.parse_date(row[0])
if not date_obj:
continue
withdrawal = self.clean_amount(row[4])
deposit = self.clean_amount(row[5])
transaction = {
'date': date_obj,
'description': row[1].strip(),
'reference': row[2].strip(),
'type': 'debit' if withdrawal > 0 else 'credit',
'amount': withdrawal if withdrawal > 0 else deposit,
'balance': self.clean_amount(row[6])
}
transactions.append(transaction)
except Exception as e:
print(f"Error processing row: {str(e)}")
continue
if not transactions:
raise ValueError("No valid transactions found in the statement")
return pd.DataFrame(transactions)
except Exception as e:
raise ValueError(f"Error processing PDF statement: {str(e)}")
class BudgetTracker:
"""Main class for budget and expense tracking functionality"""
def __init__(self):
"""Initialize the budget tracker with database connection"""
self.conn = sqlite3.connect('budget_tracker.db', check_same_thread=False)
self.statement_parser = BankStatementParser()
self.setup_database()
def setup_database(self):
"""Set up the necessary database tables"""
cursor = self.conn.cursor()
# Create transactions table
cursor.execute('''
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date DATE NOT NULL,
description TEXT NOT NULL,
reference_no TEXT,
type TEXT CHECK(type IN ('debit', 'credit')) NOT NULL,
amount DECIMAL(10,2) NOT NULL DEFAULT 0,
balance DECIMAL(10,2) NOT NULL DEFAULT 0,
category TEXT,
tags TEXT,
source TEXT NOT NULL DEFAULT 'manual',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create budgets table
cursor.execute('''
CREATE TABLE IF NOT EXISTS budgets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
amount DECIMAL(10,2) NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create categories table
cursor.execute('''
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
type TEXT CHECK(type IN ('expense', 'income', 'transfer')) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create payment request tickets table
cursor.execute('''
CREATE TABLE IF NOT EXISTS payment_request_tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ticket_number TEXT UNIQUE NOT NULL,
department TEXT NOT NULL,
amount DECIMAL(10,2) NOT NULL,
description TEXT NOT NULL,
purpose TEXT NOT NULL,
vendor_name TEXT,
vendor_account TEXT,
supporting_documents TEXT,
status TEXT CHECK(status IN ('pending', 'approved', 'rejected', 'dispatched')) NOT NULL DEFAULT 'pending',
priority TEXT CHECK(priority IN ('low', 'medium', 'high', 'urgent')) NOT NULL DEFAULT 'medium',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Add default categories
default_categories = [
('Salary', 'income', 'Regular salary income'),
('Sales Revenue', 'income', 'Income from sales'),
('Office Supplies', 'expense', 'Office supplies and stationery'),
('Utilities', 'expense', 'Electricity, water, internet, etc.'),
('Marketing', 'expense', 'Marketing and advertising expenses'),
('Travel', 'expense', 'Business travel expenses'),
('Transfer', 'transfer', 'Internal transfers'),
('Other', 'expense', 'Miscellaneous expenses')
]
cursor.executemany('''
INSERT OR IGNORE INTO categories (name, type, description)
VALUES (?, ?, ?)
''', default_categories)
self.conn.commit()
def process_bank_statement(self, file, file_type):
"""Process uploaded bank statement"""
try:
file_content = file.read()
file.seek(0)
if file_type.lower() == 'pdf':
df = self.statement_parser.parse_pdf_statement(file)
else:
df = self.statement_parser.parse_excel_statement(file_content)
cursor = self.conn.cursor()
transactions_added = 0
duplicates_found = 0
for _, row in df.iterrows():
cursor.execute('''
SELECT COUNT(*) FROM transactions
WHERE date = ? AND description = ? AND amount = ? AND type = ?
''', (
row['date'].strftime('%Y-%m-%d'),
row['description'],
float(row['amount']),
row['type']
))
if cursor.fetchone()[0] == 0:
cursor.execute('''
INSERT INTO transactions
(date, description, reference_no, type, amount, balance, source)
VALUES (?, ?, ?, ?, ?, ?, 'bank_statement')
''', (
row['date'].strftime('%Y-%m-%d'),
row['description'],
row['reference'],
row['type'],
float(row['amount']),
float(row['balance'])
))
transactions_added += 1
else:
duplicates_found += 1
self.conn.commit()
message = f"Successfully processed {transactions_added} new transaction(s)"
if duplicates_found > 0:
message += f" and skipped {duplicates_found} duplicate(s)"
return True, message
except Exception as e:
return False, str(e)
def add_manual_transaction(self, date, description, amount, category, transaction_type, reference_no=None):
"""Add a manual transaction"""
cursor = self.conn.cursor()
try:
cursor.execute('''
INSERT INTO transactions
(date, description, reference_no, type, amount, category, source)
VALUES (?, ?, ?, ?, ?, ?, 'manual')
''', (date, description, reference_no, transaction_type, amount, category))
transaction_id = cursor.lastrowid
self.conn.commit()
return transaction_id
except Exception as e:
self.conn.rollback()
raise e
def delete_manual_transaction(self, transaction_id):
"""Delete a manually entered transaction"""
cursor = self.conn.cursor()
try:
cursor.execute('SELECT source FROM transactions WHERE id = ?', (transaction_id,))
result = cursor.fetchone()
if not result or result[0] != 'manual':
raise ValueError("Only manually entered transactions can be deleted")
cursor.execute('DELETE FROM transactions WHERE id = ?', (transaction_id,))
self.conn.commit()
return True, "Transaction deleted successfully"
except Exception as e:
self.conn.rollback()
return False, f"Error deleting transaction: {str(e)}"
def get_transactions(self, start_date=None, end_date=None, category=None, transaction_type=None):
"""Retrieve transactions with filters"""
query = "SELECT * FROM transactions WHERE 1=1"
params = []
if start_date:
query += " AND date >= ?"
params.append(start_date)
if end_date:
query += " AND date <= ?"
params.append(end_date)
if category:
query += " AND category = ?"
params.append(category)
if transaction_type:
query += " AND type = ?"
params.append(transaction_type)
query += " ORDER BY date DESC, id DESC"
cursor = self.conn.cursor()
cursor.execute(query, params)
return cursor.fetchall()
def get_transaction_summary(self, start_date=None, end_date=None):
"""Get transaction summary including total debits, credits, and balance"""
cursor = self.conn.cursor()
query = '''
SELECT
COUNT(*) as total_transactions,
COALESCE(SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END), 0) as total_debits,
COALESCE(SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END), 0) as total_credits,
COALESCE((SELECT balance FROM transactions
WHERE date <= ? ORDER BY date DESC, id DESC LIMIT 1), 0) as closing_balance
FROM transactions
WHERE date BETWEEN ? AND ?
'''
end_date = end_date or datetime.now().date()
start_date = start_date or (end_date - timedelta(days=30))
cursor.execute(query, (end_date, start_date, end_date))
result = cursor.fetchone()
return (
result[0] or 0,
float(result[1] or 0),
float(result[2] or 0),
float(result[3] or 0)
)
def get_category_summary(self, start_date=None, end_date=None, transaction_type=None):
"""Get summary of transactions by category"""
query = '''
SELECT
COALESCE(category, 'Uncategorized') as category,
SUM(amount) as total_amount,
COUNT(*) as transaction_count
FROM transactions
WHERE date BETWEEN ? AND ?
'''
params = [start_date or '1900-01-01', end_date or '9999-12-31']
if transaction_type:
query += " AND type = ?"
params.append(transaction_type)
query += " GROUP BY category ORDER BY total_amount DESC"
cursor = self.conn.cursor()
cursor.execute(query, params)
return cursor.fetchall()
def generate_ticket_number(self):
"""Generate a unique ticket number for payment requests"""
cursor = self.conn.cursor()
today = datetime.now().strftime('%Y%m%d')
cursor.execute("""
SELECT ticket_number FROM payment_request_tickets
WHERE ticket_number LIKE ?
ORDER BY ticket_number DESC LIMIT 1
""", (f'PR-{today}-%',))
result = cursor.fetchone()
if result:
last_number = int(result[0].split('-')[-1])
new_number = str(last_number + 1).zfill(4)
else:
new_number = '0001'
return f'PR-{today}-{new_number}'
def create_payment_request(self, department, amount, description, purpose,
vendor_name=None, vendor_account=None, priority='medium'):
"""Create a new payment request ticket"""
cursor = self.conn.cursor()
try:
ticket_number = self.generate_ticket_number()
cursor.execute("""
INSERT INTO payment_request_tickets (
ticket_number, department, amount, description,
purpose, vendor_name, vendor_account, priority
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
ticket_number, department, amount, description,
purpose, vendor_name, vendor_account, priority
))
ticket_id = cursor.lastrowid
self.conn.commit()
return ticket_id, ticket_number
except Exception as e:
self.conn.rollback()
raise Exception(f"Error creating payment request: {str(e)}")
def update_payment_request(self, ticket_id, status, comments=None):
"""Update payment request status"""
cursor = self.conn.cursor()
try:
cursor.execute("""
UPDATE payment_request_tickets
SET status = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (status, ticket_id))
self.conn.commit()
return True
except Exception as e:
self.conn.rollback()
raise Exception(f"Error updating payment request: {str(e)}")
def get_payment_requests(self, status=None, department=None):
"""Get payment requests with optional filters"""
query = "SELECT * FROM payment_request_tickets WHERE 1=1"
params = []
if status:
query += " AND status = ?"
params.append(status)
if department:
query += " AND department = ?"
params.append(department)
query += " ORDER BY created_at DESC"
cursor = self.conn.cursor()
cursor.execute(query, params)
return cursor.fetchall()
class BudgetTrackerUI:
"""
Main user interface class for the budget tracking application.
Handles all UI components and user interactions, integrating with
the core BudgetTracker and BudgetManager functionality.
"""
def __init__(self):
"""
Initialize the UI with necessary components:
- BudgetTracker for core functionality
- BudgetManager for enhanced budget management
- Streamlit page configuration
"""
self.tracker = BudgetTracker()
self.tracker.budget_manager = BudgetManager(self.tracker.conn)
st.set_page_config(
page_title="Budget Tracker",
layout="wide",
initial_sidebar_state="expanded"
)
def run(self):
"""
Main application entry point. Sets up the navigation and
routes to appropriate page handlers based on user selection.
"""
st.title("Budget and Expense Tracking Platform")
# Main navigation in sidebar
page = st.sidebar.selectbox(
"Navigation",
["Dashboard", "Transactions", "Bank Statements",
"Enhanced Budget Management", "Payment Requests", "Analytics"]
)
# Route to appropriate page handler
if page == "Dashboard":
self.show_dashboard()
elif page == "Transactions":
self.show_transactions()
elif page == "Bank Statements":
self.show_bank_statements()
elif page == "Enhanced Budget Management":
self.show_enhanced_budget_management()
elif page == "Payment Requests":
self.show_payment_requests()
elif page == "Analytics":
self.show_analytics()
def show_dashboard(self):
"""
Display the main dashboard with key metrics and recent activity.
Includes summary statistics and visualizations of budget health.
"""
st.header("Dashboard")
# Date range selection for dashboard metrics
col1, col2 = st.columns(2)
with col1:
start_date = st.date_input(
"From Date",
value=datetime.now().date() - timedelta(days=30)
)
with col2:
end_date = st.date_input("To Date", value=datetime.now().date())
try:
# Get and display summary metrics
summary = self.tracker.get_transaction_summary(start_date, end_date)
total_transactions, total_debits, total_credits, closing_balance = summary
# Display key metrics in columns
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
"Total Transactions",
f"{int(total_transactions):,}",
help="Number of transactions in selected period"
)
with col2:
st.metric(
"Total Debits",
f"₹{float(total_debits):,.2f}",
help="Total outgoing funds"
)
with col3:
st.metric(
"Total Credits",
f"₹{float(total_credits):,.2f}",
help="Total incoming funds"
)
with col4:
st.metric(
"Closing Balance",
f"₹{float(closing_balance):,.2f}",
delta=f"₹{float(total_credits - total_debits):,.2f}",
delta_color="normal" if total_credits >= total_debits else "inverse"
)
# Display recent transactions
st.subheader("Recent Transactions")
transactions = self.tracker.get_transactions(start_date, end_date)
if transactions:
df = pd.DataFrame(
transactions,
columns=['id', 'date', 'description', 'reference_no',
'type', 'amount', 'balance', 'category',
'tags', 'source', 'created_at']
)
# Format data for display
df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y-%m-%d')
df['amount'] = df.apply(lambda x: f"₹{x['amount']:,.2f}", axis=1)
df['balance'] = df.apply(lambda x: f"₹{x['balance']:,.2f}", axis=1)
# Apply conditional formatting
def highlight_type(row):
if row['type'] == 'debit':
return ['background-color: #ffebee'] * len(row)
elif row['type'] == 'credit':
return ['background-color: #e8f5e9'] * len(row)
return ['background-color: #f5f5f5'] * len(row)
styled_df = (df.style
.apply(highlight_type, axis=1)
.set_properties(**{
'background-color': '#f5f5f5',
'color': 'black',
'border-color': '#ddd'
}))
st.dataframe(styled_df, height=400)
else:
st.info("No transactions found for the selected period.")
except Exception as e:
st.error(f"Error loading dashboard: {str(e)}")
def show_enhanced_budget_management(self):
"""
Enhanced budget management interface with multiple tabs for
different budget management functions.
"""
st.header("Enhanced Budget Management")
# Navigation tabs for different budget management functions
tabs = st.tabs([
"Budget Overview",
"Create Budget",
"Transaction Mapping",
"Budget Analytics"
])
# Handle each tab's content
with tabs[0]:
self.show_budget_overview()
with tabs[1]:
self.show_budget_creation()
with tabs[2]:
self.show_transaction_mapping()
with tabs[3]:
self.show_budget_analytics()
def show_budget_overview(self):
"""
Display comprehensive overview of all budgets and their utilization.
This method provides a detailed view of budget performance including:
- Period selection with budget counts
- Summary metrics for the selected period
- Individual budget progress with detailed metrics
- Burn rate analysis and projections
"""
st.subheader("Budget Overview")
# First, retrieve all budget periods with their associated budget counts
cursor = self.tracker.conn.cursor()
cursor.execute("""
SELECT
bp.id,
bp.name,
bp.start_date,
bp.end_date,
COUNT(b.id) as budget_count,
bp.status
FROM budget_periods bp
LEFT JOIN enhanced_budgets b ON bp.id = b.period_id
GROUP BY bp.id
ORDER BY bp.start_date DESC
""")
periods = cursor.fetchall()
if not periods:
st.warning("No budget periods defined. Please create a budget period first.")
st.write("""
To get started:
1. Go to the 'Create Budget' tab
2. Choose 'Create New' under Budget Period
3. Define your first budget period
""")
return
# Create a user-friendly period selection dropdown
period_options = [
f"{p[1]} ({p[2]} to {p[3]}) - {p[4]} budgets - {p[5]}"
for p in periods
]
selected_index = st.selectbox(
"Select Budget Period",
range(len(periods)),
format_func=lambda x: period_options[x]
)
selected_period = periods[selected_index]
# Display period details for context
st.write("### Period Details")
st.write(f"**Period:** {selected_period[1]}")
st.write(f"**Duration:** {selected_period[2]} to {selected_period[3]}")
st.write(f"**Status:** {selected_period[5]}")
st.write(f"**Number of Budgets:** {selected_period[4]}")
# Retrieve all budgets for the selected period with detailed information
cursor.execute("""
SELECT
bc.name as category_name,
b.amount as budget_amount,
COALESCE(b.rollover_amount, 0) as rollover_amount,
COALESCE(SUM(m.amount), 0) as spent_amount,
COUNT(DISTINCT m.transaction_id) as transaction_count,
b.alert_threshold,
b.created_at,
bc.id as category_id,
b.id as budget_id
FROM enhanced_budgets b
JOIN budget_categories bc ON b.category_id = bc.id
LEFT JOIN budget_transaction_mapping m ON b.id = m.budget_id
WHERE b.period_id = ?
GROUP BY b.id, bc.name
ORDER BY bc.name
""", (selected_period[0],))
budgets = cursor.fetchall()
if not budgets:
st.info(f"""No budgets found for period: {selected_period[1]}
To create a budget:
1. Go to the 'Create Budget' tab
2. Select or create a category
3. Set the budget amount and period
4. Click 'Create Budget' to save""")
return
# Calculate and display summary metrics
total_budget = sum(float(b[1]) + float(b[2]) for b in budgets)
total_spent = sum(float(b[3]) for b in budgets)
# Display summary metrics in columns
col1, col2, col3 = st.columns(3)
with col1:
st.metric(
"Total Budget",
f"₹{total_budget:,.2f}",
help="Total budget allocated for this period"
)
with col2:
utilization = (total_spent/total_budget * 100) if total_budget > 0 else 0
st.metric(
"Total Spent",
f"₹{total_spent:,.2f}",
delta=f"{utilization:.1f}%",
delta_color="inverse"
)
with col3:
st.metric(
"Remaining Budget",
f"₹{(total_budget - total_spent):,.2f}",
help="Total remaining budget across all categories"
)
# Calculate period metrics for burn rate calculations
start_date = datetime.strptime(selected_period[2], '%Y-%m-%d')
end_date = datetime.strptime(selected_period[3], '%Y-%m-%d')
total_days = (end_date - start_date).days
days_elapsed = (datetime.now() - start_date).days
days_remaining = (end_date - datetime.now()).days
# Display individual budget progress
st.subheader("Budget Progress by Category")
for budget in budgets:
category_name = budget[0]
budget_amount = float(budget[1]) + float(budget[2]) # Include rollover
spent_amount = float(budget[3])
transaction_count = budget[4]
alert_threshold = float(budget[5] or 80) # Default to 80% if not set
created_at = budget[6]
with st.container():
col1, col2 = st.columns([3, 1])
with col1:
st.write(f"**{category_name}**")
progress = (spent_amount / budget_amount) if budget_amount > 0 else 0
st.progress(min(progress, 1.0))
if progress >= (alert_threshold / 100):
st.warning(f"⚠️ Alert: Utilization {progress:.1%} exceeds threshold {alert_threshold:.1f}%")
elif progress > 1.0:
st.error(f"🚨 Over budget: {progress:.1%}")
with col2:
st.write(f"₹{spent_amount:,.2f} / ₹{budget_amount:,.2f}")
with st.expander(f"View Details - {category_name}"):
detail_col1, detail_col2 = st.columns(2)
# Calculate burn rate and projections
daily_burn = spent_amount / max(1, days_elapsed)
monthly_burn = daily_burn * 30
projected_total = spent_amount + (daily_burn * days_remaining)
with detail_col1:
st.write(f"**Budget Details:**")
st.write(f"- Created: {created_at}")
st.write(f"- Allocated: ₹{budget_amount:,.2f}")
st.write(f"- Spent: ₹{spent_amount:,.2f}")
st.write(f"- Remaining: ₹{(budget_amount - spent_amount):,.2f}")
st.write(f"- Utilization: {(progress * 100):.1f}%")
with detail_col2:
st.write(f"**Metrics:**")
st.write(f"- Daily Burn Rate: ₹{daily_burn:,.2f}")
st.write(f"- Monthly Burn Rate: ₹{monthly_burn:,.2f}")
st.write(f"- Transaction Count: {transaction_count}")
st.write(f"- Days Remaining: {max(0, days_remaining)}")
# Display recent transactions for this budget
if transaction_count > 0:
st.write("**Recent Transactions:**")
cursor.execute("""
SELECT
t.date,
t.description,
m.amount,
m.created_at
FROM budget_transaction_mapping m
JOIN transactions t ON m.transaction_id = t.id
WHERE m.budget_id = ?
ORDER BY t.date DESC
LIMIT 5
""", (budget[8],))
recent_transactions = cursor.fetchall()
for txn in recent_transactions:
st.write(f"- {txn[0]}: ₹{float(txn[2]):,.2f} - {txn[1]}")
if projected_total > budget_amount:
st.warning(f"""
⚠️ Projected Overspend Warning:
At the current burn rate of ₹{daily_burn:,.2f}/day,
this budget is projected to exceed its limit by ₹{(projected_total - budget_amount):,.2f}
""")
st.write("---")
def show_budget_creation(self):
"""
Interface for creating new budgets and categories.
Includes forms for both category and budget creation.
"""
st.subheader("Create New Budget")
# Two columns: Categories and Budget Creation
col1, col2 = st.columns(2)
with col1:
st.write("### Budget Categories")
# Form for creating new categories
with st.form("category_form"):
category_name = st.text_input("Category Name")
category_desc = st.text_area("Description")
# Get existing categories for parent selection
cursor = self.tracker.conn.cursor()
cursor.execute("SELECT id, name FROM budget_categories")
categories = cursor.fetchall()
parent_category = st.selectbox(
"Parent Category (Optional)",
options=[None] + categories,
format_func=lambda x: "None" if x is None else x[1]
)
if st.form_submit_button("Create Category"):
try:
parent_id = parent_category[0] if parent_category else None
self.tracker.budget_manager.create_budget_category(
category_name,
category_desc,
parent_id
)
st.success("Category created successfully!")
# Store success state in session state
st.session_state.category_created = True
st.rerun()
except Exception as e:
st.error(f"Error creating category: {str(e)}")
with col2:
st.write("### Create Budget")
with st.form("budget_form"):
# Category selection
cursor = self.tracker.conn.cursor()
cursor.execute("SELECT id, name FROM budget_categories")
categories = cursor.fetchall()
categories_dict = dict(categories)
if not categories:
st.warning("Please create a category first")
st.form_submit_button("Create Budget", disabled=True)
return
selected_category = st.selectbox(
"Category",
options=categories,
format_func=lambda x: x[1]
)
# Period creation/selection
period_type = st.radio(
"Budget Period",
options=["Create New", "Use Existing"]
)
if period_type == "Create New":
period_name = st.text_input("Period Name")
start_date = st.date_input("Start Date")