lokesh341 commited on
Commit
4d0eb18
·
verified ·
1 Parent(s): 9b87248

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +321 -12
menu.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
3
  from salesforce import get_salesforce_connection
4
  import os
@@ -24,19 +23,14 @@ 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
- # First try: Video1__c from Salesforce if provided
28
  if video_url:
29
- # If it's a complete URL (http/https)
30
  if video_url.startswith(('http://', 'https://')):
31
  return video_url
32
- # If it's a relative path (/videos/xxx.mp4)
33
  elif video_url.startswith('/'):
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://yourdomain.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
  open(PLACEHOLDER_PATH, 'wb').close()
42
  print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
@@ -78,10 +72,10 @@ def menu():
78
  cart_count_result = sf.query(cart_query)
79
  cart_item_count = cart_count_result['totalSize']
80
 
81
- # Query to fetch Menu_Item__c records including Video1__c
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
  result = sf.query(menu_query)
@@ -92,11 +86,14 @@ def menu():
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
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
  """
@@ -108,6 +105,8 @@ def menu():
108
  if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
109
  item['Total_Ordered__c'] = 0
110
  item['Video1__c'] = get_valid_video_path(item['Name'])
 
 
111
 
112
  # Merge both Menu_Item__c and Custom_Dish__c records
113
  all_items = food_items + custom_dishes
@@ -148,7 +147,6 @@ def menu():
148
 
149
  except Exception as e:
150
  print(f"Error fetching menu data: {str(e)}")
151
- # Fallback data with video support
152
  ordered_menu = {section: [] for section in SECTION_ORDER}
153
  best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
154
  ordered_menu["Best Sellers"] = [{
@@ -158,7 +156,8 @@ def menu():
158
  "Image1__c": "/static/placeholder.jpg",
159
  "Video1__c": get_valid_video_path(name),
160
  "Total_Ordered__c": 100,
161
- "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg"
 
162
  } for name in best_sellers]
163
 
164
  categories = ["All", "Veg", "Non veg"]
@@ -309,4 +308,314 @@ def add_to_cart():
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
2
  from salesforce import get_salesforce_connection
3
  import os
 
23
  Get valid video path for item with placeholder fallback
24
  Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
25
  """
 
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
 
 
34
  if not os.path.exists(PLACEHOLDER_PATH):
35
  open(PLACEHOLDER_PATH, 'wb').close()
36
  print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
 
72
  cart_count_result = sf.query(cart_query)
73
  cart_item_count = cart_count_result['totalSize']
74
 
75
+ # Query to fetch Menu_Item__c records including Ingredients__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, Ingredients__c
79
  FROM Menu_Item__c
80
  """
81
  result = sf.query(menu_query)
 
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
+ # Ensure Ingredients__c and Description__c are present
90
+ item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
91
+ item['Description__c'] = item.get('Description__c', 'No description available')
92
 
93
  # Query to fetch Custom_Dish__c records
94
  custom_dish_query = """
95
  SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
96
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Ingredients__c
97
  FROM Custom_Dish__c
98
  WHERE CreatedDate >= LAST_N_DAYS:7
