geethareddy commited on
Commit
fe1fd9a
·
verified ·
1 Parent(s): b237eca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -236
app.py CHANGED
@@ -18,66 +18,22 @@ app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q") # Replace
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():
35
- #return "Welcome to Biryani Hub!"
36
  return render_template("index.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
  def menu():
82
  selected_category = request.args.get("category", "All")
83
  try:
@@ -92,195 +48,6 @@ def menu():
92
  categories = []
93
  print(f"Error fetching data: {e}")
94
  return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
95
- def cart():
96
- email = session.get('user_email') # Get logged-in user's email
97
- if not email:
98
- return redirect(url_for("login")) # Redirect to login if not logged in
99
- try:
100
- result = sf.query(f"""
101
- SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
102
- FROM Cart_Item__c
103
- WHERE Customer_Email__c = '{email}'
104
- """)
105
- cart_items = result.get("records", [])
106
- subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
107
- except Exception as e:
108
- print(f"Error fetching cart items: {e}")
109
- cart_items = []
110
- subtotal = 0
111
-
112
- return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)
113
-
114
-
115
-
116
- @app.route('/cart/add', methods=['POST'])
117
- def add_to_cart():
118
- data = request.json
119
- item_name = data.get('itemName')
120
- item_price = data.get('itemPrice')
121
- item_image = data.get('itemImage')
122
- addons = data.get('addons', [])
123
- customer_email = session.get('user_email')
124
-
125
- if not customer_email:
126
- return jsonify({"success": False, "error": "User not logged in."}), 401
127
-
128
- try:
129
- query = f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'"
130
- result = sf.query(query)
131
-
132
- if result['totalSize'] > 0:
133
- # Update existing item quantity
134
- cart_item = result['records'][0]
135
- sf.Cart_Item__c.update(cart_item['Id'], {
136
- "Quantity__c": cart_item['Quantity__c'] + 1
137
- })
138
- else:
139
- # Add new item to the cart
140
- sf.Cart_Item__c.create({
141
- "Name": item_name,
142
- "Price__c": item_price,
143
- "Quantity__c": 1,
144
- "Add_Ons__c": ";".join(addons) if addons else None,
145
- "Image1__c": item_image,
146
- "Customer_Email__c": customer_email,
147
- })
148
- return jsonify({"success": True, "message": "Item added to cart."})
149
- except Exception as e:
150
- return jsonify({"success": False, "error": str(e)}), 500
151
-
152
- @app.route("/cart/add_item", methods=["POST"])
153
- def add_item_to_cart():
154
- data = request.json # Extract JSON data from the request
155
- email = data.get('email') # Customer email
156
- item_name = data.get('item_name') # Item name
157
- quantity = data.get('quantity', 0) # Quantity to add (default is 1) // default value is 1
158
-
159
- try:
160
- # Check if the item already exists in the cart for this customer
161
- cart_items = sf.query(
162
- f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Item_Name__c = '{item_name}'"
163
- )['records']
164
-
165
- if cart_items:
166
- # If the item already exists, update its quantity
167
- cart_item = cart_items[0]
168
- new_quantity = cart_item['Quantity__c'] + quantity
169
- sf.Cart_Item__c.update(cart_item['Id'], {"Quantity__c": new_quantity})
170
- return jsonify({"success": True, "message": "Item quantity updated successfully."})
171
- else:
172
- # If the item does not exist, add it to the cart
173
- sf.Cart_Item__c.create({
174
- "Customer_Email__c": email,
175
- "Item_Name__c": item_name,
176
- "Quantity__c": quantity
177
- })
178
-
179
- return jsonify({"success": True, "message": "Item added/updated successfully.", "redirect": "/menu"})
180
- except Exception as e:
181
- return jsonify({"success": False, "error": str(e)}), 500
182
-
183
 
