Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,39 @@
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
| 2 |
-
from simple_salesforce import Salesforce
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
import os
|
| 5 |
import logging
|
|
|
|
| 6 |
|
| 7 |
# Load environment variables
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
# Set up logging
|
| 11 |
-
logging.basicConfig(level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
app = Flask(__name__, template_folder='templates', static_folder='static')
|
| 15 |
|
| 16 |
-
# Salesforce connection function
|
| 17 |
-
def get_salesforce_connection():
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
sf = get_salesforce_connection()
|
| 33 |
|
| 34 |
@app.route('/')
|
|
@@ -42,7 +47,7 @@ def get_menu_items():
|
|
| 42 |
if not sf:
|
| 43 |
sf = get_salesforce_connection()
|
| 44 |
if not sf:
|
| 45 |
-
return jsonify({"error": "Unable to connect to Salesforce"}), 500
|
| 46 |
|
| 47 |
dietary_preference = request.json.get('dietary_preference', 'both').lower()
|
| 48 |
try:
|
|
@@ -53,16 +58,20 @@ def get_menu_items():
|
|
| 53 |
soql += " WHERE Category__c = 'Non-Veg'"
|
| 54 |
soql += " LIMIT 200"
|
| 55 |
|
| 56 |
-
logger.info(f"Executing SOQL query: {soql}")
|
| 57 |
result = sf.query(soql)
|
| 58 |
menu_items = [
|
| 59 |
{
|
| 60 |
"name": record['Name'],
|
| 61 |
-
"image_url": record.get('Image_URL__c', ''),
|
| 62 |
"category": record.get('Category__c', '')
|
| 63 |
}
|
| 64 |
for record in result['records'] if 'Name' in record
|
| 65 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
logger.info(f"Fetched {len(menu_items)} menu items for {dietary_preference}")
|
| 67 |
return jsonify({"menu_items": menu_items})
|
| 68 |
except Exception as e:
|
|
@@ -76,7 +85,7 @@ def suggest_items():
|
|
| 76 |
if not sf:
|
| 77 |
sf = get_salesforce_connection()
|
| 78 |
if not sf:
|
| 79 |
-
return jsonify({"error": "Unable to connect to Salesforce"}), 500
|
| 80 |
|
| 81 |
search_term = request.json.get('search_term', '').strip()
|
| 82 |
if not search_term:
|
|
@@ -84,10 +93,10 @@ def suggest_items():
|
|
| 84 |
|
| 85 |
try:
|
| 86 |
soql = f"SELECT Name, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{search_term}%' OR Ingredients__c LIKE '%{search_term}%' LIMIT 10"
|
| 87 |
-
logger.info(f"Executing SOQL query: {soql}")
|
| 88 |
result = sf.query(soql)
|
| 89 |
suggestions = [
|
| 90 |
-
{"name": record['Name'], "image_url": record.get('Image_URL__c', '')}
|
| 91 |
for record in result['records'] if 'Name' in record
|
| 92 |
]
|
| 93 |
logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}'")
|
|
@@ -96,14 +105,14 @@ def suggest_items():
|
|
| 96 |
logger.error(f"Failed to fetch suggestions: {str(e)}")
|
| 97 |
return jsonify({"error": "Failed to fetch suggestions from Salesforce"}), 500
|
| 98 |
|
| 99 |
-
# Fetch item details
|
| 100 |
@app.route('/get_item_details', methods=['POST'])
|
| 101 |
def get_item_details():
|
| 102 |
global sf
|
| 103 |
if not sf:
|
| 104 |
sf = get_salesforce_connection()
|
| 105 |
if not sf:
|
| 106 |
-
return jsonify({"error": "Unable to connect to Salesforce"}), 500
|
| 107 |
|
| 108 |
item_name = request.json.get('item_name', '').strip()
|
| 109 |
if not item_name:
|
|
@@ -111,7 +120,7 @@ def get_item_details():
|
|
| 111 |
|
| 112 |
try:
|
| 113 |
soql = f"SELECT Name, Description__c, Ingredients__c, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
|
| 114 |
-
logger.info(f"Executing SOQL query: {soql}")
|
| 115 |
result = sf.query(soql)
|
| 116 |
|
| 117 |
if result['totalSize'] == 0:
|
|
@@ -123,7 +132,7 @@ def get_item_details():
|
|
| 123 |
"name": record.get('Name', ''),
|
| 124 |
"description": "Description not available",
|
| 125 |
"ingredients": "Ingredients not listed",
|
| 126 |
-
"image_url": record.get('Image_URL__c', '')
|
| 127 |
}
|
| 128 |
logger.info(f"Fallback: Found '{item_name}' in menu items")
|
| 129 |
return jsonify({"item_details": item_details})
|
|
@@ -134,7 +143,7 @@ def get_item_details():
|
|
| 134 |
"name": record.get('Name', ''),
|
| 135 |
"description": record.get('Description__c', 'No description available'),
|
| 136 |
"ingredients": record.get('Ingredients__c', 'No ingredients listed'),
|
| 137 |
-
"image_url": record.get('Image_URL__c', '')
|
| 138 |
}
|
| 139 |
logger.info(f"Fetched details for '{item_name}'")
|
| 140 |
return jsonify({"item_details": item_details})
|
|
@@ -149,17 +158,16 @@ def submit_ingredients():
|
|
| 149 |
if not sf:
|
| 150 |
sf = get_salesforce_connection()
|
| 151 |
if not sf:
|
| 152 |
-
return jsonify({"error": "Unable to connect to Salesforce"}), 500
|
| 153 |
|
| 154 |
ingredients = request.json.get('ingredients', [])
|
| 155 |
if not ingredients:
|
| 156 |
return jsonify({"error": "No ingredients provided"}), 400
|
| 157 |
|
| 158 |
try:
|
| 159 |
-
# Create a new record in Ingredient_Object__c with the selected ingredients
|
| 160 |
ingredient_names = ", ".join(ingredients)
|
| 161 |
sf.Ingredient_Object__c.create({
|
| 162 |
-
'Name': f"User Selection {ingredient_names[:50]}", # Truncate
|
| 163 |
'Ingredients__c': ingredient_names
|
| 164 |
})
|
| 165 |
logger.info(f"Submitted ingredients to Salesforce: {ingredient_names}")
|
|
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
| 2 |
+
from simple_salesforce import Salesforce, SalesforceLogin
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
import os
|
| 5 |
import logging
|
| 6 |
+
import time
|
| 7 |
|
| 8 |
# Load environment variables
|
| 9 |
load_dotenv()
|
| 10 |
|
| 11 |
# Set up logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
app = Flask(__name__, template_folder='templates', static_folder='static')
|
| 16 |
|
| 17 |
+
# Salesforce connection function with retry logic
|
| 18 |
+
def get_salesforce_connection(retries=3, delay=2):
|
| 19 |
+
for attempt in range(retries):
|
| 20 |
+
try:
|
| 21 |
+
sf = Salesforce(
|
| 22 |
+
username=os.getenv('SFDC_USERNAME'),
|
| 23 |
+
password=os.getenv('SFDC_PASSWORD'),
|
| 24 |
+
security_token=os.getenv('SFDC_SECURITY_TOKEN'),
|
| 25 |
+
domain=os.getenv('SFDC_DOMAIN', 'login')
|
| 26 |
+
)
|
| 27 |
+
logger.info("Successfully connected to Salesforce")
|
| 28 |
+
return sf
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Attempt {attempt + 1}/{retries} - Error connecting to Salesforce: {str(e)}")
|
| 31 |
+
if attempt < retries - 1:
|
| 32 |
+
time.sleep(delay)
|
| 33 |
+
logger.critical("Failed to connect to Salesforce after retries")
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
# Initialize Salesforce connection globally
|
| 37 |
sf = get_salesforce_connection()
|
| 38 |
|
| 39 |
@app.route('/')
|
|
|
|
| 47 |
if not sf:
|
| 48 |
sf = get_salesforce_connection()
|
| 49 |
if not sf:
|
| 50 |
+
return jsonify({"error": "Unable to connect to Salesforce after retries"}), 500
|
| 51 |
|
| 52 |
dietary_preference = request.json.get('dietary_preference', 'both').lower()
|
| 53 |
try:
|
|
|
|
| 58 |
soql += " WHERE Category__c = 'Non-Veg'"
|
| 59 |
soql += " LIMIT 200"
|
| 60 |
|
| 61 |
+
logger.info(f"Executing SOQL query for {dietary_preference}: {soql}")
|
| 62 |
result = sf.query(soql)
|
| 63 |
menu_items = [
|
| 64 |
{
|
| 65 |
"name": record['Name'],
|
| 66 |
+
"image_url": record.get('Image_URL__c', 'https://via.placeholder.com/60'),
|
| 67 |
"category": record.get('Category__c', '')
|
| 68 |
}
|
| 69 |
for record in result['records'] if 'Name' in record
|
| 70 |
]
|
| 71 |
+
if not menu_items:
|
| 72 |
+
logger.warning(f"No items found for {dietary_preference}")
|
| 73 |
+
return jsonify({"menu_items": [], "message": f"No {dietary_preference} items found in Salesforce"})
|
| 74 |
+
|
| 75 |
logger.info(f"Fetched {len(menu_items)} menu items for {dietary_preference}")
|
| 76 |
return jsonify({"menu_items": menu_items})
|
| 77 |
except Exception as e:
|
|
|
|
| 85 |
if not sf:
|
| 86 |
sf = get_salesforce_connection()
|
| 87 |
if not sf:
|
| 88 |
+
return jsonify({"error": "Unable to connect to Salesforce after retries"}), 500
|
| 89 |
|
| 90 |
search_term = request.json.get('search_term', '').strip()
|
| 91 |
if not search_term:
|
|
|
|
| 93 |
|
| 94 |
try:
|
| 95 |
soql = f"SELECT Name, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{search_term}%' OR Ingredients__c LIKE '%{search_term}%' LIMIT 10"
|
| 96 |
+
logger.info(f"Executing SOQL query for suggestions: {soql}")
|
| 97 |
result = sf.query(soql)
|
| 98 |
suggestions = [
|
| 99 |
+
{"name": record['Name'], "image_url": record.get('Image_URL__c', 'https://via.placeholder.com/60')}
|
| 100 |
for record in result['records'] if 'Name' in record
|
| 101 |
]
|
| 102 |
logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}'")
|
|
|
|
| 105 |
logger.error(f"Failed to fetch suggestions: {str(e)}")
|
| 106 |
return jsonify({"error": "Failed to fetch suggestions from Salesforce"}), 500
|
| 107 |
|
| 108 |
+
# Fetch item details with fallback
|
| 109 |
@app.route('/get_item_details', methods=['POST'])
|
| 110 |
def get_item_details():
|
| 111 |
global sf
|
| 112 |
if not sf:
|
| 113 |
sf = get_salesforce_connection()
|
| 114 |
if not sf:
|
| 115 |
+
return jsonify({"error": "Unable to connect to Salesforce after retries"}), 500
|
| 116 |
|
| 117 |
item_name = request.json.get('item_name', '').strip()
|
| 118 |
if not item_name:
|
|
|
|
| 120 |
|
| 121 |
try:
|
| 122 |
soql = f"SELECT Name, Description__c, Ingredients__c, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
|
| 123 |
+
logger.info(f"Executing SOQL query for item details: {soql}")
|
| 124 |
result = sf.query(soql)
|
| 125 |
|
| 126 |
if result['totalSize'] == 0:
|
|
|
|
| 132 |
"name": record.get('Name', ''),
|
| 133 |
"description": "Description not available",
|
| 134 |
"ingredients": "Ingredients not listed",
|
| 135 |
+
"image_url": record.get('Image_URL__c', 'https://via.placeholder.com/60')
|
| 136 |
}
|
| 137 |
logger.info(f"Fallback: Found '{item_name}' in menu items")
|
| 138 |
return jsonify({"item_details": item_details})
|
|
|
|
| 143 |
"name": record.get('Name', ''),
|
| 144 |
"description": record.get('Description__c', 'No description available'),
|
| 145 |
"ingredients": record.get('Ingredients__c', 'No ingredients listed'),
|
| 146 |
+
"image_url": record.get('Image_URL__c', 'https://via.placeholder.com/60')
|
| 147 |
}
|
| 148 |
logger.info(f"Fetched details for '{item_name}'")
|
| 149 |
return jsonify({"item_details": item_details})
|
|
|
|
| 158 |
if not sf:
|
| 159 |
sf = get_salesforce_connection()
|
| 160 |
if not sf:
|
| 161 |
+
return jsonify({"error": "Unable to connect to Salesforce after retries"}), 500
|
| 162 |
|
| 163 |
ingredients = request.json.get('ingredients', [])
|
| 164 |
if not ingredients:
|
| 165 |
return jsonify({"error": "No ingredients provided"}), 400
|
| 166 |
|
| 167 |
try:
|
|
|
|
| 168 |
ingredient_names = ", ".join(ingredients)
|
| 169 |
sf.Ingredient_Object__c.create({
|
| 170 |
+
'Name': f"User Selection {ingredient_names[:50]}", # Truncate to fit Salesforce limits
|
| 171 |
'Ingredients__c': ingredient_names
|
| 172 |
})
|
| 173 |
logger.info(f"Submitted ingredients to Salesforce: {ingredient_names}")
|