nagasurendra commited on
Commit
5324aa9
·
verified ·
1 Parent(s): 60c7f69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -752
app.py CHANGED
@@ -4,6 +4,9 @@ from flask.sessions import SecureCookieSessionInterface # Import the class
4
  from salesforce import get_salesforce_connection
5
  from datetime import timedelta
6
  import os
 
 
 
7
 
8
  # Initialize Flask app and Salesforce connection
9
  print("Starting app...")
@@ -486,758 +489,10 @@ def login():
486
  return render_template("login.html", error=f"Error: {str(e)}")
487
 
488
  return render_template("login.html")
489
-
490
- @app.route("/menu", methods=["GET", "POST"])
491
- def menu():
492
- selected_category = request.args.get("category", "All")
493
- user_email = session.get('user_email')
494
-
495
- if not user_email:
496
- user_email = request.args.get("email")
497
- user_name = request.args.get("name")
498
-
499
- if user_email:
500
- session['user_email'] = user_email
501
- session['user_name'] = user_name # Store name in session
502
- else:
503
- return redirect(url_for("login"))
504
- else:
505
- user_name = session.get('user_name') # Get name from session if it's already stored
506
-
507
- # Get the first letter of the user's name (make it uppercase for consistency)
508
- first_letter = user_name[0].upper() if user_name else "A"
509
-
510
- try:
511
- # Fetch user referral and reward points
512
- user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
513
- user_result = sf.query(user_query)
514
-
515
- if not user_result['records']:
516
- return redirect(url_for('login'))
517
-
518
- referral_code = user_result['records'][0].get('Referral__c', 'N/A')
519
- reward_points = user_result['records'][0].get('Reward_Points__c', 0)
520
-
521
- # Query to fetch Menu_Item__c records including Total_Ordered__c for best sellers
522
- menu_query = """
523
- SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
524
- FROM Menu_Item__c
525
- """
526
- result = sf.query(menu_query)
527
- food_items = result['records'] if 'records' in result else []
528
-
529
- # Ensure Total_Ordered__c has a valid value
530
- for item in food_items:
531
- if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
532
- item['Total_Ordered__c'] = 0 # Default value
533
-
534
- # Query to fetch Custom_Dish__c records created within the last 7 days with Total_Ordered__c > 10
535
- custom_dish_query = """
536
- SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
537
- FROM Custom_Dish__c
538
- WHERE CreatedDate >= LAST_N_DAYS:7
539
- """
540
- custom_dish_result = sf.query(custom_dish_query)
541
- custom_dishes = custom_dish_result['records'] if 'records' in custom_dish_result else []
542
-
543
- # Merge both Menu_Item__c and Custom_Dish__c records into the ordered menu
544
- all_items = food_items + custom_dishes
545
-
546
- # Define the order of sections, adding "Best Sellers" at the top
547
- section_order = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
548
- ordered_menu = {section: [] for section in section_order}
549
-
550
- # Sort items by Total_Ordered__c in descending order and pick top 4 as best sellers
551
- best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
552
-
553
- if selected_category == "Veg":
554
- best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
555
- elif selected_category == "Non veg":
556
- best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
557
-
558
- # Take only the top 4 best sellers after filtering
559
- best_sellers = best_sellers[:4]
560
-
561
- # Ensure "Best Sellers" is added only if there are items after filtering
562
- if best_sellers:
563
- ordered_menu["Best Sellers"] = best_sellers
564
-
565
- # Create a set to track item names already added to prevent duplicates
566
- added_item_names = set()
567
-
568
- # Filter and organize menu items based on category and section (to avoid duplicates)
569
- for item in all_items:
570
- section = item.get("Section__c", "Others") # Default to "Others" if missing
571
- if section not in ordered_menu:
572
- ordered_menu[section] = []
573
-
574
- # Skip item if it's already been added to avoid duplicates
575
- if item['Name'] in added_item_names:
576
- continue
577
-
578
- # Apply category filters
579
- if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
580
- continue
581
- if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
582
- continue
583
-
584
- ordered_menu[section].append(item)
585
- added_item_names.add(item['Name']) # Add item to the set of added items
586
- print(f"Added item to {section}: {item['Name']}") # Debugging
587
-
588
- # Remove empty sections
589
- ordered_menu = {section: items for section, items in ordered_menu.items() if items}
590
- print(f"Final ordered menu: {ordered_menu.keys()}") # Debugging
591
-
592
- categories = ["All", "Veg", "Non veg"]
593
-
594
- except Exception as e:
595
- print(f"Error fetching menu data: {str(e)}")
596
- ordered_menu = {}
597
- categories = ["All", "Veg", "Non veg"]
598
- referral_code = 'N/A'
599
- reward_points = 0
600
-
601
- # Pass the user's first letter (first_letter) to the template
602
- return render_template(
603
- "menu.html",
604
- ordered_menu=ordered_menu,
605
- categories=categories,
606
- selected_category=selected_category,
607
- referral_code=referral_code,
608
- reward_points=reward_points,
609
- user_name=user_name, # Pass name to the template
610
- first_letter=first_letter # Pass first letter to the template
611
- )
612
-
613
-
614
- @app.route("/cart", methods=["GET"])
615
- def cart():
616
- email = session.get('user_email')
617
- if not email:
618
- return redirect(url_for("login"))
619
-
620
- try:
621
- # Fetch cart items with Category and Section
622
- result = sf.query(f"""
623
- SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c
624
- FROM Cart_Item__c
625
- WHERE Customer_Email__c = '{email}'
626
- """)
627
- cart_items = result.get("records", [])
628
-
629
- subtotal = sum(item['Price__c'] for item in cart_items)
630
-
631
- # Fetch reward points
632
- customer_result = sf.query(f"""
633
- SELECT Reward_Points__c
634
- FROM Customer_Login__c
635
- WHERE Email__c = '{email}'
636
- """)
637
- reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
638
-
639
- # Fetch coupons for the user
640
- coupon_result = sf.query(f"""
641
- SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
642
- """)
643
- if coupon_result["records"]:
644
- raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
645
- coupons = raw_coupons.split("\n") if raw_coupons else []
646
- else:
647
- coupons = []
648
-
649
- # Initialize suggestions as an empty list
650
- suggestions = []
651
-
652
- # If there are items in the cart, fetch suggestions
653
- if cart_items:
654
- # Get the category and section of the first item in the cart (You can choose which item you want to base suggestions on)
655
- first_item = cart_items[0]
656
- item_category = first_item.get('Category__c', 'All') # Default to 'All' if not found
657
- item_section = first_item.get('Section__c', 'Biryanis') # Default to 'Biryanis' if not found
658
-
659
- # Define section-to-complementary section mapping
660
- complementary_sections = {
661
- 'Breads': ['Curries', 'Biryanis', 'Starters'],
662
- 'Biryanis': ['Curries', 'Starters', 'Desserts'],
663
- 'Curries': ['Biryanis', 'Breads', 'Starters'],
664
- 'Starters': ['Biryanis', 'Curries', 'Desserts'],
665
- 'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'],
666
- 'Soft Drinks': ['Starters', 'Biryanis', 'Curries']
667
- }
668
-
669
- # Get the complementary sections for the selected section
670
- suggested_sections = complementary_sections.get(item_section, [])
671
-
672
- # Fetch suggestions from the complementary sections
673
- try:
674
- for suggested_section in suggested_sections:
675
- if item_category == "All":
676
- query = f"""
677
- SELECT Name, Price__c, Image1__c
678
- FROM Menu_Item__c
679
- WHERE Section__c = '{suggested_section}'
680
- AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg')
681
- LIMIT 4
682
- """
683
- else:
684
- query = f"""
685
- SELECT Name, Price__c, Image1__c
686
- FROM Menu_Item__c
687
- WHERE Section__c = '{suggested_section}'
688
- AND Veg_NonVeg__c = '{item_category}'
689
- LIMIT 4
690
- """
691
- suggestion_result = sf.query(query)
692
- suggestions.extend(suggestion_result.get("records", [])) # Add suggestions from each section
693
-
694
- # Limit the number of suggestions to 4
695
- if len(suggestions) > 4:
696
- suggestions = suggestions[:4]
697
-
698
- except Exception as e:
699
- print(f"Error fetching suggestions: {e}")
700
-
701
- return render_template(
702
- "cart.html",
703
- cart_items=cart_items,
704
- subtotal=subtotal,
705
- reward_points=reward_points,
706
- customer_email=email,
707
- coupons=coupons,
708
- suggestions=suggestions
709
- )
710
-
711
- except Exception as e:
712
- print(f"Error fetching cart items: {e}")
713
- return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[])
714
-
715
-
716
- @app.route("/cart/add_suggestion_to_cart", methods=["POST"])
717
- def add_suggestion_to_cart():
718
- try:
719
- # Get data from the request
720
- data = request.get_json()
721
- item_name = data.get('item_name').strip()
722
- item_price = data.get('item_price')
723
- item_image = data.get('item_image')
724
- item_id = data.get('item_id')
725
- customer_email = data.get('customer_email')
726
- addons = data.get('addons', [])
727
- instructions = data.get('instructions', "")
728
-
729
- # Default values if addons and instructions are not provided
730
- addons_price = 0
731
- addons_string = "None"
732
-
733
- # Check if the customer already has this item in their cart
734
- query = f"""
735
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
736
- FROM Cart_Item__c
737
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
738
- """
739
- result = sf.query(query)
740
- cart_items = result.get("records", [])
741
-
742
- # If item already exists in the cart, update its quantity and other details
743
- if cart_items:
744
- cart_item_id = cart_items[0]['Id']
745
- existing_quantity = cart_items[0]['Quantity__c']
746
- existing_addons = cart_items[0].get('Add_Ons__c', "None")
747
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
748
- existing_instructions = cart_items[0].get('Instructions__c', "")
749
-
750
- # Combine existing and new addons
751
- combined_addons = existing_addons if existing_addons != "None" else ""
752
- if addons:
753
- combined_addons = f"{combined_addons}; {addons}".strip("; ")
754
-
755
- combined_instructions = existing_instructions
756
- if instructions:
757
- combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
758
-
759
- combined_addons_list = combined_addons.split("; ")
760
- combined_addons_price = sum(
761
- float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
762
- )
763
-
764
- # Update the cart item
765
- sf.Cart_Item__c.update(cart_item_id, {
766
- "Quantity__c": existing_quantity + 1,
767
- "Add_Ons__c": combined_addons,
768
- "Add_Ons_Price__c": combined_addons_price,
769
- "Instructions__c": combined_instructions,
770
- "Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
771
- })
772
- else:
773
- # If item doesn't exist in cart, create a new cart item
774
- total_price = float(item_price) + addons_price
775
-
776
- # Create a new cart item in Salesforce
777
- sf.Cart_Item__c.create({
778
- "Name": item_name,
779
- "Price__c": total_price,
780
- "Base_Price__c": item_price,
781
- "Quantity__c": 1,
782
- "Add_Ons_Price__c": addons_price,
783
- "Add_Ons__c": addons_string,
784
- "Image1__c": item_image,
785
- "Customer_Email__c": customer_email,
786
- "Instructions__c": instructions
787
- })
788
-
789
- return jsonify({"success": True, "message": "Item added to cart successfully."})
790
-
791
- except Exception as e:
792
- print(f"Error adding item to cart: {str(e)}")
793
- return jsonify({"success": False, "error": str(e)})
794
-
795
-
796
- @app.route('/cart/add', methods=['POST'])
797
- def add_to_cart():
798
- try:
799
- # Get data from request
800
- data = request.json
801
- item_name = data.get('itemName', '').strip()
802
- item_price = data.get('itemPrice')
803
- item_image = data.get('itemImage')
804
- addons = data.get('addons', [])
805
- instructions = data.get('instructions', '')
806
- category = data.get('category')
807
- section = data.get('section')
808
- quantity = data.get('quantity', 1) # Get the quantity field from the request
809
- customer_email = session.get('user_email')
810
-
811
- # Basic validation for required fields
812
- if not item_name or not item_price:
813
- return jsonify({"success": False, "error": "Item name and price are required."}), 400
814
-
815
- if not customer_email:
816
- return jsonify({"success": False, "error": "User email is required."}), 400
817
-
818
- # Query to check if the item is already in the cart
819
- query = f"""
820
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
821
- FROM Cart_Item__c
822
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
823
- """
824
- result = sf.query(query)
825
- cart_items = result.get("records", [])
826
-
827
- # Calculate the total price for the addons
828
- addons_price = sum(addon['price'] for addon in addons)
829
- new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
830
-
831
- # If the item is already in the cart, update it
832
- if cart_items:
833
- cart_item_id = cart_items[0]['Id']
834
- existing_quantity = cart_items[0]['Quantity__c']
835
- existing_addons = cart_items[0].get('Add_Ons__c', "None")
836
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
837
- existing_instructions = cart_items[0].get('Instructions__c', "")
838
-
839
- # Combine the new addons with the existing ones
840
- combined_addons = existing_addons if existing_addons != "None" else ""
841
- if new_addons:
842
- combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
843
-
844
- # Combine existing instructions with new instructions
845
- combined_instructions = existing_instructions
846
- if instructions:
847
- combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
848
-
849
- # Calculate total addons price
850
- combined_addons_list = combined_addons.split("; ")
851
- combined_addons_price = sum(
852
- float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
853
- )
854
-
855
- # Update the cart item in Salesforce (updating quantity)
856
- sf.Cart_Item__c.update(cart_item_id, {
857
- "Quantity__c": existing_quantity + quantity, # Add the selected quantity
858
- "Add_Ons__c": combined_addons,
859
- "Add_Ons_Price__c": combined_addons_price,
860
- "Instructions__c": combined_instructions,
861
- "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
862
- "Category__c": category,
863
- "Section__c": section
864
- })
865
- else:
866
- # If the item is not already in the cart, create a new entry
867
- addons_string = "None"
868
- if addons:
869
- addons_string = new_addons
870
-
871
- total_price = item_price * quantity + addons_price # Multiply by the quantity
872
-
873
- # Create new cart item in Salesforce
874
- sf.Cart_Item__c.create({
875
- "Name": item_name,
876
- "Price__c": total_price,
877
- "Base_Price__c": item_price,
878
- "Quantity__c": quantity, # Use the selected quantity
879
- "Add_Ons_Price__c": addons_price,
880
- "Add_Ons__c": addons_string,
881
- "Image1__c": item_image,
882
- "Customer_Email__c": customer_email,
883
- "Instructions__c": instructions,
884
- "Category__c": category,
885
- "Section__c": section
886
- })
887
-
888
- return jsonify({"success": True, "message": "Item added to cart successfully."})
889
-
890
- except KeyError as e:
891
- # Handle missing expected keys in request data
892
- return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
893
-
894
- except Exception as e:
895
- # Log the error for debugging and return a general error message
896
- print(f"Error adding item to cart: {str(e)}")
897
- return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
898
-
899
-
900
- @app.route("/cart/add_item", methods=["POST"])
901
- def add_item_to_cart():
902
- data = request.json # Extract JSON data from the request
903
- email = data.get('email') # Customer email
904
- item_name = data.get('item_name') # Item name
905
- quantity = data.get('quantity', 1) # Quantity to add (default is 1)
906
- addons = data.get('addons', []) # Add-ons for the item (optional)
907
-
908
- # Validate inputs
909
- if not email or not item_name:
910
- return jsonify({"success": False, "error": "Email and item name are required."}), 400
911
-
912
- try:
913
- # Add a new item to the cart with the provided details
914
- sf.Cart_Item__c.create({
915
- "Customer_Email__c": email, # Associate the cart item with the customer's email
916
- "Item_Name__c": item_name, # Item name
917
- "Quantity__c": quantity, # Quantity to add
918
- "Add_Ons__c": addons_string
919
- })
920
-
921
- return jsonify({"success": True, "message": "Item added to cart successfully."})
922
- except Exception as e:
923
- print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
924
- return jsonify({"success": False, "error": str(e)}), 500
925
-
926
-
927
-
928
- @app.route('/cart/remove/<item_name>', methods=['POST'])
929
- def remove_cart_item(item_name):
930
- try:
931
- customer_email = session.get('user_email')
932
- if not customer_email:
933
- return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
934
- query = f"""
935
- SELECT Id FROM Cart_Item__c
936
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
937
- """
938
- result = sf.query(query)
939
- if result['totalSize'] == 0:
940
- return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
941
- cart_item_id = result['records'][0]['Id']
942
- sf.Cart_Item__c.delete(cart_item_id)
943
- return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
944
- except Exception as e:
945
- print(f"Error: {str(e)}")
946
- return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
947
-
948
- @app.route('/api/addons', methods=['GET'])
949
- def get_addons():
950
- item_name = request.args.get('item_name')
951
- item_section = request.args.get('item_section')
952
-
953
- # Check if both item_name and item_section are provided
954
- if not item_name or not item_section:
955
- return jsonify({"success": False, "error": "Item name and section are required."}), 400
956
-
957
- try:
958
- # Fetch customization options from Salesforce based on the section
959
- query = f"""
960
- SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
961
- FROM Customization_Options__c
962
- WHERE Section__c = '{item_section}'
963
- """
964
- result = sf.query(query)
965
- addons = result.get('records', [])
966
-
967
- # Check if we found any addons
968
- if not addons:
969
- return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
970
-
971
- # Format data for frontend
972
- formatted_addons = []
973
- for addon in addons:
974
- # Ensure 'Options__c' exists and is not None
975
- options = addon.get("Options__c", "")
976
- if options: # If options are available, split them
977
- options = options.split(", ") # Convert comma-separated options into a list
978
- else:
979
- options = [] # If no options, default to an empty list
980
-
981
- formatted_addons.append({
982
- "name": addon["Name"],
983
- "type": addon["Customization_Type__c"],
984
- "options": options,
985
- "max_selections": addon.get("Max_Selections__c", 1),
986
- "extra_charge": addon.get("Extra_Charge__c", False),
987
- "extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
988
- })
989
-
990
- return jsonify({"success": True, "addons": formatted_addons})
991
-
992
- except Exception as e:
993
- # Log the exception for debugging
994
- app.logger.error(f"Error fetching addons: {str(e)}")
995
- return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
996
-
997
-
998
- @app.route("/cart/update_quantity", methods=["POST"])
999
- def update_quantity():
1000
- data = request.json # Extract JSON data from the request
1001
- email = data.get('email')
1002
- item_name = data.get('item_name')
1003
- try:
1004
- # Convert quantity to an integer
1005
- quantity = int(data.get('quantity'))
1006
- except (ValueError, TypeError):
1007
- return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
1008
-
1009
- # Validate inputs
1010
- if not email or not item_name or quantity is None:
1011
- return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
1012
-
1013
- try:
1014
- # Query the cart item in Salesforce
1015
- cart_items = sf.query(
1016
- f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
1017
- f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
1018
- )['records']
1019
-
1020
- if not cart_items:
1021
- return jsonify({"success": False, "error": "Cart item not found."}), 404
1022
-
1023
- # Retrieve the first matching record
1024
- cart_item_id = cart_items[0]['Id']
1025
- base_price = cart_items[0]['Base_Price__c']
1026
- addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
1027
-
1028
- # Calculate the new item price
1029
- new_item_price = (base_price * quantity) + addons_price
1030
-
1031
- # Update the record in Salesforce
1032
- sf.Cart_Item__c.update(cart_item_id, {
1033
- "Quantity__c": quantity,
1034
- "Price__c": new_item_price, # Update base price
1035
- })
1036
-
1037
- # Recalculate the subtotal for all items in the cart
1038
- cart_items = sf.query(f"""
1039
- SELECT Price__c, Add_Ons_Price__c
1040
- FROM Cart_Item__c
1041
- WHERE Customer_Email__c = '{email}'
1042
- """)['records']
1043
- new_subtotal = sum(item['Price__c'] for item in cart_items)
1044
-
1045
- # Return updated item price and subtotal
1046
- return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
1047
- print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
1048
- return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
1049
-
1050
- except Exception as e:
1051
- print(f"Error updating quantity: {str(e)}")
1052
- return jsonify({"success": False, "error": str(e)}), 500
1053
-
1054
- @app.route("/checkout", methods=["POST"])
1055
- def checkout():
1056
- email = session.get('user_email')
1057
- user_id = session.get('user_name')
1058
- table_number = session.get('table_number') # Retrieve table number
1059
-
1060
- print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}") # Debugging session data
1061
-
1062
- if not email or not user_id:
1063
- print("User not logged in")
1064
- return jsonify({"success": False, "message": "User not logged in"})
1065
-
1066
- try:
1067
- # Fetch the selected coupon (if any)
1068
- data = request.json
1069
- selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
1070
- # Now selected_coupon will be None if it's not provided or empty, or a valid string otherwise
1071
- print(f"Selected Coupon: {selected_coupon}") # Debugging selected coupon
1072
-
1073
- # Fetch cart items for the current user
1074
- result = sf.query(f"""
1075
- SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
1076
- FROM Cart_Item__c
1077
- WHERE Customer_Email__c = '{email}'
1078
- """)
1079
-
1080
- # Log the cart items to see if they are fetched correctly
1081
- cart_items = result.get("records", [])
1082
- print(f"Cart Items Retrieved: {cart_items}") # Debugging log
1083
-
1084
- if not cart_items:
1085
- print("Cart is empty")
1086
- return jsonify({"success": False, "message": "Cart is empty"})
1087
-
1088
- total_price = sum(item['Price__c'] for item in cart_items)
1089
- print(f"Total Price: {total_price}") # Debugging total price calculation
1090
-
1091
- discount = 0
1092
-
1093
- # Fetch the user's existing coupons
1094
- coupon_query = sf.query(f"""
1095
- SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
1096
- """)
1097
- print(f"Coupon Query Results: {coupon_query}") # Debugging coupon query results
1098
-
1099
- has_coupons = bool(coupon_query["records"])
1100
- print(f"Has Coupons: {has_coupons}") # Debugging coupon presence check
1101
-
1102
- if selected_coupon:
1103
- # Apply 10% discount if a valid coupon is selected
1104
- discount = total_price * 0.10 # Example: 10% discount
1105
- print(f"Discount Applied: {discount}") # Debugging discount calculation
1106
-
1107
- referral_coupon_id = coupon_query["records"][0]["Id"]
1108
- print(f"Referral Coupon ID: {referral_coupon_id}") # Debugging referral coupon ID
1109
-
1110
- existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
1111
- print(f"Existing Coupons Before Removal: {existing_coupons}") # Debugging existing coupons
1112
-
1113
- # Remove the selected coupon from the list of existing coupons
1114
- updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
1115
- updated_coupons_str = "\n".join(updated_coupons).strip()
1116
-
1117
- print(f"Updated Coupons After Removal: {updated_coupons}") # Debugging updated coupons
1118
-
1119
- # If no coupons remain, set the field to None (not empty string)
1120
- if not updated_coupons:
1121
- updated_coupons_str = None # Set to None if no coupons are left
1122
- print("No Coupons Remaining. Setting to None") # Debugging no coupons left
1123
-
1124
- # Update the Referral_Coupon__c record
1125
- print(f"Updating Referral Coupon: {updated_coupons_str}") # Debugging update to Salesforce
1126
- sf.Referral_Coupon__c.update(referral_coupon_id, {
1127
- "Coupon_Code__c": updated_coupons_str
1128
- })
1129
- else:
1130
- # If no coupon is selected, add reward points
1131
- reward_points_to_add = total_price * 0.10 # Example: 10% reward points
1132
- print(f"Reward Points to Add: {reward_points_to_add}") # Debugging reward points
1133
-
1134
- # Fetch current reward points
1135
- customer_record = sf.query(f"""
1136
- SELECT Id, Reward_Points__c FROM Customer_Login__c
1137
- WHERE Email__c = '{email}'
1138
- """)
1139
- print(f"Customer Reward Points Query: {customer_record}") # Debugging customer reward points query
1140
-
1141
- customer = customer_record.get("records", [])[0] if customer_record else None
1142
- if customer:
1143
- current_reward_points = customer.get("Reward_Points__c") or 0
1144
- print(f"Current Reward Points: {current_reward_points}") # Debugging current reward points
1145
- new_reward_points = current_reward_points + reward_points_to_add
1146
- print(f"New Reward Points: {new_reward_points}") # Debugging new reward points calculation
1147
-
1148
- # Update reward points
1149
- sf.Customer_Login__c.update(customer["Id"], {
1150
- "Reward_Points__c": new_reward_points
1151
- })
1152
-
1153
- # Final total bill calculation
1154
- total_bill = total_price - discount
1155
- print(f"Total Bill After Discount: {total_bill}") # Debugging final total bill
1156
-
1157
- # Store all order details (before deleting cart items)
1158
- order_details = "\n".join(
1159
- f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
1160
- f"Instructions: {item.get('Instructions__c', 'None')} | "
1161
- f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
1162
- for item in cart_items
1163
- )
1164
- print(f"Order Details: {order_details}") # Debugging order details
1165
-
1166
- # Fetch Customer ID from Customer_Login__c
1167
- customer_query = sf.query(f"""
1168
- SELECT Id FROM Customer_Login__c
1169
- WHERE Email__c = '{email}'
1170
- """)
1171
-
1172
- customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
1173
- print(f"Customer ID: {customer_id}") # Debugging customer ID retrieval
1174
-
1175
- if not customer_id:
1176
- print("Customer record not found")
1177
- return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
1178
- table_number = table_number if table_number != 'null' else None # Ensure 'null' string is replaced with None
1179
- # Store order data
1180
- order_data = {
1181
- "Customer_Name__c": user_id,
1182
- "Customer_Email__c": email,
1183
- "Total_Amount__c": total_price,
1184
- "Discount__c": discount,
1185
- "Total_Bill__c": total_bill,
1186
- "Order_Status__c": "Pending",
1187
- "Customer2__c": customer_id,
1188
- "Order_Details__c": order_details,
1189
- "Table_Number__c": table_number # Store table number
1190
- }
1191
- print(f"Order Data: {order_data}") # Debugging order data
1192
-
1193
- # Create the order in Salesforce
1194
- order_response = sf.Order__c.create(order_data)
1195
- print(f"Order Response: {order_response}") # Debugging order creation response
1196
-
1197
- # Ensure the order was created successfully before deleting cart items
1198
- if order_response:
1199
- # Only delete cart items after the order is created
1200
- for item in cart_items:
1201
- print(f"Deleting Cart Item: {item['Id']}") # Debugging cart item deletion
1202
- sf.Cart_Item__c.delete(item["Id"])
1203
-
1204
- return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill})
1205
-
1206
- except Exception as e:
1207
- print(f"Error during checkout: {str(e)}") # Debugging error message
1208
- return jsonify({"success": False, "error": str(e)})
1209
-
1210
-
1211
- @app.route("/order", methods=["GET"])
1212
- def order_summary():
1213
- email = session.get('user_email') # Fetch logged-in user's email
1214
- if not email:
1215
- return redirect(url_for("login"))
1216
-
1217
- try:
1218
- # Fetch the most recent order for the user
1219
- result = sf.query(f"""
1220
- SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
1221
- FROM Order__c
1222
- WHERE Customer_Email__c = '{email}'
1223
- ORDER BY CreatedDate DESC
1224
- LIMIT 1
1225
- """)
1226
- order = result.get("records", [])[0] if result.get("records") else None
1227
-
1228
- if not order:
1229
- return render_template("order.html", order=None)
1230
-
1231
- return render_template("order.html", order=order)
1232
- except Exception as e:
1233
- print(f"Error fetching order details: {str(e)}")
1234
- return render_template("order.html", order=None, error=str(e))
1235
- import smtplib
1236
- from email.mime.multipart import MIMEMultipart
1237
- from email.mime.text import MIMEText
1238
-
1239
-
1240
-
1241
 
1242
  if __name__ == "__main__":
1243
  app.run(debug=True, host="0.0.0.0", port=7860)
 
4
  from salesforce import get_salesforce_connection
5
  from datetime import timedelta
6
  import os
7
+ import smtplib
8
+ from email.mime.multipart import MIMEMultipart
9
+ from email.mime.text import MIMEText
10
 
11
  # Initialize Flask app and Salesforce connection
12
  print("Starting app...")
 
489
  return render_template("login.html", error=f"Error: {str(e)}")
490
 
491
  return render_template("login.html")
492
+ # Register Blueprints for each functionality
493
+ app.register_blueprint(menu_blueprint)
494
+ app.register_blueprint(cart_blueprint)
495
+ app.register_blueprint(order_blueprint)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
 
497
  if __name__ == "__main__":
498
  app.run(debug=True, host="0.0.0.0", port=7860)