Spaces:
Build error
Build error
Update menu.py
Browse files12345678910115 unmodified lines171819202122232425262728297 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231 unmodified line1251261271281291301311321331341351361371381391401411421431442 unmodified lines1471481491501511521531541551561571581591601611621631641657 unmodified lines1731741751761771781791801811821831841851862 unmodified lines1891901911921931941951961971981992002012022032042052 unmodified lines2082092102112122132142152162172181 unmodified line2202212222232242252262272282292302312322332342352362372382392402412422432442 unmodified lines2472482492502512522532542552562572582592602612622632642656 unmodified lines272273274275276277278279280281282283284285from flask import Blueprint, render_template, request, session, jsonify # Added jsonify importfrom salesforce import get_salesforce_connectionmenu_blueprint = Blueprint('menu', __name__)# Initialize Salesforce connectionsf = get_salesforce_connection()@menu_blueprint.route("/menu", methods=["GET", "POST"])def menu():selected_category = request.args.get("category", "All")5 unmodified linesif user_email:session['user_email'] = user_emailsession['user_name'] = user_name # Store name in sessionelse: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:7 unmodified linesreferral_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 sellersmenu_query = """SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__cFROM Menu_Item__c"""result = sf.query(menu_query)food_items = result['records'] if 'records' in result else []# Ensure Total_Ordered__c has a valid valuefor 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 > 10custom_dish_query = """SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__cFROM Custom_Dish__cWHERE 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 menuall_items = food_items + custom_dishes# Define the order of sections, adding "Best Sellers" at the topsection_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 sellersbest_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 filteringbest_sellers = best_sellers[:4]# Ensure "Best Sellers" is added only if there are items after filteringif best_sellers:ordered_menu["Best Sellers"] = best_sellers# Create a set to track item names already added to prevent duplicatesadded_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 missingif section not in ordered_menu:ordered_menu[section] = []# Skip item if it's already been added to avoid duplicatesif item['Name'] in added_item_names:continue# Apply category filtersif selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:continueif selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:continueordered_menu[section].append(item)added_item_names.add(item['Name']) # Add item to the set of added itemsprint(f"Added item to {section}: {item['Name']}") # Debugging# Remove empty sectionsordered_menu = {section: items for section, items in ordered_menu.items() if items}print(f"Final ordered menu: {ordered_menu.keys()}") # Debuggingcategories = ["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 templatereturn render_template("menu.html",ordered_menu=ordered_menu,1 unmodified lineselected_category=selected_category,referral_code=referral_code,reward_points=reward_points,user_name=user_name, # Pass name to the templatefirst_letter=first_letter # Pass first letter to the template)@menu_blueprint.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 providedif not item_name or not item_section:return jsonify({"success": False, "error": "Item name and section are required."}), 400try:# Fetch customization options from Salesforce based on the sectionquery = f"""SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__cFROM Customization_Options__c2 unmodified linesresult = sf.query(query)addons = result.get('records', [])# Check if we found any addonsif not addons:return jsonify({"success": False, "error": "No customization options found for the given section."}), 404# Format data for frontendformatted_addons = []for addon in addons:# Ensure 'Options__c' exists and is not Noneoptions = addon.get("Options__c", "")if options: # If options are available, split themoptions = options.split(", ") # Convert comma-separated options into a listelse:options = [] # If no options, default to an empty listformatted_addons.append({"name": addon["Name"],7 unmodified linesreturn jsonify({"success": True, "addons": formatted_addons})except Exception as e:# Log the exception for debuggingapp.logger.error(f"Error fetching addons: {str(e)}")return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500@menu_blueprint.route('/cart/add', methods=['POST'])def add_to_cart():try:# Get data from requestdata = request.jsonitem_name = data.get('itemName', '').strip()item_price = data.get('itemPrice')2 unmodified linesinstructions = data.get('instructions', '')category = data.get('category')section = data.get('section')quantity = data.get('quantity', 1) # Get the quantity field from the requestcustomer_email = session.get('user_email')# Basic validation for required fieldsif not item_name or not item_price:return jsonify({"success": False, "error": "Item name and price are required."}), 400if not customer_email:return jsonify({"success": False, "error": "User email is required."}), 400# Query to check if the item is already in the cartquery = f"""SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__cFROM Cart_Item__c2 unmodified linesresult = sf.query(query)cart_items = result.get("records", [])# Calculate the total price for the addonsaddons_price = sum(addon['price'] for addon in addons)new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])# If the item is already in the cart, update itif cart_items:cart_item_id = cart_items[0]['Id']existing_quantity = cart_items[0]['Quantity__c']1 unmodified lineexisting_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)existing_instructions = cart_items[0].get('Instructions__c', "")# Combine the new addons with the existing onescombined_addons = existing_addons if existing_addons != "None" else ""if new_addons:combined_addons = f"{combined_addons}; {new_addons}".strip("; ")# Combine existing instructions with new instructionscombined_instructions = existing_instructionsif instructions:combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")# Calculate total addons pricecombined_addons_list = combined_addons.split("; ")combined_addons_price = sum(float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon)# Update the cart item in Salesforce (updating quantity)sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": existing_quantity + quantity, # Add the selected quantity"Add_Ons__c": combined_addons,"Add_Ons_Price__c": combined_addons_price,"Instructions__c": combined_instructions,2 unmodified lines"Section__c": section})else:# If the item is not already in the cart, create a new entryaddons_string = "None"if addons:addons_string = new_addonstotal_price = item_price * quantity + addons_price # Multiply by the quantity# Create new cart item in Salesforcesf.Cart_Item__c.create({"Name": item_name,"Price__c": total_price,"Base_Price__c": item_price,"Quantity__c": quantity, # Use the selected quantity"Add_Ons_Price__c": addons_price,"Add_Ons__c": addons_string,"Image1__c": item_image,6 unmodified linesreturn jsonify({"success": True, "message": "Item added to cart successfully."})except KeyError as e:# Handle missing expected keys in request datareturn jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400except Exception as e:# Log the error for debugging and return a general error messageprint(f"Error adding item to cart: {str(e)}")return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 50012345678910111213141516171819202122232425262728293031323334353637383940414243444546475 unmodified lines5354555657585960616263647 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641 unmodified line1661671681691701711721731741751761771781791801811821831842 unmodified lines1871881891901911921931941951961971981992002012027 unmodified lines2102112122132142152162172182192202212 unmodified lines2242252262272282292302312322332342352362372382 unmodified lines2412422432442452462472482491 unmodified line2512522532542552562572582592602612622632642652662672682692702712 unmodified lines2742752762772782792802812822832842852862872882892906 unmodified lines297298299300301302303304from flask import Blueprint, render_template, request, session, jsonify, redirect, url_forfrom salesforce import get_salesforce_connectionimport osmenu_blueprint = Blueprint('menu', __name__)# Initialize Salesforce connectionsf = get_salesforce_connection()# Constants for video handlingSTATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')PLACEHOLDER_VIDEO = 'placeholder.mp4'PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]# Create placeholder video at startup if it doesn't existif not os.path.exists(PLACEHOLDER_PATH):open(PLACEHOLDER_PATH, 'wb').close()print(f"Created placeholder video at {PLACEHOLDER_PATH}")def get_valid_video_path(item_name, video_url=None):"""Get valid video path for item with placeholder fallbackPriority: 1. Video1__c from Salesforce 2. placeholder.mp4"""# First try: Video1__c from Salesforce if providedif video_url:# If it's a complete URL (http/https)if video_url.startswith(('http://', 'https://')):return video_url# If it's a relative path (/videos/xxx.mp4)elif video_url.startswith('/'):return video_url# If it's a Salesforce File ID (starts with '069')elif video_url.startswith('069'):return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"# Final fallback: placeholder.mp4if not os.path.exists(PLACEHOLDER_PATH):open(PLACEHOLDER_PATH, 'wb').close()print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")return f"/static/{PLACEHOLDER_VIDEO}"@menu_blueprint.route("/menu", methods=["GET", "POST"])def menu():selected_category = request.args.get("category", "All")5 unmodified linesif user_email:session['user_email'] = user_emailsession['user_name'] = user_nameelse:return redirect(url_for("login"))else:user_name = session.get('user_name')first_letter = user_name[0].upper() if user_name else "A"try:7 unmodified linesreferral_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 Video1__cmenu_query = """SELECT Name, Price__c, Description__c, Image1__c, Image2__c,Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__cFROM Menu_Item__c"""result = sf.query(menu_query)food_items = result['records'] if 'records' in result else []# Process items and add video pathsfor item in food_items:if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:item['Total_Ordered__c'] = 0item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))# Query to fetch Custom_Dish__c recordscustom_dish_query = """SELECT Name, Price__c, Description__c, Image1__c, Image2__c,Veg_NonVeg__c, Section__c, Total_Ordered__cFROM Custom_Dish__cWHERE CreatedDate >= LAST_N_DAYS:7"""custom_dish_result = sf.query(custom_dish_query)custom_dishes = custom_dish_result.get('records', [])# Process custom dishes and add video pathsfor item in custom_dishes:if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:item['Total_Ordered__c'] = 0item['Video1__c'] = get_valid_video_path(item['Name'])# Merge both Menu_Item__c and Custom_Dish__c recordsall_items = food_items + custom_dishesordered_menu = {section: [] for section in SECTION_ORDER}# Process best sellersbest_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"]]best_sellers = best_sellers[:4]if best_sellers:ordered_menu["Best Sellers"] = best_sellers# Organize other sectionsadded_item_names = set()for item in all_items:section = item.get("Section__c", "Others")if section not in ordered_menu:ordered_menu[section] = []if item['Name'] in added_item_names:continueif selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:continueif selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:continueordered_menu[section].append(item)added_item_names.add(item['Name'])ordered_menu = {section: items for section, items in ordered_menu.items() if items}categories = ["All", "Veg", "Non veg"]except Exception as e:print(f"Error fetching menu data: {str(e)}")# Fallback data with video supportordered_menu = {section: [] for section in SECTION_ORDER}best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]ordered_menu["Best Sellers"] = [{"Name": name,"Price__c": "12.99","Description__c": f"Popular {name}","Image1__c": "/static/placeholder.jpg","Video1__c": get_valid_video_path(name),"Total_Ordered__c": 100,"Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg"} for name in best_sellers]categories = ["All", "Veg", "Non veg"]referral_code = 'N/A'reward_points = 0return render_template("menu.html",ordered_menu=ordered_menu,1 unmodified lineselected_category=selected_category,referral_code=referral_code,reward_points=reward_points,user_name=user_name,first_letter=first_letter)@menu_blueprint.route('/api/addons', methods=['GET'])def get_addons():item_name = request.args.get('item_name')item_section = request.args.get('item_section')if not item_name or not item_section:return jsonify({"success": False, "error": "Item name and section are required."}), 400try:query = f"""SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__cFROM Customization_Options__c2 unmodified linesresult = sf.query(query)addons = result.get('records', [])if not addons:return jsonify({"success": False, "error": "No customization options found for the given section."}), 404formatted_addons = []for addon in addons:options = addon.get("Options__c", "")if options:options = options.split(", ")else:options = []formatted_addons.append({"name": addon["Name"],7 unmodified linesreturn jsonify({"success": True, "addons": formatted_addons})except Exception as e:print(f"Error fetching addons: {str(e)}")return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500@menu_blueprint.route('/cart/add', methods=['POST'])def add_to_cart():try:data = request.jsonitem_name = data.get('itemName', '').strip()item_price = data.get('itemPrice')2 unmodified linesinstructions = data.get('instructions', '')category = data.get('category')section = data.get('section')quantity = data.get('quantity', 1)customer_email = session.get('user_email')if not item_name or not item_price:return jsonify({"success": False, "error": "Item name and price are required."}), 400if not customer_email:return jsonify({"success": False, "error": "User email is required."}), 400query = f"""SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__cFROM Cart_Item__c2 unmodified linesresult = sf.query(query)cart_items = result.get("records", [])addons_price = sum(addon['price'] for addon in addons)new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])if cart_items:cart_item_id = cart_items[0]['Id']existing_quantity = cart_items[0]['Quantity__c']1 unmodified lineexisting_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)existing_instructions = cart_items[0].get('Instructions__c', "")combined_addons = existing_addons if existing_addons != "None" else ""if new_addons:combined_addons = f"{combined_addons}; {new_addons}".strip("; ")combined_instructions = existing_instructionsif instructions:combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")combined_addons_list = combined_addons.split("; ")combined_addons_price = sum(float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon)sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": existing_quantity + quantity,"Add_Ons__c": combined_addons,"Add_Ons_Price__c": combined_addons_price,"Instructions__c": combined_instructions,2 unmodified lines"Section__c": section})else:addons_string = "None"if addons:addons_string = new_addonstotal_price = item_price * quantity + addons_pricesf.Cart_Item__c.create({"Name": item_name,"Price__c": total_price,"Base_Price__c": item_price,"Quantity__c": quantity,"Add_Ons_Price__c": addons_price,"Add_Ons__c": addons_string,"Image1__c": item_image,6 unmodified linesreturn jsonify({"success": True, "message": "Item added to cart successfully."})except KeyError as e:return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400except Exception as e:print(f"Error adding item to cart: {str(e)}")return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
menu.py+87-68