Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,10 +2,14 @@ from flask import Flask, render_template, request, jsonify, redirect, url_for, s
|
|
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 Menu_page import menu_page # Now you can import the Blueprint after app is initialized
|
6 |
from datetime import timedelta
|
7 |
import os
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
|
11 |
# Initialize Flask app and Salesforce connection
|
@@ -18,17 +22,11 @@ sf = get_salesforce_connection()
|
|
18 |
print("Salesforce connection established.")
|
19 |
|
20 |
# Set the secret key to handle sessions securely
|
21 |
-
app.secret_key = os.getenv("SECRET_KEY", "
|
22 |
|
23 |
-
|
24 |
-
app.
|
25 |
-
|
26 |
-
|
27 |
-
# Configure the session type
|
28 |
-
app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
|
29 |
-
#app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
|
30 |
-
app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
|
31 |
-
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
|
32 |
|
33 |
# Initialize the session
|
34 |
Session(app) # Correctly initialize the Session object
|
@@ -61,7 +59,7 @@ def home():
|
|
61 |
|
62 |
# Ensure session is saved before redirecting
|
63 |
session.modified = True
|
64 |
-
return redirect(url_for("
|
65 |
|
66 |
return render_template("index.html")
|
67 |
|
@@ -169,97 +167,94 @@ def generate_custom_dish():
|
|
169 |
except Exception as e:
|
170 |
return jsonify({"success": False, "error": str(e)}), 500
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
def edit_profile():
|
175 |
email = session.get('user_email') # Get logged-in user's email
|
176 |
if not email:
|
177 |
return redirect(url_for("login"))
|
178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
try:
|
180 |
# Fetch user details from Salesforce
|
181 |
result = sf.query(f"""
|
182 |
-
SELECT Id, Name, Email__c, Phone_Number__c,
|
183 |
FROM Customer_Login__c
|
184 |
WHERE Email__c = '{email}'
|
185 |
""")
|
186 |
|
187 |
if not result['records']:
|
188 |
-
return
|
189 |
|
190 |
user = result['records'][0]
|
191 |
user_id = user.get("Id")
|
192 |
-
user_name = user.get("Name")
|
193 |
-
user_phone = user.get("Phone_Number__c")
|
194 |
-
user_email = user.get("Email__c")
|
195 |
|
196 |
-
|
197 |
-
|
198 |
-
return jsonify({"success": False, "message": "Error fetching user data"})
|
199 |
-
|
200 |
-
try:
|
201 |
-
# Process user profile update
|
202 |
-
new_name = request.form.get('name')
|
203 |
new_email = request.form.get('email')
|
204 |
new_phone = request.form.get('phone')
|
205 |
-
|
|
|
206 |
|
|
|
207 |
update_data = {
|
208 |
'Name': new_name,
|
209 |
'Email__c': new_email,
|
210 |
-
'Phone_Number__c': new_phone
|
|
|
|
|
211 |
}
|
212 |
|
213 |
-
if new_password:
|
214 |
-
update_data['Password__c'] = new_password
|
215 |
-
|
216 |
# Update Salesforce record
|
217 |
sf.Customer_Login__c.update(user_id, update_data)
|
218 |
|
219 |
-
return
|
|
|
|
|
|
|
|
|
220 |
|
221 |
except Exception as e:
|
222 |
-
return
|
223 |
|
224 |
-
import re
|
225 |
-
@app.route("/customer_details", methods=["GET"])
|
226 |
-
def customer_details():
|
227 |
-
email = session.get('user_email') # Get logged-in user's email
|
228 |
|
229 |
-
if not email:
|
230 |
-
return redirect(url_for("login")) # If no email is found, redirect to login
|
231 |
|
232 |
-
|
233 |
-
|
234 |
-
customer_record = sf.query(f"""
|
235 |
-
SELECT Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
|
236 |
-
FROM Customer_Login__c
|
237 |
-
WHERE Email__c = '{email}'
|
238 |
-
LIMIT 1
|
239 |
-
""")
|
240 |
-
|
241 |
-
# If no customer record found, handle it
|
242 |
-
if not customer_record.get("records"):
|
243 |
-
return jsonify({"success": False, "message": "Customer not found in Salesforce"})
|
244 |
-
|
245 |
-
# Get the customer details
|
246 |
-
customer = customer_record["records"][0]
|
247 |
-
|
248 |
-
# Prepare the data to return to the frontend
|
249 |
-
customer_data = {
|
250 |
-
"name": customer.get("Name", ""),
|
251 |
-
"email": customer.get("Email__c", ""),
|
252 |
-
"phone": customer.get("Phone_Number__c", ""),
|
253 |
-
"referral_code": customer.get("Referral__c", ""),
|
254 |
-
"reward_points": customer.get("Reward_Points__c", 0)
|
255 |
-
}
|
256 |
-
|
257 |
-
# Return the customer details as JSON response
|
258 |
-
return render_template("customer_details.html", customer=customer_data)
|
259 |
-
|
260 |
-
except Exception as e:
|
261 |
-
print(f"Error fetching customer details: {str(e)}")
|
262 |
-
return jsonify({"success": False, "message": f"Error fetching customer details: {str(e)}"})
|
263 |
|
264 |
@app.route("/order-history", methods=["GET"])
|
265 |
def order_history():
|
@@ -277,25 +272,55 @@ def order_history():
|
|
277 |
ORDER BY CreatedDate DESC
|
278 |
""")
|
279 |
|
|
|
|
|
280 |
orders = result.get("records", []) # Fetch all orders
|
281 |
|
282 |
-
|
|
|
|
|
|
|
283 |
for order in orders:
|
284 |
order_details = order.get("Order_Details__c", "")
|
285 |
-
#
|
286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
|
288 |
-
|
289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
290 |
|
291 |
-
# Update the order details with the cleaned and formatted details
|
292 |
-
order['Order_Details__c'] = cleaned_details
|
293 |
|
294 |
return render_template("order_history.html", orders=orders)
|
295 |
|
296 |
except Exception as e:
|
297 |
print(f"Error fetching order history: {str(e)}")
|
298 |
return render_template("order_history.html", orders=[], error=str(e))
|
|
|
|
|
299 |
app.permanent_session_lifetime = timedelta(minutes=5)
|
300 |
@app.before_request
|
301 |
def check_session_timeout():
|
@@ -406,6 +431,9 @@ def signup():
|
|
406 |
|
407 |
return render_template("signup.html")
|
408 |
|
|
|
|
|
|
|
409 |
@app.route("/login", methods=["GET", "POST"])
|
410 |
def login():
|
411 |
if request.method == "POST":
|
@@ -452,7 +480,7 @@ def login():
|
|
452 |
new_reward_points = reward_points - 500
|
453 |
sf.Customer_Login__c.update(user['Id'], {"Reward_Points__c": new_reward_points})
|
454 |
|
455 |
-
return redirect(url_for("
|
456 |
|
457 |
else:
|
458 |
print("Invalid credentials!")
|
@@ -463,584 +491,11 @@ def login():
|
|
463 |
return render_template("login.html", error=f"Error: {str(e)}")
|
464 |
|
465 |
return render_template("login.html")
|
|
|
|
|
|
|
466 |
|
467 |
-
|
468 |
-
@app.route("/cart", methods=["GET"])
|
469 |
-
def cart():
|
470 |
-
email = session.get('user_email')
|
471 |
-
if not email:
|
472 |
-
return redirect(url_for("login"))
|
473 |
-
|
474 |
-
try:
|
475 |
-
# Fetch cart items with Category and Section
|
476 |
-
result = sf.query(f"""
|
477 |
-
SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c
|
478 |
-
FROM Cart_Item__c
|
479 |
-
WHERE Customer_Email__c = '{email}'
|
480 |
-
""")
|
481 |
-
cart_items = result.get("records", [])
|
482 |
-
|
483 |
-
subtotal = sum(item['Price__c'] for item in cart_items)
|
484 |
-
|
485 |
-
# Fetch reward points
|
486 |
-
customer_result = sf.query(f"""
|
487 |
-
SELECT Reward_Points__c
|
488 |
-
FROM Customer_Login__c
|
489 |
-
WHERE Email__c = '{email}'
|
490 |
-
""")
|
491 |
-
reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0
|
492 |
-
|
493 |
-
# Fetch coupons for the user
|
494 |
-
coupon_result = sf.query(f"""
|
495 |
-
SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
496 |
-
""")
|
497 |
-
if coupon_result["records"]:
|
498 |
-
raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "")
|
499 |
-
coupons = raw_coupons.split("\n") if raw_coupons else []
|
500 |
-
else:
|
501 |
-
coupons = []
|
502 |
-
|
503 |
-
# Initialize suggestions as an empty list
|
504 |
-
suggestions = []
|
505 |
-
|
506 |
-
# If there are items in the cart, fetch suggestions
|
507 |
-
if cart_items:
|
508 |
-
# Get the category and section of the first item in the cart (You can choose which item you want to base suggestions on)
|
509 |
-
first_item = cart_items[0]
|
510 |
-
item_category = first_item.get('Category__c', 'All') # Default to 'All' if not found
|
511 |
-
item_section = first_item.get('Section__c', 'Biryanis') # Default to 'Biryanis' if not found
|
512 |
-
|
513 |
-
# Define section-to-complementary section mapping
|
514 |
-
complementary_sections = {
|
515 |
-
'Breads': ['Curries', 'Biryanis', 'Starters'],
|
516 |
-
'Biryanis': ['Curries', 'Starters', 'Desserts'],
|
517 |
-
'Curries': ['Biryanis', 'Breads', 'Starters'],
|
518 |
-
'Starters': ['Biryanis', 'Curries', 'Desserts'],
|
519 |
-
'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'],
|
520 |
-
'Soft Drinks': ['Starters', 'Biryanis', 'Curries']
|
521 |
-
}
|
522 |
-
|
523 |
-
# Get the complementary sections for the selected section
|
524 |
-
suggested_sections = complementary_sections.get(item_section, [])
|
525 |
-
|
526 |
-
# Fetch suggestions from the complementary sections
|
527 |
-
try:
|
528 |
-
for suggested_section in suggested_sections:
|
529 |
-
if item_category == "All":
|
530 |
-
query = f"""
|
531 |
-
SELECT Name, Price__c, Image1__c
|
532 |
-
FROM Menu_Item__c
|
533 |
-
WHERE Section__c = '{suggested_section}'
|
534 |
-
AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg')
|
535 |
-
LIMIT 4
|
536 |
-
"""
|
537 |
-
else:
|
538 |
-
query = f"""
|
539 |
-
SELECT Name, Price__c, Image1__c
|
540 |
-
FROM Menu_Item__c
|
541 |
-
WHERE Section__c = '{suggested_section}'
|
542 |
-
AND Veg_NonVeg__c = '{item_category}'
|
543 |
-
LIMIT 4
|
544 |
-
"""
|
545 |
-
suggestion_result = sf.query(query)
|
546 |
-
suggestions.extend(suggestion_result.get("records", [])) # Add suggestions from each section
|
547 |
-
|
548 |
-
# Limit the number of suggestions to 4
|
549 |
-
if len(suggestions) > 4:
|
550 |
-
suggestions = suggestions[:4]
|
551 |
-
|
552 |
-
except Exception as e:
|
553 |
-
print(f"Error fetching suggestions: {e}")
|
554 |
-
|
555 |
-
return render_template(
|
556 |
-
"cart.html",
|
557 |
-
cart_items=cart_items,
|
558 |
-
subtotal=subtotal,
|
559 |
-
reward_points=reward_points,
|
560 |
-
customer_email=email,
|
561 |
-
coupons=coupons,
|
562 |
-
suggestions=suggestions
|
563 |
-
)
|
564 |
-
|
565 |
-
except Exception as e:
|
566 |
-
print(f"Error fetching cart items: {e}")
|
567 |
-
return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[])
|
568 |
-
|
569 |
-
@app.route('/cart/add', methods=['POST'])
|
570 |
-
def add_to_cart():
|
571 |
-
try:
|
572 |
-
# Get data from request
|
573 |
-
data = request.json
|
574 |
-
item_name = data.get('itemName', '').strip()
|
575 |
-
item_price = data.get('itemPrice')
|
576 |
-
item_image = data.get('itemImage')
|
577 |
-
addons = data.get('addons', [])
|
578 |
-
instructions = data.get('instructions', '')
|
579 |
-
category = data.get('category')
|
580 |
-
section = data.get('section')
|
581 |
-
quantity = data.get('quantity', 1) # Get the quantity field from the request
|
582 |
-
customer_email = session.get('user_email')
|
583 |
-
|
584 |
-
# Basic validation for required fields
|
585 |
-
if not item_name or not item_price:
|
586 |
-
return jsonify({"success": False, "error": "Item name and price are required."}), 400
|
587 |
-
|
588 |
-
if not customer_email:
|
589 |
-
return jsonify({"success": False, "error": "User email is required."}), 400
|
590 |
-
|
591 |
-
# Query to check if the item is already in the cart
|
592 |
-
query = f"""
|
593 |
-
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
594 |
-
FROM Cart_Item__c
|
595 |
-
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
596 |
-
"""
|
597 |
-
result = sf.query(query)
|
598 |
-
cart_items = result.get("records", [])
|
599 |
-
|
600 |
-
# Calculate the total price for the addons
|
601 |
-
addons_price = sum(addon['price'] for addon in addons)
|
602 |
-
new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])
|
603 |
-
|
604 |
-
# If the item is already in the cart, update it
|
605 |
-
if cart_items:
|
606 |
-
cart_item_id = cart_items[0]['Id']
|
607 |
-
existing_quantity = cart_items[0]['Quantity__c']
|
608 |
-
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
609 |
-
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
610 |
-
existing_instructions = cart_items[0].get('Instructions__c', "")
|
611 |
-
|
612 |
-
# Combine the new addons with the existing ones
|
613 |
-
combined_addons = existing_addons if existing_addons != "None" else ""
|
614 |
-
if new_addons:
|
615 |
-
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
|
616 |
-
|
617 |
-
# Combine existing instructions with new instructions
|
618 |
-
combined_instructions = existing_instructions
|
619 |
-
if instructions:
|
620 |
-
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
621 |
-
|
622 |
-
# Calculate total addons price
|
623 |
-
combined_addons_list = combined_addons.split("; ")
|
624 |
-
combined_addons_price = sum(
|
625 |
-
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
626 |
-
)
|
627 |
-
|
628 |
-
# Update the cart item in Salesforce (updating quantity)
|
629 |
-
sf.Cart_Item__c.update(cart_item_id, {
|
630 |
-
"Quantity__c": existing_quantity + quantity, # Add the selected quantity
|
631 |
-
"Add_Ons__c": combined_addons,
|
632 |
-
"Add_Ons_Price__c": combined_addons_price,
|
633 |
-
"Instructions__c": combined_instructions,
|
634 |
-
"Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
|
635 |
-
"Category__c": category,
|
636 |
-
"Section__c": section
|
637 |
-
})
|
638 |
-
else:
|
639 |
-
# If the item is not already in the cart, create a new entry
|
640 |
-
addons_string = "None"
|
641 |
-
if addons:
|
642 |
-
addons_string = new_addons
|
643 |
-
|
644 |
-
total_price = item_price * quantity + addons_price # Multiply by the quantity
|
645 |
-
|
646 |
-
# Create new cart item in Salesforce
|
647 |
-
sf.Cart_Item__c.create({
|
648 |
-
"Name": item_name,
|
649 |
-
"Price__c": total_price,
|
650 |
-
"Base_Price__c": item_price,
|
651 |
-
"Quantity__c": quantity, # Use the selected quantity
|
652 |
-
"Add_Ons_Price__c": addons_price,
|
653 |
-
"Add_Ons__c": addons_string,
|
654 |
-
"Image1__c": item_image,
|
655 |
-
"Customer_Email__c": customer_email,
|
656 |
-
"Instructions__c": instructions,
|
657 |
-
"Category__c": category,
|
658 |
-
"Section__c": section
|
659 |
-
})
|
660 |
-
|
661 |
-
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
662 |
-
|
663 |
-
except KeyError as e:
|
664 |
-
# Handle missing expected keys in request data
|
665 |
-
return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
|
666 |
-
|
667 |
-
except Exception as e:
|
668 |
-
# Log the error for debugging and return a general error message
|
669 |
-
print(f"Error adding item to cart: {str(e)}")
|
670 |
-
return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
|
671 |
-
|
672 |
-
|
673 |
-
@app.route("/cart/add_suggestion_to_cart", methods=["POST"])
|
674 |
-
def add_suggestion_to_cart():
|
675 |
-
try:
|
676 |
-
# Get data from the request
|
677 |
-
data = request.get_json()
|
678 |
-
item_name = data.get('item_name').strip()
|
679 |
-
item_price = data.get('item_price')
|
680 |
-
item_image = data.get('item_image')
|
681 |
-
item_id = data.get('item_id')
|
682 |
-
customer_email = data.get('customer_email')
|
683 |
-
addons = data.get('addons', [])
|
684 |
-
instructions = data.get('instructions', "")
|
685 |
-
|
686 |
-
# Default values if addons and instructions are not provided
|
687 |
-
addons_price = 0
|
688 |
-
addons_string = "None"
|
689 |
-
|
690 |
-
# Check if the customer already has this item in their cart
|
691 |
-
query = f"""
|
692 |
-
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c
|
693 |
-
FROM Cart_Item__c
|
694 |
-
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
695 |
-
"""
|
696 |
-
result = sf.query(query)
|
697 |
-
cart_items = result.get("records", [])
|
698 |
-
|
699 |
-
# If item already exists in the cart, update its quantity and other details
|
700 |
-
if cart_items:
|
701 |
-
cart_item_id = cart_items[0]['Id']
|
702 |
-
existing_quantity = cart_items[0]['Quantity__c']
|
703 |
-
existing_addons = cart_items[0].get('Add_Ons__c', "None")
|
704 |
-
existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
705 |
-
existing_instructions = cart_items[0].get('Instructions__c', "")
|
706 |
-
|
707 |
-
# Combine existing and new addons
|
708 |
-
combined_addons = existing_addons if existing_addons != "None" else ""
|
709 |
-
if addons:
|
710 |
-
combined_addons = f"{combined_addons}; {addons}".strip("; ")
|
711 |
-
|
712 |
-
combined_instructions = existing_instructions
|
713 |
-
if instructions:
|
714 |
-
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
715 |
-
|
716 |
-
combined_addons_list = combined_addons.split("; ")
|
717 |
-
combined_addons_price = sum(
|
718 |
-
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
719 |
-
)
|
720 |
-
|
721 |
-
# Update the cart item
|
722 |
-
sf.Cart_Item__c.update(cart_item_id, {
|
723 |
-
"Quantity__c": existing_quantity + 1,
|
724 |
-
"Add_Ons__c": combined_addons,
|
725 |
-
"Add_Ons_Price__c": combined_addons_price,
|
726 |
-
"Instructions__c": combined_instructions,
|
727 |
-
"Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
|
728 |
-
})
|
729 |
-
else:
|
730 |
-
# If item doesn't exist in cart, create a new cart item
|
731 |
-
total_price = float(item_price) + addons_price
|
732 |
-
|
733 |
-
# Create a new cart item in Salesforce
|
734 |
-
sf.Cart_Item__c.create({
|
735 |
-
"Name": item_name,
|
736 |
-
"Price__c": total_price,
|
737 |
-
"Base_Price__c": item_price,
|
738 |
-
"Quantity__c": 1,
|
739 |
-
"Add_Ons_Price__c": addons_price,
|
740 |
-
"Add_Ons__c": addons_string,
|
741 |
-
"Image1__c": item_image,
|
742 |
-
"Customer_Email__c": customer_email,
|
743 |
-
"Instructions__c": instructions
|
744 |
-
})
|
745 |
-
|
746 |
-
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
747 |
-
|
748 |
-
except Exception as e:
|
749 |
-
print(f"Error adding item to cart: {str(e)}")
|
750 |
-
return jsonify({"success": False, "error": str(e)})
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
@app.route("/cart/add_item", methods=["POST"])
|
755 |
-
def add_item_to_cart():
|
756 |
-
data = request.json # Extract JSON data from the request
|
757 |
-
email = data.get('email') # Customer email
|
758 |
-
item_name = data.get('item_name') # Item name
|
759 |
-
quantity = data.get('quantity', 1) # Quantity to add (default is 1)
|
760 |
-
addons = data.get('addons', []) # Add-ons for the item (optional)
|
761 |
-
|
762 |
-
# Validate inputs
|
763 |
-
if not email or not item_name:
|
764 |
-
return jsonify({"success": False, "error": "Email and item name are required."}), 400
|
765 |
-
|
766 |
-
try:
|
767 |
-
# Add a new item to the cart with the provided details
|
768 |
-
sf.Cart_Item__c.create({
|
769 |
-
"Customer_Email__c": email, # Associate the cart item with the customer's email
|
770 |
-
"Item_Name__c": item_name, # Item name
|
771 |
-
"Quantity__c": quantity, # Quantity to add
|
772 |
-
"Add_Ons__c": addons_string
|
773 |
-
})
|
774 |
-
|
775 |
-
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
776 |
-
except Exception as e:
|
777 |
-
print(f"Error adding item to cart: {str(e)}") # Log the error for debugging
|
778 |
-
return jsonify({"success": False, "error": str(e)}), 500
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
@app.route('/cart/remove/<item_name>', methods=['POST'])
|
783 |
-
def remove_cart_item(item_name):
|
784 |
-
try:
|
785 |
-
customer_email = session.get('user_email')
|
786 |
-
if not customer_email:
|
787 |
-
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
|
788 |
-
query = f"""
|
789 |
-
SELECT Id FROM Cart_Item__c
|
790 |
-
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
|
791 |
-
"""
|
792 |
-
result = sf.query(query)
|
793 |
-
if result['totalSize'] == 0:
|
794 |
-
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
|
795 |
-
cart_item_id = result['records'][0]['Id']
|
796 |
-
sf.Cart_Item__c.delete(cart_item_id)
|
797 |
-
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
|
798 |
-
except Exception as e:
|
799 |
-
print(f"Error: {str(e)}")
|
800 |
-
return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
|
801 |
-
|
802 |
-
@app.route('/api/addons', methods=['GET'])
|
803 |
-
def get_addons():
|
804 |
-
item_name = request.args.get('item_name')
|
805 |
-
item_section = request.args.get('item_section')
|
806 |
-
|
807 |
-
# Check if both item_name and item_section are provided
|
808 |
-
if not item_name or not item_section:
|
809 |
-
return jsonify({"success": False, "error": "Item name and section are required."}), 400
|
810 |
-
|
811 |
-
try:
|
812 |
-
# Fetch customization options from Salesforce based on the section
|
813 |
-
query = f"""
|
814 |
-
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
|
815 |
-
FROM Customization_Options__c
|
816 |
-
WHERE Section__c = '{item_section}'
|
817 |
-
"""
|
818 |
-
result = sf.query(query)
|
819 |
-
addons = result.get('records', [])
|
820 |
-
|
821 |
-
# Check if we found any addons
|
822 |
-
if not addons:
|
823 |
-
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
|
824 |
-
|
825 |
-
# Format data for frontend
|
826 |
-
formatted_addons = []
|
827 |
-
for addon in addons:
|
828 |
-
# Ensure 'Options__c' exists and is not None
|
829 |
-
options = addon.get("Options__c", "")
|
830 |
-
if options: # If options are available, split them
|
831 |
-
options = options.split(", ") # Convert comma-separated options into a list
|
832 |
-
else:
|
833 |
-
options = [] # If no options, default to an empty list
|
834 |
-
|
835 |
-
formatted_addons.append({
|
836 |
-
"name": addon["Name"],
|
837 |
-
"type": addon["Customization_Type__c"],
|
838 |
-
"options": options,
|
839 |
-
"max_selections": addon.get("Max_Selections__c", 1),
|
840 |
-
"extra_charge": addon.get("Extra_Charge__c", False),
|
841 |
-
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
|
842 |
-
})
|
843 |
-
|
844 |
-
return jsonify({"success": True, "addons": formatted_addons})
|
845 |
-
|
846 |
-
except Exception as e:
|
847 |
-
# Log the exception for debugging
|
848 |
-
app.logger.error(f"Error fetching addons: {str(e)}")
|
849 |
-
return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
|
850 |
-
|
851 |
-
|
852 |
-
@app.route("/cart/update_quantity", methods=["POST"])
|
853 |
-
def update_quantity():
|
854 |
-
data = request.json # Extract JSON data from the request
|
855 |
-
email = data.get('email')
|
856 |
-
item_name = data.get('item_name')
|
857 |
-
try:
|
858 |
-
# Convert quantity to an integer
|
859 |
-
quantity = int(data.get('quantity'))
|
860 |
-
except (ValueError, TypeError):
|
861 |
-
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
|
862 |
-
|
863 |
-
# Validate inputs
|
864 |
-
if not email or not item_name or quantity is None:
|
865 |
-
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
|
866 |
-
|
867 |
-
try:
|
868 |
-
# Query the cart item in Salesforce
|
869 |
-
cart_items = sf.query(
|
870 |
-
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
|
871 |
-
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
|
872 |
-
)['records']
|
873 |
-
|
874 |
-
if not cart_items:
|
875 |
-
return jsonify({"success": False, "error": "Cart item not found."}), 404
|
876 |
-
|
877 |
-
# Retrieve the first matching record
|
878 |
-
cart_item_id = cart_items[0]['Id']
|
879 |
-
base_price = cart_items[0]['Base_Price__c']
|
880 |
-
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
|
881 |
-
|
882 |
-
# Calculate the new item price
|
883 |
-
new_item_price = (base_price * quantity) + addons_price
|
884 |
-
|
885 |
-
# Update the record in Salesforce
|
886 |
-
sf.Cart_Item__c.update(cart_item_id, {
|
887 |
-
"Quantity__c": quantity,
|
888 |
-
"Price__c": new_item_price, # Update base price
|
889 |
-
})
|
890 |
-
|
891 |
-
# Recalculate the subtotal for all items in the cart
|
892 |
-
cart_items = sf.query(f"""
|
893 |
-
SELECT Price__c, Add_Ons_Price__c
|
894 |
-
FROM Cart_Item__c
|
895 |
-
WHERE Customer_Email__c = '{email}'
|
896 |
-
""")['records']
|
897 |
-
new_subtotal = sum(item['Price__c'] for item in cart_items)
|
898 |
-
|
899 |
-
# Return updated item price and subtotal
|
900 |
-
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
901 |
-
print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
|
902 |
-
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
|
903 |
-
|
904 |
-
except Exception as e:
|
905 |
-
print(f"Error updating quantity: {str(e)}")
|
906 |
-
return jsonify({"success": False, "error": str(e)}), 500
|
907 |
-
@app.route("/checkout", methods=["POST"])
|
908 |
-
def checkout():
|
909 |
-
email = session.get('user_email')
|
910 |
-
user_id = session.get('user_name')
|
911 |
-
table_number = session.get('table_number') # Retrieve table number
|
912 |
-
|
913 |
-
if not email or not user_id:
|
914 |
-
return jsonify({"success": False, "message": "User not logged in"})
|
915 |
-
|
916 |
-
try:
|
917 |
-
data = request.json
|
918 |
-
selected_coupon = data.get("selectedCoupon", "").strip()
|
919 |
-
|
920 |
-
# Fetch cart items
|
921 |
-
result = sf.query(f"""
|
922 |
-
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
|
923 |
-
FROM Cart_Item__c
|
924 |
-
WHERE Customer_Email__c = '{email}'
|
925 |
-
""")
|
926 |
-
cart_items = result.get("records", [])
|
927 |
-
|
928 |
-
if not cart_items:
|
929 |
-
return jsonify({"success": False, "message": "Cart is empty"})
|
930 |
-
|
931 |
-
total_price = sum(item['Price__c'] for item in cart_items)
|
932 |
-
discount = 0
|
933 |
-
|
934 |
-
# Fetch the user's existing coupons
|
935 |
-
coupon_query = sf.query(f"""
|
936 |
-
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
|
937 |
-
""")
|
938 |
-
|
939 |
-
has_coupons = bool(coupon_query["records"])
|
940 |
-
|
941 |
-
if selected_coupon:
|
942 |
-
discount = total_price * 0.10 # 10% discount
|
943 |
-
referral_coupon_id = coupon_query["records"][0]["Id"]
|
944 |
-
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
|
945 |
-
|
946 |
-
# Remove only the selected coupon
|
947 |
-
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
|
948 |
-
updated_coupons_str = "\n".join(updated_coupons).strip()
|
949 |
-
|
950 |
-
sf.Referral_Coupon__c.update(referral_coupon_id, {
|
951 |
-
"Coupon_Code__c": updated_coupons_str
|
952 |
-
})
|
953 |
-
else:
|
954 |
-
reward_points_to_add = total_price * 0.10
|
955 |
-
|
956 |
-
# Fetch current reward points
|
957 |
-
customer_record = sf.query(f"""
|
958 |
-
SELECT Id, Reward_Points__c FROM Customer_Login__c
|
959 |
-
WHERE Email__c = '{email}'
|
960 |
-
""")
|
961 |
-
customer = customer_record.get("records", [])[0] if customer_record else None
|
962 |
-
|
963 |
-
if customer:
|
964 |
-
current_reward_points = customer.get("Reward_Points__c") or 0
|
965 |
-
new_reward_points = current_reward_points + reward_points_to_add
|
966 |
-
|
967 |
-
sf.Customer_Login__c.update(customer["Id"], {
|
968 |
-
"Reward_Points__c": new_reward_points
|
969 |
-
})
|
970 |
-
|
971 |
-
total_bill = total_price - discount
|
972 |
-
|
973 |
-
# ✅ Store all order details
|
974 |
-
order_details = "\n".join(
|
975 |
-
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
|
976 |
-
f"Instructions: {item.get('Instructions__c', 'None')} | "
|
977 |
-
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
|
978 |
-
for item in cart_items
|
979 |
-
)
|
980 |
-
|
981 |
-
# Fetch Customer ID from Customer_Login__c
|
982 |
-
customer_query = sf.query(f"""
|
983 |
-
SELECT Id FROM Customer_Login__c
|
984 |
-
WHERE Email__c = '{email}'
|
985 |
-
""")
|
986 |
-
|
987 |
-
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
|
988 |
-
|
989 |
-
if not customer_id:
|
990 |
-
return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
|
991 |
-
|
992 |
-
# ✅ Store table number in Order__c
|
993 |
-
order_data = {
|
994 |
-
"Customer_Name__c": user_id,
|
995 |
-
"Customer_Email__c": email,
|
996 |
-
"Total_Amount__c": total_price,
|
997 |
-
"Discount__c": discount,
|
998 |
-
"Total_Bill__c": total_bill,
|
999 |
-
"Order_Status__c": "Pending",
|
1000 |
-
"Customer2__c": customer_id,
|
1001 |
-
"Order_Details__c": order_details,
|
1002 |
-
"Table_Number__c": table_number # ✅ Store table number
|
1003 |
-
}
|
1004 |
-
|
1005 |
-
sf.Order__c.create(order_data)
|
1006 |
-
|
1007 |
-
# ✅ Delete cart items after order is placed
|
1008 |
-
for item in cart_items:
|
1009 |
-
sf.Cart_Item__c.delete(item["Id"])
|
1010 |
-
|
1011 |
-
return jsonify({"success": True, "message": "Order placed successfully!"})
|
1012 |
-
|
1013 |
-
except Exception as e:
|
1014 |
-
print(f"Error during checkout: {str(e)}")
|
1015 |
-
return jsonify({"success": False, "error": str(e)})
|
1016 |
-
|
1017 |
-
@app.route("/order", methods=["GET"])
|
1018 |
-
def order_summary():
|
1019 |
-
email = session.get('user_email') # Fetch logged-in user's email
|
1020 |
-
if not email:
|
1021 |
-
return redirect(url_for("login"))
|
1022 |
-
|
1023 |
-
try:
|
1024 |
-
# Fetch the most recent order for the user
|
1025 |
-
result = sf.query(f"""
|
1026 |
-
SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
|
1027 |
-
FROM Order__c
|
1028 |
-
WHERE Customer_Email__c = '{email}'
|
1029 |
-
ORDER BY CreatedDate DESC
|
1030 |
-
LIMIT 1
|
1031 |
-
""")
|
1032 |
-
order = result.get("records", [])[0] if result.get("records") else None
|
1033 |
-
|
1034 |
-
if not order:
|
1035 |
-
return render_template("order.html", order=None)
|
1036 |
-
|
1037 |
-
return render_template("order.html", order=order)
|
1038 |
-
except Exception as e:
|
1039 |
-
print(f"Error fetching order details: {str(e)}")
|
1040 |
-
return render_template("order.html", order=None, error=str(e))
|
1041 |
-
import smtplib
|
1042 |
-
from email.mime.multipart import MIMEMultipart
|
1043 |
-
from email.mime.text import MIMEText
|
1044 |
|
1045 |
|
1046 |
if __name__ == "__main__":
|
|
|
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 |
+
import smtplib
|
8 |
+
from email.mime.multipart import MIMEMultipart
|
9 |
+
from email.mime.text import MIMEText
|
10 |
+
from menu import menu_blueprint # Make sure this import is correct
|
11 |
+
from cart import cart_blueprint # Same for other blueprints
|
12 |
+
from order import order_blueprint # Same for user blueprint
|
13 |
|
14 |
|
15 |
# Initialize Flask app and Salesforce connection
|
|
|
22 |
print("Salesforce connection established.")
|
23 |
|
24 |
# Set the secret key to handle sessions securely
|
25 |
+
app.secret_key = os.getenv("SECRET_KEY", "xEr0cwgsiatzrzaeFewYrVA1O") # Replace with a secure key
|
26 |
|
27 |
+
app.config["SESSION_TYPE"] = "filesystem" # Storing sessions in filesystem
|
28 |
+
app.config["SESSION_COOKIE_SECURE"] = True # Enabling secure cookies (ensure your app is served over HTTPS)
|
29 |
+
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Cross-site cookies allowed
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
# Initialize the session
|
32 |
Session(app) # Correctly initialize the Session object
|
|
|
59 |
|
60 |
# Ensure session is saved before redirecting
|
61 |
session.modified = True
|
62 |
+
return redirect(url_for("menu.menu")) # Redirect to menu directly
|
63 |
|
64 |
return render_template("index.html")
|
65 |
|
|
|
167 |
except Exception as e:
|
168 |
return jsonify({"success": False, "error": str(e)}), 500
|
169 |
|
170 |
+
@app.route("/customer_details", methods=["GET"])
|
171 |
+
def customer_details():
|
|
|
172 |
email = session.get('user_email') # Get logged-in user's email
|
173 |
if not email:
|
174 |
return redirect(url_for("login"))
|
175 |
|
176 |
+
try:
|
177 |
+
# Fetch customer details from Salesforce based on the email
|
178 |
+
customer_record = sf.query(f"""
|
179 |
+
SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
|
180 |
+
FROM Customer_Login__c
|
181 |
+
WHERE Email__c = '{email}'
|
182 |
+
LIMIT 1
|
183 |
+
""")
|
184 |
+
|
185 |
+
if not customer_record.get("records"):
|
186 |
+
flash("Customer not found", "danger")
|
187 |
+
return redirect(url_for("login"))
|
188 |
+
|
189 |
+
customer = customer_record["records"][0]
|
190 |
+
|
191 |
+
# Prepare the data to return to the frontend
|
192 |
+
customer_data = {
|
193 |
+
"name": customer.get("Name", ""),
|
194 |
+
"email": customer.get("Email__c", ""),
|
195 |
+
"phone": customer.get("Phone_Number__c", ""),
|
196 |
+
"referral_code": customer.get("Referral__c", ""),
|
197 |
+
"reward_points": customer.get("Reward_Points__c", 0)
|
198 |
+
}
|
199 |
+
|
200 |
+
return render_template("customer_details.html", customer=customer_data)
|
201 |
+
|
202 |
+
except Exception as e:
|
203 |
+
flash(f"Error fetching customer details: {str(e)}", "danger")
|
204 |
+
return redirect(url_for("login"))
|
205 |
+
|
206 |
+
@app.route("/update_profile", methods=["POST"])
|
207 |
+
def update_profile():
|
208 |
+
email = session.get('user_email') # Get logged-in user's email
|
209 |
+
if not email:
|
210 |
+
return jsonify({'status': 'error', 'message': 'User not logged in'})
|
211 |
+
|
212 |
try:
|
213 |
# Fetch user details from Salesforce
|
214 |
result = sf.query(f"""
|
215 |
+
SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
|
216 |
FROM Customer_Login__c
|
217 |
WHERE Email__c = '{email}'
|
218 |
""")
|
219 |
|
220 |
if not result['records']:
|
221 |
+
return jsonify({'status': 'error', 'message': 'User not found'})
|
222 |
|
223 |
user = result['records'][0]
|
224 |
user_id = user.get("Id")
|
|
|
|
|
|
|
225 |
|
226 |
+
# Get updated profile data from the form
|
227 |
+
new_name = request.form.get('customerName')
|
|
|
|
|
|
|
|
|
|
|
228 |
new_email = request.form.get('email')
|
229 |
new_phone = request.form.get('phone')
|
230 |
+
new_referral_code = request.form.get('referralCode')
|
231 |
+
new_reward_points = request.form.get('rewardPoints')
|
232 |
|
233 |
+
# Prepare data for Salesforce update
|
234 |
update_data = {
|
235 |
'Name': new_name,
|
236 |
'Email__c': new_email,
|
237 |
+
'Phone_Number__c': new_phone,
|
238 |
+
'Referral__c': new_referral_code,
|
239 |
+
'Reward_Points__c': new_reward_points
|
240 |
}
|
241 |
|
|
|
|
|
|
|
242 |
# Update Salesforce record
|
243 |
sf.Customer_Login__c.update(user_id, update_data)
|
244 |
|
245 |
+
return jsonify({
|
246 |
+
'status': 'success',
|
247 |
+
'message': 'Profile updated successfully!',
|
248 |
+
'data': update_data
|
249 |
+
})
|
250 |
|
251 |
except Exception as e:
|
252 |
+
return jsonify({'status': 'error', 'message': str(e)})
|
253 |
|
|
|
|
|
|
|
|
|
254 |
|
|
|
|
|
255 |
|
256 |
+
from datetime import datetime
|
257 |
+
import pytz # Library to handle timezone conversions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
258 |
|
259 |
@app.route("/order-history", methods=["GET"])
|
260 |
def order_history():
|
|
|
272 |
ORDER BY CreatedDate DESC
|
273 |
""")
|
274 |
|
275 |
+
print(f"Salesforce query result: {result}") # Debugging line
|
276 |
+
|
277 |
orders = result.get("records", []) # Fetch all orders
|
278 |
|
279 |
+
if not orders:
|
280 |
+
print("No orders found for this email.") # Debugging line
|
281 |
+
|
282 |
+
# Format the order details for better readability
|
283 |
for order in orders:
|
284 |
order_details = order.get("Order_Details__c", "")
|
285 |
+
items = order_details.split("\n") # Assuming each item is separated by a new line
|
286 |
+
formatted_items = []
|
287 |
+
|
288 |
+
# Loop through the items and format them as "item name * quantity"
|
289 |
+
for item in items:
|
290 |
+
item_details = item.split(" | ")
|
291 |
+
if len(item_details) > 1:
|
292 |
+
name = item_details[0].strip()
|
293 |
+
quantity = item_details[1].strip()
|
294 |
+
formatted_items.append(f"{name} * {quantity}")
|
295 |
+
|
296 |
+
# Join the formatted items into a single string
|
297 |
+
order['formatted_items'] = ", ".join(formatted_items)
|
298 |
+
|
299 |
+
# Get the order date and time from CreatedDate
|
300 |
+
created_date = order.get("CreatedDate", "")
|
301 |
+
if created_date:
|
302 |
+
# Convert CreatedDate to datetime object in UTC
|
303 |
+
utc_datetime = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.000+0000')
|
304 |
+
utc_datetime = utc_datetime.replace(tzinfo=pytz.UTC)
|
305 |
|
306 |
+
# Convert UTC datetime to the desired timezone (e.g., IST)
|
307 |
+
local_timezone = pytz.timezone('Asia/Kolkata') # Replace with your timezone
|
308 |
+
local_datetime = utc_datetime.astimezone(local_timezone)
|
309 |
+
|
310 |
+
# Format the date and time in the desired format
|
311 |
+
order['formatted_date'] = local_datetime.strftime('%B %d, %I:%M %p')
|
312 |
+
|
313 |
+
order_status = order.get("Order_Status__c", "N/A") # Default to "N/A" if no status
|
314 |
+
order['order_status'] = order_status
|
315 |
|
|
|
|
|
316 |
|
317 |
return render_template("order_history.html", orders=orders)
|
318 |
|
319 |
except Exception as e:
|
320 |
print(f"Error fetching order history: {str(e)}")
|
321 |
return render_template("order_history.html", orders=[], error=str(e))
|
322 |
+
|
323 |
+
|
324 |
app.permanent_session_lifetime = timedelta(minutes=5)
|
325 |
@app.before_request
|
326 |
def check_session_timeout():
|
|
|
431 |
|
432 |
return render_template("signup.html")
|
433 |
|
434 |
+
|
435 |
+
|
436 |
+
|
437 |
@app.route("/login", methods=["GET", "POST"])
|
438 |
def login():
|
439 |
if request.method == "POST":
|
|
|
480 |
new_reward_points = reward_points - 500
|
481 |
sf.Customer_Login__c.update(user['Id'], {"Reward_Points__c": new_reward_points})
|
482 |
|
483 |
+
return redirect(url_for("menu.menu"))
|
484 |
|
485 |
else:
|
486 |
print("Invalid credentials!")
|
|
|
491 |
return render_template("login.html", error=f"Error: {str(e)}")
|
492 |
|
493 |
return render_template("login.html")
|
494 |
+
# Register Blueprints for each functionality
|
495 |
+
app.register_blueprint(menu_blueprint)
|
496 |
+
app.register_blueprint(cart_blueprint, url_prefix='/cart') # Register the cart blueprint with URL prefix
|
497 |
|
498 |
+
app.register_blueprint(order_blueprint)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
499 |
|
500 |
|
501 |
if __name__ == "__main__":
|