nagasurendra commited on
Commit
7adc402
·
verified ·
1 Parent(s): b4f3a62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -84
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import bcrypt
2
  import gradio as gr
3
  from simple_salesforce import Salesforce
 
4
 
5
  # Salesforce Connection
6
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
@@ -13,41 +14,118 @@ def hash_password(password):
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,25 +133,30 @@ def login(email, password):
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,47 +195,12 @@ def filter_menu(preference):
112
 
113
  return html_content
114
 
115
- # Create Modal Window HTML
116
- def create_modal_window():
117
- add_ons = load_add_ons_from_salesforce()
118
- add_ons_html = ""
119
- for add_on in add_ons:
120
- add_ons_html += f"""
121
- <label>
122
- <input type="checkbox" name="biryani-extra" value="{add_on['Name']}" data-price="{add_on['Price__c']}" />
123
- {add_on['Name']} + ${add_on['Price__c']}
124
- </label>
125
- <br>
126
- """
127
-
128
- modal_html = f"""
129
- <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;">
130
- <div style="text-align: right;">
131
- <button onclick="closeModal()" style="background: none; border: none; font-size: 18px; cursor: pointer;">&times;</button>
132
- </div>
133
- <img id="modal-image" style="width: 100%; height: 300px; border-radius: 8px; margin-bottom: 20px;" />
134
- <h2 id="modal-name"></h2>
135
- <p id="modal-description"></p>
136
- <p id="modal-price"></p>
137
- <label for="biryani-extras"><strong>Add-ons :</strong></label>
138
- <div id="biryani-extras-options" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;">
139
- {add_ons_html}
140
- </div>
141
- <label for="quantity">Quantity:</label>
142
- <input type="number" id="quantity" value="1" min="1" style="width: 50px;" />
143
- <textarea id="special-instructions" placeholder="Add your special instructions here..." style="width: 100%; height: 60px;"></textarea>
144
- <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>
145
- </div>
146
- """
147
- return modal_html
148
-
149
  # JavaScript for Modal and Cart
150
  def modal_js():
151
  modal_script = """
152
  <script>
153
  let cart = [];
154
  let totalCartCost = 0;
155
-
156
  function openModal(name, image2, description, price) {
157
  const modal = document.getElementById('modal');
158
  modal.style.display = 'block';
@@ -169,11 +217,9 @@ def modal_js():
169
  document.getElementById('special-instructions').value = '';
170
  resetAddOns(); // Reset add-ons when opening the modal
171
  }
172
-
173
  function closeModal() {
174
  document.getElementById('modal').style.display = 'none';
175
  }
176
-
177
  function addToCart() {
178
  const name = document.getElementById('modal-name').innerText;
179
  const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
@@ -187,7 +233,6 @@ def modal_js():
187
  }));
188
  const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
189
  const totalCost = (price * quantity) + extrasCost;
190
-
191
  // Add the item to the cart with its specific add-ons
192
  cart.push({ name, price, quantity, extras, instructions, totalCost });
193
  totalCartCost += totalCost; // Update the total cost of the cart
@@ -195,17 +240,14 @@ def modal_js():
195
  updateCartTotalCost(); // Update total cost displayed
196
  closeModal();
197
  }
198
-
199
  function updateCartButton() {
200
  const cartButton = document.getElementById('cart-button');
201
  cartButton.innerText = `View Cart (${cart.length} items)`;
202
  }
203
-
204
  function openCartModal() {
205
  const cartModal = document.getElementById('cart-modal');
206
  const cartItemsContainer = document.getElementById('cart-items');
207
  cartItemsContainer.innerHTML = "";
208
-
209
  cart.forEach((item, index) => {
210
  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(', ');
211
  cartItemsContainer.innerHTML += `
@@ -219,14 +261,11 @@ def modal_js():
219
  </div>
220
  `;
221
  });
222
-
223
  cartModal.style.display = 'block';
224
  }
225
-
226
  function closeCartModal() {
227
  document.getElementById('cart-modal').style.display = 'none';
228
  }
229
-
230
  function removeFromCart(index) {
231
  totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost
232
  cart.splice(index, 1);
@@ -234,14 +273,12 @@ def modal_js():
234
  updateCartTotalCost(); // Update total cost displayed
235
  openCartModal();
236
  }
237
-
238
  function updateCartItem(index, type, value) {
239
  if (type === 'item') {
240
  cart[index].quantity = parseInt(value);
241
  } else if (type === 'extra') {
242
  cart[index].extras[0].quantity = parseInt(value); // Assuming one add-on for simplicity
243
  }
244
-
245
  const item = cart[index];
246
  const price = item.price;
247
  const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
@@ -249,17 +286,14 @@ def modal_js():
249
  document.getElementById(`item-${index}-total`).innerText = item.totalCost.toFixed(2);
250
  updateCartTotalCost(); // Update total cost displayed
251
  }
252
-
253
  function updateCartTotalCost() {
254
  const totalCostElement = document.getElementById('cart-total-cost');
255
  totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0);
256
  totalCostElement.innerText = `Total Cart Cost: $${totalCartCost.toFixed(2)}`;
257
  }
258
-
259
  function proceedToCheckout() {
260
  alert("Proceeding to checkout...");
261
  }
262
-
263
  // Reset all selected add-ons when opening a new item modal
264
  function resetAddOns() {
265
  const checkboxes = document.querySelectorAll('input[name="biryani-extra"]');
@@ -301,11 +335,19 @@ with gr.Blocks() as app:
301
  gr.HTML(create_modal_window())
302
  gr.HTML(modal_js())
303
 
 
 
 
 
 
 
 
304
  login_button.click(
305
  lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
306
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
307
  [login_email, login_password], [login_page, menu_page, menu_output, login_output]
308
  )
 
309
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
310
 
311
  app.launch()
 
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='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
 
14
  def verify_password(plain_password, hashed_password):
15
  return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
16
 
17
+ # Function to create Order in Salesforce
18
+ def create_order_in_salesforce(user_email, cart_items, total_cost, special_instructions):
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
+ query = "SELECT Name, Price__c FROM Add_Ons__c"
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
+ # Create order in Salesforce and get order ID
75
+ order_id = create_order_in_salesforce(user_email, cart_items, total_cost, special_instructions)
76
+
77
+ # Return order ID to display the details page
78
+ return order_id
79
+
80
+ # Function to display the order details after checkout
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 while fetching order details: {str(e)}"
114
 
115
+ # Function to handle login and authentication
116
  def login(email, password):
117
  try:
118
+ # Query the user by email
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
  except Exception as e:
134
  return f"Error during login: {str(e)}", None
135
 
136
+ # Function to handle signup
137
+ def signup(name, email, phone, password):
 
 
 
 
 
 
 
 
 
138
  try:
139
+ # Check if the email already exists
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 f"Error during signup: {str(e)}"
158
 
159
+ # Function to filter menu based on preference
160
  def filter_menu(preference):
161
  menu_data = load_menu_from_salesforce()
162
 
 
195
 
196
  return html_content
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # JavaScript for Modal and Cart
199
  def modal_js():
200
  modal_script = """
