nagasurendra commited on
Commit
19a5f27
·
verified ·
1 Parent(s): feb9c12

Update cart.py

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