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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -55
app.py CHANGED
@@ -62,17 +62,17 @@ def load_menu_from_salesforce():
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
@@ -83,9 +83,9 @@ cart_id = None
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:
@@ -114,11 +114,10 @@ def add_to_cart(item_name, item_price, quantity, special_instructions, selected_
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
 
@@ -126,31 +125,31 @@ 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():
148
  summary = ""
149
  for item in cart:
150
  summary += f"{item['name']} (x{item['quantity']}) - ${item['total_cost']:.2f}\n"
151
- if item['instructions']:
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
@@ -161,34 +160,36 @@ 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>
183
  """
184
  html_content += '</div>'
185
  html_content += '</div>'
186
 
187
- if not any(filtered_data.values()):
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 = ""
@@ -221,7 +222,6 @@ def generate_modal_html(item_name, item_image, item_description, item_price):
221
  """
222
  return modal_content
223
 
224
-
225
  # --- Gradio App ---
226
  with gr.Blocks() as app:
227
  # Hidden components to store data
@@ -254,29 +254,16 @@ with gr.Blocks() as app:
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),
@@ -297,19 +284,33 @@ with gr.Blocks() as app:
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_
 
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
 
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:
 
114
  'cart_item_id': cart_item['id']
115
  })
116
  total_cart_cost += total_cost + addons_cost
 
117
  return cart, total_cart_cost
118
 
119
  except Exception as e:
120
+ print(f"Error adding to cart: {e}")
121
  return f"Error adding to cart: {str(e)}"
122
 
123
 
 
125
  global total_cart_cost, cart_id
126
  if 0 <= index < len(cart):
127
  try:
128
+ cart_item_id = cart[index].get('cart_item_id') # Use get() to avoid KeyError
129
+ if cart_item_id:
130
+ sf.Cart_Item__c.delete(cart_item_id)
131
 
132
  total_cart_cost -= cart[index]['total_cost']
133
+ if cart_id: # Check if cart_id exists before updating
134
+ sf.Cart__c.update(cart_id, {'Total_Cost__c': total_cart_cost})
135
 
136
  cart.pop(index)
 
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
  # Checkout Summary
146
  def proceed_to_checkout():
147
  summary = ""
148
  for item in cart:
149
  summary += f"{item['name']} (x{item['quantity']}) - ${item['total_cost']:.2f}\n"
150
+ if item.get('instructions'):
151
  summary += f"Instructions: {item['instructions']}\n"
152
+ if item.get('addons'):
153
  summary += f"Add-ons: {', '.join([addon['Name'] for addon in item['addons']])}\n"
154
  summary += f"Total Bill: <span class="math-inline">\{total\_cart\_cost\:\.2f\}"
155
  return summary
 
160
  for item in menu\_data\:
161
  if "Section\_\_c" not in item or "Veg\_NonVeg\_\_c" not in item\:
162
  continue
163
+ section \= item\["Section\_\_c"\]\.strip\(\)
164
+ if section not in filtered\_data\:
165
+ filtered\_data\[section\] \= \[\]
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\[section\]\.append\(item\)
168
+ if not any\(filtered\_data\.values\(\)\)\:
169
+ return "<p\>No items match your filter\.</p\>"
170
  html\_content \= '<div style\="padding\: 0 10px; max\-width\: 1200px; margin\: auto;"\>'
171
  for section, items in filtered\_data\.items\(\)\:
172
  html\_content \+\= f"<h2 style\='text\-align\: center; margin\-top\: 5px;'\>\{section\}</h2\>"
173
  html\_content \+\= '<div style\="display\: grid; grid\-template\-columns\: repeat\(auto\-fit, minmax\(250px, 1fr\)\); gap\: 15px; justify\-content\: center; margin\-top\: 10px;"\>'
174
  for item in items\:
175
+ image\_url \= item\.get\('Image1\_\_c', ''\)
176
  html\_content \+\= f"""
177
  <div style\="border\: 1px solid \#ddd; border\-radius\: 10px; box\-shadow\: 0px 4px 8px rgba\(0, 0, 0, 0\.1\); overflow\: hidden; height\: 350px;"\>
178
+ <img src\="\{image\_url\}" style\="width\: 100%; height\: 200px; object\-fit\: cover; cursor\: pointer;"
179
  onclick\="openModal\('\{item\['Name'\]\}', '\{item\.get\('Image2\_\_c', ''\)\}', '\{item\['Description\_\_c'\]\}', \{item\['Price\_\_c'\]\}\)"\>
180
  <div style\="padding\: 10px;"\>
181
  <h3 style\='font\-size\: 1\.2em; text\-align\: center;'\>\{item\['Name'\]\}</h3\>
182
  <p style\='font\-size\: 1\.1em; color\: green; text\-align\: center;'\></span>{item['Price__c']}</p>
183
+ <p style='font-size: 0.9em; text-align: justify; margin: 5px;'>{item['Description__c'] or ''}</p>
184
+ </div>
185
  </div>
 
186
  """
187
  html_content += '</div>'
188
  html_content += '</div>'
189
 
 
 
190
  return html_content
191
 
192
+ # Function to generate HTML for the modal popup
193
  def generate_modal_html(item_name, item_image, item_description, item_price):
194
  add_ons = load_add_ons_from_salesforce()
195
  add_ons_html = ""
 
222
  """
223
  return modal_content
224
 
 
225
  # --- Gradio App ---
226
  with gr.Blocks() as app:
227
  # Hidden components to store data
 
254
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
255
  menu_output = gr.HTML(filter_menu("All"))
256
 
257
+ modal_html = gr.HTML(generate_modal_html("", "", "", 0))
 
258
 
259
  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>")
260
  cart_summary = gr.Textbox(label="Cart Summary", interactive=False)
261
+ checkout_button = gr.Button("Proceed to Checkout", visible=False)
262
 
263
+ with gr.Form():
 
264
  item_name_hidden = gr.Textbox(visible=False)
265
  item_price_hidden = gr.Number(visible=False)
266
+ submit_button = gr.Button("Add to Cart", visible=False)
 
 
 
 
 
 
 
 
 
 
 
267
 
268
  submit_button.click(
269
  fn=lambda *args: add_to_cart(*args),
 
284
 
285
  checkout_button.click(proceed_to_checkout, [], cart_summary)
286
 
287
+ # --- Event Handlers ---
288
+ login_button.click(
289
+ lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
290
+ if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
291
+ [login_email, login_password], [login_page, menu_page, menu_output, login_output]
292
+ )
293
+
294
+ submit_signup.click(
295
+ lambda name, email, phone, password: signup(name, email, phone, password),
296
+ inputs=[signup_name, signup_email, signup_phone, signup_password],
297
+ outputs=signup_output
298
+ )
299
+
300
+ signup_button.click(
301
+ lambda: (gr.update(visible=False), gr.update(visible=True)),
302
+ inputs=[],
303
+ outputs=[login_page, signup_page]
304
+ )
305
+
306
+ login_redirect.click(
307
+ lambda: (gr.update(visible=True), gr.update(visible=False)),
308
+ inputs=[],
309
+ outputs=[login_page, signup_page]
310
+ )
311
 
 
312
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
313
 
314
+ # When an image is clicked, open the modal and populate it with item details
315
+ def open_modal(item_name, item_image, item_description, item_price):
316
+ return gr.