lokeshloki143 commited on
Commit
b535544
·
verified ·
1 Parent(s): 0da1c37

Update cart.py

Browse files
Files changed (1) hide show
  1. cart.py +83 -12
cart.py CHANGED
@@ -1,13 +1,16 @@
1
- from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
 
2
  from salesforce import get_salesforce_connection
3
  import re
4
 
 
5
  sf = get_salesforce_connection()
 
 
6
  cart_blueprint = Blueprint('cart', __name__)
7
 
8
  # Utility function to sanitize SOQL inputs
9
  def sanitize_input(value):
10
- """Remove potentially dangerous characters for SOQL injection."""
11
  if value:
12
  value = re.sub(r'[;\'"\\]', '', value)
13
  return value
@@ -16,7 +19,7 @@ def sanitize_input(value):
16
  def cart():
17
  email = session.get('user_email')
18
  if not email:
19
- return redirect(url_for("login"))
20
 
21
  try:
22
  sanitized_email = sanitize_input(email)
@@ -43,7 +46,7 @@ def cart():
43
  def bill():
44
  email = session.get('user_email')
45
  if not email:
46
- return redirect(url_for("login"))
47
 
48
  try:
49
  sanitized_email = sanitize_input(email)
@@ -53,18 +56,34 @@ def bill():
53
  WHERE Customer_Email__c = '{sanitized_email}'
54
  """)
55
  cart_items = result.get("records", [])
 
 
 
 
 
 
 
 
 
56
  subtotal = sum(item['Price__c'] for item in cart_items)
57
 
58
  return render_template(
59
  "bill.html",
60
  cart_items=cart_items,
61
  subtotal=subtotal,
62
- customer_email=email
 
63
  )
64
 
65
  except Exception as e:
66
  print(f"Error fetching bill items: {e}")
67
- return render_template("bill.html", cart_items=[], subtotal=0, customer_email=email)
 
 
 
 
 
 
68
 
69
  @cart_blueprint.route("/bill/fetch_cart", methods=["GET"])
70
  def fetch_cart():
@@ -419,11 +438,10 @@ def submit_order():
419
  def order():
420
  email = session.get('user_email')
421
  if not email:
422
- return redirect(url_for("login"))
423
 
424
  try:
425
  sanitized_email = sanitize_input(email)
426
- # Fetch the latest order for the user
427
  result = sf.query(f"""
428
  SELECT Id, Order_Details__c, Total_Bill__c, CreatedDate
429
  FROM Order__c
@@ -440,15 +458,13 @@ def order():
440
  total = order['Total_Bill__c']
441
  order_details_raw = order['Order_Details__c'] or ""
442
 
443
- # Parse order details into a list of items
444
  order_items = []
445
  for line in order_details_raw.split("\n"):
446
  if not line.strip():
447
  continue
448
- # Example line: "Chicken Biryani x2 | Add-Ons: Extra Raita | Instructions: Less spicy | Price: $24.00 | Image: <url>"
449
  try:
450
  parts = line.split(" | ")
451
- name_quantity = parts[0].split(" x") # "Chicken Biryani x2" -> ["Chicken Biryani", "2"]
452
  name = name_quantity[0]
453
  quantity = int(name_quantity[1])
454
  addons = parts[1].replace("Add-Ons: ", "") if len(parts) > 1 else "None"
@@ -475,4 +491,59 @@ def order():
475
 
476
  except Exception as e:
477
  print(f"Error fetching order: {e}")
