Spaces:
Runtime error
Runtime error
File size: 19,256 Bytes
a7abf85 d3245ed 36d2eb6 b12f5e4 9bf1d7d 5324aa9 8369d3e 386c140 d8f342f 6218638 174e074 17ac46c 6218638 b5bdea6 6218638 a7abf85 b5bdea6 6218638 01b8424 a7abf85 6218638 a7abf85 c32eb64 d831144 a69087c d3245ed 13d210d 6218638 145b38f 6218638 d8f342f 174e074 17ac46c d8dce64 6218638 3ad292c a7abf85 c096c2c 4ad81b7 c096c2c 4ad81b7 c096c2c 1fd9c90 7136825 040f053 2ba0ba2 8c2cea7 2ba0ba2 f62a0a9 80f989c 0270ecb 80f989c 9de76b8 18d9d83 cafc49b 2ba0ba2 424b262 2ba0ba2 492f069 2ba0ba2 ce2f341 2ba0ba2 ce2f341 424b262 88fcb87 328af5b ce2f341 88fcb87 ce2f341 88fcb87 328af5b ce2f341 88fcb87 328af5b 88fcb87 328af5b ce2f341 71bacb0 ce2f341 71bacb0 328af5b ce2f341 71bacb0 328af5b 71bacb0 88fcb87 2ba0ba2 ce2f341 2ba0ba2 ce2f341 424b262 88fcb87 328af5b ce2f341 88fcb87 ce2f341 88fcb87 328af5b ce2f341 88fcb87 328af5b 88fcb87 328af5b ce2f341 328af5b ce2f341 328af5b ce2f341 328af5b 2ba0ba2 328af5b ce2f341 acf390f 3e6bc95 acf390f ecdf36a 99773b4 acf390f ecdf36a acf390f 2ba0ba2 492f069 a7abf85 fcdec6b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_session import Session # Import the Session class
from flask.sessions import SecureCookieSessionInterface # Import the class
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 # Make sure this import is correct
from cart import cart_blueprint # Same for other blueprints
from order import order_blueprint # Same for user 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 # Library to handle timezone conversions
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__)
# Add debug logs in Salesforce connection setup
sf = get_salesforce_connection()
# Set the secret key to handle sessions securely
app.secret_key = os.getenv("SECRET_KEY", "PWEmya351XHeWQy0ZHbIvYm3") # Replace with a secure key
app.config["SESSION_TYPE"] = "filesystem" # Storing sessions in filesystem
app.config["SESSION_COOKIE_SECURE"] = True # Enabling secure cookies (ensure your app is served over HTTPS)
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Cross-site cookies allowed
# Initialize the session
Session(app) # Correctly initialize the Session object
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('/login', methods=['GET', 'POST'])
def login():
# Your login logic goes here
# Fetch user details from URL parameters
user_email = request.args.get("email")
user_name = request.args.get("name")
table_number = request.args.get("table") # Capture table number
if user_email and user_name:
session["user_email"] = user_email
session["user_name"] = user_name
session["table_number"] = table_number # Store table number in session
print(f"User logged in: {user_email} - {user_name} - Table: {table_number}")
# Ensure session is saved before redirecting
session.modified = True
return redirect(url_for("menu.menu")) # Redirect to menu directly
return render_template('login.html')
@app.route("/")
def home():
# Fetch user details from URL parameters
user_email = request.args.get("email")
user_name = request.args.get("name")
table_number = request.args.get("table") # Capture table number
if user_email and user_name:
session["user_email"] = user_email
session["user_name"] = user_name
session["table_number"] = table_number # Store table number in session
print(f"User logged in: {user_email} - {user_name} - Table: {table_number}")
# Ensure session is saved before redirecting
session.modified = True
return redirect(url_for("menu.menu")) # Redirect to menu directly
return render_template("index.html")
@app.route("/logout")
def logout():
# Retrieve table number before clearing session
table_number = session.get('table_number', '')
# Clear session variables
session.pop('name', None)
session.pop('email', None)
session.pop('rewardPoints', None)
session.pop('coupon', None)
# Pass table number to redirect page
return render_template("redirect_page.html", table_number=table_number)
@app.route('/customdish')
def customdish():
# Retrieve the user_name from the session
user_name = session.get('user_name', None)
# Pass user_name to the template if it exists, otherwise pass 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:
# Fetch customer name from Customer_Login__c using email
soql_customer = f"SELECT Name, Email__c FROM Customer_Login__c WHERE Email__c = '{customer_email}' LIMIT 1"
customer_record = sf.query(soql_customer)
customer_name = customer_record['records'][0]['Name'] if customer_record['records'] else 'Unknown Customer'
if items: # Bulk items in cart submission
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
# Check if item exists in cart
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']:
# Update existing cart item
record = existing_item['records'][0]
item_id = record['Id']
existing_quantity = record['Quantity__c'] or 0
existing_addons = record.get('Add_Ons__c') or ''
existing_instructions = record.get('Instructions__c') or ''
new_quantity = existing_quantity + quantity
new_addons = existing_addons + (', ' + ingredient_names if ingredient_names else '')
new_instructions = existing_instructions + ('; ' + 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:
# Create new cart item
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']}")
# Create corresponding Custom_Dish__c record
sf.Custom_Dish__c.create({
'Name': f"{customer_name} - {item['name']}",
'Price__c': total_price,
'Description__c': (ingredient_names + '; ' + instructions).strip('; '),
'Image1__c': item.get('image_url', ''),
'Veg_NonVeg__c': item.get('veg_nonveg', ''),
'Total_Ordered__c': 1,
'Section__c': 'Customized dish' # Fixed value here
})
logger.debug(f"Created Custom_Dish__c for {item['name']}")
return jsonify({"success": True, "message": f"Processed {len(items)} items"})
elif menu_item: # Single item customization
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']:
# Update existing cart item
record = existing_item['records'][0]
item_id = record['Id']
existing_quantity = record['Quantity__c'] or 0
existing_addons = record.get('Add_Ons__c') or ''
existing_instructions = record.get('Instructions__c') or ''
new_quantity = existing_quantity + quantity
new_addons = existing_addons + (', ' + ingredient_names if ingredient_names else '')
new_instructions = existing_instructions + ('; ' + 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:
# Create new cart item
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']}")
# Create corresponding Custom_Dish__c record
sf.Custom_Dish__c.create({
'Name': f"{customer_name} - {menu_item['name']}",
'Price__c': total_price,
'Description__c': (ingredient_names + '; ' + instructions).strip('; '),
'Image1__c': menu_item.get('image_url', ''),
'Veg_NonVeg__c': menu_item.get('veg_nonveg', ''),
'Total_Ordered__c': 1,
'Section__c': 'Customized dish' # Fixed value here
})
logger.debug(f"Created Custom_Dish__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
from flask import Flask, render_template, request, jsonify
import os
import base64
import requests
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Configuration
UPLOAD_FOLDER = 'static/captures'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Zapier webhook settings
ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
def send_to_zapier(image_path):
if not ZAPIER_WEBHOOK_URL:
logging.error("Zapier webhook URL not set.")
return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
try:
payload = {
'image_url': request.url_root + image_path,
'filename': os.path.basename(image_path),
'content_type': 'image/jpeg'
}
session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
session.mount('https://', HTTPAdapter(max_retries=retries))
logging.debug(f"Sending image URL to Zapier webhook: {ZAPIER_WEBHOOK_URL}")
response = session.post(ZAPIER_WEBHOOK_URL, json=payload, timeout=10)
response.raise_for_status()
logging.debug("Image URL sent to Zapier successfully.")
return {"status": "success"}
except requests.exceptions.RequestException as e:
logging.error(f"Failed to send to Zapier: {str(e)}")
if e.response is not None:
logging.error(f"Response details: {e.response.text}")
return {"error": f"Failed to send to Zapier: {str(e)}"}
@app.route('/camera')
def camera():
return render_template('camera.html')
@app.route('/capture', methods=['POST'])
def capture():
try:
data = request.form['image']
header, encoded = data.split(",", 1)
binary_data = base64.b64decode(encoded)
filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
with open(filepath, "wb") as f:
f.write(binary_data)
image_url = f"/{filepath}"
return jsonify({
'status': 'success',
'image_url': image_url
})
except Exception as e:
logging.error(f"Error in capture: {str(e)}")
return jsonify({'status': 'error', 'message': str(e)})
@app.route('/upload_zapier', methods=['POST'])
def upload_zapier():
try:
image_url = request.form['image_url']
if not image_url.startswith('/static/captures/'):
return jsonify({'status': 'error', 'message': 'Invalid image path.'})
result = send_to_zapier(image_url.lstrip('/'))
if 'error' in result:
return jsonify({'status': 'error', 'message': result['error']})
return jsonify({'status': 'success'})
except Exception as e:
logging.error(f"Error in upload_zapier: {str(e)}")
return jsonify({'status': 'error', 'message': str(e)})
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=7860) |