nagasurendra commited on
Commit
4823548
·
verified ·
1 Parent(s): 7caf8fd

Update cart.py

Browse files
Files changed (1) hide show
  1. cart.py +92 -93
cart.py CHANGED
@@ -267,84 +267,128 @@ def update_quantity():
267
  def checkout():
268
  email = session.get('user_email')
269
  user_id = session.get('user_name')
270
- table_number = session.get('table_number')
 
 
271
 
272
  if not email or not user_id:
 
273
  return jsonify({"success": False, "message": "User not logged in"})
274
 
275
  try:
 
276
  data = request.json
277
  selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
 
 
278
 
279
- # Fetch cart items
280
  result = sf.query(f"""
281
  SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
282
  FROM Cart_Item__c
283
  WHERE Customer_Email__c = '{email}'
284
  """)
 
 
285
  cart_items = result.get("records", [])
 
 
286
  if not cart_items:
 
287
  return jsonify({"success": False, "message": "Cart is empty"})
288
 
289
  total_price = sum(item['Price__c'] for item in cart_items)
 
 
290
  discount = 0
291
 
292
- # Coupon handling (existing logic)
293
  coupon_query = sf.query(f"""
294
  SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
295
  """)
296
- if selected_coupon and coupon_query["records"]:
297
- discount = total_price * 0.10
 
 
 
 
 
 
 
 
298
  referral_coupon_id = coupon_query["records"][0]["Id"]
 
 
299
  existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
 
 
 
300
  updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
301
- updated_coupons_str = "\n".join(updated_coupons).strip() or None
302
- sf.Referral_Coupon__c.update(referral_coupon_id, {"Coupon_Code__c": updated_coupons_str})
 
 
 
 
 
 
 
 
 
 
 
 
303
  else:
304
- # Add reward points (existing logic)
305
- reward_points_to_add = total_price * 0.10
 
 
 
306
  customer_record = sf.query(f"""
307
- SELECT Id, Reward_Points__c, Total_Orders__c, Total_Spent__c
308
- FROM Customer_Login__c WHERE Email__c = '{email}'
309
  """)
 
 
310
  customer = customer_record.get("records", [])[0] if customer_record else None
311
  if customer:
312
- current_reward_points = customer.get("Reward_Points__c", 0)
 
313
  new_reward_points = current_reward_points + reward_points_to_add
314
- total_orders = (customer.get("Total_Orders__c", 0) or 0) + 1
315
- total_spent = (customer.get("Total_Spent__c", 0) or 0) + total_price
316
-
317
- # Determine badge
318
- badge = "Newbie"
319
- if total_orders >= 10:
320
- badge = "VIP"
321
- elif total_orders >= 5:
322
- badge = "Regular"
323
- if total_spent > 500:
324
- badge = "Gold Member"
325
-
326
- # Update customer record
327
  sf.Customer_Login__c.update(customer["Id"], {
328
- "Reward_Points__c": new_reward_points,
329
- "Total_Orders__c": total_orders,
330
- "Total_Spent__c": total_spent,
331
- "Badge__c": badge
332
  })
333
 
 
334
  total_bill = total_price - discount
 
335
 