478
- return render_template("order.html", order=None, message="Error fetching your order. Please contact support.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for, Flask
2
+ from flask_cors import CORS
3
  from salesforce import get_salesforce_connection
4
  import re
5
 
6
+ # Initialize Salesforce connection
7
  sf = get_salesforce_connection()
8
+
9
+ # Create the cart blueprint
10
  cart_blueprint = Blueprint('cart', __name__)
11
 
12
  # Utility function to sanitize SOQL inputs
13
  def sanitize_input(value):
 
14
  if value:
15
  value = re.sub(r'[;\'"\\]', '', value)
16
  return value
 
19
  def cart():
20
  email = session.get('user_email')
21
  if not email:
22
+ return redirect(url_for("cart.login"))
23
 
24
  try:
25
  sanitized_email = sanitize_input(email)
 
46
  def bill():
47
  email = session.get('user_email')
48
  if not email:
49
+ return redirect(url_for("cart.login"))
50
 
51
  try:
52
  sanitized_email = sanitize_input(email)
 
56
  WHERE Customer_Email__c = '{sanitized_email}'
57
  """)
58
  cart_items = result.get("records", [])
59
+ if not cart_items:
60
+ return render_template(
61
+ "bill.html",
62
+ cart_items=[],
63
+ subtotal=0,
64
+ customer_email=email,
65
+ error_message="Your cart is empty. Please add items to proceed."
66
+ )
67
+
68
  subtotal = sum(item['Price__c'] for item in cart_items)
69
 
70
  return render_template(
71
  "bill.html",
72
  cart_items=cart_items,
73
  subtotal=subtotal,
74
+ customer_email=email,
75
+ error_message=None
76
  )
77
 
78
  except Exception as e:
79
  print(f"Error fetching bill items: {e}")
80
+ return render_template(
81
+ "bill.html",
82
+ cart_items=[],
83
+ subtotal=0,
84
+ customer_email=email,
85
+ error_message=f"Error fetching cart items: {str(e)}"
86
+ ), 500
87
 
88
  @cart_blueprint.route("/bill/fetch_cart", methods=["GET"])
89
  def fetch_cart():
 
438
  def order():
439
  email = session.get('user_email')
440
  if not email:
441
+ return redirect(url_for("cart.login"))
442
 
443
  try:
444
  sanitized_email = sanitize_input(email)
 
445
  result = sf.query(f"""
446
  SELECT Id, Order_Details__c, Total_Bill__c, CreatedDate
447
  FROM Order__c
 
458
  total = order['Total_Bill__c']
459
  order_details_raw = order['Order_Details__c'] or ""
460
 
 
461
  order_items = []
462
  for line in order_details_raw.split("\n"):
463
  if not line.strip():
464
  continue
 
465
  try:
466
  parts = line.split(" | ")
467
+ name_quantity = parts[0].split(" x")
468
  name = name_quantity[0]
469
  quantity = int(name_quantity[1])
470
  addons = parts[1].replace("Add-Ons: ", "") if len(parts) > 1 else "None"
 
491
 
492
  except Exception as e:
493
  print(f"Error fetching order: {e}")
494
+ return render_template("order.html", order=None, message="Error fetching your order. Please contact support.")
495
+
496
+ @cart_blueprint.route("/cart/validate_redirect", methods=["GET"])
497
+ def validate_redirect():
498
+ try:
499
+ email = session.get('user_email')
500
+ if not email:
501
+ return jsonify({
502
+ "success": False,
503
+ "message": "Please log in to proceed to the bill page.",
504
+ "redirect": url_for("cart.login")
505
+ }), 401
506
+
507
+ sanitized_email = sanitize_input(email)
508
+ result = sf.query(f"""
509
+ SELECT Id
510
+ FROM Cart_Item__c
511
+ WHERE Customer_Email__c = '{sanitized_email}'
512
+ """)
513
+ cart_items = result.get("records", [])
514
+ if not cart_items:
515
+ return jsonify({
516
+ "success": False,
517
+ "message": "Your cart is empty. Add items before proceeding to the bill page.",
518
+ "redirect": "/menu"
519
+ }), 400
520
+
521
+ return jsonify({"success": True, "message": "Redirect allowed."})
522
+
523
+ except Exception as e:
524
+ print(f"Error validating redirect: {e}")
525
+ return jsonify({
526
+ "success": False,
527
+ "message": "An error occurred while validating the redirect. Please try again."
528
+ }), 500
529
+
530
+ @cart_blueprint.route("/login", methods=["GET", "POST"])
531
+ def login():
532
+ if request.method == "POST":
533
+ email = request.form.get("email")
534
+ if not email:
535
+ return render_template("login.html", error="Email is required.")
536
+ session['user_email'] = email
537
+ session['user_name'] = "Test User"
538
+ session['table_number'] = "1"
539
+ return redirect(url_for("cart.cart"))
540
+ return render_template("login.html")
541
+
542
+ # Create the Flask app and register the blueprint
543
+ app = Flask(__name__)
544
+ app.secret_key = "your-secret-key-12345" # Replace with a secure key
545
+ CORS(app) # Enable CORS for Hugging Face Spaces
546
+ app.register_blueprint(cart_blueprint)
547
+
548
+ if __name__ == "__main__":
549
+ app.run(host="0.0.0.0", port=7860)