99
  """
 
105
  if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
106
  item['Total_Ordered__c'] = 0
107
  item['Video1__c'] = get_valid_video_path(item['Name'])
108
+ item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
109
+ item['Description__c'] = item.get('Description__c', 'No description available')
110
 
111
  # Merge both Menu_Item__c and Custom_Dish__c records
112
  all_items = food_items + custom_dishes
 
147
 
148
  except Exception as e:
149
  print(f"Error fetching menu data: {str(e)}")
 
150
  ordered_menu = {section: [] for section in SECTION_ORDER}
151
  best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
152
  ordered_menu["Best Sellers"] = [{
 
156
  "Image1__c": "/static/placeholder.jpg",
157
  "Video1__c": get_valid_video_path(name),
158
  "Total_Ordered__c": 100,
159
+ "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
160
+ "Ingredients__c": "Sample ingredients",
161
  } for name in best_sellers]
162
 
163
  categories = ["All", "Veg", "Non veg"]
 
308
 
309
  except Exception as e:
310
  print(f"Error adding item to cart: {str(e)}")
311
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
312
+ from salesforce import get_salesforce_connection
313
+ import os
314
+
315
+ menu_blueprint = Blueprint('menu', __name__)
316
+
317
+ # Initialize Salesforce connection
318
+ sf = get_salesforce_connection()
319
+
320
+ # Constants for video handling
321
+ STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')
322
+ PLACEHOLDER_VIDEO = 'placeholder.mp4'
323
+ PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
324
+ SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
325
+
326
+ # Create placeholder video at startup if it doesn't exist
327
+ if not os.path.exists(PLACEHOLDER_PATH):
328
+ open(PLACEHOLDER_PATH, 'wb').close()
329
+ print(f"Created placeholder video at {PLACEHOLDER_PATH}")
330
+
331
+ def get_valid_video_path(item_name, video_url=None):
332
+ """
333
+ Get valid video path for item with placeholder fallback
334
+ Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
335
+ """
336
+ if video_url:
337
+ if video_url.startswith(('http://', 'https://')):
338
+ return video_url
339
+ elif video_url.startswith('/'):
340
+ return video_url
341
+ elif video_url.startswith('069'):
342
+ return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
343
+
344
+ if not os.path.exists(PLACEHOLDER_PATH):
345
+ open(PLACEHOLDER_PATH, 'wb').close()
346
+ print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
347
+
348
+ return f"/static/{PLACEHOLDER_VIDEO}"
349
+
350
+ @menu_blueprint.route("/menu", methods=["GET", "POST"])
351
+ def menu():
352
+ selected_category = request.args.get("category", "All")
353
+ user_email = session.get('user_email')
354
+
355
+ if not user_email:
356
+ user_email = request.args.get("email")
357
+ user_name = request.args.get("name")
358
+
359
+ if user_email:
360
+ session['user_email'] = user_email
361
+ session['user_name'] = user_name
362
+ else:
363
+ return redirect(url_for("login"))
364
+ else:
365
+ user_name = session.get('user_name')
366
+
367
+ first_letter = user_name[0].upper() if user_name else "A"
368
+
369
+ try:
370
+ # Fetch user referral and reward points
371
+ user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
372
+ user_result = sf.query(user_query)
373
+
374
+ if not user_result['records']:
375
+ return redirect(url_for('login'))
376
+
377
+ referral_code = user_result['records'][0].get('Referral__c', 'N/A')
378
+ reward_points = user_result['records'][0].get('Reward_Points__c', 0)
379
+
380
+ # Get cart item count
381
+ cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
382
+ cart_count_result = sf.query(cart_query)
383
+ cart_item_count = cart_count_result['totalSize']
384
+
385
+ # Query to fetch Menu_Item__c records including Ingredients__c
386
+ menu_query = """
387
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
388
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Video1__c, Ingredients__c
389
+ FROM Menu_Item__c
390
+ """
391
+ result = sf.query(menu_query)
392
+ food_items = result['records'] if 'records' in result else []
393
+
394
+ # Process items and add video paths
395
+ for item in food_items:
396
+ if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
397
+ item['Total_Ordered__c'] = 0
398
+ item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
399
+ # Ensure Ingredients__c and Description__c are present
400
+ item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
401
+ item['Description__c'] = item.get('Description__c', 'No description available')
402
+
403
+ # Query to fetch Custom_Dish__c records
404
+ custom_dish_query = """
405
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c,
406
+ Veg_NonVeg__c, Section__c, Total_Ordered__c, Ingredients__c
407
+ FROM Custom_Dish__c
408
+ WHERE CreatedDate >= LAST_N_DAYS:7
409
+ """
410
+ custom_dish_result = sf.query(custom_dish_query)
411
+ custom_dishes = custom_dish_result.get('records', [])
412
+
413
+ # Process custom dishes and add video paths
414
+ for item in custom_dishes:
415
+ if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
416
+ item['Total_Ordered__c'] = 0
417
+ item['Video1__c'] = get_valid_video_path(item['Name'])
418
+ item['Ingredients__c'] = item.get('Ingredients__c', 'Not specified')
419
+ item['Description__c'] = item.get('Description__c', 'No description available')
420
+
421
+ # Merge both Menu_Item__c and Custom_Dish__c records
422
+ all_items = food_items + custom_dishes
423
+ ordered_menu = {section: [] for section in SECTION_ORDER}
424
+
425
+ # Process best sellers
426
+ best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
427
+
428
+ if selected_category == "Veg":
429
+ best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
430
+ elif selected_category == "Non veg":
431
+ best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
432
+
433
+ best_sellers = best_sellers[:4]
434
+ if best_sellers:
435
+ ordered_menu["Best Sellers"] = best_sellers
436
+
437
+ # Organize other sections
438
+ added_item_names = set()
439
+ for item in all_items:
440
+ section = item.get("Section__c", "Others")
441
+ if section not in ordered_menu:
442
+ ordered_menu[section] = []
443
+
444
+ if item['Name'] in added_item_names:
445
+ continue
446
+
447
+ if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
448
+ continue
449
+ if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
450
+ continue
451
+
452
+ ordered_menu[section].append(item)
453
+ added_item_names.add(item['Name'])
454
+
455
+ ordered_menu = {section: items for section, items in ordered_menu.items() if items}
456
+ categories = ["All", "Veg", "Non veg"]
457
+
458
+ except Exception as e:
459
+ print(f"Error fetching menu data: {str(e)}")
460
+ ordered_menu = {section: [] for section in SECTION_ORDER}
461
+ best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
462
+ ordered_menu["Best Sellers"] = [{
463
+ "Name": name,
464
+ "Price__c": "12.99",
465
+ "Description__c": f"Popular {name}",
466
+ "Image1__c": "/static/placeholder.jpg",
467
+ "Video1__c": get_valid_video_path(name),
468
+ "Total_Ordered__c": 100,
469
+ "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg",
470
+ "Ingredients__c": "Sample ingredients",
471
+ } for name in best_sellers]
472
+
473
+ categories = ["All", "Veg", "Non veg"]
474
+ referral_code = 'N/A'
475
+ reward_points = 0
476
+ cart_item_count = 0
477
+
478
+ return render_template(
479
+ "menu.html",
480
+ ordered_menu=ordered_menu,
481
+ categories=categories,
482
+ selected_category=selected_category,
483
+ referral_code=referral_code,
484
+ reward_points=reward_points,
485
+ user_name=user_name,
486
+ first_letter=first_letter,
487
+ cart_item_count=cart_item_count
488
+ )
489
+
490
+ @menu_blueprint.route('/api/addons', methods=['GET'])
491
+ def get_addons():
492
+ item_name = request.args.get('item_name')
493
+ item_section = request.args.get('item_section')
494
+
495
+ if not item_name or not item_section:
496
+ return jsonify({"success": False, "error": "Item name and section are required."}), 400
497
+
498
+ try:
499
+ query = f"""
500
+ SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
501
+ FROM Customization_Options__c
502
+ WHERE Section__c = '{item_section}'
503
+ """
504
+ result = sf.query(query)
505
+ addons = result.get('records', [])
506
+
507
+ if not addons:
508
+ return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
509
+
510
+ formatted_addons = []
511
+ for addon in addons:
512
+ options = addon.get("Options__c", "")
513
+ if options:
514
+ options = options.split(", ")
515
+ else:
516
+ options = []
517
+
518
+ formatted_addons.append({
519
+ "name": addon["Name"],
520
+ "type": addon["Customization_Type__c"],
521
+ "options": options,
522
+ "max_selections": addon.get("Max_Selections__c", 1),
523
+ "extra_charge": addon.get("Extra_Charge__c", False),
524
+ "extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
525
+ })
526
+
527
+ return jsonify({"success": True, "addons": formatted_addons})
528
+
529
+ except Exception as e:
530
+ print(f"Error fetching addons: {str(e)}")
531
+ return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
532
+
533
+ @menu_blueprint.route('/cart/add', methods=['POST'])
534
+ def add_to_cart():
535
+ try:
536
+ data = request.json
537
+ item_name = data.get('itemName', '').strip()
538
+ item_price = data.get('itemPrice')
539
+ item_image = data.get('itemImage')
540
+ addons = data.get('addons', [])
541
+ instructions = data.get('instructions', '')
542
+ category = data.get('category')
543
+ section = data.get('section')
544
+ quantity = data.get('quantity', 1)
545
+ customer_email = session.get('user_email')
546
+
547
+ if not item_name or not item_price:
548
+ return jsonify({"success": False, "error": "Item name and price are required."}), 400
549
+
550
+ if not customer_email:
551
+ return jsonify({"success": False, "error": "User email is required."}), 400
552
+
553
+ query = f"""
554
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
555
+ FROM Cart_Item__c
556
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
557
+ """
558
+ result = sf.query(query)
559
+ cart_items = result.get("records", [])
560
+
561
+ addons_price = sum(addon['price'] for addon in addons)
562
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
563
+
564
+ if cart_items:
565
+ cart_item_id = cart_items[0]['Id']
566
+ existing_quantity = cart_items[0]['Quantity__c']
567
+ existing_addons = cart_items[0].get('Add_Ons__c', "None")
568
+ existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
569
+ existing_instructions = cart_items[0].get('Instructions__c', "")
570
+
571
+ combined_addons = existing_addons if existing_addons != "None" else ""
572
+ if new_addons:
573
+ combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
574
+
575
+ combined_instructions = existing_instructions
576
+ if instructions:
577
+ combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
578
+
579
+ combined_addons_list = combined_addons.split("; ")
580
+ combined_addons_price = sum(
581
+ float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
582
+ )
583
+
584
+ sf.Cart_Item__c.update(cart_item_id, {
585
+ "Quantity__c": existing_quantity + quantity,
586
+ "Add_Ons__c": combined_addons,
587
+ "Add_Ons_Price__c": combined_addons_price,
588
+ "Instructions__c": combined_instructions,
589
+ "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
590
+ "Category__c": category,
591
+ "Section__c": section
592
+ })
593
+ else:
594
+ addons_string = "None"
595
+ if addons:
596
+ addons_string = new_addons
597
+
598
+ total_price = item_price * quantity + addons_price
599
+
600
+ sf.Cart_Item__c.create({
601
+ "Name": item_name,
602
+ "Price__c": total_price,
603
+ "Base_Price__c": item_price,
604
+ "Quantity__c": quantity,
605
+ "Add_Ons_Price__c": addons_price,
606
+ "Add_Ons__c": addons_string,
607
+ "Image1__c": item_image,
608
+ "Customer_Email__c": customer_email,
609
+ "Instructions__c": instructions,
610
+ "Category__c": category,
611
+ "Section__c": section
612
+ })
613
+
614
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
615
+
616
+ except KeyError as e:
617
+ return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
618
+
619
+ except Exception as e:
620
+ print(f"Error adding item to cart: {str(e)}")
621
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500