geethareddy commited on
Commit
1b2a568
·
verified ·
1 Parent(s): e8ac576

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -209
app.py CHANGED
@@ -55,16 +55,16 @@ 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"
@@ -73,211 +73,61 @@ def load_add_ons_from_salesforce():
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
-
80
- filtered_data = {}
81
- for item in menu_data:
82
- if "Section__c" not in item or "Veg_NonVeg__c" not in item:
83
- continue
84
-
85
- if item["Section__c"] not in filtered_data:
86
- filtered_data[item["Section__c"]] = []
87
-
88
- 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"]):
89
- filtered_data[item["Section__c"].strip()].append(item)
90
-
91
- html_content = '<div style="padding: 0 10px; max-width: 1200px; margin: auto;">'
92
- for section, items in filtered_data.items():
93
- html_content += f"<h2 style='text-align: center; margin-top: 5px;'>{section}</h2>"
94
- html_content += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; justify-content: center; margin-top: 10px;">'
95
- for item in items:
96
- html_content += f"""
97
- <div style="border: 1px solid #ddd; border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); overflow: hidden; height: 350px;">
98
- <img src="{item.get('Image1__c', '')}" style="width: 100%; height: 200px; object-fit: cover;"
99
- onclick="openModal('{item['Name']}', '{item.get('Image2__c', '')}', '{item['Description__c']}', '${item['Price__c']}')">
100
- <div style="padding: 10px;">
101
- <h3 style='font-size: 1.2em; text-align: center;'>{item['Name']}</h3>
102
- <p style='font-size: 1.1em; color: green; text-align: center;'>${item['Price__c']}</p>
103
- <p style='font-size: 0.9em; text-align: justify; margin: 5px;'>{item['Description__c']}</p>
104
- </div>
105
- </div>
106
- """
107
- html_content += '</div>'
108
- html_content += '</div>'
109
-
110
- if not any(filtered_data.values()):
111
- return "<p>No items match your filter.</p>"
112
-
113
- return html_content
114
-
115
- # Function to save cart details to Salesforce
116
- def save_cart_to_salesforce(cart):
117
  try:
118
- # Loop through each cart item and create a new Order__c record
119
- for item in cart:
120
- order_data = {
121
- 'Name2__c': item['name'], # Custom name for the order (can be the item name or order ID)
122
- 'Item_Name__c': item['name'], # Name of the item in the order
123
- 'Quantity__c': item['quantity'], # Quantity of the item
124
- 'Price__c': item['price'], # Price of the item
125
- 'Total_Cost__c': item['totalCost'], # Total cost for the item
126
- 'Special_Instructions__c': item['instructions'], # Special instructions (if any)
127
- }
128
-
129
- # Handle add-ons if available
130
- if item['extras']:
131
- add_ons = ", ".join([add_on['name'] for add_on in item['extras']])
132
- order_data['Add_Ons__c'] = add_ons # Add-ons associated with the item
133
-
134
- # Create the order in Salesforce
135
- sf.Order__c.create(order_data)
136
-
137
- return "Cart saved successfully to Salesforce!"
138
  except Exception as e:
139
- return f"Error while saving cart to Salesforce: {str(e)}"
140
 
141
- # Function to create the modal window with add-ons
142
- def create_modal_window():
143
- add_ons = load_add_ons_from_salesforce()
144
- add_ons_html = ""
145
- for add_on in add_ons:
146
- add_ons_html += f"""
147
- <label>
148
- <input type="checkbox" name="biryani-extra" value="{add_on['Name']}" data-price="{add_on['Price__c']}" />
149
- {add_on['Name']} + ${add_on['Price__c']}
150
- </label>
151
- <br>
152
- """
153
 
154
- modal_html = f"""
155
- <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;">
156
- <div style="text-align: right;">
157
- <button onclick="closeModal()" style="background: none; border: none; font-size: 18px; cursor: pointer;">&times;</button>
158
- </div>
159
- <img id="modal-image" style="width: 100%; height: 300px; border-radius: 8px; margin-bottom: 20px;" />
160
- <h2 id="modal-name"></h2>
161
- <p id="modal-description"></p>
162
- <p id="modal-price"></p>
163
- <label for="biryani-extras"><strong>Add-ons :</strong></label>
164
- <div id="biryani-extras-options" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;">
165
- {add_ons_html}
 
 
 
166
  </div>
167
- <label for="quantity">Quantity:</label>
168
- <input type="number" id="quantity" value="1" min="1" style="width: 50px;" />
169
- <textarea id="special-instructions" placeholder="Add your special instructions here..." style="width: 100%; height: 60px;"></textarea>
170
- <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>
171
- </div>
172
- """
173
- return modal_html
174
 
