lokesh341 commited on
Commit
4e07a43
·
verified ·
1 Parent(s): de66839

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +96 -102
menu.py CHANGED
@@ -1,38 +1,40 @@
1
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
2
- from salesforce import get_salesforce_connection
3
  import os
4
- menu_blueprint = Blueprint('menu', _name_)
 
 
 
5
  # Initialize Salesforce connection
6
  sf = get_salesforce_connection()
 
7
  # Constants for video handling
8
- STATIC_DIR = os.path.join(os.path.dirname(_file_), 'static')
9
  PLACEHOLDER_VIDEO = 'placeholder.mp4'
10
  PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
11
  SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
 
12
  # Create placeholder video at startup if it doesn't exist
13
  if not os.path.exists(PLACEHOLDER_PATH):
14
- open(PLACEHOLDER_PATH, 'wb').close()
 
15
  print(f"Created placeholder video at {PLACEHOLDER_PATH}")
 
16
  def get_valid_video_path(item_name, video_url=None):
17
  """
18
  Get valid video path for item with placeholder fallback
19
  Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
20
  """
21
- # First try: Video1__c from Salesforce if provided
22
  if video_url:
23
- # If it's a complete URL (http/https)
24
  if video_url.startswith(('http://', 'https://')):
25
  return video_url
26
- # If it's a relative path (/videos/xxx.mp4)
27
  elif video_url.startswith('/'):
28
  return video_url
29
- # If it's a Salesforce File ID (starts with '069')
30
  elif video_url.startswith('069'):
31
- return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
32
 
33
- # Final fallback: placeholder.mp4
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}"
@@ -42,11 +44,11 @@ def menu():
42
  selected_category = request.args.get("category", "All")
43
  user_email = session.get('user_email')
44
 
 
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:
@@ -58,105 +60,106 @@ def menu():
58
 
59
  try:
60
  # Fetch user referral and reward points
61
- user_query = f"SELECT Referral_c, Reward_Pointsc FROM Customer_Loginc 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 Video1c, Ingredientsinfoc, NutritionalInfoc, Allergens_c
76
  menu_query = """
77
- SELECT Name, Price_c, Descriptionc, Image1c, Image2_c,
78
- Veg_NonVeg_c, Sectionc, Total_Orderedc, Video1_c,
79
- Ingredientsinfo_c, NutritionalInfoc, 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, ingredients, nutritional info, and allergens
86
  for item in food_items:
87
- item['Ingredientsinfo_c'] = item.get('Ingredientsinfo_c', 'Not Available')
88
- item['NutritionalInfo_c'] = item.get('NutritionalInfo_c', 'Not Available')
89
- item['Allergens_c'] = item.get('Allergens_c', 'Not Available')
90
- item['Video1_c'] = get_valid_video_path(item['Name'], item.get('Video1_c'))
91
-
92
- # Query to fetch Custom_Dish__c records
 
 
 
 
93
  custom_dish_query = """
94
- SELECT Name, Price_c, Descriptionc, Image1c, Image2_c,
95
- Veg_NonVeg_c, Sectionc, Total_Ordered_c
96
  FROM Custom_Dish__c
97
  WHERE CreatedDate >= LAST_N_DAYS:7
