Spaces:
Sleeping
Sleeping
File size: 24,897 Bytes
a7abf85 d3245ed 36d2eb6 b12f5e4 bc5ffb6 d06632b 5b82b78 bc5ffb6 ea32532 444fe60 a7abf85 01b8424 a7abf85 01b8424 a7abf85 01b8424 a7abf85 098997e d3245ed 3dc3601 8697d42 d3245ed a69087c d3245ed 8dec0d6 13d210d 3ad292c a7abf85 b9ae446 444fe60 7dfdd45 7169f69 2a3e9ab f135c76 755be33 f633995 f135c76 d0a197b f135c76 7169f69 7dfdd45 a7abf85 2a3e9ab a7abf85 50a98c7 a469f92 8c30948 a7abf85 0bb04b6 7b4bb2e 80598cc a7abf85 7169f69 f135c76 4437c76 ea32532 f135c76 a7abf85 5b82b78 ea32532 5b82b78 444fe60 a7abf85 96ffdf1 098997e a7abf85 098997e a7abf85 a3ace3a 3dc3601 a7abf85 96ffdf1 a7abf85 96ffdf1 a7abf85 098997e a7abf85 dab4dc4 a7abf85 dab4dc4 a7abf85 af1892f c053032 42a3b7a af1892f a7abf85 af1892f a7abf85 b69e71d a7abf85 6867b80 a5663b6 42a3b7a a7abf85 42a3b7a a7abf85 b69e71d a7abf85 a06e7a7 76eace7 a06e7a7 98110bb a06e7a7 a7abf85 33cad0b 5c3fd6b 33cad0b 5c3fd6b 33cad0b 76eace7 a06e7a7 5c3fd6b 33cad0b 5c3fd6b 33cad0b 5c3fd6b 33cad0b 5c3fd6b 33cad0b af1892f 61b8aca 444fe60 af1892f a7abf85 61b8aca 98110bb a7abf85 61b8aca a7abf85 61b8aca a7abf85 61b8aca 8f12848 61b8aca a7abf85 61b8aca a7abf85 61b8aca a7abf85 0767ada a7abf85 0767ada a7abf85 fe30914 c3f3bfe 4340133 c3f3bfe 52bd2a7 4340133 c3f3bfe 4340133 a7abf85 c3f3bfe a7abf85 c3f3bfe f85d242 4340133 f85d242 c3f3bfe 257a2f9 4340133 c3f3bfe f85d242 4340133 c3f3bfe f85d242 a7abf85 c3f3bfe 4340133 9c827f0 a7abf85 4340133 fe30914 e35b13d 98110bb e35b13d 98110bb e35b13d 98110bb 11514ee e35b13d 98110bb e35b13d 98110bb e35b13d 98110bb daa1840 47fb249 0636fdf 47fb249 9c71f47 47fb249 9c71f47 47fb249 9c71f47 47fb249 9c71f47 47fb249 9c71f47 61c3999 b12635f 61c3999 545ecbf 61c3999 545ecbf b12635f c5d3c60 b12635f ed4816c b6e4c17 b12635f b6e4c17 b12635f 545ecbf 61c3999 c55dcd2 9d3e1c8 a350be0 9d3e1c8 76eace7 a7abf85 a350be0 a7abf85 11514ee 9d3e1c8 a7abf85 9d3e1c8 a7abf85 9d3e1c8 8e33160 9d3e1c8 a350be0 9d3e1c8 7af850f afa308c 7af850f a36dc77 7af850f d8d6d04 7af850f d8d6d04 4b5387c 9d6d30e 0c50a71 9d6d30e 51026ee 9d6d30e d2cbfea 7af850f a7abf85 9d3e1c8 a350be0 5fba391 a7abf85 7af850f a7abf85 01b8424 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_session import Session # Import the Session class
from flask.sessions import SecureCookieSessionInterface # Import the class
from salesforce import get_salesforce_connection
import os
import random
import string
import logging
# Set up logging configuration
logging.basicConfig(level=logging.DEBUG)
# Initialize Flask app and Salesforce connection
print("Starting app...")
app = Flask(__name__)
print("Flask app initialized.")
# Add debug logs in Salesforce connection setup
sf = get_salesforce_connection()
print("Salesforce connection established.")
# Set the secret key to handle sessions securely
app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q") # Replace with a secure key
# Configure the session type
app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
#app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
# Initialize the session
Session(app) # Correctly initialize the Session object
print("Session interface configured.")
# Ensure secure session handling for environments like Hugging Face
app.session_interface = SecureCookieSessionInterface()
print("Session interface configured.")
@app.route("/")
def home():
return render_template("index.html")
def generate_referral_code(length=8):
"""Generate a random alphanumeric referral code."""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
def generate_coupon_code(length=10):
"""Generate a unique alphanumeric coupon code."""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
def process_referral_code(referral_code):
"""
Process the referral code by creating a referral coupon if the referrer is found.
Args:
referral_code (str): The referral code provided by the user.
Returns:
str: A message indicating the result of the referral code processing.
"""
try:
# Query for the referrer using the referral code
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Customer_Referral_Code__c = '{referral_code}'"
referral_result = sf.query(query)
print(referral_result)
if len(referral_result['records']) == 0:
return "Referral not found. No coupon generated."
else:
# Fetch the referrer's details
referrer = referral_result["records"][0]
# Generate a unique coupon code
coupon_code = generate_coupon_code()
# Create a referral coupon in Salesforce
sf.Referral_Coupon__c.create({
"Name": referrer["Name"],
"Referral_Email__c": referrer["Email__c"],
"Coupon_Code__c": coupon_code,
"Coupon_Status__c": "Active"
})
return f"Coupon code '{coupon_code}' generated for referrer '{referrer['Name']}' ({referrer['Email__c']})."
except Exception as e:
return f"Error processing referral code: {str(e)}"
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
name = request.form.get("name")
phone = request.form.get("phone")
email = request.form.get("email")
password = request.form.get("password")
referral_code = request.form.get("referral")
try:
# Step 1: Generate a unique referral code for the new user
while True:
customer_referral_code = generate_referral_code()
query = f"SELECT Id FROM Customer_Login__c WHERE Customer_Referral_Code__c = '{customer_referral_code}'"
result = sf.query(query)
if not result["records"]:
break
sf.Customer_Login__c.create({
"Name": name,
"Phone_Number__c": phone,
"Email__c": email,
"Password__c": password,
"Referral__c": referral_code,
"Customer_Referral_Code__c": customer_referral_code
})
# Step 3: Check if a referral code was provided
if referral_code:
referral_message = process_referral_code(referral_code)
print(referral_message)
# Log different levels of messages
logging.debug("This is a debug message.")
logging.info("Referral Code received: %s", referral_code)
logging.warning("This is a warning.")
logging.error("This is an error.")
return redirect(url_for("login"))
except Exception as e:
return render_template("signup.html", error=f"Error: {str(e)}")
return render_template("signup.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
print(f"Login attempt with email: {email}") # Debug log
try:
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
result = sf.query(query)
if result["records"]:
session['user_id'] = result["records"][0]['Id']
session['user_email'] = email
print(f"Session variables set: user_id={session['user_id']}, user_email={session['user_email']}")
#print(f"Session cookie: {request.cookies.get(app.session_cookie_name)}") # Check session cookie
return redirect(url_for("menu"))
else:
print("Invalid credentials!")
return render_template("login.html", error="Invalid credentials!")
except Exception as e:
print(f"Error during login: {str(e)}")
return render_template("login.html", error=f"Error: {str(e)}")
return render_template("login.html")
@app.route("/menu", methods=["GET", "POST"])
def menu():
selected_category = request.args.get("category", "All")
user_id = session.get('user_id')
print(f"Cookies on /menu: {request.cookies}")
print(f"Session check in /menu: user_id={user_id}")
# Get the selected category from the query parameter, default is "All"
selected_category = request.args.get("category", "All")
print(f"Selected category: {selected_category}")
if not user_id:
print("Session missing, redirecting to login.")
return redirect(url_for('login'))
try:
query = """
SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c
FROM Menu_Item__c
"""
# Query to fetch menu items
result = sf.query(query)
# Fetch all food items from the query result
food_items = result['records'] if 'records' in result else []
# Dynamically determine categories based on the fetched data
categories = {item.get("Veg_NonVeg__c").capitalize() for item in food_items if item.get("Veg_NonVeg__c")}
categories = {"Veg", "Non-Veg"} # Explicitly overwrite to ensure valid categories only
# Filter food items based on the selected category
if selected_category == "Veg":
food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
elif selected_category == "Non-Veg":
food_items = [item for item in food_items if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
except Exception as e:
print(f"Error fetching menu data: {str(e)}")
food_items = []
categories = {"All", "Veg", "Non-Veg"} # Default categories on error
# Render the menu page with the filtered data
return render_template(
"menu.html",
food_items=food_items,
categories=sorted(categories), # Sort categories alphabetically if needed
selected_category=selected_category,
)
@app.route("/cart", methods=["GET"])
def cart():
email = session.get('user_email') # Get logged-in user's email
if not email:
return redirect(url_for("login"))
try:
# Query cart items
result = sf.query(f"""
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c
FROM Cart_Item__c
WHERE Customer_Email__c = '{email}'
""")
cart_items = result.get("records", [])
# Subtotal should be the sum of all item prices in the cart
subtotal = sum(item['Price__c'] for item in cart_items)
return render_template("cart.html", cart_items=cart_items, subtotal=subtotal, customer_email=email)
except Exception as e:
print(f"Error fetching cart items: {e}")
return render_template("cart.html", cart_items=[], subtotal=0)
@app.route('/cart/add', methods=['POST'])
def add_to_cart():
data = request.json # Extract JSON payload from frontend
item_name = data.get('itemName').strip() # Item name
item_price = data.get('itemPrice') # Base price of the item
item_image = data.get('itemImage') # Item image
addons = data.get('addons', []) # Add-ons array
instructions = data.get('instructions', '') # Special instructions
customer_email = session.get('user_email') # Get logged-in user's email
if not item_name or not item_price:
return jsonify({"success": False, "error": "Item name and price are required."})
try:
# Query the cart to check if the item already exists
query = f"""
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c FROM Cart_Item__c
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
"""
result = sf.query(query)
cart_items = result.get("records", [])
# Calculate the price of the new add-ons
addons_price = sum(addon['price'] for addon in addons) # New add-ons price
new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons]) # Format new add-ons
if cart_items:
# If the item already exists in the cart, update it
cart_item_id = cart_items[0]['Id']
existing_quantity = cart_items[0]['Quantity__c']
existing_addons = cart_items[0].get('Add_Ons__c', "None") # Previous add-ons
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0) # Previous add-ons price
existing_instructions = cart_items[0].get('Instructions__c', "") # Previous instructions
# Combine the existing and new add-ons
combined_addons = existing_addons if existing_addons != "None" else ""
if new_addons:
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
# Combine the existing and new instructions
combined_instructions = existing_instructions
if instructions:
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
# Recalculate the total add-ons price
combined_addons_list = combined_addons.split("; ")
combined_addons_price = sum(
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
)
# Update the item in the cart
sf.Cart_Item__c.update(cart_item_id, {
"Quantity__c": existing_quantity + 1, # Increase quantity by 1
"Add_Ons__c": combined_addons, # Update add-ons list
"Add_Ons_Price__c": combined_addons_price, # Update add-ons price
"Instructions__c": combined_instructions, # Update instructions
"Price__c": (existing_quantity + 1) * item_price + combined_addons_price, # Update total price
})
else:
# If the item does not exist in the cart, create a new one
addons_string = "None"
if addons:
addons_string = new_addons # Use the formatted add-ons string
total_price = item_price + addons_price # Base price + add-ons price
# Create a new cart item
sf.Cart_Item__c.create({
"Name": item_name, # Item name
"Price__c": total_price, # Total price (item + add-ons)
"Base_Price__c": item_price, # Base price without add-ons
"Quantity__c": 1, # Default quantity is 1
"Add_Ons_Price__c": addons_price, # Total add-ons price
"Add_Ons__c": addons_string, # Add-ons with names and prices
"Image1__c": item_image, # Item image URL
"Customer_Email__c": customer_email, # Associated customer's email
"Instructions__c": instructions # Save instructions
})
return jsonify({"success": True, "message": "Item added to cart successfully."})
except Exception as e:
print(f"Error adding item to cart: {str(e)}")
return jsonify({"success": False, "error": str(e)})
@app.route("/cart/add_item", methods=["POST"])
def add_item_to_cart():
data = request.json # Extract JSON data from the request
email = data.get('email') # Customer email
item_name = data.get('item_name') # Item name
quantity = data.get('quantity', 1) # Quantity to add (default is 1)
addons = data.get('addons', []) # Add-ons for the item (optional)
# Validate inputs
if not email or not item_name:
return jsonify({"success": False, "error": "Email and item name are required."}), 400
try:
# Add a new item to the cart with the provided details
sf.Cart_Item__c.create({
"Customer_Email__c": email, # Associate the cart item with the customer's email
"Item_Name__c": item_name, # Item name
"Quantity__c": quantity, # Quantity to add
"Add_Ons__c": addons_string
})
return jsonify({"success": True, "message": "Item added to cart successfully."})
except Exception as e:
print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
return jsonify({"success": False, "error": str(e)}), 500
@app.route('/cart/remove/<item_name>', methods=['POST'])
def remove_cart_item(item_name):
try:
customer_email = session.get('user_email')
if not customer_email:
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
query = f"""
SELECT Id FROM Cart_Item__c
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
"""
result = sf.query(query)
if result['totalSize'] == 0:
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
cart_item_id = result['records'][0]['Id']
sf.Cart_Item__c.delete(cart_item_id)
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
except Exception as e:
print(f"Error: {str(e)}")
return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
@app.route('/api/addons', methods=['GET'])
def get_addons():
item_name = request.args.get('item_name') # Fetch the requested item name
if not item_name:
return jsonify({"success": False, "error": "Item name is required."})
try:
# Fetch add-ons related to the item (update query as needed)
query = f"""
SELECT Name, Price__c
FROM Add_Ons__c
"""
addons = sf.query(query)['records']
return jsonify({"success": True, "addons": addons})
except Exception as e:
print(f"Error fetching add-ons: {e}")
return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
@app.route("/cart/update_quantity", methods=["POST"])
def update_quantity():
data = request.json
item_name = data.get("item_name")
email = data.get("email")
try:
quantity = int(data.get("quantity"))
except (ValueError, TypeError):
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
if not item_name or not email:
return jsonify({"success": False, "error": "Email and item name are required."}), 400
try:
# Fetch the cart item from Salesforce
cart_items = sf.query(f"SELECT Id, Base_Price__c FROM Cart_Item__c WHERE Name = '{item_name}'")["records"]
if not cart_items:
return jsonify({"success": False, "error": "Cart item not found."}), 404
cart_item_id = cart_items[0]["Id"]
base_price = cart_items[0].get("Base_Price__c", 0) # Default to 0 if None
if base_price is None:
base_price = 0
new_item_price = base_price * quantity
# Update Cart Item in Salesforce
sf.Cart_Item__c.update(cart_item_id, {
"Quantity__c": quantity,
"Price__c": new_item_price,
})
# Fetch all cart items for this user to calculate the new subtotal
cart_items = sf.query(f"SELECT Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}'")["records"]
new_subtotal = sum(item["Price__c"] for item in cart_items)
# Fetch the latest Order for the user
order_result = sf.query(f"""
SELECT Id FROM Order__c
WHERE Customer_Email__c = '{email}'
ORDER BY CreatedDate DESC
LIMIT 1
""")
if order_result.get("records"):
order_id = order_result["records"][0]["Id"]
sf.Order__c.update(order_id, {"Total_Amount__c": new_subtotal})
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
except Exception as e:
print(f"Error updating quantity: {str(e)}")
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/checkout", methods=["POST"])
def checkout():
email = session.get('user_email')
user_id = session.get('user_id')
if not email or not user_id:
return jsonify({"success": False, "message": "User not logged in"})
try:
# Fetch cart items for the user
result = sf.query(f"""
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c
FROM Cart_Item__c
WHERE Customer_Email__c = '{email}'
""")
cart_items = result.get("records", [])
if not cart_items:
return jsonify({"success": False, "message": "Cart is empty"})
# Calculate the total price of the order
total_price = sum(item['Price__c'] for item in cart_items)
# Format order details including instructions
order_details = []
for item in cart_items:
details = f"{item['Name']} (Qty: {item['Quantity__c']}, Add-Ons: {item['Add_Ons__c'] or 'None'}, Price: ${item['Price__c']})"
if item.get('Instructions__c'): # Include instructions if available
details += f", Instructions: {item['Instructions__c']}"
order_details.append(details)
# Create the order in Salesforce
order_data = {
"Customer_Name__c": user_id,
"Customer_Email__c": email,
"Total_Amount__c": total_price,
"Order_Status__c": "Pending",
"Order_Details__c": "\n".join(order_details) # Store all item details
}
sf.Order__c.create(order_data)
# Clear the cart after placing the order
for item in cart_items:
sf.Cart_Item__c.delete(item["Id"])
return jsonify({"success": True, "message": "Order placed successfully!"})
except Exception as e:
print(f"Error during checkout: {str(e)}")
return jsonify({"success": False, "error": str(e)})
@app.route('/get_coupon_codes', methods=['POST'])
def get_coupon_codes():
data = request.json
email = data.get('email')
if not email:
return jsonify({'success': False, 'message': 'Email is required.'})
try:
# Query to fetch active coupon codes for the user
result = sf.query(f"""
SELECT Coupon_Code__c
FROM Referral_Coupon__c
WHERE Referral_Email__c = '{email}' AND Coupon_Status__c = 'Active'
""")
coupons = result.get('records', [])
if not coupons:
return jsonify({'success': False, 'message': 'No active coupons found.'})
return jsonify({'success': True, 'coupons': coupons})
except Exception as e:
print(f"Error fetching coupons: {str(e)}")
return jsonify({'success': False, 'message': 'Error fetching coupons.'})
@app.route('/apply_coupon', methods=['POST'])
def apply_coupon():
data = request.json
coupon_code = data.get('coupon_code')
subtotal = data.get('subtotal')
email = data.get('email')
if not coupon_code:
return jsonify({'success': False, 'message': 'Coupon code is required.'})
try:
# Query Salesforce to check if the coupon code is valid (whether it's active)
query = f"SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Coupon_Code__c = '{coupon_code}' AND Coupon_Status__c = 'Active'"
result = sf.query(query)
if not result['records']:
return jsonify({'success': False, 'message': 'Invalid or expired coupon code.'})
# Apply a fixed 10% discount
discount_percentage = 0.10 # 10% discount
discount_amount = subtotal * discount_percentage
final_total = subtotal - discount_amount
order_query = f"""
SELECT Id, Total_Amount__c, Offers_Applied__c
FROM Order__c
WHERE Customer_Email__c = '{email}' AND Order_Status__c = 'Pending'
ORDER BY CreatedDate DESC
LIMIT 1
"""
order_result = sf.query(order_query)
if order_result.get("records"):
order_id = order_result["records"][0]["Id"]
print(order_id)
update_result = sf.Order__c.update(order_id, {
"Total_Amount__c": final_total, # Update total amount with the discount
"Offers_Applied__c": f"Discount Applied: ${discount_amount:.2f} ({discount_percentage}% off)" # Update discount in offers
})
print(f"Updated order: {update_result}")
return jsonify({
'success': True,
'discount': discount_amount,
'final_total': final_total,
'message': 'Coupon applied successfully.'
})
except Exception as e:
return jsonify({'success': False, 'message': f'Error applying coupon: {str(e)}'})
@app.route("/order", methods=["GET"])
def order_summary():
email = session.get('user_email') # Fetch logged-in user's email
if not email:
return redirect(url_for("login"))
try:
# Fetch the most recent order for the user
result = sf.query(f"""
SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c
FROM Order__c
WHERE Customer_Email__c = '{email}'
ORDER BY CreatedDate DESC
LIMIT 1
""")
order = result.get("records", [])[0] if result.get("records") else None
print(order)
if not order:
return render_template("order.html", order=None)
# Fetch the applied coupon codes for the user
coupon_result = sf.query(f"""
SELECT Coupon_Code__c
FROM Referral_Coupon__c
WHERE Referral_Email__c = '{email}' AND Coupon_Status__c = 'Active'
""")
# Calculate the final total after applying discount
final_total = order['Total_Amount__c'] # Final price after discount
print(final_total)
update_result = sf.Order__c.update(order['Id'], {
"Total_Amount__c": final_total, # Update total amount with the discount
})
print(f"Updated order: {update_result}")
return render_template("order.html", order=order, final_total=final_total)
except Exception as e:
print(f"Error fetching order details: {str(e)}")
return render_template("order.html", order=None, error=str(e))
if __name__ == "__main__":
app.run(debug=False, host="0.0.0.0", port=7860) |