175
- # JavaScript for Modal and Cart
176
- def modal_js():
177
- modal_script = """
178
- <script>
179
- let cart = [];
180
- let totalCartCost = 0;
181
- function openModal(name, image2, description, price) {
182
- const modal = document.getElementById('modal');
183
- modal.style.display = 'block';
184
- modal.style.position = 'fixed';
185
- modal.style.width = window.innerWidth <= 768 ? '90%' : '30%';
186
- modal.style.top = `${event.clientY}px`;
187
- modal.style.left = '50%';
188
- modal.style.transform = 'translate(-50%, -50%)';
189
- document.getElementById('modal-image').src = image2;
190
- document.getElementById('modal-name').innerText = name;
191
- document.getElementById('modal-description').innerText = description;
192
- document.getElementById('modal-price').innerText = price;
193
- document.getElementById('quantity').value = 1;
194
- document.getElementById('special-instructions').value = '';
195
- resetAddOns(); // Reset add-ons when opening the modal
196
- }
197
- function closeModal() {
198
- document.getElementById('modal').style.display = 'none';
199
- }
200
- function addToCart() {
201
- const name = document.getElementById('modal-name').innerText;
202
- const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
203
- const quantity = parseInt(document.getElementById('quantity').value) || 1;
204
- const instructions = document.getElementById('special-instructions').value;
205
- const selectedAddOns = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked'));
206
- const extras = selectedAddOns.map(extra => ({
207
- name: extra.value,
208
- price: parseFloat(extra.getAttribute('data-price')),
209
- }));
210
- const extrasCost = extras.reduce((total, extra) => total + (extra.price * 1), 0); // Default quantity for add-ons set to 1
211
- const totalCost = (price * quantity) + extrasCost;
212
- // Add the item to the cart with its specific add-ons
213
- cart.push({ name, price, quantity, extras, instructions, totalCost });
214
- totalCartCost += totalCost; // Update the total cost of the cart
215
- updateCartButton();
216
- updateCartTotalCost(); // Update total cost displayed
217
- closeModal();
218
- }
219
- function updateCartButton() {
220
- const cartButton = document.getElementById('cart-button');
221
- cartButton.innerText = `View Cart (${cart.length} items)`;
222
- }
223
- function openCartModal() {
224
- const cartModal = document.getElementById('cart-modal');
225
- const cartItemsContainer = document.getElementById('cart-items');
226
- cartItemsContainer.innerHTML = "";
227
- cart.forEach((item, index) => {
228
- const extrasList = item.extras.map(extra => `${extra.name} (+$${extra.price})`).join(', ');
229
- cartItemsContainer.innerHTML += `
230
- <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px;">
231
- <h3>${item.name}</h3>
232
- <p>Quantity: <input type="number" value="${item.quantity}" min="1" style="width: 50px;" onchange="updateCartItem(${index}, 'item', this.value)" /></p>
233
- <p>Extras: ${extrasList || 'None'}</p>
234
- <p>Special Instructions: ${item.instructions || 'None'}</p>
235
- <p>Total Cost: $<span id="item-${index}-total">${item.totalCost.toFixed(2)}</span></p>
236
- <button onclick="removeFromCart(${index})" style="color: red;">Remove</button>
237
- </div>
238
- `;
239
- });
240
- cartModal.style.display = 'block';
241
- }
242
- function closeCartModal() {
243
- document.getElementById('cart-modal').style.display = 'none';
244
- }
245
- function removeFromCart(index) {
246
- totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost
247
- cart.splice(index, 1);
248
- updateCartButton();
249
- updateCartTotalCost(); // Update total cost displayed
250
- openCartModal();
251
- }
252
- function updateCartItem(index, type, value) {
253
- if (type === 'item') {
254
- cart[index].quantity = parseInt(value);
255
- }
256
- const item = cart[index];
257
- const price = item.price;
258
- const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * 1), 0);
259
- item.totalCost = (price * item.quantity) + extrasCost;
260
- document.getElementById(`item-${index}-total`).innerText = item.totalCost.toFixed(2);
261
- updateCartTotalCost(); // Update total cost displayed
262
- }
263
- function updateCartTotalCost() {
264
- const totalCostElement = document.getElementById('cart-total-cost');
265
- totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0);
266
- totalCostElement.innerText = `Total Cart Cost: $${totalCartCost.toFixed(2)}`;
267
- }
268
- function proceedToCheckout() {
269
- // Save the cart to Salesforce when the user checks out
270
- save_cart_to_salesforce(cart);
271
- alert("Proceeding to checkout...");
272
- }
273
- // Reset all selected add-ons when opening a new item modal
274
- function resetAddOns() {
275
- const checkboxes = document.querySelectorAll('input[name="biryani-extra"]');
276
- checkboxes.forEach(checkbox => checkbox.checked = false); // Uncheck all add-ons by default
277
- }
278
- </script>
279
- """
280
- return modal_script
281
 