98
  """
99
- custom_dish_result = sf.query(custom_dish_query)
100
  custom_dishes = custom_dish_result.get('records', [])
101
 
102
- # Process custom dishes and add video paths
103
  for item in custom_dishes:
104
- item['Ingredientsinfo__c'] = 'Custom Dish Ingredients'
105
- item['NutritionalInfo__c'] = 'Custom Dish Nutritional Info'
106
- item['Allergens__c'] = 'Custom Dish Allergens'
107
  item['Video1__c'] = get_valid_video_path(item['Name'])
108
-
109
- # Merge both Menu_Item_c and Custom_Dish_c records
 
 
 
 
 
 
110
  all_items = food_items + custom_dishes
111
  ordered_menu = {section: [] for section in SECTION_ORDER}
112
 
113
  # Process best sellers
114
- best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
115
-
116
  if selected_category == "Veg":
117
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
118
  elif selected_category == "Non veg":
119
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
 
120
 
121
- best_sellers = best_sellers[:4]
122
- if best_sellers:
123
- ordered_menu["Best Sellers"] = best_sellers
124
-
125
- # Organize other sections
126
  added_item_names = set()
127
  for item in all_items:
128
- section = item.get("Section__c", "Others")
129
  if section not in ordered_menu:
130
  ordered_menu[section] = []
131
 
132
  if item['Name'] in added_item_names:
133
  continue
134
 
135
- if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
 
136
  continue
137
- if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
138
  continue
139
 
140
  ordered_menu[section].append(item)
141
  added_item_names.add(item['Name'])
142
 
 
143
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
144
  categories = ["All", "Veg", "Non veg"]
145
 
146
  except Exception as e:
147
  print(f"Error fetching menu data: {str(e)}")
 
148
  ordered_menu = {section: [] for section in SECTION_ORDER}
149
- best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
150
- ordered_menu["Best Sellers"] = [{
151
- "Name": name,
152
- "Price__c": "12.99",
153
- "Description__c": f"Popular {name}",
154
- "Image1__c": "/static/placeholder.jpg",
155
- "Video1__c": get_valid_video_path(name),
156
- "Total_Ordered__c": 100,
157
- "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg"
158
- } for name in best_sellers]
159
-
160
  categories = ["All", "Veg", "Non veg"]
161
  referral_code = 'N/A'
162
  reward_points = 0
@@ -173,21 +176,22 @@ def menu():
173
  first_letter=first_letter,
174
  cart_item_count=cart_item_count
175
  )
 
176
  @menu_blueprint.route('/api/addons', methods=['GET'])
177
  def get_addons():
178
- item_name = request.args.get('item_name')
179
- item_section = request.args.get('item_section')
180
 
181
  if not item_name or not item_section:
182
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
183
 
184
  try:
185
  query = f"""
186
- SELECT Name, Customization_Type_c, Optionsc, Max_Selectionsc, Extra_Chargec, Extra_Charge_Amount_c
187
  FROM Customization_Options__c
188
  WHERE Section__c = '{item_section}'
189
  """
190
- result = sf.query(query)
191
  addons = result.get('records', [])
192
 
193
  if not addons:
@@ -196,14 +200,10 @@ def get_addons():
196
  formatted_addons = []
197
  for addon in addons:
198
  options = addon.get("Options__c", "")
199
- if options:
200
- options = options.split(", ")
201
- else:
202
- options = []
203
-
204
  formatted_addons.append({
205
- "name": addon["Name"],
206
- "type": addon["Customization_Type__c"],
207
  "options": options,
208
  "max_selections": addon.get("Max_Selections__c", 1),
209
  "extra_charge": addon.get("Extra_Charge__c", False),
@@ -221,41 +221,39 @@ def add_to_cart():
221
  try:
222
  data = request.json
223
  item_name = data.get('itemName', '').strip()
224
- item_price = data.get('itemPrice')
225
- item_image = data.get('itemImage')
226
  addons = data.get('addons', [])
227
  instructions = data.get('instructions', '')
228
- category = data.get('category')
229
- section = data.get('section')
230
- quantity = data.get('quantity', 1)
231
  customer_email = session.get('user_email')
232
 
233
- if not item_name or not item_price:
234
- return jsonify({"success": False, "error": "Item name and price are required."}), 400
235
-
236
- if not customer_email:
237
- return jsonify({"success": False, "error": "User email is required."}), 400
238
 
239
  query = f"""
240
- SELECT Id, Quantity_c, Add_Onsc, Add_Ons_Pricec, Instructions_c
241
  FROM Cart_Item__c
