lokesh341 commited on
Commit
d3fa992
·
verified ·
1 Parent(s): e757288

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +87 -68
menu.py CHANGED
@@ -1,11 +1,47 @@
1
- from flask import Blueprint, render_template, request, session, jsonify # Added jsonify import
2
  from salesforce import get_salesforce_connection
 
3
 
4
  menu_blueprint = Blueprint('menu', __name__)
5
 
6
  # Initialize Salesforce connection
7
  sf = get_salesforce_connection()
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  @menu_blueprint.route("/menu", methods=["GET", "POST"])
10
  def menu():
11
  selected_category = request.args.get("category", "All")
@@ -17,13 +53,12 @@ def menu():
17
 
18
  if user_email:
19
  session['user_email'] = user_email
20
- session['user_name'] = user_name # Store name in session
21
  else:
22
  return redirect(url_for("login"))
23
  else:
24
- user_name = session.get('user_name') # Get name from session if it's already stored
25
 
26
- # Get the first letter of the user's name (make it uppercase for consistency)
27
  first_letter = user_name[0].upper() if user_name else "A"
28
 
29
  try:
@@ -37,87 +72,93 @@ def menu():
37
  referral_code = user_result['records'][0].get('Referral__c', 'N/A')
38
  reward_points = user_result['records'][0].get('Reward_Points__c', 0)
39
 
40
- # Query to fetch Menu_Item__c records including Total_Ordered__c for best sellers
41
  menu_query = """
42
- SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
 
43
  FROM Menu_Item__c
44
  """
45
  result = sf.query(menu_query)
46
  food_items = result['records'] if 'records' in result else []
47
 
48
- # Ensure Total_Ordered__c has a valid value
49
  for item in food_items:
50
  if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
51
- item['Total_Ordered__c'] = 0 # Default value
 
52
 
53
- # Query to fetch Custom_Dish__c records created within the last 7 days with Total_Ordered__c > 10
54
  custom_dish_query = """
55
- SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
 
56
  FROM Custom_Dish__c
57
  WHERE CreatedDate >= LAST_N_DAYS:7
58
  """
59
  custom_dish_result = sf.query(custom_dish_query)
60
- custom_dishes = custom_dish_result['records'] if 'records' in custom_dish_result else []
61
 
62
- # Merge both Menu_Item__c and Custom_Dish__c records into the ordered menu
63
- all_items = food_items + custom_dishes
 
 
 
64
 
65
- # Define the order of sections, adding "Best Sellers" at the top
66
- section_order = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
67
- ordered_menu = {section: [] for section in section_order}
68
 
69
- # Sort items by Total_Ordered__c in descending order and pick top 4 as best sellers
70
  best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
71
-
72
  if selected_category == "Veg":
73
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
74
  elif selected_category == "Non veg":
75
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
76
 
77
- # Take only the top 4 best sellers after filtering
78
  best_sellers = best_sellers[:4]
79
-
80
- # Ensure "Best Sellers" is added only if there are items after filtering
81
  if best_sellers:
82
  ordered_menu["Best Sellers"] = best_sellers
83
 
84
- # Create a set to track item names already added to prevent duplicates
85
  added_item_names = set()
86
-
87
- # Filter and organize menu items based on category and section (to avoid duplicates)
88
  for item in all_items:
89
- section = item.get("Section__c", "Others") # Default to "Others" if missing
90
  if section not in ordered_menu:
91
  ordered_menu[section] = []
92
 
93
- # Skip item if it's already been added to avoid duplicates
94
  if item['Name'] in added_item_names:
95
  continue
96
 
97
- # Apply category filters
98
  if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
99
  continue
100
  if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
101
  continue
102
 
103
  ordered_menu[section].append(item)
104
- added_item_names.add(item['Name']) # Add item to the set of added items
105
- print(f"Added item to {section}: {item['Name']}") # Debugging
106
 
107
- # Remove empty sections
108
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
109
- print(f"Final ordered menu: {ordered_menu.keys()}") # Debugging
110
-
111
  categories = ["All", "Veg", "Non veg"]
112
 
113
  except Exception as e:
114
  print(f"Error fetching menu data: {str(e)}")
