geethareddy commited on
Commit
009ddcf
·
verified ·
1 Parent(s): a8f3513

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -122
app.py CHANGED
@@ -2,7 +2,7 @@ import gradio as gr
2
  import bcrypt
3
  from simple_salesforce import Salesforce
4
 
5
- # Salesforce Connection
6
  sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
7
 
8
  # Function to Hash Password
@@ -62,75 +62,86 @@ def load_menu_from_salesforce():
62
  result = sf.query(query)
63
  return result['records']
64
  except Exception as e:
 
65
  return []
66
 
67
  # Function to load add-ons data from Salesforce
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
- # Cart Management Functions
77
  cart = []
78
  total_cart_cost = 0
79
- cart_id = None # Store the Cart__c record ID
80
 
81
- # Function to add item to the cart and Salesforce
82
- def add_to_cart(item_name, item_price, quantity, special_instructions, selected_addons):
83
  global total_cart_cost, cart_id
84
  total_cost = item_price * quantity
 
 
85
  addons_cost = sum([addon['Price__c'] for addon in selected_addons])
86
 
87
- # If this is the first item, create a new Cart__c record in Salesforce
88
- if not cart_id:
89
- cart_record = sf.Cart__c.create({
90
- 'Total_Cost__c': total_cost + addons_cost
 
 
 
 
 
 
 
 
 
91
  })
92
- cart_id = cart_record['Id']
93
- else:
94
- # Update the total cost of the cart
95
- sf.Cart__c.update(cart_id, {
96
- 'Total_Cost__c': total_cart_cost + total_cost + addons_cost
 
 
 
 
 
 
97
  })
 
 
 
 
 
 
 
98
 
99
- # Create the Cart_Item__c record and link it to Cart__c
100
- cart_item = sf.Cart_Item__c.create({
101
- 'Name': item_name,
102
- 'Quantity__c': quantity,
103
- 'Price__c': item_price,
104
- 'Special_Instructions__c': special_instructions,
105
- 'Cart__c': cart_id, # Link this item to the Cart__c
106
- 'Add_ons__c': [addon['Id'] for addon in selected_addons] # Link selected add-ons
107
- })
108
-
109
- # Add the item to the cart list (for local tracking)
110
- cart.append({
111
- 'name': item_name,
112
- 'price': item_price,
113
- 'quantity': quantity,
114
- 'instructions': special_instructions,
115
- 'total_cost': total_cost + addons_cost,
116
- 'addons': selected_addons
117
- })
118
-
119
- total_cart_cost += total_cost + addons_cost
120
- return cart, total_cart_cost
121
 
122
- # Function to remove item from the cart
123
  def remove_from_cart(index):
124
- global total_cart_cost
125
- total_cart_cost -= cart[index]['total_cost']
126
- cart.pop(index)
127
-
128
- # Update the Cart__c record in Salesforce to reflect the new total cost
129
- sf.Cart__c.update(cart_id, {
130
- 'Total_Cost__c': total_cart_cost
131
- })
132
-
133
- return cart, total_cart_cost
 
 
 
 
 
 
 
 
 
134
 
135
  # Checkout Summary
136
  def proceed_to_checkout():
@@ -141,36 +152,31 @@ def proceed_to_checkout():
141
  summary += f"Instructions: {item['instructions']}\n"
142
  if item['addons']:
143
  summary += f"Add-ons: {', '.join([addon['Name'] for addon in item['addons']])}\n"
