Cart / app.py
dschandra's picture
Update app.py
ec96e6b verified
raw
history blame
5.9 kB
import gradio as gr
from simple_salesforce import Salesforce
# Salesforce Connection
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
# Cart to store items
cart = []
# Function to fetch menu items
def fetch_menu_from_salesforce():
query = "SELECT Id, Name, Price__c, Description__c, Image1__c, Section__c, Veg_NonVeg__c FROM Menu_Item__c"
menu_items = sf.query(query)
return menu_items["records"]
# Function to fetch add-ons
def fetch_add_ons_from_salesforce():
query = "SELECT Id, Name, Price__c, Menu_Item__c FROM Add_Ons__c WHERE Available_In_Menu__c = true"
add_ons = sf.query(query)
return add_ons["records"]
# Function to generate menu HTML
def generate_menu_html(menu_items):
html = "<div style='display: flex; flex-wrap: wrap;'>"
for item in menu_items:
html += f"""
<div style="border: 1px solid #ddd; padding: 10px; margin: 10px; width: 300px; border-radius: 8px; text-align: center;">
<img src="{item.get('Image1__c')}" alt="{item.get('Name')}" style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px;">
<h3>{item.get('Name')}</h3>
<p>{item.get('Description__c')}</p>
<p style="font-weight: bold;">${item.get('Price__c')}</p>
<button onclick="openPopup('{item.get('Id')}', '{item.get('Name')}', {item.get('Price__c')})">Customize & Add</button>
</div>
"""
html += "</div>"
return html
# Function to save order in Salesforce
def save_order_in_salesforce(cart_data, total_cost):
try:
if not cart_data:
return "Cart is empty!"
# Save Order
order = {
"Name": f"Order-{datetime.now().strftime('%Y%m%d%H%M%S')}",
"Total_Amount__c": total_cost,
"Order_Date__c": datetime.now().isoformat(),
}
order_result = sf.Order__c.create(order)
order_id = order_result["id"]
# Save Order Items
for item in cart_data:
order_item = {
"Order__c": order_id,
"Menu_Item__c": item["menu_item_id"],
"Quantity__c": item["quantity"],
"Price__c": item["price"],
"Total_Price__c": item["total_price"],
"Add_Ons__c": ", ".join(addon["name"] for addon in item["add_ons"]),
"Special_Instructions__c": item["instructions"],
}
sf.Order_Item__c.create(order_item)
return "Order placed successfully!"
except Exception as e:
return f"Error saving order: {str(e)}"
# JS for Popup
popup_script = """
<script>
function openPopup(id, name, price) {
document.getElementById('popup-name').innerText = name;
document.getElementById('popup-price').innerText = `$${price}`;
document.getElementById('popup').style.display = 'block';
document.getElementById('popup').setAttribute('data-id', id);
}
function closePopup() {
document.getElementById('popup').style.display = 'none';
}
function addToCart() {
const id = document.getElementById('popup').getAttribute('data-id');
const name = document.getElementById('popup-name').innerText;
const price = parseFloat(document.getElementById('popup-price').innerText.replace('$', ''));
const quantity = parseInt(document.getElementById('popup-quantity').value);
const instructions = document.getElementById('popup-instructions').value;
const addOns = Array.from(document.querySelectorAll('input[name="addon"]:checked')).map(addon => ({
name: addon.getAttribute('data-name'),
price: parseFloat(addon.getAttribute('data-price')),
}));
const totalPrice = price * quantity + addOns.reduce((acc, addon) => acc + addon.price, 0);
cart.push({ menu_item_id: id, name, price, quantity, add_ons: addOns, instructions, total_price: totalPrice });
closePopup();
alert(`${name} added to cart!`);
}
</script>
"""
# Gradio App
with gr.Blocks() as app:
menu_items = fetch_menu_from_salesforce()
add_ons = fetch_add_ons_from_salesforce()
with gr.Row():
gr.HTML("<h1>Welcome to Biryani Hub</h1>")
with gr.Row():
cart_view = gr.Textbox(label="Cart Items", interactive=False)
total_cost_view = gr.Textbox(label="Total Cost", interactive=False)
with gr.Row():
menu_output = gr.HTML(generate_menu_html(menu_items))
with gr.Row():
submit_order = gr.Button("Proceed to Order")
order_status = gr.Textbox(label="Order Status", interactive=False)
submit_order.click(
lambda: save_order_in_salesforce(cart, sum(item["total_price"] for item in cart)),
inputs=[],
outputs=order_status,
)
gr.HTML("""
<div id="popup" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 400px; height: 600px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
<h3 id="popup-name"></h3>
<p id="popup-price"></p>
<label>Quantity:</label>
<input type="number" id="popup-quantity" value="1" min="1">
<label>Special Instructions:</label>
<textarea id="popup-instructions" rows="3"></textarea>
<label>Add-Ons:</label>
<div>
""" +
"".join(
f'<input type="checkbox" name="addon" data-name="{addon["Name"]}" data-price="{addon["Price__c"]}"> {addon["Name"]} (+${addon["Price__c"]})<br>'
for addon in add_ons
) +
"""
</div>
<button onclick="addToCart()">Add to Cart</button>
<button onclick="closePopup()">Close</button>
</div>
""")
gr.HTML(popup_script)
app.launch()