File size: 6,838 Bytes
6a477c5
 
 
 
 
71978cc
59fda72
6a477c5
4be2e38
6a477c5
 
 
540f4a3
6a477c5
4be2e38
59fda72
6a477c5
 
 
 
 
 
 
 
 
 
 
 
 
71978cc
59fda72
6a477c5
a2f1a4d
6a477c5
 
 
4be2e38
59fda72
 
427c1b1
6a477c5
 
 
 
567f5b5
71978cc
59fda72
427c1b1
40bbbf4
59fda72
 
 
 
 
 
427c1b1
 
 
59fda72
 
 
 
 
427c1b1
 
59fda72
427c1b1
 
 
567f5b5
427c1b1
59fda72
 
 
 
 
 
 
 
 
 
 
 
 
 
40bbbf4
59fda72
 
 
 
 
 
 
 
 
 
 
 
40bbbf4
427c1b1
 
 
 
 
 
567f5b5
427c1b1
 
 
 
a2f1a4d
6a477c5
40bbbf4
427c1b1
 
540f4a3
427c1b1
40bbbf4
59fda72
 
 
 
 
 
 
 
 
 
 
 
427c1b1
 
 
 
 
 
 
 
59fda72
427c1b1
 
 
567f5b5
427c1b1
40bbbf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a477c5
 
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
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
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: {e}")
        return None

# Initialize Salesforce connection
sf = get_salesforce_connection()

@app.route('/')
def index():
    return render_template('index.html')

# Fetch menu items with dietary filter
@app.route('/get_menu_items', methods=['POST'])
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

    dietary_preference = request.json.get('dietary_preference', 'both').lower()
    try:
        soql = "SELECT Name, Image_URL__c, Category__c FROM Ingredient_Object__c"
        if dietary_preference == 'vegetarian':
            soql += " WHERE Category__c = 'Veg'"
        elif dietary_preference == 'non-vegetarian':
            soql += " WHERE Category__c = 'Non-Veg'"
        soql += " 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', ''),
                "category": record.get('Category__c', '')
            }
            for record in result['records'] if 'Name' in record
        ]
        logger.info(f"Fetched {len(menu_items)} menu items for {dietary_preference}")
        return jsonify({"menu_items": menu_items})
    except Exception as e:
        logger.error(f"Failed to fetch menu items: {str(e)}")
        return jsonify({"error": "Failed to fetch menu items from Salesforce"}), 500

# Fetch suggestions based on search term
@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 Name, Image_URL__c FROM Ingredient_Object__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}'")
        return jsonify({"suggestions": suggestions})
    except Exception as e:
        logger.error(f"Failed to fetch suggestions: {str(e)}")
        return jsonify({"error": "Failed to fetch suggestions from Salesforce"}), 500

# Fetch item details
@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 Name, Description__c, Ingredients__c, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
        logger.info(f"Executing SOQL query: {soql}")
        result = sf.query(soql)

        if result['totalSize'] == 0:
            soql_fallback = f"SELECT Name, Image_URL__c FROM Ingredient_Object__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
            result_fallback = sf.query(soql_fallback)
            if result_fallback['totalSize'] > 0:
                record = result_fallback['records'][0]
                item_details = {
                    "name": record.get('Name', ''),
                    "description": "Description not available",
                    "ingredients": "Ingredients not listed",
                    "image_url": record.get('Image_URL__c', '')
                }
                logger.info(f"Fallback: Found '{item_name}' in menu items")
                return jsonify({"item_details": item_details})
            return jsonify({"error": f"No item found matching '{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}'")
        return jsonify({"item_details": item_details})
    except Exception as e:
        logger.error(f"Failed to fetch item details: {str(e)}")
        return jsonify({"error": "Failed to fetch item details from Salesforce"}), 500

# Submit selected items to Salesforce
@app.route('/submit_ingredients', methods=['POST'])
def submit_ingredients():
    global sf
    if not sf:
        sf = get_salesforce_connection()
        if not sf:
            return jsonify({"error": "Unable to connect to Salesforce"}), 500

    ingredients = request.json.get('ingredients', [])
    if not ingredients:
        return jsonify({"error": "No ingredients provided"}), 400

    try:
        # Create a new record in Ingredient_Object__c with the selected ingredients
        ingredient_names = ", ".join(ingredients)
        sf.Ingredient_Object__c.create({
            'Name': f"User Selection {ingredient_names[:50]}",  # Truncate if too long
            'Ingredients__c': ingredient_names
        })
        logger.info(f"Submitted ingredients to Salesforce: {ingredient_names}")
        return jsonify({"success": "Ingredients submitted successfully"})
    except Exception as e:
        logger.error(f"Failed to submit ingredients: {str(e)}")
        return jsonify({"error": "Failed to submit ingredients to Salesforce"}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=7860)