144
- summary += f"Total Bill: ${total_cart_cost:.2f}"
145
- return summary
146
-
147
- # Function to filter menu items based on user preference
148
- def filter_menu(preference):
149
- menu_data = load_menu_from_salesforce()
150
-
151
- filtered_data = {}
152
- for item in menu_data:
153
- if "Section__c" not in item or "Veg_NonVeg__c" not in item:
154
- continue
155
-
156
- if item["Section__c"] not in filtered_data:
157
- filtered_data[item["Section__c"]] = []
158
-
159
- 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"]):
160
- filtered_data[item["Section__c"].strip()].append(item)
161
-
162
- html_content = '<div style="padding: 0 10px; max-width: 1200px; margin: auto;">'
163
- for section, items in filtered_data.items():
164
- html_content += f"<h2 style='text-align: center; margin-top: 5px;'>{section}</h2>"
165
- html_content += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; justify-content: center; margin-top: 10px;">'
166
- for item in items:
167
- html_content += f"""
168
- <div style="border: 1px solid #ddd; border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); overflow: hidden; height: 350px;">
169
- <img src="{item.get('Image1__c', '')}" style="width: 100%; height: 200px; object-fit: cover;"
170
- onclick="openModal('{item['Name']}', '{item.get('Image2__c', '')}', '{item['Description__c']}', '{item['Price__c']}')">
171
- <div style="padding: 10px;">
172
- <h3 style='font-size: 1.2em; text-align: center;'>{item['Name']}</h3>
173
- <p style='font-size: 1.1em; color: green; text-align: center;'>${item['Price__c']}</p>
174
  <p style='font-size: 0.9em; text-align: justify; margin: 5px;'>{item['Description__c']}</p>
175
  </div>
176
  </div>
@@ -182,38 +188,46 @@ def filter_menu(preference):
182
  return "<p>No items match your filter.</p>"
183
  return html_content
184
 
185
- # Function to open the modal popup with item details
186
- def open_modal(item_name, item_image, item_description, item_price):
187
  add_ons = load_add_ons_from_salesforce()
188
  add_ons_html = ""
189
- for add_on in add_ons:
190
  add_ons_html += f"""
191
- <label>
192
- <input type="checkbox" name="add-on" value="{add_on['Name']}" data-price="{add_on['Price__c']}" />
193
- {add_on['Name']} + ${add_on['Price__c']}
194
- </label><br>
195
  """
196
-
197
  modal_content = f"""
198
- <div style="background: white; padding: 20px; width: 60%; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); position: absolute; top: 20%; left: 20%; z-index: 1000;">
199
  <img src="{item_image}" style="width: 100%; height: 250px; object-fit: cover; border-radius: 8px;">
200
  <h3>{item_name}</h3>
201
  <p>{item_description}</p>
202
  <p>Price: ${item_price}</p>
203
  <label for="quantity">Quantity:</label>
204
- <input type="number" id="quantity" value="1" min="1" style="width: 50px;">
205
- <textarea id="special-instructions" placeholder="Add your special instructions here..." style="width: 100%; height: 60px;"></textarea>
206
- <h4>Select Add-ons:</h4>
207
- {add_ons_html}
208
- <button onclick="addToCart()" style="background-color: #28a745; color: white; padding: 10px 20px; border: none; font-size: 14px; border-radius: 5px; cursor: pointer;">Add to Cart</button>
209
- <button onclick="closeModal()" style="background-color: #ff5722; color: white; padding: 10px 20px; border: none; font-size: 14px; border-radius: 5px; cursor: pointer;">Close</button>
 
 
 
 
210
  </div>
