lokesh341 commited on
Commit
4a9aef9
·
verified ·
1 Parent(s): 4506f5a

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +75 -91
menu.py CHANGED
@@ -1,6 +1,6 @@
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
 
@@ -15,7 +15,8 @@ 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
 
21
  def get_valid_video_path(item_name, video_url=None):
@@ -33,11 +34,12 @@ def get_valid_video_path(item_name, video_url=None):
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,11 +49,11 @@ 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:
@@ -65,8 +67,7 @@ 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')
@@ -75,96 +76,86 @@ def menu():
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 Video1__c and nutrition fields
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,
84
- IngredientsInfo__c, Nutritional_Info__c, 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
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
 
96
- # Query to fetch Custom_Dish__c records with nutrition fields
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
- IngredientsInfo__c, Nutritional_Info__c, Allergens__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
- if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
110
- item['Total_Ordered__c'] = 0
111
  item['Video1__c'] = get_valid_video_path(item['Name'])
 
112
 
113
- # Merge both Menu_Item__c and Custom_Dish__c records
114
  all_items = food_items + custom_dishes
115
  ordered_menu = {section: [] for section in SECTION_ORDER}
116
 
117
- # Process best sellers
118
- best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
119
-
120
  if selected_category == "Veg":
121
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
122
  elif selected_category == "Non veg":
123
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
 
124
 
125
- best_sellers = best_sellers[:4]
126
- if best_sellers:
127
- ordered_menu["Best Sellers"] = best_sellers
128
-
129
- # Organize other sections
130
- added_item_names = set()
131
  for item in all_items:
132
- section = item.get("Section__c", "Others")
133
  if section not in ordered_menu:
134
  ordered_menu[section] = []
135
 
136
  if item['Name'] in added_item_names:
137
  continue
138
 
139
- if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
 
 
140
  continue
141
- if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
142
  continue
143
 
144
  ordered_menu[section].append(item)
145
  added_item_names.add(item['Name'])
146
 
 
147
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
148
  categories = ["All", "Veg", "Non veg"]
149
 
150
  except Exception as e:
151
  print(f"Error fetching menu data: {str(e)}")
152
- # Fallback data with video and nutrition support
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
- "IngredientsInfo__c": "Paneer, cream, tomatoes, spices" if "Paneer" in name else "Chicken, rice, spices, yogurt",
164
- "Nutritional_Info__c": "Calories: 500-700, Protein: 20g" if "Paneer" in name else "Calories: 600-800, Protein: 30g",
165
- "Allergens__c": "Dairy" if "Paneer" in name else "None"
166
- } for name in best_sellers]
167
-
168
  categories = ["All", "Veg", "Non veg"]
169
  referral_code = 'N/A'
170
  reward_points = 0
@@ -184,8 +175,8 @@ def menu():
184
 
185
  @menu_blueprint.route('/api/addons', methods=['GET'])
186
  def get_addons():
187
- item_name = request.args.get('item_name')
188
- item_section = request.args.get('item_section')
189
 
190
  if not item_name or not item_section:
191
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
@@ -196,7 +187,7 @@ def get_addons():
196
  FROM Customization_Options__c
197
  WHERE Section__c = '{item_section}'
198
  """
199
- result = sf.query(query)
200
  addons = result.get('records', [])
201
 
202
  if not addons:
@@ -205,14 +196,10 @@ def get_addons():
205
  formatted_addons = []
206
  for addon in addons:
207
  options = addon.get("Options__c", "")
208
- if options:
209
- options = options.split(", ")
210
- else:
211
- options = []
212
-
213
  formatted_addons.append({
214
- "name": addon["Name"],
215
- "type": addon["Customization_Type__c"],
216
  "options": options,
217
  "max_selections": addon.get("Max_Selections__c", 1),
218
  "extra_charge": addon.get("Extra_Charge__c", False),
@@ -230,41 +217,41 @@ def add_to_cart():
230
  try:
231
  data = request.json
232
  item_name = data.get('itemName', '').strip()
233
- item_price = data.get('itemPrice')
234
- item_image = data.get('itemImage')
235
  addons = data.get('addons', [])
236
  instructions = data.get('instructions', '')
237
- category = data.get('category')
238
- section = data.get('section')
239
- quantity = data.get('quantity', 1)
240
  customer_email = session.get('user_email')
241
 
242
- if not item_name or not item_price:
243
- return jsonify({"success": False, "error": "Item name and price are required."}), 400
244
-
245
- if not customer_email:
246
- return jsonify({"success": False, "error": "User email is required."}), 400
247
 
 
248
  query = f"""
249
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
250
  FROM Cart_Item__c
