lokesh341 commited on
Commit
6b7317a
·
verified ·
1 Parent(s): 5bb21d5

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +39 -80
menu.py CHANGED
@@ -15,6 +15,7 @@ SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "C
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
 
@@ -23,22 +24,17 @@ 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}"
44
 
@@ -50,7 +46,6 @@ def menu():
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
@@ -65,10 +60,8 @@ def menu():
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
 
@@ -77,7 +70,7 @@ def menu():
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 new fields and Video1__c
81
  menu_query = """
82
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
83
  Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
@@ -85,19 +78,17 @@ def menu():
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
91
  for item in food_items:
92
- if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
93
- item['Total_Ordered__c'] = 0
94
  item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
95
- # Ensure optional fields are present with fallback
96
  item['Ingredients__c'] = item.get('Ingredients__c', '')
97
  item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', '')
98
  item['Allergens__c'] = item.get('Allergens__c', '')
99
 
100
- # Query to fetch Custom_Dish__c records including new fields
101
  custom_dish_query = """
102
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
103
  Veg_NonVeg__c, Section__c, Total_Ordered__c,
@@ -108,28 +99,24 @@ def menu():
108
  custom_dish_result = sf.query(custom_dish_query)
109
  custom_dishes = custom_dish_result.get('records', [])
110
 
111
- # Process custom dishes and add video paths
112
  for item in custom_dishes:
113
- if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
114
- item['Total_Ordered__c'] = 0
115
  item['Video1__c'] = get_valid_video_path(item['Name'])
116
- # Ensure optional fields are present with fallback
117
  item['Ingredients__c'] = item.get('Ingredients__c', '')
118
  item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', '')
119
  item['Allergens__c'] = item.get('Allergens__c', '')
120
 
121
- # Merge both Menu_Item__c and Custom_Dish__c records
122
  all_items = food_items + custom_dishes
123
  ordered_menu = {section: [] for section in SECTION_ORDER}
124
 
125
  # Process best sellers
126
  best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
127
-
128
  if selected_category == "Veg":
129
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
130
  elif selected_category == "Non veg":
131
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
132
-
133
  best_sellers = best_sellers[:4]
134
  if best_sellers:
135
  ordered_menu["Best Sellers"] = best_sellers
@@ -140,24 +127,20 @@ def menu():
140
  section = item.get("Section__c", "Others")
141
  if section not in ordered_menu:
142
  ordered_menu[section] = []
143
-
144
  if item['Name'] in added_item_names:
145
  continue
146
-
147
  if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
148
  continue
149
  if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
150
  continue
151
-
152
  ordered_menu[section].append(item)
153
  added_item_names.add(item['Name'])
154
 
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 with video support and new fields
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"] = [{
@@ -168,11 +151,10 @@ def menu():
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
- "Ingredients__c": "Sample ingredients for " + name,
172
  "NutritionalInfo__c": "Calories: 500, Protein: 20g",
173
  "Allergens__c": "Contains nuts, dairy"
174
  } for name in best_sellers]
175
-
176
  categories = ["All", "Veg", "Non veg"]
177
  referral_code = 'N/A'
178
  reward_points = 0
@@ -192,12 +174,10 @@ def menu():
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
@@ -206,18 +186,11 @@ def get_addons():
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"],
@@ -226,32 +199,27 @@ def get_addons():
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
@@ -261,8 +229,8 @@ def add_to_cart():
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']
@@ -270,20 +238,15 @@ def add_to_cart():
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,
@@ -294,31 +257,27 @@ def add_to_cart():
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
 
15
 
16
  # Create placeholder video at startup if it doesn't exist
17
  if not os.path.exists(PLACEHOLDER_PATH):
18
+ os.makedirs(STATIC_DIR, exist_ok=True) # Ensure static directory exists
19
  open(PLACEHOLDER_PATH, 'wb').close()
20
  print(f"Created placeholder video at {PLACEHOLDER_PATH}")
21
 
 
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://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
34
 
 
35
  if not os.path.exists(PLACEHOLDER_PATH):
