nagasurendra commited on
Commit
1dc178b
·
verified ·
1 Parent(s): 307c7be

Update cart.py

Browse files
Files changed (1) hide show
  1. cart.py +71 -120
cart.py CHANGED
@@ -267,128 +267,84 @@ 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') # 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,59 +354,54 @@ def checkout():
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
424
  email = session.get('user_email')
425
-
426
  if not email:
427
  return jsonify({"success": False, "message": "User not logged in"})
428
 
429
  try:
430
- # Fetch the most recent order (or any other logic to get the previous order)
431
- previous_order_query = f"""
432
- SELECT Order_Details__c
433
- FROM Order__c
434
- WHERE Customer_Email__c = '{email}' AND Order_Status__c = 'Completed'
435
- ORDER BY CreatedDate DESC LIMIT 1
436
- """
437
- previous_order_result = sf.query(previous_order_query)
438
- previous_order = previous_order_result["records"][0] if previous_order_result["records"] else None
439
-
440
- if not previous_order:
441
- return jsonify({"success": False, "message": "No previous order found."})
442
-
443
- # Parse the order details to extract the items and add-ons
444
- order_details = previous_order["Order_Details__c"]
445
-
446
- # Assuming the order details are stored as JSON (you can use JSON.parse() in JavaScript to handle this)
447
- # You might need to adjust the parsing based on how the data is structured (whether it's JSON or string-based)
448
- order_items = json.loads(order_details)["items"]
449
-
450
- return jsonify({"success": True, "previousOrder": order_items})
 
 
 
451
 
452
  except Exception as e:
453
- print(f"Error fetching previous order: {e}")
454
- return jsonify({"success": False, "message": "Error fetching previous order."})
455
-
456
-
 
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
  "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 jsonify({"success": False, "message": "User not logged in"})
379
 
380
  try:
381
+ # Fetch customer loyalty data
382
+ customer_record = sf.query(f"""
383
+ SELECT Reward_Points__c, Total_Orders__c, Total_Spent__c, Badge__c
384
+ FROM Customer_Login__c WHERE Email__c = '{email}'
385
+ """)
386
+ customer = customer_record.get("records", [])[0] if customer_record["records"] else None
387
+ if not customer:
388
+ return jsonify({"success": False, "message": "Customer not found"})
389
+
390
+ # Define available rewards
391
+ rewards = [
392
+ {"name": "$5 Off", "points": 50, "description": "Get $5 off your next order"},
393
+ {"name": "Free Drink", "points": 100, "description": "Redeem for a free drink"},
394
+ {"name": "20% Off", "points": 200, "description": "20% off your next order"}
395
+ ]
396
+
397
+ loyalty_data = {
398
+ "reward_points": customer.get("Reward_Points__c", 0),
399
+ "total_orders": customer.get("Total_Orders__c", 0),
400
+ "total_spent": customer.get("Total_Spent__c", 0),
401
+ "badge": customer.get("Badge__c", "Newbie"),
402
+ "available_rewards": rewards
403
+ }
404
+ return jsonify({"success": True, "data": loyalty_data})
405
 
406
  except Exception as e:
407
+ return jsonify({"success": False, "error": str(e)})