251
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
252
  """
253
  result = sf.query(query)
254
  cart_items = result.get("records", [])
255
 
256
- addons_price = sum(addon['price'] for addon in addons)
257
- new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
258
 
259
  if cart_items:
260
- cart_item_id = cart_items[0]['Id']
261
- existing_quantity = cart_items[0]['Quantity__c']
262
- existing_addons = cart_items[0].get('Add_Ons__c', "None")
263
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
264
- existing_instructions = cart_items[0].get('Instructions__c', "")
 
 
265
 
266
  combined_addons = existing_addons if existing_addons != "None" else ""
267
- if new_addons:
268
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
269
 
270
  combined_instructions = existing_instructions
@@ -276,29 +263,27 @@ def add_to_cart():
276
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
277
  )
278
 
 
 
279
  sf.Cart_Item__c.update(cart_item_id, {
280
  "Quantity__c": existing_quantity + quantity,
281
  "Add_Ons__c": combined_addons,
282
  "Add_Ons_Price__c": combined_addons_price,
283
  "Instructions__c": combined_instructions,
284
- "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
285
  "Category__c": category,
286
  "Section__c": section
287
  })
288
  else:
289
- addons_string = "None"
290
- if addons:
291
- addons_string = new_addons
292
-
293
  total_price = item_price * quantity + addons_price
294
-
295
  sf.Cart_Item__c.create({
296
  "Name": item_name,
297
  "Price__c": total_price,
298
  "Base_Price__c": item_price,
299
  "Quantity__c": quantity,
300
  "Add_Ons_Price__c": addons_price,
301
- "Add_Ons__c": addons_string,
302
  "Image1__c": item_image,
303
  "Customer_Email__c": customer_email,
304
  "Instructions__c": instructions,
@@ -308,9 +293,8 @@ def add_to_cart():
308
 
309
  return jsonify({"success": True, "message": "Item added to cart successfully."})
310
 
311
- except KeyError as e:
312
- return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
313
-
314
  except Exception as e:
315
  print(f"Error adding item to cart: {str(e)}")
316
- 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
 
 
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):
 
34
  return video_url
35
  # If it's a Salesforce File ID (starts with '069')
36
  elif video_url.startswith('069'):
37
+ return f"https://biryanihub-dev-ed.develop.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
38
 
39
  # Final fallback: placeholder.mp4
40
  if not os.path.exists(PLACEHOLDER_PATH):
41
+ with open(PLACEHOLDER_PATH, 'wb') as f:
42
+ f.close()
43
  print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
44
 
45
  return f"/static/{PLACEHOLDER_VIDEO}"
 
49
  selected_category = request.args.get("category", "All")
50
  user_email = session.get('user_email')
51
 
52
+ # Handle user authentication
53
  if not user_email:
54
  user_email = request.args.get("email")
55
  user_name = request.args.get("name")
56
+ if user_email and user_name:
 
57
  session['user_email'] = user_email
58
  session['user_name'] = user_name
59
  else:
 
67
  # Fetch user referral and reward points
68
  user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
69
  user_result = sf.query(user_query)
70
+ if not user_result.get('records'):
 
71
  return redirect(url_for('login'))
72
 
73
  referral_code = user_result['records'][0].get('Referral__c', 'N/A')
 
76
  # Get cart item count
77
  cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
78
  cart_count_result = sf.query(cart_query)
79
+ cart_item_count = cart_count_result.get('totalSize', 0)
80
 
81
+ # Fetch all Menu_Item__c records
82
  menu_query = """
83
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
84
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c
 
85
  FROM Menu_Item__c
86
  """
87
+ menu_result = sf.query_all(menu_query) # Use query_all to fetch all records
88
+ food_items = menu_result.get('records', [])
89
 
90
+ # Process menu items and add video paths
91
  for item in food_items:
92
+ item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0) or 0
 
93
  item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
94
+ item['Section__c'] = item.get('Section__c') or "Others" # Default section
95
 
96
+ # Fetch all Custom_Dish__c records from the last 7 days
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 and add video paths
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') or "Customized dish" # Default section
111
 
112
+ # Merge all items
113
  all_items = food_items + custom_dishes
114
  ordered_menu = {section: [] for section in SECTION_ORDER}
115
 
116
+ # Process best sellers (top 4 by Total_Ordered__c)
117
+ best_sellers = sorted(all_items, key=lambda x: x['Total_Ordered__c'], reverse=True)
 
118
  if selected_category == "Veg":
119
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
120
  elif selected_category == "Non veg":
121
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
122
+ ordered_menu["Best Sellers"] = best_sellers[:4]
123
 
124
+ # Organize items into sections
125
+ added_item_names = set() # To avoid duplicates
 
 
 
 
126
  for item in all_items:
127
+ section = item['Section__c']
128
  if section not in ordered_menu:
129
  ordered_menu[section] = []
130
 
131
  if item['Name'] in added_item_names:
132
  continue
133
 
134
+ # Apply category filter
135
+ veg_nonveg = item.get("Veg_NonVeg__c", "both")
136
+ if selected_category == "Veg" and veg_nonveg not in ["Veg", "both"]:
137
  continue
138
+ if selected_category == "Non veg" and veg_nonveg not in ["Non veg", "both"]:
139
  continue
140
 
141
  ordered_menu[section].append(item)
142
  added_item_names.add(item['Name'])
143
 
144
+ # Remove empty sections
145
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
146
  categories = ["All", "Veg", "Non veg"]
147
 
148
  except Exception as e:
149
  print(f"Error fetching menu data: {str(e)}")
150
+ # Fallback data
151
  ordered_menu = {section: [] for section in SECTION_ORDER}
152
+ best_sellers = [
153
+ {"Name": "Chicken Biryani", "Price__c": 12.99, "Description__c": "Popular Chicken Biryani", "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"},
154
+ {"Name": "Paneer Butter Masala", "Price__c": 11.99, "Description__c": "Popular Paneer Butter Masala", "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"},
155
+ {"Name": "Veg Manchurian", "Price__c": 9.99, "Description__c": "Popular Veg Manchurian", "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"},
156
+ {"Name": "Prawn Fry", "Price__c": 14.99, "Description__c": "Popular Prawn Fry", "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"}
157
+ ]
158
+ ordered_menu["Best Sellers"] = best_sellers
 
 
 
 
 
 
 
159
  categories = ["All", "Veg", "Non veg"]
160
  referral_code = 'N/A'
161
  reward_points = 0
 
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
 
187
  FROM Customization_Options__c
188
  WHERE Section__c = '{item_section}'
189
  """
