DSatishchandra commited on
Commit
867e7b9
·
verified ·
1 Parent(s): effa2ab

Create Menu_page.py

Browse files
Files changed (1) hide show
  1. Menu_page.py +225 -0
Menu_page.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @app.route("/menu", methods=["GET", "POST"])
2
+ def menu():
3
+ selected_category = request.args.get("category", "All")
4
+ user_email = session.get('user_email')
5
+
6
+ if not user_email:
7
+ user_email = request.args.get("email")
8
+ user_name = request.args.get("name")
9
+
10
+ if user_email:
11
+ session['user_email'] = user_email
12
+ session['user_name'] = user_name # Store name in session
13
+ else:
14
+ return redirect(url_for("login"))
15
+ else:
16
+ user_name = session.get('user_name') # Get name from session if it's already stored
17
+
18
+ # Get the first letter of the user's name (make it uppercase for consistency)
19
+ first_letter = user_name[0].upper() if user_name else "A"
20
+
21
+ try:
22
+ # Fetch user referral and reward points
23
+ user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
24
+ user_result = sf.query(user_query)
25
+
26
+ if not user_result['records']:
27
+ return redirect(url_for('login'))
28
+
29
+ referral_code = user_result['records'][0].get('Referral__c', 'N/A')
30
+ reward_points = user_result['records'][0].get('Reward_Points__c', 0)
31
+
32
+ # Query to fetch Menu_Item__c records including Total_Ordered__c for best sellers
33
+ menu_query = """
34
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
35
+ FROM Menu_Item__c
36
+ """
37
+ result = sf.query(menu_query)
38
+ food_items = result['records'] if 'records' in result else []
39
+
40
+ # Ensure Total_Ordered__c has a valid value
41
+ for item in food_items:
42
+ if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
43
+ item['Total_Ordered__c'] = 0 # Default value
44
+
45
+ # Query to fetch Custom_Dish__c records created within the last 7 days with Total_Ordered__c > 10
46
+ custom_dish_query = """
47
+ SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
48
+ FROM Custom_Dish__c
49
+ WHERE CreatedDate >= LAST_N_DAYS:7
50
+ """
51
+ custom_dish_result = sf.query(custom_dish_query)
52
+ custom_dishes = custom_dish_result['records'] if 'records' in custom_dish_result else []
53
+
54
+ # Merge both Menu_Item__c and Custom_Dish__c records into the ordered menu
55
+ all_items = food_items + custom_dishes
56
+
57
+ # Define the order of sections, adding "Best Sellers" at the top
58
+ section_order = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
59
+ ordered_menu = {section: [] for section in section_order}
60
+
61
+ # Sort items by Total_Ordered__c in descending order and pick top 4 as best sellers
62
+ best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
63
+
64
+ if selected_category == "Veg":
65
+ best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
66
+ elif selected_category == "Non veg":
67
+ best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
68
+
69
+ # Take only the top 4 best sellers after filtering
70
+ best_sellers = best_sellers[:4]
71
+
72
+ # Ensure "Best Sellers" is added only if there are items after filtering
73
+ if best_sellers:
74
+ ordered_menu["Best Sellers"] = best_sellers
75
+
76
+ # Create a set to track item names already added to prevent duplicates
77
+ added_item_names = set()
78
+
79
+ # Filter and organize menu items based on category and section (to avoid duplicates)
80
+ for item in all_items:
81
+ section = item.get("Section__c", "Others") # Default to "Others" if missing
82
+ if section not in ordered_menu:
83
+ ordered_menu[section] = []
84
+
85
+ # Skip item if it's already been added to avoid duplicates
86
+ if item['Name'] in added_item_names:
87
+ continue
88
+
89
+ # Apply category filters
90
+ if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
91
+ continue
92
+ if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
93
+ continue
94
+
95
+ ordered_menu[section].append(item)
96
+ added_item_names.add(item['Name']) # Add item to the set of added items
97
+ print(f"Added item to {section}: {item['Name']}") # Debugging
98
+
99
+ # Remove empty sections
100
+ ordered_menu = {section: items for section, items in ordered_menu.items() if items}
101
+ print(f"Final ordered menu: {ordered_menu.keys()}") # Debugging
102
+
103
+ categories = ["All", "Veg", "Non veg"]
104
+
105
+ except Exception as e:
106
+ print(f"Error fetching menu data: {str(e)}")
107
+ ordered_menu = {}
108
+ categories = ["All", "Veg", "Non veg"]
109
+ referral_code = 'N/A'
110
+ reward_points = 0
111
+
112
+ # Pass the user's first letter (first_letter) to the template
113
+ return render_template(
114
+ "menu.html",
115
+ ordered_menu=ordered_menu,
116
+ categories=categories,
117
+ selected_category=selected_category,
118
+ referral_code=referral_code,
119
+ reward_points=reward_points,
120
+ user_name=user_name, # Pass name to the template
121
+ first_letter=first_letter # Pass first letter to the template
122
+ )
123
+
124
+ @app.route('/cart/add', methods=['POST'])
125
+ def add_to_cart():
126
+ try:
127
+ # Get data from request
128
+ data = request.json
129
+ item_name = data.get('itemName', '').strip()
130
+ item_price = data.get('itemPrice')
131
+ item_image = data.get('itemImage')
132
+ addons = data.get('addons', [])
133
+ instructions = data.get('instructions', '')
134
+ category = data.get('category')
135
+ section = data.get('section')
136
+ quantity = data.get('quantity', 1) # Get the quantity field from the request
137
+ customer_email = session.get('user_email')
138
+
139
+ # Basic validation for required fields
140
+ if not item_name or not item_price:
141
+ return jsonify({"success": False, "error": "Item name and price are required."}), 400
142
+
143
+ if not customer_email:
144
+ return jsonify({"success": False, "error": "User email is required."}), 400
145
+
146
+ # Query to check if the item is already in the cart
147
+ query = f"""
148
+ SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
149
+ FROM Cart_Item__c
150
+ WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
151
+ """
152
+ result = sf.query(query)
153
+ cart_items = result.get("records", [])
154
+
155
+ # Calculate the total price for the addons
156
+ addons_price = sum(addon['price'] for addon in addons)
157
+ new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
158
+
159
+ # If the item is already in the cart, update it
160
+ if cart_items:
161
+ cart_item_id = cart_items[0]['Id']
162
+ existing_quantity = cart_items[0]['Quantity__c']
163
+ existing_addons = cart_items[0].get('Add_Ons__c', "None")
164
+ existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
165
+ existing_instructions = cart_items[0].get('Instructions__c', "")
166
+
167
+ # Combine the new addons with the existing ones
168
+ combined_addons = existing_addons if existing_addons != "None" else ""
169
+ if new_addons:
170
+ combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
171
+
172
+ # Combine existing instructions with new instructions
173
+ combined_instructions = existing_instructions
174
+ if instructions:
175
+ combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
176
+
177
+ # Calculate total addons price
178
+ combined_addons_list = combined_addons.split("; ")
179
+ combined_addons_price = sum(
180
+ float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
181
+ )
182
+
183
+ # Update the cart item in Salesforce (updating quantity)
184
+ sf.Cart_Item__c.update(cart_item_id, {
185
+ "Quantity__c": existing_quantity + quantity, # Add the selected quantity
186
+ "Add_Ons__c": combined_addons,
187
+ "Add_Ons_Price__c": combined_addons_price,
188
+ "Instructions__c": combined_instructions,
189
+ "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
190
+ "Category__c": category,
191
+ "Section__c": section
192
+ })
193
+ else:
194
+ # If the item is not already in the cart, create a new entry
195
+ addons_string = "None"
196
+ if addons:
197
+ addons_string = new_addons
198
+
199
+ total_price = item_price * quantity + addons_price # Multiply by the quantity
200
+
201
+ # Create new cart item in Salesforce
202
+ sf.Cart_Item__c.create({
203
+ "Name": item_name,
204
+ "Price__c": total_price,
205
+ "Base_Price__c": item_price,
206
+ "Quantity__c": quantity, # Use the selected quantity
207
+ "Add_Ons_Price__c": addons_price,
208
+ "Add_Ons__c": addons_string,
209
+ "Image1__c": item_image,
210
+ "Customer_Email__c": customer_email,
211
+ "Instructions__c": instructions,
212
+ "Category__c": category,
213
+ "Section__c": section
214
+ })
215
+
216
+ return jsonify({"success": True, "message": "Item added to cart successfully."})
217
+
218
+ except KeyError as e:
219
+ # Handle missing expected keys in request data
220
+ return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
221
+
222
+ except Exception as e:
223
+ # Log the error for debugging and return a general error message
224
+ print(f"Error adding item to cart: {str(e)}")
225
+ return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500