DSatishchandra commited on
Commit
a7abf85
·
verified ·
1 Parent(s): 143dfbd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -117
app.py CHANGED
@@ -1,124 +1,267 @@
1
- import gradio as gr
2
- from models.salesforce import fetch_menu_items, place_order_in_salesforce
3
- from models.cart import add_to_cart, view_cart, clear_cart
4
- from models.user import login_user, signup_user
5
-
6
- # Global user state
7
- current_user = {"email": None, "name": None}
8
-
9
- # Login Interface
10
- def login(email, password):
11
- success, message = login_user(email, password)
12
- if success:
13
- current_user["email"] = email
14
- current_user["name"] = message
15
- return "Login successful! Redirecting to menu..."
16
- return f"Login failed: {message}"
17
-
18
- # Signup Interface
19
- def signup(name, email, phone, password):
20
- success, message = signup_user(name, email, phone, password)
21
- if success:
22
- return "Signup successful! Please login now."
23
- return f"Signup failed: {message}"
24
-
25
- # Load Menu Items
26
- def load_menu(preference):
27
- items = fetch_menu_items()
28
- print(f"Fetched menu items: {items}") # Debugging output
29
- filtered_items = [
30
- item for item in items
31
- if preference == "All"
32
- or (preference == "Veg" and item["Veg_NonVeg__c"] == "Veg")
33
- or (preference == "Non-Veg" and item["Veg_NonVeg__c"] == "Non-Veg")
34
- ]
35
- print(f"Filtered menu items: {filtered_items}") # Debugging output
36
- return filtered_items
37
-
38
- def display_menu(preference):
39
- menu_items = fetch_menu_items()
40
- # Filter based on preference
41
- if preference == "Veg":
42
- filtered_items = [item for item in menu_items if item["Veg_NonVeg"] == "Veg"]
43
- elif preference == "Non-Veg":
44
- filtered_items = [item for item in menu_items if item["Veg_NonVeg"] == "Non veg"]
45
- else:
46
- filtered_items = menu_items
47
-
48
- # Prepare for display in Gradio
49
- return [[item["Name"], item["Price"], item["Description"]] for item in filtered_items]
50
 
51
-
 
 
 
 
 
52
 
53
- # Add to Cart
54
- def add_to_cart_interface(item_name, price):
55
- add_to_cart(item_name, price)
56
- return f"Added {item_name} to cart!"
57
 