336
- # Store order (existing logic)
337
- customer_query = sf.query(f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{email}'")
338
- customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
339
- if not customer_id:
340
- return jsonify({"success": False, "message": "Customer record not found"})
341
-
342
  order_details = "\n".join(
343
  f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
344
- f"Instructions: {item.get('Instructions__c', 'None')} | Price: ${item['Price__c']}"
 
345
  for item in cart_items
346
  )
347
- table_number = table_number if table_number != 'null' else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  order_data = {
349
  "Customer_Name__c": user_id,
350
  "Customer_Email__c": email,
@@ -354,71 +398,26 @@ def checkout():
354
  "Order_Status__c": "Pending",
355
  "Customer2__c": customer_id,
356
  "Order_Details__c": order_details,
357
- "Table_Number__c": table_number
358
  }
 
 
 
359
  order_response = sf.Order__c.create(order_data)
 
360
 
 
361
  if order_response:
 
362
  for item in cart_items:
 
363
  sf.Cart_Item__c.delete(item["Id"])
364
 
365
- return jsonify({
366
- "success": True,
367
- "message": "Order placed successfully!",
368
- "discount": discount,
369
- "totalBill": total_bill
370
- })
371
 
372
  except Exception as e:
 
373
  return jsonify({"success": False, "error": str(e)})
374
- @cart_blueprint.route("/loyalty", methods=["GET"])
375
- def get_loyalty_data():
376
- email = session.get('user_email')
377
- if not email:
378
- return redirect(url_for('login'))
379
-
380
- try:
381
- customer_record = sf.query(f"""
382
- SELECT Reward_Points__c, Total_Orders__c, Total_Spent__c, Badge__c
383
- FROM Customer_Login__c WHERE Email__c = '{email}'
384
- """)
385
- customer = customer_record.get("records", [])[0] if customer_record["records"] else None
386
- if not customer:
387
- return "Customer not found", 404
388
-
389
- # Clean up data
390
- reward_points = round(customer.get("Reward_Points__c", 0) or 0, 2) # Round to 2 decimals
391
- total_orders = customer.get("Total_Orders__c", 0) or 0
392
- total_spent = customer.get("Total_Spent__c", 0) or 0
393
- badge = customer.get("Badge__c") or "Newbie" # Default to "Newbie" if None
394
-
395
- # Define rewards with image URLs (you can store these in Salesforce or locally)
396
- rewards = [
397
- {"name": "$5 Off", "points": 50, "description": "Get $5 off your next order", "image": "/static/images/reward_discount.png"},
398
- {"name": "Free Drink", "points": 100, "description": "Redeem for a free drink", "image": "/static/images/reward_drink.png"},
399
- {"name": "20% Off", "points": 200, "description": "20% off your next order", "image": "/static/images/reward_percentage.png"}
400
- ]
401
-
402
- # Badge images (map badge names to image paths)
403
- badge_images = {
404
- "Newbie": "/static/images/badge_bronze.png",
405
- "Regular": "/static/images/badge_silver.png",
406
- "VIP": "/static/images/badge_gold.png",
407
- "Gold Member": "/static/images/badge_platinum.png"
408
- }
409
-
410
- loyalty_data = {
411
- "reward_points": reward_points,
412
- "total_orders": total_orders,
413
- "total_spent": total_spent,
414
- "badge": badge,
415
- "badge_image": badge_images.get(badge, "/static/images/badge_bronze.png"), # Default to bronze
416
- "available_rewards": rewards
417
- }
418
- return render_template("loyalty.html", loyalty_data=loyalty_data)
419
-
420
- except Exception as e:
421
- return f"Error: {str(e)}", 500
422
  @cart_blueprint.route("/fetch_previous_order", methods=["GET"])
423
  def fetch_previous_order():
424
  # Assuming `email` is the unique identifier for the user
@@ -452,4 +451,4 @@ def fetch_previous_order():
452
 
453
  except Exception as e:
454
  print(f"Error fetching previous order: {e}")
455
- return jsonify({"success": False, "message": "Error fetching previous order."})
 
267
  def checkout():
268
  email = session.get('user_email')
269
  user_id = session.get('user_name')
270
+ table_number = session.get('table_number') # Retrieve table number
271
+
272
+ print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}") # Debugging session data
273
 
274
  if not email or not user_id:
275
+ print("User not logged in")
276
  return jsonify({"success": False, "message": "User not logged in"})
277
 
278
  try:
279
+ # Fetch the selected coupon (if any)
280
  data = request.json
281
  selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
282
+ # Now selected_coupon will be None if it's not provided or empty, or a valid string otherwise
283
+ print(f"Selected Coupon: {selected_coupon}") # Debugging selected coupon
284
 
285
+ # Fetch cart items for the current user
286
  result = sf.query(f"""
287
  SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
288
  FROM Cart_Item__c
289
  WHERE Customer_Email__c = '{email}'
290
  """)
291
+
292
+ # Log the cart items to see if they are fetched correctly
293
  cart_items = result.get("records", [])
294
+ print(f"Cart Items Retrieved: {cart_items}") # Debugging log
295
+
296
  if not cart_items:
297
+ print("Cart is empty")
298
  return jsonify({"success": False, "message": "Cart is empty"})
299
 
300
  total_price = sum(item['Price__c'] for item in cart_items)
301
+ print(f"Total Price: {total_price}") # Debugging total price calculation
302
+
303
  discount = 0
304
 
305
+ # Fetch the user's existing coupons
306
  coupon_query = sf.query(f"""
307
  SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
308
  """)
309
+ print(f"Coupon Query Results: {coupon_query}") # Debugging coupon query results
310
+
311
+ has_coupons = bool(coupon_query["records"])
312
+ print(f"Has Coupons: {has_coupons}") # Debugging coupon presence check
313
+
314
+ if selected_coupon:
315
+ # Apply 10% discount if a valid coupon is selected
316
+ discount = total_price * 0.10 # Example: 10% discount
317
+ print(f"Discount Applied: {discount}") # Debugging discount calculation
318
+
319
  referral_coupon_id = coupon_query["records"][0]["Id"]
320
+ print(f"Referral Coupon ID: {referral_coupon_id}") # Debugging referral coupon ID
321
+
322
  existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
