Spaces:
Sleeping
Sleeping
| import bcrypt | |
| import gradio as gr | |
| from simple_salesforce import Salesforce | |
| from flask import Flask, request, jsonify | |
| import logging | |
| # Set up logging for debugging | |
| logging.basicConfig(level=logging.DEBUG) | |
| # Salesforce Connection | |
| sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q') | |
| # Flask app to handle order submission | |
| app = Flask(__name__) | |
| # --- Utility Functions --- | |
| # Function to Hash Password | |
| def hash_password(password): | |
| logging.debug(f"Hashing password: {password}") | |
| return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') | |
| # Function to Verify Password | |
| def verify_password(plain_password, hashed_password): | |
| logging.debug(f"Verifying password: {plain_password} against {hashed_password}") | |
| return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8')) | |
| # --- Salesforce Integration --- | |
| # Signup function | |
| def signup(name, email, phone, password): | |
| try: | |
| email = email.strip() | |
| logging.debug(f"Signup attempt for email: {email}") | |
| query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{email}'" | |
| result = sf.query(query) | |
| logging.debug(f"Salesforce query result for signup: {result}") | |
| if len(result['records']) > 0: | |
| logging.warning(f"Email already exists: {email}") | |
| return "Email already exists! Please use a different email." | |
| hashed_password = hash_password(password) | |
| sf.Customer_Login__c.create({ | |
| 'Name': name.strip(), | |
| 'Email__c': email, | |
| 'Phone_Number__c': phone.strip(), | |
| 'Password__c': hashed_password | |
| }) | |
| logging.info(f"Signup successful for email: {email}") | |
| return "Signup successful! You can now login." | |
| except Exception as e: | |
| logging.error(f"Error during signup: {str(e)}") | |
| return f"Error during signup: {str(e)}" | |
| # Login function | |
| def login(email, password): | |
| try: | |
| email = email.strip() | |
| logging.debug(f"Login attempt for email: {email}") | |
| query = f"SELECT Name, Password__c FROM Customer_Login__c WHERE Email__c = '{email}'" | |
| result = sf.query(query) | |
| logging.debug(f"Salesforce query result for login: {result}") | |
| if len(result['records']) == 0: | |
| logging.warning(f"Invalid login attempt for email: {email}") | |
| return "Invalid email or password.", None | |
| user = result['records'][0] | |
| stored_password = user['Password__c'] | |
| if verify_password(password.strip(), stored_password): | |
| logging.info(f"Login successful for email: {email}") | |
| return "Login successful!", user['Name'] | |
| else: | |
| logging.warning(f"Invalid password for email: {email}") | |
| return "Invalid email or password.", None | |
| except Exception as e: | |
| logging.error(f"Error during login: {str(e)}") | |
| return f"Error during login: {str(e)}", None | |
| # --- Menu and Add-ons Functions --- | |
| # Function to load menu data from Salesforce | |
| def load_menu_from_salesforce(): | |
| try: | |
| query = "SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c FROM Menu_Item__c" | |
| logging.debug(f"Loading menu from Salesforce with query: {query}") | |
| result = sf.query(query) | |
| logging.debug(f"Salesforce menu result: {result}") | |
| return result['records'] | |
| except Exception as e: | |
| logging.error(f"Error loading menu from Salesforce: {str(e)}") | |
| return [] | |
| # Function to load add-ons data from Salesforce | |
| def load_add_ons_from_salesforce(): | |
| try: | |
| query = "SELECT Name, Price__c FROM Add_Ons__c" | |
| logging.debug(f"Loading add-ons from Salesforce with query: {query}") | |
| result = sf.query(query) | |
| logging.debug(f"Salesforce add-ons result: {result}") | |
| return result['records'] | |
| except Exception as e: | |
| logging.error(f"Error loading add-ons from Salesforce: {str(e)}") | |
| return [] | |
| # Function to filter menu items based on preference | |
| def filter_menu(preference): | |
| menu_data = load_menu_from_salesforce() | |
| filtered_data = {} | |
| logging.debug(f"Filtering menu with preference: {preference}") | |
| for item in menu_data: | |
| if "Section__c" not in item or "Veg_NonVeg__c" not in item: | |
| continue | |
| if item["Section__c"] not in filtered_data: | |
| filtered_data[item["Section__c"]] = [] | |
| if preference == "All" or (preference == "Veg" and item["Veg_NonVeg__c"] in ["Veg", "Both"]) or (preference == "Non-Veg" and item["Veg_NonVeg__c"] in ["Non veg", "Both"]): | |
| filtered_data[item["Section__c"].strip()].append(item) | |
| html_content = '<div style="padding: 0 10px; max-width: 1200px; margin: auto;">' | |
| for section, items in filtered_data.items(): | |
| html_content += f"<h2 style='text-align: center; margin-top: 5px;'>{section}</h2>" | |
| html_content += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; justify-content: center; margin-top: 10px;">' | |
| for item in items: | |
| html_content += f""" | |
| <div style="border: 1px solid #ddd; border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); overflow: hidden; height: 350px;"> | |
| <img src="{item.get('Image1__c', '')}" style="width: 100%; height: 200px; object-fit: cover;" | |
| onclick="openModal('{item['Name']}', '{item.get('Image2__c', '')}', '{item['Description__c']}', '${item['Price__c']}')"> | |
| <div style="padding: 10px;"> | |
| <h3 style='font-size: 1.2em; text-align: center;'>{item['Name']}</h3> | |
| <p style='font-size: 1.1em; color: green; text-align: center;'>${item['Price__c']}</p> | |
| <p style='font-size: 0.9em; text-align: justify; margin: 5px;'>{item['Description__c']}</p> | |
| </div> | |
| </div> | |
| """ | |
| html_content += '</div>' | |
| html_content += '</div>' | |
| if not any(filtered_data.values()): | |
| logging.debug("No items match the filter.") | |
| return "<p>No items match your filter.</p>" | |
| logging.debug("Filter applied successfully.") | |
| return html_content | |
| # --- Modal and Cart Logic --- | |
| # Create Modal Window HTML | |
| def create_modal_window(): | |
| add_ons = load_add_ons_from_salesforce() | |
| add_ons_html = "" | |
| for add_on in add_ons: | |
| add_ons_html += f""" | |
| <label> | |
| <input type="checkbox" name="biryani-extra" value="{add_on['Name']}" data-price="{add_on['Price__c']}" /> | |
| {add_on['Name']} + ${add_on['Price__c']} | |
| </label> | |
| <br> | |
| """ | |
| modal_html = f""" | |
| <div id="modal" style="display: none; position: fixed; background: white; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); padding: 20px; z-index: 1000;"> | |
| <div style="text-align: right;"> | |
| <button onclick="closeModal()" style="background: none; border: none; font-size: 18px; cursor: pointer;">×</button> | |
| </div> | |
| <img id="modal-image" style="width: 100%; height: 300px; border-radius: 8px; margin-bottom: 20px;" /> | |
| <h2 id="modal-name"></h2> | |
| <p id="modal-description"></p> | |
| <p id="modal-price"></p> | |
| <label for="biryani-extras"><strong>Add-ons :</strong></label> | |
| <div id="biryani-extras-options" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;"> | |
| {add_ons_html} | |
| </div> | |
| <label for="quantity">Quantity:</label> | |
| <input type="number" id="quantity" value="1" min="1" style="width: 50px;" /> | |
| <textarea id="special-instructions" placeholder="Add your special instructions here..." style="width: 100%; height: 60px;"></textarea> | |
| <button style="background-color: #28a745; color: white; border: none; padding: 10px 20px; font-size: 14px; border-radius: 5px; cursor: pointer;" onclick="addToCart()">Add to Cart</button> | |
| </div> | |
| <div id="cart-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: white; z-index: 1000; overflow-y: auto;"> | |
| <div style="padding: 20px;"> | |
| <div style="text-align: right;"> | |
| <button onclick="closeCartModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button> | |
| </div> | |
| <h1>Your Cart</h1> | |
| <div id="cart-items"></div> | |
| <p id="cart-total-cost" style="font-size: 1.2em; font-weight: bold;">Total Cart Cost: $0.00</p> | |
| <div id="order-summary" style="margin-top: 20px;"> | |
| <h2>Final Order Summary:</h2> | |
| <div id="final-order-summary"></div> | |
| <p><strong>Total Bill: $<span id="total-bill"></span></strong></p> | |
| </div> | |
| <button style="background: #ff5722; color: white; padding: 10px 20px; border-radius: 5px; border: none; cursor: pointer;" onclick="proceedToCheckout()">Proceed to Checkout</button> | |
| </div> | |
| </div> | |
| """ | |
| return modal_html | |
| # --- Order Submission Logic --- | |
| # Function to create an order in Salesforce | |
| def create_order_in_salesforce(customer_id, cart_items, total_cost): | |
| try: | |
| logging.debug(f"Creating order in Salesforce for customer ID: {customer_id}") | |
| cart_summary = '' | |
| add_ons_summary = '' | |
| instructions_summary = '' | |
| for item in cart_items: | |
| cart_summary += f"Item: {item['name']}, Quantity: {item['quantity']}, Price: {item['total_cost']}\n" | |
| add_ons_summary += ', '.join([addon['name'] for addon in item['add_ons']]) # List of add-ons | |
| instructions_summary += item.get('instructions', '') # Special instructions for the item | |
| # Create the order record in Salesforce | |
| order = sf.Order__c.create({ | |
| 'Customer_Name__c': customer_id, | |
| 'Customer_Email__c': 'customer_email', # Replace with actual email of the customer | |
| 'Order_Items__c': cart_summary, # Cart items summary | |
| 'Add_Ons__c': add_ons_summary, # Add-ons summary | |
| 'Instructions__c': instructions_summary, # Special instructions for the order | |
| 'Total_Price__c': total_cost, | |
| 'Order_Status__c': 'Pending', # Default order status | |
| 'Order_Date_Time__c': '2025-01-20T10:00:00Z' # Current timestamp or system timestamp | |
| }) | |
| logging.info(f"Order placed successfully with order ID: {order['id']}") | |
| return f"Order placed successfully! Order ID: {order['id']}" | |
| except Exception as e: | |
| logging.error(f"Error during order creation: {str(e)}") | |
| return f"Error during order creation: {str(e)}" | |
| # Route to handle order submission | |
| def create_order(): | |
| try: | |
| data = request.get_json() # Get the JSON data from the request | |
| cart_summary = data['cartSummary'] # Extract the cart summary | |
| total_cost = data['totalCost'] # Extract the total cost | |
| customer_id = data['customerId'] # Extract the customer ID | |
| # Debug log to check if data is correct | |
| logging.debug(f"Order Details: {cart_summary}, {total_cost}, {customer_id}") | |
| # Call the function to create the order in Salesforce | |
| result = create_order_in_salesforce(customer_id, cart_summary, total_cost) | |
| return jsonify({'message': result}) # Return a response with the order result | |
| except Exception as e: | |
| logging.error(f"Error in create_order route: {str(e)}") | |
| return jsonify({'message': f"Error during order creation: {str(e)}"}), 500 | |
| # --- Gradio Interface --- | |
| # JavaScript for Modal and Cart | |
| def modal_js(): | |
| modal_script = """ | |
| <script> | |
| let cart = []; | |
| let totalCartCost = 0; | |
| function openModal(name, image2, description, price) { | |
| const modal = document.getElementById('modal'); | |
| modal.style.display = 'block'; | |
| modal.style.position = 'fixed'; | |
| modal.style.width = window.innerWidth <= 768 ? '90%' : '30%'; | |
| modal.style.top = ${event.clientY}px; | |
| modal.style.left = '50%'; | |
| modal.style.transform = 'translate(-50%, -50%)'; | |
| document.getElementById('modal-image').src = image2; | |
| document.getElementById('modal-name').innerText = name; | |
| document.getElementById('modal-description').innerText = description; | |
| document.getElementById('modal-price').innerText = price; | |
| document.getElementById('quantity').value = 1; | |
| document.getElementById('special-instructions').value = ''; | |
| resetAddOns(); // Reset add-ons when opening the modal | |
| } | |
| function closeModal() { | |
| document.getElementById('modal').style.display = 'none'; | |
| } | |
| function addToCart() { | |
| const name = document.getElementById('modal-name').innerText; | |
| const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', '')); | |
| const quantity = parseInt(document.getElementById('quantity').value) || 1; | |
| const instructions = document.getElementById('special-instructions').value; | |
| const selectedAddOns = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked')); | |
| const extras = selectedAddOns.map(extra => ({ | |
| name: extra.value, | |
| price: parseFloat(extra.getAttribute('data-price')), | |
| quantity: 1 // Default quantity for add-ons is 1 | |
| })); | |
| const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0); | |
| const totalCost = (price * quantity) + extrasCost; | |
| // Add the item to the cart with its specific add-ons | |
| cart.push({ name, price, quantity, extras, instructions, totalCost }); | |
| totalCartCost += totalCost; // Update the total cost of the cart | |
| updateCartButton(); | |
| updateCartTotalCost(); // Update total cost displayed | |
| closeModal(); | |
| } | |
| function updateCartButton() { | |
| const cartButton = document.getElementById('cart-button'); | |
| cartButton.innerText = View Cart (${cart.length} items); | |
| } | |
| function openCartModal() { | |
| const cartModal = document.getElementById('cart-modal'); | |
| const cartItemsContainer = document.getElementById('cart-items'); | |
| cartItemsContainer.innerHTML = ""; | |
| cart.forEach((item, index) => { | |
| const extrasList = item.extras.map(extra => ${extra.name} x<input type="number" value="${extra.quantity}" min="1" style="width: 50px;" onchange="updateCartItem(${index}, 'extra', this.value)" /> (+$${(extra.price * extra.quantity).toFixed(2)})).join(', '); | |
| cartItemsContainer.innerHTML += | |
| <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px;"> | |
| <h3>${item.name}</h3> | |
| <p>Quantity: <input type="number" value="${item.quantity}" min="1" style="width: 50px;" onchange="updateCartItem(${index}, 'item', this.value)" /></p> | |
| <p>Extras: ${extrasList || 'None'}</p> | |
| <p>Special Instructions: ${item.instructions || 'None'}</p> | |
| <p>Total Cost: $<span id="item-${index}-total">${item.totalCost.toFixed(2)}</span></p> | |
| <button onclick="removeFromCart(${index})" style="color: red;">Remove</button> | |
| </div> | |
| ; | |
| }); | |
| cartModal.style.display = 'block'; | |
| } | |
| function closeCartModal() { | |
| document.getElementById('cart-modal').style.display = 'none'; | |
| } | |
| function removeFromCart(index) { | |
| totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost | |
| cart.splice(index, 1); | |
| updateCartButton(); | |
| updateCartTotalCost(); // Update total cost displayed | |
| openCartModal(); | |
| } | |
| function updateCartItem(index, type, value) { | |
| if (type === 'item') { | |
| cart[index].quantity = parseInt(value); | |
| } else if (type === 'extra') { | |
| cart[index].extras[0].quantity = parseInt(value); // Assuming one add-on for simplicity | |
| } | |
| const item = cart[index]; | |
| const price = item.price; | |
| const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0); | |
| item.totalCost = (price * item.quantity) + extrasCost; | |
| document.getElementById(item-${index}-total).innerText = item.totalCost.toFixed(2); | |
| updateCartTotalCost(); // Update total cost displayed | |
| } | |
| function updateCartTotalCost() { | |
| const totalCostElement = document.getElementById('cart-total-cost'); | |
| totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0); | |
| totalCostElement.innerText = Total Cart Cost: $${totalCartCost.toFixed(2)}; | |
| } | |
| function proceedToCheckout() { | |
| // Collecting cart summary | |
| const cartSummary = cart.map(item => | |
| ${item.name} (x${item.quantity}) - $${item.totalCost.toFixed(2)} | |
| Extras: ${item.extras.map(extra => extra.name).join(', ') || 'None'} | |
| Instructions: ${item.instructions || 'None'} | |
| ).join('<br>'); | |
| const totalCost = totalCartCost.toFixed(2); // Total cost of the cart | |
| const customerId = 'customer_id'; // The customer ID from the session | |
| // Sending cart data to the backend | |
| fetch('/create-order', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ | |
| cartSummary: cartSummary, | |
| totalCost: totalCost, | |
| customerId: customerId | |
| }) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| alert(data.message); | |
| closeCartModal(); | |
| }) | |
| .catch(error => { | |
| console.error('Error:', error); | |
| alert('Failed to place the order.'); | |
| }); | |
| } | |
| </script> | |
| """ | |
| return modal_script | |
| # --- Gradio Interface --- | |
| with gr.Blocks() as app: | |
| with gr.Row(): | |
| gr.HTML("<h1 style='text-align: center;'>Welcome to Biryani Hub</h1>") | |
| with gr.Row(visible=True) as login_page: | |
| with gr.Column(): | |
| login_email = gr.Textbox(label="Email") | |
| login_password = gr.Textbox(label="Password", type="password") | |
| login_button = gr.Button("Login") | |
| signup_button = gr.Button("Go to Signup") | |
| login_output = gr.Textbox(label="Status") | |
| with gr.Row(visible=False) as signup_page: | |
| with gr.Column(): | |
| signup_name = gr.Textbox(label="Name") | |
| signup_email = gr.Textbox(label="Email") | |
| signup_phone = gr.Textbox(label="Phone") | |
| signup_password = gr.Textbox(label="Password", type="password") | |
| submit_signup = gr.Button("Signup") | |
| login_redirect = gr.Button("Go to Login") | |
| signup_output = gr.Textbox(label="Status") | |
| with gr.Row(visible=False) as menu_page: | |
| with gr.Column(): | |
| preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All") | |
| menu_output = gr.HTML() | |
| gr.HTML("<div id='cart-button' style='position: fixed; top: 20px; right: 20px; background: #28a745; color: white; padding: 10px 20px; border-radius: 30px; cursor: pointer; z-index: 1000;' onclick='openCartModal()'>View Cart</div>") | |
| gr.HTML(create_modal_window()) | |
| gr.HTML(modal_js()) | |
| login_button.click( | |
| lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!") | |
| if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."), | |
| [login_email, login_password], [login_page, menu_page, menu_output, login_output] | |
| ) | |
| submit_signup.click( | |
| lambda name, email, phone, password: signup(name, email, phone, password), | |
| inputs=[signup_name, signup_email, signup_phone, signup_password], | |
| outputs=signup_output | |
| ) | |
| signup_button.click( | |
| lambda: (gr.update(visible=False), gr.update(visible=True)), | |
| inputs=[], | |
| outputs=[login_page, signup_page] | |
| ) | |
| login_redirect.click( | |
| lambda: (gr.update(visible=True), gr.update(visible=False)), | |
| inputs=[], | |
| outputs=[login_page, signup_page] | |
| ) | |
| preference.change(lambda pref: filter_menu(pref), [preference], menu_output) | |
| app.launch() |