58
- # View Cart
59
- def view_cart_interface():
60
- cart, total = view_cart()
61
- return cart, total
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Place Order
64
- def place_order_interface():
65
- email = current_user["email"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  if not email:
67
- return "Error: Please login to place an order."
68
- cart, total = view_cart()
69
- if not cart:
70
- return "Error: Cart is empty!"
71
- order_details = "\n".join([f"{item['Name']} - ${item['Price']} x {item['Quantity']}" for item in cart])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  try:
73
- place_order_in_salesforce(email, order_details, total)
74
- clear_cart()
75
- return f"Order placed successfully! Total: ${total}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  except Exception as e:
77
- return f"Error placing order: {str(e)}"
78
-
79
- # Gradio Interfaces
80
- with gr.Blocks() as app:
81
- preference_radio = gr.Radio(["All", "Veg", "Non-Veg"], label="Filter Menu", value="All")
82
- menu_data_table = gr.Dataframe(headers=["Name", "Price", "Description"], datatype=["str", "number", "str"])
83
-
84
- # Add a button to trigger menu display
85
- menu_button = gr.Button("Show Menu")
86
-
87
- # Connect display logic
88
- menu_button.click(
89
- display_menu, # Function to call
90
- inputs=preference_radio, # Input component
91
- outputs=menu_data_table # Output component
92
- )
93
-
94
-
95
- with gr.Tab("Signup"):
96
- name = gr.Textbox(label="Name", placeholder="Enter your name")
97
- signup_email = gr.Textbox(label="Email", placeholder="Enter your email")
98
- phone = gr.Textbox(label="Phone", placeholder="Enter your phone number")
99
- signup_password = gr.Textbox(label="Password", type="password", placeholder="Create a password")
100
- signup_button = gr.Button("Signup")
101
- signup_output = gr.Textbox(label="Signup Status")
102
- signup_button.click(signup, inputs=[name, signup_email, phone, signup_password], outputs=signup_output)
103
-
104
- with gr.Tab("Menu"):
105
- preference = gr.Radio(["All", "Veg", "Non-Veg"], label="Filter Menu", value="All")
106
- menu_output = gr.Dataframe(headers=["Name", "Description", "Price"])
107
- preference.change(lambda p: load_menu(p), inputs=[preference], outputs=menu_output)
108
- item_name = gr.Textbox(label="Item Name")
109
- item_price = gr.Textbox(label="Price")
110
- add_button = gr.Button("Add to Cart")
111
- cart_status = gr.Textbox(label="Cart Status")
112
- add_button.click(add_to_cart_interface, inputs=[item_name, item_price], outputs=cart_status)
113
-
114
- with gr.Tab("Cart"):
115
- view_button = gr.Button("View Cart")
116
- cart_output = gr.Dataframe(headers=["Name", "Price", "Quantity"])
117
- total_output = gr.Textbox(label="Total Amount")
118
- view_button.click(view_cart_interface, outputs=[cart_output, total_output])
119
-
120
- place_order_button = gr.Button("Place Order")
121
- order_status = gr.Textbox(label="Order Status")
122
- place_order_button.click(place_order_interface, outputs=order_status)
123
-
124
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify, redirect, url_for, session
2
+ import random
3
+ from salesforce import get_salesforce_connection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Initialize Flask app and Salesforce connection
6
+ app = Flask(__name__)
7
+ sf = get_salesforce_connection()
8
+
9
+ # Set the secret key to handle sessions securely
10
+ app.secret_key = 'sSSjyhInIsUohKpG8sHzty2q' # Replace with a secure key
11
 
12
+ @app.route("/")
13
+ def home():
14
+ return render_template("index.html")
 
15
 
16
+ @app.route("/signup", methods=["GET", "POST"])
17
+ def signup():
18
+ if request.method == "POST":
19
+ name = request.form.get("name")
20
+ phone = request.form.get("phone")
21
+ email = request.form.get("email")
22
+ password = request.form.get("password")
23
+ try:
24
+ sf.Customer_Login__c.create({
25
+ "Name": name,
26
+ "Phone_Number__c": phone,
27
+ "Email__c": email,
28
+ "Password__c": password
29
+ })
30
+ return redirect(url_for("login"))
31
+ except Exception as e:
32
+ return render_template("signup.html", error=f"Error: {str(e)}")
33
+ return render_template("signup.html")
34
 
35
+ @app.route("/login", methods=["GET", "POST"])
36
+ def login():
37
+ if request.method == "POST":
38
+ email = request.form.get("email")
39
+ password = request.form.get("password")
40
+ try:
41
+ query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
42
+ result = sf.query(query)
43
+ if result["records"]:
44
+ session['user_id'] = result["records"][0]['Id']
45
+ session['user_email'] = email
46
+ return redirect(url_for("menu"))
47
+ else:
48
+ return render_template("login.html", error="Invalid credentials!")
49
+ except Exception as e:
50
+ return render_template("login.html", error=f"Error: {str(e)}")
51
+ return render_template("login.html")
52
+
53
+ @app.route("/menu", methods=["GET", "POST"])
54
+ def menu():
55
+ selected_category = request.args.get("category", "All")
56
+ user_id = session.get('user_id')
57
+ if not user_id:
58
+ return redirect(url_for('login'))
59
+ try:
60
+ query = "SELECT Name, Price__c, Image1__c, Category__c, Description__c FROM Menu_Item__c"
61
+ result = sf.query(query)
62
+ food_items = result['records'] if 'records' in result else []
63
+ categories = {item['Category__c'] for item in food_items if 'Category__c' in item}
64
+ if selected_category != "All":
65
+ food_items = [item for item in food_items if item.get("Category__c") == selected_category]
66
+ except Exception as e:
67
+ food_items = []
68
+ categories = []
69
+ print(f"Error fetching data: {e}")
70
+ return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
71
+
72
+ @app.route("/cart", methods=["GET"])
73
+ def cart():
74
+ email = session.get('user_email') # Get logged-in user's email
75
  if not email:
76
+ return redirect(url_for("login")) # Redirect to login if not logged in
77
+ try:
78
+ result = sf.query(f"""
79
+ SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
80
+ FROM Cart_Item__c
81
+ WHERE Customer_Email__c = '{email}'
82
+ """)
83
+ cart_items = result.get("records", [])
84
+ subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
85
+ except Exception as e:
86
+ print(f"Error fetching cart items: {e}")
87
+ cart_items = []
88
+ subtotal = 0
89
+
90
+ return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
91
+
92
+
93
+
94
+ @app.route('/cart/add', methods=['POST'])
95
+ def add_to_cart():
96
+ data = request.json
97
+ item_name = data.get('itemName').strip()
98
+ item_price = data.get('itemPrice')
99
+ item_image = data.get('itemImage')
100
+ addons = data.get('addons', [])
101
+ customer_email = session.get('user_email') # Get logged-in user's email from session
102
+
103
+ if not item_name or not item_price:
104
+ return jsonify({"success": False, "error": "Item name and price are required."})
105
+
106
  try:
107
+ # Check if the item already exists in the cart for this custpmer
108
+ query= f""" SELECT Id, Quantity__c FROM Cart_Item__c
109
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
110
+ """
111
+ result = sf.query(query)
112
+ if result['totalSize'] > 0:
113
+ # Update quantity if the item exists
114
+ cart_item = result['records'][0]
115
+ sf.Cart_Item__c.update(cart_item['Id'], {
116
+ "Quantity__c": cart_item['Quantity__c'] + 1
117
+ })
118
+ else:
119
+ # Add a new item if it doesn't exist
120
+ sf.Cart_Item__c.create({
121
+ "Name": item_name,
122
+ "Price__c": item_price,
123
+ "Quantity__c": 1,
124
+ "Add_Ons__c": ";".join(addons) if addons else None,
125
+ "Image1__c": item_image,
126
+ "Customer_Email__c": customer_email, # Associate with the logged-in user
127
+
128
+ })
129
+ return jsonify({"success": True, "message": "Item added/updated successfully."})
130
  except Exception as e:
131
+ return jsonify({"success": False, "error": str(e)})
132
+
133
+ @app.route("/cart/add_item", methods=["POST"])
134
+ def add_item_to_cart():
135
+ data = request.json # Extract JSON data from the request
136
+ email = data.get('email') # Customer email
137
+ item_name = data.get('item_name') # Item name
138
+ quantity = data.get('quantity', 0) # Quantity to add (default is 1) // default value is 1
139
+
140
+ try:
141
+ # Check if the item already exists in the cart for this customer
142
+ cart_items = sf.query(
143
+ f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Item_Name__c = '{item_name}'"
144
+ )['records']
145
+
146
+ if cart_items:
147
+ # If the item already exists, update its quantity
148
+ cart_item = cart_items[0]
149
+ new_quantity = cart_item['Quantity__c'] + quantity
150
+ sf.Cart_Item__c.update(cart_item['Id'], {"Quantity__c": new_quantity})
151
+ return jsonify({"success": True, "message": "Item quantity updated successfully."})
152
+ else:
153
+ # If the item does not exist, add it to the cart
154
+ sf.Cart_Item__c.create({
155
+ "Customer_Email__c": email,
156
+ "Item_Name__c": item_name,
157
+ "Quantity__c": quantity
158
+ })
159
+
160
+ return jsonify({"success": True, "message": "Item added/updated successfully."})
161
+ except Exception as e:
162
+ return jsonify({"success": False, "error": str(e)}), 500
163
+
164
+
165
+ @app.route('/cart/remove/<item_name>', methods=['POST'])
166
+ def remove_cart_item(item_name):
167
+ try:
168
+ customer_email = session.get('user_email')
169
+ if not customer_email:
170
+ return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
171
+ query = f"""
172
+ SELECT Id FROM Cart_Item__c
173
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
174
+ """
175
+ result = sf.query(query)
176
+ if result['totalSize'] == 0:
177
+ return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
178
+ cart_item_id = result['records'][0]['Id']
179
+ sf.Cart_Item__c.delete(cart_item_id)
180
+ return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
181
+ except Exception as e:
182
+ print(f"Error: {str(e)}")
183
+ return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
184
+
185
+ @app.route('/api/addons', methods=['GET'])
186
+ def get_addons():
187
+ item_name = request.args.get('item_name')
188
+ if not item_name:
189
+ return jsonify({"success": False, "error": "Item name is required."})
190
+
191
+ try:
192
+ query = f"SELECT Name, Price__c FROM Add_Ons__c WHERE Menu_Item__r.Name = '{item_name}'"
193
+ addons = sf.query(query)['records']
194
+ return jsonify({"success": True, "addons": addons})
195
+ except Exception as e:
196
+ print(f"Error fetching add-ons: {e}")
197
+ return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
198
+
199
+ @app.route("/cart/update_quantity", methods=["POST"])
200
+ def update_quantity():
201
+ data = request.json # Extract JSON data from the request
202
+ email = data.get('email') # Customer email
203
+ item_name = data.get('item_name') # Item name (Cart Item Name in Salesforce)
204
+ quantity = data.get('quantity') # New quantity
205
+
206
+ # Validate inputs
207
+ if not email or not item_name:
208
+ return jsonify({"success": False, "error": "Email and item name are required."}), 400
209
+
210
+ try:
211
+ # Query the cart item using the correct field names
212
+ cart_items = sf.query(
213
+ f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name__c = '{item_name}'"
214
+ )['records']
215
+
216
+ if not cart_items:
217
+ return jsonify({"success": False, "error": "Cart item not found."}), 404
218
+
219
+ # Get the first matching record ID
220
+ cart_item_id = cart_items[0]['Id']
221
+
222
+ # Update the quantity in Salesforce
223
+ sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity})
224
+
225
+ return jsonify({"success": True, "new_quantity": quantity})
226
+ except Exception as e:
227
+ return jsonify({"success": False, "error": str(e)}), 500
228
+
229
+
230
+
231
+ @app.route("/checkout", methods=["POST"])
232
+ def checkout():
233
+ email = session.get('user_email')
234
+ user_id = session.get('user_id')
235
+ if not email or not user_id:
236
+ return jsonify({"success": False, "message": "User not logged in"})
237
+ try:
238
+ result = sf.query(f"""
239
+ SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
240
+ FROM Cart_Item__c
241
+ WHERE Customer_Email__c = '{email}'
242
+ """)
243
+ cart_items = result["records"]
244
+ if not cart_items:
245
+ return jsonify({"success": False, "message": "Cart is empty"})
246
+ total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
247
+ order_data = {
248
+ "Customer_Name__c": user_id,
249
+ "Customer_Email__c": email,
250
+ "Total_Amount__c": total_price,
251
+ "Order_Status__c": "Pending",
252
+ "Order_Items__c": "\n".join(
253
+ [f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
254
+ ),
255
+ "Add_Ons__c": "\n".join(
256
+ [f"{item['Add_Ons__c']}" if item['Add_Ons__c'] else "None" for item in cart_items]
257
+ ),
258
+ }
259
+ sf.Order__c.create(order_data)
260
+ for item in cart_items:
261
+ sf.Cart_Item__c.delete(item["Id"])
262
+ return jsonify({"success": True, "message": "Order placed successfully!"})
263
+ except Exception as e:
264
+ return jsonify({"success": False, "error": str(e)})
265
+
266
+ if __name__ == "__main__":
267
+ app.run(host="0.0.0.0", port=8000)