EnrollementUI / src /streamlit_app.py
ryanpereira's picture
Update src/streamlit_app.py
1acc394 verified
import streamlit as st
import requests
import pandas as pd
from typing import Dict, Any
# Configure the page
st.set_page_config(
page_title="Customer Management System",
page_icon="👥",
layout="wide"
)
# Constants
API_BASE_URL = "https://ryanpereira-enrollmentapi.hf.space" # Update this if your FastAPI server runs on a different port
# Helper functions
def get_all_customers() -> list:
try:
response = requests.get(f"{API_BASE_URL}/customers")
return response.json()
except Exception as e:
st.error(f"Error fetching customers: {str(e)}")
return []
def create_customer(customer_data: Dict[str, Any]) -> bool:
try:
response = requests.post(f"{API_BASE_URL}/customers", json=customer_data)
if response.status_code == 200:
return True
st.error(f"Error creating customer: {response.json().get('detail', 'Unknown error')}")
return False
except Exception as e:
st.error(f"Error creating customer: {str(e)}")
return False
def update_customer(customer_id: int, customer_data: Dict[str, Any]) -> bool:
try:
response = requests.put(f"{API_BASE_URL}/customers/{customer_id}", json=customer_data)
if response.status_code == 200:
return True
st.error(f"Error updating customer: {response.json().get('detail', 'Unknown error')}")
return False
except Exception as e:
st.error(f"Error updating customer: {str(e)}")
return False
def delete_customer(customer_id: int) -> bool:
try:
response = requests.delete(f"{API_BASE_URL}/customers/{customer_id}")
if response.status_code == 200:
return True
st.error(f"Error deleting customer: {response.json().get('detail', 'Unknown error')}")
return False
except Exception as e:
st.error(f"Error deleting customer: {str(e)}")
return False
# Main app
def main():
st.title("Customer Management System")
# Sidebar for navigation
st.sidebar.title("Navigation")
page = st.sidebar.radio("Go to", ["View Customers", "Add Customer"])
if page == "View Customers":
view_customers_page()
else:
add_customer_page()
def view_customers_page():
st.header("Customer List")
# Add search functionality
search_term = st.text_input("Search customers", "")
# Fetch and display customers
customers = get_all_customers()
if customers:
# Convert to DataFrame for better display
df = pd.DataFrame(customers)
# Filter based on search term
if search_term:
mask = df.apply(lambda x: x.astype(str).str.contains(search_term, case=False).any(), axis=1)
df = df[mask]
# Display the table
st.dataframe(df, use_container_width=True)
# Add edit and delete buttons for each customer
for idx, customer in df.iterrows():
col1, col2 = st.columns([1, 1])
with col1:
if st.button(f"Edit {customer['name']}", key=f"edit_{customer['id']}"):
st.session_state.edit_customer = customer.to_dict()
st.session_state.show_edit_form = True
with col2:
if st.button(f"Delete {customer['name']}", key=f"delete_{customer['id']}"):
if st.confirm(f"Are you sure you want to delete {customer['name']}?"):
if delete_customer(customer['id']):
st.success(f"Successfully deleted {customer['name']}")
st.rerun()
# Edit form
if st.session_state.get('show_edit_form', False):
st.subheader("Edit Customer")
edit_customer_form(st.session_state.edit_customer)
else:
st.info("No customers found. Add some customers to get started!")
def add_customer_page():
st.header("Add New Customer")
with st.form("add_customer_form"):
customer_data = {
"id": st.number_input("ID", min_value=1, step=1),
"name": st.text_input("Name"),
"age": st.number_input("Age", min_value=0, max_value=120, step=1),
"email": st.text_input("Email"),
"phone": st.text_input("Phone"),
"address": st.text_input("Address"),
"city": st.text_input("City"),
"state": st.text_input("State"),
"zip": st.text_input("ZIP Code")
}
submitted = st.form_submit_button("Add Customer")
if submitted:
if create_customer(customer_data):
st.success("Customer added successfully!")
st.rerun()
def edit_customer_form(customer_data: Dict[str, Any]):
with st.form("edit_customer_form"):
edited_data = {
"id": st.number_input("ID", value=customer_data["id"], disabled=True),
"name": st.text_input("Name", value=customer_data["name"]),
"age": st.number_input("Age", value=customer_data["age"], min_value=0, max_value=120, step=1),
"email": st.text_input("Email", value=customer_data["email"]),
"phone": st.text_input("Phone", value=customer_data["phone"]),
"address": st.text_input("Address", value=customer_data["address"]),
"city": st.text_input("City", value=customer_data["city"]),
"state": st.text_input("State", value=customer_data["state"]),
"zip": st.text_input("ZIP Code", value=customer_data["zip"])
}
submitted = st.form_submit_button("Update Customer")
if submitted:
if update_customer(edited_data["id"], edited_data):
st.success("Customer updated successfully!")
st.session_state.show_edit_form = False
st.rerun()
if __name__ == "__main__":
main()