Spaces:
Sleeping
Sleeping
| from flask import Flask, render_template, request, jsonify, send_from_directory | |
| 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.DEBUG) | |
| 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() | |
| def index(): | |
| return render_template('index.html') | |
| def static_files(filename): | |
| return send_from_directory(app.static_folder, filename) | |
| def get_ingredients(): | |
| global sf | |
| if not sf: | |
| sf = get_salesforce_connection() | |
| if not sf: | |
| return jsonify({"error": "Unable to connect to Salesforce"}), 500 | |
| data = request.json | |
| dietary_preference = data.get('dietary_preference', 'both').lower() | |
| try: | |
| category_map = { | |
| 'vegetarian': 'Veg', | |
| 'non-vegetarian': 'Non-Veg', | |
| 'chicken': 'Non-Veg', | |
| 'beef': 'Non-Veg', | |
| 'lamb': 'Non-Veg', | |
| 'both': 'both' | |
| } | |
| category = category_map.get(dietary_preference, 'both') | |
| soql = f"SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c WHERE Category__c = '{category}'" | |
| soql += " LIMIT 200" | |
| logger.debug(f"Executing SOQL query for Sector_Detail__c: {soql}") | |
| result = sf.query(soql) | |
| ingredients = [ | |
| { | |
| "name": record['Name'], | |
| "image_url": record.get('Image_URL__c', ''), | |
| "category": record.get('Category__c', '') | |
| } | |
| for record in result['records'] if 'Name' in record | |
| ] | |
| logger.debug(f"Fetched {len(ingredients)} ingredients from Sector_Detail__c") | |
| return jsonify({"ingredients": ingredients}) | |
| except Exception as e: | |
| logger.error(f"Failed to fetch ingredients: {str(e)}") | |
| return jsonify({"error": f"Failed to fetch ingredients from Salesforce: {str(e)}"}), 500 | |
| def get_menu_items(): | |
| global sf | |
| if not sf: | |
| sf = get_salesforce_connection() | |
| if not sf: | |
| return jsonify({"error": "Unable to connect to Salesforce"}), 500 | |
| data = request.json | |
| ingredient_names = data.get('ingredient_names', '') | |
| category = data.get('category', '') | |
| try: | |
| soql = "SELECT Name, Description__c, Image1__c, Image2__c, Price__c, Section__c, Veg_NonVeg__c, Total_Ordered__c FROM Menu_Item__c" | |
| conditions = [] | |
| if ingredient_names: | |
| words = ingredient_names.split() | |
| name_conditions = [f"Name LIKE '%{word}%'" for word in words] | |
| conditions.append(f"({' OR '.join(name_conditions)})") | |
| if category: | |
| if category.lower() == 'vegetarian': | |
| conditions.append("Veg_NonVeg__c = 'Vegetarian'") | |
| elif category.lower() == 'non-vegetarian': | |
| conditions.append("Veg_NonVeg__c = 'Non-Vegetarian'") | |
| if conditions: | |
| soql += " WHERE " + " AND ".join(conditions) | |
| soql += " LIMIT 200" | |
| logger.debug(f"Executing SOQL query for Menu_Item__c: {soql}") | |
| result = sf.query(soql) | |
| menu_items = [ | |
| { | |
| "name": record['Name'], | |
| "description": record.get('Description__c', 'No description available'), | |
| "image_url": record.get('Image1__c', '') or record.get('Image2__c', ''), | |
| "price": record.get('Price__c', 0.0), | |
| "section": record.get('Section__c', ''), | |
| "veg_nonveg": record.get('Veg_NonVeg__c', ''), | |
| "total_ordered": record.get('Total_Ordered__c', 0) | |
| } | |
| for record in result['records'] if 'Name' in record | |
| ] | |
| logger.debug(f"Fetched {len(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 from Salesforce: {str(e)}"}), 500 | |
| def submit_customization_ingredients(): | |
| global sf | |
| if not sf: | |
| sf = get_salesforce_connection() | |
| if not sf: | |
| return jsonify({"error": "Unable to connect to Salesforce"}), 500 | |
| data = request.json | |
| items = data.get('items', []) | |
| menu_item = data.get('menu_item', {}) | |
| ingredients = data.get('ingredients', []) | |
| instructions = data.get('instructions', '') | |
| try: | |
| if items: # Cart submission | |
| ingredient_name = f"Order_{datetime.now().strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}" | |
| for item in items: | |
| description = f"{item['name']} ({item.get('instructions', 'No instructions')})" | |
| if item.get('ingredients'): | |
| description += f", Ingredients: {', '.join(i['name'] for i in item['ingredients'])}" | |
| sf.Ingredient_Object__c.create({ | |
| 'Ingredient_Name__c': ingredient_name, | |
| 'Category__c': item.get('veg_nonveg', ''), | |
| 'Description__c': description, | |
| 'Image_URL__c': item.get('image_url', ''), | |
| 'Quantity__c': 1, | |
| 'Ingredientsinfo__c': item.get('instructions', '') | |
| }) | |
| logger.debug(f"Submitted {len(items)} items under {ingredient_name}") | |
| return jsonify({"success": True, "message": f"Submitted {len(items)} items"}) | |
| elif menu_item: # Single item customization | |
| ingredient_name = f"Custom_{menu_item['name']}_{uuid.uuid4().hex[:8]}" | |
| description = f"{menu_item['name']} ({instructions or 'No instructions'})" | |
| if ingredients: | |
| description += f", Ingredients: {', '.join(i['name'] for i in ingredients)}" | |
| sf.Ingredient_Object__c.create({ | |
| 'Ingredient_Name__c': ingredient_name, | |
| 'Category__c': menu_item.get('veg_nonveg', ''), | |
| 'Description__c': description, | |
| 'Image_URL__c': menu_item.get('image_url', ''), | |
| 'Quantity__c': 1, | |
| 'Ingredientsinfo__c': instructions | |
| }) | |
| logger.debug(f"Submitted customization for {menu_item['name']}") | |
| return jsonify({"success": True, "message": "Customization submitted"}) | |
| else: | |
| return jsonify({"error": "No items or menu item provided"}), 400 | |
| except Exception as e: | |
| logger.error(f"Failed to submit: {str(e)}") | |
| return jsonify({"error": f"Failed to submit: {str(e)}"}), 500 | |
| if __name__ == '__main__': | |
| app.run(debug=True, host='0.0.0.0', port=7860) |