lokesh341's picture
Update app.py
427c1b1 verified
raw
history blame
4.85 kB
from flask import Flask, render_template, request, jsonify
from simple_salesforce import Salesforce
from dotenv import load_dotenv
import os
import logging
# Load environment variables from .env file
load_dotenv()
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__, template_folder='templates', static_folder='static')
# Function to get Salesforce connection
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: {e}")
return None
# Initialize Salesforce connection
sf = get_salesforce_connection()
@app.route('/')
def index():
return render_template('index.html')
# Fetch all menu items (names and images) from Salesforce
@app.route('/get_menu_items', methods=['GET'])
def get_menu_items():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Failed to connect to Salesforce"}), 500
try:
soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c LIMIT 200"
logger.info(f"Executing SOQL query: {soql}")
result = sf.query(soql)
menu_items = [
{"name": record['Name'], "image_url": record.get('Image_URL__c', '')}
for record in result['records'] if 'Name' in record
]
logger.info(f"Fetched {len(menu_items)} 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: {str(e)}"}), 500
# Fetch details (description and ingredients) for a specific menu item
@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": "Failed 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:
# Query Salesforce for the specific item
soql = f"SELECT Name, Description__c, Ingredients__c, Image_URL__c FROM Sector_Detail__c WHERE Name = '{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 with name '{item_name}'"}), 404
record = result['records'][0]
item_details = {
"name": record.get('Name', ''),
"description": record.get('Description__c', 'No description available'),
"ingredients": record.get('Ingredients__c', 'No ingredients listed'),
"image_url": record.get('Image_URL__c', '')
}
logger.info(f"Fetched details for {item_name}: {item_details}")
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
# Suggest suitable items based on user input (e.g., "chicken")
@app.route('/suggest_items', methods=['POST'])
def suggest_items():
global sf
if not sf:
sf = get_salesforce_connection()
if not sf:
return jsonify({"error": "Failed to connect to Salesforce"}), 500
search_term = request.json.get('search_term', '').strip().lower()
if not search_term:
return jsonify({"error": "Search term is required"}), 400
try:
# Search for items where Name or Ingredients__c contains the search term
soql = f"SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE Name LIKE '%{search_term}%' OR Ingredients__c LIKE '%{search_term}%' LIMIT 10"
logger.info(f"Executing SOQL query: {soql}")
result = sf.query(soql)
suggestions = [
{"name": record['Name'], "image_url": record.get('Image_URL__c', '')}
for record in result['records'] if 'Name' in record
]
logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}': {suggestions}")
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
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=7860)