Spaces:
Sleeping
Sleeping
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 | |
# 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.") | |
def home(): | |
return render_template("index.html") | |
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") | |
try: | |
sf.Customer_Login__c.create({ | |
"Name": name, | |
"Phone_Number__c": phone, | |
"Email__c": email, | |
"Password__c": password | |
}) | |
return redirect(url_for("login")) | |
except Exception as e: | |
return render_template("signup.html", error=f"Error: {str(e)}") | |
return render_template("signup.html") | |
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") | |
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, | |
) | |
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", []) | |
for item in cart_items: | |
item['Add_Ons__c'] = item.get('Add_Ons__c', "None") | |
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) | |
def add_to_cart(): | |
data = request.json | |
item_name = data.get('itemName').strip() | |
item_price = data.get('itemPrice') | |
item_image = data.get('itemImage') | |
addons = data.get('addons', []) | |
customer_email = session.get('user_email') # Get logged-in user's email from session | |
# Validate the required fields | |
if not item_name or not item_price: | |
return jsonify({"success": False, "error": "Item name and price are required."}) | |
try: | |
# Add a new item to the cart with the provided details | |
sf.Cart_Item__c.create({ | |
"Name": item_name, # Item name | |
"Price__c": item_price, # Item price | |
"Quantity__c": 1, # Always add as a new entry with quantity 1 | |
"Add_Ons__c": ";".join(addons) if addons and isinstance(addons, list) else "None", # Convert add-ons to a string | |
"Image1__c": item_image, # Item image | |
"Customer_Email__c": customer_email, # Associate with the logged-in user | |
}) | |
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)}) | |
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": ";".join(addons) if addons and isinstance(addons, list) else "None" # Add-ons (if any) | |
}) | |
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 | |
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 | |
def get_addons(): | |
item_name = request.args.get('item_name') | |
if not item_name: | |
return jsonify({"success": False, "error": "Item name is required."}) | |
try: | |
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."}) | |
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, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name__c = '{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'] | |
# Update the quantity in Salesforce | |
sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity}) | |
return jsonify({"success": True, "new_quantity": quantity}) | |
except Exception as e: | |
return jsonify({"success": False, "error": str(e)}), 500 | |
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: | |
result = sf.query(f""" | |
SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c | |
FROM Cart_Item__c | |
WHERE Customer_Email__c = '{email}' | |
""") | |
cart_items = result["records"] | |
if not cart_items: | |
return jsonify({"success": False, "message": "Cart is empty"}) | |
total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items) | |
order_data = { | |
"Customer_Name__c": user_id, | |
"Customer_Email__c": email, | |
"Total_Amount__c": total_price, | |
"Order_Status__c": "Pending", | |
"Order_Items__c": "\n".join( | |
[f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items] | |
), | |
"Add_Ons__c": "\n".join( | |
[item['Add_Ons__c'] if item.get('Add_Ons__c') else "None" for item in cart_items] | |
), | |
} | |
sf.Order__c.create(order_data) | |
for item in cart_items: | |
sf.Cart_Item__c.delete(item["Id"]) | |
return jsonify({"success": True, "message": "Order placed successfully!"}) | |
except Exception as e: | |
return jsonify({"success": False, "error": str(e)}) | |
if __name__ == "__main__": | |
app.run(debug=False, host="0.0.0.0", port=7860) |