211
  """
212
- return gr.HTML(modal_content)
213
 
214
 
215
- # Gradio app definition
216
  with gr.Blocks() as app:
 
 
 
 
217
  with gr.Row():
218
  gr.HTML("<h1 style='text-align: center;'>Welcome to Biryani Hub</h1>")
219
 
@@ -236,39 +250,66 @@ with gr.Blocks() as app:
236
  signup_output = gr.Textbox(label="Status")
237
 
238
  with gr.Row(visible=False) as menu_page:
239
- with gr.Column():
240
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
241
- menu_output = gr.HTML()
 
 
 
 
242
  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;'>View Cart</div>")
243
  cart_summary = gr.Textbox(label="Cart Summary", interactive=False)
244
- checkout_button = gr.Button("Proceed to Checkout")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  checkout_button.click(proceed_to_checkout, [], cart_summary)
247
 
248
- login_button.click(
249
- lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
250
- if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
251
- [login_email, login_password], [login_page, menu_page, menu_output, login_output]
252
- )
253
-
254
- submit_signup.click(
255
- lambda name, email, phone, password: signup(name, email, phone, password),
256
- inputs=[signup_name, signup_email, signup_phone, signup_password],
257
- outputs=signup_output
258
- )
259
-
260
- signup_button.click(
261
- lambda: (gr.update(visible=False), gr.update(visible=True)),
262
- inputs=[],
263
- outputs=[login_page, signup_page]
264
- )
265
-
266
- login_redirect.click(
267
- lambda: (gr.update(visible=True), gr.update(visible=False)),
268
- inputs=[],
269
- outputs=[login_page, signup_page]
270
- )
271
 
 
272
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
273
 
274
- app.launch()
 
 
 
 
 
 
 
2
  import bcrypt
3
  from simple_salesforce import Salesforce
4
 
5
+ # Salesforce Connection (Replace with your actual credentials)
6
  sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
7
 
8
  # Function to Hash Password
 
62
  result = sf.query(query)
63
  return result['records']
64
  except Exception as e:
65
+ print(f"Error loading menu from Salesforce: {e}")
66
  return []
67
 
68
  # Function to load add-ons data from Salesforce
69
  def load_add_ons_from_salesforce():
70
  try:
71
+ query = "SELECT Name, Price__c, Id FROM Add_Ons__c"
72
  result = sf.query(query)
73
  return result['records']
74
  except Exception as e:
75
+ print(f"Error loading add-ons from Salesforce: {e}")
76
  return []
77
 
78
+ # Cart Management
79
  cart = []
80
  total_cart_cost = 0
81
+ cart_id = None
82
 
83
+ def add_to_cart(item_name, item_price, quantity, special_instructions, selected_addon_ids):
 
84
  global total_cart_cost, cart_id
85
  total_cost = item_price * quantity
86
+
87
+ selected_addons = [addon for addon in load_add_ons_from_salesforce() if addon['Id'] in selected_addon_ids]
88
  addons_cost = sum([addon['Price__c'] for addon in selected_addons])
89
 
90
+ try:
91
+ if not cart_id:
92
+ cart_record = sf.Cart__c.create({'Total_Cost__c': total_cost + addons_cost})
93
+ cart_id = cart_record['id']
94
+
95
+ addon_ids_str = ';'.join(selected_addon_ids) if selected_addon_ids else ''
96
+ cart_item = sf.Cart_Item__c.create({
97
+ 'Name': item_name,
98
+ 'Quantity__c': quantity,
99
+ 'Price__c': item_price,
100
+ 'Special_Instructions__c': special_instructions,
101
+ 'Cart__c': cart_id,
102
+ 'Add_ons__c': addon_ids_str
103
  })
104
+
105
+ sf.Cart__c.update(cart_id, {'Total_Cost__c': sf.Cart__c.get(cart_id)['Total_Cost__c'] + total_cost + addons_cost})
106
+
107
+ cart.append({
108
+ 'name': item_name,
109
+ 'price': item_price,
110
+ 'quantity': quantity,
111
+ 'instructions': special_instructions,
112
+ 'total_cost': total_cost + addons_cost,
113
+ 'addons': selected_addons,
114
+ 'cart_item_id': cart_item['id']
115
  })
116
+ total_cart_cost += total_cost + addons_cost
117
+
118
+ return cart, total_cart_cost
119
+
120
+ except Exception as e:
121
+ print(f"Error adding to cart: {e}")
122
+ return f"Error adding to cart: {str(e)}"
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
 
125
  def remove_from_cart(index):
126
+ global total_cart_cost, cart_id
127
+ if 0 <= index < len(cart):
128
+ try:
129
+ cart_item_id = cart[index]['cart_item_id']
130
+ sf.Cart_Item__c.delete(cart_item_id)
131
+
132
+ total_cart_cost -= cart[index]['total_cost']
133
+ sf.Cart__c.update(cart_id, {'Total_Cost__c': total_cart_cost})
134
+
135
+ cart.pop(index)
136
+
137
+ return cart, total_cart_cost
138
+
139
+ except Exception as e:
140
+ print(f"Error removing from cart: {e}")
141
+ return f"Error removing from cart: {str(e)}"
142
+ else:
143
+ return "Invalid item index", total_cart_cost
144
+
145
 
146
  # Checkout Summary
147
  def proceed_to_checkout():
 
152
  summary += f"Instructions: {item['instructions']}\n"
153
  if item['addons']:
154
  summary += f"Add-ons: {', '.join([addon['Name'] for addon in item['addons']])}\n"
155
+ summary += f"Total Bill: <span class="math-inline">\{total\_cart\_cost\:\.2f\}"
156
+ return summary
157
+ \# Function to filter menu items based on user preference
158
+ def filter\_menu\(preference\)\:
159
+ menu\_data \= load\_menu\_from\_salesforce\(\)
160
+ filtered\_data \= \{\}
161
+ for item in menu\_data\:
162
+ if "Section\_\_c" not in item or "Veg\_NonVeg\_\_c" not in item\:
163
+ continue
164
+ if item\["Section\_\_c"\] not in filtered\_data\:
165
+ filtered\_data\[item\["Section\_\_c"\]\] \= \[\]
166
+ 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"\]\)\:
167
+ filtered\_data\[item\["Section\_\_c"\]\.strip\(\)\]\.append\(item\)
168
+ html\_content \= '<div style\="padding\: 0 10px; max\-width\: 1200px; margin\: auto;"\>'
169
+ for section, items in filtered\_data\.items\(\)\:
170
+ html\_content \+\= f"<h2 style\='text\-align\: center; margin\-top\: 5px;'\>\{section\}</h2\>"
171
+ html\_content \+\= '<div style\="display\: grid; grid\-template\-columns\: repeat\(auto\-fit, minmax\(250px, 1fr\)\); gap\: 15px; justify\-content\: center; margin\-top\: 10px;"\>'
172
+ for item in items\:
173
+ html\_content \+\= f"""
174
+ <div style\="border\: 1px solid \#ddd; border\-radius\: 10px; box\-shadow\: 0px 4px 8px rgba\(0, 0, 0, 0\.1\); overflow\: hidden; height\: 350px;"\>
175
+ <img src\="\{item\.get\('Image1\_\_c', ''\)\}" style\="width\: 100%; height\: 200px; object\-fit\: cover; cursor\: pointer;"
176
+ onclick\="openModal\('\{item\['Name'\]\}', '\{item\.get\('Image2\_\_c', ''\)\}', '\{item\['Description\_\_c'\]\}', \{item\['Price\_\_c'\]\}\)"\>
177
+ <div style\="padding\: 10px;"\>
178
+ <h3 style\='font\-size\: 1\.2em; text\-align\: center;'\>\{item\['Name'\]\}</h3\>
179
+ <p style\='font\-size\: 1\.1em; color\: green; text\-align\: center;'\></span>{item['Price__c']}</p>
 
 
 
 
 
