geethareddy commited on
Commit
29a3e68
·
verified ·
1 Parent(s): c567e60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -67
app.py CHANGED
@@ -78,125 +78,154 @@ def login():
78
  return render_template("login.html", error=f"Error: {str(e)}")
79
 
80
  return render_template("login.html")
81
-
82
  @app.route("/menu", methods=["GET", "POST"])
83
  def menu():
84
  selected_category = request.args.get("category", "All")
85
  user_id = session.get('user_id')
86
- print(f"Cookies on /menu: {request.cookies}") # Debug: Check cookies sent
87
  print(f"Session check in /menu: user_id={user_id}")
88
-
 
 
 
89
  if not user_id:
90
  print("Session missing, redirecting to login.")
91
  return redirect(url_for('login'))
92
 
 
93
  try:
94
- query = "SELECT Name, Price__c, Image1__c, Image2__c, Category__c, Description__c FROM Menu_Item__c"
 
 
 
 
95
  result = sf.query(query)
 
 
96
  food_items = result['records'] if 'records' in result else []
97
- categories = {item['Category__c'] for item in food_items if 'Category__c' in item}
98
- if selected_category != "All":
99
- food_items = [item for item in food_items if item.get("Category__c") == selected_category]
 
 
 
 
 
 
 
 
100
  except Exception as e:
101
  print(f"Error fetching menu data: {str(e)}")
102
  food_items = []
103
- categories = []
104
- return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
105
 
 
 
 
 
 
 
106
 
 
107
  @app.route("/cart", methods=["GET"])
108
  def cart():
109
- email = session.get('user_email') # Get logged-in user's email
110
  if not email:
111
- return redirect(url_for("login")) # Redirect to login if not logged in
 
112
  try:
 
113
  result = sf.query(f"""
114
  SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
115
  FROM Cart_Item__c
116
  WHERE Customer_Email__c = '{email}'
117
  """)
118
  cart_items = result.get("records", [])
119
- subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
 
 
 
 
 
 
 
120
  except Exception as e:
121
  print(f"Error fetching cart items: {e}")
122
  cart_items = []
123
  subtotal = 0
124
-
125
- return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
126
 
 
127
 
128
 
129
  @app.route('/cart/add', methods=['POST'])
130
  def add_to_cart():
131
- data = request.json
132
  item_name = data.get('itemName').strip()
133
- item_price = data.get('itemPrice')
134
  item_image = data.get('itemImage')
135
- addons = data.get('addons', [])
136
- customer_email = session.get('user_email') # Get logged-in user's email from session
137
 
138
  if not item_name or not item_price:
139
  return jsonify({"success": False, "error": "Item name and price are required."})
140
 
 
 
 
 
 
 
 
 
 
 
 
141
  try:
142
- # Check if the item already exists in the cart for this custpmer
143
- query= f""" SELECT Id, Quantity__c FROM Cart_Item__c
144
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
145
- """
146
- result = sf.query(query)
147
- if result['totalSize'] > 0:
148
- # Update quantity if the item exists
149
- cart_item = result['records'][0]
150
- sf.Cart_Item__c.update(cart_item['Id'], {
151
- "Quantity__c": cart_item['Quantity__c'] + 1
152
- })
153
- else:
154
- # Add a new item if it doesn't exist
155
- sf.Cart_Item__c.create({
156
- "Name": item_name,
157
- "Price__c": item_price,
158
- "Quantity__c": 1,
159
- "Add_Ons__c": ";".join(addons) if addons else None,
160
- "Image1__c": item_image,
161
- "Customer_Email__c": customer_email, # Associate with the logged-in user
162
-
163
- })
164
- return jsonify({"success": True, "message": "Item added/updated successfully."})
165
  except Exception as e:
 
166
  return jsonify({"success": False, "error": str(e)})
167
 
 
 
168
  @app.route("/cart/add_item", methods=["POST"])
169
  def add_item_to_cart():
170
  data = request.json # Extract JSON data from the request
171
  email = data.get('email') # Customer email