184
- @app.route('/cart/remove/<item_name>', methods=['POST'])
185
- def remove_cart_item(item_name):
186
- try:
187
- customer_email = session.get('user_email')
188
- if not customer_email:
189
- return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
190
- query = f"""
191
- SELECT Id FROM Cart_Item__c
192
- WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
193
- """
194
- result = sf.query(query)
195
- if result['totalSize'] == 0:
196
- return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
197
- cart_item_id = result['records'][0]['Id']
198
- sf.Cart_Item__c.delete(cart_item_id)
199
- return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
200
- except Exception as e:
201
- print(f"Error: {str(e)}")
202
- return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
203
-
204
- @app.route('/api/addons', methods=['GET'])
205
- def get_addons():
206
- item_name = request.args.get('item_name')
207
- if not item_name:
208
- return jsonify({"success": False, "error": "Item name is required."})
209
-
210
- try:
211
- # Salesforce query to get the add-ons related to the item name
212
- query = f"SELECT Name, Price__c FROM Add_Ons__c"
213
- addons = sf.query(query)['records']# Get records of add-ons
214
- return jsonify({"success": True, "addons": addons})
215
- except Exception as e:
216
- print(f"Error fetching add-ons: {e}")
217
- return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
218
-
219
- @app.route("/cart/update_quantity", methods=["POST"])
220
- def update_quantity():
221
- data = request.json # Extract JSON data from the request
222
- email = data.get('email') # Customer email
223
- item_name = data.get('item_name') # Item name (Cart Item Name in Salesforce)
224
- quantity = data.get('quantity') # New quantity
225
-
226
- # Validate inputs
227
- if not email or not item_name:
228
- return jsonify({"success": False, "error": "Email and item name are required."}), 400
229
-
230
- try:
231
- # Query the cart item using the correct field names
232
- cart_items = sf.query(
233
- f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name__c = '{item_name}'"
234
- )['records']
235
-
236
- if not cart_items:
237
- return jsonify({"success": False, "error": "Cart item not found."}), 404
238
-
239
- # Get the first matching record ID
240
- cart_item_id = cart_items[0]['Id']
241
-
242
- # Update the quantity in Salesforce
243
- sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity})
244
-
245
- return jsonify({"success": True, "new_quantity": quantity})
246
- except Exception as e:
247
- return jsonify({"success": False, "error": str(e)}), 500
248
-
249
- @app.route("/checkout", methods=["POST"])
250
- def checkout():
251
- email = session.get('user_email')
252
- user_id = session.get('user_id')
253
- if not email or not user_id:
254
- return jsonify({"success": False, "message": "User not logged in"})
255
- try:
256
- result = sf.query(f"""
257
- SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
258
- FROM Cart_Item__c
259
- WHERE Customer_Email__c = '{email}'
260
- """)
261
- cart_items = result["records"]
262
- if not cart_items:
263
- return jsonify({"success": False, "message": "Cart is empty"})
264
- total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
265
- order_data = {
266
- "Customer_Name__c": user_id,
267
- "Customer_Email__c": email,
268
- "Total_Amount__c": total_price,
269
- "Order_Status__c": "Pending",
270
- "Order_Items__c": "\n".join(
271
- [f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
272
- ),
273
- "Add_Ons__c": "\n".join(
274
- [f"{item['Add_Ons__c']}" if item['Add_Ons__c'] else "None" for item in cart_items]
275
- ),
276
- }
277
- sf.Order__c.create(order_data)
278
- for item in cart_items:
279
- sf.Cart_Item__c.delete(item["Id"])
280
- return jsonify({"success": True, "message": "Order placed successfully!"})
281
- except Exception as e:
282
- return jsonify({"success": False, "error": str(e)})
283
-
284
  if __name__ == "__main__":
285
  app.run(host='0.0.0.0', port=7860, debug=False)
286
-
 
18
 
19
  # Configure the session type
20
  app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
 
21
  app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
22
  app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
23
 
24
  # Initialize the session
25
+ Session(app)
26
  print("Session interface configured.")
27
 
28
+ # Ensure secure session handling
29
  app.session_interface = SecureCookieSessionInterface()
30
  print("Session interface configured.")
31
 
32
  @app.route("/")
33
  def home():
 
34
  return render_template("index.html")
35
 
36
+ @app.route("/menu", methods=["GET"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def menu():
38
  selected_category = request.args.get("category", "All")
39
  try:
 
48
  categories = []
49
  print(f"Error fetching data: {e}")
50
  return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  if __name__ == "__main__":
53
  app.run(host='0.0.0.0', port=7860, debug=False)