|
from flask import Flask, render_template, request, jsonify, redirect, url_for, session |
|
from flask_session import Session |
|
from flask.sessions import SecureCookieSessionInterface |
|
from salesforce import get_salesforce_connection |
|
from datetime import timedelta |
|
from email.mime.multipart import MIMEMultipart |
|
from email.mime.text import MIMEText |
|
from menu import menu_blueprint |
|
from cart import cart_blueprint |
|
from order import order_blueprint |
|
from orderhistory import orderhistory_blueprint |
|
from user_details import user_details_blueprint |
|
from customdish import customdish_blueprint |
|
from combined_summary import combined_summary_blueprint |
|
|
|
from datetime import datetime |
|
from datetime import datetime |
|
import pytz |
|
import os |
|
import smtplib |
|
import random |
|
import string |
|
from flask import Flask, render_template, request, jsonify, send_from_directory |
|
from simple_salesforce import Salesforce |
|
from dotenv import load_dotenv |
|
import os |
|
import logging |
|
import uuid |
|
from datetime import datetime |
|
|
|
|
|
app = Flask(__name__) |
|
logging.basicConfig(level=logging.DEBUG) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
sf = get_salesforce_connection() |
|
|
|
|
|
|
|
app.secret_key = os.getenv("SECRET_KEY", "PWEmya351XHeWQy0ZHbIvYm3") |
|
app.config["SESSION_TYPE"] = "filesystem" |
|
app.config["SESSION_COOKIE_SECURE"] = True |
|
app.config["SESSION_COOKIE_SAMESITE"] = "None" |
|
|
|
|
|
Session(app) |
|
app.session_interface = SecureCookieSessionInterface() |
|
|
|
app.register_blueprint(cart_blueprint, url_prefix='/cart') |
|
app.register_blueprint(user_details_blueprint, url_prefix='/user') |
|
app.register_blueprint(menu_blueprint) |
|
app.register_blueprint(order_blueprint) |
|
app.register_blueprint(orderhistory_blueprint, url_prefix='/orderhistory') |
|
app.register_blueprint(customdish_blueprint, url_prefix='/customdish') |
|
app.register_blueprint(combined_summary_blueprint, url_prefix='/combined_summary') |
|
|
|
|
|
@app.route("/") |
|
def home(): |
|
|
|
user_email = request.args.get("email") |
|
user_name = request.args.get("name") |
|
table_number = request.args.get("table") |
|
if user_email and user_name: |
|
session["user_email"] = user_email |
|
session["user_name"] = user_name |
|
session["table_number"] = table_number |
|
print(f"User logged in: {user_email} - {user_name} - Table: {table_number}") |
|
|
|
|
|
session.modified = True |
|
return redirect(url_for("menu.menu")) |
|
return render_template("index.html") |
|
@app.route("/login", methods=["GET", "POST"]) |
|
def login(): |
|
if request.method == "POST": |
|
email = request.form.get("email") |
|
password = request.form.get("password") |
|
print(f"Login attempt with email: {email}") |
|
|
|
try: |
|
|
|
query = f"SELECT Id, Name, Email__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'" |
|
result = sf.query(query) |
|
|
|
if result["records"]: |
|
user = result["records"][0] |
|
session['user_id'] = user['Id'] |
|
|
|
|
|
if 'user_email' not in session or session['user_email'] != email: |
|
session['user_email'] = email |
|
session['user_name'] = user.get("Name", "") |
|
print(f"✅ Session email updated: {session['user_email']}") |
|
|
|
reward_points = user.get("Reward_Points__c") or 0 |
|
|
|
|
|
if reward_points >= 500: |
|
new_coupon_code = generate_coupon_code() |
|
coupon_query = sf.query(f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'") |
|
|
|
if coupon_query["records"]: |
|
coupon_record = coupon_query["records"][0] |
|
referral_coupon_id = coupon_record["Id"] |
|
existing_coupons = coupon_record.get("Coupon_Code__c", "") |
|
|
|
updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip() |
|
sf.Referral_Coupon__c.update(referral_coupon_id, {"Coupon_Code__c": updated_coupons}) |
|
else: |
|
sf.Referral_Coupon__c.create({ |
|
"Referral_Email__c": email, |
|
"Name": user.get("Name", ""), |
|
"Coupon_Code__c": new_coupon_code |
|
}) |
|
|
|
new_reward_points = reward_points - 500 |
|
sf.Customer_Login__c.update(user['Id'], {"Reward_Points__c": new_reward_points}) |
|
|
|
return redirect(url_for("menu.menu")) |
|
|
|
else: |
|
print("Invalid credentials!") |
|
return render_template("login.html", error="Invalid credentials!") |
|
|
|
except Exception as e: |
|
print(f"Error during login: {str(e)}") |
|
return render_template("login.html", error=f"Error: {str(e)}") |
|
|
|
return render_template("login.html") |
|
|
|
|
|
@app.route("/logout") |
|
def logout(): |
|
|
|
table_number = session.get('table_number', '') |
|
|
|
|
|
session.pop('name', None) |
|
session.pop('email', None) |
|
session.pop('rewardPoints', None) |
|
session.pop('coupon', None) |
|
|
|
|
|
return render_template("redirect_page.html", table_number=table_number) |
|
|
|
@app.route('/customdish') |
|
def customdish(): |
|
|
|
user_name = session.get('user_name', None) |
|
|
|
return render_template('customdish.html', user_name=user_name) |
|
|
|
|
|
|
|
@app.route('/get_ingredients', methods=['POST']) |
|
def get_ingredients(): |
|
global sf |
|
if not sf: |
|
sf = get_salesforce_connection() |
|
if not sf: |
|
return jsonify({"error": "Unable to connect to Salesforce"}), 500 |
|
|
|
data = request.json |
|
dietary_preference = data.get('dietary_preference', 'both').lower() |
|
|
|
try: |
|
category_map = { |
|
'vegetarian': 'Veg', |
|
'non-vegetarian': 'Non-Veg', |
|
'chicken': 'Non-Veg', |
|
'beef': 'Non-Veg', |
|
'lamb': 'Non-Veg', |
|
'both': 'both' |
|
} |
|
category = category_map.get(dietary_preference, 'both') |
|
soql = f"SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c WHERE Category__c = '{category}'" |
|
soql += " LIMIT 200" |
|
logger.debug(f"Executing SOQL query for Sector_Detail__c: {soql}") |
|
result = sf.query(soql) |
|
ingredients = [ |
|
{ |
|
"name": record['Name'], |
|
"image_url": record.get('Image_URL__c', ''), |
|
"category": record.get('Category__c', '') |
|
} |
|
for record in result['records'] if 'Name' in record |
|
] |
|
logger.debug(f"Fetched {len(ingredients)} ingredients from Sector_Detail__c") |
|
return jsonify({"ingredients": ingredients}) |
|
except Exception as e: |
|
logger.error(f"Failed to fetch ingredients: {str(e)}") |
|
return jsonify({"error": f"Failed to fetch ingredients from Salesforce: {str(e)}"}), 500 |
|
|
|
@app.route('/get_menu_items', methods=['POST']) |
|
def get_menu_items(): |
|
global sf |
|
if not sf: |
|
sf = get_salesforce_connection() |
|
if not sf: |
|
return jsonify({"error": "Unable to connect to Salesforce"}), 500 |
|
|
|
data = request.json |
|
ingredient_names = data.get('ingredient_names', '') |
|
category = data.get('category', '') |
|
|
|
try: |
|
soql = "SELECT Name, Description__c, Image1__c, Image2__c, Price__c, Section__c, Veg_NonVeg__c, Total_Ordered__c FROM Menu_Item__c" |
|
conditions = [] |
|
if ingredient_names: |
|
words = ingredient_names.split() |
|
name_conditions = [f"Name LIKE '%{word}%'" for word in words] |
|
conditions.append(f"({' OR '.join(name_conditions)})") |
|
if category: |
|
if category.lower() == 'vegetarian': |
|
conditions.append("Veg_NonVeg__c = 'Vegetarian'") |
|
elif category.lower() == 'non-vegetarian': |
|
conditions.append("Veg_NonVeg__c = 'Non-Vegetarian'") |
|
if conditions: |
|
soql += " WHERE " + " AND ".join(conditions) |
|
soql += " LIMIT 200" |
|
logger.debug(f"Executing SOQL query for Menu_Item__c: {soql}") |
|
result = sf.query(soql) |
|
menu_items = [ |
|
{ |
|
"name": record['Name'], |
|
"description": record.get('Description__c', 'No description available'), |
|
"image_url": record.get('Image1__c', '') or record.get('Image2__c', ''), |
|
"price": record.get('Price__c', 0.0), |
|
"section": record.get('Section__c', ''), |
|
"veg_nonveg": record.get('Veg_NonVeg__c', ''), |
|
"total_ordered": record.get('Total_Ordered__c', 0) |
|
} |
|
for record in result['records'] if 'Name' in record |
|
] |
|
logger.debug(f"Fetched {len(menu_items)} menu items") |
|
return jsonify({"menu_items": menu_items}) |
|
except Exception as e: |
|
logger.error(f"Failed to fetch menu items: {str(e)}") |
|
return jsonify({"error": f"Failed to fetch menu items from Salesforce: {str(e)}"}), 500 |
|
|
|
|
|
@app.route('/submit_customization_ingredients', methods=['POST']) |
|
def submit_customization_ingredients(): |
|
global sf |
|
if not sf: |
|
sf = get_salesforce_connection() |
|
if not sf: |
|
return jsonify({"error": "Unable to connect to Salesforce"}), 500 |
|
|
|
data = request.json |
|
items = data.get('items', []) |
|
menu_item = data.get('menu_item', {}) |
|
ingredients = data.get('ingredients', []) |
|
instructions = data.get('instructions', '') |
|
|
|
|
|
customer_email = session.get('user_email') |
|
|
|
if not customer_email: |
|
return jsonify({"error": "User email not found in session"}), 400 |
|
|
|
try: |
|
if items: |
|
for item in items: |
|
ingredient_names = ', '.join(i['name'] for i in item.get('ingredients', [])) if item.get('ingredients') else '' |
|
base_price = item.get('price', 0.0) |
|
quantity = 1 |
|
addons_price = 0 |
|
total_price = (base_price * quantity) + addons_price |
|
|
|
|
|
soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item['name']}' LIMIT 1" |
|
existing_item = sf.query(soql) |
|
|
|
if existing_item['records']: |
|
item_id = existing_item['records'][0]['Id'] |
|
existing_quantity = existing_item['records'][0]['Quantity__c'] |
|
existing_addons = existing_item['records'][0]['Add_Ons__c'] |
|
existing_instructions = existing_item['records'][0]['Instructions__c'] |
|
existing_price = existing_item['records'][0]['Price__c'] |
|
|
|
|
|
new_quantity = existing_quantity + quantity |
|
new_addons = (existing_addons or '') + (', ' + ingredient_names if ingredient_names else '') |
|
new_instructions = (existing_instructions or '') + ('; ' + instructions if instructions else '') |
|
|
|
|
|
updated_price = (base_price * new_quantity) + addons_price |
|
|
|
|
|
sf.Cart_Item__c.update(item_id, { |
|
'Quantity__c': new_quantity, |
|
'Add_Ons__c': new_addons, |
|
'Instructions__c': new_instructions, |
|
'Price__c': updated_price |
|
}) |
|
logger.debug(f"Updated {item['name']} in Cart_Item__c") |
|
else: |
|
sf.Cart_Item__c.create({ |
|
'Name': item['name'], |
|
'Base_Price__c': base_price, |
|
'Quantity__c': quantity, |
|
'Add_Ons__c': ingredient_names, |
|
'Add_Ons_Price__c': addons_price, |
|
'Price__c': total_price, |
|
'Image1__c': item.get('image_url', ''), |
|
'Instructions__c': item.get('instructions', ''), |
|
'Category__c': item.get('veg_nonveg', ''), |
|
'Section__c': item.get('section', ''), |
|
'Customer_Email__c': customer_email |
|
}) |
|
logger.debug(f"Created new Cart_Item__c for {item['name']}") |
|
return jsonify({"success": True, "message": f"Processed {len(items)} items"}) |
|
|
|
elif menu_item: |
|
ingredient_names = ', '.join(i['name'] for i in ingredients) if ingredients else '' |
|
base_price = menu_item.get('price', 0.0) |
|
quantity = 1 |
|
addons_price = 0 |
|
total_price = (base_price * quantity) + addons_price |
|
|
|
|
|
soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{menu_item['name']}' LIMIT 1" |
|
existing_item = sf.query(soql) |
|
|
|
if existing_item['records']: |
|
item_id = existing_item['records'][0]['Id'] |
|
existing_quantity = existing_item['records'][0]['Quantity__c'] |
|
existing_addons = existing_item['records'][0]['Add_Ons__c'] |
|
existing_instructions = existing_item['records'][0]['Instructions__c'] |
|
existing_price = existing_item['records'][0]['Price__c'] |
|
|
|
|
|
new_quantity = existing_quantity + quantity |
|
new_addons = (existing_addons or '') + (', ' + ingredient_names if ingredient_names else '') |
|
new_instructions = (existing_instructions or '') + ('; ' + instructions if instructions else '') |
|
|
|
|
|
updated_price = (base_price * new_quantity) + addons_price |
|
|
|
|
|
sf.Cart_Item__c.update(item_id, { |
|
'Quantity__c': new_quantity, |
|
'Add_Ons__c': new_addons, |
|
'Instructions__c': new_instructions, |
|
'Price__c': updated_price |
|
}) |
|
logger.debug(f"Updated customization for {menu_item['name']} in Cart_Item__c") |
|
else: |
|
sf.Cart_Item__c.create({ |
|
'Name': menu_item['name'], |
|
'Base_Price__c': base_price, |
|
'Quantity__c': quantity, |
|
'Add_Ons__c': ingredient_names, |
|
'Add_Ons_Price__c': addons_price, |
|
'Price__c': total_price, |
|
'Image1__c': menu_item.get('image_url', ''), |
|
'Instructions__c': instructions, |
|
'Category__c': menu_item.get('veg_nonveg', ''), |
|
'Section__c': menu_item.get('section', ''), |
|
'Customer_Email__c': customer_email |
|
}) |
|
logger.debug(f"Created new Cart_Item__c for {menu_item['name']}") |
|
return jsonify({"success": True, "message": "Customization submitted"}) |
|
|
|
else: |
|
return jsonify({"error": "No items or menu item provided"}), 400 |
|
|
|
except Exception as e: |
|
logger.error(f"Failed to submit: {str(e)}") |
|
return jsonify({"error": f"Failed to submit: {str(e)}"}), 500 |
|
|
|
|
|
if __name__ == "__main__": |
|
app.run(debug=True, host="0.0.0.0", port=7860) |