172
  item_name = data.get('item_name') # Item name
173
- quantity = data.get('quantity', 0) # Quantity to add (default is 1) // default value is 1
174
-
175
- try:
176
- # Check if the item already exists in the cart for this customer
177
- cart_items = sf.query(
178
- f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Item_Name__c = '{item_name}'"
179
- )['records']
180
 
181
- if cart_items:
182
- # If the item already exists, update its quantity
183
- cart_item = cart_items[0]
184
- new_quantity = cart_item['Quantity__c'] + quantity
185
- sf.Cart_Item__c.update(cart_item['Id'], {"Quantity__c": new_quantity})
186
- return jsonify({"success": True, "message": "Item quantity updated successfully."})
187
- else:
188
- # If the item does not exist, add it to the cart
189
- sf.Cart_Item__c.create({
190
- "Customer_Email__c": email,
191
- "Item_Name__c": item_name,
192
- "Quantity__c": quantity
193
- })
194
 
195
- return jsonify({"success": True, "message": "Item added/updated successfully."})
 
 
 
 
 
 
 
 
 
196
  except Exception as e:
 
197
  return jsonify({"success": False, "error": str(e)}), 500
198
 
199
 
 
200
  @app.route('/cart/remove/<item_name>', methods=['POST'])
201
  def remove_cart_item(item_name):
202
  try:
@@ -219,18 +248,23 @@ def remove_cart_item(item_name):
219
 
220
  @app.route('/api/addons', methods=['GET'])
221
  def get_addons():
222
- item_name = request.args.get('item_name')
223
  if not item_name:
224
  return jsonify({"success": False, "error": "Item name is required."})
225
 
226
  try:
227
- query = f"SELECT Name, Price__c FROM Add_Ons__c"
 
 
 
 
228
  addons = sf.query(query)['records']
229
  return jsonify({"success": True, "addons": addons})
230
  except Exception as e:
231
  print(f"Error fetching add-ons: {e}")
232
  return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
233
 
 
234
  @app.route("/cart/update_quantity", methods=["POST"])
235
  def update_quantity():
236
  data = request.json # Extract JSON data from the request
@@ -269,16 +303,22 @@ def checkout():
269
  user_id = session.get('user_id')
270
  if not email or not user_id:
271
  return jsonify({"success": False, "message": "User not logged in"})
 
272
  try:
 
273
  result = sf.query(f"""
274
  SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
275
  FROM Cart_Item__c
276
  WHERE Customer_Email__c = '{email}'
277
  """)
278
- cart_items = result["records"]
279
  if not cart_items:
280
  return jsonify({"success": False, "message": "Cart is empty"})
281
- total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
 
 
 
 
282
  order_data = {
283
  "Customer_Name__c": user_id,
284
  "Customer_Email__c": email,
@@ -288,15 +328,19 @@ def checkout():
288
  [f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
289
  ),
290
  "Add_Ons__c": "\n".join(
291
- [f"{item['Add_Ons__c']}" if item['Add_Ons__c'] else "None" for item in cart_items]
292
  ),
293
  }
294
  sf.Order__c.create(order_data)
 
 
295
  for item in cart_items:
296
  sf.Cart_Item__c.delete(item["Id"])
 
297
  return jsonify({"success": True, "message": "Order placed successfully!"})
298
  except Exception as e:
299
  return jsonify({"success": False, "error": str(e)})
300
 
 
301
  if __name__ == "__main__":
302
  app.run(debug=False, host="0.0.0.0", port=7860)
 
78
  return render_template("login.html", error=f"Error: {str(e)}")
79
 
80
  return render_template("login.html")
 
81
  @app.route("/menu", methods=["GET", "POST"])
82
  def menu():
83
  selected_category = request.args.get("category", "All")
84
  user_id = session.get('user_id')
85
+ print(f"Cookies on /menu: {request.cookies}")
86
  print(f"Session check in /menu: user_id={user_id}")
87
+
88
+ # Get the selected category from the query parameter, default is "All"
89
+ selected_category = request.args.get("category", "All")
90
+ print(f"Selected category: {selected_category}")
91
  if not user_id:
