dschandra commited on
Commit
77b50a3
·
verified ·
1 Parent(s): ec96e6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -128
app.py CHANGED
@@ -4,149 +4,84 @@ from simple_salesforce import Salesforce
4
  # Salesforce Connection
5
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
6
 
7
- # Cart to store items
8
- cart = []
9
-
10
- # Function to fetch menu items
11
- def fetch_menu_from_salesforce():
12
- query = "SELECT Id, Name, Price__c, Description__c, Image1__c, Section__c, Veg_NonVeg__c FROM Menu_Item__c"
13
- menu_items = sf.query(query)
14
- return menu_items["records"]
15
-
16
- # Function to fetch add-ons
17
- def fetch_add_ons_from_salesforce():
18
- query = "SELECT Id, Name, Price__c, Menu_Item__c FROM Add_Ons__c WHERE Available_In_Menu__c = true"
19
- add_ons = sf.query(query)
20
- return add_ons["records"]
21
-
22
- # Function to generate menu HTML
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def generate_menu_html(menu_items):
24
- html = "<div style='display: flex; flex-wrap: wrap;'>"
25
  for item in menu_items:
26
  html += f"""
27
- <div style="border: 1px solid #ddd; padding: 10px; margin: 10px; width: 300px; border-radius: 8px; text-align: center;">
28
- <img src="{item.get('Image1__c')}" alt="{item.get('Name')}" style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px;">
29
- <h3>{item.get('Name')}</h3>
30
- <p>{item.get('Description__c')}</p>
31
- <p style="font-weight: bold;">${item.get('Price__c')}</p>
32
- <button onclick="openPopup('{item.get('Id')}', '{item.get('Name')}', {item.get('Price__c')})">Customize & Add</button>
 
 
 
33
  </div>
34
  """
35
- html += "</div>"
36
  return html
37
 
38
- # Function to save order in Salesforce
39
- def save_order_in_salesforce(cart_data, total_cost):
40
- try:
41
- if not cart_data:
42
- return "Cart is empty!"
43
-
44
- # Save Order
45
- order = {
46
- "Name": f"Order-{datetime.now().strftime('%Y%m%d%H%M%S')}",
47
- "Total_Amount__c": total_cost,
48
- "Order_Date__c": datetime.now().isoformat(),
49
- }
50
- order_result = sf.Order__c.create(order)
51
- order_id = order_result["id"]
52
-
53
- # Save Order Items
54
- for item in cart_data:
55
- order_item = {
56
- "Order__c": order_id,
57
- "Menu_Item__c": item["menu_item_id"],
58
- "Quantity__c": item["quantity"],
59
- "Price__c": item["price"],
60
- "Total_Price__c": item["total_price"],
61
- "Add_Ons__c": ", ".join(addon["name"] for addon in item["add_ons"]),
62
- "Special_Instructions__c": item["instructions"],
63
- }
64
- sf.Order_Item__c.create(order_item)
65
-
66
- return "Order placed successfully!"
67
- except Exception as e:
68
- return f"Error saving order: {str(e)}"
69
-
70
- # JS for Popup
71
- popup_script = """
72
- <script>
73
- function openPopup(id, name, price) {
74
- document.getElementById('popup-name').innerText = name;
75
- document.getElementById('popup-price').innerText = `$${price}`;
76
- document.getElementById('popup').style.display = 'block';
77
- document.getElementById('popup').setAttribute('data-id', id);
78
- }
79
-
80
- function closePopup() {
81
- document.getElementById('popup').style.display = 'none';
82
- }
83
-
84
- function addToCart() {
85
- const id = document.getElementById('popup').getAttribute('data-id');
86
- const name = document.getElementById('popup-name').innerText;
87
- const price = parseFloat(document.getElementById('popup-price').innerText.replace('$', ''));
88
- const quantity = parseInt(document.getElementById('popup-quantity').value);
89
- const instructions = document.getElementById('popup-instructions').value;
90
- const addOns = Array.from(document.querySelectorAll('input[name="addon"]:checked')).map(addon => ({
91
- name: addon.getAttribute('data-name'),
92
- price: parseFloat(addon.getAttribute('data-price')),
93
- }));
94
-
95
- const totalPrice = price * quantity + addOns.reduce((acc, addon) => acc + addon.price, 0);
96
- cart.push({ menu_item_id: id, name, price, quantity, add_ons: addOns, instructions, total_price: totalPrice });
97
- closePopup();
98
- alert(`${name} added to cart!`);
99
- }
100
- </script>
101
- """
102
-
103
  # Gradio App
104
  with gr.Blocks() as app:
105
- menu_items = fetch_menu_from_salesforce()
106
- add_ons = fetch_add_ons_from_salesforce()
107
 
108
  with gr.Row():
109
  gr.HTML("<h1>Welcome to Biryani Hub</h1>")
110
 
111
  with gr.Row():
112
- cart_view = gr.Textbox(label="Cart Items", interactive=False)
113
- total_cost_view = gr.Textbox(label="Total Cost", interactive=False)
114
-
115
- with gr.Row():
116
- menu_output = gr.HTML(generate_menu_html(menu_items))
117
 
 
118
  with gr.Row():
