Akshayram1 commited on
Commit
6b86a11
·
verified ·
1 Parent(s): a3d096a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -43
app.py CHANGED
@@ -1,56 +1,245 @@
1
  import streamlit as st
2
- import requests
 
 
 
 
3
 
4
- # Firebase Auth REST API to login
5
- def firebase_login(email, password):
 
 
 
 
 
 
 
 
 
6
  try:
7
- api_key = "AIzaSyBEL99hu6ja9LjNABpBRL1QtHCAVSh1umQ" # Your Firebase Web API Key
8
- url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={api_key}"
9
- payload = {"email": email, "password": password, "returnSecureToken": True}
10
- response = requests.post(url, data=payload)
11
-
12
- if response.status_code == 200:
13
- user_data = response.json()
14
- return user_data['localId'], user_data['idToken']
15
- else:
16
- return None, None
17
  except Exception as e:
18
- st.error(f"Error logging in: {str(e)}")
19
- return None, None
20
-
21
- def main():
22
- st.set_page_config(page_title="Login", layout="centered")
23
 
24
- # Check login state
25
- if "logged_in" not in st.session_state:
26
- st.session_state.logged_in = False
27
-
28
- # Check if already logged in
29
- if st.session_state.logged_in:
30
- st.write("You are already logged in.")
31
- st.write("Redirecting to your dashboard...")
32
 
33
- # Redirect by setting query parameter
34
- st.query_params.page = "app2"
35
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- # Login form if not logged in
38
- email = st.text_input("Email")
39
- password = st.text_input("Password", type="password")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- if st.button("Login"):
42
- user_id, id_token = firebase_login(email, password)
43
- if user_id:
44
- st.session_state.logged_in = True
45
- st.session_state.email = email
46
- st.session_state.user_id = user_id
 
 
 
47
 
48
- # Set query parameter to redirect to app2.py
49
- st.query_params.page = "app2"
 
 
 
 
50
 
