lokesh341 commited on
Commit
a7e3033
·
verified ·
1 Parent(s): 29a2fcc

Update menu.py

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