36
  open(PLACEHOLDER_PATH, 'wb').close()
37
+ print(f"Recreated missing placeholder video at {PLACEHOLDER_PATH}")
38
 
39
  return f"/static/{PLACEHOLDER_VIDEO}"
40
 
 
46
  if not user_email:
47
  user_email = request.args.get("email")
48
  user_name = request.args.get("name")
 
49
  if user_email:
50
  session['user_email'] = user_email
51
  session['user_name'] = user_name
 
60
  # Fetch user referral and reward points
61
  user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
62
  user_result = sf.query(user_query)
 
63
  if not user_result['records']:
64
  return redirect(url_for('login'))
 
65
  referral_code = user_result['records'][0].get('Referral__c', 'N/A')
66
  reward_points = user_result['records'][0].get('Reward_Points__c', 0)
67
 
 
70
  cart_count_result = sf.query(cart_query)
71
  cart_item_count = cart_count_result['totalSize']
72
 
73
+ # Query to fetch Menu_Item__c records
74
  menu_query = """
75
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
76
  Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c,
 
78
  FROM Menu_Item__c
79
  """
80
  result = sf.query(menu_query)
81
+ food_items = result.get('records', [])
82
 
83
+ # Process menu items
84
  for item in food_items:
85
+ item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
 
86
  item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
 
87
  item['Ingredients__c'] = item.get('Ingredients__c', '')
88
  item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', '')
89
  item['Allergens__c'] = item.get('Allergens__c', '')
90
 
91
+ # Query to fetch Custom_Dish__c records
92
  custom_dish_query = """
93
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
94
  Veg_NonVeg__c, Section__c, Total_Ordered__c,
 
99
  custom_dish_result = sf.query(custom_dish_query)
100
  custom_dishes = custom_dish_result.get('records', [])
101
 
102
+ # Process custom dishes
103
  for item in custom_dishes:
104
+ item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
 
105
  item['Video1__c'] = get_valid_video_path(item['Name'])
 
106
  item['Ingredients__c'] = item.get('Ingredients__c', '')
107
  item['NutritionalInfo__c'] = item.get('NutritionalInfo__c', '')
108
  item['Allergens__c'] = item.get('Allergens__c', '')
109
 
110
+ # Merge items
111
  all_items = food_items + custom_dishes
112
  ordered_menu = {section: [] for section in SECTION_ORDER}
113
 
114
  # Process best sellers
115
  best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
 
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
  best_sellers = best_sellers[:4]
121
  if best_sellers:
122
  ordered_menu["Best Sellers"] = best_sellers
 
127
  section = item.get("Section__c", "Others")
128
  if section not in ordered_menu:
129
  ordered_menu[section] = []
 
130
  if item['Name'] in added_item_names:
131
  continue
 
132
  if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
133
  continue
134
  if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
135
  continue
 
136
  ordered_menu[section].append(item)
137
  added_item_names.add(item['Name'])
138
 
139
+ ordered_menu = {k: v for k, v in ordered_menu.items() if v}
140
  categories = ["All", "Veg", "Non veg"]
141
 
142
  except Exception as e:
143
  print(f"Error fetching menu data: {str(e)}")
 
144
  ordered_menu = {section: [] for section in SECTION_ORDER}
145
  best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
146
  ordered_menu["Best Sellers"] = [{
 
151
  "Video1__c": get_valid_video_path(name),
152
  "Total_Ordered__c": 100,
153
  "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
154
+ "Ingredients__c": f"Sample ingredients for {name}",
155
  "NutritionalInfo__c": "Calories: 500, Protein: 20g",
156
  "Allergens__c": "Contains nuts, dairy"
157
  } for name in best_sellers]
 
158
  categories = ["All", "Veg", "Non veg"]
159
  referral_code = 'N/A'
160
  reward_points = 0
 
174
 
175
  @menu_blueprint.route('/api/addons', methods=['GET'])
176
  def get_addons():
177
+ item_name = request.args.get('item_name')
178
+ item_section = request.args.get('item_section')
 
179
  if not item_name or not item_section:
180
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
 
181
  try:
182
  query = f"""