242
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
243
  """
244
  result = sf.query(query)
245
  cart_items = result.get("records", [])
246
 
247
- addons_price = sum(addon['price'] for addon in addons)
248
- new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
249
 
250
  if cart_items:
251
- cart_item_id = cart_items[0]['Id']
252
- existing_quantity = cart_items[0]['Quantity__c']
253
- existing_addons = cart_items[0].get('Add_Ons__c', "None")
254
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
255
- existing_instructions = cart_items[0].get('Instructions__c', "")
 
256
 
257
  combined_addons = existing_addons if existing_addons != "None" else ""
258
- if new_addons:
259
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
260
 
261
  combined_instructions = existing_instructions
@@ -267,29 +265,26 @@ def add_to_cart():
267
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
268
  )
269
 
 
 
270
  sf.Cart_Item__c.update(cart_item_id, {
271
  "Quantity__c": existing_quantity + quantity,
272
  "Add_Ons__c": combined_addons,
273
  "Add_Ons_Price__c": combined_addons_price,
274
  "Instructions__c": combined_instructions,
275
- "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
276
  "Category__c": category,
277
  "Section__c": section
278
  })
279
  else:
280
- addons_string = "None"
281
- if addons:
282
- addons_string = new_addons
283
-
284
  total_price = item_price * quantity + addons_price
285
-
286
  sf.Cart_Item__c.create({
287
  "Name": item_name,
288
  "Price__c": total_price,
289
  "Base_Price__c": item_price,
290
  "Quantity__c": quantity,
291
  "Add_Ons_Price__c": addons_price,
292
- "Add_Ons__c": addons_string,
293
  "Image1__c": item_image,
294
  "Customer_Email__c": customer_email,
295
  "Instructions__c": instructions,
@@ -299,9 +294,8 @@ def add_to_cart():
299
 
300
  return jsonify({"success": True, "message": "Item added to cart successfully."})
301
 
302
- except KeyError as e:
303
- return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
304
-
305
  except Exception as e:
306
  print(f"Error adding item to cart: {str(e)}")
307
- return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
 
1
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
 
2
  import os
3
+ from salesforce import get_salesforce_connection
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
+ with open(PLACEHOLDER_PATH, 'wb') as f:
19
+ f.close()
20
  print(f"Created placeholder video at {PLACEHOLDER_PATH}")
21
+
22
  def get_valid_video_path(item_name, video_url=None):
23
  """
24
  Get valid video path for item with placeholder fallback
25
  Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
26
  """
 
27
  if video_url:
 
28
  if video_url.startswith(('http://', 'https://')):
29
  return video_url
 
30
  elif video_url.startswith('/'):
31
  return video_url
 
32
  elif video_url.startswith('069'):
33
+ return f"https://biryanihub-dev-ed.develop.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
34
 
 
35
  if not os.path.exists(PLACEHOLDER_PATH):
36
+ with open(PLACEHOLDER_PATH, 'wb') as f:
37
+ f.close()
38
  print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
39
 
40
  return f"/static/{PLACEHOLDER_VIDEO}"
 
44
  selected_category = request.args.get("category", "All")
45
  user_email = session.get('user_email')
46
 
47
+ # Handle user authentication
48
  if not user_email:
49
  user_email = request.args.get("email")
50
  user_name = request.args.get("name")
51
+ if user_email and user_name:
 
52
  session['user_email'] = user_email
53
  session['user_name'] = user_name
54
  else:
 
60
 
61
  try:
62
  # Fetch user referral and reward points
63
+ user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
64
  user_result = sf.query(user_query)
65
+ if not user_result.get('records'):
 
66
  return redirect(url_for('login'))
67
 
68
  referral_code = user_result['records'][0].get('Referral__c', 'N/A')
69
  reward_points = user_result['records'][0].get('Reward_Points__c', 0)
70
 
71
  # Get cart item count
72
+ cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
73
  cart_count_result = sf.query(cart_query)
74
+ cart_item_count = cart_count_result.get('totalSize', 0)
75
 
76
+ # Fetch all Menu_Item__c records
77
  menu_query = """
78
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
79
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c
 
80
  FROM Menu_Item__c
81
  """
82
+ menu_result = sf.query_all(menu_query) # Fetch all records
83
+ food_items = menu_result.get('records', [])
84
 
85
+ # Process menu items
86
  for item in food_items:
87
+ item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
88
+ item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
89
+ item['Section__c'] = item.get('Section__c', "Others")
90
+ item['Description__c'] = item.get('Description__c', "No description available")
91
+ # Placeholder for missing fields until created in Salesforce
92
+ item['IngredientsInfo__c'] = item.get('IngredientsInfo__c', "Not specified")
93
+ item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', "Not available")
94
+ item['Allergens__c'] = item.get('Allergens__c', "None listed")
95
+
96
+ # Fetch all Custom_Dish__c records
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
  FROM Custom_Dish__c
101
  WHERE CreatedDate >= LAST_N_DAYS:7
102
  """
103
+ custom_dish_result = sf.query_all(custom_dish_query)
104
  custom_dishes = custom_dish_result.get('records', [])
