BiryaniHubsales / app.py
geethareddy's picture
Update app.py
5bde4c7 verified
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask.sessions import SecureCookieSessionInterface
from salesforce import get_salesforce_connection
import os
# 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
app.config["SESSION_COOKIE_PATH"] = "/" # Available across all routes
app.config["SESSION_COOKIE_DOMAIN"] = None # Let the browser determine the domain
app.config["SESSION_COOKIE_SECURE"] = False # Set to True if HTTPS
app.config["SESSION_COOKIE_HTTPONLY"] = True # Prevent JavaScript access
app.config["SESSION_PERMANENT"] = False # Do not use permanent sessions
# Ensure secure session handling for environments like Hugging Face
app.session_interface = SecureCookieSessionInterface()
print("Session interface configured.")
@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")) # Redirect to login if not logged in
try:
result = sf.query(f"""
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
FROM Cart_Item__c
WHERE Customer_Email__c = '{email}'
""")
cart_items = result.get("records", [])
subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
except Exception as e:
print(f"Error fetching cart items: {e}")
cart_items = []
subtotal = 0
return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
@app.route("/cart/update_quantity", methods=["POST"])
def update_quantity():
data = request.json # Extract JSON data from the request
email = data.get('email') # Customer email
item_name = data.get('item_name') # Item name (Cart Item Name in Salesforce)
quantity = data.get('quantity') # New quantity
# Validate inputs
if not email or not item_name:
return jsonify({"success": False, "error": "Email and item name are required."}), 400
try:
# Query the cart item using the correct field names
cart_items = sf.query(
f"SELECT Id, Price__c, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
)['records']
if not cart_items:
return jsonify({"success": False, "error": "Cart item not found."}), 404
# Get the first matching record ID
cart_item_id = cart_items[0]['Id']
item_price = cart_items[0]['Price__c'] # Get the price of the item
# Update the quantity in Salesforce
sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity})
# Recalculate subtotal for the cart
result = sf.query(f"""
SELECT Quantity__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}'
""")
cart_items = result["records"]
subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
return jsonify({"success": True, "new_quantity": quantity, "subtotal": subtotal, "new_price": item_price * quantity})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=False, host="0.0.0.0", port=7860)