Yaswanth56 commited on
Commit
8a03bf5
·
verified ·
1 Parent(s): 84364a4

Update app.py

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