92
  print("Session missing, redirecting to login.")
93
  return redirect(url_for('login'))
94
 
95
+
96
  try:
97
+ query = """
98
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c
99
+ FROM Menu_Item__c
100
+ """
101
+ # Query to fetch menu items
102
  result = sf.query(query)
103
+
104
+ # Fetch all food items from the query result
105
  food_items = result['records'] if 'records' in result else []
106
+
107
+ # Dynamically determine categories based on the fetched data
108
+ categories = {item.get("Veg_NonVeg__c").capitalize() for item in food_items if item.get("Veg_NonVeg__c")}
109
+ categories = {"Veg", "Non-Veg"} # Explicitly overwrite to ensure valid categories only
110
+
111
+ # Filter food items based on the selected category
112
+ if selected_category == "Veg":
113
+ food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
114
+ elif selected_category == "Non-Veg":
115
+ food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
116
+
117
  except Exception as e:
118
  print(f"Error fetching menu data: {str(e)}")
119
  food_items = []
120
+ categories = {"All", "Veg", "Non-Veg"} # Default categories on error
 
121
 
122
+ # Render the menu page with the filtered data
123
+ return render_template(
124
+ "menu.html",
125
+ food_items=food_items,
126
+ categories=sorted(categories), # Sort categories alphabetically if needed
127
+ selected_category=selected_category,
128
 
129
+ )
130
  @app.route("/cart", methods=["GET"])
131
  def cart():
132
+ email = session.get('user_email') # Get logged-in user's email
133
  if not email:
134
+ return redirect(url_for("login")) # Redirect to login if not logged in
135
+
136
  try:
137
+ # Query cart items
138
  result = sf.query(f"""
139
  SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
140
  FROM Cart_Item__c
141
  WHERE Customer_Email__c = '{email}'
142
  """)
143
  cart_items = result.get("records", [])
144
+
145
+ # Calculate the subtotal, including add-ons prices
146
+ subtotal = sum(item['Price__c'] * item['Quantity__c'] for item in cart_items)
147
+
148
+ # Ensure add-ons are processed properly
149
+ for item in cart_items:
150
+ item['Add_Ons__c'] = item.get('Add_Ons__c', "None") # Default to "None" if no add-ons
151
+
152
  except Exception as e:
153
  print(f"Error fetching cart items: {e}")
154
  cart_items = []
155
  subtotal = 0
 
 
156
 
157
+ return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
158
 
159
 
160
  @app.route('/cart/add', methods=['POST'])
161
  def add_to_cart():
162
+ data = request.json # Extract JSON payload
163
  item_name = data.get('itemName').strip()
164
+ item_price = data.get('itemPrice') # Base price of the item
165
  item_image = data.get('itemImage')
166
+ addons = data.get('addons', []) # Extract add-ons array
167
+ customer_email = session.get('user_email') # Get the logged-in user's email
168
 
169
  if not item_name or not item_price:
170
  return jsonify({"success": False, "error": "Item name and price are required."})
171
 
172
+ # Convert add-ons array to a formatted string and calculate the add-ons total price
173
+ addons_string = "None"
174
+ addons_total_price = 0
175
+ if addons:
176
+ addons_details = [f"{addon['name']} (${addon['price']})" for addon in addons]
177
+ addons_total_price = sum(addon['price'] for addon in addons)
178
+ addons_string = "; ".join(addons_details)
179
+
180
+ # Calculate the total price (item price + add-ons)
181
+ total_price = item_price + addons_total_price
182
+
183
  try:
184
+ # Save the cart item in Salesforce
185
+ sf.Cart_Item__c.create({
186
+ "Name": item_name, # Item name
187
+ "Price__c": total_price, # Total price (item + add-ons)
188
+ "Base_Price__c": item_price, # Base price without add-ons
189
+ "Quantity__c": 1, # Default quantity is 1
190
+ "Add_Ons__c": addons_string, # Add-ons with name and price
191
+ "Image1__c": item_image, # Item image URL
192
+ "Customer_Email__c": customer_email, # Associated customer's email
193
+ })
194
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
 
 
 
 
 
 
 
 
 
 
 
 
195
  except Exception as e:
196
+ print(f"Error adding item to cart: {str(e)}")
197
  return jsonify({"success": False, "error": str(e)})
198
 
199
+
200
+
201
  @app.route("/cart/add_item", methods=["POST"])
202
  def add_item_to_cart():
203
  data = request.json # Extract JSON data from the request
204
  email = data.get('email') # Customer email
205
  item_name = data.get('item_name') # Item name
206
+ quantity = data.get('quantity', 1) # Quantity to add (default is 1)
207
+ addons = data.get('addons', []) # Add-ons for the item (optional)
 
 
 
 
 
208
 
209
+ # Validate inputs
210
+ if not email or not item_name:
211
+ return jsonify({"success": False, "error": "Email and item name are required."}), 400
 
 
 
 
 
 
 
 
 
 
212
 
213
+ try:
214
+ # Add a new item to the cart with the provided details
215
+ sf.Cart_Item__c.create({
216
+ "Customer_Email__c": email, # Associate the cart item with the customer's email
217
+ "Item_Name__c": item_name, # Item name
218
+ "Quantity__c": quantity, # Quantity to add
219
+ "Add_Ons__c": addons_string
220
+ })
221
+
222
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
223
  except Exception as e:
224
+ print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
225
  return jsonify({"success": False, "error": str(e)}), 500
226
 
227
 
228
+
229
  @app.route('/cart/remove/<item_name>', methods=['POST'])
230
  def remove_cart_item(item_name):
231
  try:
 
248
 
249
  @app.route('/api/addons', methods=['GET'])
250
  def get_addons():
251
+ item_name = request.args.get('item_name') # Fetch the requested item name
252
  if not item_name:
253
  return jsonify({"success": False, "error": "Item name is required."})
254
 
255
  try:
256
+ # Fetch add-ons related to the item (update query as needed)
257
+ query = f"""
258
+ SELECT Name, Price__c
259
+ FROM Add_Ons__c
260
+ """
261
  addons = sf.query(query)['records']
262
  return jsonify({"success": True, "addons": addons})
263
  except Exception as e:
264
  print(f"Error fetching add-ons: {e}")
265
  return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
266
 
267
+
268
  @app.route("/cart/update_quantity", methods=["POST"])
269
  def update_quantity():
270
  data = request.json # Extract JSON data from the request
 
303
  user_id = session.get('user_id')
304
  if not email or not user_id:
305
  return jsonify({"success": False, "message": "User not logged in"})
306
+
307
  try:
308
+ # Fetch cart items for the user
309
  result = sf.query(f"""
310
  SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
311
  FROM Cart_Item__c
312
  WHERE Customer_Email__c = '{email}'
313
  """)
314
+ cart_items = result.get("records", [])
315
  if not cart_items:
316
  return jsonify({"success": False, "message": "Cart is empty"})
317
+
318
+ # Calculate the total price of the order
319
+ total_price = sum(item['Price__c'] * item['Quantity__c'] for item in cart_items)
320
+
321
+ # Create the order in Salesforce
322
  order_data = {
323
  "Customer_Name__c": user_id,
324
  "Customer_Email__c": email,
 
328
  [f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
329
  ),
330
  "Add_Ons__c": "\n".join(
331
+ [item['Add_Ons__c'] if item.get('Add_Ons__c') else "None" for item in cart_items]
332
  ),
333
  }
334
  sf.Order__c.create(order_data)
335
+
336
+ # Clear the cart after placing the order
337
  for item in cart_items:
338
  sf.Cart_Item__c.delete(item["Id"])
339
+
340
  return jsonify({"success": True, "message": "Order placed successfully!"})
341
  except Exception as e:
342
  return jsonify({"success": False, "error": str(e)})
343
 
344
+
345
  if __name__ == "__main__":
346
  app.run(debug=False, host="0.0.0.0", port=7860)