115
- ordered_menu = {}
 
 
 
 
 
 
 
 
 
 
 
 
116
  categories = ["All", "Veg", "Non veg"]
117
  referral_code = 'N/A'
118
  reward_points = 0
119
 
120
- # Pass the user's first letter (first_letter) to the template
121
  return render_template(
122
  "menu.html",
123
  ordered_menu=ordered_menu,
@@ -125,20 +166,19 @@ def menu():
125
  selected_category=selected_category,
126
  referral_code=referral_code,
127
  reward_points=reward_points,
128
- user_name=user_name, # Pass name to the template
129
- first_letter=first_letter # Pass first letter to the template
130
  )
 
131
  @menu_blueprint.route('/api/addons', methods=['GET'])
132
  def get_addons():
133
  item_name = request.args.get('item_name')
134
  item_section = request.args.get('item_section')
135
 
136
- # Check if both item_name and item_section are provided
137
  if not item_name or not item_section:
138
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
139
 
140
  try:
141
- # Fetch customization options from Salesforce based on the section
142
  query = f"""
143
  SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
144
  FROM Customization_Options__c
@@ -147,19 +187,16 @@ def get_addons():
147
  result = sf.query(query)
148
  addons = result.get('records', [])
149
 
150
- # Check if we found any addons
151
  if not addons:
152
  return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
153
 
154
- # Format data for frontend
155
  formatted_addons = []
156
  for addon in addons:
157
- # Ensure 'Options__c' exists and is not None
158
  options = addon.get("Options__c", "")
159
- if options: # If options are available, split them
160
- options = options.split(", ") # Convert comma-separated options into a list
161
  else:
162
- options = [] # If no options, default to an empty list
163
 
164
  formatted_addons.append({
165
  "name": addon["Name"],
@@ -173,14 +210,12 @@ def get_addons():
173
  return jsonify({"success": True, "addons": formatted_addons})
174
 
175
  except Exception as e:
176
- # Log the exception for debugging
177
- app.logger.error(f"Error fetching addons: {str(e)}")
178
  return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
179
 
180
  @menu_blueprint.route('/cart/add', methods=['POST'])
181
  def add_to_cart():
182
  try:
183
- # Get data from request
184
  data = request.json
185
  item_name = data.get('itemName', '').strip()
186
  item_price = data.get('itemPrice')
@@ -189,17 +224,15 @@ def add_to_cart():
189
  instructions = data.get('instructions', '')
190
  category = data.get('category')
191
  section = data.get('section')
192
- quantity = data.get('quantity', 1) # Get the quantity field from the request
193
  customer_email = session.get('user_email')
194
 
195
- # Basic validation for required fields
196
  if not item_name or not item_price:
197
  return jsonify({"success": False, "error": "Item name and price are required."}), 400
198
 
199
  if not customer_email:
200
  return jsonify({"success": False, "error": "User email is required."}), 400
201
 
202
- # Query to check if the item is already in the cart
203
  query = f"""
204
  SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
205
  FROM Cart_Item__c
@@ -208,11 +241,9 @@ def add_to_cart():
208
  result = sf.query(query)
209
  cart_items = result.get("records", [])
210
 
211
- # Calculate the total price for the addons
212
  addons_price = sum(addon['price'] for addon in addons)
213
  new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
214
 
215
- # If the item is already in the cart, update it
216
  if cart_items:
217
  cart_item_id = cart_items[0]['Id']
218
  existing_quantity = cart_items[0]['Quantity__c']
@@ -220,25 +251,21 @@ def add_to_cart():
220
  existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
221
  existing_instructions = cart_items[0].get('Instructions__c', "")
222
 
223
- # Combine the new addons with the existing ones
224
  combined_addons = existing_addons if existing_addons != "None" else ""
225
  if new_addons:
226
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
227
 
228
- # Combine existing instructions with new instructions
229
  combined_instructions = existing_instructions
230
  if instructions:
231
  combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
232
 
233
- # Calculate total addons price
234
  combined_addons_list = combined_addons.split("; ")
235
  combined_addons_price = sum(
236
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
237
  )
238
 
