from flask import Flask, render_template, send_from_directory, request, jsonify import requests from dotenv import load_dotenv import os import time # Load environment variables from .env file load_dotenv() app = Flask(__name__, template_folder='templates', static_folder='static') # Salesforce credentials from environment variables SFDC_USERNAME = os.getenv('SFDC_USERNAME') SFDC_PASSWORD = os.getenv('SFDC_PASSWORD') SFDC_SECURITY_TOKEN = os.getenv('SFDC_SECURITY_TOKEN') SFDC_INSTANCE_URL = os.getenv('SFDC_INSTANCE_URL', 'https://login.salesforce.com') CLIENT_ID = os.getenv('SFDC_CLIENT_ID') # Add to .env CLIENT_SECRET = os.getenv('SFDC_CLIENT_SECRET') # Add to .env # Cache the access token and its expiration access_token = None token_expiry = 0 # Function to get Salesforce access token def get_salesforce_access_token(): global access_token, token_expiry if time.time() < token_expiry - 300: # Use cached token if valid (with 5-minute buffer) return access_token auth_url = f"{SFDC_INSTANCE_URL}/services/oauth2/token" data = { 'grant_type': 'password', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'username': SFDC_USERNAME, 'password': f"{SFDC_PASSWORD}{SFDC_SECURITY_TOKEN}" } try: response = requests.post(auth_url, data=data, timeout=10) response.raise_for_status() token_data = response.json() access_token = token_data['access_token'] token_expiry = time.time() + int(token_data.get('expires_in', 3600)) # Default 1 hour print(f"New access token retrieved, expires at {time.ctime(token_expiry)}") return access_token except requests.exceptions.RequestException as e: print(f"Authentication error: {e.response.text if 'response' in e.__dict__ else str(e)}") return None # Get initial token access_token = get_salesforce_access_token() @app.route('/') def index(): return render_template('index.html') @app.route('/static/') def serve_static(filename): return send_from_directory('static', filename) @app.route('/get_ingredients', methods=['POST']) def get_ingredients(): global access_token if not access_token: access_token = get_salesforce_access_token() if not access_token: return jsonify({"error": "Failed to authenticate with Salesforce"}), 500 dietary_preference = request.json.get('dietary_preference', '').lower() # Salesforce SOQL query based on dietary preference if dietary_preference == 'veg': soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Veg', 'Both') LIMIT 200" elif dietary_preference == 'non-vegetarian': soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg', 'Both') LIMIT 200" else: soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c LIMIT 200" # Increased limit for 50+ ingredients headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } url = f"{SFDC_INSTANCE_URL}/services/data/v57.0/query/?q={soql}" try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() data = response.json() ingredients = [record['Sector_Detail_Name__c'] for record in data['records'] if 'Sector_Detail_Name__c' in record] return jsonify({"ingredients": ingredients}) except requests.exceptions.RequestException as e: error_msg = str(e) if e.response and e.response.status_code == 401: # Unauthorized, try refreshing token access_token = get_salesforce_access_token() if access_token: return get_ingredients() # Retry the request return jsonify({"error": f"Failed to fetch ingredients: {error_msg}"}), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=7860)