Update cart.py
Browse files
cart.py
CHANGED
@@ -1,8 +1,18 @@
|
|
1 |
-
from flask import Blueprint, render_template, request, session, jsonify
|
2 |
from salesforce import get_salesforce_connection
|
3 |
-
|
4 |
|
|
|
5 |
cart_blueprint = Blueprint('cart', __name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
@cart_blueprint.route("/cart", methods=["GET"])
|
7 |
def cart():
|
8 |
email = session.get('user_email')
|
@@ -10,11 +20,13 @@ def cart():
|
|
10 |
return redirect(url_for("login"))
|
11 |
|
12 |
try:
|
|
|
|
|
13 |
# Fetch cart items with Category and Section
|
14 |
result = sf.query(f"""
|
15 |
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c
|
16 |
FROM Cart_Item__c
|
17 |
-
WHERE Customer_Email__c = '{
|
18 |
""")
|
19 |
cart_items = result.get("records", [])
|
20 |
|
@@ -24,13 +36,13 @@ def cart():
|
|
24 |
customer_result = sf.query(f"""
|
25 |
SELECT Reward_Points__c
|
26 |
FROM Customer_Login__c
|
27 |
-
WHERE Email__c = '{
|
28 |
""")
|
29 |
reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
|
30 |
|
31 |
# Fetch coupons for the user
|
32 |
coupon_result = sf.query(f"""
|
33 |
-
SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{
|
34 |
""")
|
35 |
if coupon_result["records"]:
|
36 |
raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
|
@@ -43,10 +55,10 @@ def cart():
|
|
43 |
|
44 |
# If there are items in the cart, fetch suggestions
|
45 |
if cart_items:
|
46 |
-
# Get the category and section of the first item in the cart
|
47 |
first_item = cart_items[0]
|
48 |
-
item_category = first_item.get('Category__c', 'All')
|
49 |
-
item_section = first_item.get('Section__c', 'Biryanis')
|
50 |
|
51 |
# Define section-to-complementary section mapping
|
52 |
complementary_sections = {
|
@@ -58,7 +70,7 @@ def cart():
|
|
58 |
'Soft Drinks': ['Starters', 'Biryanis', 'Curries']
|
59 |
}
|
60 |
|
61 |
-
# Get the complementary sections
|
62 |
suggested_sections = complementary_sections.get(item_section, [])
|
63 |
|
64 |
# Fetch suggestions from the complementary sections
|
@@ -68,7 +80,7 @@ def cart():
|
|
68 |
query = f"""
|
69 |
SELECT Name, Price__c, Image1__c
|
70 |
FROM Menu_Item__c
|
71 |
-
WHERE Section__c = '{suggested_section}'
|
72 |
AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg')
|
73 |
LIMIT 4
|
74 |
"""
|
@@ -76,14 +88,14 @@ def cart():
|
|
76 |
query = f"""
|
77 |
SELECT Name, Price__c, Image1__c
|
78 |
FROM Menu_Item__c
|
79 |
-
WHERE Section__c = '{suggested_section}'
|
80 |
-
AND Veg_NonVeg__c = '{item_category}'
|
81 |
LIMIT 4
|
82 |
"""
|
83 |
suggestion_result = sf.query(query)
|
84 |
-
suggestions.extend(suggestion_result.get("records", []))
|
85 |
|
86 |
-
# Limit
|
87 |
if len(suggestions) > 4:
|
88 |
suggestions = suggestions[:4]
|
89 |
|
@@ -104,24 +116,65 @@ def cart():
|
|
104 |
print(f"Error fetching cart items: {e}")
|
105 |
return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[])
|
106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
@cart_blueprint.route("/add_suggestion_to_cart", methods=["POST"])
|
108 |
def add_suggestion_to_cart():
|
109 |
try:
|
110 |
# Get data from the request
|
111 |
data = request.get_json()
|
112 |
-
item_name = data.get('item_name').strip()
|
113 |
item_price = data.get('item_price')
|
114 |
item_image = data.get('item_image')
|
115 |
-
|
116 |
-
customer_email = data.get('customer_email')
|
117 |
addons = data.get('addons', [])
|
118 |
-
instructions = data.get('instructions', "")
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
#
|
121 |
addons_price = 0
|
122 |
-
addons_string = "None"
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
-
# Check if
|
125 |
query = f"""
|
126 |
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
127 |
FROM Cart_Item__c
|
@@ -130,41 +183,37 @@ def add_suggestion_to_cart():
|
|
130 |
result = sf.query(query)
|
131 |
cart_items = result.get("records", [])
|
132 |
|
133 |
-
# If item already exists in the cart, update its quantity and other details
|
134 |
if cart_items:
|
|
|
135 |
cart_item_id = cart_items[0]['Id']
|
136 |
existing_quantity = cart_items[0]['Quantity__c']
|
137 |
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
138 |
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
139 |
existing_instructions = cart_items[0].get('Instructions__c', "")
|
140 |
|
141 |
-
# Combine
|
142 |
combined_addons = existing_addons if existing_addons != "None" else ""
|
143 |
if addons:
|
144 |
-
combined_addons = f"{combined_addons}
|
145 |
|
|
|
146 |
combined_instructions = existing_instructions
|
147 |
if instructions:
|
148 |
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
149 |
|
150 |
-
|
151 |
-
combined_addons_price = sum(
|
152 |
-
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
153 |
-
)
|
154 |
|
155 |
-
# Update
|
156 |
sf.Cart_Item__c.update(cart_item_id, {
|
157 |
"Quantity__c": existing_quantity + 1,
|
158 |
-
"Add_Ons__c": combined_addons,
|
159 |
"Add_Ons_Price__c": combined_addons_price,
|
160 |
"Instructions__c": combined_instructions,
|
161 |
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
162 |
})
|
163 |
else:
|
164 |
-
#
|
165 |
total_price = float(item_price) + addons_price
|
166 |
-
|
167 |
-
# Create a new cart item in Salesforce
|
168 |
sf.Cart_Item__c.create({
|
169 |
"Name": item_name,
|
170 |
"Price__c": total_price,
|
@@ -181,24 +230,26 @@ def add_suggestion_to_cart():
|
|
181 |
|
182 |
except Exception as e:
|
183 |
print(f"Error adding item to cart: {str(e)}")
|
184 |
-
return jsonify({"success": False, "error": str(e)})
|
185 |
-
|
|
|
186 |
def remove_cart_item(item_name):
|
187 |
try:
|
188 |
customer_email = session.get('user_email')
|
189 |
if not customer_email:
|
190 |
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
|
191 |
|
|
|
|
|
192 |
query = f"""
|
193 |
SELECT Id FROM Cart_Item__c
|
194 |
-
WHERE Customer_Email__c = '{
|
195 |
"""
|
196 |
result = sf.query(query)
|
197 |
|
198 |
if result['totalSize'] == 0:
|
199 |
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
200 |
|
201 |
-
# If item exists, delete it
|
202 |
cart_item_id = result['records'][0]['Id']
|
203 |
sf.Cart_Item__c.delete(cart_item_id)
|
204 |
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
@@ -209,22 +260,19 @@ def remove_cart_item(item_name):
|
|
209 |
@cart_blueprint.route("/update_quantity", methods=["POST"])
|
210 |
def update_quantity():
|
211 |
print("Handling update_quantity request...")
|
212 |
-
data = request.json
|
213 |
-
email = data.get('email')
|
214 |
-
item_name = data.get('item_name')
|
215 |
|
216 |
try:
|
217 |
-
# Convert quantity to an integer
|
218 |
quantity = int(data.get('quantity'))
|
219 |
except (ValueError, TypeError):
|
220 |
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
|
221 |
|
222 |
-
# Validate inputs
|
223 |
if not email or not item_name or quantity is None:
|
224 |
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
|
225 |
|
226 |
try:
|
227 |
-
# Query the cart item in Salesforce
|
228 |
cart_items = sf.query(
|
229 |
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
|
230 |
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
|
@@ -233,190 +281,197 @@ def update_quantity():
|
|
233 |
if not cart_items:
|
234 |
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
235 |
|
236 |
-
# Retrieve the first matching record
|
237 |
cart_item_id = cart_items[0]['Id']
|
238 |
base_price = cart_items[0]['Base_Price__c']
|
239 |
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
240 |
|
241 |
-
# Calculate the new item price
|
242 |
new_item_price = (base_price * quantity) + addons_price
|
243 |
|
244 |
-
# Update the record in Salesforce
|
245 |
sf.Cart_Item__c.update(cart_item_id, {
|
246 |
"Quantity__c": quantity,
|
247 |
-
"Price__c": new_item_price,
|
248 |
})
|
249 |
|
250 |
-
# Recalculate the subtotal for all items in the cart
|
251 |
cart_items = sf.query(f"""
|
252 |
SELECT Price__c, Add_Ons_Price__c
|
253 |
FROM Cart_Item__c
|
254 |
WHERE Customer_Email__c = '{email}'
|
255 |
""")['records']
|
256 |
-
new_subtotal = sum(item['Price__c'] for item in cart_items)
|
257 |
|
258 |
-
# Return updated item price and subtotal
|
259 |
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
260 |
|
261 |
except Exception as e:
|
262 |
print(f"Error updating quantity: {str(e)}")
|
263 |
return jsonify({"success": False, "error": str(e)}), 500
|
264 |
|
265 |
-
|
266 |
@cart_blueprint.route("/checkout", methods=["POST"])
|
267 |
def checkout():
|
268 |
email = session.get('user_email')
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}") # Debugging session data
|
273 |
-
|
274 |
-
if not email or not user_id:
|
275 |
-
print("User not logged in")
|
276 |
-
return jsonify({"success": False, "message": "User not logged in"})
|
277 |
|
278 |
try:
|
279 |
-
|
|
|
280 |
data = request.json
|
281 |
selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
|
282 |
-
# Now selected_coupon will be None if it's not provided or empty, or a valid string otherwise
|
283 |
-
print(f"Selected Coupon: {selected_coupon}") # Debugging selected coupon
|
284 |
|
285 |
-
# Fetch cart items
|
286 |
result = sf.query(f"""
|
287 |
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
288 |
FROM Cart_Item__c
|
289 |
-
WHERE Customer_Email__c = '{
|
290 |
""")
|
291 |
-
|
292 |
-
# Log the cart items to see if they are fetched correctly
|
293 |
cart_items = result.get("records", [])
|
294 |
-
print(f"Cart Items Retrieved: {cart_items}") # Debugging log
|
295 |
-
|
296 |
if not cart_items:
|
297 |
-
|
298 |
-
return jsonify({"success": False, "message": "Cart is empty"})
|
299 |
-
|
300 |
-
total_price = sum(item['Price__c'] for item in cart_items)
|
301 |
-
print(f"Total Price: {total_price}") # Debugging total price calculation
|
302 |
|
|
|
303 |
discount = 0
|
304 |
|
305 |
-
#
|
306 |
-
|
307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
308 |
""")
|
309 |
-
|
|
|
|
|
310 |
|
311 |
-
|
312 |
-
|
|
|
|
|
313 |
|
|
|
314 |
if selected_coupon:
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
|
327 |
-
updated_coupons_str = "\n".join(updated_coupons).strip()
|
328 |
-
|
329 |
-
print(f"Updated Coupons After Removal: {updated_coupons}") # Debugging updated coupons
|
330 |
-
|
331 |
-
# If no coupons remain, set the field to None (not empty string)
|
332 |
-
if not updated_coupons:
|
333 |
-
updated_coupons_str = None # Set to None if no coupons are left
|
334 |
-
print("No Coupons Remaining. Setting to None") # Debugging no coupons left
|
335 |
-
|
336 |
-
# Update the Referral_Coupon__c record
|
337 |
-
print(f"Updating Referral Coupon: {updated_coupons_str}") # Debugging update to Salesforce
|
338 |
-
sf.Referral_Coupon__c.update(referral_coupon_id, {
|
339 |
-
"Coupon_Code__c": updated_coupons_str
|
340 |
-
})
|
341 |
-
else:
|
342 |
-
# If no coupon is selected, add reward points
|
343 |
-
reward_points_to_add = total_price * 0.10 # Example: 10% reward points
|
344 |
-
print(f"Reward Points to Add: {reward_points_to_add}") # Debugging reward points
|
345 |
|
346 |
-
|
|
|
|
|
347 |
customer_record = sf.query(f"""
|
348 |
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
349 |
-
WHERE Email__c = '{
|
350 |
""")
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
if customer:
|
355 |
-
current_reward_points = customer.get("Reward_Points__c") or 0
|
356 |
-
print(f"Current Reward Points: {current_reward_points}") # Debugging current reward points
|
357 |
new_reward_points = current_reward_points + reward_points_to_add
|
358 |
-
print(f"New Reward Points: {new_reward_points}") # Debugging new reward points calculation
|
359 |
-
|
360 |
-
# Update reward points
|
361 |
sf.Customer_Login__c.update(customer["Id"], {
|
362 |
"Reward_Points__c": new_reward_points
|
363 |
})
|
364 |
|
365 |
-
#
|
366 |
-
total_bill = total_price - discount
|
367 |
-
print(f"Total Bill After Discount: {total_bill}") # Debugging final total bill
|
368 |
-
|
369 |
-
# Store all order details (before deleting cart items)
|
370 |
order_details = "\n".join(
|
371 |
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
|
372 |
f"Instructions: {item.get('Instructions__c', 'None')} | "
|
373 |
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
|
374 |
for item in cart_items
|
375 |
)
|
376 |
-
print(f"Order Details: {order_details}") # Debugging order details
|
377 |
|
378 |
-
# Fetch Customer ID
|
379 |
customer_query = sf.query(f"""
|
380 |
SELECT Id FROM Customer_Login__c
|
381 |
-
WHERE Email__c = '{
|
382 |
""")
|
383 |
-
|
384 |
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
385 |
-
print(f"Customer ID: {customer_id}") # Debugging customer ID retrieval
|
386 |
-
|
387 |
if not customer_id:
|
388 |
-
|
389 |
-
|
390 |
-
table_number = table_number if table_number != 'null' else None
|
391 |
-
# Store order data
|
392 |
order_data = {
|
393 |
"Customer_Name__c": user_id,
|
394 |
"Customer_Email__c": email,
|
395 |
-
"Total_Amount__c":
|
396 |
"Discount__c": discount,
|
397 |
-
"Total_Bill__c":
|
398 |
"Order_Status__c": "Pending",
|
399 |
"Customer2__c": customer_id,
|
400 |
"Order_Details__c": order_details,
|
401 |
-
"Table_Number__c": table_number
|
402 |
}
|
403 |
-
print(f"Order Data: {order_data}") # Debugging order data
|
404 |
-
|
405 |
-
# Create the order in Salesforce
|
406 |
order_response = sf.Order__c.create(order_data)
|
407 |
-
print(f"Order Response: {order_response}") # Debugging order creation response
|
408 |
|
409 |
-
#
|
410 |
if order_response:
|
411 |
-
# Only delete cart items after the order is created
|
412 |
for item in cart_items:
|
413 |
-
print(f"Deleting Cart Item: {item['Id']}") # Debugging cart item deletion
|
414 |
sf.Cart_Item__c.delete(item["Id"])
|
415 |
|
416 |
-
return jsonify({"success": True, "message": "Order placed successfully!"
|
417 |
|
418 |
except Exception as e:
|
419 |
-
print(f"Error during
|
420 |
-
return jsonify({"success": False, "error": str(e)})
|
421 |
-
|
422 |
-
|
|
|
1 |
+
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
|
2 |
from salesforce import get_salesforce_connection
|
3 |
+
import re
|
4 |
|
5 |
+
sf = get_salesforce_connection()
|
6 |
cart_blueprint = Blueprint('cart', __name__)
|
7 |
+
|
8 |
+
# Utility function to sanitize SOQL inputs
|
9 |
+
def sanitize_input(value):
|
10 |
+
"""Remove potentially dangerous characters for SOQL injection."""
|
11 |
+
if value:
|
12 |
+
# Remove quotes, semicolons, and other dangerous characters
|
13 |
+
value = re.sub(r'[;\'"\\]', '', value)
|
14 |
+
return value
|
15 |
+
|
16 |
@cart_blueprint.route("/cart", methods=["GET"])
|
17 |
def cart():
|
18 |
email = session.get('user_email')
|
|
|
20 |
return redirect(url_for("login"))
|
21 |
|
22 |
try:
|
23 |
+
# Sanitize email input
|
24 |
+
sanitized_email = sanitize_input(email)
|
25 |
# Fetch cart items with Category and Section
|
26 |
result = sf.query(f"""
|
27 |
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c
|
28 |
FROM Cart_Item__c
|
29 |
+
WHERE Customer_Email__c = '{sanitized_email}'
|
30 |
""")
|
31 |
cart_items = result.get("records", [])
|
32 |
|
|
|
36 |
customer_result = sf.query(f"""
|
37 |
SELECT Reward_Points__c
|
38 |
FROM Customer_Login__c
|
39 |
+
WHERE Email__c = '{sanitized_email}'
|
40 |
""")
|
41 |
reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
|
42 |
|
43 |
# Fetch coupons for the user
|
44 |
coupon_result = sf.query(f"""
|
45 |
+
SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{sanitized_email}'
|
46 |
""")
|
47 |
if coupon_result["records"]:
|
48 |
raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
|
|
|
55 |
|
56 |
# If there are items in the cart, fetch suggestions
|
57 |
if cart_items:
|
58 |
+
# Get the category and section of the first item in the cart
|
59 |
first_item = cart_items[0]
|
60 |
+
item_category = first_item.get('Category__c', 'All')
|
61 |
+
item_section = first_item.get('Section__c', 'Biryanis')
|
62 |
|
63 |
# Define section-to-complementary section mapping
|
64 |
complementary_sections = {
|
|
|
70 |
'Soft Drinks': ['Starters', 'Biryanis', 'Curries']
|
71 |
}
|
72 |
|
73 |
+
# Get the complementary sections
|
74 |
suggested_sections = complementary_sections.get(item_section, [])
|
75 |
|
76 |
# Fetch suggestions from the complementary sections
|
|
|
80 |
query = f"""
|
81 |
SELECT Name, Price__c, Image1__c
|
82 |
FROM Menu_Item__c
|
83 |
+
WHERE Section__c = '{sanitize_input(suggested_section)}'
|
84 |
AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg')
|
85 |
LIMIT 4
|
86 |
"""
|
|
|
88 |
query = f"""
|
89 |
SELECT Name, Price__c, Image1__c
|
90 |
FROM Menu_Item__c
|
91 |
+
WHERE Section__c = '{sanitize_input(suggested_section)}'
|
92 |
+
AND Veg_NonVeg__c = '{sanitize_input(item_category)}'
|
93 |
LIMIT 4
|
94 |
"""
|
95 |
suggestion_result = sf.query(query)
|
96 |
+
suggestions.extend(suggestion_result.get("records", []))
|
97 |
|
98 |
+
# Limit to 4 suggestions
|
99 |
if len(suggestions) > 4:
|
100 |
suggestions = suggestions[:4]
|
101 |
|
|
|
116 |
print(f"Error fetching cart items: {e}")
|
117 |
return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[])
|
118 |
|
119 |
+
@cart_blueprint.route("/fetch_menu_items", methods=["GET"])
|
120 |
+
def fetch_menu_items():
|
121 |
+
try:
|
122 |
+
# Get query parameters for filtering (optional)
|
123 |
+
category = request.args.get('category', 'All')
|
124 |
+
section = request.args.get('section', '')
|
125 |
+
|
126 |
+
# Sanitize inputs
|
127 |
+
category = sanitize_input(category)
|
128 |
+
section = sanitize_input(section)
|
129 |
+
|
130 |
+
# Build SOQL query
|
131 |
+
query = """
|
132 |
+
SELECT Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
|
133 |
+
FROM Menu_Item__c
|
134 |
+
WHERE Active__c = true
|
135 |
+
"""
|
136 |
+
if category != 'All':
|
137 |
+
query += f" AND Veg_NonVeg__c = '{category}'"
|
138 |
+
if section:
|
139 |
+
query += f" AND Section__c = '{section}'"
|
140 |
+
query += " LIMIT 20"
|
141 |
+
|
142 |
+
result = sf.query(query)
|
143 |
+
menu_items = result.get("records", [])
|
144 |
+
|
145 |
+
return jsonify({"success": True, "menu_items": menu_items})
|
146 |
+
|
147 |
+
except Exception as e:
|
148 |
+
print(f"Error fetching menu items: {e}")
|
149 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
150 |
+
|
151 |
@cart_blueprint.route("/add_suggestion_to_cart", methods=["POST"])
|
152 |
def add_suggestion_to_cart():
|
153 |
try:
|
154 |
# Get data from the request
|
155 |
data = request.get_json()
|
156 |
+
item_name = sanitize_input(data.get('item_name').strip())
|
157 |
item_price = data.get('item_price')
|
158 |
item_image = data.get('item_image')
|
159 |
+
customer_email = sanitize_input(data.get('customer_email'))
|
|
|
160 |
addons = data.get('addons', [])
|
161 |
+
instructions = sanitize_input(data.get('instructions', ""))
|
162 |
+
|
163 |
+
# Validate inputs
|
164 |
+
if not all([item_name, item_price, customer_email]):
|
165 |
+
return jsonify({"success": False, "error": "Missing required fields"}), 400
|
166 |
|
167 |
+
# Process add-ons
|
168 |
addons_price = 0
|
169 |
+
addons_string = ", ".join(addons) if addons else "None"
|
170 |
+
|
171 |
+
if addons:
|
172 |
+
# Assuming addons are in format "Name ($Price)"
|
173 |
+
addons_price = sum(
|
174 |
+
float(addon.split("($")[1][:-1]) for addon in addons if "($" in addon
|
175 |
+
)
|
176 |
|
177 |
+
# Check if item exists in cart
|
178 |
query = f"""
|
179 |
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
180 |
FROM Cart_Item__c
|
|
|
183 |
result = sf.query(query)
|
184 |
cart_items = result.get("records", [])
|
185 |
|
|
|
186 |
if cart_items:
|
187 |
+
# Update existing item
|
188 |
cart_item_id = cart_items[0]['Id']
|
189 |
existing_quantity = cart_items[0]['Quantity__c']
|
190 |
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
191 |
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
192 |
existing_instructions = cart_items[0].get('Instructions__c', "")
|
193 |
|
194 |
+
# Combine add-ons
|
195 |
combined_addons = existing_addons if existing_addons != "None" else ""
|
196 |
if addons:
|
197 |
+
combined_addons = f"{combined_addons}, {addons_string}".strip(", ")
|
198 |
|
199 |
+
# Combine instructions
|
200 |
combined_instructions = existing_instructions
|
201 |
if instructions:
|
202 |
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
203 |
|
204 |
+
combined_addons_price = existing_addons_price + addons_price
|
|
|
|
|
|
|
205 |
|
206 |
+
# Update cart item
|
207 |
sf.Cart_Item__c.update(cart_item_id, {
|
208 |
"Quantity__c": existing_quantity + 1,
|
209 |
+
"Add_Ons__c": combined_addons if combined_addons else "None",
|
210 |
"Add_Ons_Price__c": combined_addons_price,
|
211 |
"Instructions__c": combined_instructions,
|
212 |
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
213 |
})
|
214 |
else:
|
215 |
+
# Create new cart item
|
216 |
total_price = float(item_price) + addons_price
|
|
|
|
|
217 |
sf.Cart_Item__c.create({
|
218 |
"Name": item_name,
|
219 |
"Price__c": total_price,
|
|
|
230 |
|
231 |
except Exception as e:
|
232 |
print(f"Error adding item to cart: {str(e)}")
|
233 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
234 |
+
|
235 |
+
@cart_blueprint.route("/remove/<item_name>", methods=["POST"])
|
236 |
def remove_cart_item(item_name):
|
237 |
try:
|
238 |
customer_email = session.get('user_email')
|
239 |
if not customer_email:
|
240 |
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
|
241 |
|
242 |
+
sanitized_email = sanitize_input(customer_email)
|
243 |
+
sanitized_item_name = sanitize_input(item_name)
|
244 |
query = f"""
|
245 |
SELECT Id FROM Cart_Item__c
|
246 |
+
WHERE Customer_Email__c = '{sanitized_email}' AND Name = '{sanitized_item_name}'
|
247 |
"""
|
248 |
result = sf.query(query)
|
249 |
|
250 |
if result['totalSize'] == 0:
|
251 |
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
252 |
|
|
|
253 |
cart_item_id = result['records'][0]['Id']
|
254 |
sf.Cart_Item__c.delete(cart_item_id)
|
255 |
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
|
|
260 |
@cart_blueprint.route("/update_quantity", methods=["POST"])
|
261 |
def update_quantity():
|
262 |
print("Handling update_quantity request...")
|
263 |
+
data = request.json
|
264 |
+
email = sanitize_input(data.get('email'))
|
265 |
+
item_name = sanitize_input(data.get('item_name'))
|
266 |
|
267 |
try:
|
|
|
268 |
quantity = int(data.get('quantity'))
|
269 |
except (ValueError, TypeError):
|
270 |
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
|
271 |
|
|
|
272 |
if not email or not item_name or quantity is None:
|
273 |
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
|
274 |
|
275 |
try:
|
|
|
276 |
cart_items = sf.query(
|
277 |
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
|
278 |
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
|
|
|
281 |
if not cart_items:
|
282 |
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
283 |
|
|
|
284 |
cart_item_id = cart_items[0]['Id']
|
285 |
base_price = cart_items[0]['Base_Price__c']
|
286 |
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
287 |
|
|
|
288 |
new_item_price = (base_price * quantity) + addons_price
|
289 |
|
|
|
290 |
sf.Cart_Item__c.update(cart_item_id, {
|
291 |
"Quantity__c": quantity,
|
292 |
+
"Price__c": new_item_price,
|
293 |
})
|
294 |
|
|
|
295 |
cart_items = sf.query(f"""
|
296 |
SELECT Price__c, Add_Ons_Price__c
|
297 |
FROM Cart_Item__c
|
298 |
WHERE Customer_Email__c = '{email}'
|
299 |
""")['records']
|
300 |
+
new_subtotal = sum(item['Price__c'] for item in cart_items)
|
301 |
|
|
|
302 |
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
303 |
|
304 |
except Exception as e:
|
305 |
print(f"Error updating quantity: {str(e)}")
|
306 |
return jsonify({"success": False, "error": str(e)}), 500
|
307 |
|
|
|
308 |
@cart_blueprint.route("/checkout", methods=["POST"])
|
309 |
def checkout():
|
310 |
email = session.get('user_email')
|
311 |
+
if not email:
|
312 |
+
return jsonify({"success": False, "message": "User not logged in"}), 401
|
|
|
|
|
|
|
|
|
|
|
|
|
313 |
|
314 |
try:
|
315 |
+
sanitized_email = sanitize_input(email)
|
316 |
+
# Fetch selected coupon
|
317 |
data = request.json
|
318 |
selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
|
|
|
|
|
319 |
|
320 |
+
# Fetch cart items
|
321 |
result = sf.query(f"""
|
322 |
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
323 |
FROM Cart_Item__c
|
324 |
+
WHERE Customer_Email__c = '{sanitized_email}'
|
325 |
""")
|
|
|
|
|
326 |
cart_items = result.get("records", [])
|
|
|
|
|
327 |
if not cart_items:
|
328 |
+
return jsonify({"success": False, "message": "Cart is empty"}), 400
|
|
|
|
|
|
|
|
|
329 |
|
330 |
+
subtotal = sum(item['Price__c'] for item in cart_items)
|
331 |
discount = 0
|
332 |
|
333 |
+
# Apply coupon if selected
|
334 |
+
if selected_coupon:
|
335 |
+
discount = subtotal * 0.10 # 10% discount
|
336 |
+
|
337 |
+
total = subtotal - discount
|
338 |
+
|
339 |
+
# Prepare cart items for response
|
340 |
+
bill_items = [
|
341 |
+
{
|
342 |
+
"name": item['Name'],
|
343 |
+
"quantity": item['Quantity__c'],
|
344 |
+
"price": item['Price__c'],
|
345 |
+
"addons": item.get('Add_Ons__c', 'None'),
|
346 |
+
"instructions": item.get('Instructions__c', 'None'),
|
347 |
+
"image": item['Image1__c']
|
348 |
+
} for item in cart_items
|
349 |
+
]
|
350 |
+
|
351 |
+
# Fetch menu items for "Anything else you want?"
|
352 |
+
menu_query = """
|
353 |
+
SELECT Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
|
354 |
+
FROM Menu_Item__c
|
355 |
+
WHERE Active__c = true
|
356 |
+
LIMIT 20
|
357 |
+
"""
|
358 |
+
menu_result = sf.query(menu_query)
|
359 |
+
menu_items = menu_result.get("records", [])
|
360 |
+
|
361 |
+
return jsonify({
|
362 |
+
"success": True,
|
363 |
+
"cart": {
|
364 |
+
"items": bill_items,
|
365 |
+
"subtotal": subtotal,
|
366 |
+
"discount": discount,
|
367 |
+
"total": total,
|
368 |
+
"selected_coupon": selected_coupon
|
369 |
+
},
|
370 |
+
"menu_items": menu_items
|
371 |
+
})
|
372 |
+
|
373 |
+
except Exception as e:
|
374 |
+
print(f"Error during checkout: {str(e)}")
|
375 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
376 |
+
|
377 |
+
@cart_blueprint.route("/submit_order", methods=["POST"])
|
378 |
+
def submit_order():
|
379 |
+
email = session.get('user_email')
|
380 |
+
user_id = session.get('user_name')
|
381 |
+
table_number = session.get('table_number')
|
382 |
+
|
383 |
+
if not email or not user_id:
|
384 |
+
return jsonify({"success": False, "message": "User not logged in"}), 401
|
385 |
+
|
386 |
+
try:
|
387 |
+
sanitized_email = sanitize_input(email)
|
388 |
+
data = request.json
|
389 |
+
cart = data.get("cart")
|
390 |
+
if not cart:
|
391 |
+
return jsonify({"success": False, "message": "Cart data is required"}), 400
|
392 |
+
|
393 |
+
# Fetch cart items to validate
|
394 |
+
result = sf.query(f"""
|
395 |
+
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
396 |
+
FROM Cart_Item__c
|
397 |
+
WHERE Customer_Email__c = '{sanitized_email}'
|
398 |
""")
|
399 |
+
cart_items = result.get("records", [])
|
400 |
+
if not cart_items:
|
401 |
+
return jsonify({"success": False, "message": "Cart is empty"}), 400
|
402 |
|
403 |
+
subtotal = cart.get("subtotal")
|
404 |
+
discount = cart.get("discount", 0)
|
405 |
+
total = cart.get("total")
|
406 |
+
selected_coupon = cart.get("selected_coupon")
|
407 |
|
408 |
+
# Handle coupon redemption
|
409 |
if selected_coupon:
|
410 |
+
coupon_query = sf.query(f"""
|
411 |
+
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{sanitized_email}'
|
412 |
+
""")
|
413 |
+
if coupon_query["records"]:
|
414 |
+
referral_coupon_id = coupon_query["records"][0]["Id"]
|
415 |
+
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
|
416 |
+
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
|
417 |
+
updated_coupons_str = "\n".join(updated_coupons).strip() or None
|
418 |
+
sf.Referral_Coupon__c.update(referral_coupon_id, {
|
419 |
+
"Coupon_Code__c": updated_coupons_str
|
420 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
421 |
|
422 |
+
# Add reward points if no coupon
|
423 |
+
if not selected_coupon:
|
424 |
+
reward_points_to_add = subtotal * 0.10
|
425 |
customer_record = sf.query(f"""
|
426 |
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
427 |
+
WHERE Email__c = '{sanitized_email}'
|
428 |
""")
|
429 |
+
if customer_record["records"]:
|
430 |
+
customer = customer_record["records"][0]
|
431 |
+
current_reward_points = customer.get("Reward_Points__c", 0)
|
|
|
|
|
|
|
432 |
new_reward_points = current_reward_points + reward_points_to_add
|
|
|
|
|
|
|
433 |
sf.Customer_Login__c.update(customer["Id"], {
|
434 |
"Reward_Points__c": new_reward_points
|
435 |
})
|
436 |
|
437 |
+
# Prepare order details
|
|
|
|
|
|
|
|
|
438 |
order_details = "\n".join(
|
439 |
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
|
440 |
f"Instructions: {item.get('Instructions__c', 'None')} | "
|
441 |
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
|
442 |
for item in cart_items
|
443 |
)
|
|
|
444 |
|
445 |
+
# Fetch Customer ID
|
446 |
customer_query = sf.query(f"""
|
447 |
SELECT Id FROM Customer_Login__c
|
448 |
+
WHERE Email__c = '{sanitized_email}'
|
449 |
""")
|
|
|
450 |
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
|
|
|
|
451 |
if not customer_id:
|
452 |
+
return jsonify({"success": False, "message": "Customer record not found"}), 404
|
453 |
+
|
454 |
+
table_number = table_number if table_number != 'null' else None
|
|
|
455 |
order_data = {
|
456 |
"Customer_Name__c": user_id,
|
457 |
"Customer_Email__c": email,
|
458 |
+
"Total_Amount__c": subtotal,
|
459 |
"Discount__c": discount,
|
460 |
+
"Total_Bill__c": total,
|
461 |
"Order_Status__c": "Pending",
|
462 |
"Customer2__c": customer_id,
|
463 |
"Order_Details__c": order_details,
|
464 |
+
"Table_Number__c": table_number
|
465 |
}
|
|
|
|
|
|
|
466 |
order_response = sf.Order__c.create(order_data)
|
|
|
467 |
|
468 |
+
# Delete cart items
|
469 |
if order_response:
|
|
|
470 |
for item in cart_items:
|
|
|
471 |
sf.Cart_Item__c.delete(item["Id"])
|
472 |
|
473 |
+
return jsonify({"success": True, "message": "Order placed successfully!"})
|
474 |
|
475 |
except Exception as e:
|
476 |
+
print(f"Error during order submission: {str(e)}")
|
477 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
|
|
|