from flask import Flask, render_template, request, jsonify from simple_salesforce import Salesforce from dotenv import load_dotenv import os # Load environment variables from .env file load_dotenv() 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') ) return sf except Exception as e: print(f"Error connecting to Salesforce: {e}") return None # Initialize Salesforce connection (can be moved to request scope in production) sf = get_salesforce_connection() @app.route('/') def index(): return render_template('index.html') @app.route('/get_ingredients', methods=['POST']) def get_ingredients(): global sf if not sf: sf = get_salesforce_connection() if not sf: return jsonify({"error": "Failed to connect to Salesforce"}), 500 dietary_preference = request.json.get('dietary_preference', '').lower() # Validate and map dietary preference to SOQL condition preference_map = { 'vegetarian': "Category__c = 'Veg'", 'non-vegetarian': "Category__c = 'Non-Veg'" } condition = preference_map.get(dietary_preference, "1=1") # Default to all if invalid try: soql = f"SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE {condition} LIMIT 200" result = sf.query(soql) ingredients = [ {"name": record['Name'], "image_url": record.get('Image_URL__c', '')} for record in result['records'] if 'Name' in record ] return jsonify({"ingredients": ingredients}) except Exception as e: return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=7860)