51
- st.success("Login successful! Redirecting to your dashboard...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  else:
53
- st.error("Login failed. Please check your credentials.")
54
 
55
  if __name__ == "__main__":
56
- main()
 
1
  import streamlit as st
2
+ import firebase_admin
3
+ from firebase_admin import credentials, db
4
+ import pandas as pd
5
+ import plotly.express as px
6
+ from datetime import datetime
7
 
8
+ # Initialize Firebase Realtime Database
9
+ try:
10
+ app = firebase_admin.get_app()
11
+ except ValueError:
12
+ cred = credentials.Certificate("serviceAccountKey.json")
13
+ app = firebase_admin.initialize_app(cred, {
14
+ 'databaseURL': 'https://transacapp-22b6e-default-rtdb.firebaseio.com/'
15
+ })
16
+
17
+ def fetch_usernames():
18
+ """Fetch list of all usernames from Firebase"""
19
  try:
20
+ ref = db.reference('financialMessages')
21
+ users = ref.get()
22
+ if users:
23
+ return list(users.keys())
24
+ return []
 
 
 
 
 
25
  except Exception as e:
26
+ st.error(f"Error fetching usernames: {str(e)}")
27
+ return []
 
 
 
28
 
29
+ def fetch_user_transactions(username, selected_month):
30
+ """Fetch financial messages for a specific user and month from Firebase"""
31
+ try:
32
+ ref = db.reference(f'financialMessages/{username}/{selected_month}')
33
+ transactions = ref.get()
34
+
35
+ if not transactions:
36
+ return []
37
 
38
+ messages = []
39
+ for transaction_id, data in transactions.items():
40
+ if isinstance(data, dict):
41
+ messages.append({
42
+ 'Person Name': data.get('personName', ''),
43
+ 'Account Number': data.get('accountNumber', ''),
44
+ 'Amount': float(data.get('amount', 0)),
45
+ 'Reference No': data.get('referenceNo', ''),
46
+ 'Transaction Date': data.get('transactionDate', ''),
47
+ 'Transaction Type': data.get('transactionType', '')
48
+ })
49
+
50
+ return messages
51
+ except Exception as e:
52
+ st.error(f"Error fetching data: {str(e)}")
53
+ return []
54
 
55
+ def create_transaction_distribution_chart(df):
56
+ """Create an enhanced transaction distribution visualization with multiple chart types"""
57
+ # Calculate transaction type summaries
58
+ type_summary = df.groupby('Transaction Type').agg({
59
+ 'Person Name': 'count',
60
+ 'Amount': ['sum', 'mean', 'min', 'max']
61
+ }).round(2)
62
+
63
+ type_summary.columns = ['Count', 'Total Amount', 'Average Amount', 'Min Amount', 'Max Amount']
64
+ type_summary = type_summary.reset_index()
65
+
66
+ # Create bar chart comparing transaction counts and amounts
67
+ fig_comparison = px.bar(
68
+ type_summary,
69
+ x='Transaction Type',
70
+ y=['Count', 'Total Amount'],
71
+ barmode='group',
72
+ title='Transaction Comparison by Type',
73
+ labels={'value': 'Value', 'variable': 'Metric'},
74
+ color_discrete_sequence=['#4C78A8', '#72B7B2'],
75
+ template='plotly_white'
76
+ )
77
+
78
+ fig_comparison.update_layout(
79
+ xaxis_title="Transaction Type",
80
+ yaxis_title="Value",
81
+ legend_title="Metric",
82
+ height=400,
83
+ showlegend=True,
84
+ legend=dict(
85
+ orientation="h",
86
+ yanchor="bottom",
87
+ y=1.02,
88
+ xanchor="right",
89
+ x=1
90
+ )
91
+ )
92
+
93
+ # Create detailed metrics visualization
94
+ fig_metrics = px.bar(
95
+ type_summary.melt(
96
+ id_vars=['Transaction Type'],
97
+ value_vars=['Average Amount', 'Min Amount', 'Max Amount']
98
+ ),
99
+ x='Transaction Type',
100
+ y='value',
101
+ color='variable',
102
+ barmode='group',
103
+ title='Transaction Amount Metrics by Type',
104
+ labels={'value': 'Amount (₹)', 'variable': 'Metric'},
105
+ color_discrete_sequence=['#FF9DA7', '#9C755F', '#BAB0AC'],
106
+ template='plotly_white'
107
+ )
108
+
109
+ fig_metrics.update_layout(
110
+ xaxis_title="Transaction Type",
111
+ yaxis_title="Amount (₹)",
112
+ height=400,
113
+ showlegend=True,
114
+ legend=dict(
115
+ orientation="h",
116
+ yanchor="bottom",
117
+ y=1.02,
118
+ xanchor="right",
119
+ x=1
120
+ )
121
+ )
122
+
123
+ # Add hover information
124
+ for fig in [fig_comparison, fig_metrics]:
125
+ fig.update_traces(
126
+ hovertemplate="<br>".join([
127
+ "Transaction Type: %{x}",
128
+ "Value: %{y:,.2f}",
129
+ "<extra></extra>"
130
+ ])
131
+ )
132
+
133
+ return fig_comparison, fig_metrics
134
 
135
+ def main():
136
+ st.set_page_config(page_title="Financial Transactions Dashboard", layout="wide")
137
+
138
+ # Header
139
+ st.title("Financial Transactions Dashboard")
140
+ st.markdown("---")
141
+
142
+ # Sidebar filters
143
+ st.sidebar.header("Filters")
144
 
145
+ # Username dropdown
146
+ usernames = fetch_usernames()
147
+ username = st.sidebar.selectbox(
148
+ "Select Username",
149
+ options=usernames if usernames else ["No users found"]
150
+ )
151
 
152
+ # Month selection
153
+ months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
154
+ selected_month = st.sidebar.selectbox("Select Month", options=months)
155
+
156
+ if username and username != "No users found":
157
+ # Fetch data
158
+ data = fetch_user_transactions(username, selected_month)
159
+
160
+ if data:
161
+ df = pd.DataFrame(data)
162
+ df['Amount'] = pd.to_numeric(df['Amount'])
163
+
164
+ # Transaction type dropdown
165
+ transaction_type = st.sidebar.selectbox(
166
+ "Select Transaction Type",
167
+ options=["All", "debited", "credited"]
168
+ )
169
+
170
+ # Date filter
171
+ dates = df['Transaction Date'].unique()
172
+ selected_dates = st.sidebar.multiselect(
173
+ "Select Dates",
174
+ options=dates,
175
+ default=dates
176
+ )
177
+
178
+ # Apply filters
179
+ if transaction_type != "All":
180
+ masked_df = df[
181
+ (df['Transaction Type'] == transaction_type) &
182
+ (df['Transaction Date'].isin(selected_dates))
183
+ ]
184
+ else:
185
+ masked_df = df[df['Transaction Date'].isin(selected_dates)]
186
+
187
+ # Dashboard metrics
188
+ col1, col2, col3 = st.columns(3)
189
+
190
+ with col1:
191
+ st.metric("Total Transactions", len(masked_df))
192
+
193
+ with col2:
194
+ total_debited = masked_df[masked_df['Transaction Type'] == 'debited']['Amount'].sum()
195
+ st.metric("Total Debited", f"₹ {total_debited:,.2f}")
196
+
197
+ with col3:
198
+ total_credited = masked_df[masked_df['Transaction Type'] == 'credited']['Amount'].sum()
199
+ st.metric("Total Credited", f"₹ {total_credited:,.2f}")
200
+
201
+ # Transactions table
202
+ st.subheader("Recent Transactions")
203
+ st.dataframe(
204
+ masked_df,
205
+ column_config={
206
+ "Amount": st.column_config.NumberColumn(
207
+ "Amount",
208
+ format="₹ %.2f"
209
+ )
210
+ },
211
+ hide_index=True
212
+ )
213
+
214
+ # Create transaction distribution visualizations
215
+ fig_count, fig_amount = create_transaction_distribution_chart(masked_df)
216
+
217
+ # Display visualizations in columns
218
+ st.subheader("Transaction Distribution Analysis")
219
+ col1, col2 = st.columns(2)
220
+
221
+ with col1:
222
+ st.plotly_chart(fig_count, use_container_width=True)
223
+
224
+ with col2:
225
+ st.plotly_chart(fig_amount, use_container_width=True)
226
+
227
+ # Daily transactions chart
228
+ st.subheader("Daily Transaction Amounts")
229
+ daily_amounts = masked_df.groupby('Transaction Date')['Amount'].sum()
230
+ st.line_chart(daily_amounts)
231
+
232
+ # Download button
233
+ if st.button("Download Transactions"):
234
+ csv = masked_df.to_csv(index=False)
235
+ st.download_button(
236
+ label="Download CSV",
237
+ data=csv,
238
+ file_name=f"{username}_{selected_month}_transactions.csv",
239
+ mime="text/csv"
240
+ )
241
  else:
242
+ st.warning(f"No transactions found for user: {username} in {selected_month}")
243
 
244
  if __name__ == "__main__":
245
+ main()