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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -68
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 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,61 +73,212 @@ def load_add_ons_from_salesforce():
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,24 +307,16 @@ 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()
 
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
  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
+ # 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
+ <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;">
147
+ <div style="padding: 20px;">
148
+ <div style="text-align: right;">
149
+ <button onclick="closeCartModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
150
+ </div>
151
+ <h1>Your Cart</h1>
152
+ <div id="cart-items"></div>
153
+ <p id="cart-total-cost" style="font-size: 1.2em; font-weight: bold;">Total Cart Cost: $0.00</p>
154
+ <div id="order-summary" style="margin-top: 20px;">
155
+ <h2>Final Order Summary:</h2>
156
+ <div id="final-order-summary"></div>
157
+ <p><strong>Total Bill: $<span id="total-bill"></span></strong></p>
158
+ </div>
159
+ <button style="background: #ff5722; color: white; padding: 10px 20px; border-radius: 5px; border: none; cursor: pointer;" onclick="proceedToCheckout()">Proceed to Checkout</button>
160
+ </div>
161
+ </div>
162
+ """
163
+ return modal_html
164
 
165
+ # JavaScript for Modal and Cart
166
+ def modal_js():
167
+ modal_script = """
168
+ <script>
169
+ let cart = [];
170
+ let totalCartCost = 0;
171
+ function openModal(name, image2, description, price) {
172
+ const modal = document.getElementById('modal');
173
+ modal.style.display = 'block';
174
+ modal.style.position = 'fixed';
175
+ modal.style.width = window.innerWidth <= 768 ? '90%' : '30%';
176
+ modal.style.top = ${event.clientY}px;
177
+ modal.style.left = '50%';
178
+ modal.style.transform = 'translate(-50%, -50%)';
179
+ document.getElementById('modal-image').src = image2;
180
+ document.getElementById('modal-name').innerText = name;
181
+ document.getElementById('modal-description').innerText = description;
182
+ document.getElementById('modal-price').innerText = price;
183
+ document.getElementById('quantity').value = 1;
184
+ document.getElementById('special-instructions').value = '';
185
+ resetAddOns(); // Reset add-ons when opening the modal
186
+ }
187
+ function closeModal() {
188
+ document.getElementById('modal').style.display = 'none';
189
+ }
190
+ function addToCart() {
191
+ const name = document.getElementById('modal-name').innerText;
192
+ const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
193
+ const quantity = parseInt(document.getElementById('quantity').value) || 1;
194
+ const instructions = document.getElementById('special-instructions').value;
195
+ const selectedAddOns = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked'));
196
+ const extras = selectedAddOns.map(extra => ({
197
+ name: extra.value,
198
+ price: parseFloat(extra.getAttribute('data-price')),
199
+ quantity: 1 // Default quantity for add-ons is 1
200
+ }));
201
+ const extrasCost = extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
202
+ const totalCost = (price * quantity) + extrasCost;
203
+ // Add the item to the cart with its specific add-ons
204
+ cart.push({ name, price, quantity, extras, instructions, totalCost });
205
+ totalCartCost += totalCost; // Update the total cost of the cart
206
+ updateCartButton();
207
+ updateCartTotalCost(); // Update total cost displayed
208
+ closeModal();
209
+ }
210
+ function updateCartButton() {
211
+ const cartButton = document.getElementById('cart-button');
212
+ cartButton.innerText = View Cart (${cart.length} items);
213
+ }
214
+ function openCartModal() {
215
+ const cartModal = document.getElementById('cart-modal');
216
+ const cartItemsContainer = document.getElementById('cart-items');
217
+ cartItemsContainer.innerHTML = "";
218
+ cart.forEach((item, index) => {
219
+ 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(', ');
220
+ cartItemsContainer.innerHTML +=
221
+ <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px;">
222
+ <h3>${item.name}</h3>
223
+ <p>Quantity: <input type="number" value="${item.quantity}" min="1" style="width: 50px;" onchange="updateCartItem(${index}, 'item', this.value)" /></p>
224
+ <p>Extras: ${extrasList || 'None'}</p>
225
+ <p>Special Instructions: ${item.instructions || 'None'}</p>
226
+ <p>Total Cost: $<span id="item-${index}-total">${item.totalCost.toFixed(2)}</span></p>
227
+ <button onclick="removeFromCart(${index})" style="color: red;">Remove</button>
228
+ </div>
229
+ ;
230
+ });
231
+ cartModal.style.display = 'block';
232
+ }
233
+ function closeCartModal() {
234
+ document.getElementById('cart-modal').style.display = 'none';
235
+ }
236
+ function removeFromCart(index) {
237
+ totalCartCost -= cart[index].totalCost; // Deduct the cost of the removed item from total cost
238
+ cart.splice(index, 1);
239
+ updateCartButton();
240
+ updateCartTotalCost(); // Update total cost displayed
241
+ openCartModal();
242
+ }
243
+ function updateCartItem(index, type, value) {
244
+ if (type === 'item') {
245
+ cart[index].quantity = parseInt(value);
246
+ } else if (type === 'extra') {
247
+ cart[index].extras[0].quantity = parseInt(value); // Assuming one add-on for simplicity
248
+ }
249
+ const item = cart[index];
250
+ const price = item.price;
251
+ const extrasCost = item.extras.reduce((total, extra) => total + (extra.price * extra.quantity), 0);
252
+ item.totalCost = (price * item.quantity) + extrasCost;
253
+ document.getElementById(item-${index}-total).innerText = item.totalCost.toFixed(2);
254
+ updateCartTotalCost(); // Update total cost displayed
255
+ }
256
+ function updateCartTotalCost() {
257
+ const totalCostElement = document.getElementById('cart-total-cost');
258
+ totalCartCost = cart.reduce((total, item) => total + item.totalCost, 0);
259
+ totalCostElement.innerText = Total Cart Cost: $${totalCartCost.toFixed(2)};
260
+ }
261
+ function proceedToCheckout() {
262
+ // Build the cart summary string with item details
263
+ const cartSummary = cart.map(item =>
264
+ ${item.name} (x${item.quantity}) - $${item.totalCost.toFixed(2)}
265
+ Extras: ${item.extras.map(extra => extra.name).join(', ') || 'None'}
266
+ Instructions: ${item.instructions || 'None'}
267
+ ).join('<br>');
268
+ // Insert the summary into the modal
269
+ document.getElementById('final-order-summary').innerHTML = cartSummary;
270
+ document.getElementById('total-bill').innerText = totalCartCost.toFixed(2);
271
+ // Show the cart modal with the summary
272
+ openCartModal();
273
+ }
274
+ // Reset all selected add-ons when opening a new item modal
275
+ function resetAddOns() {
276
+ const checkboxes = document.querySelectorAll('input[name="biryani-extra"]');
277
+ checkboxes.forEach(checkbox => checkbox.checked = false); // Uncheck all add-ons
278
+ }
279
+ </script>
280
+ """
281
+ return modal_script
282
 
283
  # Gradio App
284
  with gr.Blocks() as app:
 
307
  with gr.Column():
308
  preference = gr.Radio(choices=["All", "Veg", "Non-Veg"], label="Filter Preference", value="All")
309
  menu_output = gr.HTML()
310
+ 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>")
311
+ 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><div id='order-summary'><h2>Final Order Summary:</h2><div id='final-order-summary'></div><p><strong>Total Bill: $<span id='total-bill'></span></strong></p></div><button style='background: #ff5722; color: white; padding: 10px 20px; border-radius: 5px; border: none; cursor: pointer;' onclick='proceedToCheckout()'>Proceed to Checkout</button></div></div>")
312
+ gr.HTML(create_modal_window())
313
+ gr.HTML(modal_js())
314
 
315
  login_button.click(
316
+ lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value=filter_menu("All")), "Login successful!")
317
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
318
  [login_email, login_password], [login_page, menu_page, menu_output, login_output]
319
  )
320
+ preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
321
 
322
+ app.launch()