105
 
106
+ # Process custom dishes
107
  for item in custom_dishes:
108
+ item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
 
 
109
  item['Video1__c'] = get_valid_video_path(item['Name'])
110
+ item['Section__c'] = item.get('Section__c', "Customized dish")
111
+ item['Description__c'] = item.get('Description__c', "No description available")
112
+ # Placeholder for missing fields until created in Salesforce
113
+ item['IngredientsInfo__c'] = item.get('IngredientsInfo__c', "Not specified")
114
+ item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', "Not available")
115
+ item['Allergens__c'] = item.get('Allergens__c', "None listed")
116
+
117
+ # Merge all items
118
  all_items = food_items + custom_dishes
119
  ordered_menu = {section: [] for section in SECTION_ORDER}
120
 
121
  # Process best sellers
122
+ best_sellers = sorted(all_items, key=lambda x: x['Total_Ordered__c'], reverse=True)
 
123
  if selected_category == "Veg":
124
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
125
  elif selected_category == "Non veg":
126
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
127
+ ordered_menu["Best Sellers"] = best_sellers[:4]
128
 
129
+ # Organize items into sections
 
 
 
 
130
  added_item_names = set()
131
  for item in all_items:
132
+ section = item['Section__c']
133
  if section not in ordered_menu:
134
  ordered_menu[section] = []
135
 
136
  if item['Name'] in added_item_names:
137
  continue
138
 
139
+ veg_nonveg = item.get("Veg_NonVeg__c", "both")
140
+ if selected_category == "Veg" and veg_nonveg not in ["Veg", "both"]:
141
  continue
142
+ if selected_category == "Non veg" and veg_nonveg not in ["Non veg", "both"]:
143
  continue
144
 
145
  ordered_menu[section].append(item)
146
  added_item_names.add(item['Name'])
147
 
148
+ # Remove empty sections
149
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
150
  categories = ["All", "Veg", "Non veg"]
151
 
152
  except Exception as e:
153
  print(f"Error fetching menu data: {str(e)}")
154
+ # Fallback data with all required fields
155
  ordered_menu = {section: [] for section in SECTION_ORDER}
156
+ best_sellers = [
157
+ {"Name": "Chicken Biryani", "Price__c": 12.99, "Description__c": "Spicy chicken with rice", "Image1__c": "/static/placeholder.jpg", "Video1__c": get_valid_video_path("Chicken Biryani"), "Total_Ordered__c": 100, "Veg_NonVeg__c": "Non veg", "Section__c": "Best Sellers", "IngredientsInfo__c": "Chicken, rice, spices", "NutritionalInfo__c": "600 cal, 30g protein", "Allergens__c": "None"},
158
+ {"Name": "Paneer Butter Masala", "Price__c": 11.99, "Description__c": "Creamy paneer curry", "Image1__c": "/static/placeholder.jpg", "Video1__c": get_valid_video_path("Paneer Butter Masala"), "Total_Ordered__c": 90, "Veg_NonVeg__c": "Veg", "Section__c": "Best Sellers", "IngredientsInfo__c": "Paneer, cream, tomatoes", "NutritionalInfo__c": "700 cal, 20g protein", "Allergens__c": "Dairy"},
159
+ {"Name": "Veg Manchurian", "Price__c": 9.99, "Description__c": "Indo-Chinese veggie dish", "Image1__c": "/static/placeholder.jpg", "Video1__c": get_valid_video_path("Veg Manchurian"), "Total_Ordered__c": 80, "Veg_NonVeg__c": "Veg", "Section__c": "Best Sellers", "IngredientsInfo__c": "Vegetables, soy sauce", "NutritionalInfo__c": "400 cal, 10g protein", "Allergens__c": "Soy"},
160
+ {"Name": "Prawn Fry", "Price__c": 14.99, "Description__c": "Crispy fried prawns", "Image1__c": "/static/placeholder.jpg", "Video1__c": get_valid_video_path("Prawn Fry"), "Total_Ordered__c": 70, "Veg_NonVeg__c": "Non veg", "Section__c": "Best Sellers", "IngredientsInfo__c": "Prawns, spices", "NutritionalInfo__c": "500 cal, 25g protein", "Allergens__c": "Shellfish"}
161
+ ]
162
+ ordered_menu["Best Sellers"] = best_sellers
 
 
 
 
163
  categories = ["All", "Veg", "Non veg"]
