nagasurendra commited on
Commit
98110bb
·
verified ·
1 Parent(s): 3b6cbee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -46
app.py CHANGED
@@ -150,7 +150,6 @@ def cart():
150
  print(f"Error fetching cart items: {e}")
151
  return render_template("cart.html", cart_items=[], subtotal=0)
152
 
153
-
154
  @app.route('/cart/add', methods=['POST'])
155
  def add_to_cart():
156
  data = request.json # Extract JSON payload from frontend
@@ -158,6 +157,7 @@ def add_to_cart():
158
  item_price = data.get('itemPrice') # Base price of the item
159
  item_image = data.get('itemImage') # Item image
160
  addons = data.get('addons', []) # Add-ons array
 
161
  customer_email = session.get('user_email') # Get logged-in user's email
162
 
163
  if not item_name or not item_price:
@@ -166,7 +166,7 @@ def add_to_cart():
166
  try:
167
  # Query the cart to check if the item already exists
168
  query = f"""
169
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c FROM Cart_Item__c
170
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
171
  """
172
  result = sf.query(query)
@@ -180,45 +180,24 @@ def add_to_cart():
180
  # If the item already exists in the cart, update it
181
  cart_item_id = cart_items[0]['Id']
182
  existing_quantity = cart_items[0]['Quantity__c']
183
- existing_addons = cart_items[0].get('Add_Ons__c', "None") # Previous add-ons
184
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0) # Previous add-ons price
185
-
186
- # Combine the existing and new add-ons
187
- combined_addons = existing_addons if existing_addons != "None" else ""
188
- if new_addons:
189
- combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
190
-
191
- # Recalculate the total add-ons price
192
- combined_addons_list = combined_addons.split("; ")
193
- combined_addons_price = sum(
194
- float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
195
- )
196
 
197
- # Update the item in the cart
198
  sf.Cart_Item__c.update(cart_item_id, {
199
  "Quantity__c": existing_quantity + 1, # Increase quantity by 1
200
- "Add_Ons__c": combined_addons, # Update add-ons list
201
- "Add_Ons_Price__c": combined_addons_price, # Update add-ons price
202
- "Price__c": (existing_quantity + 1) * item_price + combined_addons_price, # Update total price
203
  })
204
  else:
205
  # If the item does not exist in the cart, create a new one
206
- addons_string = "None"
207
- if addons:
208
- addons_string = new_addons # Use the formatted add-ons string
209
-
210
- total_price = item_price + addons_price # Base price + add-ons price
211
-
212
- # Create a new cart item
213
  sf.Cart_Item__c.create({
214
- "Name": item_name, # Item name
215
- "Price__c": total_price, # Total price (item + add-ons)
216
- "Base_Price__c": item_price, # Base price without add-ons
217
- "Quantity__c": 1, # Default quantity is 1
218
- "Add_Ons_Price__c": addons_price, # Total add-ons price
219
- "Add_Ons__c": addons_string, # Add-ons with names and prices
220
- "Image1__c": item_image, # Item image URL
221
- "Customer_Email__c": customer_email, # Associated customer's email
 
222
  })
223
 
224
  return jsonify({"success": True, "message": "Item added to cart successfully."})
@@ -227,6 +206,7 @@ def add_to_cart():
227
  return jsonify({"success": False, "error": str(e)})
228
 
229
 
 
230
  @app.route("/cart/add_item", methods=["POST"])
231
  def add_item_to_cart():
232
  data = request.json # Extract JSON data from the request
@@ -349,15 +329,15 @@ def update_quantity():
349
  return jsonify({"success": False, "error": str(e)}), 500
350
  @app.route("/checkout", methods=["POST"])
351
  def checkout():
352
- email = session.get('user_email') # Fetch logged-in user's email
353
- user_id = session.get('user_id') # Fetch logged-in user's ID
354
  if not email or not user_id:
355
  return jsonify({"success": False, "message": "User not logged in"})
356
 
357
  try:
358
  # Fetch cart items for the user
359
  result = sf.query(f"""
360
- SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c
361
  FROM Cart_Item__c
362
  WHERE Customer_Email__c = '{email}'
363
  """)
@@ -368,19 +348,21 @@ def checkout():
368
  # Calculate the total price of the order
369
  total_price = sum(item['Price__c'] for item in cart_items)
370
 
371
- # Concatenate order details for all items
372
- order_details = "\n".join([
373
- f"{item['Name']} (Qty: {item['Quantity__c']}, Add-Ons: {item.get('Add_Ons__c', 'None')}, Price: ${item['Price__c']})"
374
- for item in cart_items
375
- ])
 
 
376
 
377
  # Create the order in Salesforce
378
  order_data = {
379
  "Customer_Name__c": user_id,
380
  "Customer_Email__c": email,
381
  "Total_Amount__c": total_price,
382
- "Order_Status__c": "Pending", # Default status
383
- "Order_Details__c": order_details # Storing concatenated order details
384
  }