119
- submit_order = gr.Button("Proceed to Order")
120
- order_status = gr.Textbox(label="Order Status", interactive=False)
121
-
122
- submit_order.click(
123
- lambda: save_order_in_salesforce(cart, sum(item["total_price"] for item in cart)),
124
- inputs=[],
125
- outputs=order_status,
126
- )
127
-
128
- gr.HTML("""
129
- <div id="popup" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 400px; height: 600px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
130
- <h3 id="popup-name"></h3>
131
- <p id="popup-price"></p>
132
- <label>Quantity:</label>
133
- <input type="number" id="popup-quantity" value="1" min="1">
134
- <label>Special Instructions:</label>
135
- <textarea id="popup-instructions" rows="3"></textarea>
136
- <label>Add-Ons:</label>
137
- <div>
138
- """ +
139
- "".join(
140
- f'<input type="checkbox" name="addon" data-name="{addon["Name"]}" data-price="{addon["Price__c"]}"> {addon["Name"]} (+${addon["Price__c"]})<br>'
141
- for addon in add_ons
142
- ) +
143
- """
144
- </div>
145
- <button onclick="addToCart()">Add to Cart</button>
146
- <button onclick="closePopup()">Close</button>
147
- </div>
148
- """)
149
-
150
- gr.HTML(popup_script)
151
 
152
  app.launch()
 
4
  # Salesforce Connection
5
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
6
 
7
+ # Sample menu items from Salesforce
8
+ def fetch_menu_items():
9
+ try:
10
+ query = "SELECT Id, Name, Price__c, Image1__c, Description__c, Section__c FROM Menu_Item__c"
11
+ menu_items = sf.query(query)['records']
12
+ return menu_items
13
+ except Exception as e:
14
+ print(f"Error fetching menu items: {e}")
15
+ return []
16
+
17
+ # Cart management
18
+ cart = {}
19
+
20
+ def update_cart(item_id, name, price, quantity):
21
+ if item_id in cart:
22
+ cart[item_id]['quantity'] += quantity
23
+ if cart[item_id]['quantity'] <= 0:
24
+ del cart[item_id]
25
+ else:
26
+ if quantity > 0:
27
+ cart[item_id] = {'name': name, 'price': price, 'quantity': quantity}
28
+ return cart_summary()
29
+
30
+ def cart_summary():
31
+ total_items = sum(item['quantity'] for item in cart.values())
32
+ total_cost = sum(item['quantity'] * item['price'] for item in cart.values())
33
+ return f"{total_items} items | Total: ₹{total_cost:.2f}"
34
+
35
+ # Cart Page
36
+ def cart_page():
37
+ items_html = "".join(
38
+ f"""
39
+ <div>
40
+ <h4>{item['name']} (₹{item['price']})</h4>
41
+ <p>Quantity: {item['quantity']}</p>
42
+ </div>
43
+ """
44
+ for item in cart.values()
45
+ )
46
+ total_cost = sum(item['quantity'] * item['price'] for item in cart.values())
47
+ return f"""
48
+ <h3>Your Cart</h3>
49
+ <div>{items_html}</div>
50
+ <h4>Total Cost: ₹{total_cost:.2f}</h4>
51
+ <button onclick="alert('Checkout functionality to be implemented')">Proceed to Checkout</button>
52
+ """
53
+
54
+ # Generate HTML for Menu Items
55
  def generate_menu_html(menu_items):
56
+ html = ""
57
  for item in menu_items:
58
  html += f"""
59
+ <div style="border: 1px solid #ddd; padding: 10px; margin: 10px; border-radius: 8px; display: flex; align-items: center;">
60
+ <img src="{item['Image1__c']}" alt="{item['Name']}" style="width: 100px; height: 100px; margin-right: 10px;">
61
+ <div>
62
+ <h4>{item['Name']}</h4>
63
+ <p>₹{item['Price__c']}</p>
64
+ <button onclick="updateCart('{item['Id']}', '{item['Name']}', {item['Price__c']}, -1)">-</button>
65
+ <span>0</span>
66
+ <button onclick="updateCart('{item['Id']}', '{item['Name']}', {item['Price__c']}, 1)">+</button>
67
+ </div>
68
  </div>
69
  """
 
70
  return html
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # Gradio App
73
  with gr.Blocks() as app:
74
+ menu_items = fetch_menu_items()
 
75
 
76
  with gr.Row():
77
  gr.HTML("<h1>Welcome to Biryani Hub</h1>")
78
 
79
  with gr.Row():
80
+ gr.HTML(generate_menu_html(menu_items))
 
 
 
 
81
 
82
+ # Floating Cart Button
83
  with gr.Row():
84
+ cart_display = gr.HTML("0 items | Total: ₹0.00", elem_id="cart-summary")
85
+ gr.Button("View Cart", elem_id="view-cart-btn").click(cart_page, [], cart_display)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  app.launch()