nagasurendra commited on
Commit
53279a2
·
verified ·
1 Parent(s): 9a31124

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -708
app.py CHANGED
@@ -81,711 +81,3 @@ def dashboard():
81
  if __name__ == '__main__':
82
  app.run(debug=True)
83
 
84
- # Initialize Flask app and Salesforce connection
85
- print("Starting app...")
86
- app = Flask(__name__)
87
- CORS(app)
88
- print("Flask app initialized.")
89
-
90
- # Add debug logs in Salesforce connection setup
91
- sf = get_salesforce_connection()
92
- print("Salesforce connection established.")
93
-
94
- # Set the secret key to handle sessions securely
95
- app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q") # Replace with a secure key
96
-
97
- # Configure the session type
98
- app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
99
- #app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
100
- app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
101
- app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
102
-
103
- # Initialize the session
104
- Session(app) # Correctly initialize the Session object
105
- print("Session interface configured.")
106
-
107
- # Ensure secure session handling for environments like Hugging Face
108
- app.session_interface = SecureCookieSessionInterface()
109
- print("Session interface configured.")
110
- import random
111
- import string
112
-
113
- def generate_referral_code(length=8):
114
- # Generates a random referral code with uppercase, lowercase letters, and digits
115
- characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
116
- referral_code = ''.join(random.choice(characters) for _ in range(length))
117
- return referral_code
118
-
119
-
120
- @app.route('/')
121
- def home():
122
- # Get email and name from the URL query parameters
123
- email = request.args.get('email')
124
- name = request.args.get('name')
125
-
126
- # Use email and name as needed (e.g., display them in the page)
127
- return render_template('index.html', email=email, name=name)
128
-
129
- from datetime import datetime
130
-
131
- def generate_coupon_code(length=10):
132
- """Generates a random alphanumeric coupon code"""
133
- characters = string.ascii_uppercase + string.digits # A-Z, 0-9
134
- return ''.join(random.choice(characters) for _ in range(length))
135
-
136
-
137
- import re
138
-
139
- import re
140
-
141
- @app.route("/order-history", methods=["GET"])
142
- def order_history():
143
- email = session.get('user_email') # Get logged-in user's email
144
- if not email:
145
- return redirect(url_for("login"))
146
-
147
- try:
148
- # Fetch past orders for the user
149
- result = sf.query(f"""
150
- SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c,
151
- Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c, CreatedDate
152
- FROM Order__c
153
- WHERE Customer_Email__c = '{email}'
154
- ORDER BY CreatedDate DESC
155
- """)
156
-
157
- orders = result.get("records", []) # Fetch all orders
158
-
159
- # Strip image URLs from order details and split remaining data by new lines
160
- for order in orders:
161
- order_details = order.get("Order_Details__c", "")
162
- # Remove image URLs using regex
163
- cleaned_details = re.sub(r'http[s]?://\S+', '', order_details)
164
-
165
- # Now split the cleaned details by lines and join them with <br> to create line breaks
166
- cleaned_details = cleaned_details.replace("\n", "<br>")
167
-
168
- # Update the order details with the cleaned and formatted details
169
- order['Order_Details__c'] = cleaned_details
170
-
171
- return render_template("order_history.html", orders=orders)
172
-
173
- except Exception as e:
174
- print(f"Error fetching order history: {str(e)}")
175
- return render_template("order_history.html", orders=[], error=str(e))
176
- @app.route("/logout")
177
- def logout():
178
- session.clear() # Clear the session
179
- return redirect(url_for("login")) # Redirect to the login page
180
-
181
- @app.route("/signup", methods=["GET", "POST"])
182
- def signup():
183
- if request.method == "POST":
184
- name = request.form.get("name")
185
- phone = request.form.get("phone")
186
- email = request.form.get("email").strip() # Trim spaces
187
- password = request.form.get("password")
188
- referral_code = request.form.get("referral") # Fetch referral code from the form
189
- generated_referral_code = generate_referral_code()
190
-
191
- try:
192
- ref = 0 # Default reward points for new user
193
-
194
- # **Fix: Fetch all emails and compare in Python (Case-Insensitive)**
195
- email_query = "SELECT Id, Email__c FROM Customer_Login__c"
196
- email_result = sf.query(email_query)
197
-
198
- # Convert all stored emails to lowercase and compare with user input
199
- existing_emails = {record["Email__c"].lower() for record in email_result["records"]}
200
- if email.lower() in existing_emails:
201
- return render_template("signup.html", error="Email already in use! Please use a different email.")
202
-
203
- # Check if a referral code is entered
204
- if referral_code:
205
- referral_query = f"SELECT Id, Email__c, Name FROM Customer_Login__c WHERE Referral__c = '{referral_code}'"
206
- referral_result = sf.query(referral_query)
207
-
208
- if not referral_result['records']:
209
- return render_template("signup.html", error="Invalid referral code!")
210
-
211
- # Get referrer's details
212
- referrer = referral_result['records'][0]
213
- referrer_email = referrer.get('Email__c')
214
- referrer_name = referrer.get('Name')
215
-
216
- # Generate a new unique coupon code
217
- new_coupon_code = generate_coupon_code()
218
-
219
- # Check if referrer already has a record in Referral_Coupon__c
220
- existing_coupon_query = f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{referrer_email}'"
221
- existing_coupon_result = sf.query(existing_coupon_query)
222
-
223
- if existing_coupon_result['records']:
224
- referral_record = existing_coupon_result['records'][0]
225
- referral_id = referral_record['Id']
226
- existing_coupons = referral_record.get('Coupon_Code__c', '')
227
-
228
- updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()
229
-
230
- # Update the existing record with the new coupon
231
- sf.Referral_Coupon__c.update(referral_id, {
232
- "Coupon_Code__c": updated_coupons
233
- })
234
- else:
235
- # If no record exists, create a new one
236
- sf.Referral_Coupon__c.create({
237
- "Name": referrer_name,
238
- "Referral_Email__c": referrer_email,
239
- "Coupon_Code__c": new_coupon_code
240
- })
241
-
242
- # **Fix: Ensure Salesforce enforces unique email constraint**
243
- sf.Customer_Login__c.create({
244
- "Name": name,
245
- "Phone_Number__c": phone,
246
- "Email__c": email,
247
- "Password__c": password,
248
- "Reward_Points__c": ref, # No points added, only coupon is created
249
- "Referral__c": generated_referral_code
250
- })
251
-
252
- return redirect(url_for("login"))
253
-
254
- except Exception as e:
255
- return render_template("signup.html", error=f"Error: {str(e)}")
256
-
257
- return render_template("signup.html")
258
-
259
-
260
-
261
-
262
- @app.route("/login", methods=["GET", "POST"])
263
- def login():
264
- if request.method == "POST":
265
- email = request.form.get("email")
266
- password = request.form.get("password")
267
- print(f"Login attempt with email: {email}") # Debug log
268
-
269
- try:
270
- # Fetch user details, including Name and Reward_Points__c
271
- query = f"SELECT Id, Name, Email__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
272
- result = sf.query(query)
273
-
274
- if result["records"]:
275
- user = result["records"][0]
276
- session['user_id'] = user['Id']
277
- session['user_email'] = email
278
- print(f"Session variables set: user_id={session['user_id']}, user_email={session['user_email']}")
279
-
280
- user_name = user.get("Name", "") # Get the user's name
281
- reward_points = user.get("Reward_Points__c") or 0 # Ensures reward_points is always an integer
282
-
283
-
284
-
285
- if reward_points >= 500:
286
- print(f"User {email} has {reward_points} reward points. Generating coupon...")
287
-
288
- # Generate a new coupon code
289
- new_coupon_code = generate_coupon_code()
290
-
291
- # Check if user already has a record in Referral_Coupon__c
292
- coupon_query = sf.query(f"""
293
- SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
294
- """)
295
-
296
- if coupon_query["records"]:
297
- # If record exists, append the new coupon
298
- coupon_record = coupon_query["records"][0]
299
- referral_coupon_id = coupon_record["Id"]
300
- existing_coupons = coupon_record.get("Coupon_Code__c", "")
301
-
302
- # Append the new coupon on the next line
303
- updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()
304
-
305
- # Update the Referral_Coupon__c record
306
- sf.Referral_Coupon__c.update(referral_coupon_id, {
307
- "Coupon_Code__c": updated_coupons
308
- })
309
- print(f"Updated existing coupon record for {email}. New Coupon: {new_coupon_code}")
310
- else:
311
- # If no record exists, create a new one with Referral_Name__c
312
- sf.Referral_Coupon__c.create({
313
- "Referral_Email__c": email,
314
- "Name": user_name, # Store user's name in Referral_Coupon__c
315
- "Coupon_Code__c": new_coupon_code
316
- })
317
- print(f"Created new coupon record for {email} with name {user_name}. Coupon: {new_coupon_code}")
318
-
319
- # Subtract 500 reward points from user's account
320
- new_reward_points = reward_points - 500
321
- sf.Customer_Login__c.update(user['Id'], {
322
- "Reward_Points__c": new_reward_points
323
- })
324
- print(f"Coupon {new_coupon_code} generated and 500 points deducted. New balance: {new_reward_points}")
325
-
326
- return redirect(url_for("menu"))
327
-
328
- else:
329
- print("Invalid credentials!")
330
- return render_template("login.html", error="Invalid credentials!")
331
-
332
- except Exception as e:
333
- print(f"Error during login: {str(e)}")
334
- return render_template("login.html", error=f"Error: {str(e)}")
335
-
336
- return render_template("login.html")
337
- @app.route("/menu", methods=["GET", "POST"])
338
- def menu():
339
- selected_category = request.args.get("category", "All")
340
- user_email = request.args.get("email") # Fetch the user's email from URL parameter
341
- user_name = request.args.get("name") # Fetch the user's name from URL parameter
342
-
343
- if not user_email:
344
- print("Email missing, redirecting to login.")
345
- return redirect(url_for('login'))
346
-
347
- # Now, you can use user_email and user_name in your queries and logic
348
- try:
349
- # Fetch the user's Referral__c and Reward_Points__c from Salesforce using the email
350
- user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
351
- user_result = sf.query(user_query)
352
-
353
- if not user_result['records']:
354
- print("User not found!")
355
- return redirect(url_for('login'))
356
-
357
- referral_code = user_result['records'][0].get('Referral__c', 'N/A') # Default to 'N/A' if empty
358
- reward_points = user_result['records'][0].get('Reward_Points__c', 0) # Default to 0 if empty
359
-
360
- # Query to fetch menu items
361
- menu_query = """
362
- SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c
363
- FROM Menu_Item__c
364
- """
365
- result = sf.query(menu_query)
366
- food_items = result['records'] if 'records' in result else []
367
-
368
- # Filter categories dynamically
369
- categories = {item.get("Veg_NonVeg__c").capitalize() for item in food_items if item.get("Veg_NonVeg__c")}
370
- categories = {"Veg", "Non-Veg"} # Ensure valid categories only
371
-
372
- # Filter food items based on the selected category
373
- if selected_category == "Veg":
374
- food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
375
- elif selected_category == "Non-Veg":
376
- food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
377
-
378
- except Exception as e:
379
- print(f"Error fetching menu data: {str(e)}")
380
- food_items = []
381
- categories = {"All", "Veg", "Non-Veg"} # Default categories on error
382
- referral_code = 'N/A'
383
- reward_points = 0
384
-
385
- # Render the menu page with the fetched data and user details
386
- return render_template(
387
- "menu.html",
388
- food_items=food_items,
389
- categories=sorted(categories), # Sort categories alphabetically if needed
390
- selected_category=selected_category,
391
- referral_code=referral_code,
392
- reward_points=reward_points,
393
- user_name=user_name, # Pass user name to the template
394
- user_email=user_email # Pass user email to the template
395
- )
396
-
397
-
398
-
399
-
400
- @app.route("/cart", methods=["GET"])
401
- def cart():
402
- email = session.get('user_email') # Get logged-in user's email
403
- if not email:
404
- return redirect(url_for("login"))
405
-
406
- try:
407
- # Query cart items
408
- result = sf.query(f"""
409
- SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c
410
- FROM Cart_Item__c
411
- WHERE Customer_Email__c = '{email}'
412
- """)
413
- cart_items = result.get("records", [])
414
-
415
- # Subtotal should be the sum of all item prices in the cart
416
- subtotal = sum(item['Price__c'] for item in cart_items)
417
-
418
- # Fetch reward points
419
- customer_result = sf.query(f"""
420
- SELECT Reward_Points__c
421
- FROM Customer_Login__c
422
- WHERE Email__c = '{email}'
423
- """)
424
- reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
425
-
426
- # Fetch coupons for the user
427
- coupon_result = sf.query(f"""
428
- SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
429
- """)
430
-
431
- # Extract and split coupons into a list
432
- if coupon_result["records"]:
433
- raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
434
- coupons = raw_coupons.split("\n") if raw_coupons else []
435
- else:
436
- coupons = []
437
-
438
- return render_template(
439
- "cart.html",
440
- cart_items=cart_items,
441
- subtotal=subtotal,
442
- reward_points=reward_points,
443
- customer_email=email,
444
- coupons=coupons # Send coupons to template
445
- )
446
-
447
- except Exception as e:
448
- print(f"Error fetching cart items: {e}")
449
- return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[])
450
-
451
-
452
-
453
- @app.route('/cart/add', methods=['POST'])
454
- def add_to_cart():
455
- data = request.json # Extract JSON payload from frontend
456
- item_name = data.get('itemName').strip() # Item name
457
- item_price = data.get('itemPrice') # Base price of the item
458
- item_image = data.get('itemImage') # Item image
459
- addons = data.get('addons', []) # Add-ons array
460
- instructions = data.get('instructions', '') # Special instructions
461
- customer_email = session.get('user_email') # Get logged-in user's email
462
-
463
- if not item_name or not item_price:
464
- return jsonify({"success": False, "error": "Item name and price are required."})
465
-
466
- try:
467
- # Query the cart to check if the item already exists
468
- query = f"""
469
- SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c FROM Cart_Item__c
470
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
471
- """
472
- result = sf.query(query)
473
- cart_items = result.get("records", [])
474
-
475
- # Calculate the price of the new add-ons
476
- addons_price = sum(addon['price'] for addon in addons) # New add-ons price
477
- new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) # Format new add-ons
478
-
479
- if cart_items:
480
- # If the item already exists in the cart, update it
481
- cart_item_id = cart_items[0]['Id']
482
- existing_quantity = cart_items[0]['Quantity__c']
483
- existing_addons = cart_items[0].get('Add_Ons__c', "None") # Previous add-ons
484
- existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0) # Previous add-ons price
485
- existing_instructions = cart_items[0].get('Instructions__c', "") # Previous instructions
486
-
487
- # Combine the existing and new add-ons
488
- combined_addons = existing_addons if existing_addons != "None" else ""
489
- if new_addons:
490
- combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
491
-
492
- # Combine the existing and new instructions
493
- combined_instructions = existing_instructions
494
- if instructions:
495
- combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
496
-
497
- # Recalculate the total add-ons price
498
- combined_addons_list = combined_addons.split("; ")
499
- combined_addons_price = sum(
500
- float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
501
- )
502
-
503
- # Update the item in the cart
504
- sf.Cart_Item__c.update(cart_item_id, {
505
- "Quantity__c": existing_quantity + 1, # Increase quantity by 1
506
- "Add_Ons__c": combined_addons, # Update add-ons list
507
- "Add_Ons_Price__c": combined_addons_price, # Update add-ons price
508
- "Instructions__c": combined_instructions, # Update instructions
509
- "Price__c": (existing_quantity + 1) * item_price + combined_addons_price, # Update total price
510
- })
511
- else:
512
- # If the item does not exist in the cart, create a new one
513
- addons_string = "None"
514
- if addons:
515
- addons_string = new_addons # Use the formatted add-ons string
516
-
517
- total_price = item_price + addons_price # Base price + add-ons price
518
-
519
- # Create a new cart item
520
- sf.Cart_Item__c.create({
521
- "Name": item_name, # Item name
522
- "Price__c": total_price, # Total price (item + add-ons)
523
- "Base_Price__c": item_price, # Base price without add-ons
524
- "Quantity__c": 1, # Default quantity is 1
525
- "Add_Ons_Price__c": addons_price, # Total add-ons price
526
- "Add_Ons__c": addons_string, # Add-ons with names and prices
527
- "Image1__c": item_image, # Item image URL
528
- "Customer_Email__c": customer_email, # Associated customer's email
529
- "Instructions__c": instructions # Save instructions
530
- })
531
-
532
- return jsonify({"success": True, "message": "Item added to cart successfully."})
533
- except Exception as e:
534
- print(f"Error adding item to cart: {str(e)}")
535
- return jsonify({"success": False, "error": str(e)})
536
-
537
-
538
-
539
- @app.route("/cart/add_item", methods=["POST"])
540
- def add_item_to_cart():
541
- data = request.json # Extract JSON data from the request
542
- email = data.get('email') # Customer email
543
- item_name = data.get('item_name') # Item name
544
- quantity = data.get('quantity', 1) # Quantity to add (default is 1)
545
- addons = data.get('addons', []) # Add-ons for the item (optional)
546
-
547
- # Validate inputs
548
- if not email or not item_name:
549
- return jsonify({"success": False, "error": "Email and item name are required."}), 400
550
-
551
- try:
552
- # Add a new item to the cart with the provided details
553
- sf.Cart_Item__c.create({
554
- "Customer_Email__c": email, # Associate the cart item with the customer's email
555
- "Item_Name__c": item_name, # Item name
556
- "Quantity__c": quantity, # Quantity to add
557
- "Add_Ons__c": addons_string
558
- })
559
-
560
- return jsonify({"success": True, "message": "Item added to cart successfully."})
561
- except Exception as e:
562
- print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
563
- return jsonify({"success": False, "error": str(e)}), 500
564
-
565
-
566
-
567
- @app.route('/cart/remove/<item_name>', methods=['POST'])
568
- def remove_cart_item(item_name):
569
- try:
570
- customer_email = session.get('user_email')
571
- if not customer_email:
572
- return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
573
- query = f"""
574
- SELECT Id FROM Cart_Item__c
575
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
576
- """
577
- result = sf.query(query)
578
- if result['totalSize'] == 0:
579
- return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
580
- cart_item_id = result['records'][0]['Id']
581
- sf.Cart_Item__c.delete(cart_item_id)
582
- return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
583
- except Exception as e:
584
- print(f"Error: {str(e)}")
585
- return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
586
-
587
- @app.route('/api/addons', methods=['GET'])
588
- def get_addons():
589
- item_name = request.args.get('item_name') # Fetch the requested item name
590
- if not item_name:
591
- return jsonify({"success": False, "error": "Item name is required."})
592
-
593
- try:
594
- # Fetch add-ons related to the item (update query as needed)
595
- query = f"""
596
- SELECT Name, Price__c
597
- FROM Add_Ons__c
598
- """
599
- addons = sf.query(query)['records']
600
- return jsonify({"success": True, "addons": addons})
601
- except Exception as e:
602
- print(f"Error fetching add-ons: {e}")
603
- return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
604
- @app.route("/cart/update_quantity", methods=["POST"])
605
- def update_quantity():
606
- data = request.json # Extract JSON data from the request
607
- email = data.get('email')
608
- item_name = data.get('item_name')
609
- try:
610
- # Convert quantity to an integer
611
- quantity = int(data.get('quantity'))
612
- except (ValueError, TypeError):
613
- return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
614
-
615
- # Validate inputs
616
- if not email or not item_name or quantity is None:
617
- return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
618
-
619
- try:
620
- # Query the cart item in Salesforce
621
- cart_items = sf.query(
622
- f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
623
- f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
624
- )['records']
625
-
626
- if not cart_items:
627
- return jsonify({"success": False, "error": "Cart item not found."}), 404
628
-
629
- # Retrieve the first matching record
630
- cart_item_id = cart_items[0]['Id']
631
- base_price = cart_items[0]['Base_Price__c']
632
- addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
633
-
634
- # Calculate the new item price
635
- new_item_price = (base_price * quantity) + addons_price
636
-
637
- # Update the record in Salesforce
638
- sf.Cart_Item__c.update(cart_item_id, {
639
- "Quantity__c": quantity,
640
- "Price__c": new_item_price, # Update base price
641
- })
642
-
643
- # Recalculate the subtotal for all items in the cart
644
- cart_items = sf.query(f"""
645
- SELECT Price__c, Add_Ons_Price__c
646
- FROM Cart_Item__c
647
- WHERE Customer_Email__c = '{email}'
648
- """)['records']
649
- new_subtotal = sum(item['Price__c'] for item in cart_items)
650
-
651
- # Return updated item price and subtotal
652
- return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
653
- print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
654
- return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
655
-
656
- except Exception as e:
657
- print(f"Error updating quantity: {str(e)}")
658
- return jsonify({"success": False, "error": str(e)}), 500
659
- @app.route("/checkout", methods=["POST"])
660
- def checkout():
661
- email = session.get('user_email')
662
- user_id = session.get('user_id')
663
-
664
- if not email or not user_id:
665
- return jsonify({"success": False, "message": "User not logged in"})
666
-
667
- try:
668
- data = request.json
669
- selected_coupon = data.get("selectedCoupon", "").strip()
670
-
671
- # Fetch cart items
672
- result = sf.query(f"""
673
- SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
674
- FROM Cart_Item__c
675
- WHERE Customer_Email__c = '{email}'
676
- """)
677
- cart_items = result.get("records", [])
678
-
679
- if not cart_items:
680
- return jsonify({"success": False, "message": "Cart is empty"})
681
-
682
- total_price = sum(item['Price__c'] for item in cart_items)
683
- discount = 0
684
- # Fetch the user's existing coupons
685
- coupon_query = sf.query(f"""
686
- SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
687
- """)
688
-
689
- has_coupons = bool(coupon_query["records"]) # Check if user has any coupons
690
-
691
- if selected_coupon:
692
- # Case 3: User selected a valid coupon → Apply discount & remove coupon
693
- discount = total_price * 0.10 # 10% discount
694
- referral_coupon_id = coupon_query["records"][0]["Id"]
695
- existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
696
-
697
- # Remove only the selected coupon
698
- updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
699
-
700
- # Convert list back to a string with newlines
701
- updated_coupons_str = "\n".join(updated_coupons).strip()
702
-
703
- # Update the Referral_Coupon__c record with the remaining coupons
704
- sf.Referral_Coupon__c.update(referral_coupon_id, {
705
- "Coupon_Code__c": updated_coupons_str
706
- })
707
- else:
708
- # Case 1 & Case 2: User has no coupons or has coupons but didn’t select one → Add 10% to reward points
709
- reward_points_to_add = total_price * 0.10
710
-
711
- # Fetch current reward points
712
- customer_record = sf.query(f"""
713
- SELECT Id, Reward_Points__c FROM Customer_Login__c
714
- WHERE Email__c = '{email}'
715
- """)
716
- customer = customer_record.get("records", [])[0] if customer_record else None
717
-
718
- if customer:
719
- current_reward_points = customer.get("Reward_Points__c") or 0
720
- new_reward_points = current_reward_points + reward_points_to_add
721
-
722
- print(f"Updating reward points: Current = {current_reward_points}, Adding = {reward_points_to_add}, New = {new_reward_points}")
723
-
724
- # Update reward points in Salesforce
725
- sf.Customer_Login__c.update(customer["Id"], {
726
- "Reward_Points__c": new_reward_points
727
- })
728
- print(f"Successfully updated reward points for {email}")
729
-
730
-
731
-
732
- total_bill = total_price - discount
733
-
734
- # ✅ Store **all details** including Add-Ons, Instructions, Price, and Image
735
- order_details = "\n".join(
736
- f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
737
- f"Instructions: {item.get('Instructions__c', 'None')} | "
738
- f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
739
- for item in cart_items
740
- )
741
-
742
- # Store the order details in Order__c
743
- order_data = {
744
- "Customer_Name__c": user_id,
745
- "Customer_Email__c": email,
746
- "Total_Amount__c": total_price,
747
- "Discount__c": discount,
748
- "Total_Bill__c": total_bill,
749
- "Order_Status__c": "Pending",
750
- "Order_Details__c": order_details # ✅ Now includes **all details**
751
- }
752
-
753
- sf.Order__c.create(order_data)
754
-
755
- # ✅ Delete cart items after order is placed
756
- for item in cart_items:
757
- sf.Cart_Item__c.delete(item["Id"])
758
-
759
- return jsonify({"success": True, "message": "Order placed successfully!"})
760
-
761
- except Exception as e:
762
- print(f"Error during checkout: {str(e)}")
763
- return jsonify({"success": False, "error": str(e)})
764
-
765
- @app.route("/order", methods=["GET"])
766
- def order_summary():
767
- email = session.get('user_email') # Fetch logged-in user's email
768
- if not email:
769
- return redirect(url_for("login"))
770
-
771
- try:
772
- # Fetch the most recent order for the user
773
- result = sf.query(f"""
774
- SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
775
- FROM Order__c
776
- WHERE Customer_Email__c = '{email}'
777
- ORDER BY CreatedDate DESC
778
- LIMIT 1
779
- """)
780
- order = result.get("records", [])[0] if result.get("records") else None
781
-
782
- if not order:
783
- return render_template("order.html", order=None)
784
-
785
- return render_template("order.html", order=order)
786
- except Exception as e:
787
- print(f"Error fetching order details: {str(e)}")
788
- return render_template("order.html", order=None, error=str(e))
789
-
790
- if __name__ == "__main__":
791
- app.run(debug=False, host="0.0.0.0", port=7860)
 
81
  if __name__ == '__main__':
82
  app.run(debug=True)
83