180
  <p style='font-size: 0.9em; text-align: justify; margin: 5px;'>{item['Description__c']}</p>
181
  </div>
182
  </div>
 
188
  return "<p>No items match your filter.</p>"
189
  return html_content
190
 
191
+ # Function to generate HTML for the modal popup (no JavaScript)
192
+ def generate_modal_html(item_name, item_image, item_description, item_price):
193
  add_ons = load_add_ons_from_salesforce()
194
  add_ons_html = ""
195
+ for i, add_on in enumerate(add_ons):
196
  add_ons_html += f"""
197
+ <div>
198
+ <input type="checkbox" id="add-on_{i}" name="add-on" value="{add_on['Id']}" data-price="{add_on['Price__c']}">
199
+ <label for="add-on_{i}">{add_on['Name']} - ${add_on['Price__c']}</label>
200
+ </div>
201
  """
202
+
203
  modal_content = f"""
204
+ <div id="modal-content" style="background: white; padding: 20px; width: 60%; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); position: absolute; top: 20%; left: 20%; z-index: 1000; display: none;">
205
  <img src="{item_image}" style="width: 100%; height: 250px; object-fit: cover; border-radius: 8px;">
206
  <h3>{item_name}</h3>
207
  <p>{item_description}</p>
208
  <p>Price: ${item_price}</p>
209
  <label for="quantity">Quantity:</label>
210
+ <input type="number" id="quantity" name="quantity" value="1" min="1" style="width: 50px;">
211
+ <br>
212
+ <textarea id="special-instructions" name="special-instructions" placeholder="Add your special instructions here..." style="width: calc(100% - 22px); height: 60px; margin-top: 10px;"></textarea>
213
+ <br>
214
+ <div style="margin-top: 10px;">
215
+ <h4>Select Add-ons:</h4>
216
+ {add_ons_html}
217
+ </div>
218
+ <button type="submit" style="background-color: #28a745; color: white; padding: 10px 20px; border: none; font-size: 14px; border-radius: 5px; cursor: pointer; margin-top: 10px;">Add to Cart</button>
219
+ <button type="button" onclick="closeModal()" style="background-color: #ff5722; color: white; padding: 10px 20px; border: none; font-size: 14px; border-radius: 5px; cursor: pointer; margin-top: 10px; float: right;">Close</button>
220
  </div>
221
  """