239
- # Update the cart item in Salesforce (updating quantity)
240
  sf.Cart_Item__c.update(cart_item_id, {
241
- "Quantity__c": existing_quantity + quantity, # Add the selected quantity
242
  "Add_Ons__c": combined_addons,
243
  "Add_Ons_Price__c": combined_addons_price,
244
  "Instructions__c": combined_instructions,
@@ -247,19 +274,17 @@ def add_to_cart():
247
  "Section__c": section
248
  })
249
  else:
250
- # If the item is not already in the cart, create a new entry
251
  addons_string = "None"
252
  if addons:
253
  addons_string = new_addons
254
 
255
- total_price = item_price * quantity + addons_price # Multiply by the quantity
256
 
257
- # Create new cart item in Salesforce
258
  sf.Cart_Item__c.create({
259
  "Name": item_name,
260
  "Price__c": total_price,
261
  "Base_Price__c": item_price,
262
- "Quantity__c": quantity, # Use the selected quantity
263
  "Add_Ons_Price__c": addons_price,
264
  "Add_Ons__c": addons_string,
265
  "Image1__c": item_image,
@@ -272,14 +297,8 @@ def add_to_cart():
272
  return jsonify({"success": True, "message": "Item added to cart successfully."})
273
 
274
  except KeyError as e:
275
- # Handle missing expected keys in request data
276
  return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
277
 
278
  except Exception as e:
279
- # Log the error for debugging and return a general error message
280
  print(f"Error adding item to cart: {str(e)}")
281
- return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
282
-
283
-
284
-
285
-
 
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):
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")
 
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:
 
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
+ # Query to fetch Menu_Item__c records including Video1__c
76
  menu_query = """
77
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
78
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c
79
  FROM Menu_Item__c
80
  """
81
  result = sf.query(menu_query)
82
  food_items = result['records'] if 'records' in result else []
83
 
84
+ # Process items and add video paths
85
  for item in food_items:
86
  if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
87
+ item['Total_Ordered__c'] = 0
88
+ item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
89
 
90
+ # Query to fetch Custom_Dish__c records
91
  custom_dish_query = """
92
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
93
+ Veg_NonVeg__c, Section__c, Total_Ordered__c
94
  FROM Custom_Dish__c
95
  WHERE CreatedDate >= LAST_N_DAYS:7
96
  """
97
  custom_dish_result = sf.query(custom_dish_query)
98
+ custom_dishes = custom_dish_result.get('records', [])
99
 
100
+ # Process custom dishes and add video paths
101
+ for item in custom_dishes:
102
+ if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
103
+ item['Total_Ordered__c'] = 0
104
+ item['Video1__c'] = get_valid_video_path(item['Name'])
105
 
106
+ # Merge both Menu_Item__c and Custom_Dish__c records
107
+ all_items = food_items + custom_dishes
108
+ ordered_menu = {section: [] for section in SECTION_ORDER}
109
 
110
+ # Process best sellers
111
  best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
112
+
113
  if selected_category == "Veg":
114
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
115
  elif selected_category == "Non veg":
116
  best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
117
 
 
118
  best_sellers = best_sellers[:4]
 
 
119
  if best_sellers:
120
  ordered_menu["Best Sellers"] = best_sellers
121
 
122
+ # Organize other sections
123
  added_item_names = set()
 
 
124
  for item in all_items:
125
+ section = item.get("Section__c", "Others")
126
  if section not in ordered_menu:
127
  ordered_menu[section] = []
128
 
 
129
  if item['Name'] in added_item_names:
130
  continue
131
 
 
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
 
137
  ordered_menu[section].append(item)
138
+ added_item_names.add(item['Name'])
 
139
 
 
140
  ordered_menu = {section: items for section, items in ordered_menu.items() if items}
 
 
141
  categories = ["All", "Veg", "Non veg"]
142
 
143
  except Exception as e:
144
  print(f"Error fetching menu data: {str(e)}")
145
+ # Fallback data with video support
146
+ ordered_menu = {section: [] for section in SECTION_ORDER}
147
+ best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
148
+ ordered_menu["Best Sellers"] = [{
149
+ "Name": name,
150
+ "Price__c": "12.99",
151
+ "Description__c": f"Popular {name}",
152
+ "Image1__c": "/static/placeholder.jpg",
153
+ "Video1__c": get_valid_video_path(name),
154
+ "Total_Ordered__c": 100,
155
+ "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg"
156
+ } for name in best_sellers]
157
+
158
  categories = ["All", "Veg", "Non veg"]
159
  referral_code = 'N/A'
160
  reward_points = 0
161
 
 
162
  return render_template(
163
  "menu.html",
164
  ordered_menu=ordered_menu,
 
166
  selected_category=selected_category,
167
  referral_code=referral_code,
168
  reward_points=reward_points,
169
+ user_name=user_name,
170
+ first_letter=first_letter
171
  )
172
+
173
  @menu_blueprint.route('/api/addons', methods=['GET'])
174
  def get_addons():
175
  item_name = request.args.get('item_name')
176
  item_section = request.args.get('item_section')
177
 
 
178
  if not item_name or not item_section:
179
  return jsonify({"success": False, "error": "Item name and section are required."}), 400
180
 
181
  try:
 
182
  query = f"""
183
  SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
184
  FROM Customization_Options__c
 
187
  result = sf.query(query)
188
  addons = result.get('records', [])
189
 
 
190
  if not addons:
191
  return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
192
 
 
193
  formatted_addons = []
194
  for addon in addons:
 
195
  options = addon.get("Options__c", "")
196
+ if options:
197
+ options = options.split(", ")
198
  else:
199
+ options = []
200
 
201
  formatted_addons.append({
202
  "name": addon["Name"],
 
210
  return jsonify({"success": True, "addons": formatted_addons})
211
 
212
  except Exception as e:
213
+ print(f"Error fetching addons: {str(e)}")
 
214
  return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
215
 
216
  @menu_blueprint.route('/cart/add', methods=['POST'])
217
  def add_to_cart():
218
  try:
 
219
  data = request.json
220
  item_name = data.get('itemName', '').strip()
221
  item_price = data.get('itemPrice')
 
224
  instructions = data.get('instructions', '')
225
  category = data.get('category')
226
  section = data.get('section')
227
+ quantity = data.get('quantity', 1)
228
  customer_email = session.get('user_email')
229
 
 
230
  if not item_name or not item_price:
231
  return jsonify({"success": False, "error": "Item name and price are required."}), 400
232
 
233
  if not customer_email:
234
  return jsonify({"success": False, "error": "User email is required."}), 400
235
 
 
236
  query = f"""
237
  SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
238
  FROM Cart_Item__c
 
241
  result = sf.query(query)
242
  cart_items = result.get("records", [])
243
 
 
244
  addons_price = sum(addon['price'] for addon in addons)
245
  new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
246
 
 
247
  if cart_items:
248
  cart_item_id = cart_items[0]['Id']
249
  existing_quantity = cart_items[0]['Quantity__c']
 
251
  existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
252
  existing_instructions = cart_items[0].get('Instructions__c', "")
253
 
 
254
  combined_addons = existing_addons if existing_addons != "None" else ""
255
  if new_addons:
256
  combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
257
 
 
258
  combined_instructions = existing_instructions
259
  if instructions:
260
  combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
261
 
 
262
  combined_addons_list = combined_addons.split("; ")
263
  combined_addons_price = sum(
264
  float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
265
  )
266
 
 
267
  sf.Cart_Item__c.update(cart_item_id, {
268
+ "Quantity__c": existing_quantity + quantity,
269
  "Add_Ons__c": combined_addons,
270
  "Add_Ons_Price__c": combined_addons_price,
271
  "Instructions__c": combined_instructions,
 
274
  "Section__c": section
275
  })
276
  else:
 
277
  addons_string = "None"
278
  if addons:
279
  addons_string = new_addons
280
 
281
+ total_price = item_price * quantity + addons_price
282
 
 
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": addons_string,
290
  "Image1__c": item_image,
 
297
  return jsonify({"success": True, "message": "Item added to cart successfully."})
298
 
299
  except KeyError as e:
 
300
  return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
301
 
302
  except Exception as e:
 
303
  print(f"Error adding item to cart: {str(e)}")
304
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500