385
  sf.Order__c.create(order_data)
386
 
@@ -388,11 +370,11 @@ def checkout():
388
  for item in cart_items:
389
  sf.Cart_Item__c.delete(item["Id"])
390
 
391
- # Return success response with redirect URL
392
- return jsonify({"success": True, "redirect": "/order", "message": "Order placed successfully!"})
393
  except Exception as e:
394
  print(f"Error during checkout: {str(e)}")
395
  return jsonify({"success": False, "error": str(e)})
 
396
  @app.route("/order", methods=["GET"])
397
  def order_summary():
398
  email = session.get('user_email') # Fetch logged-in user's email
 
150
  print(f"Error fetching cart items: {e}")
151
  return render_template("cart.html", cart_items=[], subtotal=0)
152
 
 
153
  @app.route('/cart/add', methods=['POST'])
154
  def add_to_cart():
155
  data = request.json # Extract JSON payload from frontend
 
157
  item_price = data.get('itemPrice') # Base price of the item
158
  item_image = data.get('itemImage') # Item image
159
  addons = data.get('addons', []) # Add-ons array
160
+ instructions = data.get('instructions', '') # Special instructions
161
  customer_email = session.get('user_email') # Get logged-in user's email
162
 
163
  if not item_name or not item_price:
 
166
  try:
167
  # Query the cart to check if the item already exists
168
  query = f"""
169
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c FROM Cart_Item__c
170
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
171
  """
172
  result = sf.query(query)
 
180
  # If the item already exists in the cart, update it
181
  cart_item_id = cart_items[0]['Id']
182
  existing_quantity = cart_items[0]['Quantity__c']
183
+ combined_instructions = instructions if instructions else cart_items[0].get('Instructions__c', '')
 
 
 
 
 
 
 
 
 
 
 
 
184
 
 
185
  sf.Cart_Item__c.update(cart_item_id, {
186
  "Quantity__c": existing_quantity + 1, # Increase quantity by 1
187
+ "Instructions__c": combined_instructions, # Update instructions
 
 
188
  })
189
  else:
190
  # If the item does not exist in the cart, create a new one
 
 
 
 
 
 
 
191
  sf.Cart_Item__c.create({
192
+ "Name": item_name,
193
+ "Price__c": item_price + addons_price,
194
+ "Base_Price__c": item_price,
195
+ "Quantity__c": 1,
196
+ "Add_Ons__c": new_addons,
197
+ "Add_Ons_Price__c": addons_price,
198
+ "Image1__c": item_image,
199
+ "Customer_Email__c": customer_email,
200
+ "Instructions__c": instructions # Save instructions
201
  })
202
 
203
  return jsonify({"success": True, "message": "Item added to cart successfully."})
 
206
  return jsonify({"success": False, "error": str(e)})
207
 
208
 
209
+
210
  @app.route("/cart/add_item", methods=["POST"])
211
  def add_item_to_cart():
212
  data = request.json # Extract JSON data from the request
 
329
  return jsonify({"success": False, "error": str(e)}), 500
330
  @app.route("/checkout", methods=["POST"])
331
  def checkout():
332
+ email = session.get('user_email')
333
+ user_id = session.get('user_id')
334
  if not email or not user_id:
335
  return jsonify({"success": False, "message": "User not logged in"})
336
 
337
  try:
338
  # Fetch cart items for the user
339
  result = sf.query(f"""
340
+ SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c
341
  FROM Cart_Item__c
342
  WHERE Customer_Email__c = '{email}'
343
  """)
 
348
  # Calculate the total price of the order
349
  total_price = sum(item['Price__c'] for item in cart_items)
350
 
351
+ # Format order details including instructions
352
+ order_details = []
353
+ for item in cart_items:
354
+ details = f"{item['Name']} (Qty: {item['Quantity__c']}, Add-Ons: {item['Add_Ons__c'] or 'None'}, Price: ${item['Price__c']})"
355
+ if item.get('Instructions__c'): # Include instructions if available
356
+ details += f", Instructions: {item['Instructions__c']}"
357
+ order_details.append(details)
358
 
359
  # Create the order in Salesforce
360
  order_data = {
361
  "Customer_Name__c": user_id,
362
  "Customer_Email__c": email,
363
  "Total_Amount__c": total_price,
364
+ "Order_Status__c": "Pending",
365
+ "Order_Details__c": "\n".join(order_details) # Store all item details
366
  }
367
  sf.Order__c.create(order_data)
368
 
 
370
  for item in cart_items:
371
  sf.Cart_Item__c.delete(item["Id"])
372
 
373
+ return jsonify({"success": True, "message": "Order placed successfully!"})
 
374
  except Exception as e:
375
  print(f"Error during checkout: {str(e)}")
376
  return jsonify({"success": False, "error": str(e)})
377
+
378
  @app.route("/order", methods=["GET"])
379
  def order_summary():
380
  email = session.get('user_email') # Fetch logged-in user's email