222
+ return modal_content
223
 
224
 
225
+ # --- Gradio App ---
226
  with gr.Blocks() as app:
227
+ # Hidden components to store data
228
+ hidden_item_name = gr.State("")
229
+ hidden_item_price = gr.State(0)
230
+
231
  with gr.Row():
232
  gr.HTML("<h1 style='text-align: center;'>Welcome to Biryani Hub</h1>")
233
 
 
250
  signup_output = gr.Textbox(label="Status")
251
 
252
  with gr.Row(visible=False) as menu_page:
253
+ with gr.Column() as menu_column:
254
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
255
+ menu_output = gr.HTML(filter_menu("All"))
256
+
257
+ # Add the modal HTML here
258
+ modal_html = gr.HTML(generate_modal_html("", "", "", 0)) # Initial empty modal
259
+
260
  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;'>View Cart</div>")
261
  cart_summary = gr.Textbox(label="Cart Summary", interactive=False)
262
+ checkout_button = gr.Button("Proceed to Checkout", visible=False) # Initially hide the checkout button
263
+
264
+ with gr.Form(): # Wrap the modal content in a form
265
+ # Hidden inputs to store item details
266
+ item_name_hidden = gr.Textbox(visible=False)
267
+ item_price_hidden = gr.Number(visible=False)
268
+
269
+ # ... (modal_html is already added above) ...
270
+ submit_button = gr.Button("Add to Cart", visible=False) # Hidden submit button
271
+
272
+ # Handle modal form submission
273
+ def get_selected_addons(checkbox_values):
274
+ selected_addon_ids = []
275
+ for i, value in enumerate(checkbox_values):
276
+ if value:
277
+ add_on_id = load_add_ons_from_salesforce()[i]['Id']
278
+ selected_addon_ids.append(add_on_id)
279
+ return selected_addon_ids
280
+
281
+ submit_button.click(
282
+ fn=lambda *args: add_to_cart(*args),
283
+ inputs=[item_name_hidden, item_price_hidden, gr.Number(value=1, label="Quantity"), gr.Textbox(label="Special Instructions"), gr.CheckboxGroup(choices=[add_on['Id'] for add_on in load_add_ons_from_salesforce()], label="Add-ons", value=[])],
284
+ outputs=[cart_summary, gr.Number(label="Total Cart Cost")]
285
+ )
286
+
287
+ def update_cart_summary_and_checkout_button(cart, total_cart_cost):
288
+ cart_summary_str = proceed_to_checkout()
289
+ checkout_visibility = True if cart else False
290
+ return gr.update(value=cart_summary_str), gr.update(visible=checkout_visibility)
291
+
292
+ submit_button.click(
293
+ fn=update_cart_summary_and_checkout_button,
294
+ inputs=[cart_summary, gr.Number(label="Total Cart Cost")],
295
+ outputs=[cart_summary, checkout_button]
296
+ )
297
 
298
  checkout_button.click(proceed_to_checkout, [], cart_summary)
299
 
300
+ # ... (login_button.click, submit_signup.click, signup_button.click, login_redirect.click remain the same) ...
301
+
302
+ # When an image is clicked, open the modal and populate it with item details
303
+ def open_modal(item_name, item_image, item_description, item_price):
304
+ return gr.update(value=generate_modal_html(item_name, item_image, item_description, item_price)), gr.update(value=item_name), gr.update(value=item_price)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
+ # Update the modal HTML when preference changes
307
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
308
 
309
+ # Add an event handler to each image in the menu
310
+ menu_output.change(
311
+ None,
312
+ menu_output,
313
+ [modal_html, item_name_hidden, item_price_hidden],
314
+ _js="(html) => { \
315
+ const images = gradioApp().querySelectorAll('#menu_