Spaces:
Runtime error
Runtime error
Update cart.py
Browse files
cart.py
CHANGED
@@ -1,8 +1,9 @@
|
|
1 |
-
from flask import Blueprint, render_template, request, session, jsonify
|
2 |
from salesforce import get_salesforce_connection
|
3 |
-
sf = get_salesforce_connection()
|
4 |
|
|
|
5 |
cart_blueprint = Blueprint('cart', __name__)
|
|
|
6 |
@cart_blueprint.route("/cart", methods=["GET"])
|
7 |
def cart():
|
8 |
email = session.get('user_email')
|
@@ -43,15 +44,16 @@ 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 = {
|
53 |
'Breads': ['Curries', 'Biryanis', 'Starters'],
|
54 |
-
'Biryanis': ['Curries', 'Starters', '
|
|
|
55 |
'Curries': ['Biryanis', 'Breads', 'Starters'],
|
56 |
'Starters': ['Biryanis', 'Curries', 'Desserts'],
|
57 |
'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'],
|
@@ -81,12 +83,9 @@ def cart():
|
|
81 |
LIMIT 4
|
82 |
"""
|
83 |
suggestion_result = sf.query(query)
|
84 |
-
suggestions.extend(suggestion_result.get("records", []))
|
85 |
-
|
86 |
-
# Limit the number of suggestions to 4
|
87 |
if len(suggestions) > 4:
|
88 |
suggestions = suggestions[:4]
|
89 |
-
|
90 |
except Exception as e:
|
91 |
print(f"Error fetching suggestions: {e}")
|
92 |
|
@@ -107,21 +106,17 @@ def cart():
|
|
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 |
-
item_id = data.get('item_id')
|
116 |
customer_email = data.get('customer_email')
|
117 |
addons = data.get('addons', [])
|
118 |
instructions = data.get('instructions', "")
|
119 |
|
120 |
-
# Default values if addons and instructions are not provided
|
121 |
addons_price = 0
|
122 |
addons_string = "None"
|
123 |
|
124 |
-
# Check if the customer already has this item in their cart
|
125 |
query = f"""
|
126 |
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
127 |
FROM Cart_Item__c
|
@@ -130,7 +125,6 @@ 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']
|
@@ -138,7 +132,6 @@ def add_suggestion_to_cart():
|
|
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 existing and new addons
|
142 |
combined_addons = existing_addons if existing_addons != "None" else ""
|
143 |
if addons:
|
144 |
combined_addons = f"{combined_addons}; {addons}".strip("; ")
|
@@ -152,7 +145,6 @@ def add_suggestion_to_cart():
|
|
152 |
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
153 |
)
|
154 |
|
155 |
-
# Update the cart item
|
156 |
sf.Cart_Item__c.update(cart_item_id, {
|
157 |
"Quantity__c": existing_quantity + 1,
|
158 |
"Add_Ons__c": combined_addons,
|
@@ -161,10 +153,7 @@ def add_suggestion_to_cart():
|
|
161 |
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
162 |
})
|
163 |
else:
|
164 |
-
# If item doesn't exist in cart, create a new cart item
|
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,
|
@@ -182,6 +171,7 @@ def add_suggestion_to_cart():
|
|
182 |
except Exception as e:
|
183 |
print(f"Error adding item to cart: {str(e)}")
|
184 |
return jsonify({"success": False, "error": str(e)})
|
|
|
185 |
@cart_blueprint.route('/remove/<item_name>', methods=['POST'])
|
186 |
def remove_cart_item(item_name):
|
187 |
try:
|
@@ -198,7 +188,6 @@ def remove_cart_item(item_name):
|
|
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 +198,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,162 +219,156 @@ 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 |
user_id = session.get('user_name')
|
270 |
-
table_number = session.get('table_number')
|
271 |
|
272 |
-
print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}")
|
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 |
-
# Fetch the selected coupon (if any)
|
280 |
data = request.json
|
281 |
selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
|
282 |
-
|
283 |
-
print(f"Selected Coupon: {selected_coupon}") # Debugging selected coupon
|
284 |
|
285 |
-
# Fetch cart items for the current user
|
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 = '{email}'
|
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}")
|
295 |
|
296 |
if not cart_items:
|
297 |
print("Cart is empty")
|
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}")
|
302 |
|
303 |
discount = 0
|
304 |
|
305 |
-
# Fetch the user's existing coupons
|
306 |
coupon_query = sf.query(f"""
|
307 |
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
308 |
""")
|
309 |
-
print(f"Coupon Query Results: {coupon_query}")
|
310 |
|
311 |
has_coupons = bool(coupon_query["records"])
|
312 |
-
print(f"Has Coupons: {has_coupons}")
|
313 |
|
314 |
if selected_coupon:
|
315 |
-
|
316 |
-
|
317 |
-
print(f"Discount Applied: {discount}") # Debugging discount calculation
|
318 |
|
319 |
referral_coupon_id = coupon_query["records"][0]["Id"]
|
320 |
-
print(f"Referral Coupon ID: {referral_coupon_id}")
|
321 |
|
322 |
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
|
323 |
-
print(f"Existing Coupons Before Removal: {existing_coupons}")
|
324 |
|
325 |
-
# Remove the selected coupon from the list of existing coupons
|
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}")
|
330 |
|
331 |
-
# If no coupons remain, set the field to None (not empty string)
|
332 |
if not updated_coupons:
|
333 |
-
updated_coupons_str = None
|
334 |
-
print("No Coupons Remaining. Setting to None")
|
335 |
|
336 |
-
|
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 |
-
|
343 |
-
|
344 |
-
print(f"Reward Points to Add: {reward_points_to_add}") # Debugging reward points
|
345 |
|
346 |
-
# Fetch current reward points
|
347 |
customer_record = sf.query(f"""
|
348 |
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
349 |
WHERE Email__c = '{email}'
|
350 |
""")
|
351 |
-
print(f"Customer Reward Points Query: {customer_record}")
|
352 |
|
353 |
customer = customer_record.get("records", [])[0] if customer_record else None
|
354 |
if customer:
|
355 |
current_reward_points = customer.get("Reward_Points__c") or 0
|
356 |
-
print(f"Current Reward Points: {current_reward_points}")
|
357 |
new_reward_points = current_reward_points + reward_points_to_add
|
358 |
-
print(f"New Reward Points: {new_reward_points}")
|
359 |
|
360 |
-
# Update reward points
|
361 |
sf.Customer_Login__c.update(customer["Id"], {
|
362 |
"Reward_Points__c": new_reward_points
|
363 |
})
|
364 |
|
365 |
-
# Final total bill calculation
|
366 |
total_bill = total_price - discount
|
367 |
-
print(f"Total Bill After Discount: {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}")
|
377 |
|
378 |
-
# Fetch Customer ID from Customer_Login__c
|
379 |
customer_query = sf.query(f"""
|
380 |
SELECT Id FROM Customer_Login__c
|
381 |
WHERE Email__c = '{email}'
|
382 |
""")
|
383 |
|
384 |
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
385 |
-
print(f"Customer ID: {customer_id}")
|
386 |
|
387 |
if not customer_id:
|
388 |
print("Customer record not found")
|
389 |
return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
|
390 |
-
|
391 |
-
|
392 |
order_data = {
|
393 |
"Customer_Name__c": user_id,
|
394 |
"Customer_Email__c": email,
|
@@ -398,25 +378,20 @@ def checkout():
|
|
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}")
|
404 |
|
405 |
-
# Create the order in Salesforce
|
406 |
order_response = sf.Order__c.create(order_data)
|
407 |
-
print(f"Order Response: {order_response}")
|
408 |
|
409 |
-
# Ensure the order was created successfully before deleting cart items
|
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']}")
|
414 |
sf.Cart_Item__c.delete(item["Id"])
|
415 |
|
416 |
return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill})
|
417 |
|
418 |
except Exception as e:
|
419 |
-
print(f"Error during checkout: {str(e)}")
|
420 |
-
return jsonify({"success": False, "error": str(e)})
|
421 |
-
|
422 |
-
|
|
|
1 |
+
from flask import Blueprint, render_template, request, session, jsonify
|
2 |
from salesforce import get_salesforce_connection
|
|
|
3 |
|
4 |
+
sf = get_salesforce_connection()
|
5 |
cart_blueprint = Blueprint('cart', __name__)
|
6 |
+
|
7 |
@cart_blueprint.route("/cart", methods=["GET"])
|
8 |
def cart():
|
9 |
email = session.get('user_email')
|
|
|
44 |
|
45 |
# If there are items in the cart, fetch suggestions
|
46 |
if cart_items:
|
47 |
+
# Get the category and section of the first item in the cart
|
48 |
first_item = cart_items[0]
|
49 |
+
item_category = first_item.get('Category__c', 'All')
|
50 |
+
item_section = first_item.get('Section__c', 'Biryanis')
|
51 |
|
52 |
# Define section-to-complementary section mapping
|
53 |
complementary_sections = {
|
54 |
'Breads': ['Curries', 'Biryanis', 'Starters'],
|
55 |
+
'Biryanis': ['Curries', 'Starters', 'Dessetett
|
56 |
+
s'],
|
57 |
'Curries': ['Biryanis', 'Breads', 'Starters'],
|
58 |
'Starters': ['Biryanis', 'Curries', 'Desserts'],
|
59 |
'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'],
|
|
|
83 |
LIMIT 4
|
84 |
"""
|
85 |
suggestion_result = sf.query(query)
|
86 |
+
suggestions.extend(suggestion_result.get("records", []))
|
|
|
|
|
87 |
if len(suggestions) > 4:
|
88 |
suggestions = suggestions[:4]
|
|
|
89 |
except Exception as e:
|
90 |
print(f"Error fetching suggestions: {e}")
|
91 |
|
|
|
106 |
@cart_blueprint.route("/add_suggestion_to_cart", methods=["POST"])
|
107 |
def add_suggestion_to_cart():
|
108 |
try:
|
|
|
109 |
data = request.get_json()
|
110 |
item_name = data.get('item_name').strip()
|
111 |
item_price = data.get('item_price')
|
112 |
item_image = data.get('item_image')
|
|
|
113 |
customer_email = data.get('customer_email')
|
114 |
addons = data.get('addons', [])
|
115 |
instructions = data.get('instructions', "")
|
116 |
|
|
|
117 |
addons_price = 0
|
118 |
addons_string = "None"
|
119 |
|
|
|
120 |
query = f"""
|
121 |
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
122 |
FROM Cart_Item__c
|
|
|
125 |
result = sf.query(query)
|
126 |
cart_items = result.get("records", [])
|
127 |
|
|
|
128 |
if cart_items:
|
129 |
cart_item_id = cart_items[0]['Id']
|
130 |
existing_quantity = cart_items[0]['Quantity__c']
|
|
|
132 |
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
133 |
existing_instructions = cart_items[0].get('Instructions__c', "")
|
134 |
|
|
|
135 |
combined_addons = existing_addons if existing_addons != "None" else ""
|
136 |
if addons:
|
137 |
combined_addons = f"{combined_addons}; {addons}".strip("; ")
|
|
|
145 |
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
146 |
)
|
147 |
|
|
|
148 |
sf.Cart_Item__c.update(cart_item_id, {
|
149 |
"Quantity__c": existing_quantity + 1,
|
150 |
"Add_Ons__c": combined_addons,
|
|
|
153 |
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
154 |
})
|
155 |
else:
|
|
|
156 |
total_price = float(item_price) + addons_price
|
|
|
|
|
157 |
sf.Cart_Item__c.create({
|
158 |
"Name": item_name,
|
159 |
"Price__c": total_price,
|
|
|
171 |
except Exception as e:
|
172 |
print(f"Error adding item to cart: {str(e)}")
|
173 |
return jsonify({"success": False, "error": str(e)})
|
174 |
+
|
175 |
@cart_blueprint.route('/remove/<item_name>', methods=['POST'])
|
176 |
def remove_cart_item(item_name):
|
177 |
try:
|
|
|
188 |
if result['totalSize'] == 0:
|
189 |
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
190 |
|
|
|
191 |
cart_item_id = result['records'][0]['Id']
|
192 |
sf.Cart_Item__c.delete(cart_item_id)
|
193 |
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
|
|
198 |
@cart_blueprint.route("/update_quantity", methods=["POST"])
|
199 |
def update_quantity():
|
200 |
print("Handling update_quantity request...")
|
201 |
+
data = request.json
|
202 |
email = data.get('email')
|
203 |
item_name = data.get('item_name')
|
204 |
|
205 |
try:
|
|
|
206 |
quantity = int(data.get('quantity'))
|
207 |
except (ValueError, TypeError):
|
208 |
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
|
209 |
|
|
|
210 |
if not email or not item_name or quantity is None:
|
211 |
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
|
212 |
|
213 |
try:
|
|
|
214 |
cart_items = sf.query(
|
215 |
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
|
216 |
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
|
|
|
219 |
if not cart_items:
|
220 |
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
221 |
|
|
|
222 |
cart_item_id = cart_items[0]['Id']
|
223 |
base_price = cart_items[0]['Base_Price__c']
|
224 |
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
225 |
|
|
|
226 |
new_item_price = (base_price * quantity) + addons_price
|
227 |
|
|
|
228 |
sf.Cart_Item__c.update(cart_item_id, {
|
229 |
"Quantity__c": quantity,
|
230 |
+
"Price__c": new_item_price,
|
231 |
})
|
232 |
|
|
|
233 |
cart_items = sf.query(f"""
|
234 |
SELECT Price__c, Add_Ons_Price__c
|
235 |
FROM Cart_Item__c
|
236 |
WHERE Customer_Email__c = '{email}'
|
237 |
""")['records']
|
238 |
+
new_subtotal = sum(item['Price__c'] for item in cart_items)
|
239 |
|
|
|
240 |
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
241 |
|
242 |
except Exception as e:
|
243 |
print(f"Error updating quantity: {str(e)}")
|
244 |
return jsonify({"success": False, "error": str(e)}), 500
|
245 |
|
|
|
246 |
@cart_blueprint.route("/checkout", methods=["POST"])
|
247 |
def checkout():
|
248 |
email = session.get('user_email')
|
249 |
user_id = session.get('user_name')
|
250 |
+
table_number = session.get('table_number')
|
251 |
|
252 |
+
print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}")
|
253 |
|
254 |
if not email or not user_id:
|
255 |
print("User not logged in")
|
256 |
return jsonify({"success": False, "message": "User not logged in"})
|
257 |
|
258 |
try:
|
|
|
259 |
data = request.json
|
260 |
selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
|
261 |
+
print(f"Selected Coupon: {selected_coupon}")
|
|
|
262 |
|
|
|
263 |
result = sf.query(f"""
|
264 |
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
265 |
FROM Cart_Item__c
|
266 |
WHERE Customer_Email__c = '{email}'
|
267 |
""")
|
268 |
|
|
|
269 |
cart_items = result.get("records", [])
|
270 |
+
print(f"Cart Items Retrieved: {cart_items}")
|
271 |
|
272 |
if not cart_items:
|
273 |
print("Cart is empty")
|
274 |
return jsonify({"success": False, "message": "Cart is empty"})
|
275 |
|
276 |
+
# Update Total_Ordered__c in Custom_Dish__c for each custom dish in the cart
|
277 |
+
for item in cart_items:
|
278 |
+
item_name = item['Name']
|
279 |
+
quantity = item['Quantity__c']
|
280 |
+
custom_dish_query = f"SELECT Id, Total_Ordered__c FROM Custom_Dish__c WHERE Name = '{item_name}'"
|
281 |
+
custom_dish_result = sf.query(custom_dish_query)
|
282 |
+
|
283 |
+
if custom_dish_result['totalSize'] > 0:
|
284 |
+
custom_dish = custom_dish_result['records'][0]
|
285 |
+
dish_id = custom_dish['Id']
|
286 |
+
total_ordered = custom_dish.get('Total_Ordered__c', 0) or 0
|
287 |
+
sf.Custom_Dish__c.update(dish_id, {
|
288 |
+
'Total_Ordered__c': total_ordered + quantity
|
289 |
+
})
|
290 |
+
|
291 |
total_price = sum(item['Price__c'] for item in cart_items)
|
292 |
+
print(f"Total Price: {total_price}")
|
293 |
|
294 |
discount = 0
|
295 |
|
|
|
296 |
coupon_query = sf.query(f"""
|
297 |
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
298 |
""")
|
299 |
+
print(f"Coupon Query Results: {coupon_query}")
|
300 |
|
301 |
has_coupons = bool(coupon_query["records"])
|
302 |
+
print(f"Has Coupons: {has_coupons}")
|
303 |
|
304 |
if selected_coupon:
|
305 |
+
discount = total_price * 0.10
|
306 |
+
print(f"Discount Applied: {discount}")
|
|
|
307 |
|
308 |
referral_coupon_id = coupon_query["records"][0]["Id"]
|
309 |
+
print(f"Referral Coupon ID: {referral_coupon_id}")
|
310 |
|
311 |
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
|
312 |
+
print(f"Existing Coupons Before Removal: {existing_coupons}")
|
313 |
|
|
|
314 |
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
|
315 |
updated_coupons_str = "\n".join(updated_coupons).strip()
|
316 |
|
317 |
+
print(f"Updated Coupons After Removal: {updated_coupons}")
|
318 |
|
|
|
319 |
if not updated_coupons:
|
320 |
+
updated_coupons_str = None
|
321 |
+
print("No Coupons Remaining. Setting to None")
|
322 |
|
323 |
+
print(f"Updating Referral Coupon: {updated_coupons_str}")
|
|
|
324 |
sf.Referral_Coupon__c.update(referral_coupon_id, {
|
325 |
"Coupon_Code__c": updated_coupons_str
|
326 |
})
|
327 |
else:
|
328 |
+
reward_points_to_add = total_price * 0.10
|
329 |
+
print(f"Reward Points to Add: {reward_points_to_add}")
|
|
|
330 |
|
|
|
331 |
customer_record = sf.query(f"""
|
332 |
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
333 |
WHERE Email__c = '{email}'
|
334 |
""")
|
335 |
+
print(f"Customer Reward Points Query: {customer_record}")
|
336 |
|
337 |
customer = customer_record.get("records", [])[0] if customer_record else None
|
338 |
if customer:
|
339 |
current_reward_points = customer.get("Reward_Points__c") or 0
|
340 |
+
print(f"Current Reward Points: {current_reward_points}")
|
341 |
new_reward_points = current_reward_points + reward_points_to_add
|
342 |
+
print(f"New Reward Points: {new_reward_points}")
|
343 |
|
|
|
344 |
sf.Customer_Login__c.update(customer["Id"], {
|
345 |
"Reward_Points__c": new_reward_points
|
346 |
})
|
347 |
|
|
|
348 |
total_bill = total_price - discount
|
349 |
+
print(f"Total Bill After Discount: {total_bill}")
|
350 |
|
|
|
351 |
order_details = "\n".join(
|
352 |
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
|
353 |
f"Instructions: {item.get('Instructions__c', 'None')} | "
|
354 |
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
|
355 |
for item in cart_items
|
356 |
)
|
357 |
+
print(f"Order Details: {order_details}")
|
358 |
|
|
|
359 |
customer_query = sf.query(f"""
|
360 |
SELECT Id FROM Customer_Login__c
|
361 |
WHERE Email__c = '{email}'
|
362 |
""")
|
363 |
|
364 |
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
365 |
+
print(f"Customer ID: {customer_id}")
|
366 |
|
367 |
if not customer_id:
|
368 |
print("Customer record not found")
|
369 |
return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
|
370 |
+
|
371 |
+
table_number = table_number if table_number != 'null' else None
|
372 |
order_data = {
|
373 |
"Customer_Name__c": user_id,
|
374 |
"Customer_Email__c": email,
|
|
|
378 |
"Order_Status__c": "Pending",
|
379 |
"Customer2__c": customer_id,
|
380 |
"Order_Details__c": order_details,
|
381 |
+
"Table_Number__c": table_number
|
382 |
}
|
383 |
+
print(f"Order Data: {order_data}")
|
384 |
|
|
|
385 |
order_response = sf.Order__c.create(order_data)
|
386 |
+
print(f"Order Response: {order_response}")
|
387 |
|
|
|
388 |
if order_response:
|
|
|
389 |
for item in cart_items:
|
390 |
+
print(f"Deleting Cart Item: {item['Id']}")
|
391 |
sf.Cart_Item__c.delete(item["Id"])
|
392 |
|
393 |
return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill})
|
394 |
|
395 |
except Exception as e:
|
396 |
+
print(f"Error during checkout: {str(e)}")
|
397 |
+
return jsonify({"success": False, "error": str(e)})
|
|
|
|