Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
import bcrypt
|
2 |
import gradio as gr
|
3 |
from simple_salesforce import Salesforce
|
4 |
-
from datetime import datetime
|
5 |
|
6 |
# Salesforce Connection
|
7 |
sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
@@ -14,118 +13,41 @@ def hash_password(password):
|
|
14 |
def verify_password(plain_password, hashed_password):
|
15 |
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
16 |
|
17 |
-
#
|
18 |
-
def
|
19 |
-
try:
|
20 |
-
# Fetch User details from Customer_Login__c object
|
21 |
-
user = sf.Customer_Login__c.get_by_custom_id('Email__c', user_email)
|
22 |
-
user_id = user['Id']
|
23 |
-
|
24 |
-
# Create the order record in Order__c
|
25 |
-
order_data = {
|
26 |
-
'Email__c': user_id, # Relating the order to the logged-in user
|
27 |
-
'Order_Date__c': datetime.now().strftime('%Y-%m-%d'),
|
28 |
-
'Total_Amount__c': total_cost,
|
29 |
-
'Order_Status__c': 'Pending', # Initial status
|
30 |
-
'Special_Instructions__c': special_instructions
|
31 |
-
}
|
32 |
-
order_response = sf.Order__c.create(order_data)
|
33 |
-
|
34 |
-
# Create order items (order details) for each item in the cart
|
35 |
-
for item in cart_items:
|
36 |
-
item_data = {
|
37 |
-
'Order__c': order_response['id'], # Linking this item to the created order
|
38 |
-
'Name': item['name'],
|
39 |
-
'Quantity__c': item['quantity'],
|
40 |
-
'Price__c': item['price'],
|
41 |
-
'Add_Ons__c': str(item['add_ons']),
|
42 |
-
'Special_Instructions__c': item['special_instructions']
|
43 |
-
}
|
44 |
-
sf.Order_Item__c.create(item_data)
|
45 |
-
|
46 |
-
return order_response['id'] # Returning order ID for further use
|
47 |
-
except Exception as e:
|
48 |
-
return f"Error during order creation: {str(e)}"
|
49 |
-
|
50 |
-
# Function to load menu data
|
51 |
-
def load_menu_from_salesforce():
|
52 |
-
try:
|
53 |
-
query = "SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c FROM Menu_Item__c"
|
54 |
-
result = sf.query(query)
|
55 |
-
return result['records']
|
56 |
-
except Exception as e:
|
57 |
-
return []
|
58 |
-
|
59 |
-
# Function to load add-ons data
|
60 |
-
def load_add_ons_from_salesforce():
|
61 |
try:
|
62 |
-
|
|
|
63 |
result = sf.query(query)
|
64 |
-
return result['records']
|
65 |
-
except Exception as e:
|
66 |
-
return []
|
67 |
-
|
68 |
-
# Function to handle cart and checkout
|
69 |
-
def proceed_to_checkout(user_email, cart_items):
|
70 |
-
# Calculate total cost
|
71 |
-
total_cost = sum(item['price'] * item['quantity'] for item in cart_items)
|
72 |
-
special_instructions = ', '.join([item['special_instructions'] for item in cart_items])
|
73 |
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
# Return order ID to display the details page
|
78 |
-
return order_id
|
79 |
|
80 |
-
|
81 |
-
def show_order_details(order_id):
|
82 |
-
try:
|
83 |
-
# Query the order record
|
84 |
-
order_query = f"SELECT Name, Order_Date__c, Total_Amount__c, Order_Status__c, Special_Instructions__c FROM Order__c WHERE Id = '{order_id}'"
|
85 |
-
order = sf.query(order_query)
|
86 |
-
order_details = order['records'][0]
|
87 |
-
|
88 |
-
# Query the order items associated with the order
|
89 |
-
items_query = f"SELECT Name, Quantity__c, Price__c, Add_Ons__c, Special_Instructions__c FROM Order_Item__c WHERE Order__c = '{order_id}'"
|
90 |
-
items = sf.query(items_query)
|
91 |
-
|
92 |
-
# Prepare the message to display the order details
|
93 |
-
order_message = f"Thank you for your order! Here's the summary:\n"
|
94 |
-
order_message += f"Order ID: {order_details['Name']}\n"
|
95 |
-
order_message += f"Order Date: {order_details['Order_Date__c']}\n"
|
96 |
-
order_message += f"Total Amount: ${order_details['Total_Amount__c']}\n"
|
97 |
-
order_message += f"Order Status: {order_details['Order_Status__c']}\n"
|
98 |
-
order_message += f"Special Instructions: {order_details['Special_Instructions__c']}\n\n"
|
99 |
-
|
100 |
-
order_message += "Items ordered:\n"
|
101 |
-
for item in items['records']:
|
102 |
-
order_message += f"\nItem Name: {item['Name']}\n"
|
103 |
-
order_message += f"Quantity: {item['Quantity__c']}\n"
|
104 |
-
order_message += f"Price: ${item['Price__c']}\n"
|
105 |
-
order_message += f"Add-ons: {item['Add_Ons__c']}\n"
|
106 |
-
order_message += f"Special Instructions: {item['Special_Instructions__c']}\n"
|
107 |
-
|
108 |
-
order_message += "\nThank you for shopping with us! Visit again soon."
|
109 |
-
|
110 |
-
return order_message
|
111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
except Exception as e:
|
113 |
-
return f"Error
|
114 |
|
115 |
-
#
|
116 |
def login(email, password):
|
117 |
try:
|
118 |
-
|
119 |
query = f"SELECT Name, Password__c FROM Customer_Login__c WHERE Email__c = '{email}'"
|
120 |
result = sf.query(query)
|
121 |
-
|
122 |
if len(result['records']) == 0:
|
123 |
return "Invalid email or password.", None
|
124 |
-
|
125 |
user = result['records'][0]
|
126 |
stored_password = user['Password__c']
|
127 |
-
|
128 |
-
# Verify password
|
129 |
if verify_password(password.strip(), stored_password):
|
130 |
return "Login successful!", user['Name']
|
131 |
else:
|
@@ -133,30 +55,25 @@ def login(email, password):
|
|
133 |
except Exception as e:
|
134 |
return f"Error during login: {str(e)}", None
|
135 |
|
136 |
-
# Function to
|
137 |
-
def
|
138 |
try:
|
139 |
-
|
140 |
-
query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{email}'"
|
141 |
result = sf.query(query)
|
142 |
-
|
143 |
-
if len(result['records']) > 0:
|
144 |
-
return "Email already exists! Please use a different email."
|
145 |
-
|
146 |
-
# Hash password and create user
|
147 |
-
hashed_password = hash_password(password)
|
148 |
-
|
149 |
-
sf.Customer_Login__c.create({
|
150 |
-
'Name': name.strip(),
|
151 |
-
'Email__c': email.strip(),
|
152 |
-
'Phone_Number__c': phone.strip(),
|
153 |
-
'Password__c': hashed_password
|
154 |
-
})
|
155 |
-
return "Signup successful! You can now login."
|
156 |
except Exception as e:
|
157 |
-
return
|
158 |
|
159 |
-
# Function to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
def filter_menu(preference):
|
161 |
menu_data = load_menu_from_salesforce()
|
162 |
|
@@ -195,39 +112,45 @@ def filter_menu(preference):
|
|
195 |
|
196 |
return html_content
|
197 |
|
198 |
-
#
|
199 |
-
def
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
231 |
# JavaScript for Modal and Cart
|
232 |
def modal_js():
|
233 |
modal_script = """
|
@@ -262,7 +185,7 @@ def modal_js():
|
|
262 |
const extras = selectedAddOns.map(extra => ({
|
263 |
name: extra.value,
|
264 |
price: parseFloat(extra.getAttribute('data-price')),
|
265 |
-
quantity: 1
|
266 |
}));
|
267 |
const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
|
268 |
const totalCost = (price * quantity) + extrasCost;
|
@@ -277,60 +200,39 @@ def modal_js():
|
|
277 |
const cartButton = document.getElementById('cart-button');
|
278 |
cartButton.innerText = `View Cart (${cart.length} items)`;
|
279 |
}
|
280 |
-
function openCartModal() {
|
281 |
-
const cartModal = document.getElementById('cart-modal');
|
282 |
-
const cartItemsContainer = document.getElementById('cart-items');
|
283 |
-
cartItemsContainer.innerHTML = "";
|
284 |
-
cart.forEach((item, index) => {
|
285 |
-
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(', ');
|
286 |
-
cartItemsContainer.innerHTML += `
|
287 |
-
<div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px;">
|
288 |
-
<h3>${item.name}</h3>
|
289 |
-
<p>Quantity: <input type="number" value="${item.quantity}" min="1" style="width: 50px;" onchange="updateCartItem(${index}, 'item', this.value)" /></p>
|
290 |
-
<p>Extras: ${extrasList || 'None'}</p>
|
291 |
-
<p>Special Instructions: ${item.instructions || 'None'}</p>
|
292 |
-
<p>Total Cost: $<span id="item-${index}-total">${item.totalCost.toFixed(2)}</span></p>
|
293 |
-
<button onclick="removeFromCart(${index})" style="color: red;">Remove</button>
|
294 |
-
</div>
|
295 |
-
`;
|
296 |
-
});
|
297 |
-
cartModal.style.display = 'block';
|
298 |
-
}
|
299 |
-
function closeCartModal() {
|
300 |
-
document.getElementById('cart-modal').style.display = 'none';
|
301 |
-
}
|
302 |
-
function removeFromCart(index) {
|
303 |
-
totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost
|
304 |
-
cart.splice(index, 1);
|
305 |
-
updateCartButton();
|
306 |
-
updateCartTotalCost(); // Update total cost displayed
|
307 |
-
openCartModal();
|
308 |
-
}
|
309 |
-
function updateCartItem(index, type, value) {
|
310 |
-
if (type === 'item') {
|
311 |
-
cart[index].quantity = parseInt(value);
|
312 |
-
} else if (type === 'extra') {
|
313 |
-
cart[index].extras[0].quantity = parseInt(value); // Assuming one add-on for simplicity
|
314 |
-
}
|
315 |
-
const item = cart[index];
|
316 |
-
const price = item.price;
|
317 |
-
const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
|
318 |
-
item.totalCost = (price * item.quantity) + extrasCost;
|
319 |
-
document.getElementById(`item-${index}-total`).innerText = item.totalCost.toFixed(2);
|
320 |
-
updateCartTotalCost(); // Update total cost displayed
|
321 |
-
}
|
322 |
-
function updateCartTotalCost() {
|
323 |
-
const totalCostElement = document.getElementById('cart-total-cost');
|
324 |
-
totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0);
|
325 |
-
totalCostElement.innerText = `Total Cart Cost: $${totalCartCost.toFixed(2)}`;
|
326 |
-
}
|
327 |
function proceedToCheckout() {
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
334 |
}
|
335 |
</script>
|
336 |
"""
|
@@ -368,19 +270,11 @@ with gr.Blocks() as app:
|
|
368 |
gr.HTML(create_modal_window())
|
369 |
gr.HTML(modal_js())
|
370 |
|
371 |
-
with gr.Row(visible=False) as order_page:
|
372 |
-
with gr.Column():
|
373 |
-
order_id_input = gr.Textbox(label="Order ID")
|
374 |
-
show_order_button = gr.Button("Show Order Details")
|
375 |
-
order_details_output = gr.Textbox(label="Order Details")
|
376 |
-
show_order_button.click(show_order_details, [order_id_input], order_details_output)
|
377 |
-
|
378 |
login_button.click(
|
379 |
lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
|
380 |
if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
|
381 |
[login_email, login_password], [login_page, menu_page, menu_output, login_output]
|
382 |
)
|
383 |
-
|
384 |
preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
|
385 |
|
386 |
-
app.launch()
|
|
|
1 |
import bcrypt
|
2 |
import gradio as gr
|
3 |
from simple_salesforce import Salesforce
|
|
|
4 |
|
5 |
# Salesforce Connection
|
6 |
sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
|
|
13 |
def verify_password(plain_password, hashed_password):
|
14 |
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
15 |
|
16 |
+
# Signup function
|
17 |
+
def signup(name, email, phone, password):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
try:
|
19 |
+
email = email.strip()
|
20 |
+
query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{email}'"
|
21 |
result = sf.query(query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
if len(result['records']) > 0:
|
24 |
+
return "Email already exists! Please use a different email."
|
|
|
|
|
|
|
25 |
|
26 |
+
hashed_password = hash_password(password)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
sf.Customer_Login__c.create({
|
29 |
+
'Name': name.strip(),
|
30 |
+
'Email__c': email,
|
31 |
+
'Phone_Number__c': phone.strip(),
|
32 |
+
'Password__c': hashed_password
|
33 |
+
})
|
34 |
+
return "Signup successful! You can now login."
|
35 |
except Exception as e:
|
36 |
+
return f"Error during signup: {str(e)}"
|
37 |
|
38 |
+
# Login function
|
39 |
def login(email, password):
|
40 |
try:
|
41 |
+
email = email.strip()
|
42 |
query = f"SELECT Name, Password__c FROM Customer_Login__c WHERE Email__c = '{email}'"
|
43 |
result = sf.query(query)
|
44 |
+
|
45 |
if len(result['records']) == 0:
|
46 |
return "Invalid email or password.", None
|
47 |
+
|
48 |
user = result['records'][0]
|
49 |
stored_password = user['Password__c']
|
50 |
+
|
|
|
51 |
if verify_password(password.strip(), stored_password):
|
52 |
return "Login successful!", user['Name']
|
53 |
else:
|
|
|
55 |
except Exception as e:
|
56 |
return f"Error during login: {str(e)}", None
|
57 |
|
58 |
+
# Function to load menu data
|
59 |
+
def load_menu_from_salesforce():
|
60 |
try:
|
61 |
+
query = "SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c FROM Menu_Item__c"
|
|
|
62 |
result = sf.query(query)
|
63 |
+
return result['records']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
except Exception as e:
|
65 |
+
return []
|
66 |
|
67 |
+
# Function to load add-ons data
|
68 |
+
def load_add_ons_from_salesforce():
|
69 |
+
try:
|
70 |
+
query = "SELECT Name, Price__c FROM Add_Ons__c"
|
71 |
+
result = sf.query(query)
|
72 |
+
return result['records']
|
73 |
+
except Exception as e:
|
74 |
+
return []
|
75 |
+
|
76 |
+
# Function to filter menu items
|
77 |
def filter_menu(preference):
|
78 |
menu_data = load_menu_from_salesforce()
|
79 |
|
|
|
112 |
|
113 |
return html_content
|
114 |
|
115 |
+
# Function to create order in Salesforce
|
116 |
+
def create_order_in_salesforce(cart, customer_email):
|
117 |
+
try:
|
118 |
+
# Fetch customer details
|
119 |
+
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c = '{customer_email}'"
|
120 |
+
result = sf.query(query)
|
121 |
+
|
122 |
+
if len(result['records']) == 0:
|
123 |
+
return "Customer not found."
|
124 |
+
|
125 |
+
customer = result['records'][0]
|
126 |
+
customer_id = customer['Id']
|
127 |
+
customer_name = customer['Name']
|
128 |
+
|
129 |
+
# Create Order record
|
130 |
+
order = sf.Order.create({
|
131 |
+
'AccountId': customer_id, # Assuming Account is linked to Customer
|
132 |
+
'Status': 'Draft', # You can set this as per your requirement
|
133 |
+
'OrderNumber': 'Auto-generated', # Use your custom logic if required
|
134 |
+
'Name': f"Order for {customer_name}",
|
135 |
+
'Customer_Email__c': customer_email # Assuming a custom field for email in Order
|
136 |
+
})
|
137 |
+
|
138 |
+
# Create Order Items for each cart item
|
139 |
+
for item in cart:
|
140 |
+
sf.OrderItem.create({
|
141 |
+
'OrderId': order['id'],
|
142 |
+
'Product2Id': item['product_id'], # Assuming you have Product2 Id for each item
|
143 |
+
'Quantity': item['quantity'],
|
144 |
+
'UnitPrice': item['price'],
|
145 |
+
'TotalPrice': item['totalCost'],
|
146 |
+
'Special_Instructions__c': item['instructions'],
|
147 |
+
})
|
148 |
+
|
149 |
+
return "Order successfully placed and saved to Salesforce."
|
150 |
+
|
151 |
+
except Exception as e:
|
152 |
+
return f"Error during order creation: {str(e)}"
|
153 |
+
|
154 |
# JavaScript for Modal and Cart
|
155 |
def modal_js():
|
156 |
modal_script = """
|
|
|
185 |
const extras = selectedAddOns.map(extra => ({
|
186 |
name: extra.value,
|
187 |
price: parseFloat(extra.getAttribute('data-price')),
|
188 |
+
quantity: 1
|
189 |
}));
|
190 |
const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
|
191 |
const totalCost = (price * quantity) + extrasCost;
|
|
|
200 |
const cartButton = document.getElementById('cart-button');
|
201 |
cartButton.innerText = `View Cart (${cart.length} items)`;
|
202 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
function proceedToCheckout() {
|
204 |
+
// Collect cart details
|
205 |
+
const cartData = cart.map(item => ({
|
206 |
+
product_id: item.product_id, // Assuming you have a product_id field
|
207 |
+
name: item.name,
|
208 |
+
quantity: item.quantity,
|
209 |
+
price: item.price,
|
210 |
+
totalCost: item.totalCost,
|
211 |
+
instructions: item.instructions
|
212 |
+
}));
|
213 |
+
|
214 |
+
const email = 'user@example.com'; // Replace with dynamic email
|
215 |
+
|
216 |
+
fetch('/create_order', {
|
217 |
+
method: 'POST',
|
218 |
+
headers: {
|
219 |
+
'Content-Type': 'application/json',
|
220 |
+
},
|
221 |
+
body: JSON.stringify({
|
222 |
+
cart: cartData,
|
223 |
+
email: email
|
224 |
+
})
|
225 |
+
})
|
226 |
+
.then(response => response.json())
|
227 |
+
.then(data => {
|
228 |
+
alert(data.message);
|
229 |
+
if (data.success) {
|
230 |
+
// Optionally redirect to a confirmation page or clear cart
|
231 |
+
}
|
232 |
+
})
|
233 |
+
.catch(error => {
|
234 |
+
alert("Error during checkout: " + error);
|
235 |
+
});
|
236 |
}
|
237 |
</script>
|
238 |
"""
|
|
|
270 |
gr.HTML(create_modal_window())
|
271 |
gr.HTML(modal_js())
|
272 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
login_button.click(
|
274 |
lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
|
275 |
if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
|
276 |
[login_email, login_password], [login_page, menu_page, menu_output, login_output]
|
277 |
)
|
|
|
278 |
preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
|
279 |
|
280 |
+
app.launch()
|