lokesh341 commited on
Commit
7e251aa
·
verified ·
1 Parent(s): 375539f

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +201 -228
menu.py CHANGED
@@ -7,173 +7,181 @@ menu_blueprint = Blueprint('menu', __name__)
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
- # 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}"
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  @menu_blueprint.route("/menu", methods=["GET", "POST"])
46
  def menu():
 
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:
58
- return redirect(url_for("login"))
59
- else:
60
- user_name = session.get('user_name')
61
 
62
  first_letter = user_name[0].upper() if user_name else "A"
63
 
64
  try:
65
- # Fetch user referral and reward points
66
- user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c 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
- # First try basic query with essential fields
81
- base_fields = [
82
- "Name", "Price__c", "Description__c", "Image1__c", "Image2__c",
83
- "Veg_NonVeg__c", "Section__c", "Total_Ordered__c", "Video1__c"
84
- ]
85
-
86
- # Try to include nutrition fields if they exist
87
- try:
88
- describe_result = sf.Menu_Item__c.describe()
89
- available_fields = [field['name'] for field in describe_result['fields']]
90
-
91
- nutrition_fields = []
92
- if 'IngredientsInfo__c' in available_fields:
93
- nutrition_fields.append('IngredientsInfo__c')
94
- if 'Nutritional_Info__c' in available_fields:
95
- nutrition_fields.append('Nutritional_Info__c')
96
- if 'Allergens__c' in available_fields:
97
- nutrition_fields.append('Allergens__c')
98
-
99
- query_fields = base_fields + nutrition_fields
100
- except Exception as e:
101
- print(f"Error checking for nutrition fields: {str(e)}")
102
- query_fields = base_fields
103
-
104
- # Build and execute the query
105
- menu_query = f"SELECT {', '.join(query_fields)} FROM Menu_Item__c"
106
- result = sf.query(menu_query)
107
- food_items = result['records'] if 'records' in result else []
108
-
109
- # Process items with fallback values
110
- for item in food_items:
111
- # Ensure required fields have values
112
  item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
113
  item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
114
 
