Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,13 @@
|
|
1 |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
|
2 |
-
|
3 |
-
from flask.sessions import SecureCookieSessionInterface # Import the class
|
4 |
from salesforce import get_salesforce_connection
|
5 |
-
import os
|
6 |
|
7 |
# Initialize Flask app and Salesforce connection
|
8 |
-
print("Starting app...")
|
9 |
app = Flask(__name__)
|
10 |
-
print("Flask app initialized.")
|
11 |
-
|
12 |
-
# Add debug logs in Salesforce connection setup
|
13 |
sf = get_salesforce_connection()
|
14 |
-
print("Salesforce connection established.")
|
15 |
|
16 |
# Set the secret key to handle sessions securely
|
17 |
-
app.secret_key =
|
18 |
-
|
19 |
-
# Configure the session type
|
20 |
-
app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
|
21 |
-
#app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
|
22 |
-
app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
|
23 |
-
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
|
24 |
-
|
25 |
-
# Initialize the session
|
26 |
-
Session(app) # Correctly initialize the Session object
|
27 |
-
print("Session interface configured.")
|
28 |
-
|
29 |
-
# Ensure secure session handling for environments like Hugging Face
|
30 |
-
app.session_interface = SecureCookieSessionInterface()
|
31 |
-
print("Session interface configured.")
|
32 |
|
33 |
@app.route("/")
|
34 |
def home():
|
@@ -58,52 +37,38 @@ def login():
|
|
58 |
if request.method == "POST":
|
59 |
email = request.form.get("email")
|
60 |
password = request.form.get("password")
|
61 |
-
print(f"Login attempt with email: {email}") # Debug log
|
62 |
-
|
63 |
try:
|
64 |
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
|
65 |
result = sf.query(query)
|
66 |
-
|
67 |
if result["records"]:
|
68 |
session['user_id'] = result["records"][0]['Id']
|
69 |
session['user_email'] = email
|
70 |
-
print(f"Session variables set: user_id={session['user_id']}, user_email={session['user_email']}")
|
71 |
-
#print(f"Session cookie: {request.cookies.get(app.session_cookie_name)}") # Check session cookie
|
72 |
return redirect(url_for("menu"))
|
73 |
else:
|
74 |
-
print("Invalid credentials!")
|
75 |
return render_template("login.html", error="Invalid credentials!")
|
76 |
except Exception as e:
|
77 |
-
print(f"Error during login: {str(e)}")
|
78 |
return render_template("login.html", error=f"Error: {str(e)}")
|
79 |
-
|
80 |
return render_template("login.html")
|
81 |
|
82 |
@app.route("/menu", methods=["GET", "POST"])
|
83 |
def menu():
|
84 |
selected_category = request.args.get("category", "All")
|
85 |
user_id = session.get('user_id')
|
86 |
-
print(f"Cookies on /menu: {request.cookies}") # Debug: Check cookies sent
|
87 |
-
print(f"Session check in /menu: user_id={user_id}")
|
88 |
-
|
89 |
if not user_id:
|
90 |
-
print("Session missing, redirecting to login.")
|
91 |
return redirect(url_for('login'))
|
92 |
-
|
93 |
try:
|
94 |
-
query = "SELECT Name, Price__c, Image1__c,
|
95 |
result = sf.query(query)
|
96 |
food_items = result['records'] if 'records' in result else []
|
97 |
categories = {item['Category__c'] for item in food_items if 'Category__c' in item}
|
98 |
if selected_category != "All":
|
99 |
food_items = [item for item in food_items if item.get("Category__c") == selected_category]
|
100 |
except Exception as e:
|
101 |
-
print(f"Error fetching menu data: {str(e)}")
|
102 |
food_items = []
|
103 |
categories = []
|
|
|
104 |
return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
|
105 |
|
106 |
-
|
107 |
@app.route("/cart", methods=["GET"])
|
108 |
def cart():
|
109 |
email = session.get('user_email') # Get logged-in user's email
|
@@ -129,41 +94,38 @@ def cart():
|
|
129 |
@app.route('/cart/add', methods=['POST'])
|
130 |
def add_to_cart():
|
131 |
data = request.json
|
132 |
-
item_name = data.get('itemName')
|
133 |
item_price = data.get('itemPrice')
|
134 |
item_image = data.get('itemImage')
|
135 |
addons = data.get('addons', [])
|
136 |
-
customer_email = session.get('user_email')
|
137 |
|
138 |
-
if not
|
139 |
-
return jsonify({"success": False, "error": "
|
140 |
|
141 |
try:
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
if result['totalSize'] > 0:
|
148 |
-
# Update quantity if the item exists
|
149 |
cart_item = result['records'][0]
|
150 |
sf.Cart_Item__c.update(cart_item['Id'], {
|
151 |
"Quantity__c": cart_item['Quantity__c'] + 1
|
152 |
})
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
return jsonify({"success": True, "message": "Item added/updated successfully."})
|
165 |
except Exception as e:
|
166 |
-
return jsonify({"success": False, "error": str(e)})
|
167 |
|
168 |
@app.route("/cart/add_item", methods=["POST"])
|
169 |
def add_item_to_cart():
|
@@ -192,7 +154,7 @@ def add_item_to_cart():
|
|
192 |
"Quantity__c": quantity
|
193 |
})
|
194 |
|
195 |
-
return jsonify({"success": True, "message": "Item added/updated successfully."})
|
196 |
except Exception as e:
|
197 |
return jsonify({"success": False, "error": str(e)}), 500
|
198 |
|
@@ -224,7 +186,7 @@ def get_addons():
|
|
224 |
return jsonify({"success": False, "error": "Item name is required."})
|
225 |
|
226 |
try:
|
227 |
-
query = f"SELECT Name, Price__c FROM Add_Ons__c"
|
228 |
addons = sf.query(query)['records']
|
229 |
return jsonify({"success": True, "addons": addons})
|
230 |
except Exception as e:
|
@@ -299,4 +261,5 @@ def checkout():
|
|
299 |
return jsonify({"success": False, "error": str(e)})
|
300 |
|
301 |
if __name__ == "__main__":
|
302 |
-
app.run(
|
|
|
|
1 |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
|
2 |
+
import random
|
|
|
3 |
from salesforce import get_salesforce_connection
|
|
|
4 |
|
5 |
# Initialize Flask app and Salesforce connection
|
|
|
6 |
app = Flask(__name__)
|
|
|
|
|
|
|
7 |
sf = get_salesforce_connection()
|
|
|
8 |
|
9 |
# Set the secret key to handle sessions securely
|
10 |
+
app.secret_key = 'sSSjyhInIsUohKpG8sHzty2q' # Replace with a secure key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
@app.route("/")
|
13 |
def home():
|
|
|
37 |
if request.method == "POST":
|
38 |
email = request.form.get("email")
|
39 |
password = request.form.get("password")
|
|
|
|
|
40 |
try:
|
41 |
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
|
42 |
result = sf.query(query)
|
|
|
43 |
if result["records"]:
|
44 |
session['user_id'] = result["records"][0]['Id']
|
45 |
session['user_email'] = email
|
|
|
|
|
46 |
return redirect(url_for("menu"))
|
47 |
else:
|
|
|
48 |
return render_template("login.html", error="Invalid credentials!")
|
49 |
except Exception as e:
|
|
|
50 |
return render_template("login.html", error=f"Error: {str(e)}")
|
|
|
51 |
return render_template("login.html")
|
52 |
|
53 |
@app.route("/menu", methods=["GET", "POST"])
|
54 |
def menu():
|
55 |
selected_category = request.args.get("category", "All")
|
56 |
user_id = session.get('user_id')
|
|
|
|
|
|
|
57 |
if not user_id:
|
|
|
58 |
return redirect(url_for('login'))
|
|
|
59 |
try:
|
60 |
+
query = "SELECT Name, Price__c, Image1__c, Category__c, Description__c FROM Menu_Item__c"
|
61 |
result = sf.query(query)
|
62 |
food_items = result['records'] if 'records' in result else []
|
63 |
categories = {item['Category__c'] for item in food_items if 'Category__c' in item}
|
64 |
if selected_category != "All":
|
65 |
food_items = [item for item in food_items if item.get("Category__c") == selected_category]
|
66 |
except Exception as e:
|
|
|
67 |
food_items = []
|
68 |
categories = []
|
69 |
+
print(f"Error fetching data: {e}")
|
70 |
return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
|
71 |
|
|
|
72 |
@app.route("/cart", methods=["GET"])
|
73 |
def cart():
|
74 |
email = session.get('user_email') # Get logged-in user's email
|
|
|
94 |
@app.route('/cart/add', methods=['POST'])
|
95 |
def add_to_cart():
|
96 |
data = request.json
|
97 |
+
item_name = data.get('itemName')
|
98 |
item_price = data.get('itemPrice')
|
99 |
item_image = data.get('itemImage')
|
100 |
addons = data.get('addons', [])
|
101 |
+
customer_email = session.get('user_email')
|
102 |
|
103 |
+
if not customer_email:
|
104 |
+
return jsonify({"success": False, "error": "User not logged in."}), 401
|
105 |
|
106 |
try:
|
107 |
+
query = f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'"
|
108 |
+
result = sf.query(query)
|
109 |
+
|
110 |
+
if result['totalSize'] > 0:
|
111 |
+
# Update existing item quantity
|
|
|
|
|
112 |
cart_item = result['records'][0]
|
113 |
sf.Cart_Item__c.update(cart_item['Id'], {
|
114 |
"Quantity__c": cart_item['Quantity__c'] + 1
|
115 |
})
|
116 |
+
else:
|
117 |
+
# Add new item to the cart
|
118 |
+
sf.Cart_Item__c.create({
|
119 |
+
"Name": item_name,
|
120 |
+
"Price__c": item_price,
|
121 |
+
"Quantity__c": 1,
|
122 |
+
"Add_Ons__c": ";".join(addons) if addons else None,
|
123 |
+
"Image1__c": item_image,
|
124 |
+
"Customer_Email__c": customer_email,
|
125 |
+
})
|
126 |
+
return jsonify({"success": True, "message": "Item added to cart."})
|
|
|
127 |
except Exception as e:
|
128 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
129 |
|
130 |
@app.route("/cart/add_item", methods=["POST"])
|
131 |
def add_item_to_cart():
|
|
|
154 |
"Quantity__c": quantity
|
155 |
})
|
156 |
|
157 |
+
return jsonify({"success": True, "message": "Item added/updated successfully.", "redirect": "/menu"})
|
158 |
except Exception as e:
|
159 |
return jsonify({"success": False, "error": str(e)}), 500
|
160 |
|
|
|
186 |
return jsonify({"success": False, "error": "Item name is required."})
|
187 |
|
188 |
try:
|
189 |
+
query = f"SELECT Name, Price__c FROM Add_Ons__c WHERE Menu_Item__r.Name = '{item_name}'"
|
190 |
addons = sf.query(query)['records']
|
191 |
return jsonify({"success": True, "addons": addons})
|
192 |
except Exception as e:
|
|
|
261 |
return jsonify({"success": False, "error": str(e)})
|
262 |
|
263 |
if __name__ == "__main__":
|
264 |
+
app.run(host="0.0.0.0", port=8080)
|
265 |
+
|