nagasurendra Yaswanth56 commited on
Commit
3ba6e48
·
verified ·
1 Parent(s): 416b66f

Update app.py (#3)

Browse files

- Update app.py (235eeb0bfc34f6696604a86a21bcec2552b7a747)


Co-authored-by: Yaswanth Telagamsetti <Yaswanth56@users.noreply.huggingface.co>

Files changed (1) hide show
  1. app.py +495 -5
app.py CHANGED
@@ -1,4 +1,5 @@
1
  from flask import Flask, render_template, request, jsonify, redirect, url_for, session
 
2
  from flask_session import Session # Import the Session class
3
  from flask.sessions import SecureCookieSessionInterface # Import the class
4
  from salesforce import get_salesforce_connection
@@ -7,6 +8,7 @@ from simple_salesforce import Salesforce
7
 
8
  import salesforce_api as sf
9
 
 
10
  # Initialize Flask app and Salesforce connection
11
  print("Starting app...")
12
  app = Flask(__name__)
@@ -120,15 +122,26 @@ def order_history():
120
  except Exception as e:
121
  print(f"Error fetching order history: {str(e)}")
122
  return render_template("order_history.html", orders=[], error=str(e))
 
123
 
124
  @app.route("/logout")
125
  def logout():
126
- session.clear() # Clear the session
127
- session.modified = True # Explicitly mark session as modified
128
- # Optionally, delete the session cookie explicitly
 
 
 
 
129
  response = redirect("https://biryanihub-dev-ed.develop.my.salesforce-sites.com/PublicLogin")
130
- response.delete_cookie('session') # Adjust this depending on the session cookie name
131
- return response # Redirect to Salesforce login page
 
 
 
 
 
 
132
 
133
  @app.route("/signup", methods=["GET", "POST"])
134
  def signup():
@@ -209,6 +222,8 @@ def signup():
209
  return render_template("signup.html")
210
 
211
 
 
 
212
  @app.route("/login", methods=["GET", "POST"])
213
  def login():
214
  if request.method == "POST":
@@ -284,3 +299,478 @@ def login():
284
  return render_template("login.html", error=f"Error: {str(e)}")
285
 
286
  return render_template("login.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask, render_template, request, jsonify, redirect, url_for, session
2
+ from flask import Flask, request, session, redirect, url_for, render_template
3
  from flask_session import Session # Import the Session class
4
  from flask.sessions import SecureCookieSessionInterface # Import the class
5
  from salesforce import get_salesforce_connection
 
8
 
9
  import salesforce_api as sf
10
 
11
+
12
  # Initialize Flask app and Salesforce connection
13
  print("Starting app...")
14
  app = Flask(__name__)
 
122
  except Exception as e:
123
  print(f"Error fetching order history: {str(e)}")
124
  return render_template("order_history.html", orders=[], error=str(e))
125
+ from flask import session, redirect, request, url_for, make_response
126
 
127
  @app.route("/logout")
128
  def logout():
129
+ # Clear session variables
130
+ session.pop('name', None)
131
+ session.pop('email', None)
132
+ session.pop('rewardPoints', None)
133
+ session.pop('coupon', None)
134
+
135
+ # Create the redirect response
136
  response = redirect("https://biryanihub-dev-ed.develop.my.salesforce-sites.com/PublicLogin")
137
+
138
+ # Add headers to prevent caching (optional, but helpful)
139
+ response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
140
+ response.headers['Pragma'] = 'no-cache'
141
+ response.headers['Expires'] = '0'
142
+
143
+ # Return the response with the added headers
144
+ return response
145
 
146
  @app.route("/signup", methods=["GET", "POST"])
147
  def signup():
 
222
  return render_template("signup.html")
223
 
224
 
225
+
226
+
227
  @app.route("/login", methods=["GET", "POST"])
228
  def login():
229
  if request.method == "POST":
 
299
  return render_template("login.html", error=f"Error: {str(e)}")
300
 
301
  return render_template("login.html")
302
+
303
+
304
+ return render_template("menu.html", user_name=user_name)
305
+ @app.route("/menu", methods=["GET", "POST"])
306
+ def menu():
307
+ selected_category = request.args.get("category", "All")
308
+ user_id = session.get('user_id')
309
+ user_email = session.get('user_email') # Fetch the user's email
310
+ print(f"Session check in /menu: user_id={user_id}, user_email={user_email}")
311
+
312
+ if not user_email:
313
+ user_email = request.args.get("email")
314
+ user_name = request.args.get("name")
315
+
316
+ if user_email:
317
+ session['user_email'] = user_email
318
+ session['user_name'] = user_name # If needed
319
+
320
+ print(f"✅ User session set: {user_email}, {user_name}")
321
+ else:
322
+ print("❌ No email in URL, redirecting to login.")
323
+ return redirect(url_for("login"))
324
+
325
+ print(f"Session check in /menu: user_email={user_email}")
326
+
327
+
328
+ try:
329
+ # Fetch the user's Referral__c and Reward_Points__c
330
+ user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
331
+ user_result = sf.query(user_query)
332
+
333
+ if not user_result['records']:
334
+ print("❌ User not found!")
335
+ return redirect(url_for('login'))
336
+
337
+ referral_code = user_result['records'][0].get('Referral__c', 'N/A') # Default to 'N/A' if empty
338
+ reward_points = user_result['records'][0].get('Reward_Points__c', 0) # Default to 0 if empty
339
+
340
+ # Query to fetch menu items
341
+ menu_query = """
342
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c
343
+ FROM Menu_Item__c
344
+ """
345
+ result = sf.query(menu_query)
346
+ food_items = result['records'] if 'records' in result else []
347
+
348
+ # Extract valid categories dynamically
349
+ valid_categories = {"All", "Veg", "Non-Veg"} # Ensuring consistency
350
+ extracted_categories = {item.get("Veg_NonVeg__c", "").strip().capitalize() for item in food_items if item.get("Veg_NonVeg__c")}
351
+
352
+ # Ensure "Non-Veg" is included correctly
353
+ cleaned_categories = {"Veg" if cat.lower() == "veg" else "Non-Veg" if "non" in cat.lower() else cat for cat in extracted_categories}
354
+ categories = valid_categories.intersection(cleaned_categories) # Keep only expected categories
355
+
356
+ # Filtering logic
357
+ if selected_category == "Veg":
358
+ food_items = [item for item in food_items if item.get("Veg_NonVeg__c", "").lower() == "veg"]
359
+ elif selected_category == "Non-Veg":
360
+ food_items = [item for item in food_items if "non" in item.get("Veg_NonVeg__c", "").lower()]
361
+
362
+ # "All" does not filter anything, it shows everything by default
363
+
364
+ except Exception as e:
365
+ print(f"❌ Error fetching menu data: {str(e)}")
366
+ food_items = []
367
+ categories = {"All", "Veg", "Non-Veg"} # Default categories on error
368
+ referral_code = 'N/A'
369
+ reward_points = 0
370
+
371
+ # Render the menu page with the fetched data
372
+ return render_template(
373
+ "menu.html",
374
+ food_items=food_items,
375
+ categories=sorted(categories), # Sort categories alphabetically if needed
376
+ selected_category=selected_category,
377
+ referral_code=referral_code,
378
+ reward_points=reward_points
379
+ )
380
+
381
+
382
+
383
+
384
+
385
+ @app.route("/cart", methods=["GET"])
386
+ def cart():
387
+ email = session.get('user_email') # Get logged-in user's email
388
+ if not email:
389
+ return redirect(url_for("login"))
390
+
391
+ try:
392
+ # Query cart items
393
+ result = sf.query(f"""
394
+ SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c
395
+ FROM Cart_Item__c
396
+ WHERE Customer_Email__c = '{email}'
397
+ """)
398
+ cart_items = result.get("records", [])
399
+
400
+ # Subtotal should be the sum of all item prices in the cart
401
+ subtotal = sum(item['Price__c'] for item in cart_items)
402
+
403
+ # Fetch reward points
404
+ customer_result = sf.query(f"""
405
+ SELECT Reward_Points__c
406
+ FROM Customer_Login__c
407
+ WHERE Email__c = '{email}'
408
+ """)
409
+ reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
410
+
411
+ # Fetch coupons for the user
412
+ coupon_result = sf.query(f"""
413
+ SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
414
+ """)
415
+
416
+ # Extract and split coupons into a list
417
+ if coupon_result["records"]:
418
+ raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
419
+ coupons = raw_coupons.split("\n") if raw_coupons else []
420
+ else:
421
+ coupons = []
422
+
423
+ return render_template(
424
+ "cart.html",
425
+ cart_items=cart_items,
426
+ subtotal=subtotal,
427
+ reward_points=reward_points,
428
+ customer_email=email,
429
+ coupons=coupons # Send coupons to template
430
+ )
431
+
432
+ except Exception as e:
433
+ print(f"Error fetching cart items: {e}")
434
+ return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[])
435
+
436
+
437
+
438
+ @app.route('/cart/add', methods=['POST'])
439
+ def add_to_cart():
440
+ data = request.json # Extract JSON payload from frontend
441
+ item_name = data.get('itemName').strip() # Item name
442
+ item_price = data.get('itemPrice') # Base price of the item
443
+ item_image = data.get('itemImage') # Item image
444
+ addons = data.get('addons', []) # Add-ons array
445
+ instructions = data.get('instructions', '') # Special instructions
446
+ customer_email = session.get('user_email') # Get logged-in user's email
447
+
448
+ if not item_name or not item_price:
449
+ return jsonify({"success": False, "error": "Item name and price are required."})
450
+
451
+ try:
452
+ # Query the cart to check if the item already exists
453
+ query = f"""
454
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c FROM Cart_Item__c
455
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
456
+ """
457
+ result = sf.query(query)
458
+ cart_items = result.get("records", [])
459
+
460
+ # Calculate the price of the new add-ons
461
+ addons_price = sum(addon['price'] for addon in addons) # New add-ons price
462
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) # Format new add-ons
463
+
464
+ if cart_items:
465
+ # If the item already exists in the cart, update it
466
+ cart_item_id = cart_items[0]['Id']
467
+ existing_quantity = cart_items[0]['Quantity__c']
468
+ existing_addons = cart_items[0].get('Add_Ons__c', "None") # Previous add-ons
469
+ existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0) # Previous add-ons price
470
+ existing_instructions = cart_items[0].get('Instructions__c', "") # Previous instructions
471
+
472
+ # Combine the existing and new add-ons
473
+ combined_addons = existing_addons if existing_addons != "None" else ""
474
+ if new_addons:
475
+ combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
476
+
477
+ # Combine the existing and new instructions
478
+ combined_instructions = existing_instructions
479
+ if instructions:
480
+ combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
481
+
482
+ # Recalculate the total add-ons price
483
+ combined_addons_list = combined_addons.split("; ")
484
+ combined_addons_price = sum(
485
+ float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
486
+ )
487
+
488
+ # Update the item in the cart
489
+ sf.Cart_Item__c.update(cart_item_id, {
490
+ "Quantity__c": existing_quantity + 1, # Increase quantity by 1
491
+ "Add_Ons__c": combined_addons, # Update add-ons list
492
+ "Add_Ons_Price__c": combined_addons_price, # Update add-ons price
493
+ "Instructions__c": combined_instructions, # Update instructions
494
+ "Price__c": (existing_quantity + 1) * item_price + combined_addons_price, # Update total price
495
+ })
496
+ else:
497
+ # If the item does not exist in the cart, create a new one
498
+ addons_string = "None"
499
+ if addons:
500
+ addons_string = new_addons # Use the formatted add-ons string
501
+
502
+ total_price = item_price + addons_price # Base price + add-ons price
503
+
504
+ # Create a new cart item
505
+ sf.Cart_Item__c.create({
506
+ "Name": item_name, # Item name
507
+ "Price__c": total_price, # Total price (item + add-ons)
508
+ "Base_Price__c": item_price, # Base price without add-ons
509
+ "Quantity__c": 1, # Default quantity is 1
510
+ "Add_Ons_Price__c": addons_price, # Total add-ons price
511
+ "Add_Ons__c": addons_string, # Add-ons with names and prices
512
+ "Image1__c": item_image, # Item image URL
513
+ "Customer_Email__c": customer_email, # Associated customer's email
514
+ "Instructions__c": instructions # Save instructions
515
+ })
516
+
517
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
518
+ except Exception as e:
519
+ print(f"Error adding item to cart: {str(e)}")
520
+ return jsonify({"success": False, "error": str(e)})
521
+
522
+
523
+
524
+ @app.route("/cart/add_item", methods=["POST"])
525
+ def add_item_to_cart():
526
+ data = request.json # Extract JSON data from the request
527
+ email = data.get('email') # Customer email
528
+ item_name = data.get('item_name') # Item name
529
+ quantity = data.get('quantity', 1) # Quantity to add (default is 1)
530
+ addons = data.get('addons', []) # Add-ons for the item (optional)
531
+
532
+ # Validate inputs
533
+ if not email or not item_name:
534
+ return jsonify({"success": False, "error": "Email and item name are required."}), 400
535
+
536
+ try:
537
+ # Add a new item to the cart with the provided details
538
+ sf.Cart_Item__c.create({
539
+ "Customer_Email__c": email, # Associate the cart item with the customer's email
540
+ "Item_Name__c": item_name, # Item name
541
+ "Quantity__c": quantity, # Quantity to add
542
+ "Add_Ons__c": addons_string
543
+ })
544
+
545
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
546
+ except Exception as e:
547
+ print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
548
+ return jsonify({"success": False, "error": str(e)}), 500
549
+
550
+
551
+
552
+ @app.route('/cart/remove/<item_name>', methods=['POST'])
553
+ def remove_cart_item(item_name):
554
+ try:
555
+ customer_email = session.get('user_email')
556
+ if not customer_email:
557
+ return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
558
+ query = f"""
559
+ SELECT Id FROM Cart_Item__c
560
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
561
+ """
562
+ result = sf.query(query)
563
+ if result['totalSize'] == 0:
564
+ return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
565
+ cart_item_id = result['records'][0]['Id']
566
+ sf.Cart_Item__c.delete(cart_item_id)
567
+ return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
568
+ except Exception as e:
569
+ print(f"Error: {str(e)}")
570
+ return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
571
+
572
+ @app.route('/api/addons', methods=['GET'])
573
+ def get_addons():
574
+ item_name = request.args.get('item_name') # Fetch the requested item name
575
+ if not item_name:
576
+ return jsonify({"success": False, "error": "Item name is required."})
577
+
578
+ try:
579
+ # Fetch add-ons related to the item (update query as needed)
580
+ query = f"""
581
+ SELECT Name, Price__c
582
+ FROM Add_Ons__c
583
+ """
584
+ addons = sf.query(query)['records']
585
+ return jsonify({"success": True, "addons": addons})
586
+ except Exception as e:
587
+ print(f"Error fetching add-ons: {e}")
588
+ return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
589
+ @app.route("/cart/update_quantity", methods=["POST"])
590
+ def update_quantity():
591
+ data = request.json # Extract JSON data from the request
592
+ email = data.get('email')
593
+ item_name = data.get('item_name')
594
+ try:
595
+ # Convert quantity to an integer
596
+ quantity = int(data.get('quantity'))
597
+ except (ValueError, TypeError):
598
+ return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
599
+
600
+ # Validate inputs
601
+ if not email or not item_name or quantity is None:
602
+ return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
603
+
604
+ try:
605
+ # Query the cart item in Salesforce
606
+ cart_items = sf.query(
607
+ f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
608
+ f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
609
+ )['records']
610
+
611
+ if not cart_items:
612
+ return jsonify({"success": False, "error": "Cart item not found."}), 404
613
+
614
+ # Retrieve the first matching record
615
+ cart_item_id = cart_items[0]['Id']
616
+ base_price = cart_items[0]['Base_Price__c']
617
+ addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
618
+
619
+ # Calculate the new item price
620
+ new_item_price = (base_price * quantity) + addons_price
621
+
622
+ # Update the record in Salesforce
623
+ sf.Cart_Item__c.update(cart_item_id, {
624
+ "Quantity__c": quantity,
625
+ "Price__c": new_item_price, # Update base price
626
+ })
627
+
628
+ # Recalculate the subtotal for all items in the cart
629
+ cart_items = sf.query(f"""
630
+ SELECT Price__c, Add_Ons_Price__c
631
+ FROM Cart_Item__c
632
+ WHERE Customer_Email__c = '{email}'
633
+ """)['records']
634
+ new_subtotal = sum(item['Price__c'] for item in cart_items)
635
+
636
+ # Return updated item price and subtotal
637
+ return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
638
+ print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
639
+ return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
640
+
641
+ except Exception as e:
642
+ print(f"Error updating quantity: {str(e)}")
643
+ return jsonify({"success": False, "error": str(e)}), 500
644
+ @app.route("/checkout", methods=["POST"])
645
+ def checkout():
646
+ email = session.get('user_email')
647
+ user_id = session.get('user_name')
648
+
649
+ if not email or not user_id:
650
+ return jsonify({"success": False, "message": "User not logged in"})
651
+
652
+ try:
653
+ data = request.json
654
+ selected_coupon = data.get("selectedCoupon", "").strip()
655
+
656
+ # Fetch cart items
657
+ result = sf.query(f"""
658
+ SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
659
+ FROM Cart_Item__c
660
+ WHERE Customer_Email__c = '{email}'
661
+ """)
662
+ cart_items = result.get("records", [])
663
+
664
+ if not cart_items:
665
+ return jsonify({"success": False, "message": "Cart is empty"})
666
+
667
+ total_price = sum(item['Price__c'] for item in cart_items)
668
+ discount = 0
669
+ # Fetch the user's existing coupons
670
+ coupon_query = sf.query(f"""
671
+ SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
672
+ """)
673
+
674
+ has_coupons = bool(coupon_query["records"]) # Check if user has any coupons
675
+
676
+ if selected_coupon:
677
+ # Case 3: User selected a valid coupon → Apply discount & remove coupon
678
+ discount = total_price * 0.10 # 10% discount
679
+ referral_coupon_id = coupon_query["records"][0]["Id"]
680
+ existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
681
+
682
+ # Remove only the selected coupon
683
+ updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
684
+
685
+ # Convert list back to a string with newlines
686
+ updated_coupons_str = "\n".join(updated_coupons).strip()
687
+
688
+ # Update the Referral_Coupon__c record with the remaining coupons
689
+ sf.Referral_Coupon__c.update(referral_coupon_id, {
690
+ "Coupon_Code__c": updated_coupons_str
691
+ })
692
+ else:
693
+ # Case 1 & Case 2: User has no coupons or has coupons but didn’t select one → Add 10% to reward points
694
+ reward_points_to_add = total_price * 0.10
695
+
696
+ # Fetch current reward points
697
+ customer_record = sf.query(f"""
698
+ SELECT Id, Reward_Points__c FROM Customer_Login__c
699
+ WHERE Email__c = '{email}'
700
+ """)
701
+ customer = customer_record.get("records", [])[0] if customer_record else None
702
+
703
+ if customer:
704
+ current_reward_points = customer.get("Reward_Points__c") or 0
705
+ new_reward_points = current_reward_points + reward_points_to_add
706
+
707
+ print(f"Updating reward points: Current = {current_reward_points}, Adding = {reward_points_to_add}, New = {new_reward_points}")
708
+
709
+ # Update reward points in Salesforce
710
+ sf.Customer_Login__c.update(customer["Id"], {
711
+ "Reward_Points__c": new_reward_points
712
+ })
713
+ print(f"Successfully updated reward points for {email}")
714
+
715
+
716
+
717
+ total_bill = total_price - discount
718
+
719
+ # ✅ Store **all details** including Add-Ons, Instructions, Price, and Image
720
+ order_details = "\n".join(
721
+ f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
722
+ f"Instructions: {item.get('Instructions__c', 'None')} | "
723
+ f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
724
+ for item in cart_items
725
+ )
726
+
727
+ # Store the order details in Order__c
728
+ order_data = {
729
+ "Customer_Name__c": user_id,
730
+ "Customer_Email__c": email,
731
+ "Total_Amount__c": total_price,
732
+ "Discount__c": discount,
733
+ "Total_Bill__c": total_bill,
734
+ "Order_Status__c": "Pending",
735
+ "Order_Details__c": order_details # ✅ Now includes **all details**
736
+ }
737
+
738
+ sf.Order__c.create(order_data)
739
+
740
+ # ✅ Delete cart items after order is placed
741
+ for item in cart_items:
742
+ sf.Cart_Item__c.delete(item["Id"])
743
+
744
+ return jsonify({"success": True, "message": "Order placed successfully!"})
745
+
746
+ except Exception as e:
747
+ print(f"Error during checkout: {str(e)}")
748
+ return jsonify({"success": False, "error": str(e)})
749
+
750
+ @app.route("/order", methods=["GET"])
751
+ def order_summary():
752
+ email = session.get('user_email') # Fetch logged-in user's email
753
+ if not email:
754
+ return redirect(url_for("login"))
755
+
756
+ try:
757
+ # Fetch the most recent order for the user
758
+ result = sf.query(f"""
759
+ SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
760
+ FROM Order__c
761
+ WHERE Customer_Email__c = '{email}'
762
+ ORDER BY CreatedDate DESC
763
+ LIMIT 1
764
+ """)
765
+ order = result.get("records", [])[0] if result.get("records") else None
766
+
767
+ if not order:
768
+ return render_template("order.html", order=None)
769
+
770
+ return render_template("order.html", order=order)
771
+ except Exception as e:
772
+ print(f"Error fetching order details: {str(e)}")
773
+ return render_template("order.html", order=None, error=str(e))
774
+
775
+ if __name__ == "__main__":
776
+ app.run(debug=True, host="0.0.0.0", port=7860)