115
- # Add fallback values for nutrition fields
116
- item['IngredientsInfo__c'] = item.get('IngredientsInfo__c', 'Ingredients information not available')
117
- item['Nutritional_Info__c'] = item.get('Nutritional_Info__c', 'Nutritional information not available')
118
- item['Allergens__c'] = item.get('Allergens__c', 'Allergen information not available')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- # Process best sellers
121
- best_sellers = sorted(food_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
122
-
123
- # Apply category filter
124
- if selected_category == "Veg":
125
- best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
126
- elif selected_category == "Non veg":
127
- best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
128
 
129
- best_sellers = best_sellers[:4]
130
  ordered_menu = {section: [] for section in SECTION_ORDER}
131
-
132
  if best_sellers:
133
  ordered_menu["Best Sellers"] = best_sellers
134
 
135
- # Organize items by section
136
- added_item_names = set()
137
- for item in food_items:
138
  section = item.get("Section__c", "Others")
139
- if section not in ordered_menu:
140
- ordered_menu[section] = []
141
-
142
- if item['Name'] in added_item_names:
143
- continue
144
-
145
- # Apply category filter to all items
146
- if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
147
- continue
148
- if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
149
- continue
150
 
151
- ordered_menu[section].append(item)
152
- added_item_names.add(item['Name'])
153
-
154
- # Remove empty sections
155
- ordered_menu = {section: items for section, items in ordered_menu.items() if items}
156
- categories = ["All", "Veg", "Non veg"]
157
 
158
  except Exception as e:
159
- print(f"Error fetching menu data: {str(e)}")
160
- # Fallback data
161
- ordered_menu = {section: [] for section in SECTION_ORDER}
162
- best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
163
- ordered_menu["Best Sellers"] = [{
164
- "Name": name,
165
- "Price__c": "12.99",
166
- "Description__c": f"Popular {name}",
167
- "Image1__c": "/static/placeholder.jpg",
168
- "Video1__c": get_valid_video_path(name),
169
- "Total_Ordered__c": 100,
170
- "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
171
- "IngredientsInfo__c": "Ingredients information not available",
172
- "Nutritional_Info__c": "Nutritional information not available",
173
- "Allergens__c": "Allergen information not available"
174
- } for name in best_sellers]
175
-
176
- categories = ["All", "Veg", "Non veg"]
 
 
 
 
 
 
 
 
177
  referral_code = 'N/A'
178
  reward_points = 0
179
  cart_item_count = 0
@@ -181,144 +189,109 @@ def menu():
181
  return render_template(
182
  "menu.html",
183
  ordered_menu=ordered_menu,
184
- categories=categories,
185
  selected_category=selected_category,
186
  referral_code=referral_code,
187
  reward_points=reward_points,
188
  user_name=user_name,
189
  first_letter=first_letter,
190
- cart_item_count=cart_item_count
 
191
  )
192
 
193
  @menu_blueprint.route('/api/addons', methods=['GET'])
194
  def get_addons():
195
- item_name = request.args.get('item_name')
196
- item_section = request.args.get('item_section')
197
-
198
- if not item_name or not item_section:
199
- return jsonify({"success": False, "error": "Item name and section are required."}), 400
200
-
201
  try:
202
- query = f"""
203
- SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
 
 
 
 
 
204
  FROM Customization_Options__c
205
  WHERE Section__c = '{item_section}'
206
- """
207
- result = sf.query(query)
208
- addons = result.get('records', [])
209
-
210
- if not addons:
211
- return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
212
 
213
  formatted_addons = []
214
  for addon in addons:
215
- options = addon.get("Options__c", "")
216
- if options:
217
- options = options.split(", ")
218
- else:
219
- options = []
220
-
221
  formatted_addons.append({
222
  "name": addon["Name"],
223
  "type": addon["Customization_Type__c"],
224
- "options": options,
225
  "max_selections": addon.get("Max_Selections__c", 1),
226
  "extra_charge": addon.get("Extra_Charge__c", False),
227
- "extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
228
  })
229
 
230
  return jsonify({"success": True, "addons": formatted_addons})
231
 
232
  except Exception as e:
233
  print(f"Error fetching addons: {str(e)}")
234
- return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
235
 
236
  @menu_blueprint.route('/cart/add', methods=['POST'])
237
  def add_to_cart():
238
  try:
239
  data = request.json
240
- item_name = data.get('itemName', '').strip()
241
- item_price = data.get('itemPrice')
242
- item_image = data.get('itemImage')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  addons = data.get('addons', [])
244
- instructions = data.get('instructions', '')
245
- category = data.get('category')
246
- section = data.get('section')
247
- quantity = data.get('quantity', 1)
248
- customer_email = session.get('user_email')
249
-
250
- if not item_name or not item_price:
251
- return jsonify({"success": False, "error": "Item name and price are required."}), 400
252
-
253
- if not customer_email:
254
- return jsonify({"success": False, "error": "User email is required."}), 400
255
 
256
- query = f"""
257
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
 
258
  FROM Cart_Item__c
259
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
260
- """
261
- result = sf.query(query)
262
- cart_items = result.get("records", [])
263
-
264
- addons_price = sum(addon['price'] for addon in addons)
265
- new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
266
-
267
- if cart_items:
268
- cart_item_id = cart_items[0]['Id']
269
- existing_quantity = cart_items[0]['Quantity__c']
270
- existing_addons = cart_items[0].get('Add_Ons__c', "None")
271
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
272
- existing_instructions = cart_items[0].get('Instructions__c', "")
273
-
274
- combined_addons = existing_addons if existing_addons != "None" else ""
275
- if new_addons:
276
- combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
277
-
278
- combined_instructions = existing_instructions
279
- if instructions:
280
- combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
281
-
282
- combined_addons_list = combined_addons.split("; ")
283
- combined_addons_price = sum(
284
- float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
285
- )
286
-
287
- sf.Cart_Item__c.update(cart_item_id, {
288
- "Quantity__c": existing_quantity + quantity,
289
- "Add_Ons__c": combined_addons,
290
- "Add_Ons_Price__c": combined_addons_price,
291
- "Instructions__c": combined_instructions,
292
- "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
293
- "Category__c": category,
294
- "Section__c": section
295
  })
296
  else:
297
- addons_string = "None"
298
- if addons:
299
- addons_string = new_addons
300
-
301
- total_price = item_price * quantity + addons_price
302
-
303
- sf.Cart_Item__c.create({
304
- "Name": item_name,
305
- "Price__c": total_price,
306
- "Base_Price__c": item_price,
307
- "Quantity__c": quantity,
308
- "Add_Ons_Price__c": addons_price,
309
- "Add_Ons__c": addons_string,
310
- "Image1__c": item_image,
311
- "Customer_Email__c": customer_email,
312
- "Instructions__c": instructions,
313
- "Category__c": category,
314
- "Section__c": section
315
- })
316
-
317
- return jsonify({"success": True, "message": "Item added to cart successfully."})
318
 
319
- except KeyError as e:
320
- return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
321
 
322
  except Exception as e:
323
- print(f"Error adding item to cart: {str(e)}")
324
- return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
 
7
  # Initialize Salesforce connection
8
  sf = get_salesforce_connection()
9
 
10
+ # Constants
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 = [
15
+ "Best Sellers", "Starters", "Biryanis", "Curries",
16
+ "Breads", "Customized dish", "Appetizer", "Desserts",
17
+ "Soft Drinks"
18
+ ]
19
 
20
+ # Create placeholder video if missing
21
  if not os.path.exists(PLACEHOLDER_PATH):
22
  open(PLACEHOLDER_PATH, 'wb').close()
 
23
 
24
  def get_valid_video_path(item_name, video_url=None):
25
+ """Handle video paths with proper fallback logic"""
 
 
 
 
26
  if video_url:
 
27
  if video_url.startswith(('http://', 'https://')):
28
  return video_url
 
29
  elif video_url.startswith('/'):
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
  return f"/static/{PLACEHOLDER_VIDEO}"
34
 
35
+ def get_available_fields():
36
+ """Check which custom fields exist in Salesforce"""
37
+ try:
38
+ desc = sf.Menu_Item__c.describe()
39
+ existing_fields = {field['name'] for field in desc['fields']}
40
+
41
+ return {
42
+ 'base': [
43
+ 'Name', 'Price__c', 'Description__c', 'Image1__c', 'Image2__c',
44
+ 'Veg_NonVeg__c', 'Section__c', 'Total_Ordered__c', 'Video1__c'
45
+ ],
46
+ 'nutrition': [
47
+ f for f in ['IngredientsInfo__c', 'Nutritional_Info__c', 'Allergens__c']
48
+ if f in existing_fields
49
+ ]
50
+ }
51
+ except Exception as e:
52
+ print(f"Error checking Salesforce fields: {str(e)}")
53
+ return {
54
+ 'base': ['Name', 'Price__c', 'Description__c', 'Image1__c', 'Veg_NonVeg__c', 'Section__c'],
55
+ 'nutrition': []
56
+ }
57
+
58
  @menu_blueprint.route("/menu", methods=["GET", "POST"])
59
  def menu():
60
+ # Authentication and session handling
61
  selected_category = request.args.get("category", "All")
62
+ user_email = session.get('user_email') or request.args.get("email")
63
+ user_name = session.get('user_name') or request.args.get("name")
64
 
65
  if not user_email:
66
+ return redirect(url_for("login"))
67
+
68
+ if not session.get('user_email'):
69
+ session['user_email'] = user_email
70
+ session['user_name'] = user_name
 
 
 
 
 
71
 
72
  first_letter = user_name[0].upper() if user_name else "A"
73
 
74
  try:
75
+ # Check available fields in Salesforce
76
+ available_fields = get_available_fields()
77
+ all_fields = available_fields['base'] + available_fields['nutrition']
78
+
79
+ # Fetch user data
80
+ user_data = sf.query(f"""
81
+ SELECT Referral__c, Reward_Points__c
82
+ FROM Customer_Login__c
83
+ WHERE Email__c = '{user_email}'
84
+ """).get('records', [{}])[0]
85
+
86
+ if not user_data:
87
  return redirect(url_for('login'))
88
 
89
+ referral_code = user_data.get('Referral__c', 'N/A')
90
+ reward_points = user_data.get('Reward_Points__c', 0)
91
+
92
+ # Get cart count
93
+ cart_item_count = sf.query(f"""
94
+ SELECT COUNT()
95
+ FROM Cart_Item__c
96
+ WHERE Customer_Email__c = '{user_email}'
97
+ """)['totalSize']
98
+
99
+ # Fetch menu items with available fields
100
+ menu_items = sf.query(f"""
101
+ SELECT {', '.join(all_fields)}
102
+ FROM Menu_Item__c
103
+ """).get('records', [])
104
+
105
+ # Process items with nutrition data
106
+ for item in menu_items:
107
+ # Required fields
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
109
  item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
110
 
111
+ # Nutrition fields with clear fallbacks
112
+ item['IngredientsInfo__c'] = item.get('IngredientsInfo__c',
113
+ 'Ingredients information not available' if 'IngredientsInfo__c' in available_fields['nutrition']
114
+ else 'Ingredients data not configured')
115
+
116
+ item['Nutritional_Info__c'] = item.get('Nutritional_Info__c',
117
+ 'Nutritional information not available' if 'Nutritional_Info__c' in available_fields['nutrition']
118
+ else 'Nutritional data not configured')
119
+
120
+ item['Allergens__c'] = item.get('Allergens__c',
121
+ 'Allergen information not available' if 'Allergens__c' in available_fields['nutrition']
122
+ else 'Allergen data not configured')
123
+
124
+ # Filter by category
125
+ category_filter = {
126
+ "Veg": ["Veg", "both"],
127
+ "Non veg": ["Non veg", "both"],
128
+ "All": ["Veg", "Non veg", "both"]
129
+ }.get(selected_category, ["Veg", "Non veg", "both"])
130
+
131
+ filtered_items = [
132
+ item for item in menu_items
133
+ if item.get("Veg_NonVeg__c") in category_filter
134
+ ]
135
 
136
+ # Get best sellers (top 4 most ordered)
137
+ best_sellers = sorted(
138
+ filtered_items,
139
+ key=lambda x: x.get("Total_Ordered__c", 0),
140
+ reverse=True
141
+ )[:4]
 
 
142
 
143
+ # Organize by sections
144
  ordered_menu = {section: [] for section in SECTION_ORDER}
 
145
  if best_sellers:
146
  ordered_menu["Best Sellers"] = best_sellers
147
 
148
+ added_items = set()
149
+ for item in filtered_items:
 
150
  section = item.get("Section__c", "Others")
151
+ if item['Name'] not in added_items:
152
+ ordered_menu.setdefault(section, []).append(item)
153
+ added_items.add(item['Name'])
 
 
 
 
 
 
 
 
154
 
155
+ # Clean empty sections
156
+ ordered_menu = {k: v for k, v in ordered_menu.items() if v}
 
 
 
 
157
 
158
  except Exception as e:
159
+ print(f"Error in menu route: {str(e)}")
160
+ # Comprehensive fallback data
161
+ ordered_menu = {
162
+ "Best Sellers": [
163
+ {
164
+ "Name": "Chicken Biryani",
165
+ "Price__c": 14.99,
166
+ "Description__c": "Fragrant basmati rice with chicken and spices",
167
+ "Image1__c": "/static/placeholder.jpg",
168
+ "Veg_NonVeg__c": "Non veg",
169
+ "IngredientsInfo__c": "Chicken, basmati rice, yogurt, spices",
170
+ "Nutritional_Info__c": "Calories: 850, Protein: 45g",
171
+ "Allergens__c": "Dairy (yogurt)"
172
+ },
173
+ {
174
+ "Name": "Paneer Tikka",
175
+ "Price__c": 12.99,
176
+ "Description__c": "Grilled cottage cheese with spices",
177
+ "Image1__c": "/static/placeholder.jpg",
178
+ "Veg_NonVeg__c": "Veg",
179
+ "IngredientsInfo__c": "Paneer, bell peppers, spices",
180
+ "Nutritional_Info__c": "Calories: 420, Protein: 22g",
181
+ "Allergens__c": "Dairy (paneer)"
182
+ }
183
+ ]
184
+ }
185
  referral_code = 'N/A'
186
  reward_points = 0
187
  cart_item_count = 0
 
189
  return render_template(
190
  "menu.html",
191
  ordered_menu=ordered_menu,
192
+ categories=["All", "Veg", "Non veg"],
193
  selected_category=selected_category,
194
  referral_code=referral_code,
195
  reward_points=reward_points,
196
  user_name=user_name,
197
  first_letter=first_letter,
198
+ cart_item_count=cart_item_count,
199
+ show_nutrition=bool(available_fields['nutrition'])
200
  )
201
 
202
  @menu_blueprint.route('/api/addons', methods=['GET'])
203
  def get_addons():
 
 
 
 
 
 
204
  try:
205
+ item_section = request.args.get('item_section')
206
+ if not item_section:
207
+ return jsonify({"success": False, "error": "Section is required"}), 400
208
+
209
+ addons = sf.query(f"""
210
+ SELECT Name, Customization_Type__c, Options__c,
211
+ Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
212
  FROM Customization_Options__c
213
  WHERE Section__c = '{item_section}'
214
+ """).get('records', [])
 
 
 
 
 
215
 
216
  formatted_addons = []
217
  for addon in addons:
 
 
 
 
 
 
218
  formatted_addons.append({
219
  "name": addon["Name"],
220
  "type": addon["Customization_Type__c"],
221
+ "options": addon.get("Options__c", "").split(", ") if addon.get("Options__c") else [],
222
  "max_selections": addon.get("Max_Selections__c", 1),
223
  "extra_charge": addon.get("Extra_Charge__c", False),
224
+ "extra_charge_amount": float(addon.get("Extra_Charge_Amount__c", 0))
225
  })
226
 
227
  return jsonify({"success": True, "addons": formatted_addons})
228
 
229
  except Exception as e:
230
  print(f"Error fetching addons: {str(e)}")
231
+ return jsonify({"success": False, "error": str(e)}), 500
232
 
233
  @menu_blueprint.route('/cart/add', methods=['POST'])
234
  def add_to_cart():
235
  try:
236
  data = request.json
237
+ required_fields = ['itemName', 'itemPrice', 'category', 'section']
238
+ if not all(field in data for field in required_fields):
239
+ return jsonify({"success": False, "error": "Missing required fields"}), 400
240
+
241
+ if not session.get('user_email'):
242
+ return jsonify({"success": False, "error": "Not authenticated"}), 401
243
+
244
+ # Prepare cart item data
245
+ cart_data = {
246
+ "Name": data['itemName'].strip(),
247
+ "Price__c": float(data['itemPrice']),
248
+ "Base_Price__c": float(data['itemPrice']),
249
+ "Quantity__c": int(data.get('quantity', 1)),
250
+ "Customer_Email__c": session['user_email'],
251
+ "Category__c": data['category'],
252
+ "Section__c": data['section'],
253
+ "Image1__c": data.get('itemImage'),
254
+ "Instructions__c": data.get('instructions', '')[:255]
255
+ }
256
+
257
+ # Handle addons
258
  addons = data.get('addons', [])
259
+ if addons:
260
+ addons_price = sum(float(a['price']) for a in addons)
261
+ addons_str = "; ".join(f"{a['name']} (${a['price']})" for a in addons)
262
+ cart_data.update({
263
+ "Add_Ons__c": addons_str,
264
+ "Add_Ons_Price__c": addons_price,
265
+ "Price__c": float(data['itemPrice']) * int(data.get('quantity', 1)) + addons_price
266
+ })
 
 
 
267
 
268
+ # Check if item already in cart
269
+ existing = sf.query(f"""
270
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c
271
  FROM Cart_Item__c
272
+ WHERE Name = '{cart_data["Name"]}'
273
+ AND Customer_Email__c = '{session['user_email']}'
274
+ """).get('records', [])
275
+
276
+ if existing:
277
+ # Update existing item
278
+ existing = existing[0]
279
+ new_quantity = existing['Quantity__c'] + cart_data['Quantity__c']
280
+ new_addons = f"{existing.get('Add_Ons__c', '')}; {cart_data.get('Add_Ons__c', '')}".strip("; ")
281
+ new_addons_price = existing.get('Add_Ons_Price__c', 0) + cart_data.get('Add_Ons_Price__c', 0)
282
+
283
+ sf.Cart_Item__c.update(existing['Id'], {
284
+ "Quantity__c": new_quantity,
285
+ "Add_Ons__c": new_addons,
286
+ "Add_Ons_Price__c": new_addons_price,
287
+ "Price__c": (cart_data['Base_Price__c'] * new_quantity) + new_addons_price
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  })
289
  else:
290
+ # Create new cart item
291
+ sf.Cart_Item__c.create(cart_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
+ return jsonify({"success": True, "message": "Added to cart"})
 
294
 
295
  except Exception as e:
296
+ print(f"Error adding to cart: {str(e)}")
297
+ return jsonify({"success": False, "error": str(e)}), 500