File size: 7,754 Bytes
6c1ecc9 d5a438f 6c1ecc9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
from flask import Blueprint, render_template, request
from salesforce import get_salesforce_connection
menu_blueprint = Blueprint('menu', __name__)
# Initialize Salesforce connection
sf = get_salesforce_connection()
@app.route("/menu", methods=["GET", "POST"])
def menu():
selected_category = request.args.get("category", "All")
user_email = session.get('user_email')
if not user_email:
user_email = request.args.get("email")
user_name = request.args.get("name")
if user_email:
session['user_email'] = user_email
session['user_name'] = user_name # Store name in session
else:
return redirect(url_for("login"))
else:
user_name = session.get('user_name') # Get name from session if it's already stored
# Get the first letter of the user's name (make it uppercase for consistency)
first_letter = user_name[0].upper() if user_name else "A"
try:
# Fetch user referral and reward points
user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
user_result = sf.query(user_query)
if not user_result['records']:
return redirect(url_for('login'))
referral_code = user_result['records'][0].get('Referral__c', 'N/A')
reward_points = user_result['records'][0].get('Reward_Points__c', 0)
# Query to fetch Menu_Item__c records including Total_Ordered__c for best sellers
menu_query = """
SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
FROM Menu_Item__c
"""
result = sf.query(menu_query)
food_items = result['records'] if 'records' in result else []
# Ensure Total_Ordered__c has a valid value
for item in food_items:
if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
item['Total_Ordered__c'] = 0 # Default value
# Query to fetch Custom_Dish__c records created within the last 7 days with Total_Ordered__c > 10
custom_dish_query = """
SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
FROM Custom_Dish__c
WHERE CreatedDate >= LAST_N_DAYS:7
"""
custom_dish_result = sf.query(custom_dish_query)
custom_dishes = custom_dish_result['records'] if 'records' in custom_dish_result else []
# Merge both Menu_Item__c and Custom_Dish__c records into the ordered menu
all_items = food_items + custom_dishes
# Define the order of sections, adding "Best Sellers" at the top
section_order = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
ordered_menu = {section: [] for section in section_order}
# Sort items by Total_Ordered__c in descending order and pick top 4 as best sellers
best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
if selected_category == "Veg":
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
elif selected_category == "Non veg":
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
# Take only the top 4 best sellers after filtering
best_sellers = best_sellers[:4]
# Ensure "Best Sellers" is added only if there are items after filtering
if best_sellers:
ordered_menu["Best Sellers"] = best_sellers
# Create a set to track item names already added to prevent duplicates
added_item_names = set()
# Filter and organize menu items based on category and section (to avoid duplicates)
for item in all_items:
section = item.get("Section__c", "Others") # Default to "Others" if missing
if section not in ordered_menu:
ordered_menu[section] = []
# Skip item if it's already been added to avoid duplicates
if item['Name'] in added_item_names:
continue
# Apply category filters
if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
continue
if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
continue
ordered_menu[section].append(item)
added_item_names.add(item['Name']) # Add item to the set of added items
print(f"Added item to {section}: {item['Name']}") # Debugging
# Remove empty sections
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
print(f"Final ordered menu: {ordered_menu.keys()}") # Debugging
categories = ["All", "Veg", "Non veg"]
except Exception as e:
print(f"Error fetching menu data: {str(e)}")
ordered_menu = {}
categories = ["All", "Veg", "Non veg"]
referral_code = 'N/A'
reward_points = 0
# Pass the user's first letter (first_letter) to the template
return render_template(
"menu.html",
ordered_menu=ordered_menu,
categories=categories,
selected_category=selected_category,
referral_code=referral_code,
reward_points=reward_points,
user_name=user_name, # Pass name to the template
first_letter=first_letter # Pass first letter to the template
)
@app.route('/api/addons', methods=['GET'])
def get_addons():
item_name = request.args.get('item_name')
item_section = request.args.get('item_section')
# Check if both item_name and item_section are provided
if not item_name or not item_section:
return jsonify({"success": False, "error": "Item name and section are required."}), 400
try:
# Fetch customization options from Salesforce based on the section
query = f"""
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
FROM Customization_Options__c
WHERE Section__c = '{item_section}'
"""
result = sf.query(query)
addons = result.get('records', [])
# Check if we found any addons
if not addons:
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
# Format data for frontend
formatted_addons = []
for addon in addons:
# Ensure 'Options__c' exists and is not None
options = addon.get("Options__c", "")
if options: # If options are available, split them
options = options.split(", ") # Convert comma-separated options into a list
else:
options = [] # If no options, default to an empty list
formatted_addons.append({
"name": addon["Name"],
"type": addon["Customization_Type__c"],
"options": options,
"max_selections": addon.get("Max_Selections__c", 1),
"extra_charge": addon.get("Extra_Charge__c", False),
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
})
return jsonify({"success": True, "addons": formatted_addons})
except Exception as e:
# Log the exception for debugging
app.logger.error(f"Error fetching addons: {str(e)}")
return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
|