323
+ print(f"Existing Coupons Before Removal: {existing_coupons}") # Debugging existing coupons
324
+
325
+ # Remove the selected coupon from the list of existing coupons
326
  updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
327
+ updated_coupons_str = "\n".join(updated_coupons).strip()
328
+
329
+ print(f"Updated Coupons After Removal: {updated_coupons}") # Debugging updated coupons
330
+
331
+ # If no coupons remain, set the field to None (not empty string)
332
+ if not updated_coupons:
333
+ updated_coupons_str = None # Set to None if no coupons are left
334
+ print("No Coupons Remaining. Setting to None") # Debugging no coupons left
335
+
336
+ # Update the Referral_Coupon__c record
337
+ print(f"Updating Referral Coupon: {updated_coupons_str}") # Debugging update to Salesforce
338
+ sf.Referral_Coupon__c.update(referral_coupon_id, {
339
+ "Coupon_Code__c": updated_coupons_str
340
+ })
341
  else:
342
+ # If no coupon is selected, add reward points
343
+ reward_points_to_add = total_price * 0.10 # Example: 10% reward points
344
+ print(f"Reward Points to Add: {reward_points_to_add}") # Debugging reward points
345
+
346
+ # Fetch current reward points
347
  customer_record = sf.query(f"""
348
+ SELECT Id, Reward_Points__c FROM Customer_Login__c
349
+ WHERE Email__c = '{email}'
350
  """)
351
+ print(f"Customer Reward Points Query: {customer_record}") # Debugging customer reward points query
352
+
353
  customer = customer_record.get("records", [])[0] if customer_record else None
354
  if customer:
355
+ current_reward_points = customer.get("Reward_Points__c") or 0
356
+ print(f"Current Reward Points: {current_reward_points}") # Debugging current reward points
357
  new_reward_points = current_reward_points + reward_points_to_add
358
+ print(f"New Reward Points: {new_reward_points}") # Debugging new reward points calculation
359
+
360
+ # Update reward points
 
 
 
 
 
 
 
 
 
 
361
  sf.Customer_Login__c.update(customer["Id"], {
362
+ "Reward_Points__c": new_reward_points
 
 
 
363
  })
364
 
365
+ # Final total bill calculation
366
  total_bill = total_price - discount
367
+ print(f"Total Bill After Discount: {total_bill}") # Debugging final total bill
368
 
369
+ # Store all order details (before deleting cart items)
 
 
 
 
 
370
  order_details = "\n".join(
371
  f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
372
+ f"Instructions: {item.get('Instructions__c', 'None')} | "
373
+ f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
374
  for item in cart_items
375
  )
376
+ print(f"Order Details: {order_details}") # Debugging order details
377
+
378
+ # Fetch Customer ID from Customer_Login__c
379
+ customer_query = sf.query(f"""
380
+ SELECT Id FROM Customer_Login__c
381
+ WHERE Email__c = '{email}'
382
+ """)
383
+
384
+ customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
385
+ print(f"Customer ID: {customer_id}") # Debugging customer ID retrieval
386
+
387
+ if not customer_id:
388
+ print("Customer record not found")
389
+ return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
390
+ table_number = table_number if table_number != 'null' else None # Ensure 'null' string is replaced with None
391
+ # Store order data
392
  order_data = {
393
  "Customer_Name__c": user_id,
394
  "Customer_Email__c": email,
 
398
  "Order_Status__c": "Pending",
399
  "Customer2__c": customer_id,
400
  "Order_Details__c": order_details,
401
+ "Table_Number__c": table_number # Store table number
402
  }
403
+ print(f"Order Data: {order_data}") # Debugging order data
404
+
405
+ # Create the order in Salesforce
406
  order_response = sf.Order__c.create(order_data)
407
+ print(f"Order Response: {order_response}") # Debugging order creation response
408
 
409
+ # Ensure the order was created successfully before deleting cart items
410
  if order_response:
411
+ # Only delete cart items after the order is created
412
  for item in cart_items:
413
+ print(f"Deleting Cart Item: {item['Id']}") # Debugging cart item deletion
414
  sf.Cart_Item__c.delete(item["Id"])
415
 
416
+ return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill})
 
 
 
 
 
417
 
418
  except Exception as e:
419
+ print(f"Error during checkout: {str(e)}") # Debugging error message
420
  return jsonify({"success": False, "error": str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  @cart_blueprint.route("/fetch_previous_order", methods=["GET"])
422
  def fetch_previous_order():
423
  # Assuming `email` is the unique identifier for the user
 
451
 
452
  except Exception as e:
453
  print(f"Error fetching previous order: {e}")
454
+ return jsonify({"success": False, "message": "Error fetching previous order."})