', methods=['POST'])
def remove_cart_item(item_name):
try:
customer_email = session.get('user_email')
if not customer_email:
return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400
query = f"""
SELECT Id FROM Cart_Item__c
WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
"""
result = sf.query(query)
if result['totalSize'] == 0:
return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400
cart_item_id = result['records'][0]['Id']
sf.Cart_Item__c.delete(cart_item_id)
return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200
except Exception as e:
print(f"Error: {str(e)}")
return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500
@app.route('/api/addons', methods=['GET'])
def get_addons():
item_name = request.args.get('item_name')
item_section = request.args.get('item_section')
if not item_name or not item_section:
return jsonify({"success": False, "error": "Item name and section are required."})
try:
# Fetch customization options from Salesforce based on the section
query = f"""
SELECT Name, Customization_Type__c, Options__c, Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
FROM Customization_Options__c
WHERE Section__c = '{item_section}'
"""
result = sf.query(query)
addons = result.get('records', [])
# Format data for frontend
formatted_addons = []
for addon in addons:
options = addon.get("Options__c", "").split(", ") # Convert comma-separated options into a list
formatted_addons.append({
"name": addon["Name"],
"type": addon["Customization_Type__c"],
"options": options,
"max_selections": addon.get("Max_Selections__c", 1),
"extra_charge": addon.get("Extra_Charge__c", False),
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
})
return jsonify({"success": True, "addons": formatted_addons})
except Exception as e:
print(f"Error fetching add-ons: {e}")
return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})
@app.route("/cart/update_quantity", methods=["POST"])
def update_quantity():
data = request.json # Extract JSON data from the request
email = data.get('email')
item_name = data.get('item_name')
try:
# Convert quantity to an integer
quantity = int(data.get('quantity'))
except (ValueError, TypeError):
return jsonify({"success": False, "error": "Invalid quantity provided."}), 400
# Validate inputs
if not email or not item_name or quantity is None:
return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400
try:
# Query the cart item in Salesforce
cart_items = sf.query(
f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c "
f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'"
)['records']
if not cart_items:
return jsonify({"success": False, "error": "Cart item not found."}), 404
# Retrieve the first matching record
cart_item_id = cart_items[0]['Id']
base_price = cart_items[0]['Base_Price__c']
addons_price = cart_items[0].get('Add_Ons_Price__c', 0)
# Calculate the new item price
new_item_price = (base_price * quantity) + addons_price
# Update the record in Salesforce
sf.Cart_Item__c.update(cart_item_id, {
"Quantity__c": quantity,
"Price__c": new_item_price, # Update base price
})
# Recalculate the subtotal for all items in the cart
cart_items = sf.query(f"""
SELECT Price__c, Add_Ons_Price__c
FROM Cart_Item__c
WHERE Customer_Email__c = '{email}'
""")['records']
new_subtotal = sum(item['Price__c'] for item in cart_items)
# Return updated item price and subtotal
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
print(f"New item price: {new_item_price}, New subtotal: {new_subtotal}")
return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal})
except Exception as e:
print(f"Error updating quantity: {str(e)}")
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/checkout", methods=["POST"])
def checkout():
email = session.get('user_email')
user_id = session.get('user_name')
if not email or not user_id:
return jsonify({"success": False, "message": "User not logged in"})
try:
data = request.json
selected_coupon = data.get("selectedCoupon", "").strip()
# Fetch cart items
result = sf.query(f"""
SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c
FROM Cart_Item__c
WHERE Customer_Email__c = '{email}'
""")
cart_items = result.get("records", [])
if not cart_items:
return jsonify({"success": False, "message": "Cart is empty"})
total_price = sum(item['Price__c'] for item in cart_items)
discount = 0
# Fetch the user's existing coupons
coupon_query = sf.query(f"""
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'
""")
has_coupons = bool(coupon_query["records"]) # Check if user has any coupons
if selected_coupon:
# Case 3: User selected a valid coupon → Apply discount & remove coupon
discount = total_price * 0.10 # 10% discount
referral_coupon_id = coupon_query["records"][0]["Id"]
existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
# Remove only the selected coupon
updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
# Convert list back to a string with newlines
updated_coupons_str = "\n".join(updated_coupons).strip()
# Update the Referral_Coupon__c record with the remaining coupons
sf.Referral_Coupon__c.update(referral_coupon_id, {
"Coupon_Code__c": updated_coupons_str
})
else:
# Case 1 & Case 2: User has no coupons or has coupons but didn’t select one → Add 10% to reward points
reward_points_to_add = total_price * 0.10
# Fetch current reward points
customer_record = sf.query(f"""
SELECT Id, Reward_Points__c FROM Customer_Login__c
WHERE Email__c = '{email}'
""")
customer = customer_record.get("records", [])[0] if customer_record else None
if customer:
current_reward_points = customer.get("Reward_Points__c") or 0
new_reward_points = current_reward_points + reward_points_to_add
print(f"Updating reward points: Current = {current_reward_points}, Adding = {reward_points_to_add}, New = {new_reward_points}")
# Update reward points in Salesforce
sf.Customer_Login__c.update(customer["Id"], {
"Reward_Points__c": new_reward_points
})
print(f"Successfully updated reward points for {email}")
total_bill = total_price - discount
# ✅ Store **all details** including Add-Ons, Instructions, Price, and Image
order_details = "\n".join(
f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | "
f"Instructions: {item.get('Instructions__c', 'None')} | "
f"Price: ${item['Price__c']} | Image: {item['Image1__c']}"
for item in cart_items
)
# Fetch Customer ID from Customer_Login__c based on email
customer_query = sf.query(f"""
SELECT Id FROM Customer_Login__c
WHERE Email__c = '{email}'
""")
# Assuming the customer exists
customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
if not customer_id:
return jsonify({"success": False, "message": "Customer record not found in Salesforce"})
# Store the order details in Order__c
order_data = {
"Customer_Name__c": user_id,
"Customer_Email__c": email,
"Total_Amount__c": total_price,
"Discount__c": discount,
"Total_Bill__c": total_bill,
"Order_Status__c": "Pending",
"Customer2__c": customer_id, # Correcting to use the Salesforce Customer record ID
"Order_Details__c": order_details # ✅ Now includes **all details**
}
sf.Order__c.create(order_data)
# ✅ Delete cart items after order is placed
for item in cart_items:
sf.Cart_Item__c.delete(item["Id"])
send_order_email(email, order_data)
return jsonify({"success": True, "message": "Order placed successfully!"})
except Exception as e:
print(f"Error during checkout: {str(e)}")
return jsonify({"success": False, "error": str(e)})
@app.route("/order", methods=["GET"])
def order_summary():
email = session.get('user_email') # Fetch logged-in user's email
if not email:
return redirect(url_for("login"))
try:
# Fetch the most recent order for the user
result = sf.query(f"""
SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c
FROM Order__c
WHERE Customer_Email__c = '{email}'
ORDER BY CreatedDate DESC
LIMIT 1
""")
order = result.get("records", [])[0] if result.get("records") else None
if not order:
return render_template("order.html", order=None)
return render_template("order.html", order=order)
except Exception as e:
print(f"Error fetching order details: {str(e)}")
return render_template("order.html", order=None, error=str(e))
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_order_email(email, order):
restaurant_name = "Your Restaurant Name"
subject = f"Your Order Confirmation from {restaurant_name}"
# Email content
message = f"""
Hello {order['Customer_Name__c']},
Thank you for placing your order with {restaurant_name}! Below are the details of your order:
🛒 Order Summary
Order ID: {order['Id']}
Customer Name: {order['Customer_Name__c']}
Email: {order['Customer_Email__c']}
Order Status: {order['Order_Status__c']}
🍽️ Items Ordered
Item Name |
Quantity |
Add-Ons |
Instructions |
Price |
"""
# Adding items dynamically
for item in order["Order_Details__c"].split("\n"):
parts = item.split("|")
if len(parts) == 5:
message += f"""
{parts[0]} |
{parts[1]} |
{parts[2]} |
{parts[3]} |
{parts[4]} |
"""
message += f"""
💰 Billing Details
Total Amount: ${order['Total_Amount__c']}
Discount Applied: ${order['Discount__c']}
Final Bill: ${order['Total_Bill__c']}
🕒 Your order is currently: {order['Order_Status__c']}
📍 Estimated Delivery Time: [Estimated_Delivery_Time]
If you have any questions regarding your order, feel free to contact us at [Restaurant Support Email].
Looking forward to serving you!
🍴 {restaurant_name}
📍 [Restaurant Address]
📞 [Restaurant Phone]
"""
# Email sending configuration
sender_email = "yourrestaurant@example.com"
sender_password = "yourpassword"
recipient_email = email
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = recipient_email
msg["Subject"] = subject
msg.attach(MIMEText(message, "html"))
try:
server = smtplib.SMTP("smtp.gmail.com", 587) # Change for your email provider
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
server.quit()
print(f"Order email sent successfully to {email}")
except Exception as e:
print(f"Error sending email: {str(e)}")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=7860)