183
  SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
 
186
  """
187
  result = sf.query(query)
188
  addons = result.get('records', [])
 
189
  if not addons:
190
+ return jsonify({"success": False, "error": "No customization options found."}), 404
 
191
  formatted_addons = []
192
  for addon in addons:
193
+ options = addon.get("Options__c", "").split(", ") if addon.get("Options__c") else []
 
 
 
 
 
194
  formatted_addons.append({
195
  "name": addon["Name"],
196
  "type": addon["Customization_Type__c"],
 
199
  "extra_charge": addon.get("Extra_Charge__c", False),
200
  "extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
201
  })
 
202
  return jsonify({"success": True, "addons": formatted_addons})
 
203
  except Exception as e:
204
  print(f"Error fetching addons: {str(e)}")
205
+ return jsonify({"success": False, "error": "An error occurred while fetching addons."}), 500
206
 
207
  @menu_blueprint.route('/cart/add', methods=['POST'])
208
  def add_to_cart():
209
  try:
210
  data = request.json
211
  item_name = data.get('itemName', '').strip()
212
+ item_price = float(data.get('itemPrice', 0))
213
  item_image = data.get('itemImage')
214
  addons = data.get('addons', [])
215
  instructions = data.get('instructions', '')
216
  category = data.get('category')
217
  section = data.get('section')
218
+ quantity = int(data.get('quantity', 1))
219
  customer_email = session.get('user_email')
220
+
221
+ if not item_name or not item_price or not customer_email:
222
+ return jsonify({"success": False, "error": "Missing required fields."}), 400
 
 
 
223
 
224
  query = f"""
225
  SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
 
229
  result = sf.query(query)
230
  cart_items = result.get("records", [])
231
 
232
+ addons_price = sum(float(addon['price']) for addon in addons)
233
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) if addons else "None"
234
 
235
  if cart_items:
236
  cart_item_id = cart_items[0]['Id']
 
238
  existing_addons = cart_items[0].get('Add_Ons__c', "None")
239
  existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
240
  existing_instructions = cart_items[0].get('Instructions__c', "")
241
+
242
  combined_addons = existing_addons if existing_addons != "None" else ""
243
+ if new_addons and new_addons != "None":
244
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
245
+ combined_instructions = f"{existing_instructions} | {instructions}".strip(" | ") if instructions else existing_instructions
246
+
 
 
 
247
  combined_addons_list = combined_addons.split("; ")
248
+ combined_addons_price = sum(float(a.split("($")[1][:-1]) for a in combined_addons_list if "($" in a)
249
+
 
 
250
  sf.Cart_Item__c.update(cart_item_id, {
251
  "Quantity__c": existing_quantity + quantity,
252
  "Add_Ons__c": combined_addons,
 
257
  "Section__c": section
258
  })
259
  else:
 
 
 
 
260
  total_price = item_price * quantity + addons_price
 
261
  sf.Cart_Item__c.create({
262
  "Name": item_name,
263
  "Price__c": total_price,
264
  "Base_Price__c": item_price,
265
  "Quantity__c": quantity,
266
  "Add_Ons_Price__c": addons_price,
267
+ "Add_Ons__c": new_addons,
268
  "Image1__c": item_image,
269
  "Customer_Email__c": customer_email,
270
  "Instructions__c": instructions,
271
  "Category__c": category,
272
  "Section__c": section
273
  })
274
+
275
+ cart_query = f"SELECT Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}'"
276
+ cart_result = sf.query(cart_query)
277
+ cart = [{"quantity": item["Quantity__c"]} for item in cart_result.get("records", [])]
278
+
279
+ return jsonify({"success": True, "message": "Item added to cart.", "cart": cart})
280
 
281
  except Exception as e:
282
+ print(f"Error adding to cart: {str(e)}")
283
+ return jsonify({"success": False, "error": "Failed to add item to cart."}), 500