lokesh341 commited on
Commit
5bb21d5
·
verified ·
1 Parent(s): 8432f97

Update menu.py

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