lokesh341 commited on
Commit
de37515
·
verified ·
1 Parent(s): 8d3c23a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +238 -0
app.py CHANGED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ from simple_salesforce import Salesforce
3
+ from dotenv import load_dotenv
4
+ import os
5
+ import logging
6
+ import uuid
7
+ from datetime import datetime
8
+
9
+ # Load environment variables
10
+ load_dotenv()
11
+
12
+ # Set up logging
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ app = Flask(__name__, template_folder='templates', static_folder='static')
17
+
18
+ # Salesforce connection function
19
+ def get_salesforce_connection():
20
+ try:
21
+ sf = Salesforce(
22
+ username=os.getenv('SFDC_USERNAME'),
23
+ password=os.getenv('SFDC_PASSWORD'),
24
+ security_token=os.getenv('SFDC_SECURITY_TOKEN'),
25
+ domain=os.getenv('SFDC_DOMAIN', 'login')
26
+ )
27
+ logger.info("Successfully connected to Salesforce")
28
+ return sf
29
+ except Exception as e:
30
+ logger.error(f"Error connecting to Salesforce: {str(e)}")
31
+ return None
32
+
33
+ # Initialize Salesforce connection
34
+ sf = get_salesforce_connection()
35
+
36
+ @app.route('/')
37
+ def index():
38
+ return render_template('index.html')
39
+
40
+ @app.route('/get_menu_items', methods=['POST'])
41
+ def get_menu_items():
42
+ global sf
43
+ if not sf:
44
+ sf = get_salesforce_connection()
45
+ if not sf:
46
+ logger.error("Salesforce connection failed after retry")
47
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
48
+
49
+ data = request.json
50
+ dietary_preference = data.get('dietary_preference', 'both').lower()
51
+ search_term = data.get('search_term', '').strip()
52
+ try:
53
+ items = []
54
+ # Query Sector_Detail__c for dietary preferences
55
+ if not search_term:
56
+ soql_sector = "SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c"
57
+ if dietary_preference == 'vegetarian':
58
+ soql_sector += " WHERE Category__c = 'Veg'"
59
+ elif dietary_preference == 'non-vegetarian':
60
+ soql_sector += " WHERE Category__c = 'Non-Veg'"
61
+ soql_sector += " LIMIT 200"
62
+ logger.info(f"Executing SOQL query for Sector_Detail__c: {soql_sector}")
63
+ result_sector = sf.query(soql_sector)
64
+ sector_items = [
65
+ {
66
+ "name": record['Name'],
67
+ "image_url": record.get('Image_URL__c', ''),
68
+ "category": record.get('Category__c', ''),
69
+ "description": record.get('Description__c', 'No description available'),
70
+ "source": "Sector_Detail__c"
71
+ }
72
+ for record in result_sector['records'] if 'Name' in record
73
+ ]
74
+ items.extend(sector_items)
75
+
76
+ # Query Menu_Item__c
77
+ soql_menu = "SELECT Name, Description__c, Image1__c, Ingredientsinfo__c, NutritionalInfo__c, Price__c, Sector__c, Spice_Levels__c, Veg_NonVeg__c, Category__c, Dynamic_Dish__c FROM Menu_Item__c"
78
+ if search_term:
79
+ soql_menu += f" WHERE Name LIKE '%{search_term}%'"
80
+ elif dietary_preference == 'vegetarian':
81
+ soql_menu += " WHERE Veg_NonVeg__c = 'Vegetarian'"
82
+ elif dietary_preference == 'non-vegetarian':
83
+ soql_menu += " WHERE Veg_NonVeg__c = 'Non-Vegetarian'"
84
+ soql_menu += " LIMIT 200"
85
+ logger.info(f"Executing SOQL query for Menu_Item__c: {soql_menu}")
86
+ result_menu = sf.query(soql_menu)
87
+ menu_items = [
88
+ {
89
+ "name": record['Name'],
90
+ "description": record.get('Description__c', 'No description available'),
91
+ "image_url": record.get('Image1__c', ''),
92
+ "ingredients": record.get('Ingredientsinfo__c', ''),
93
+ "nutritional_info": record.get('NutritionalInfo__c', ''),
94
+ "price": record.get('Price__c', 0.0),
95
+ "sector": record.get('Sector__c', ''),
96
+ "spice_levels": record.get('Spice_Levels__c', ''),
97
+ "veg_nonveg": record.get('Veg_NonVeg__c', ''),
98
+ "category": record.get('Category__c', ''),
99
+ "dynamic_dish": record.get('Dynamic_Dish__c', False),
100
+ "source": "Menu_Item__c"
101
+ }
102
+ for record in result_menu['records'] if 'Name' in record
103
+ ]
104
+ items.extend(menu_items)
105
+
106
+ logger.info(f"Fetched {len(items)} items (Sector_Detail__c: {len([i for i in items if i['source'] == 'Sector_Detail__c'])}, Menu_Item__c: {len([i for i in items if i['source'] == 'Menu_Item__c'])}) for {dietary_preference or search_term}")
107
+ return jsonify({"menu_items": items})
108
+ except Exception as e:
109
+ logger.error(f"Failed to fetch items: {str(e)}")
110
+ return jsonify({"error": f"Failed to fetch items from Salesforce: {str(e)}"}), 500
111
+
112
+ @app.route('/get_sector_item_details', methods=['POST'])
113
+ def get_sector_item_details():
114
+ global sf
115
+ if not sf:
116
+ sf = get_salesforce_connection()
117
+ if not sf:
118
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
119
+
120
+ item_name = request.json.get('item_name', '').strip()
121
+ if not item_name:
122
+ return jsonify({"error": "Item name is required"}), 400
123
+
124
+ try:
125
+ soql = f"SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
126
+ logger.info(f"Executing SOQL query: {soql}")
127
+ result = sf.query(soql)
128
+
129
+ if result['totalSize'] == 0:
130
+ return jsonify({"error": f"No item found matching '{item_name}' in Sector_Detail__c"}), 404
131
+
132
+ record = result['records'][0]
133
+ item_details = {
134
+ "name": record.get('Name', ''),
135
+ "image_url": record.get('Image_URL__c', 'https://via.placeholder.com/30'),
136
+ "category": record.get('Category__c', ''),
137
+ "description": record.get('Description__c', 'No description available'),
138
+ "source": "Sector_Detail__c"
139
+ }
140
+ logger.info(f"Fetched details for '{item_name}' from Sector_Detail__c")
141
+ return jsonify({"item_details": item_details})
142
+ except Exception as e:
143
+ logger.error(f"Failed to fetch item details from Sector_Detail__c: {str(e)}")
144
+ return jsonify({"error": f"Failed to fetch item details from Salesforce: {str(e)}"}), 500
145
+
146
+ @app.route('/suggest_items', methods=['POST'])
147
+ def suggest_items():
148
+ global sf
149
+ if not sf:
150
+ sf = get_salesforce_connection()
151
+ if not sf:
152
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
153
+
154
+ search_term = request.json.get('search_term', '').strip()
155
+ if not item_name:
156
+ return jsonify({"error": "Search term is required"}), 400
157
+
158
+ try:
159
+ soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{search_term}%' LIMIT 10"
160
+ logger.info(f"Executing SOQL query: {soql}")
161
+ result = sf.query(soql)
162
+ suggestions = [
163
+ {"name": record['Ingredient_Name__c'], "image_url": record.get('Image_URL__c', '')}
164
+ for record in result['records'] if 'Ingredient_Name__c' in record
165
+ ]
166
+ logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}'")
167
+ return jsonify({"suggestions": suggestions})
168
+ except Exception as e:
169
+ logger.error(f"Failed to fetch suggestions: {str(e)}")
170
+ return jsonify({"error": f"Failed to fetch suggestions: {str(e)}"}), 500
171
+
172
+ @app.route('/get_item_details', methods=['POST'])
173
+ def get_item_details():
174
+ global sf
175
+ if not sf:
176
+ sf = get_salesforce_connection()
177
+ if not sf:
178
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
179
+
180
+ item_name = request.json.get('item_name', '').strip()
181
+ if not item_name:
182
+ return jsonify({"error": "Item name is required"}), 400
183
+
184
+ try:
185
+ soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{item_name}%' LIMIT 1"
186
+ logger.info(f"Executing SOQL query: {soql}")
187
+ result = sf.query(soql)
188
+
189
+ if result['totalSize'] == 0:
190
+ return jsonify({"error": f"No item found matching '{item_name}' in Ingredient_Object__c"}), 404
191
+
192
+ record = result['records'][0]
193
+ item_details = {
194
+ "name": record.get('Ingredient_Name__c', ''),
195
+ "image_url": record.get('Image_URL__c', ''),
196
+ "source": "Ingredient_Object__c"
197
+ }
198
+ logger.info(f"Fetched details for '{item_name}' from Ingredient_Object__c")
199
+ return jsonify({"item_details": item_details})
200
+ except Exception as e:
201
+ logger.error(f"Failed to fetch item details: {str(e)}")
202
+ return jsonify({"error": f"Failed to fetch item details: {str(e)}"}), 500
203
+
204
+ @app.route('/submit_items', methods=['POST'])
205
+ def submit_items():
206
+ global sf
207
+ if not sf:
208
+ sf = get_salesforce_connection()
209
+ if not sf:
210
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
211
+
212
+ items = request.json.get('items', [])
213
+ custom_order_name = request.json.get('custom_order_name', '')
214
+ if not items:
215
+ return jsonify({"error": "No items to submit"}), 400
216
+
217
+ try:
218
+ ingredient_name = custom_order_name or f"Order_{datetime.now().strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}"
219
+ item_names = ', '.join(item['name'] for item in items)
220
+ description = f"Contains: {item_names}"
221
+
222
+ for item in items:
223
+ sf.Ingredient_Object__c.create({
224
+ 'Ingredient_Name__c': ingredient_name,
225
+ 'Category__c': item.get('category', ''),
226
+ 'Description__c': f"{item.get('description', 'No description')} - {description}",
227
+ 'Image_URL__c': item.get('image_url', ''),
228
+ 'Quantity__c': item.get('quantity', 1)
229
+ })
230
+
231
+ logger.info(f"Submitted {len(items)} items under {ingredient_name}")
232
+ return jsonify({"success": f"Submitted {len(items)} items under {ingredient_name}", "ingredient_name": ingredient_name})
233
+ except Exception as e:
234
+ logger.error(f"Failed to submit items: {str(e)}")
235
+ return jsonify({"error": f"Failed to submit items: {str(e)}"}), 500
236
+
237
+ if __name__ == '__main__':
238
+ app.run(debug=True, host='0.0.0.0', port=7860)