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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
|
2 |
+
from flask_session import Session # Import the Session class
|
3 |
+
from flask.sessions import SecureCookieSessionInterface # Import the class
|
4 |
+
from salesforce import get_salesforce_connection
|
5 |
+
from datetime import timedelta
|
6 |
+
import os
|
7 |
+
|
8 |
+
# Initialize Flask app and Salesforce connection
|
9 |
+
print("Starting app...")
|
10 |
+
app = Flask(__name__)
|
11 |
+
print("Flask app initialized.")
|
12 |
+
|
13 |
+
# Add debug logs in Salesforce connection setup
|
14 |
+
sf = get_salesforce_connection()
|
15 |
+
print("Salesforce connection established.")
|
16 |
+
|
17 |
+
# Set the secret key to handle sessions securely
|
18 |
+
app.secret_key = os.getenv("SECRET_KEY", "xEr0cwgsiatzrzaeFewYrVA1O") # Replace with a secure key
|
19 |
+
|
20 |
+
# Configure the session type
|
21 |
+
app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
|
22 |
+
#app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
|
23 |
+
app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
|
24 |
+
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
|
25 |
+
|
26 |
+
# Initialize the session
|
27 |
+
Session(app) # Correctly initialize the Session object
|
28 |
+
print("Session interface configured.")
|
29 |
+
|
30 |
+
# Ensure secure session handling for environments like Hugging Face
|
31 |
+
app.session_interface = SecureCookieSessionInterface()
|
32 |
+
print("Session interface configured.")
|
33 |
+
import random
|
34 |
+
import string
|
35 |
+
|
36 |
+
def generate_referral_code(length=8):
|
37 |
+
# Generates a random referral code with uppercase, lowercase letters, and digits
|
38 |
+
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
|
39 |
+
referral_code = ''.join(random.choice(characters) for _ in range(length))
|
40 |
+
return referral_code
|
41 |
+
|
42 |
+
@app.route("/")
|
43 |
+
def home():
|
44 |
+
# Fetch user details from URL parameters
|
45 |
+
user_email = request.args.get("email")
|
46 |
+
user_name = request.args.get("name")
|
47 |
+
table_number = request.args.get("table") # Capture table number
|
48 |
+
|
49 |
+
if user_email and user_name:
|
50 |
+
session["user_email"] = user_email
|
51 |
+
session["user_name"] = user_name
|
52 |
+
session["table_number"] = table_number # Store table number in session
|
53 |
+
print(f"User logged in: {user_email} - {user_name} - Table: {table_number}")
|
54 |
+
|
55 |
+
# Ensure session is saved before redirecting
|
56 |
+
session.modified = True
|
57 |
+
return redirect(url_for("menu")) # Redirect to menu directly
|
58 |
+
|
59 |
+
return render_template("index.html")
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
from datetime import datetime
|
64 |
+
|
65 |
+
def generate_coupon_code(length=10):
|
66 |
+
"""Generates a random alphanumeric coupon code"""
|
67 |
+
characters = string.ascii_uppercase + string.digits # A-Z, 0-9
|
68 |
+
return ''.join(random.choice(characters) for _ in range(length))
|
69 |
+
@app.route("/generate_custom_dish", methods=["POST"])
|
70 |
+
def generate_custom_dish():
|
71 |
+
try:
|
72 |
+
data = request.form
|
73 |
+
dish_name = data.get("name")
|
74 |
+
description = data.get("description")
|
75 |
+
item_image_url = "https://huggingface.co/spaces/nagasurendra/BiryaniHubflask30/resolve/main/static/customized.jpg"
|
76 |
+
item_image_url2 = "https://huggingface.co/spaces/nagasurendra/BiryaniHubflask30/resolve/main/static/customized1.jpg"
|
77 |
+
|
78 |
+
if not dish_name or not description:
|
79 |
+
return jsonify({"success": False, "error": "Both fields are required"}), 400
|
80 |
+
|
81 |
+
# Generate a random price for the custom dish
|
82 |
+
price = random.randint(10, 30) # Example logic for price setting
|
83 |
+
|
84 |
+
# Determine Veg/Non-Veg
|
85 |
+
veg_keywords = ["paneer", "vegetable", "mushroom", "cheese"]
|
86 |
+
non_veg_keywords = ["chicken", "mutton", "fish", "egg"]
|
87 |
+
|
88 |
+
category = "Veg" if any(word in description.lower() for word in veg_keywords) else \
|
89 |
+
"Non veg" if any(word in description.lower() for word in non_veg_keywords) else \
|
90 |
+
"both"
|
91 |
+
|
92 |
+
# Query to check if the dish already exists in Salesforce (Custom_Dish__c object)
|
93 |
+
existing_dish_query = f"SELECT Id, Name, Price__c, Image1__c, Image2__c, Description__c, Veg_NonVeg__c FROM Custom_Dish__c WHERE Name = '{dish_name}'"
|
94 |
+
existing_dish_result = sf.query(existing_dish_query)
|
95 |
+
|
96 |
+
if existing_dish_result['totalSize'] > 0:
|
97 |
+
# If the dish exists, use the existing details
|
98 |
+
existing_dish = existing_dish_result['records'][0]
|
99 |
+
price = existing_dish['Price__c']
|
100 |
+
item_image_url = existing_dish['Image1__c']
|
101 |
+
item_image_url2 = existing_dish['Image2__c']
|
102 |
+
category = existing_dish['Veg_NonVeg__c']
|
103 |
+
else:
|
104 |
+
# If the dish does not exist, create a new custom dish
|
105 |
+
custom_dish = {
|
106 |
+
'Name': dish_name,
|
107 |
+
'Price__c': price,
|
108 |
+
'Image1__c': item_image_url,
|
109 |
+
'Image2__c': item_image_url2,
|
110 |
+
'Description__c': description,
|
111 |
+
'Veg_NonVeg__c': category,
|
112 |
+
'Section__c': 'Customized dish',
|
113 |
+
'Total_Ordered__c': 0
|
114 |
+
}
|
115 |
+
|
116 |
+
# Insert the custom dish into Salesforce (Custom_Dish__c object)
|
117 |
+
result = sf.Custom_Dish__c.create(custom_dish)
|
118 |
+
|
119 |
+
if not result.get('success'):
|
120 |
+
return jsonify({"success": False, "error": "Failed to create custom dish in Salesforce"}), 500
|
121 |
+
|
122 |
+
# After ensuring the dish exists, check if it's already in the Cart_Item__c
|
123 |
+
email = session.get('user_email') # Assuming you have the user's email in session
|
124 |
+
|
125 |
+
# Query to check if the custom dish already exists in the cart for the logged-in user
|
126 |
+
cart_item_query = f"SELECT Id, Quantity__c, Price__c, Base_Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name = '{dish_name}'"
|
127 |
+
cart_item_result = sf.query(cart_item_query)
|
128 |
+
|
129 |
+
if cart_item_result['totalSize'] > 0:
|
130 |
+
# If the custom dish is already in the cart, update the quantity and price
|
131 |
+
cart_item = cart_item_result['records'][0]
|
132 |
+
new_quantity = cart_item['Quantity__c'] + 1 # Increase quantity by 1
|
133 |
+
new_price = price * new_quantity # Update price based on new quantity
|
134 |
+
|
135 |
+
# Update the cart item in Salesforce
|
136 |
+
updated_cart_item = {
|
137 |
+
'Quantity__c': new_quantity,
|
138 |
+
'Price__c': new_price
|
139 |
+
}
|
140 |
+
|
141 |
+
cart_item_update = sf.Cart_Item__c.update(cart_item['Id'], updated_cart_item)
|
142 |
+
|
143 |
+
else:
|
144 |
+
# If the custom dish is not in the cart, create a new cart item
|
145 |
+
cart_item = {
|
146 |
+
'Name': dish_name,
|
147 |
+
'Price__c': price,
|
148 |
+
'Base_Price__c': price,
|
149 |
+
'Image1__c': item_image_url,
|
150 |
+
'Quantity__c': 1, # Default quantity is 1
|
151 |
+
'Add_Ons__c': '', # Set Add_ons__c to empty
|
152 |
+
'Add_Ons_Price__c': 0, # Set Add_ons_Price__c to 0
|
153 |
+
'Customer_Email__c': email # Associate the custom dish with the logged-in user
|
154 |
+
}
|
155 |
+
|
156 |
+
# Insert the custom dish as a Cart_Item__c record in Salesforce
|
157 |
+
cart_result = sf.Cart_Item__c.create(cart_item)
|
158 |
+
|
159 |
+
# Redirect to the cart page after successfully adding or updating the cart item
|
160 |
+
return redirect(url_for("cart"))
|
161 |
+
|
162 |
+
except Exception as e:
|
163 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
164 |
+
|
165 |
+
@app.route("/customer_details", methods=["GET"])
|
166 |
+
def customer_details():
|
167 |
+
email = session.get('user_email') # Get logged-in user's email
|
168 |
+
if not email:
|
169 |
+
return redirect(url_for("login"))
|
170 |
+
|
171 |
+
try:
|
172 |
+
# Fetch customer details from Salesforce based on the email
|
173 |
+
customer_record = sf.query(f"""
|
174 |
+
SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
|
175 |
+
FROM Customer_Login__c
|
176 |
+
WHERE Email__c = '{email}'
|
177 |
+
LIMIT 1
|
178 |
+
""")
|
179 |
+
|
180 |
+
if not customer_record.get("records"):
|
181 |
+
flash("Customer not found", "danger")
|
182 |
+
return redirect(url_for("login"))
|
183 |
+
|
184 |
+
customer = customer_record["records"][0]
|
185 |
+
|
186 |
+
# Prepare the data to return to the frontend
|
187 |
+
customer_data = {
|
188 |
+
"name": customer.get("Name", ""),
|
189 |
+
"email": customer.get("Email__c", ""),
|
190 |
+
"phone": customer.get("Phone_Number__c", ""),
|
191 |
+
"referral_code": customer.get("Referral__c", ""),
|
192 |
+
"reward_points": customer.get("Reward_Points__c", 0)
|
193 |
+
}
|
194 |
+
|
195 |
+
return render_template("customer_details.html", customer=customer_data)
|
196 |
+
|
197 |
+
except Exception as e:
|
198 |
+
flash(f"Error fetching customer details: {str(e)}", "danger")
|
199 |
+
return redirect(url_for("login"))
|
200 |
+
|
201 |
+
@app.route("/update_profile", methods=["POST"])
|
202 |
+
def update_profile():
|
203 |
+
email = session.get('user_email') # Get logged-in user's email
|
204 |
+
if not email:
|
205 |
+
return jsonify({'status': 'error', 'message': 'User not logged in'})
|
206 |
+
|
207 |
+
try:
|
208 |
+
# Fetch user details from Salesforce
|
209 |
+
result = sf.query(f"""
|
210 |
+
SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
|
211 |
+
FROM Customer_Login__c
|
212 |
+
WHERE Email__c = '{email}'
|
213 |
+
""")
|
214 |
+
|
215 |
+
if not result['records']:
|
216 |
+
return jsonify({'status': 'error', 'message': 'User not found'})
|
217 |
+
|
218 |
+
user = result['records'][0]
|
219 |
+
user_id = user.get("Id")
|
220 |
+
|
221 |
+
# Get updated profile data from the form
|
222 |
+
new_name = request.form.get('customerName')
|
223 |
+
new_email = request.form.get('email')
|
224 |
+
new_phone = request.form.get('phone')
|
225 |
+
new_referral_code = request.form.get('referralCode')
|
226 |
+
new_reward_points = request.form.get('rewardPoints')
|
227 |
+
|
228 |
+
# Prepare data for Salesforce update
|
229 |
+
update_data = {
|
230 |
+
'Name': new_name,
|
231 |
+
'Email__c': new_email,
|
232 |
+
'Phone_Number__c': new_phone,
|
233 |
+
'Referral__c': new_referral_code,
|
234 |
+
'Reward_Points__c': new_reward_points
|
235 |
+
}
|
236 |
+
|
237 |
+
# Update Salesforce record
|
238 |
+
sf.Customer_Login__c.update(user_id, update_data)
|
239 |
+
|
240 |
+
return jsonify({
|
241 |
+
'status': 'success',
|
242 |
+
'message': 'Profile updated successfully!',
|
243 |
+
'data': update_data
|
244 |
+
})
|
245 |
+
|
246 |
+
except Exception as e:
|
247 |
+
return jsonify({'status': 'error', 'message': str(e)})
|
248 |
+
|
249 |
+
|
250 |
+
|
251 |
+
from datetime import datetime
|
252 |
+
import pytz # Library to handle timezone conversions
|
253 |
+
|
254 |
+
@app.route("/order-history", methods=["GET"])
|
255 |
+
def order_history():
|
256 |
+
email = session.get('user_email') # Get logged-in user's email
|
257 |
+
if not email:
|
258 |
+
return redirect(url_for("login"))
|
259 |
+
|
260 |
+
try:
|
261 |
+
# Fetch past orders for the user
|
262 |
+
result = sf.query(f"""
|
263 |
+
SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c,
|
264 |
+
Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c, CreatedDate
|
265 |
+
FROM Order__c
|
266 |
+
WHERE Customer_Email__c = '{email}'
|
267 |
+
ORDER BY CreatedDate DESC
|
268 |
+
""")
|
269 |
+
|
270 |
+
print(f"Salesforce query result: {result}") # Debugging line
|
271 |
+
|
272 |
+
orders = result.get("records", []) # Fetch all orders
|
273 |
+
|
274 |
+
if not orders:
|
275 |
+
print("No orders found for this email.") # Debugging line
|
276 |
+
|
277 |
+
# Format the order details for better readability
|
278 |
+
for order in orders:
|
279 |
+
order_details = order.get("Order_Details__c", "")
|
280 |
+
items = order_details.split("\n") # Assuming each item is separated by a new line
|
281 |
+
formatted_items = []
|
282 |
+
|
283 |
+
# Loop through the items and format them as "item name * quantity"
|
284 |
+
for item in items:
|
285 |
+
item_details = item.split(" | ")
|
286 |
+
if len(item_details) > 1:
|
287 |
+
name = item_details[0].strip()
|
288 |
+
quantity = item_details[1].strip()
|
289 |
+
formatted_items.append(f"{name} * {quantity}")
|
290 |
+
|
291 |
+
# Join the formatted items into a single string
|
292 |
+
order['formatted_items'] = ", ".join(formatted_items)
|
293 |
+
|
294 |
+
# Get the order date and time from CreatedDate
|
295 |
+
created_date = order.get("CreatedDate", "")
|
296 |
+
if created_date:
|
297 |
+
# Convert CreatedDate to datetime object in UTC
|
298 |
+
utc_datetime = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.000+0000')
|
299 |
+
utc_datetime = utc_datetime.replace(tzinfo=pytz.UTC)
|
300 |
+
|
301 |
+
# Convert UTC datetime to the desired timezone (e.g., IST)
|
302 |
+
local_timezone = pytz.timezone('Asia/Kolkata') # Replace with your timezone
|
303 |
+
local_datetime = utc_datetime.astimezone(local_timezone)
|
304 |
+
|
305 |
+
# Format the date and time in the desired format
|
306 |
+
order['formatted_date'] = local_datetime.strftime('%B %d, %I:%M %p')
|
307 |
+
|
308 |
+
order_status = order.get("Order_Status__c", "N/A") # Default to "N/A" if no status
|
309 |
+
order['order_status'] = order_status
|
310 |
+
|
311 |
+
|
312 |
+
return render_template("order_history.html", orders=orders)
|
313 |
+
|
314 |
+
except Exception as e:
|
315 |
+
print(f"Error fetching order history: {str(e)}")
|
316 |
+
return render_template("order_history.html", orders=[], error=str(e))
|
317 |
+
|
318 |
+
|
319 |
+
app.permanent_session_lifetime = timedelta(minutes=5)
|
320 |
+
@app.before_request
|
321 |
+
def check_session_timeout():
|
322 |
+
if "last_activity" in session:
|
323 |
+
last_activity_time = session["last_activity"]
|
324 |
+
now = datetime.now().timestamp()
|
325 |
+
|
326 |
+
# Check if inactivity time has exceeded 5 minutes (300 seconds)
|
327 |
+
if now - last_activity_time > 300:
|
328 |
+
session.clear() # Clear session
|
329 |
+
return redirect(url_for("logout"))
|
330 |
+
|
331 |
+
# Update last activity timestamp on every request
|
332 |
+
session["last_activity"] = datetime.now().timestamp()
|
333 |
+
|
334 |
+
@app.route("/dashboard")
|
335 |
+
def dashboard():
|
336 |
+
return render_template("dashboard.html")
|
337 |
+
@app.route("/logout")
|
338 |
+
def logout():
|
339 |
+
# Retrieve table number before clearing session
|
340 |
+
table_number = session.get('table_number', '')
|
341 |
+
|
342 |
+
# Clear session variables
|
343 |
+
session.pop('name', None)
|
344 |
+
session.pop('email', None)
|
345 |
+
session.pop('rewardPoints', None)
|
346 |
+
session.pop('coupon', None)
|
347 |
+
|
348 |
+
# Pass table number to redirect page
|
349 |
+
return render_template("redirect_page.html", table_number=table_number)
|
350 |
+
|
351 |
+
@app.route("/signup", methods=["GET", "POST"])
|
352 |
+
def signup():
|
353 |
+
if request.method == "POST":
|
354 |
+
name = request.form.get("name")
|
355 |
+
phone = request.form.get("phone")
|
356 |
+
email = request.form.get("email").strip() # Trim spaces
|
357 |
+
password = request.form.get("password")
|
358 |
+
referral_code = request.form.get("referral") # Fetch referral code from the form
|
359 |
+
generated_referral_code = generate_referral_code()
|
360 |
+
|
361 |
+
try:
|
362 |
+
ref = 0 # Default reward points for new user
|
363 |
+
|
364 |
+
# **Fix: Fetch all emails and compare in Python (Case-Insensitive)**
|
365 |
+
email_query = "SELECT Id, Email__c FROM Customer_Login__c"
|
366 |
+
email_result = sf.query(email_query)
|
367 |
+
|
368 |
+
# Convert all stored emails to lowercase and compare with user input
|
369 |
+
existing_emails = {record["Email__c"].lower() for record in email_result["records"]}
|
370 |
+
if email.lower() in existing_emails:
|
371 |
+
return render_template("signup.html", error="Email already in use! Please use a different email.")
|
372 |
+
|
373 |
+
# Check if a referral code is entered
|
374 |
+
if referral_code:
|
375 |
+
referral_query = f"SELECT Id, Email__c, Name FROM Customer_Login__c WHERE Referral__c = '{referral_code}'"
|
376 |
+
referral_result = sf.query(referral_query)
|
377 |
+
|
378 |
+
if not referral_result['records']:
|
379 |
+
return render_template("signup.html", error="Invalid referral code!")
|
380 |
+
|
381 |
+
# Get referrer's details
|
382 |
+
referrer = referral_result['records'][0]
|
383 |
+
referrer_email = referrer.get('Email__c')
|
384 |
+
referrer_name = referrer.get('Name')
|
385 |
+
|
386 |
+
# Generate a new unique coupon code
|
387 |
+
new_coupon_code = generate_coupon_code()
|
388 |
+
|
389 |
+
# Check if referrer already has a record in Referral_Coupon__c
|
390 |
+
existing_coupon_query = f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{referrer_email}'"
|
391 |
+
existing_coupon_result = sf.query(existing_coupon_query)
|
392 |
+
|
393 |
+
if existing_coupon_result['records']:
|
394 |
+
referral_record = existing_coupon_result['records'][0]
|
395 |
+
referral_id = referral_record['Id']
|
396 |
+
existing_coupons = referral_record.get('Coupon_Code__c', '')
|
397 |
+
|
398 |
+
updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()
|
399 |
+
|
400 |
+
# Update the existing record with the new coupon
|
401 |
+
sf.Referral_Coupon__c.update(referral_id, {
|
402 |
+
"Coupon_Code__c": updated_coupons
|
403 |
+
})
|
404 |
+
else:
|
405 |
+
# If no record exists, create a new one
|
406 |
+
sf.Referral_Coupon__c.create({
|
407 |
+
"Name": referrer_name,
|
408 |
+
"Referral_Email__c": referrer_email,
|
409 |
+
"Coupon_Code__c": new_coupon_code
|
410 |
+
})
|
411 |
+
|
412 |
+
# **Fix: Ensure Salesforce enforces unique email constraint**
|
413 |
+
sf.Customer_Login__c.create({
|
414 |
+
"Name": name,
|
415 |
+
"Phone_Number__c": phone,
|
416 |
+
"Email__c": email,
|
417 |
+
"Password__c": password,
|
418 |
+
"Reward_Points__c": ref, # No points added, only coupon is created
|
419 |
+
"Referral__c": generated_referral_code
|
420 |
+
})
|
421 |
+
|
422 |
+
return redirect(url_for("login"))
|
423 |
+
|
424 |
+
except Exception as e:
|
425 |
+
return render_template("signup.html", error=f"Error: {str(e)}")
|
426 |
+
|
427 |
+
return render_template("signup.html")
|
428 |
+
|
429 |
+
|
430 |
+
|
431 |
+
|
432 |
+
@app.route("/login", methods=["GET", "POST"])
|
433 |
+
def login():
|
434 |
+
if request.method == "POST":
|
435 |
+
email = request.form.get("email")
|
436 |
+
password = request.form.get("password")
|
437 |
+
print(f"Login attempt with email: {email}") # Debug log
|
438 |
+
|
439 |
+
try:
|
440 |
+
# Fetch user details from Salesforce
|
441 |
+
query = f"SELECT Id, Name, Email__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
|
442 |
+
result = sf.query(query)
|
443 |
+
|
444 |
+
if result["records"]:
|
445 |
+
user = result["records"][0]
|
446 |
+
session['user_id'] = user['Id']
|
447 |
+
|
448 |
+
# ✅ Always store or update session email
|
449 |
+
if 'user_email' not in session or session['user_email'] != email:
|
450 |
+
session['user_email'] = email
|
451 |
+
session['user_name'] = user.get("Name", "")
|
452 |
+
print(f"✅ Session email updated: {session['user_email']}")
|
453 |
+
|
454 |
+
reward_points = user.get("Reward_Points__c") or 0
|
455 |
+
|
456 |
+
# Coupon generation logic (if reward points >= 500)
|
457 |
+
if reward_points >= 500:
|
458 |
+
new_coupon_code = generate_coupon_code()
|
459 |
+
coupon_query = sf.query(f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'")
|
460 |
+
|
461 |
+
if coupon_query["records"]:
|
462 |
+
coupon_record = coupon_query["records"][0]
|
463 |
+
referral_coupon_id = coupon_record["Id"]
|
464 |
+
existing_coupons = coupon_record.get("Coupon_Code__c", "")
|
465 |
+
|
466 |
+
updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()
|
467 |
+
sf.Referral_Coupon__c.update(referral_coupon_id, {"Coupon_Code__c": updated_coupons})
|
468 |
+
else:
|
469 |
+
sf.Referral_Coupon__c.create({
|
470 |
+
"Referral_Email__c": email,
|
471 |
+
"Name": user.get("Name", ""),
|
472 |
+
"Coupon_Code__c": new_coupon_code
|
473 |
+
})
|
474 |
+
|
475 |
+
new_reward_points = reward_points - 500
|
476 |
+
sf.Customer_Login__c.update(user['Id'], {"Reward_Points__c": new_reward_points})
|
477 |
+
|
478 |
+
return redirect(url_for("menu"))
|
479 |
+
|
480 |
+
else:
|
481 |
+
print("Invalid credentials!")
|
482 |
+
return render_template("login.html", error="Invalid credentials!")
|
483 |
+
|
484 |
+
except Exception as e:
|
485 |
+
print(f"Error during login: {str(e)}")
|
486 |
+
return render_template("login.html", error=f"Error: {str(e)}")
|
487 |
+
|
488 |
+
return render_template("login.html")
|
489 |
+
|
490 |
+
@app.route("/menu", methods=["GET", "POST"])
|
491 |
+
def menu():
|
492 |
+
selected_category = request.args.get("category", "All")
|
493 |
+
user_email = session.get('user_email')
|
494 |
+
|
495 |
+
if not user_email:
|
496 |
+
user_email = request.args.get("email")
|
497 |
+
user_name = request.args.get("name")
|
498 |
+
|
499 |
+
if user_email:
|
500 |
+
session['user_email'] = user_email
|
501 |
+
session['user_name'] = user_name # Store name in session
|
502 |
+
else:
|
503 |
+
return redirect(url_for("login"))
|
504 |
+
else:
|
505 |
+
user_name = session.get('user_name') # Get name from session if it's already stored
|
506 |
+
|
507 |
+
# Get the first letter of the user's name (make it uppercase for consistency)
|
508 |
+
first_letter = user_name[0].upper() if user_name else "A"
|
509 |
+
|
510 |
+
try:
|
511 |
+
# Fetch user referral and reward points
|
512 |
+
user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
|
513 |
+
user_result = sf.query(user_query)
|
514 |
+
|
515 |
+
if not user_result['records']:
|
516 |
+
return redirect(url_for('login'))
|
517 |
+
|
518 |
+
referral_code = user_result['records'][0].get('Referral__c', 'N/A')
|
519 |
+
reward_points = user_result['records'][0].get('Reward_Points__c', 0)
|
520 |
+
|
521 |
+
# Query to fetch Menu_Item__c records including Total_Ordered__c for best sellers
|
522 |
+
menu_query = """
|
523 |
+
SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
|
524 |
+
FROM Menu_Item__c
|
525 |
+
"""
|
526 |
+
result = sf.query(menu_query)
|
527 |
+
food_items = result['records'] if 'records' in result else []
|
528 |
+
|
529 |
+
# Ensure Total_Ordered__c has a valid value
|
530 |
+
for item in food_items:
|
531 |
+
if 'Total_Ordered__c' not in item or item['Total_Ordered__c'] is None:
|
532 |
+
item['Total_Ordered__c'] = 0 # Default value
|
533 |
+
|
534 |
+
# Query to fetch Custom_Dish__c records created within the last 7 days with Total_Ordered__c > 10
|
535 |
+
custom_dish_query = """
|
536 |
+
SELECT Name, Price__c, Description__c, Image1__c, Image2__c, Veg_NonVeg__c, Section__c, Total_Ordered__c
|
537 |
+
FROM Custom_Dish__c
|
538 |
+
WHERE CreatedDate >= LAST_N_DAYS:7
|
539 |
+
"""
|
540 |
+
custom_dish_result = sf.query(custom_dish_query)
|
541 |
+
custom_dishes = custom_dish_result['records'] if 'records' in custom_dish_result else []
|
542 |
+
|
543 |
+
# Merge both Menu_Item__c and Custom_Dish__c records into the ordered menu
|
544 |
+
all_items = food_items + custom_dishes
|
545 |
+
|
546 |
+
# Define the order of sections, adding "Best Sellers" at the top
|
547 |
+
section_order = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]
|
548 |
+
ordered_menu = {section: [] for section in section_order}
|
549 |
+
|
550 |
+
# Sort items by Total_Ordered__c in descending order and pick top 4 as best sellers
|
551 |
+
best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
|
552 |
+
|
553 |
+
if selected_category == "Veg":
|
554 |
+
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
|
555 |
+
elif selected_category == "Non veg":
|
556 |
+
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
|
557 |
+
|
558 |
+
# Take only the top 4 best sellers after filtering
|
559 |
+
best_sellers = best_sellers[:4]
|
560 |
+
|
561 |
+
# Ensure "Best Sellers" is added only if there are items after filtering
|
562 |
+
if best_sellers:
|
563 |
+
ordered_menu["Best Sellers"] = best_sellers
|
564 |
+
|
565 |
+
# Create a set to track item names already added to prevent duplicates
|
566 |
+
added_item_names = set()
|
567 |
+
|
568 |
+
# Filter and organize menu items based on category and section (to avoid duplicates)
|
569 |
+
for item in all_items:
|
570 |
+
section = item.get("Section__c", "Others") # Default to "Others" if missing
|
571 |
+
if section not in ordered_menu:
|
572 |
+
ordered_menu[section] = []
|
573 |
+
|
574 |
+
# Skip item if it's already been added to avoid duplicates
|
575 |
+
if item['Name'] in added_item_names:
|
576 |
+
continue
|
577 |
+
|
578 |
+
# Apply category filters
|
579 |
+
if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
|
580 |
+
continue
|
581 |
+
if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
|
582 |
+
continue
|
583 |
+
|
584 |
+
ordered_menu[section].append(item)
|
585 |
+
added_item_names.add(item['Name']) # Add item to the set of added items
|
586 |
+
print(f"Added item to {section}: {item['Name']}") # Debugging
|
587 |
+
|
588 |
+
# Remove empty sections
|
589 |
+
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
|
590 |
+
print(f"Final ordered menu: {ordered_menu.keys()}") # Debugging
|
591 |
+
|
592 |
+
categories = ["All", "Veg", "Non veg"]
|
593 |
+
|
594 |
+
except Exception as e:
|
595 |
+
print(f"Error fetching menu data: {str(e)}")
|
596 |
+
ordered_menu = {}
|
597 |
+
categories = ["All", "Veg", "Non veg"]
|
598 |
+
referral_code = 'N/A'
|
599 |
+
reward_points = 0
|
600 |
+
|
601 |
+
# Pass the user's first letter (first_letter) to the template
|
602 |
+
return render_template(
|
603 |
+
"menu.html",
|
604 |
+
ordered_menu=ordered_menu,
|
605 |
+
categories=categories,
|
606 |
+
selected_category=selected_category,
|
607 |
+
referral_code=referral_code,
|
608 |
+
reward_points=reward_points,
|
609 |
+
user_name=user_name, # Pass name to the template
|
610 |
+
first_letter=first_letter # Pass first letter to the template
|
611 |
+
)
|
612 |
+
|
613 |
+
|
614 |
+
@app.route("/cart", methods=["GET"])
|
615 |
+
def cart():
|
616 |
+
email = session.get('user_email')
|
617 |
+
if not email:
|
618 |
+
return redirect(url_for("login"))
|
619 |
+
|
620 |
+
try:
|
621 |
+
# Fetch cart items with Category and Section
|
622 |
+
result = sf.query(f"""
|
623 |
+
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c
|
624 |
+
FROM Cart_Item__c
|
625 |
+
WHERE Customer_Email__c = '{email}'
|
626 |
+
""")
|
627 |
+
cart_items = result.get("records", [])
|
628 |
+
|
629 |
+
subtotal = sum(item['Price__c'] for item in cart_items)
|
630 |
+
|
631 |
+
# Fetch reward points
|
632 |
+
customer_result = sf.query(f"""
|
633 |
+
SELECT Reward_Points__c
|
634 |
+
FROM Customer_Login__c
|
635 |
+
WHERE Email__c = '{email}'
|
636 |
+
""")
|
637 |
+
reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
|
638 |
+
|
639 |
+
# Fetch coupons for the user
|
640 |
+
coupon_result = sf.query(f"""
|
641 |
+
SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
642 |
+
""")
|
643 |
+
if coupon_result["records"]:
|
644 |
+
raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
|
645 |
+
coupons = raw_coupons.split("\n") if raw_coupons else []
|
646 |
+
else:
|
647 |
+
coupons = []
|
648 |
+
|
649 |
+
# Initialize suggestions as an empty list
|
650 |
+
suggestions = []
|
651 |
+
|
652 |
+
# If there are items in the cart, fetch suggestions
|
653 |
+
if cart_items:
|
654 |
+
# Get the category and section of the first item in the cart (You can choose which item you want to base suggestions on)
|
655 |
+
first_item = cart_items[0]
|
656 |
+
item_category = first_item.get('Category__c', 'All') # Default to 'All' if not found
|
657 |
+
item_section = first_item.get('Section__c', 'Biryanis') # Default to 'Biryanis' if not found
|
658 |
+
|
659 |
+
# Define section-to-complementary section mapping
|
660 |
+
complementary_sections = {
|
661 |
+
'Breads': ['Curries', 'Biryanis', 'Starters'],
|
662 |
+
'Biryanis': ['Curries', 'Starters', 'Desserts'],
|
663 |
+
'Curries': ['Biryanis', 'Breads', 'Starters'],
|
664 |
+
'Starters': ['Biryanis', 'Curries', 'Desserts'],
|
665 |
+
'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'],
|
666 |
+
'Soft Drinks': ['Starters', 'Biryanis', 'Curries']
|
667 |
+
}
|
668 |
+
|
669 |
+
# Get the complementary sections for the selected section
|
670 |
+
suggested_sections = complementary_sections.get(item_section, [])
|
671 |
+
|
672 |
+
# Fetch suggestions from the complementary sections
|
673 |
+
try:
|
674 |
+
for suggested_section in suggested_sections:
|
675 |
+
if item_category == "All":
|
676 |
+
query = f"""
|
677 |
+
SELECT Name, Price__c, Image1__c
|
678 |
+
FROM Menu_Item__c
|
679 |
+
WHERE Section__c = '{suggested_section}'
|
680 |
+
AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg')
|
681 |
+
LIMIT 4
|
682 |
+
"""
|
683 |
+
else:
|
684 |
+
query = f"""
|
685 |
+
SELECT Name, Price__c, Image1__c
|
686 |
+
FROM Menu_Item__c
|
687 |
+
WHERE Section__c = '{suggested_section}'
|
688 |
+
AND Veg_NonVeg__c = '{item_category}'
|
689 |
+
LIMIT 4
|
690 |
+
"""
|
691 |
+
suggestion_result = sf.query(query)
|
692 |
+
suggestions.extend(suggestion_result.get("records", [])) # Add suggestions from each section
|
693 |
+
|
694 |
+
# Limit the number of suggestions to 4
|
695 |
+
if len(suggestions) > 4:
|
696 |
+
suggestions = suggestions[:4]
|
697 |
+
|
698 |
+
except Exception as e:
|
699 |
+
print(f"Error fetching suggestions: {e}")
|
700 |
+
|
701 |
+
return render_template(
|
702 |
+
"cart.html",
|
703 |
+
cart_items=cart_items,
|
704 |
+
subtotal=subtotal,
|
705 |
+
reward_points=reward_points,
|
706 |
+
customer_email=email,
|
707 |
+
coupons=coupons,
|
708 |
+
suggestions=suggestions
|
709 |
+
)
|
710 |
+
|
711 |
+
except Exception as e:
|
712 |
+
print(f"Error fetching cart items: {e}")
|
713 |
+
return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[])
|
714 |
+
|
715 |
+
|
716 |
+
@app.route("/cart/add_suggestion_to_cart", methods=["POST"])
|
717 |
+
def add_suggestion_to_cart():
|
718 |
+
try:
|
719 |
+
# Get data from the request
|
720 |
+
data = request.get_json()
|
721 |
+
item_name = data.get('item_name').strip()
|
722 |
+
item_price = data.get('item_price')
|
723 |
+
item_image = data.get('item_image')
|
724 |
+
item_id = data.get('item_id')
|
725 |
+
customer_email = data.get('customer_email')
|
726 |
+
addons = data.get('addons', [])
|
727 |
+
instructions = data.get('instructions', "")
|
728 |
+
|
729 |
+
# Default values if addons and instructions are not provided
|
730 |
+
addons_price = 0
|
731 |
+
addons_string = "None"
|
732 |
+
|
733 |
+
# Check if the customer already has this item in their cart
|
734 |
+
query = f"""
|
735 |
+
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
736 |
+
FROM Cart_Item__c
|
737 |
+
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
738 |
+
"""
|
739 |
+
result = sf.query(query)
|
740 |
+
cart_items = result.get("records", [])
|
741 |
+
|
742 |
+
# If item already exists in the cart, update its quantity and other details
|
743 |
+
if cart_items:
|
744 |
+
cart_item_id = cart_items[0]['Id']
|
745 |
+
existing_quantity = cart_items[0]['Quantity__c']
|
746 |
+
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
747 |
+
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
748 |
+
existing_instructions = cart_items[0].get('Instructions__c', "")
|
749 |
+
|
750 |
+
# Combine existing and new addons
|
751 |
+
combined_addons = existing_addons if existing_addons != "None" else ""
|
752 |
+
if addons:
|
753 |
+
combined_addons = f"{combined_addons}; {addons}".strip("; ")
|
754 |
+
|
755 |
+
combined_instructions = existing_instructions
|
756 |
+
if instructions:
|
757 |
+
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
758 |
+
|
759 |
+
combined_addons_list = combined_addons.split("; ")
|
760 |
+
combined_addons_price = sum(
|
761 |
+
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
762 |
+
)
|
763 |
+
|
764 |
+
# Update the cart item
|
765 |
+
sf.Cart_Item__c.update(cart_item_id, {
|
766 |
+
"Quantity__c": existing_quantity + 1,
|
767 |
+
"Add_Ons__c": combined_addons,
|
768 |
+
"Add_Ons_Price__c": combined_addons_price,
|
769 |
+
"Instructions__c": combined_instructions,
|
770 |
+
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
771 |
+
})
|
772 |
+
else:
|
773 |
+
# If item doesn't exist in cart, create a new cart item
|
774 |
+
total_price = float(item_price) + addons_price
|
775 |
+
|
776 |
+
# Create a new cart item in Salesforce
|
777 |
+
sf.Cart_Item__c.create({
|
778 |
+
"Name": item_name,
|
779 |
+
"Price__c": total_price,
|
780 |
+
"Base_Price__c": item_price,
|
781 |
+
"Quantity__c": 1,
|
782 |
+
"Add_Ons_Price__c": addons_price,
|
783 |
+
"Add_Ons__c": addons_string,
|
784 |
+
"Image1__c": item_image,
|
785 |
+
"Customer_Email__c": customer_email,
|
786 |
+
"Instructions__c": instructions
|
787 |
+
})
|
788 |
+
|
789 |
+
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
790 |
+
|
791 |
+
except Exception as e:
|
792 |
+
print(f"Error adding item to cart: {str(e)}")
|
793 |
+
return jsonify({"success": False, "error": str(e)})
|
794 |
+
|
795 |
+
|
796 |
+
@app.route('/cart/add', methods=['POST'])
|
797 |
+
def add_to_cart():
|
798 |
+
try:
|
799 |
+
# Get data from request
|
800 |
+
data = request.json
|
801 |
+
item_name = data.get('itemName', '').strip()
|
802 |
+
item_price = data.get('itemPrice')
|
803 |
+
item_image = data.get('itemImage')
|
804 |
+
addons = data.get('addons', [])
|
805 |
+
instructions = data.get('instructions', '')
|
806 |
+
category = data.get('category')
|
807 |
+
section = data.get('section')
|
808 |
+
quantity = data.get('quantity', 1) # Get the quantity field from the request
|
809 |
+
customer_email = session.get('user_email')
|
810 |
+
|
811 |
+
# Basic validation for required fields
|
812 |
+
if not item_name or not item_price:
|
813 |
+
return jsonify({"success": False, "error": "Item name and price are required."}), 400
|
814 |
+
|
815 |
+
if not customer_email:
|
816 |
+
return jsonify({"success": False, "error": "User email is required."}), 400
|
817 |
+
|
818 |
+
# Query to check if the item is already in the cart
|
819 |
+
query = f"""
|
820 |
+
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
821 |
+
FROM Cart_Item__c
|
822 |
+
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
823 |
+
"""
|
824 |
+
result = sf.query(query)
|
825 |
+
cart_items = result.get("records", [])
|
826 |
+
|
827 |
+
# Calculate the total price for the addons
|
828 |
+
addons_price = sum(addon['price'] for addon in addons)
|
829 |
+
new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
|
830 |
+
|
831 |
+
# If the item is already in the cart, update it
|
832 |
+
if cart_items:
|
833 |
+
cart_item_id = cart_items[0]['Id']
|
834 |
+
existing_quantity = cart_items[0]['Quantity__c']
|
835 |
+
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
836 |
+
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
837 |
+
existing_instructions = cart_items[0].get('Instructions__c', "")
|
838 |
+
|
839 |
+
# Combine the new addons with the existing ones
|
840 |
+
combined_addons = existing_addons if existing_addons != "None" else ""
|
841 |
+
if new_addons:
|
842 |
+
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
|
843 |
+
|
844 |
+
# Combine existing instructions with new instructions
|
845 |
+
combined_instructions = existing_instructions
|
846 |
+
if instructions:
|
847 |
+
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
848 |
+
|
849 |
+
# Calculate total addons price
|
850 |
+
combined_addons_list = combined_addons.split("; ")
|
851 |
+
combined_addons_price = sum(
|
852 |
+
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
853 |
+
)
|
854 |
+
|
855 |
+
# Update the cart item in Salesforce (updating quantity)
|
856 |
+
sf.Cart_Item__c.update(cart_item_id, {
|
857 |
+
"Quantity__c": existing_quantity + quantity, # Add the selected quantity
|
858 |
+
"Add_Ons__c": combined_addons,
|
859 |
+
"Add_Ons_Price__c": combined_addons_price,
|
860 |
+
"Instructions__c": combined_instructions,
|
861 |
+
"Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
|
862 |
+
"Category__c": category,
|
863 |
+
"Section__c": section
|
864 |
+
})
|
865 |
+
else:
|
866 |
+
# If the item is not already in the cart, create a new entry
|
867 |
+
addons_string = "None"
|
868 |
+
if addons:
|
869 |
+
addons_string = new_addons
|
870 |
+
|
871 |
+
total_price = item_price * quantity + addons_price # Multiply by the quantity
|
872 |
+
|
873 |
+
# Create new cart item in Salesforce
|
874 |
+
sf.Cart_Item__c.create({
|
875 |
+
"Name": item_name,
|
876 |
+
"Price__c": total_price,
|
877 |
+
"Base_Price__c": item_price,
|
878 |
+
"Quantity__c": quantity, # Use the selected quantity
|
879 |
+
"Add_Ons_Price__c": addons_price,
|
880 |
+
"Add_Ons__c": addons_string,
|
881 |
+
"Image1__c": item_image,
|
882 |
+
"Customer_Email__c": customer_email,
|
883 |
+
"Instructions__c": instructions,
|
884 |
+
"Category__c": category,
|
885 |
+
"Section__c": section
|
886 |
+
})
|
887 |
+
|
888 |
+
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
889 |
+
|
890 |
+
except KeyError as e:
|
891 |
+
# Handle missing expected keys in request data
|
892 |
+
return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
|
893 |
+
|
894 |
+
except Exception as e:
|
895 |
+
# Log the error for debugging and return a general error message
|
896 |
+
print(f"Error adding item to cart: {str(e)}")
|
897 |
+
return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
|
898 |
+
|
899 |
+
|
900 |
+
@app.route("/cart/add_item", methods=["POST"])
|
901 |
+
def add_item_to_cart():
|
902 |
+
data = request.json # Extract JSON data from the request
|
903 |
+
email = data.get('email') # Customer email
|
904 |
+
item_name = data.get('item_name') # Item name
|
905 |
+
quantity = data.get('quantity', 1) # Quantity to add (default is 1)
|
906 |
+
addons = data.get('addons', []) # Add-ons for the item (optional)
|
907 |
+
|
908 |
+
# Validate inputs
|
909 |
+
if not email or not item_name:
|
910 |
+
return jsonify({"success": False, "error": "Email and item name are required."}), 400
|
911 |
+
|
912 |
+
try:
|
913 |
+
# Add a new item to the cart with the provided details
|
914 |
+
sf.Cart_Item__c.create({
|
915 |
+
"Customer_Email__c": email, # Associate the cart item with the customer's email
|
916 |
+
"Item_Name__c": item_name, # Item name
|
917 |
+
"Quantity__c": quantity, # Quantity to add
|
918 |
+
"Add_Ons__c": addons_string
|
919 |
+
})
|
920 |
+
|
921 |
+
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
922 |
+
except Exception as e:
|
923 |
+
print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
|
924 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
925 |
+
|
926 |
+
|
927 |
+
|
928 |
+
@app.route('/cart/remove/<item_name>', methods=['POST'])
|
929 |
+
def remove_cart_item(item_name):
|
930 |
+
try:
|
931 |
+
customer_email = session.get('user_email')
|
932 |
+
if not customer_email:
|
933 |
+
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
|
934 |
+
query = f"""
|
935 |
+
SELECT Id FROM Cart_Item__c
|
936 |
+
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
937 |
+
"""
|
938 |
+
result = sf.query(query)
|
939 |
+
if result['totalSize'] == 0:
|
940 |
+
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
941 |
+
cart_item_id = result['records'][0]['Id']
|
942 |
+
sf.Cart_Item__c.delete(cart_item_id)
|
943 |
+
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
944 |
+
except Exception as e:
|
945 |
+
print(f"Error: {str(e)}")
|
946 |
+
return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
|
947 |
+
|
948 |
+
@app.route('/api/addons', methods=['GET'])
|
949 |
+
def get_addons():
|
950 |
+
item_name = request.args.get('item_name')
|
951 |
+
item_section = request.args.get('item_section')
|
952 |
+
|
953 |
+
# Check if both item_name and item_section are provided
|
954 |
+
if not item_name or not item_section:
|
955 |
+
return jsonify({"success": False, "error": "Item name and section are required."}), 400
|
956 |
+
|
957 |
+
try:
|
958 |
+
# Fetch customization options from Salesforce based on the section
|
959 |
+
query = f"""
|
960 |
+
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
|
961 |
+
FROM Customization_Options__c
|
962 |
+
WHERE Section__c = '{item_section}'
|
963 |
+
"""
|
964 |
+
result = sf.query(query)
|
965 |
+
addons = result.get('records', [])
|
966 |
+
|
967 |
+
# Check if we found any addons
|
968 |
+
if not addons:
|
969 |
+
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
|
970 |
+
|
971 |
+
# Format data for frontend
|
972 |
+
formatted_addons = []
|
973 |
+
for addon in addons:
|
974 |
+
# Ensure 'Options__c' exists and is not None
|
975 |
+
options = addon.get("Options__c", "")
|
976 |
+
if options: # If options are available, split them
|
977 |
+
options = options.split(", ") # Convert comma-separated options into a list
|
978 |
+
else:
|
979 |
+
options = [] # If no options, default to an empty list
|
980 |
+
|
981 |
+
formatted_addons.append({
|
982 |
+
"name": addon["Name"],
|
983 |
+
"type": addon["Customization_Type__c"],
|
984 |
+
"options": options,
|
985 |
+
"max_selections": addon.get("Max_Selections__c", 1),
|
986 |
+
"extra_charge": addon.get("Extra_Charge__c", False),
|
987 |
+
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
|
988 |
+
})
|
989 |
+
|
990 |
+
return jsonify({"success": True, "addons": formatted_addons})
|
991 |
+
|
992 |
+
except Exception as e:
|
993 |
+
# Log the exception for debugging
|
994 |
+
app.logger.error(f"Error fetching addons: {str(e)}")
|
995 |
+
return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
|
996 |
+
|
997 |
+
|
998 |
+
@app.route("/cart/update_quantity", methods=["POST"])
|
999 |
+
def update_quantity():
|
1000 |
+
data = request.json # Extract JSON data from the request
|
1001 |
+
email = data.get('email')
|
1002 |
+
item_name = data.get('item_name')
|
1003 |
+
try:
|
1004 |
+
# Convert quantity to an integer
|
1005 |
+
quantity = int(data.get('quantity'))
|
1006 |
+
except (ValueError, TypeError):
|
1007 |
+
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
|
1008 |
+
|
1009 |
+
# Validate inputs
|
1010 |
+
if not email or not item_name or quantity is None:
|
1011 |
+
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
|
1012 |
+
|
1013 |
+
try:
|
1014 |
+
# Query the cart item in Salesforce
|
1015 |
+
cart_items = sf.query(
|
1016 |
+
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
|
1017 |
+
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
|
1018 |
+
)['records']
|
1019 |
+
|
1020 |
+
if not cart_items:
|
1021 |
+
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
1022 |
+
|
1023 |
+
# Retrieve the first matching record
|
1024 |
+
cart_item_id = cart_items[0]['Id']
|
1025 |
+
base_price = cart_items[0]['Base_Price__c']
|
1026 |
+
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
1027 |
+
|
1028 |
+
# Calculate the new item price
|
1029 |
+
new_item_price = (base_price * quantity) + addons_price
|
1030 |
+
|
1031 |
+
# Update the record in Salesforce
|
1032 |
+
sf.Cart_Item__c.update(cart_item_id, {
|
1033 |
+
"Quantity__c": quantity,
|
1034 |
+
"Price__c": new_item_price, # Update base price
|
1035 |
+
})
|
1036 |
+
|
1037 |
+
# Recalculate the subtotal for all items in the cart
|
1038 |
+
cart_items = sf.query(f"""
|
1039 |
+
SELECT Price__c, Add_Ons_Price__c
|
1040 |
+
FROM Cart_Item__c
|
1041 |
+
WHERE Customer_Email__c = '{email}'
|
1042 |
+
""")['records']
|
1043 |
+
new_subtotal = sum(item['Price__c'] for item in cart_items)
|
1044 |
+
|
1045 |
+
# Return updated item price and subtotal
|
1046 |
+
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
1047 |
+
print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
|
1048 |
+
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
1049 |
+
|
1050 |
+
except Exception as e:
|
1051 |
+
print(f"Error updating quantity: {str(e)}")
|
1052 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
1053 |
+
|
1054 |
+
@app.route("/checkout", methods=["POST"])
|
1055 |
+
def checkout():
|
1056 |
+
email = session.get('user_email')
|
1057 |
+
user_id = session.get('user_name')
|
1058 |
+
table_number = session.get('table_number') # Retrieve table number
|
1059 |
+
|
1060 |
+
print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}") # Debugging session data
|
1061 |
+
|
1062 |
+
if not email or not user_id:
|
1063 |
+
print("User not logged in")
|
1064 |
+
return jsonify({"success": False, "message": "User not logged in"})
|
1065 |
+
|
1066 |
+
try:
|
1067 |
+
# Fetch the selected coupon (if any)
|
1068 |
+
data = request.json
|
1069 |
+
selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None
|
1070 |
+
# Now selected_coupon will be None if it's not provided or empty, or a valid string otherwise
|
1071 |
+
print(f"Selected Coupon: {selected_coupon}") # Debugging selected coupon
|
1072 |
+
|
1073 |
+
# Fetch cart items for the current user
|
1074 |
+
result = sf.query(f"""
|
1075 |
+
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
1076 |
+
FROM Cart_Item__c
|
1077 |
+
WHERE Customer_Email__c = '{email}'
|
1078 |
+
""")
|
1079 |
+
|
1080 |
+
# Log the cart items to see if they are fetched correctly
|
1081 |
+
cart_items = result.get("records", [])
|
1082 |
+
print(f"Cart Items Retrieved: {cart_items}") # Debugging log
|
1083 |
+
|
1084 |
+
if not cart_items:
|
1085 |
+
print("Cart is empty")
|
1086 |
+
return jsonify({"success": False, "message": "Cart is empty"})
|
1087 |
+
|
1088 |
+
total_price = sum(item['Price__c'] for item in cart_items)
|
1089 |
+
print(f"Total Price: {total_price}") # Debugging total price calculation
|
1090 |
+
|
1091 |
+
discount = 0
|
1092 |
+
|
1093 |
+
# Fetch the user's existing coupons
|
1094 |
+
coupon_query = sf.query(f"""
|
1095 |
+
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
1096 |
+
""")
|
1097 |
+
print(f"Coupon Query Results: {coupon_query}") # Debugging coupon query results
|
1098 |
+
|
1099 |
+
has_coupons = bool(coupon_query["records"])
|
1100 |
+
print(f"Has Coupons: {has_coupons}") # Debugging coupon presence check
|
1101 |
+
|
1102 |
+
if selected_coupon:
|
1103 |
+
# Apply 10% discount if a valid coupon is selected
|
1104 |
+
discount = total_price * 0.10 # Example: 10% discount
|
1105 |
+
print(f"Discount Applied: {discount}") # Debugging discount calculation
|
1106 |
+
|
1107 |
+
referral_coupon_id = coupon_query["records"][0]["Id"]
|
1108 |
+
print(f"Referral Coupon ID: {referral_coupon_id}") # Debugging referral coupon ID
|
1109 |
+
|
1110 |
+
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
|
1111 |
+
print(f"Existing Coupons Before Removal: {existing_coupons}") # Debugging existing coupons
|
1112 |
+
|
1113 |
+
# Remove the selected coupon from the list of existing coupons
|
1114 |
+
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
|
1115 |
+
updated_coupons_str = "\n".join(updated_coupons).strip()
|
1116 |
+
|
1117 |
+
print(f"Updated Coupons After Removal: {updated_coupons}") # Debugging updated coupons
|
1118 |
+
|
1119 |
+
# If no coupons remain, set the field to None (not empty string)
|
1120 |
+
if not updated_coupons:
|
1121 |
+
updated_coupons_str = None # Set to None if no coupons are left
|
1122 |
+
print("No Coupons Remaining. Setting to None") # Debugging no coupons left
|
1123 |
+
|
1124 |
+
# Update the Referral_Coupon__c record
|
1125 |
+
print(f"Updating Referral Coupon: {updated_coupons_str}") # Debugging update to Salesforce
|
1126 |
+
sf.Referral_Coupon__c.update(referral_coupon_id, {
|
1127 |
+
"Coupon_Code__c": updated_coupons_str
|
1128 |
+
})
|
1129 |
+
else:
|
1130 |
+
# If no coupon is selected, add reward points
|
1131 |
+
reward_points_to_add = total_price * 0.10 # Example: 10% reward points
|
1132 |
+
print(f"Reward Points to Add: {reward_points_to_add}") # Debugging reward points
|
1133 |
+
|
1134 |
+
# Fetch current reward points
|
1135 |
+
customer_record = sf.query(f"""
|
1136 |
+
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
1137 |
+
WHERE Email__c = '{email}'
|
1138 |
+
""")
|
1139 |
+
print(f"Customer Reward Points Query: {customer_record}") # Debugging customer reward points query
|
1140 |
+
|
1141 |
+
customer = customer_record.get("records", [])[0] if customer_record else None
|
1142 |
+
if customer:
|
1143 |
+
current_reward_points = customer.get("Reward_Points__c") or 0
|
1144 |
+
print(f"Current Reward Points: {current_reward_points}") # Debugging current reward points
|
1145 |
+
new_reward_points = current_reward_points + reward_points_to_add
|
1146 |
+
print(f"New Reward Points: {new_reward_points}") # Debugging new reward points calculation
|
1147 |
+
|
1148 |
+
# Update reward points
|
1149 |
+
sf.Customer_Login__c.update(customer["Id"], {
|
1150 |
+
"Reward_Points__c": new_reward_points
|
1151 |
+
})
|
1152 |
+
|
1153 |
+
# Final total bill calculation
|
1154 |
+
total_bill = total_price - discount
|
1155 |
+
print(f"Total Bill After Discount: {total_bill}") # Debugging final total bill
|
1156 |
+
|
1157 |
+
# Store all order details (before deleting cart items)
|
1158 |
+
order_details = "\n".join(
|
1159 |
+
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
|
1160 |
+
f"Instructions: {item.get('Instructions__c', 'None')} | "
|
1161 |
+
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
|
1162 |
+
for item in cart_items
|
1163 |
+
)
|
1164 |
+
print(f"Order Details: {order_details}") # Debugging order details
|
1165 |
+
|
1166 |
+
# Fetch Customer ID from Customer_Login__c
|
1167 |
+
customer_query = sf.query(f"""
|
1168 |
+
SELECT Id FROM Customer_Login__c
|
1169 |
+
WHERE Email__c = '{email}'
|
1170 |
+
""")
|
1171 |
+
|
1172 |
+
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
1173 |
+
print(f"Customer ID: {customer_id}") # Debugging customer ID retrieval
|
1174 |
+
|
1175 |
+
if not customer_id:
|
1176 |
+
print("Customer record not found")
|
1177 |
+
return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
|
1178 |
+
table_number = table_number if table_number != 'null' else None # Ensure 'null' string is replaced with None
|
1179 |
+
# Store order data
|
1180 |
+
order_data = {
|
1181 |
+
"Customer_Name__c": user_id,
|
1182 |
+
"Customer_Email__c": email,
|
1183 |
+
"Total_Amount__c": total_price,
|
1184 |
+
"Discount__c": discount,
|
1185 |
+
"Total_Bill__c": total_bill,
|
1186 |
+
"Order_Status__c": "Pending",
|
1187 |
+
"Customer2__c": customer_id,
|
1188 |
+
"Order_Details__c": order_details,
|
1189 |
+
"Table_Number__c": table_number # Store table number
|
1190 |
+
}
|
1191 |
+
print(f"Order Data: {order_data}") # Debugging order data
|
1192 |
+
|
1193 |
+
# Create the order in Salesforce
|
1194 |
+
order_response = sf.Order__c.create(order_data)
|
1195 |
+
print(f"Order Response: {order_response}") # Debugging order creation response
|
1196 |
+
|
1197 |
+
# Ensure the order was created successfully before deleting cart items
|
1198 |
+
if order_response:
|
1199 |
+
# Only delete cart items after the order is created
|
1200 |
+
for item in cart_items:
|
1201 |
+
print(f"Deleting Cart Item: {item['Id']}") # Debugging cart item deletion
|
1202 |
+
sf.Cart_Item__c.delete(item["Id"])
|
1203 |
+
|
1204 |
+
return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill})
|
1205 |
+
|
1206 |
+
except Exception as e:
|
1207 |
+
print(f"Error during checkout: {str(e)}") # Debugging error message
|
1208 |
+
return jsonify({"success": False, "error": str(e)})
|
1209 |
+
|
1210 |
+
|
1211 |
+
@app.route("/order", methods=["GET"])
|
1212 |
+
def order_summary():
|
1213 |
+
email = session.get('user_email') # Fetch logged-in user's email
|
1214 |
+
if not email:
|
1215 |
+
return redirect(url_for("login"))
|
1216 |
+
|
1217 |
+
try:
|
1218 |
+
# Fetch the most recent order for the user
|
1219 |
+
result = sf.query(f"""
|
1220 |
+
SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
|
1221 |
+
FROM Order__c
|
1222 |
+
WHERE Customer_Email__c = '{email}'
|
1223 |
+
ORDER BY CreatedDate DESC
|
1224 |
+
LIMIT 1
|
1225 |
+
""")
|
1226 |
+
order = result.get("records", [])[0] if result.get("records") else None
|
1227 |
+
|
1228 |
+
if not order:
|
1229 |
+
return render_template("order.html", order=None)
|
1230 |
+
|
1231 |
+
return render_template("order.html", order=order)
|
1232 |
+
except Exception as e:
|
1233 |
+
print(f"Error fetching order details: {str(e)}")
|
1234 |
+
return render_template("order.html", order=None, error=str(e))
|
1235 |
+
import smtplib
|
1236 |
+
from email.mime.multipart import MIMEMultipart
|
1237 |
+
from email.mime.text import MIMEText
|
1238 |
+
|
1239 |
+
|
1240 |
+
|
1241 |
+
|
1242 |
+
if __name__ == "__main__":
|
1243 |
+
app.run(debug=True, host="0.0.0.0", port=7860)
|