CMS_UI / src /streamlit_app.py
Ritesh1035's picture
Update src/streamlit_app.py
01ee7b2 verified
import streamlit as st
import requests
import json
from typing import Optional
# Configure Streamlit page
st.set_page_config(
page_title="Customer Management System",
layout="wide"
)
# FastAPI base URL
BASE_URL = "https://ritesh1035-cms-apis.hf.space"
# Helper functions
def make_request(method, endpoint, data=None):
"""Make HTTP request to FastAPI backend"""
url = f"{BASE_URL}{endpoint}"
try:
if method == "GET":
response = requests.get(url)
elif method == "POST":
response = requests.post(url, json=data)
elif method == "PUT":
response = requests.put(url, json=data)
elif method == "DELETE":
response = requests.delete(url)
return response
except requests.exceptions.ConnectionError:
st.error("Cannot connect to FastAPI server. Make sure it's running on https://ritesh1035-cms-apis.hf.space")
return None
# Main title
st.title("Customer Management System")
# Sidebar for operation selection
st.sidebar.header("Choose An Operations")
operation = st.sidebar.selectbox(
"Select Operation:",
["View All Customers", "Add Customer", "Update Customer", "Delete Customer"]
)
# Main content area
if operation == "View All Customers":
st.header("Customer List")
if st.button("Refresh List"):
response = make_request("GET", "/Customer")
if response and response.status_code == 200:
customers = response.json()
if customers:
st.success(f"Found {len(customers)} customers")
# Simple table display
for customer in customers:
st.write("---")
col1, col2 = st.columns(2)
with col1:
st.write(f"**ID:** {customer['id']}")
st.write(f"**Name:** {customer['name']}")
st.write(f"**Email:** {customer['email']}")
with col2:
st.write(f"**Phone:** {customer.get('phone', 'Not provided')}")
st.write(f"**Address:** {customer.get('address', 'Not provided')}")
else:
st.info("No customers found")
elif response:
st.error(f"Failed to fetch customers: {response.status_code}")
elif operation == "Add Customer":
st.header("Add New Customer")
with st.form("add_customer"):
customer_name = st.text_input("Name (required)")
customer_email = st.text_input("Email (required)")
customer_phone = st.text_input("Phone (optional)")
customer_address = st.text_area("Address (optional)")
if st.form_submit_button("Add Customer"):
if not customer_name or not customer_email:
st.error("Name and Email are required")
else:
# Auto-generate ID based on existing customers count
try:
existing_customers = requests.get("https://ritesh1035-cms-apis.hf.space/Customer").json()
if existing_customers:
max_id = max(customer.get('id', 0) for customer in existing_customers)
customer_id = max_id + 1
else:
customer_id = 1
except:
customer_id = 1
customer_data = {
"id": customer_id,
"name": customer_name,
"email": customer_email,
"phone": customer_phone if customer_phone else None,
"address": customer_address if customer_address else None
}
response = make_request("POST", "/Customer", customer_data)
if response and response.status_code == 200:
st.success(f"Customer '{customer_name}' added successfully")
elif response:
st.error(f"Failed to add customer: {response.status_code}")
elif operation == "Update Customer":
st.header("Update Customer")
update_id = st.number_input("Customer ID to Update", min_value=1, step=1)
if st.button("Load Customer"):
response = make_request("GET", "/Customer")
if response and response.status_code == 200:
customers = response.json()
customer = next((c for c in customers if c['id'] == update_id), None)
if customer:
st.session_state.update_customer = customer
st.success(f"Loaded: {customer['name']}")
else:
st.error(f"Customer with ID {update_id} not found")
if 'update_customer' in st.session_state:
customer = st.session_state.update_customer
with st.form("update_customer_form"):
new_name = st.text_input("Name", value=customer['name'])
new_email = st.text_input("Email", value=customer['email'])
new_phone = st.text_input("Phone", value=customer.get('phone', ''))
new_address = st.text_area("Address", value=customer.get('address', ''))
if st.form_submit_button("Update Customer"):
if not new_name or not new_email:
st.error("Name and Email are required")
else:
updated_data = {
"id": update_id,
"name": new_name,
"email": new_email,
"phone": new_phone if new_phone else None,
"address": new_address if new_address else None
}
response = make_request("PUT", f"/Customer/{update_id}", updated_data)
if response and response.status_code == 200:
st.success(f"Customer updated successfully")
del st.session_state.update_customer
st.rerun()
elif response:
st.error(f"Failed to update customer: {response.status_code}")
elif operation == "Delete Customer":
st.header("Delete Customer")
st.warning("Warning: This action cannot be undone")
delete_id = st.number_input("Customer ID to Delete", min_value=1, step=1)
if st.button("Preview Customer"):
response = make_request("GET", "/Customer")
if response and response.status_code == 200:
customers = response.json()
customer = next((c for c in customers if c['id'] == delete_id), None)
if customer:
st.info(f"Customer to delete: {customer['name']} ({customer['email']})")
st.session_state.delete_customer = customer
else:
st.error(f"Customer with ID {delete_id} not found")
if 'delete_customer' in st.session_state:
customer = st.session_state.delete_customer
st.error(f"Are you sure you want to delete {customer['name']}?")
col1, col2 = st.columns(2)
with col1:
if st.button("Yes, Delete"):
response = make_request("DELETE", f"/Customer/{delete_id}")
if response and response.status_code == 200:
st.success(f"Customer deleted successfully")
del st.session_state.delete_customer
st.rerun()
elif response:
st.error(f"Failed to delete customer: {response.status_code}")
with col2:
if st.button("Cancel"):
del st.session_state.delete_customer
st.rerun()
# Footer
#st.sidebar.markdown("---")
#st.sidebar.write("Server: http://localhost:8000")
#st.sidebar.write("Make sure FastAPI is running")