Spaces:
Running
Running
File size: 10,372 Bytes
de37515 b189fed de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 95eaa6a 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 de37515 0d2fb64 95eaa6a 0d2fb64 de37515 0d2fb64 de37515 b189fed |
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 |
from flask import Flask, render_template, request, jsonify
from simple_salesforce import Salesforce
from dotenv import load_dotenv
import os
import logging
import uuid
from datetime import datetime
# Load environment variables
load_dotenv()
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__, template_folder='templates', static_folder='static')
# Salesforce connection function
def get_salesforce_connection():
try:
sf = Salesforce(
username=os.getenv('SFDC_USERNAME'),
password=os.getenv('SFDC_PASSWORD'),
security_token=os.getenv('SFDC_SECURITY_TOKEN'),
domain=os.getenv('SFDC_DOMAIN', 'login')
)
logger.info("Successfully connected to Salesforce")
return sf
except Exception as e:
logger.error(f"Error connecting to Salesforce: {str(e)}")
return None
# Initialize Salesforce connection
sf = get_salesforce_connection()
@app.route('/')
def index():
return render_template('chef-bot.html')
@app.route('/get_menu_items', methods=['POST'])
def get_menu_items():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
logger.error("Salesforce connection failed after retry")
return jsonify({"error": "Unable to connect to Salesforce"}), 500
data = request.json
dietary_preference = data.get('dietary_preference', 'both').lower()
search_term = data.get('search_term', '').strip()
try:
items = []
# Query Sector_Detail__c for dietary preferences
if not search_term:
soql_sector = "SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c"
if dietary_preference == 'vegetarian':
soql_sector += " WHERE Category__c = 'Veg'"
elif dietary_preference == 'non-vegetarian':
soql_sector += " WHERE Category__c = 'Non-Veg'"
soql_sector += " LIMIT 200"
logger.info(f"Executing SOQL query for Sector_Detail__c: {soql_sector}")
result_sector = sf.query(soql_sector)
sector_items = [
{
"name": record['Name'],
"image_url": record.get('Image_URL__c', ''),
"category": record.get('Category__c', ''),
"description": record.get('Description__c', 'No description available'),
"source": "Sector_Detail__c"
}
for record in result_sector['records'] if 'Name' in record
]
items.extend(sector_items)
# Query Menu_Item__c
soql_menu = "SELECT Name, Description__c, Image1__c, Ingredientsinfo__c, NutritionalInfo__c, Price__c, Sector__c, Spice_Levels__c, Veg_NonVeg__c, Category__c, Dynamic_Dish__c FROM Menu_Item__c"
if search_term:
soql_menu += f" WHERE Name LIKE '%{search_term}%'"
elif dietary_preference == 'vegetarian':
soql_menu += " WHERE Veg_NonVeg__c = 'Vegetarian'"
elif dietary_preference == 'non-vegetarian':
soql_menu += " WHERE Veg_NonVeg__c = 'Non-Vegetarian'"
soql_menu += " LIMIT 200"
logger.info(f"Executing SOQL query for Menu_Item__c: {soql_menu}")
result_menu = sf.query(soql_menu)
menu_items = [
{
"name": record['Name'],
"description": record.get('Description__c', 'No description available'),
"image_url": record.get('Image1__c', ''),
"ingredients": record.get('Ingredientsinfo__c', ''),
"nutritional_info": record.get('NutritionalInfo__c', ''),
"price": record.get('Price__c', 0.0),
"sector": record.get('Sector__c', ''),
"spice_levels": record.get('Spice_Levels__c', ''),
"veg_nonveg": record.get('Veg_NonVeg__c', ''),
"category": record.get('Category__c', ''),
"dynamic_dish": record.get('Dynamic_Dish__c', False),
"source": "Menu_Item__c"
}
for record in result_menu['records'] if 'Name' in record
]
items.extend(menu_items)
logger.info(f"Fetched {len(items)} items (Sector_Detail__c: {len([i for i in items if i['source'] == 'Sector_Detail__c'])}, Menu_Item__c: {len([i for i in items if i['source'] == 'Menu_Item__c'])}) for {dietary_preference or search_term}")
return jsonify({"menu_items": items})
except Exception as e:
logger.error(f"Failed to fetch items: {str(e)}")
return jsonify({"error": f"Failed to fetch items from Salesforce: {str(e)}"}), 500
@app.route('/get_sector_item_details', methods=['POST'])
def get_sector_item_details():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Unable to connect to Salesforce"}), 500
item_name = request.json.get('item_name', '').strip()
if not item_name:
return jsonify({"error": "Item name is required"}), 400
try:
soql = f"SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
logger.info(f"Executing SOQL query: {soql}")
result = sf.query(soql)
if result['totalSize'] == 0:
return jsonify({"error": f"No item found matching '{item_name}' in Sector_Detail__c"}), 404
record = result['records'][0]
item_details = {
"name": record.get('Name', ''),
"image_url": record.get('Image_URL__c', 'https://via.placeholder.com/30'),
"category": record.get('Category__c', ''),
"description": record.get('Description__c', 'No description available'),
"source": "Sector_Detail__c"
}
logger.info(f"Fetched details for '{item_name}' from Sector_Detail__c")
return jsonify({"item_details": item_details})
except Exception as e:
logger.error(f"Failed to fetch item details from Sector_Detail__c: {str(e)}")
return jsonify({"error": f"Failed to fetch item details from Salesforce: {str(e)}"}), 500
@app.route('/suggest_items', methods=['POST'])
def suggest_items():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Unable to connect to Salesforce"}), 500
search_term = request.json.get('search_term', '').strip()
if not search_term:
return jsonify({"error": "Search term is required"}), 400
try:
soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{search_term}%' LIMIT 10"
logger.info(f"Executing SOQL query: {soql}")
result = sf.query(soql)
suggestions = [
{"name": record['Ingredient_Name__c'], "image_url": record.get('Image_URL__c', '')}
for record in result['records'] if 'Ingredient_Name__c' in record
]
logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}'")
return jsonify({"suggestions": suggestions})
except Exception as e:
logger.error(f"Failed to fetch suggestions: {str(e)}")
return jsonify({"error": f"Failed to fetch suggestions: {str(e)}"}), 500
@app.route('/get_item_details', methods=['POST'])
def get_item_details():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Unable to connect to Salesforce"}), 500
item_name = request.json.get('item_name', '').strip()
if not item_name:
return jsonify({"error": "Item name is required"}), 400
try:
soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{item_name}%' LIMIT 1"
logger.info(f"Executing SOQL query: {soql}")
result = sf.query(soql)
if result['totalSize'] == 0:
return jsonify({"error": f"No item found matching '{item_name}' in Ingredient_Object__c"}), 404
record = result['records'][0]
item_details = {
"name": record.get('Ingredient_Name__c', ''),
"image_url": record.get('Image_URL__c', ''),
"source": "Ingredient_Object__c"
}
logger.info(f"Fetched details for '{item_name}' from Ingredient_Object__c")
return jsonify({"item_details": item_details})
except Exception as e:
logger.error(f"Failed to fetch item details: {str(e)}")
return jsonify({"error": f"Failed to fetch item details: {str(e)}"}), 500
@app.route('/submit_items', methods=['POST'])
def submit_items():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Unable to connect to Salesforce"}), 500
items = request.json.get('items', [])
custom_order_name = request.json.get('custom_order_name', '')
if not items:
return jsonify({"error": "No items to submit"}), 400
try:
ingredient_name = custom_order_name or f"Order_{datetime.now().strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}"
item_names = ', '.join(item['name'] for item in items)
description = f"Contains: {item_names}"
for item in items:
item_description = item['description']
if item.get('additionalIngredients'):
item_description += f", with {', '.join(item['additionalIngredients'])}"
sf.Ingredient_Object__c.create({
'Ingredient_Name__c': ingredient_name,
'Category__c': item.get('category', ''),
'Description__c': f"{item_description} - {description}",
'Image_URL__c': item.get('image_url', ''),
'Quantity__c': item.get('quantity', 1)
})
logger.info(f"Submitted {len(items)} items under {ingredient_name}")
return jsonify({"success": f"Submitted {len(items)} items under {ingredient_name}", "ingredient_name": ingredient_name})
except Exception as e:
logger.error(f"Failed to submit items: {str(e)}")
return jsonify({"error": f"Failed to submit items: {str(e)}"}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=7860) |