admin_portal / admin_portal.py
LouaiZahran's picture
Upload folder using huggingface_hub
243c4d0 verified
import gradio as gr
import psycopg2
import pandas as pd
DB_CONNECTION_STRING = "postgresql://aws-0-eu-central-1.pooler.supabase.com:6543/postgres"
DB_USER = "postgres.fokjwzocbnlqjeifhrop"
DB_PASSWORD = "72hj9eKQw5GBMHPn"
# Connect to the PostgreSQL database
def connect_db():
try:
conn = psycopg2.connect(
dbname="postgres",
user=DB_USER,
password=DB_PASSWORD,
host=DB_CONNECTION_STRING.split("//")[1].split(":")[0],
port=DB_CONNECTION_STRING.split(":")[-1].split("/")[0]
)
return conn
except Exception as e:
print("Error connecting to database:", e)
return None
# Function to create HTML clickable links
def make_clickable_wallet_number(df):
df['wallet_number'] = df['wallet_number'].apply(
lambda x: f'<a href="#" onclick="navigator.clipboard.writeText(\'{x}\'); alert(\'Copied: {x}\')">{x}</a>'
)
return gr.Dataframe(value=df, interactive=False, datatype="html")
# Function to retrieve withdrawal requests
def get_withdrawal_requests(filter_status=None):
conn = connect_db()
if conn is None:
return pd.DataFrame()
query = """
SELECT wr.request_id, wr.username, wr.amount, wr.status, wr.created_at, wr.completed_at, uw.wallet_number
FROM withdrawal_requests wr
JOIN user_wallet uw ON wr.wallet_id = uw.id
"""
if filter_status == "completed":
query += " WHERE wr.status = 'completed'"
elif filter_status == "incomplete":
query += " WHERE wr.status = 'incomplete'"
df = pd.read_sql(query, conn)
conn.close()
return df
# Function to update the status of selected requests
def update_request_status(selected_ids, new_status):
conn = connect_db()
if conn is None:
return "Error: Could not connect to the database."
try:
with conn.cursor() as cursor:
completed_at_fn = "NOW()" if new_status == "completed" else "NULL"
update_query = f"""
UPDATE withdrawal_requests
SET status = %s, completed_at = {completed_at_fn} WHERE request_id = ANY(%s)
"""
cursor.execute(update_query, (new_status, "{" + selected_ids + "}"))
conn.commit()
return f"Updated {len(selected_ids.split(','))} requests to {new_status}."
except Exception as e:
conn.rollback()
return f"Error: {e}"
finally:
conn.close()
# Gradio interface functions
def view_requests(filter_option):
status_filter = None
if filter_option == "Completed Requests":
status_filter = "completed"
elif filter_option == "Incomplete Requests":
status_filter = "incomplete"
df = get_withdrawal_requests(filter_status=status_filter)
df = make_clickable_wallet_number(df)
return df
def change_status(selected_ids, new_status):
message = update_request_status(selected_ids, new_status)
return message
# Function to retrieve application configurations
def get_configurations():
conn = connect_db()
if conn is None:
return pd.DataFrame({"Error": ["Unable to connect to database"]})
try:
query = "SELECT * FROM config WHERE id = 0"
df = pd.read_sql(query, conn)
print(df.to_string())
conn.close()
return df
except Exception as e:
conn.close()
return pd.DataFrame({"Error": [str(e)]})
# Function to update application configurations
def update_configurations(
ad_limit_per_day,
spin_limit_per_day,
ad_reward_steps,
steps_limit,
amount_limit_for_withdrawal,
points_conversion_rate
):
conn = connect_db()
if conn is None:
return "Error: Unable to connect to database."
try:
query = """
UPDATE config
SET
ad_limit_per_day = %s,
spin_limit_per_day = %s,
steps_limit = %s,
points_conversion_rate = %s,
ad_reward_steps = %s,
amount_limit_for_withdrawal = %s
WHERE id = 0
"""
with conn.cursor() as cursor:
cursor.execute(query, (
ad_limit_per_day,
spin_limit_per_day,
steps_limit,
points_conversion_rate,
ad_reward_steps,
amount_limit_for_withdrawal
))
conn.commit()
return "Configuration updated successfully."
except Exception as e:
conn.rollback()
return f"Error: {str(e)}"
finally:
conn.close()
def get_milestones():
conn = connect_db()
if conn is None:
return pd.DataFrame({"Error": ["Unable to connect to database"]})
try:
query = "SELECT * FROM reward_milestone"
df = pd.read_sql(query, conn)
print(df.to_string())
conn.close()
return df
except Exception as e:
conn.close()
return pd.DataFrame({"Error": [str(e)]})
# Function to update application configurations
def update_milestones(
req1, r1, req2, r2, req3, r3
):
conn = connect_db()
if conn is None:
return "Error: Unable to connect to database."
try:
milestones = [(req1, r1), (req2, r2), (req3, r3)]
for i, milestone in enumerate(milestones):
query = """
UPDATE reward_milestone
SET
required_steps = %s,
reward = %s
WHERE id = %s
"""
required_steps, reward = milestone
with conn.cursor() as cursor:
cursor.execute(query, (
required_steps,
reward,
i
))
conn.commit()
return "Configuration updated successfully."
except Exception as e:
conn.rollback()
return f"Error: {str(e)}"
finally:
conn.close()
# Gradio UI
with gr.Blocks() as app:
with gr.Tab("Withdrawal Requests"):
gr.Markdown("# Withdrawal Requests Management")
filter_option = gr.Radio(
choices=["All Requests", "Completed Requests", "Incomplete Requests"],
label="Filter Requests",
value="All Requests"
)
requests_table = gr.Dataframe(
label="Withdrawal Requests",
interactive=True
)
refresh_button = gr.Button("Refresh")
refresh_button.click(
view_requests, inputs=filter_option, outputs=requests_table
)
selected_ids = gr.Textbox(label="Selected Request IDs (comma-separated)", interactive=True)
current_status = gr.Radio(
choices=["incomplete", "completed"],
label="Set Selected Requests to",
value="incomplete"
)
update_button = gr.Button("Update Status")
status_message = gr.Textbox(label="Status Message", interactive=False)
update_button.click(
change_status, inputs=[selected_ids, current_status], outputs=status_message
)
requests_table.value = view_requests("All Requests")
with gr.Tab("General Configurations"):
gr.Markdown("# Application Configurations")
# Inputs for configuration fields
ad_limit_per_day = gr.Number(label="Ad Limit Per Day", precision=0)
spin_limit_per_day = gr.Number(label="Spin Limit Per Day", precision=0)
steps_limit = gr.Number(label="Steps Limit", precision=0)
points_conversion_rate = gr.Number(label="Points Conversion Rate", precision=0)
ad_reward_steps = gr.Number(label="Ad Reward Steps", precision=0)
amount_limit_for_withdrawal = gr.Number(label="Amount Limit for Withdrawal", precision=0)
save_button = gr.Button("Save Configurations")
config_message = gr.Textbox(label="Status Message", interactive=False)
# Button to update configurations
save_button.click(
update_configurations,
inputs=[
ad_limit_per_day,
spin_limit_per_day,
ad_reward_steps,
steps_limit,
amount_limit_for_withdrawal,
points_conversion_rate
],
outputs=config_message
)
# Load current configurations
def load_config():
df = get_configurations()
if not df.empty:
return df.iloc[0, 1:].to_list()
return [0] * 6
load_button = gr.Button("Load Current Configurations")
load_button.click(
load_config,
outputs=[
ad_limit_per_day,
spin_limit_per_day,
ad_reward_steps,
steps_limit,
amount_limit_for_withdrawal,
points_conversion_rate
]
)
with gr.Tab("Milestone Configurations"):
gr.Markdown("# Application Configurations")
# Inputs for configuration fields
with gr.Row():
req_steps_1 = gr.Number(label="Needed Steps for Milestone 1", precision=0)
reward_1 = gr.Number(label="Reward for Milestone 1", precision=0)
with gr.Row():
req_steps_2 = gr.Number(label="Needed Steps for Milestone 2", precision=0)
reward_2 = gr.Number(label="Reward for Milestone 2", precision=0)
with gr.Row():
req_steps_3 = gr.Number(label="Needed Steps for Milestone 3", precision=0)
reward_3 = gr.Number(label="Reward for Milestone 3", precision=0)
save_button = gr.Button("Save Configurations")
config_message = gr.Textbox(label="Status Message", interactive=False)
# Button to update configurations
save_button.click(
update_milestones,
inputs=[req_steps_1, reward_1, req_steps_2, reward_2, req_steps_3, reward_3],
outputs=config_message
)
# Load current configurations
def load_milestones():
df = get_milestones()
if not df.empty:
return df[['required_steps', 'reward']].to_numpy().flatten().tolist()
return [0] * 6
load_button = gr.Button("Load Current Configurations")
load_button.click(
load_milestones,
outputs=[req_steps_1, reward_1, req_steps_2, reward_2, req_steps_3, reward_3],
)
# Run the app
app.launch()