164
  referral_code = 'N/A'
165
  reward_points = 0
 
176
  first_letter=first_letter,
177
  cart_item_count=cart_item_count
178
  )
179
+
180
  @menu_blueprint.route('/api/addons', methods=['GET'])
181
  def get_addons():
182
+ item_name = request.args.get('item_name')
183
+ item_section = request.args.get('item_section')
184
 
185
  if not item_name or not item_section:
186
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
187
 
188
  try:
189
  query = f"""
190
+ SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
191
  FROM Customization_Options__c
192
  WHERE Section__c = '{item_section}'
193
  """
194
+ result = sf.query_all(query)
195
  addons = result.get('records', [])
196
 
197
  if not addons:
 
200
  formatted_addons = []
201
  for addon in addons:
202
  options = addon.get("Options__c", "")
203
+ options = options.split(", ") if options else []
 
 
 
 
204
  formatted_addons.append({
205
+ "name": addon.get("Name", ""),
206
+ "type": addon.get("Customization_Type__c", ""),
207
  "options": options,
208
  "max_selections": addon.get("Max_Selections__c", 1),
209
  "extra_charge": addon.get("Extra_Charge__c", False),
 
221
  try:
222
  data = request.json
223
  item_name = data.get('itemName', '').strip()
224
+ item_price = float(data.get('itemPrice', 0))
225
+ item_image = data.get('itemImage', '')
226
  addons = data.get('addons', [])
227
  instructions = data.get('instructions', '')
228
+ category = data.get('category', '')
229
+ section = data.get('section', '')
230
+ quantity = int(data.get('quantity', 1))
231
  customer_email = session.get('user_email')
232
 
233
+ if not item_name or not item_price or not customer_email:
234
+ return jsonify({"success": False, "error": "Item name, price, and user email are required."}), 400
 
 
 
235
 
236
  query = f"""
237
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c, Price__c
238
  FROM Cart_Item__c
239
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
240
  """
241
  result = sf.query(query)
242
  cart_items = result.get("records", [])
243
 
244
+ addons_price = sum(float(addon.get('price', 0)) for addon in addons)
245
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) if addons else "None"
246
 
247
  if cart_items:
248
+ cart_item = cart_items[0]
249
+ cart_item_id = cart_item['Id']
250
+ existing_quantity = int(cart_item.get('Quantity__c', 0))
251
+ existing_addons = cart_item.get('Add_Ons__c', "None")
252
+ existing_addons_price = float(cart_item.get('Add_Ons_Price__c', 0))
253
+ existing_instructions = cart_item.get('Instructions__c', "")
254
 
255
  combined_addons = existing_addons if existing_addons != "None" else ""
256
+ if new_addons != "None":
257
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
258
 
259
  combined_instructions = existing_instructions
 
265
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
266
  )
267
 
268
+ total_price = (existing_quantity + quantity) * item_price + combined_addons_price
269
+
270
  sf.Cart_Item__c.update(cart_item_id, {
271
  "Quantity__c": existing_quantity + quantity,
272
  "Add_Ons__c": combined_addons,
273
  "Add_Ons_Price__c": combined_addons_price,
274
  "Instructions__c": combined_instructions,
275
+ "Price__c": total_price,
276
  "Category__c": category,
277
  "Section__c": section
278
  })
279
  else:
 
 
 
 
280
  total_price = item_price * quantity + addons_price
 
281
  sf.Cart_Item__c.create({
282
  "Name": item_name,
283
  "Price__c": total_price,
284
  "Base_Price__c": item_price,
285
  "Quantity__c": quantity,
286
  "Add_Ons_Price__c": addons_price,
287
+ "Add_Ons__c": new_addons,
288
  "Image1__c": item_image,
289
  "Customer_Email__c": customer_email,
290
  "Instructions__c": instructions,
 
294
 
295
  return jsonify({"success": True, "message": "Item added to cart successfully."})
296
 
297
+ except ValueError as e:
298
+ return jsonify({"success": False, "error": f"Invalid data format: {str(e)}"}), 400
 
299
  except Exception as e:
300
  print(f"Error adding item to cart: {str(e)}")
301
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500