201
  <script>
202
  let cart = [];
203
  let totalCartCost = 0;
 
204
  function openModal(name, image2, description, price) {
205
  const modal = document.getElementById('modal');
206
  modal.style.display = 'block';
 
217
  document.getElementById('special-instructions').value = '';
218
  resetAddOns(); // Reset add-ons when opening the modal
219
  }
 
220
  function closeModal() {
221
  document.getElementById('modal').style.display = 'none';
222
  }
 
223
  function addToCart() {
224
  const name = document.getElementById('modal-name').innerText;
225
  const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
 
233
  }));
234
  const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
235
  const totalCost = (price * quantity) + extrasCost;
 
236
  // Add the item to the cart with its specific add-ons
237
  cart.push({ name, price, quantity, extras, instructions, totalCost });
238
  totalCartCost += totalCost; // Update the total cost of the cart
 
240
  updateCartTotalCost(); // Update total cost displayed
241
  closeModal();
242
  }
 
243
  function updateCartButton() {
244
  const cartButton = document.getElementById('cart-button');
245
  cartButton.innerText = `View Cart (${cart.length} items)`;
246
  }
 
247
  function openCartModal() {
248
  const cartModal = document.getElementById('cart-modal');
249
  const cartItemsContainer = document.getElementById('cart-items');
250
  cartItemsContainer.innerHTML = "";
 
251
  cart.forEach((item, index) => {
252
  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(', ');
253
  cartItemsContainer.innerHTML += `
 
261
  </div>
262
  `;
263
  });
 
264
  cartModal.style.display = 'block';
265
  }
 
266
  function closeCartModal() {
267
  document.getElementById('cart-modal').style.display = 'none';
268
  }
 
269
  function removeFromCart(index) {
270
  totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost
271
  cart.splice(index, 1);
 
273
  updateCartTotalCost(); // Update total cost displayed
274
  openCartModal();
275
  }
 
276
  function updateCartItem(index, type, value) {
277
  if (type === 'item') {
278
  cart[index].quantity = parseInt(value);
279
  } else if (type === 'extra') {
280
  cart[index].extras[0].quantity = parseInt(value); // Assuming one add-on for simplicity
281
  }
 
282
  const item = cart[index];
283
  const price = item.price;
284
  const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
 
286
  document.getElementById(`item-${index}-total`).innerText = item.totalCost.toFixed(2);
287
  updateCartTotalCost(); // Update total cost displayed
288
  }
 
289
  function updateCartTotalCost() {
290
  const totalCostElement = document.getElementById('cart-total-cost');
291
  totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0);
292
  totalCostElement.innerText = `Total Cart Cost: $${totalCartCost.toFixed(2)}`;
293
  }
 
294
  function proceedToCheckout() {
295
  alert("Proceeding to checkout...");
296
  }
 
297
  // Reset all selected add-ons when opening a new item modal
298
  function resetAddOns() {
299
  const checkboxes = document.querySelectorAll('input[name="biryani-extra"]');
 
335
  gr.HTML(create_modal_window())
336
  gr.HTML(modal_js())
337
 
338
+ with gr.Row(visible=False) as order_page:
339
+ with gr.Column():
340
+ order_id_input = gr.Textbox(label="Order ID")
341
+ show_order_button = gr.Button("Show Order Details")
342
+ order_details_output = gr.Textbox(label="Order Details")
343
+ show_order_button.click(show_order_details, [order_id_input], order_details_output)
344
+
345
  login_button.click(
346
  lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
347
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
348
  [login_email, login_password], [login_page, menu_page, menu_output, login_output]
349
  )
350
+
351
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
352
 
353
  app.launch()