190
+ result = sf.query_all(query)
191
  addons = result.get('records', [])
192
 
193
  if not addons:
 
196
  formatted_addons = []
197
  for addon in addons:
198
  options = addon.get("Options__c", "")
199
+ options = options.split(", ") if options else []
 
 
 
 
200
  formatted_addons.append({
201
+ "name": addon.get("Name", ""),
202
+ "type": addon.get("Customization_Type__c", ""),
203
  "options": options,
204
  "max_selections": addon.get("Max_Selections__c", 1),
205
  "extra_charge": addon.get("Extra_Charge__c", False),
 
217
  try:
218
  data = request.json
219
  item_name = data.get('itemName', '').strip()
220
+ item_price = float(data.get('itemPrice', 0))
221
+ item_image = data.get('itemImage', '')
222
  addons = data.get('addons', [])
223
  instructions = data.get('instructions', '')
224
+ category = data.get('category', '')
225
+ section = data.get('section', '')
226
+ quantity = int(data.get('quantity', 1))
227
  customer_email = session.get('user_email')
228
 
229
+ if not item_name or not item_price or not customer_email:
230
+ return jsonify({"success": False, "error": "Item name, price, and user email are required."}), 400
 
 
 
231
 
232
+ # Check if item already exists in cart
233
  query = f"""
234
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c, Price__c
235
  FROM Cart_Item__c
236
  WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
237
  """
238
  result = sf.query(query)
239
  cart_items = result.get("records", [])
240
 
241
+ addons_price = sum(float(addon.get('price', 0)) for addon in addons)
242
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) if addons else "None"
243
 
244
  if cart_items:
245
+ # Update existing cart item
246
+ cart_item = cart_items[0]
247
+ cart_item_id = cart_item['Id']
248
+ existing_quantity = int(cart_item.get('Quantity__c', 0))
249
+ existing_addons = cart_item.get('Add_Ons__c', "None")
250
+ existing_addons_price = float(cart_item.get('Add_Ons_Price__c', 0))
251
+ existing_instructions = cart_item.get('Instructions__c', "")
252
 
253
  combined_addons = existing_addons if existing_addons != "None" else ""
254
+ if new_addons != "None":
255
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
256
 
257
  combined_instructions = existing_instructions
 
263
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
264
  )
265
 
266
+ total_price = (existing_quantity + quantity) * item_price + combined_addons_price
267
+
268
  sf.Cart_Item__c.update(cart_item_id, {
269
  "Quantity__c": existing_quantity + quantity,
270
  "Add_Ons__c": combined_addons,
271
  "Add_Ons_Price__c": combined_addons_price,
272
  "Instructions__c": combined_instructions,
273
+ "Price__c": total_price,
274
  "Category__c": category,
275
  "Section__c": section
276
  })
277
  else:
278
+ # Create new cart item
 
 
 
279
  total_price = item_price * quantity + addons_price
 
280
  sf.Cart_Item__c.create({
281
  "Name": item_name,
282
  "Price__c": total_price,
283
  "Base_Price__c": item_price,
284
  "Quantity__c": quantity,
285
  "Add_Ons_Price__c": addons_price,
286
+ "Add_Ons__c": new_addons,
287
  "Image1__c": item_image,
288
  "Customer_Email__c": customer_email,
289
  "Instructions__c": instructions,
 
293
 
294
  return jsonify({"success": True, "message": "Item added to cart successfully."})
295
 
296
+ except ValueError as e:
297
+ return jsonify({"success": False, "error": f"Invalid data format: {str(e)}"}), 400
 
298
  except Exception as e:
299
  print(f"Error adding item to cart: {str(e)}")
300
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500