Spaces:
Runtime error
Runtime error
Update app.py (#2)
Browse files- Update app.py (66af2ab49457932d9f40fbcea1dacfe5d9b0b21e)
Co-authored-by: Surendra <[email protected]>
app.py
CHANGED
@@ -1,88 +1,21 @@
|
|
1 |
-
from flask import Flask, render_template, request
|
2 |
-
from
|
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 |
-
#
|
13 |
-
|
14 |
-
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
|
19 |
-
|
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():
|
35 |
-
#return "Welcome to Biryani Hub!"
|
36 |
-
return render_template("menu.html")
|
37 |
-
|
38 |
-
@app.route("/signup", methods=["GET", "POST"])
|
39 |
-
def signup():
|
40 |
-
if request.method == "POST":
|
41 |
-
name = request.form.get("name")
|
42 |
-
phone = request.form.get("phone")
|
43 |
-
email = request.form.get("email")
|
44 |
-
password = request.form.get("password")
|
45 |
-
try:
|
46 |
-
sf.Customer_Login__c.create({
|
47 |
-
"Name": name,
|
48 |
-
"Phone_Number__c": phone,
|
49 |
-
"Email__c": email,
|
50 |
-
"Password__c": password
|
51 |
-
})
|
52 |
-
return redirect(url_for("login"))
|
53 |
-
except Exception as e:
|
54 |
-
return render_template("signup.html", error=f"Error: {str(e)}")
|
55 |
-
return render_template("signup.html")
|
56 |
-
|
57 |
-
@app.route("/login", methods=["GET", "POST"])
|
58 |
-
def login():
|
59 |
-
if request.method == "POST":
|
60 |
-
email = request.form.get("email")
|
61 |
-
password = request.form.get("password")
|
62 |
-
try:
|
63 |
-
query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
|
64 |
-
result = sf.query(query)
|
65 |
-
if result["records"]:
|
66 |
-
session['user_id'] = result["records"][0]['Id']
|
67 |
-
session['user_email'] = email
|
68 |
-
return redirect(url_for("menu"))
|
69 |
-
else:
|
70 |
-
return render_template("login.html", error="Invalid credentials!")
|
71 |
-
except Exception as e:
|
72 |
-
return render_template("login.html", error=f"Error: {str(e)}")
|
73 |
-
return render_template("login.html")
|
74 |
-
|
75 |
-
@app.route("/logout", methods=["POST"])
|
76 |
-
def logout():
|
77 |
-
session.clear() # Clears the session to log the user out
|
78 |
-
return redirect(url_for('login')) # Redirect to the login page
|
79 |
-
|
80 |
-
@app.route("/menu", methods=["GET", "POST"])
|
81 |
-
@app.route("/menu")
|
82 |
-
@app.route("/menu")
|
83 |
def menu():
|
84 |
selected_category = request.args.get("category", "All")
|
85 |
-
|
86 |
try:
|
87 |
query = "SELECT Name, Price__c, Image1__c, Category__c, Description__c FROM Menu_Item__c"
|
88 |
result = sf.query(query)
|
@@ -95,197 +28,8 @@ def menu():
|
|
95 |
food_items = []
|
96 |
categories = []
|
97 |
print(f"Error fetching data: {e}")
|
98 |
-
|
99 |
return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
|
100 |
-
def cart():
|
101 |
-
email = session.get('user_email') # Get logged-in user's email
|
102 |
-
if not email:
|
103 |
-
return redirect(url_for("login")) # Redirect to login if not logged in
|
104 |
-
try:
|
105 |
-
result = sf.query(f"""
|
106 |
-
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
|
107 |
-
FROM Cart_Item__c
|
108 |
-
WHERE Customer_Email__c = '{email}'
|
109 |
-
""")
|
110 |
-
cart_items = result.get("records", [])
|
111 |
-
subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
|
112 |
-
except Exception as e:
|
113 |
-
print(f"Error fetching cart items: {e}")
|
114 |
-
cart_items = []
|
115 |
-
subtotal = 0
|
116 |
-
|
117 |
-
return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
@app.route('/cart/add', methods=['POST'])
|
122 |
-
def add_to_cart():
|
123 |
-
data = request.json
|
124 |
-
item_name = data.get('itemName')
|
125 |
-
item_price = data.get('itemPrice')
|
126 |
-
item_image = data.get('itemImage')
|
127 |
-
addons = data.get('addons', [])
|
128 |
-
customer_email = session.get('user_email')
|
129 |
-
|
130 |
-
if not customer_email:
|
131 |
-
return jsonify({"success": False, "error": "User not logged in."}), 401
|
132 |
-
|
133 |
-
try:
|
134 |
-
query = f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'"
|
135 |
-
result = sf.query(query)
|
136 |
-
|
137 |
-
if result['totalSize'] > 0:
|
138 |
-
# Update existing item quantity
|
139 |
-
cart_item = result['records'][0]
|
140 |
-
sf.Cart_Item__c.update(cart_item['Id'], {
|
141 |
-
"Quantity__c": cart_item['Quantity__c'] + 1
|
142 |
-
})
|
143 |
-
else:
|
144 |
-
# Add new item to the cart
|
145 |
-
sf.Cart_Item__c.create({
|
146 |
-
"Name": item_name,
|
147 |
-
"Price__c": item_price,
|
148 |
-
"Quantity__c": 1,
|
149 |
-
"Add_Ons__c": ";".join(addons) if addons else None,
|
150 |
-
"Image1__c": item_image,
|
151 |
-
"Customer_Email__c": customer_email,
|
152 |
-
})
|
153 |
-
return jsonify({"success": True, "message": "Item added to cart."})
|
154 |
-
except Exception as e:
|
155 |
-
return jsonify({"success": False, "error": str(e)}), 500
|
156 |
-
|
157 |
-
@app.route("/cart/add_item", methods=["POST"])
|
158 |
-
def add_item_to_cart():
|
159 |
-
data = request.json # Extract JSON data from the request
|
160 |
-
email = data.get('email') # Customer email
|
161 |
-
item_name = data.get('item_name') # Item name
|
162 |
-
quantity = data.get('quantity', 0) # Quantity to add (default is 1) // default value is 1
|
163 |
-
|
164 |
-
try:
|
165 |
-
# Check if the item already exists in the cart for this customer
|
166 |
-
cart_items = sf.query(
|
167 |
-
f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Item_Name__c = '{item_name}'"
|
168 |
-
)['records']
|
169 |
-
|
170 |
-
if cart_items:
|
171 |
-
# If the item already exists, update its quantity
|
172 |
-
cart_item = cart_items[0]
|
173 |
-
new_quantity = cart_item['Quantity__c'] + quantity
|
174 |
-
sf.Cart_Item__c.update(cart_item['Id'], {"Quantity__c": new_quantity})
|
175 |
-
return jsonify({"success": True, "message": "Item quantity updated successfully."})
|
176 |
-
else:
|
177 |
-
# If the item does not exist, add it to the cart
|
178 |
-
sf.Cart_Item__c.create({
|
179 |
-
"Customer_Email__c": email,
|
180 |
-
"Item_Name__c": item_name,
|
181 |
-
"Quantity__c": quantity
|
182 |
-
})
|
183 |
|
184 |
-
return jsonify({"success": True, "message": "Item added/updated successfully.", "redirect": "/menu"})
|
185 |
-
except Exception as e:
|
186 |
-
return jsonify({"success": False, "error": str(e)}), 500
|
187 |
-
|
188 |
-
|
189 |
-
@app.route('/cart/remove/<item_name>', methods=['POST'])
|
190 |
-
def remove_cart_item(item_name):
|
191 |
-
try:
|
192 |
-
customer_email = session.get('user_email')
|
193 |
-
if not customer_email:
|
194 |
-
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
|
195 |
-
query = f"""
|
196 |
-
SELECT Id FROM Cart_Item__c
|
197 |
-
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
198 |
-
"""
|
199 |
-
result = sf.query(query)
|
200 |
-
if result['totalSize'] == 0:
|
201 |
-
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
202 |
-
cart_item_id = result['records'][0]['Id']
|
203 |
-
sf.Cart_Item__c.delete(cart_item_id)
|
204 |
-
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
205 |
-
except Exception as e:
|
206 |
-
print(f"Error: {str(e)}")
|
207 |
-
return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
|
208 |
-
|
209 |
-
@app.route('/api/addons', methods=['GET'])
|
210 |
-
def get_addons():
|
211 |
-
item_name = request.args.get('item_name')
|
212 |
-
if not item_name:
|
213 |
-
return jsonify({"success": False, "error": "Item name is required."})
|
214 |
-
|
215 |
-
try:
|
216 |
-
# Salesforce query to get the add-ons related to the item name
|
217 |
-
query = f"SELECT Name, Price__c FROM Add_Ons__c"
|
218 |
-
addons = sf.query(query)['records']# Get records of add-ons
|
219 |
-
return jsonify({"success": True, "addons": addons})
|
220 |
-
except Exception as e:
|
221 |
-
print(f"Error fetching add-ons: {e}")
|
222 |
-
return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
|
223 |
-
|
224 |
-
@app.route("/cart/update_quantity", methods=["POST"])
|
225 |
-
def update_quantity():
|
226 |
-
data = request.json # Extract JSON data from the request
|
227 |
-
email = data.get('email') # Customer email
|
228 |
-
item_name = data.get('item_name') # Item name (Cart Item Name in Salesforce)
|
229 |
-
quantity = data.get('quantity') # New quantity
|
230 |
-
|
231 |
-
# Validate inputs
|
232 |
-
if not email or not item_name:
|
233 |
-
return jsonify({"success": False, "error": "Email and item name are required."}), 400
|
234 |
-
|
235 |
-
try:
|
236 |
-
# Query the cart item using the correct field names
|
237 |
-
cart_items = sf.query(
|
238 |
-
f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name__c = '{item_name}'"
|
239 |
-
)['records']
|
240 |
-
|
241 |
-
if not cart_items:
|
242 |
-
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
243 |
-
|
244 |
-
# Get the first matching record ID
|
245 |
-
cart_item_id = cart_items[0]['Id']
|
246 |
-
|
247 |
-
# Update the quantity in Salesforce
|
248 |
-
sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity})
|
249 |
-
|
250 |
-
return jsonify({"success": True, "new_quantity": quantity})
|
251 |
-
except Exception as e:
|
252 |
-
return jsonify({"success": False, "error": str(e)}), 500
|
253 |
-
|
254 |
-
@app.route("/checkout", methods=["POST"])
|
255 |
-
def checkout():
|
256 |
-
email = session.get('user_email')
|
257 |
-
user_id = session.get('user_id')
|
258 |
-
if not email or not user_id:
|
259 |
-
return jsonify({"success": False, "message": "User not logged in"})
|
260 |
-
try:
|
261 |
-
result = sf.query(f"""
|
262 |
-
SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
|
263 |
-
FROM Cart_Item__c
|
264 |
-
WHERE Customer_Email__c = '{email}'
|
265 |
-
""")
|
266 |
-
cart_items = result["records"]
|
267 |
-
if not cart_items:
|
268 |
-
return jsonify({"success": False, "message": "Cart is empty"})
|
269 |
-
total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
|
270 |
-
order_data = {
|
271 |
-
"Customer_Name__c": user_id,
|
272 |
-
"Customer_Email__c": email,
|
273 |
-
"Total_Amount__c": total_price,
|
274 |
-
"Order_Status__c": "Pending",
|
275 |
-
"Order_Items__c": "\n".join(
|
276 |
-
[f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
|
277 |
-
),
|
278 |
-
"Add_Ons__c": "\n".join(
|
279 |
-
[f"{item['Add_Ons__c']}" if item['Add_Ons__c'] else "None" for item in cart_items]
|
280 |
-
),
|
281 |
-
}
|
282 |
-
sf.Order__c.create(order_data)
|
283 |
-
for item in cart_items:
|
284 |
-
sf.Cart_Item__c.delete(item["Id"])
|
285 |
-
return jsonify({"success": True, "message": "Order placed successfully!"})
|
286 |
-
except Exception as e:
|
287 |
-
return jsonify({"success": False, "error": str(e)})
|
288 |
-
|
289 |
if __name__ == "__main__":
|
290 |
-
|
291 |
-
|
|
|
1 |
+
from flask import Flask, render_template, request
|
2 |
+
from simple_salesforce import Salesforce
|
|
|
|
|
3 |
import os
|
4 |
|
|
|
|
|
5 |
app = Flask(__name__)
|
|
|
6 |
|
7 |
+
# Salesforce credentials
|
8 |
+
SF_USERNAME = os.getenv("SF_USERNAME", "your_username")
|
9 |
+
SF_PASSWORD = os.getenv("SF_PASSWORD", "your_password")
|
10 |
+
SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN", "your_security_token")
|
11 |
|
12 |
+
# Connect to Salesforce
|
13 |
+
sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_SECURITY_TOKEN)
|
14 |
|
15 |
+
@app.route("/menu", methods=["GET"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
def menu():
|
17 |
selected_category = request.args.get("category", "All")
|
18 |
+
|
19 |
try:
|
20 |
query = "SELECT Name, Price__c, Image1__c, Category__c, Description__c FROM Menu_Item__c"
|
21 |
result = sf.query(query)
|
|
|
28 |
food_items = []
|
29 |
categories = []
|
30 |
print(f"Error fetching data: {e}")
|
31 |
+
|
32 |
return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
if __name__ == "__main__":
|
35 |
+
app.run(debug=True)
|
|