geethareddy commited on
Commit
498578c
·
verified ·
1 Parent(s): 1ddd591

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -231
app.py CHANGED
@@ -1,10 +1,25 @@
1
- import bcrypt
2
  import gradio as gr
 
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
9
  def hash_password(password):
10
  return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
@@ -13,7 +28,46 @@ 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()
@@ -35,7 +89,6 @@ def signup(name, email, phone, password):
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()
@@ -55,229 +108,6 @@ 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
-
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:
@@ -308,14 +138,15 @@ with gr.Blocks() as app:
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()
 
 
1
  import gradio as gr
2
+ import bcrypt
3
  from simple_salesforce import Salesforce
4
+ from datetime import datetime
5
+ import openai # if using Hugging Face-based model (replace with your Hugging Face API call logic)
6
 
7
  # Salesforce Connection
8
  sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
9
 
10
+ # Hugging Face API Integration (example with GPT for generating offers)
11
+ openai.api_key = "your-huggingface-api-key" # Replace with your Hugging Face API key
12
+
13
+ def generate_offer(customer_name):
14
+ # Example: Use Hugging Face to generate an offer for the customer
15
+ prompt = f"Generate a personalized offer for {customer_name} for their meal order."
16
+ response = openai.Completion.create(
17
+ engine="text-davinci-003", # Using GPT-3 for the example, replace with Hugging Face model if needed
18
+ prompt=prompt,
19
+ max_tokens=50
20
+ )
21
+ return response.choices[0].text.strip()
22
+
23
  # Function to Hash Password
24
  def hash_password(password):
25
  return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
 
28
  def verify_password(plain_password, hashed_password):
29
  return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
30
 
31
+ # Function to handle order and store it in Salesforce
32
+ def save_order_to_salesforce(order_details):
33
+ try:
34
+ # Use Hugging Face or any other service to generate offers or any AI processing
35
+ offer = generate_offer(order_details['Customer_Name__c'])
36
+
37
+ # Creating order data to save in Salesforce
38
+ order_data = {
39
+ 'AccountId__c': order_details['AccountId__c'],
40
+ 'Add_Ons__c': order_details['Add_Ons__c'],
41
+ 'Customer_Email__c': order_details['Customer_Email__c'],
42
+ 'Customer_Name__c': order_details['Customer_Name__c'],
43
+ 'Email__c': order_details['Email__c'],
44
+ 'Instructions__c': order_details['Instructions__c'],
45
+ 'Item_Name__c': order_details['Item_Name__c'],
46
+ 'Name2__c': order_details['Name2__c'],
47
+ 'Offers_Applied__c': offer, # Applying generated offer
48
+ 'Order_Date_Time__c': datetime.now().isoformat(), # Current timestamp
49
+ 'Order_Item__c': order_details['Order_Item__c'],
50
+ 'Order_Status__c': "Pending", # Initial order status
51
+ 'Order_Date__c': datetime.now().isoformat(), # Current timestamp
52
+ 'OrderNumber__c': f"ORD{int(datetime.timestamp(datetime.now()))}", # Generate order number
53
+ 'Price__c': order_details['Price__c'],
54
+ 'Quantity__c': order_details['Quantity__c'],
55
+ 'Reward_Points__c': order_details['Reward_Points__c'],
56
+ 'Special_Instructions__c': order_details['Special_Instructions__c'],
57
+ 'Status__c': "Confirmed", # Order status
58
+ 'Total_Amount__c': order_details['Total_Amount__c'],
59
+ 'Total_Cost__c': order_details['Total_Cost__c']
60
+ }
61
+
62
+ # Create the order in Salesforce
63
+ sf.Order__c.create(order_data)
64
+
65
+ return "Order successfully saved to Salesforce!"
66
+ except Exception as e:
67
+ return f"Error while saving order to Salesforce: {str(e)}"
68
+
69
+
70
+ # Signup and Login Functions
71
  def signup(name, email, phone, password):
72
  try:
73
  email = email.strip()
 
89
  except Exception as e:
90
  return f"Error during signup: {str(e)}"
91
 
 
92
  def login(email, password):
93
  try:
94
  email = email.strip()
 
108
  except Exception as e:
109
  return f"Error during login: {str(e)}", None
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  # Gradio App
113
  with gr.Blocks() as app:
 
138
  menu_output = gr.HTML()
139
  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>")
140
  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>")
141
+ gr.HTML("<div id='modal'></div>") # Add modal here to show details of selected item
142
+ gr.HTML("<script>function openModal(name, image, description, price) {document.getElementById('modal').innerHTML = `<h2>${name}</h2><p>${description}</p><p>${price}</p><img src='${image}' />`;}</script>")
143
 
144
  login_button.click(
145
+ lambda email, password: (gr.update(visible=False), gr.update(visible=True), gr.update(value="Menu loaded"), "Login successful!")
146
  if login(email, password)[0] == "Login successful!" else (gr.update(), gr.update(), gr.update(), "Invalid email or password."),
147
+ [login_email, login_password], [login_page, menu_page, login_output]
148
  )
149
+ submit_signup.click(signup, [signup_name, signup_email, signup_phone, signup_password], signup_output)
150
  preference.change(lambda pref: filter_menu(pref), [preference], menu_output)
151
 
152
+ app.launch()