Repository navigation
Expand file tree
/
Copy pathfriends.py
More file actions
160 lines (143 loc) Β· 6.63 KB
/
Copy pathfriends.py
File metadata and controls
160 lines (143 loc) Β· 6.63 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
from auth import logout, check_login
import streamlit as st
import pandas as pd
from sqlalchemy import text
from database import conn, cred_table
def friends_page(cookies):
check_login()
user = st.session_state.current_user
USERS = conn.query("SELECT username, paircode FROM credentials", ttl=0)
USERS = USERS.drop(USERS.loc[USERS["username"] == user].index, axis = 0)
friends_query = f"""
SELECT
CASE
WHEN user1 = '{user}' THEN user2
ELSE user1
END as friend_name
FROM friends
WHERE (user1 = '{user}' OR user2 = '{user}') AND status = 'accepted'
"""
existing_friend = conn.query(friends_query, ttl=0)['friend_name'].to_list()
col1, col2 = st.columns([3, 1])
with col1:
st.title("π₯ Friends")
st.write(f"Welcome back, **{user}**! π")
with col2:
if st.button("β¬
οΈ Back to Dashboard", use_container_width=True):
st.session_state.page = "dashboard"
st.rerun()
if st.button("πͺ Logout", use_container_width=True):
logout(cookies)
st.divider()
st.markdown("### β Add a New Friend")
with st.container(border=True):
st.radio("Search Method", ("By UserName", "By PairCode"), index=0, key="radio", horizontal=True)
if st.session_state.radio == "By UserName":
friend = st.selectbox("Select friend to add", sorted(USERS["username"]),index=None, placeholder = "π Search by UserName")
if friend:
st.write("You Selected : ", friend)
submit = st.button("Send Friend Request", type="primary")
elif st.session_state.radio == "By PairCode":
paircode = st.selectbox("Get friend via paircode", sorted(USERS["paircode"]),index=None, placeholder = "π Search by PairCode")
if paircode:
st.write("You selected : ", paircode)
submit = st.button("Send Friend Request", type="primary")
try:
friend = USERS[(USERS["paircode"] == paircode)]["username"].to_list()[0]
if paircode:
st.write("Username : ", friend)
except:
if paircode:
st.error("Friend not found")
if submit:
with conn.session as s:
check_query = '''SELECT id, status FROM friends
WHERE (user1 = '{user}' AND user2 = '{friend}')
OR (user1 = '{friend}' AND user2 = '{user}')'''
existing = conn.query(check_query.format(user=user, friend=friend), ttl=0)
if not existing.empty:
st.error(f"You and {friend} are already friends or have a pending request.")
else:
insert_query = '''INSERT INTO friends (user1, user2, status) VALUES ('{user}', '{friend}', 'sent')'''
s.execute(text(insert_query.format(user=user, friend=friend)))
s.commit()
st.success(f"Friend request sent to {friend} successfully! β
")
st.toast("Adding a new friend soon ... πββοΈ")
st.divider()
all_query = """
SELECT user1, user2, status FROM friends WHERE user2 = '{}'
"""
all_friend = conn.query(all_query.format(user), ttl=0)
pending_friend = all_friend[all_friend['status'] == 'sent']
st.markdown("### π Pending Friend Requests")
if pending_friend.empty:
st.info("You don't have any pending friend requests right now.")
else:
for f in pending_friend['user1'].to_list():
with st.container(border=True):
colA, colB, colC = st.columns([3,1,1])
with colA:
st.markdown(f"**π€ {f}** wants to be your friend!")
with colB:
if st.button("β
Accept", key=f"accept_{f}", use_container_width=True):
with conn.session as s:
accept_query = f"""
UPDATE friends SET status = 'accepted'
WHERE user1 = '{user}' AND user2 = '{f}'
OR user1 = '{f}' AND user2 = '{user}'
"""
s.execute(text(accept_query))
s.commit()
st.success(f"Friend request from {f} accepted!")
st.rerun()
with colC:
if st.button("β Decline", key=f"decline_{f}", type="primary", use_container_width=True):
with conn.session as s:
decline_query = f"""
DELETE FROM friends
WHERE user1 = '{user}' AND user2 = '{f}'
OR user1 = '{f}' AND user2 = '{user}'
"""
s.execute(text(decline_query))
s.commit()
st.error(f"Friend request from {f} declined.")
st.rerun()
st.divider()
st.markdown("### π€ My Friends List")
if not existing_friend:
st.info("You don't have any friends yet.")
else:
trans_query = f"""
SELECT *
FROM transactions
WHERE (lender = '{user}' OR borrower = '{user}')
"""
df_trans = conn.query(trans_query, ttl=0)
if len(existing_friend) <= 4:
cols = st.columns(2)
else:
cols = st.columns(3)
for i, f in enumerate(existing_friend):
lended = 0.0
borrowed = 0.0
if not df_trans.empty:
lended = df_trans[(df_trans['lender'] == user) & (df_trans['borrower'] == f)]['amount'].sum()
borrowed = df_trans[(df_trans['borrower'] == user) & (df_trans['lender'] == f)]['amount'].sum()
net = lended - borrowed
with cols[i % len(cols)]:
st.markdown(f"""
<div style="padding:15px; border-radius:10px; border:1px solid #ddd;">
<h4>π€ {f}</h4>
<div style="margin-left:10rem;">
<p><b>Lended:</b> {lended}</p>
<p><b>Borrowed:</b> {borrowed}</p>
<p><b>Net Balance:</b>
<span style="color:{'green' if net >= 0 else 'red'}; font-size:18px;">
βΉ {net}
</span>
</p>
</div>
</div>
<p></p>
""", unsafe_allow_html=True)
st.divider()