Update menu.py
Browse files
menu.py
CHANGED
|
@@ -60,6 +60,7 @@ def menu():
|
|
| 60 |
first_letter = user_name[0].upper() if user_name else "A"
|
| 61 |
user_image = session.get('user_image')
|
| 62 |
|
|
|
|
| 63 |
try:
|
| 64 |
describe_result = sf.Customer_Login__c.describe()
|
| 65 |
fields = [field['name'] for field in describe_result['fields']]
|
|
@@ -68,11 +69,13 @@ def menu():
|
|
| 68 |
logger.error(f"Error describing Customer_Login__c object: {str(e)}")
|
| 69 |
avatar_field_exists = False
|
| 70 |
|
|
|
|
| 71 |
query_fields = ["Id", "Referral__c", "Reward_Points__c"]
|
| 72 |
if avatar_field_exists:
|
| 73 |
query_fields.append("Avatar__c")
|
| 74 |
user_query = f"SELECT {', '.join(query_fields)} FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
| 75 |
|
|
|
|
| 76 |
try:
|
| 77 |
user_result = sf.query(user_query)
|
| 78 |
if not user_result.get('records'):
|
|
@@ -87,10 +90,12 @@ def menu():
|
|
| 87 |
referral_code = user_record.get('Referral__c', 'N/A')
|
| 88 |
reward_points = user_record.get('Reward_Points__c', 0)
|
| 89 |
|
|
|
|
| 90 |
if not user_image and avatar_field_exists and user_record.get('Avatar__c'):
|
| 91 |
session['user_image'] = user_record['Avatar__c']
|
| 92 |
user_image = session['user_image']
|
| 93 |
|
|
|
|
| 94 |
cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
|
| 95 |
try:
|
| 96 |
cart_count_result = sf.query(cart_query)
|
|
@@ -99,6 +104,7 @@ def menu():
|
|
| 99 |
logger.error(f"Error fetching cart item count: {str(e)}")
|
| 100 |
cart_item_count = 0
|
| 101 |
|
|
|
|
| 102 |
menu_query = """
|
| 103 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 104 |
Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
|
|
@@ -112,6 +118,7 @@ def menu():
|
|
| 112 |
logger.error(f"Error fetching menu items: {str(e)}")
|
| 113 |
food_items = []
|
| 114 |
|
|
|
|
| 115 |
for item in food_items:
|
| 116 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
|
| 117 |
item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
|
|
@@ -122,6 +129,7 @@ def menu():
|
|
| 122 |
item['Allergens__c'] = item.get('Allergens__c', "None listed")
|
| 123 |
item['is_menu_item'] = True
|
| 124 |
|
|
|
|
| 125 |
custom_dish_query = """
|
| 126 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 127 |
Veg_NonVeg__c, Section__c, Total_Ordered__c
|
|
@@ -135,6 +143,7 @@ def menu():
|
|
| 135 |
logger.error(f"Error fetching custom dishes: {str(e)}")
|
| 136 |
custom_dishes = []
|
| 137 |
|
|
|
|
| 138 |
for item in custom_dishes:
|
| 139 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
|
| 140 |
item['Video1__c'] = get_valid_video_path(item['Name'])
|
|
@@ -142,9 +151,11 @@ def menu():
|
|
| 142 |
item['Description__c'] = item.get('Description__c', "No description available")
|
| 143 |
item['is_menu_item'] = False
|
| 144 |
|
|
|
|
| 145 |
all_items = food_items + custom_dishes
|
| 146 |
ordered_menu = {section: [] for section in SECTION_ORDER}
|
| 147 |
|
|
|
|
| 148 |
best_sellers = sorted(all_items, key=lambda x: x['Total_Ordered__c'], reverse=True)
|
| 149 |
if selected_category == "Veg":
|
| 150 |
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
|
|
@@ -152,6 +163,7 @@ def menu():
|
|
| 152 |
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
|
| 153 |
ordered_menu["Best Sellers"] = best_sellers[:4]
|
| 154 |
|
|
|
|
| 155 |
added_item_names = set()
|
| 156 |
for item in all_items:
|
| 157 |
section = item['Section__c']
|
|
@@ -170,6 +182,7 @@ def menu():
|
|
| 170 |
ordered_menu[section].append(item)
|
| 171 |
added_item_names.add(item['Name'])
|
| 172 |
|
|
|
|
| 173 |
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
|
| 174 |
categories = ["All", "Veg", "Non veg"]
|
| 175 |
|
|
@@ -206,7 +219,7 @@ def search():
|
|
| 206 |
logger.error(f"Error fetching cart item count: {str(e)}")
|
| 207 |
cart_item_count = 0
|
| 208 |
|
| 209 |
-
# Fetch all
|
| 210 |
menu_query = """
|
| 211 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 212 |
Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
|
|
@@ -230,6 +243,7 @@ def search():
|
|
| 230 |
item['Allergens__c'] = item.get('Allergens__c', "None listed")
|
| 231 |
item['is_menu_item'] = True
|
| 232 |
|
|
|
|
| 233 |
custom_dish_query = """
|
| 234 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 235 |
Veg_NonVeg__c, Section__c, Total_Ordered__c
|
|
@@ -261,24 +275,233 @@ def search():
|
|
| 261 |
user_image=user_image
|
| 262 |
)
|
| 263 |
|
| 264 |
-
# Existing routes remain unchanged...
|
| 265 |
-
|
| 266 |
@menu_blueprint.route('/upload_avatar', methods=['POST'])
|
| 267 |
def upload_avatar():
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
@menu_blueprint.route('/delete_avatar', methods=['POST'])
|
| 272 |
def delete_avatar():
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
| 277 |
def get_addons():
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
| 282 |
def add_to_cart():
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
first_letter = user_name[0].upper() if user_name else "A"
|
| 61 |
user_image = session.get('user_image')
|
| 62 |
|
| 63 |
+
# Check if Avatar__c field exists on Customer_Login__c
|
| 64 |
try:
|
| 65 |
describe_result = sf.Customer_Login__c.describe()
|
| 66 |
fields = [field['name'] for field in describe_result['fields']]
|
|
|
|
| 69 |
logger.error(f"Error describing Customer_Login__c object: {str(e)}")
|
| 70 |
avatar_field_exists = False
|
| 71 |
|
| 72 |
+
# Build the SOQL query dynamically based on field availability
|
| 73 |
query_fields = ["Id", "Referral__c", "Reward_Points__c"]
|
| 74 |
if avatar_field_exists:
|
| 75 |
query_fields.append("Avatar__c")
|
| 76 |
user_query = f"SELECT {', '.join(query_fields)} FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
| 77 |
|
| 78 |
+
# Fetch user referral and reward points
|
| 79 |
try:
|
| 80 |
user_result = sf.query(user_query)
|
| 81 |
if not user_result.get('records'):
|
|
|
|
| 90 |
referral_code = user_record.get('Referral__c', 'N/A')
|
| 91 |
reward_points = user_record.get('Reward_Points__c', 0)
|
| 92 |
|
| 93 |
+
# If no session image, check Salesforce for stored avatar (if field exists)
|
| 94 |
if not user_image and avatar_field_exists and user_record.get('Avatar__c'):
|
| 95 |
session['user_image'] = user_record['Avatar__c']
|
| 96 |
user_image = session['user_image']
|
| 97 |
|
| 98 |
+
# Get cart item count
|
| 99 |
cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
|
| 100 |
try:
|
| 101 |
cart_count_result = sf.query(cart_query)
|
|
|
|
| 104 |
logger.error(f"Error fetching cart item count: {str(e)}")
|
| 105 |
cart_item_count = 0
|
| 106 |
|
| 107 |
+
# Fetch all Menu_Item__c records with required fields
|
| 108 |
menu_query = """
|
| 109 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 110 |
Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
|
|
|
|
| 118 |
logger.error(f"Error fetching menu items: {str(e)}")
|
| 119 |
food_items = []
|
| 120 |
|
| 121 |
+
# Process menu items
|
| 122 |
for item in food_items:
|
| 123 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
|
| 124 |
item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
|
|
|
|
| 129 |
item['Allergens__c'] = item.get('Allergens__c', "None listed")
|
| 130 |
item['is_menu_item'] = True
|
| 131 |
|
| 132 |
+
# Fetch all Custom_Dish__c records with only existing fields
|
| 133 |
custom_dish_query = """
|
| 134 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 135 |
Veg_NonVeg__c, Section__c, Total_Ordered__c
|
|
|
|
| 143 |
logger.error(f"Error fetching custom dishes: {str(e)}")
|
| 144 |
custom_dishes = []
|
| 145 |
|
| 146 |
+
# Process custom dishes
|
| 147 |
for item in custom_dishes:
|
| 148 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
|
| 149 |
item['Video1__c'] = get_valid_video_path(item['Name'])
|
|
|
|
| 151 |
item['Description__c'] = item.get('Description__c', "No description available")
|
| 152 |
item['is_menu_item'] = False
|
| 153 |
|
| 154 |
+
# Merge all items
|
| 155 |
all_items = food_items + custom_dishes
|
| 156 |
ordered_menu = {section: [] for section in SECTION_ORDER}
|
| 157 |
|
| 158 |
+
# Process best sellers
|
| 159 |
best_sellers = sorted(all_items, key=lambda x: x['Total_Ordered__c'], reverse=True)
|
| 160 |
if selected_category == "Veg":
|
| 161 |
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
|
|
|
|
| 163 |
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
|
| 164 |
ordered_menu["Best Sellers"] = best_sellers[:4]
|
| 165 |
|
| 166 |
+
# Organize items into sections
|
| 167 |
added_item_names = set()
|
| 168 |
for item in all_items:
|
| 169 |
section = item['Section__c']
|
|
|
|
| 182 |
ordered_menu[section].append(item)
|
| 183 |
added_item_names.add(item['Name'])
|
| 184 |
|
| 185 |
+
# Remove empty sections
|
| 186 |
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
|
| 187 |
categories = ["All", "Veg", "Non veg"]
|
| 188 |
|
|
|
|
| 219 |
logger.error(f"Error fetching cart item count: {str(e)}")
|
| 220 |
cart_item_count = 0
|
| 221 |
|
| 222 |
+
# Fetch all Menu_Item__c records with required fields
|
| 223 |
menu_query = """
|
| 224 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 225 |
Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
|
|
|
|
| 243 |
item['Allergens__c'] = item.get('Allergens__c', "None listed")
|
| 244 |
item['is_menu_item'] = True
|
| 245 |
|
| 246 |
+
# Fetch all Custom_Dish__c records
|
| 247 |
custom_dish_query = """
|
| 248 |
SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
|
| 249 |
Veg_NonVeg__c, Section__c, Total_Ordered__c
|
|
|
|
| 275 |
user_image=user_image
|
| 276 |
)
|
| 277 |
|
|
|
|
|
|
|
| 278 |
@menu_blueprint.route('/upload_avatar', methods=['POST'])
|
| 279 |
def upload_avatar():
|
| 280 |
+
try:
|
| 281 |
+
data = request.get_json()
|
| 282 |
+
if not data or 'image' not in data:
|
| 283 |
+
logger.error("No image data provided in request")
|
| 284 |
+
return jsonify({'success': False, 'error': 'No image data provided'}), 400
|
| 285 |
+
|
| 286 |
+
image_data = data['image']
|
| 287 |
+
logger.debug(f"Received image data with length: {len(image_data)}")
|
| 288 |
+
|
| 289 |
+
# Validate base64 image
|
| 290 |
+
if not image_data.startswith('data:image/'):
|
| 291 |
+
logger.error("Invalid image format: does not start with 'data:image/'")
|
| 292 |
+
return jsonify({'success': False, 'error': 'Invalid image format'}), 400
|
| 293 |
+
|
| 294 |
+
# Check size limit (~1.5MB for base64, roughly 1MB actual image)
|
| 295 |
+
if len(image_data) > 2_000_000:
|
| 296 |
+
logger.error(f"Image too large: {len(image_data)} characters (max 2,000,000)")
|
| 297 |
+
return jsonify({'success': False, 'error': 'Image too large (max ~1.5MB)'}), 400
|
| 298 |
+
|
| 299 |
+
# Validate base64 decoding
|
| 300 |
+
try:
|
| 301 |
+
base64_string = image_data.split(',')[1]
|
| 302 |
+
base64.b64decode(base64_string)
|
| 303 |
+
except Exception as e:
|
| 304 |
+
logger.error(f"Invalid base64 data: {str(e)}")
|
| 305 |
+
return jsonify({'success': False, 'error': 'Invalid base64 data'}), 400
|
| 306 |
+
|
| 307 |
+
# Store in session
|
| 308 |
+
session['user_image'] = image_data
|
| 309 |
+
logger.info("Image stored in session successfully")
|
| 310 |
+
|
| 311 |
+
# Store in Salesforce (if Avatar__c field exists)
|
| 312 |
+
user_email = session.get('user_email')
|
| 313 |
+
if user_email:
|
| 314 |
+
try:
|
| 315 |
+
user_query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
| 316 |
+
user_result = sf.query(user_query)
|
| 317 |
+
if user_result.get('records'):
|
| 318 |
+
user_id = user_result['records'][0]['Id']
|
| 319 |
+
describe_result = sf.Customer_Login__c.describe()
|
| 320 |
+
fields = [field['name'] for field in describe_result['fields']]
|
| 321 |
+
if 'Avatar__c' in fields:
|
| 322 |
+
sf.Customer_Login__c.update(user_id, {'Avatar__c': image_data})
|
| 323 |
+
logger.info(f"Image stored in Salesforce for user {user_email}")
|
| 324 |
+
else:
|
| 325 |
+
logger.warning("Avatar__c field does not exist; skipping Salesforce update")
|
| 326 |
+
else:
|
| 327 |
+
logger.warning(f"User not found in Salesforce: {user_email}")
|
| 328 |
+
except Exception as e:
|
| 329 |
+
logger.error(f"Failed to store image in Salesforce: {str(e)}")
|
| 330 |
+
|
| 331 |
+
return jsonify({'success': True, 'image': image_data})
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
logger.error(f"Error in upload_avatar: {str(e)}", exc_info=True)
|
| 335 |
+
return jsonify({'success': False, 'error': f'Server error: {str(e)}'}), 500
|
| 336 |
|
| 337 |
@menu_blueprint.route('/delete_avatar', methods=['POST'])
|
| 338 |
def delete_avatar():
|
| 339 |
+
try:
|
| 340 |
+
user_email = session.get('user_email')
|
| 341 |
+
if not user_email:
|
| 342 |
+
logger.error("No user email in session")
|
| 343 |
+
return jsonify({'success': False, 'error': 'User not authenticated'}), 401
|
| 344 |
+
|
| 345 |
+
if 'user_image' in session:
|
| 346 |
+
session.pop('user_image', None)
|
| 347 |
+
logger.info("Image removed from session")
|
| 348 |
+
|
| 349 |
+
try:
|
| 350 |
+
user_query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
| 351 |
+
user_result = sf.query(user_query)
|
| 352 |
+
if user_result.get('records'):
|
| 353 |
+
user_id = user_result['records'][0]['Id']
|
| 354 |
+
describe_result = sf.Customer_Login__c.describe()
|
| 355 |
+
fields = [field['name'] for field in describe_result['fields']]
|
| 356 |
+
if 'Avatar__c' in fields:
|
| 357 |
+
sf.Customer_Login__c.update(user_id, {'Avatar__c': None})
|
| 358 |
+
logger.info(f"Image removed from Salesforce for user {user_email}")
|
| 359 |
+
else:
|
| 360 |
+
logger.warning("Avatar__c field does not exist; skipping Salesforce update")
|
| 361 |
+
else:
|
| 362 |
+
logger.warning(f"User not found in Salesforce: {user_email}")
|
| 363 |
+
except Exception as e:
|
| 364 |
+
logger.error(f"Failed to remove image from Salesforce: {str(e)}")
|
| 365 |
+
|
| 366 |
+
return jsonify({'success': True})
|
| 367 |
+
|
| 368 |
+
except Exception as e:
|
| 369 |
+
logger.error(f"Error in delete_avatar: {str(e)}", exc_info=True)
|
| 370 |
+
return jsonify({'success': False, 'error': f'Server error: {str(e)}'}), 500
|
| 371 |
|
| 372 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
| 373 |
def get_addons():
|
| 374 |
+
item_name = request.args.get('item_name')
|
| 375 |
+
item_section = request.args.get('item_section')
|
| 376 |
+
|
| 377 |
+
if not item_name or not item_section:
|
| 378 |
+
return jsonify({"success": False, "error": "Item name and section are required."}), 400
|
| 379 |
+
|
| 380 |
+
try:
|
| 381 |
+
query = f"""
|
| 382 |
+
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
|
| 383 |
+
FROM Customization_Options__c
|
| 384 |
+
WHERE Section__c = '{item_section}'
|
| 385 |
+
"""
|
| 386 |
+
result = sf.query_all(query)
|
| 387 |
+
addons = result.get('records', [])
|
| 388 |
+
|
| 389 |
+
if not addons:
|
| 390 |
+
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
|
| 391 |
+
|
| 392 |
+
formatted_addons = []
|
| 393 |
+
for addon in addons:
|
| 394 |
+
options = addon.get("Options__c", "")
|
| 395 |
+
options = options.split(", ") if options else []
|
| 396 |
+
formatted_addons.append({
|
| 397 |
+
"name": addon.get("Name", ""),
|
| 398 |
+
"type": addon.get("Customization_Type__c", ""),
|
| 399 |
+
"options": options,
|
| 400 |
+
"max_selections": addon.get("Max_Selections__c", 1),
|
| 401 |
+
"extra_charge": addon.get("Extra_Charge__c", False),
|
| 402 |
+
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
|
| 403 |
+
})
|
| 404 |
+
|
| 405 |
+
return jsonify({"success": True, "addons": formatted_addons})
|
| 406 |
+
|
| 407 |
+
except Exception as e:
|
| 408 |
+
logger.error(f"Error fetching addons: {str(e)}")
|
| 409 |
+
return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
|
| 410 |
|
| 411 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
| 412 |
def add_to_cart():
|
| 413 |
+
try:
|
| 414 |
+
data = request.json
|
| 415 |
+
item_name = data.get('itemName', '').strip()
|
| 416 |
+
item_price = float(data.get('itemPrice', 0))
|
| 417 |
+
item_image = data.get('itemImage', '')
|
| 418 |
+
addons = data.get('addons', [])
|
| 419 |
+
instructions = data.get('instructions', '')
|
| 420 |
+
category = data.get('category', '')
|
| 421 |
+
section = data.get('section', '')
|
| 422 |
+
quantity = int(data.get('quantity', 1))
|
| 423 |
+
customer_email = session.get('user_email')
|
| 424 |
+
|
| 425 |
+
if not item_name or not item_price or not customer_email:
|
| 426 |
+
logger.error(f"Missing required fields: item_name={item_name}, item_price={item_price}, customer_email={customer_email}")
|
| 427 |
+
return jsonify({"success": False, "error": "Item name, price, and user email are required."}), 400
|
| 428 |
+
|
| 429 |
+
# Sanitize inputs to prevent SOQL injection
|
| 430 |
+
item_name = item_name.replace("'", "''")
|
| 431 |
+
customer_email = customer_email.replace("'", "''")
|
| 432 |
+
|
| 433 |
+
query = f"""
|
| 434 |
+
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c, Price__c
|
| 435 |
+
FROM Cart_Item__c
|
| 436 |
+
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
| 437 |
+
"""
|
| 438 |
+
result = sf.query(query)
|
| 439 |
+
cart_items = result.get("records", [])
|
| 440 |
+
|
| 441 |
+
addons_price = sum(float(addon.get('price', 0)) for addon in addons)
|
| 442 |
+
new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) if addons else "None"
|
| 443 |
+
|
| 444 |
+
if cart_items:
|
| 445 |
+
cart_item = cart_items[0]
|
| 446 |
+
cart_item_id = cart_item['Id']
|
| 447 |
+
existing_quantity = int(cart_item.get('Quantity__c', 0))
|
| 448 |
+
existing_addons = cart_item.get('Add_Ons__c', "None")
|
| 449 |
+
existing_addons_price = float(cart_item.get('Add_Ons_Price__c', 0))
|
| 450 |
+
existing_instructions = cart_item.get('Instructions__c', "")
|
| 451 |
+
|
| 452 |
+
combined_addons = existing_addons if existing_addons != "None" else ""
|
| 453 |
+
if new_addons != "None":
|
| 454 |
+
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
|
| 455 |
+
|
| 456 |
+
combined_instructions = existing_instructions
|
| 457 |
+
if instructions:
|
| 458 |
+
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
| 459 |
+
|
| 460 |
+
combined_addons_list = combined_addons.split("; ")
|
| 461 |
+
combined_addons_price = sum(
|
| 462 |
+
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
total_price = (existing_quantity + quantity) * item_price + combined_addons_price
|
| 466 |
+
|
| 467 |
+
sf.Cart_Item__c.update(cart_item_id, {
|
| 468 |
+
"Quantity__c": existing_quantity + quantity,
|
| 469 |
+
"Add_Ons__c": combined_addons,
|
| 470 |
+
"Add_Ons_Price__c": combined_addons_price,
|
| 471 |
+
"Instructions__c": combined_instructions,
|
| 472 |
+
"Price__c": total_price,
|
| 473 |
+
"Category__c": category,
|
| 474 |
+
"Section__c": section
|
| 475 |
+
})
|
| 476 |
+
else:
|
| 477 |
+
total_price = item_price * quantity + addons_price
|
| 478 |
+
sf.Cart_Item__c.create({
|
| 479 |
+
"Name": item_name,
|
| 480 |
+
"Price__c": total_price,
|
| 481 |
+
"Base_Price__c": item_price,
|
| 482 |
+
"Quantity__c": quantity,
|
| 483 |
+
"Add_Ons_Price__c": addons_price,
|
| 484 |
+
"Add_Ons__c": new_addons,
|
| 485 |
+
"Image1__c": item_image,
|
| 486 |
+
"Customer_Email__c": customer_email,
|
| 487 |
+
"Instructions__c": instructions,
|
| 488 |
+
"Category__c": category,
|
| 489 |
+
"Section__c": section
|
| 490 |
+
})
|
| 491 |
+
|
| 492 |
+
# Fetch updated cart for UI update
|
| 493 |
+
cart_query = f"SELECT Name, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}'"
|
| 494 |
+
cart_result = sf.query_all(cart_query)
|
| 495 |
+
cart = [{"itemName": item["Name"], "quantity": item["Quantity__c"]} for item in cart_result.get("records", [])]
|
| 496 |
+
|
| 497 |
+
logger.info(f"Item '{item_name}' added to cart for {customer_email}")
|
| 498 |
+
return jsonify({"success": True, "message": "Item added to cart successfully.", "cart": cart})
|
| 499 |
+
|
| 500 |
+
except ValueError as e:
|
| 501 |
+
logger.error(f"Invalid data format: {str(e)}")
|
| 502 |
+
return jsonify({"success": False, "error": f"Invalid data format: {str(e)}"}), 400
|
| 503 |
+
except Exception as e:
|
| 504 |
+
logger.error(f"Error adding item to cart: {str(e)}", exc_info=True)
|
| 505 |
+
return jsonify({"success": False, "error": f"An error occurred while adding the item to the cart: {str(e)}"}), 500
|
| 506 |
+
|
| 507 |
+
# Note: Ensure 'login' route exists in your app or adjust redirect accordingly
|