282
  # Gradio App
283
  with gr.Blocks() as app:
@@ -306,16 +156,24 @@ with gr.Blocks() as app:
306
  with gr.Column():
307
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
308
  menu_output = gr.HTML()
309
- 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>")
310
- gr.HTML("<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;'>&times;</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><button style='background: #ff5722; color: white; padding: 10px 20px; border-radius: 5px; border: none; cursor: pointer;' onclick='proceedToCheckout()'>Proceed to Checkout</button></div></div>")
311
- gr.HTML(create_modal_window())
312
- gr.HTML(modal_js())
313
 
314
  login_button.click(
315
- lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
316
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
317
  [login_email, login_password], [login_page, menu_page, menu_output, login_output]
318
  )
319
- preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
320
 
321
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
55
  except Exception as e:
56
  return f"Error during login: {str(e)}", None
57
 
58
+ # Function to fetch menu items from Salesforce
59
  def load_menu_from_salesforce():
60
  try:
61
+ query = "SELECT Name, Price__c, Description__c, Image1__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 fetch add-ons from Salesforce
68
  def load_add_ons_from_salesforce():
69
  try:
70
  query = "SELECT Name, Price__c FROM Add_Ons__c"
 
73
  except Exception as e:
74
  return []
75
 
76
+ # Function to save cart data to Salesforce
77
+ def save_cart_to_salesforce(email, name, cart_items, total_bill):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  try:
79
+ # Create the parent Cart__c record
80
+ parent_cart = sf.Cart__c.create({
81
+ 'Customer_Email__c': email,
82
+ 'Customer_Name__c': name,
83
+ 'Total_Bill__c': total_bill
84
+ })
85
+ parent_cart_id = parent_cart['id'] # Retrieve the ID of the created Cart__c record
86
+
87
+ # Create child Cart_Item__c records for each item in the cart
88
+ for item in cart_items:
89
+ sf.Cart_Item__c.create({
90
+ 'Cart__c': parent_cart_id, # Associate the child with the parent
91
+ 'Item_Name__c': item['name'],
92
+ 'Quantity__c': item['quantity'],
93
+ 'Price__c': item['price'],
94
+ 'Total_Price__c': item['totalCost']
95
+ })
96
+
97
+ return "Order placed successfully!"
 
98
  except Exception as e:
99
+ return f"Error saving order to Salesforce: {str(e)}"
100
 
101
+ # Process cart checkout
102
+ def process_checkout(email, name, cart):
103
+ total_bill = sum(item['totalCost'] for item in cart) # Calculate the total bill
104
+ return save_cart_to_salesforce(email, name, cart, total_bill)
 
 
 
 
 
 
 
 
105
 
106
+ # Generate the menu HTML
107
+ def generate_menu_html(preference):
108
+ menu_data = load_menu_from_salesforce()
109
+ add_ons_data = load_add_ons_from_salesforce()
110
+
111
+ filtered_menu = [item for item in menu_data if preference in ['All', item['Veg_NonVeg__c']]]
112
+ html = "<div>"
113
+
114
+ # Menu Items
115
+ for item in filtered_menu:
116
+ html += f"""
117
+ <div style="border: 1px solid #ddd; padding: 10px; margin: 10px;">
118
+ <h3>{item['Name']}</h3>
119
+ <p>Price: ${item['Price__c']}</p>
120
+ <p>Description: {item['Description__c']}</p>
121
  </div>
122
+ """
 
 
 
 
 
 
123
 
124
+ # Add-ons
125
+ html += "<h4>Add-ons:</h4><ul>"
126
+ for add_on in add_ons_data:
127
+ html += f"<li>{add_on['Name']} - ${add_on['Price__c']}</li>"
128
+ html += "</ul></div>"
129
+
130
+ return html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  # Gradio App
133
  with gr.Blocks() as app:
 
156
  with gr.Column():
157
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
158
  menu_output = gr.HTML()
159
+ checkout_button = gr.Button("Proceed to Checkout")
160
+ checkout_output = gr.Textbox(label="Checkout Status")
 
 
161
 
162
  login_button.click(
163
+ lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_menu_html("All")), "Login successful!")
164
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
165
  [login_email, login_password], [login_page, menu_page, menu_output, login_output]
166
  )
 
167
 
168
+ preference.change(lambda pref: generate_menu_html(pref), [preference], menu_output)
169
+
170
+ checkout_button.click(
171
+ lambda: process_checkout(login_email.value, "John Doe", [
172
+ {"name": "Biryani", "quantity": 2, "price": 10, "totalCost": 20},
173
+ {"name": "Naan", "quantity": 1, "price": 5, "totalCost": 5}
174
+ ]),
175
+ inputs=[],
176
+ outputs=checkout_output
177
+ )
178
+
179
+ app.launch()