Update menu.py
Browse files
menu.py
CHANGED
|
@@ -1,35 +1,28 @@
|
|
| 1 |
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
|
|
|
|
| 2 |
import os
|
| 3 |
-
from salesforce import get_salesforce_connection # Assuming this is your Salesforce connector
|
| 4 |
-
import logging
|
| 5 |
-
|
| 6 |
-
# Setup logging for debugging
|
| 7 |
-
logging.basicConfig(level=logging.DEBUG)
|
| 8 |
-
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
menu_blueprint = Blueprint('menu', __name__)
|
| 11 |
|
| 12 |
# Initialize Salesforce connection
|
| 13 |
-
|
| 14 |
-
sf = get_salesforce_connection()
|
| 15 |
-
except Exception as e:
|
| 16 |
-
logger.error(f"Failed to initialize Salesforce connection: {str(e)}")
|
| 17 |
-
sf = None
|
| 18 |
|
| 19 |
-
# Constants
|
| 20 |
STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')
|
| 21 |
PLACEHOLDER_VIDEO = 'placeholder.mp4'
|
| 22 |
PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
|
| 23 |
SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
os.makedirs(STATIC_DIR, exist_ok=True)
|
| 27 |
if not os.path.exists(PLACEHOLDER_PATH):
|
| 28 |
open(PLACEHOLDER_PATH, 'wb').close()
|
| 29 |
-
|
| 30 |
|
| 31 |
def get_valid_video_path(item_name, video_url=None):
|
| 32 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 33 |
if video_url:
|
| 34 |
if video_url.startswith(('http://', 'https://')):
|
| 35 |
return video_url
|
|
@@ -37,6 +30,11 @@ def get_valid_video_path(item_name, video_url=None):
|
|
| 37 |
return video_url
|
| 38 |
elif video_url.startswith('069'):
|
| 39 |
return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return f"/static/{PLACEHOLDER_VIDEO}"
|
| 41 |
|
| 42 |
@menu_blueprint.route("/menu", methods=["GET", "POST"])
|
|
@@ -47,125 +45,134 @@ def menu():
|
|
| 47 |
if not user_email:
|
| 48 |
user_email = request.args.get("email")
|
| 49 |
user_name = request.args.get("name")
|
| 50 |
-
|
|
|
|
| 51 |
session['user_email'] = user_email
|
| 52 |
session['user_name'] = user_name
|
| 53 |
else:
|
| 54 |
-
logger.warning("No user email in session or args, redirecting to login")
|
| 55 |
return redirect(url_for("login"))
|
| 56 |
else:
|
| 57 |
user_name = session.get('user_name')
|
| 58 |
|
| 59 |
first_letter = user_name[0].upper() if user_name else "A"
|
| 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 |
best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
|
| 155 |
ordered_menu["Best Sellers"] = [{
|
| 156 |
"Name": name,
|
| 157 |
"Price__c": "12.99",
|
| 158 |
"Description__c": f"Popular {name}",
|
| 159 |
"Image1__c": "/static/placeholder.jpg",
|
| 160 |
-
"Image2__c": "/static/placeholder.jpg",
|
| 161 |
"Video1__c": get_valid_video_path(name),
|
| 162 |
"Total_Ordered__c": 100,
|
| 163 |
"Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
|
| 164 |
-
"Ingredients__c":
|
| 165 |
"NutritionalInfo__c": "Calories: 500, Protein: 20g",
|
| 166 |
-
"Allergens__c": "Contains nuts, dairy"
|
| 167 |
-
"Section__c": "Best Sellers"
|
| 168 |
} for name in best_sellers]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
return render_template(
|
| 171 |
"menu.html",
|
|
@@ -181,64 +188,121 @@ def menu():
|
|
| 181 |
|
| 182 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
| 183 |
def get_addons():
|
| 184 |
-
item_name = request.args.get('item_name')
|
| 185 |
-
item_section = request.args.get('item_section')
|
|
|
|
| 186 |
if not item_name or not item_section:
|
| 187 |
-
return jsonify({"success": False, "error": "Item name and section required"}), 400
|
|
|
|
| 188 |
try:
|
| 189 |
-
query = f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
result = sf.query(query)
|
| 191 |
addons = result.get('records', [])
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
"
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
return jsonify({"success": True, "addons": formatted_addons})
|
|
|
|
| 201 |
except Exception as e:
|
| 202 |
-
|
| 203 |
-
return jsonify({"success": False, "error": "
|
| 204 |
|
| 205 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
| 206 |
def add_to_cart():
|
| 207 |
try:
|
| 208 |
-
data = request.
|
| 209 |
-
item_name = data.get('itemName', '')
|
| 210 |
-
item_price =
|
| 211 |
-
item_image = data.get('itemImage'
|
| 212 |
addons = data.get('addons', [])
|
| 213 |
instructions = data.get('instructions', '')
|
| 214 |
-
category = data.get('category'
|
| 215 |
-
section = data.get('section'
|
| 216 |
-
quantity =
|
| 217 |
customer_email = session.get('user_email')
|
| 218 |
|
| 219 |
-
if not item_name or not
|
| 220 |
-
return jsonify({"success": False, "error": "
|
| 221 |
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
total_price = item_price * quantity + addons_price
|
| 225 |
|
| 226 |
-
query = f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
result = sf.query(query)
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
})
|
| 234 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
sf.Cart_Item__c.create({
|
| 236 |
"Name": item_name,
|
| 237 |
"Price__c": total_price,
|
| 238 |
"Base_Price__c": item_price,
|
| 239 |
"Quantity__c": quantity,
|
| 240 |
"Add_Ons_Price__c": addons_price,
|
| 241 |
-
"Add_Ons__c":
|
| 242 |
"Image1__c": item_image,
|
| 243 |
"Customer_Email__c": customer_email,
|
| 244 |
"Instructions__c": instructions,
|
|
@@ -246,10 +310,11 @@ def add_to_cart():
|
|
| 246 |
"Section__c": section
|
| 247 |
})
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
return jsonify({"success":
|
|
|
|
| 253 |
except Exception as e:
|
| 254 |
-
|
| 255 |
-
return jsonify({"success": False, "error": "
|
|
|
|
| 1 |
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
|
| 2 |
+
from salesforce import get_salesforce_connection
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
menu_blueprint = Blueprint('menu', __name__)
|
| 6 |
|
| 7 |
# Initialize Salesforce connection
|
| 8 |
+
sf = get_salesforce_connection()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# Constants for video handling
|
| 11 |
STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')
|
| 12 |
PLACEHOLDER_VIDEO = 'placeholder.mp4'
|
| 13 |
PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
|
| 14 |
SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
|
| 15 |
|
| 16 |
+
# Create placeholder video at startup if it doesn't exist
|
|
|
|
| 17 |
if not os.path.exists(PLACEHOLDER_PATH):
|
| 18 |
open(PLACEHOLDER_PATH, 'wb').close()
|
| 19 |
+
print(f"Created placeholder video at {PLACEHOLDER_PATH}")
|
| 20 |
|
| 21 |
def get_valid_video_path(item_name, video_url=None):
|
| 22 |
+
"""
|
| 23 |
+
Get valid video path for item with placeholder fallback
|
| 24 |
+
Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
|
| 25 |
+
"""
|
| 26 |
if video_url:
|
| 27 |
if video_url.startswith(('http://', 'https://')):
|
| 28 |
return video_url
|
|
|
|
| 30 |
return video_url
|
| 31 |
elif video_url.startswith('069'):
|
| 32 |
return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
|
| 33 |
+
|
| 34 |
+
if not os.path.exists(PLACEHOLDER_PATH):
|
| 35 |
+
open(PLACEHOLDER_PATH, 'wb').close()
|
| 36 |
+
print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
|
| 37 |
+
|
| 38 |
return f"/static/{PLACEHOLDER_VIDEO}"
|
| 39 |
|
| 40 |
@menu_blueprint.route("/menu", methods=["GET", "POST"])
|
|
|
|
| 45 |
if not user_email:
|
| 46 |
user_email = request.args.get("email")
|
| 47 |
user_name = request.args.get("name")
|
| 48 |
+
|
| 49 |
+
if user_email:
|
| 50 |
session['user_email'] = user_email
|
| 51 |
session['user_name'] = user_name
|
| 52 |
else:
|
|
|
|
| 53 |
return redirect(url_for("login"))
|
| 54 |
else:
|
| 55 |
user_name = session.get('user_name')
|
| 56 |
|
| 57 |
first_letter = user_name[0].upper() if user_name else "A"
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
# Fetch user referral and reward points
|
| 61 |
+
user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
| 62 |
+
user_result = sf.query(user_query)
|
| 63 |
+
|
| 64 |
+
if not user_result['records']:
|
| 65 |
+
return redirect(url_for('login'))
|
| 66 |
+
|
| 67 |
+
referral_code = user_result['records'][0].get('Referral__c', 'N/A')
|
| 68 |
+
reward_points = user_result['records'][0].get('Reward_Points__c', 0)
|
| 69 |
+
|
| 70 |
+
# Get cart item count
|
| 71 |
+
cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
|
| 72 |
+
cart_count_result = sf.query(cart_query)
|
| 73 |
+
cart_item_count = cart_count_result['totalSize']
|
| 74 |
+
|
| 75 |
+
# Query to fetch Menu_Item__c records including new fields
|
| 76 |
+
menu_query = """
|
| 77 |
+
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 78 |
+
Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
|
| 79 |
+
Ingredients__c, NutritionalInfo__c, Allergens__c
|
| 80 |
+
FROM Menu_Item__c
|
| 81 |
+
"""
|
| 82 |
+
result = sf.query(menu_query)
|
| 83 |
+
food_items = result['records'] if 'records' in result else []
|
| 84 |
+
|
| 85 |
+
# Process items and add video paths
|
| 86 |
+
for item in food_items:
|
| 87 |
+
if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
|
| 88 |
+
item['Total_Ordered__c'] = 0
|
| 89 |
+
item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
|
| 90 |
+
# Ensure all fields have default values if missing
|
| 91 |
+
item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
|
| 92 |
+
item['Description__c'] = item.get('Description__c', 'No description available')
|
| 93 |
+
item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', 'Not available')
|
| 94 |
+
item['Allergens__c'] = item.get('Allergens__c', 'None known')
|
| 95 |
+
|
| 96 |
+
# Query to fetch Custom_Dish__c records including new fields
|
| 97 |
+
custom_dish_query = """
|
| 98 |
+
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 99 |
+
Veg_NonVeg__c, Section__c, Total_Ordered__c,
|
| 100 |
+
Ingredients__c, NutritionalInfo__c, Allergens__c
|
| 101 |
+
FROM Custom_Dish__c
|
| 102 |
+
WHERE CreatedDate >= LAST_N_DAYS:7
|
| 103 |
+
"""
|
| 104 |
+
custom_dish_result = sf.query(custom_dish_query)
|
| 105 |
+
custom_dishes = custom_dish_result.get('records', [])
|
| 106 |
+
|
| 107 |
+
# Process custom dishes and add video paths
|
| 108 |
+
for item in custom_dishes:
|
| 109 |
+
if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
|
| 110 |
+
item['Total_Ordered__c'] = 0
|
| 111 |
+
item['Video1__c'] = get_valid_video_path(item['Name'])
|
| 112 |
+
# Ensure all fields have default values if missing
|
| 113 |
+
item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
|
| 114 |
+
item['Description__c'] = item.get('Description__c', 'No description available')
|
| 115 |
+
item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', 'Not available')
|
| 116 |
+
item['Allergens__c'] = item.get('Allergens__c', 'None known')
|
| 117 |
+
|
| 118 |
+
# Merge both Menu_Item__c and Custom_Dish__c records
|
| 119 |
+
all_items = food_items + custom_dishes
|
| 120 |
+
ordered_menu = {section: [] for section in SECTION_ORDER}
|
| 121 |
+
|
| 122 |
+
# Process best sellers
|
| 123 |
+
best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
|
| 124 |
+
|
| 125 |
+
if selected_category == "Veg":
|
| 126 |
+
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
|
| 127 |
+
elif selected_category == "Non veg":
|
| 128 |
+
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
|
| 129 |
+
|
| 130 |
+
best_sellers = best_sellers[:4]
|
| 131 |
+
if best_sellers:
|
| 132 |
+
ordered_menu["Best Sellers"] = best_sellers
|
| 133 |
+
|
| 134 |
+
# Organize other sections
|
| 135 |
+
added_item_names = set()
|
| 136 |
+
for item in all_items:
|
| 137 |
+
section = item.get("Section__c", "Others")
|
| 138 |
+
if section not in ordered_menu:
|
| 139 |
+
ordered_menu[section] = []
|
| 140 |
+
|
| 141 |
+
if item['Name'] in added_item_names:
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
|
| 145 |
+
continue
|
| 146 |
+
if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
ordered_menu[section].append(item)
|
| 150 |
+
added_item_names.add(item['Name'])
|
| 151 |
+
|
| 152 |
+
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
|
| 153 |
+
categories = ["All", "Veg", "Non veg"]
|
| 154 |
+
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print(f"Error fetching menu data: {str(e)}")
|
| 157 |
+
ordered_menu = {section: [] for section in SECTION_ORDER}
|
| 158 |
best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
|
| 159 |
ordered_menu["Best Sellers"] = [{
|
| 160 |
"Name": name,
|
| 161 |
"Price__c": "12.99",
|
| 162 |
"Description__c": f"Popular {name}",
|
| 163 |
"Image1__c": "/static/placeholder.jpg",
|
|
|
|
| 164 |
"Video1__c": get_valid_video_path(name),
|
| 165 |
"Total_Ordered__c": 100,
|
| 166 |
"Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
|
| 167 |
+
"Ingredients__c": "Sample ingredients for " + name,
|
| 168 |
"NutritionalInfo__c": "Calories: 500, Protein: 20g",
|
| 169 |
+
"Allergens__c": "Contains nuts, dairy"
|
|
|
|
| 170 |
} for name in best_sellers]
|
| 171 |
+
|
| 172 |
+
categories = ["All", "Veg", "Non veg"]
|
| 173 |
+
referral_code = 'N/A'
|
| 174 |
+
reward_points = 0
|
| 175 |
+
cart_item_count = 0
|
| 176 |
|
| 177 |
return render_template(
|
| 178 |
"menu.html",
|
|
|
|
| 188 |
|
| 189 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
| 190 |
def get_addons():
|
| 191 |
+
item_name = request.args.get('item_name')
|
| 192 |
+
item_section = request.args.get('item_section')
|
| 193 |
+
|
| 194 |
if not item_name or not item_section:
|
| 195 |
+
return jsonify({"success": False, "error": "Item name and section are required."}), 400
|
| 196 |
+
|
| 197 |
try:
|
| 198 |
+
query = f"""
|
| 199 |
+
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
|
| 200 |
+
FROM Customization_Options__c
|
| 201 |
+
WHERE Section__c = '{item_section}'
|
| 202 |
+
"""
|
| 203 |
result = sf.query(query)
|
| 204 |
addons = result.get('records', [])
|
| 205 |
+
|
| 206 |
+
if not addons:
|
| 207 |
+
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
|
| 208 |
+
|
| 209 |
+
formatted_addons = []
|
| 210 |
+
for addon in addons:
|
| 211 |
+
options = addon.get("Options__c", "")
|
| 212 |
+
if options:
|
| 213 |
+
options = options.split(", ")
|
| 214 |
+
else:
|
| 215 |
+
options = []
|
| 216 |
+
|
| 217 |
+
formatted_addons.append({
|
| 218 |
+
"name": addon["Name"],
|
| 219 |
+
"type": addon["Customization_Type__c"],
|
| 220 |
+
"options": options,
|
| 221 |
+
"max_selections": addon.get("Max_Selections__c", 1),
|
| 222 |
+
"extra_charge": addon.get("Extra_Charge__c", False),
|
| 223 |
+
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
|
| 224 |
+
})
|
| 225 |
+
|
| 226 |
return jsonify({"success": True, "addons": formatted_addons})
|
| 227 |
+
|
| 228 |
except Exception as e:
|
| 229 |
+
print(f"Error fetching addons: {str(e)}")
|
| 230 |
+
return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
|
| 231 |
|
| 232 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
| 233 |
def add_to_cart():
|
| 234 |
try:
|
| 235 |
+
data = request.json
|
| 236 |
+
item_name = data.get('itemName', '').strip()
|
| 237 |
+
item_price = data.get('itemPrice')
|
| 238 |
+
item_image = data.get('itemImage')
|
| 239 |
addons = data.get('addons', [])
|
| 240 |
instructions = data.get('instructions', '')
|
| 241 |
+
category = data.get('category')
|
| 242 |
+
section = data.get('section')
|
| 243 |
+
quantity = data.get('quantity', 1)
|
| 244 |
customer_email = session.get('user_email')
|
| 245 |
|
| 246 |
+
if not item_name or not item_price:
|
| 247 |
+
return jsonify({"success": False, "error": "Item name and price are required."}), 400
|
| 248 |
|
| 249 |
+
if not customer_email:
|
| 250 |
+
return jsonify({"success": False, "error": "User email is required."}), 400
|
|
|
|
| 251 |
|
| 252 |
+
query = f"""
|
| 253 |
+
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
| 254 |
+
FROM Cart_Item__c
|
| 255 |
+
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
| 256 |
+
"""
|
| 257 |
result = sf.query(query)
|
| 258 |
+
cart_items = result.get("records", [])
|
| 259 |
+
|
| 260 |
+
addons_price = sum(addon['price'] for addon in addons)
|
| 261 |
+
new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
|
| 262 |
+
|
| 263 |
+
if cart_items:
|
| 264 |
+
cart_item_id = cart_items[0]['Id']
|
| 265 |
+
existing_quantity = cart_items[0]['Quantity__c']
|
| 266 |
+
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
| 267 |
+
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
| 268 |
+
existing_instructions = cart_items[0].get('Instructions__c', "")
|
| 269 |
+
|
| 270 |
+
combined_addons = existing_addons if existing_addons != "None" else ""
|
| 271 |
+
if new_addons:
|
| 272 |
+
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
|
| 273 |
+
|
| 274 |
+
combined_instructions = existing_instructions
|
| 275 |
+
if instructions:
|
| 276 |
+
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
| 277 |
+
|
| 278 |
+
combined_addons_list = combined_addons.split("; ")
|
| 279 |
+
combined_addons_price = sum(
|
| 280 |
+
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
sf.Cart_Item__c.update(cart_item_id, {
|
| 284 |
+
"Quantity__c": existing_quantity + quantity,
|
| 285 |
+
"Add_Ons__c": combined_addons,
|
| 286 |
+
"Add_Ons_Price__c": combined_addons_price,
|
| 287 |
+
"Instructions__c": combined_instructions,
|
| 288 |
+
"Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
|
| 289 |
+
"Category__c": category,
|
| 290 |
+
"Section__c": section
|
| 291 |
})
|
| 292 |
else:
|
| 293 |
+
addons_string = "None"
|
| 294 |
+
if addons:
|
| 295 |
+
addons_string = new_addons
|
| 296 |
+
|
| 297 |
+
total_price = item_price * quantity + addons_price
|
| 298 |
+
|
| 299 |
sf.Cart_Item__c.create({
|
| 300 |
"Name": item_name,
|
| 301 |
"Price__c": total_price,
|
| 302 |
"Base_Price__c": item_price,
|
| 303 |
"Quantity__c": quantity,
|
| 304 |
"Add_Ons_Price__c": addons_price,
|
| 305 |
+
"Add_Ons__c": addons_string,
|
| 306 |
"Image1__c": item_image,
|
| 307 |
"Customer_Email__c": customer_email,
|
| 308 |
"Instructions__c": instructions,
|
|
|
|
| 310 |
"Section__c": section
|
| 311 |
})
|
| 312 |
|
| 313 |
+
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
| 314 |
+
|
| 315 |
+
except KeyError as e:
|
| 316 |
+
return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
|
| 317 |
+
|
| 318 |
except Exception as e:
|
| 319 |
+
print(f"Error adding item to cart: {str(e)}")
|
| 320 |
+
return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
|