Akshayram1 commited on
Commit
737dc7a
ยท
verified ยท
1 Parent(s): 2eed54e

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +185 -0
app2.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import firebase_admin
3
+ from firebase_admin import credentials, auth, db
4
+ import pandas as pd
5
+ import plotly.express as px
6
+ from datetime import datetime
7
+
8
+ # Initialize Firebase
9
+ try:
10
+ if not firebase_admin._apps:
11
+ cred = credentials.Certificate("serviceAccountKey.json")
12
+ firebase_admin.initialize_app(cred, {
13
+ 'databaseURL': 'https://transacapp-22b6e-default-rtdb.firebaseio.com/'
14
+ })
15
+ except Exception as e:
16
+ st.error(f"Error initializing Firebase: {str(e)}")
17
+ st.stop()
18
+
19
+ def login():
20
+ st.title("๐Ÿ“Š Financial Dashboard Login")
21
+
22
+ with st.form("login_form"):
23
+ email = st.text_input("Email")
24
+ password = st.text_input("Password", type="password")
25
+ submit_button = st.form_submit_button("Login")
26
+
27
+ if submit_button:
28
+ try:
29
+ user = auth.get_user_by_email(email)
30
+ st.session_state['user'] = user
31
+ st.success("Logged in successfully!")
32
+ st.experimental_rerun()
33
+ except Exception as e:
34
+ st.error("Invalid credentials. Please try again.")
35
+ return submit_button
36
+ return False
37
+
38
+ def get_user_transactions(uid):
39
+ try:
40
+ transactions = []
41
+ # Get all financial messages for the user
42
+ ref = db.reference(f'financialMessages/{uid}')
43
+ financial_data = ref.get()
44
+
45
+ if financial_data:
46
+ for month, month_data in financial_data.items():
47
+ if isinstance(month_data, dict):
48
+ for trans_id, trans_data in month_data.items():
49
+ if isinstance(trans_data, dict):
50
+ trans_data['month'] = month
51
+ # Convert amount to float if it's a string
52
+ if 'amount' in trans_data:
53
+ try:
54
+ trans_data['amount'] = float(str(trans_data['amount']).replace(',', ''))
55
+ except ValueError:
56
+ trans_data['amount'] = 0.0
57
+ transactions.append(trans_data)
58
+
59
+ df = pd.DataFrame(transactions)
60
+ return df if not df.empty else pd.DataFrame(columns=[
61
+ 'accountNumber', 'amount', 'personName', 'referenceNo',
62
+ 'transactionDate', 'transactionType', 'month'
63
+ ])
64
+
65
+ except Exception as e:
66
+ st.error(f"Error fetching transactions: {str(e)}")
67
+ return pd.DataFrame()
68
+
69
+ def main():
70
+ st.set_page_config(page_title="Financial Dashboard", page_icon="๐Ÿ’ฐ", layout="wide")
71
+
72
+ if 'user' not in st.session_state:
73
+ if not login():
74
+ return
75
+
76
+ st.title("๐Ÿ’ฐ Financial Dashboard")
77
+
78
+ # Add logout button
79
+ # Add logout button
80
+ if st.sidebar.button("Logout"):
81
+ st.session_state.pop('user', None)
82
+ st.rerun() # Updated line
83
+
84
+
85
+ # Get user data
86
+ user = st.session_state['user']
87
+ df = get_user_transactions(user.uid)
88
+
89
+ if df.empty:
90
+ st.warning("No transactions found for this account.")
91
+ return
92
+
93
+ # Date filters
94
+ st.sidebar.header("๐Ÿ“… Filters")
95
+ months = sorted(df['month'].unique())
96
+ selected_months = st.sidebar.multiselect("Select Months", months, default=months)
97
+
98
+ # Transaction type filter
99
+ transaction_types = sorted(df['transactionType'].unique())
100
+ selected_types = st.sidebar.multiselect("Transaction Types", transaction_types, default=transaction_types)
101
+
102
+ # Filter data
103
+ filtered_df = df[
104
+ (df['month'].isin(selected_months)) &
105
+ (df['transactionType'].isin(selected_types))
106
+ ]
107
+
108
+ # Dashboard layout
109
+ col1, col2, col3 = st.columns(3)
110
+
111
+ with col1:
112
+ st.metric("Total Transactions", len(filtered_df))
113
+ with col2:
114
+ debited = filtered_df[filtered_df['transactionType'] == 'debited']['amount'].sum()
115
+ credited = filtered_df[filtered_df['transactionType'] == 'credited']['amount'].sum()
116
+ net_amount = credited - debited
117
+ st.metric("Net Amount", f"โ‚น{net_amount:,.2f}")
118
+ with col3:
119
+ avg_amount = filtered_df['amount'].mean()
120
+ st.metric("Average Transaction", f"โ‚น{avg_amount:,.2f}")
121
+
122
+ # Visualizations
123
+ st.subheader("๐Ÿ“Š Transaction Analysis")
124
+
125
+ # Create two columns for charts
126
+ chart_col1, chart_col2 = st.columns(2)
127
+
128
+ with chart_col1:
129
+ # Monthly transaction summary
130
+ monthly_summary = filtered_df.groupby(['month', 'transactionType']).agg({
131
+ 'amount': 'sum'
132
+ }).reset_index()
133
+
134
+ fig1 = px.bar(monthly_summary, x='month', y='amount', color='transactionType',
135
+ title='Monthly Transaction Volume by Type',
136
+ labels={'amount': 'Amount (โ‚น)', 'month': 'Month'},
137
+ barmode='group')
138
+ st.plotly_chart(fig1, use_container_width=True)
139
+
140
+ with chart_col2:
141
+ # Transaction type distribution
142
+ fig2 = px.pie(filtered_df, values='amount', names='transactionType',
143
+ title='Transaction Amount Distribution by Type')
144
+ st.plotly_chart(fig2, use_container_width=True)
145
+
146
+ # Transaction Trends
147
+ fig3 = px.line(monthly_summary, x='month', y='amount', color='transactionType',
148
+ title='Transaction Trends Over Time',
149
+ labels={'amount': 'Amount (โ‚น)', 'month': 'Month'})
150
+ st.plotly_chart(fig3, use_container_width=True)
151
+
152
+ # Detailed transaction table
153
+ st.subheader("๐Ÿ“ Recent Transactions")
154
+
155
+ # Format the dataframe for display
156
+ display_df = filtered_df.copy()
157
+ display_df['amount'] = display_df['amount'].apply(lambda x: f"โ‚น{x:,.2f}")
158
+ display_df = display_df.sort_values('transactionDate', ascending=False)
159
+
160
+ # Display as a styled dataframe
161
+ st.dataframe(
162
+ display_df,
163
+ column_config={
164
+ "transactionDate": "Date",
165
+ "transactionType": "Type",
166
+ "amount": "Amount",
167
+ "personName": "Person",
168
+ "referenceNo": "Reference",
169
+ "accountNumber": "Account"
170
+ },
171
+ hide_index=True
172
+ )
173
+
174
+ # Add download button for CSV
175
+ if st.button("Download Transaction Data"):
176
+ csv = filtered_df.to_csv(index=False)
177
+ st.download_button(
178
+ label="Download CSV",
179
+ data=csv,
180
+ file_name="transactions.csv",
181
+ mime="text/csv"
182
+ )
183
+
184
+ if __name__ == "__main__":
185
+ main()