lokesh341 commited on
Commit
16defa4
·
verified ·
1 Parent(s): 3535091

Update menu.py

Browse files
Files changed (1) hide show
  1. menu.py +104 -26
menu.py CHANGED
@@ -1,7 +1,13 @@
1
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
2
  import os
 
 
3
  from salesforce import get_salesforce_connection
4
 
 
 
 
 
5
  menu_blueprint = Blueprint('menu', __name__)
6
 
7
  # Initialize Salesforce connection
@@ -17,7 +23,7 @@ SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "C
17
  if not os.path.exists(PLACEHOLDER_PATH):
18
  with open(PLACEHOLDER_PATH, 'wb') as f:
19
  f.close()
20
- print(f"Created placeholder video at {PLACEHOLDER_PATH}")
21
 
22
  def get_valid_video_path(item_name, video_url=None):
23
  """Get valid video path for item with placeholder fallback."""
@@ -31,7 +37,7 @@ def get_valid_video_path(item_name, video_url=None):
31
  if not os.path.exists(PLACEHOLDER_PATH):
32
  with open(PLACEHOLDER_PATH, 'wb') as f:
33
  f.close()
34
- print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
35
  return f"/static/{PLACEHOLDER_VIDEO}"
36
 
37
  @menu_blueprint.route("/menu", methods=["GET", "POST"])
@@ -55,13 +61,20 @@ def menu():
55
  user_image = session.get('user_image') # Add avatar image from session
56
 
57
  # Fetch user referral and reward points
58
- user_query = f"SELECT Referral__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
59
  user_result = sf.query(user_query)
60
  if not user_result.get('records'):
61
  return redirect(url_for('login'))
62
 
63
- referral_code = user_result['records'][0].get('Referral__c', 'N/A')
64
- reward_points = user_result['records'][0].get('Reward_Points__c', 0)
 
 
 
 
 
 
 
65
 
66
  # Get cart item count
67
  cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
@@ -152,33 +165,98 @@ def menu():
152
  user_name=user_name,
153
  first_letter=first_letter,
154
  cart_item_count=cart_item_count,
155
- user_image=user_image # Pass user_image to template
 
156
  )
157
 
158
  @menu_blueprint.route('/upload_avatar', methods=['POST'])
159
  def upload_avatar():
160
- data = request.get_json()
161
- if not data or 'image' not in data:
162
- return jsonify({'success': False, 'error': 'No image data provided'})
163
-
164
- image_data = data['image']
165
- # Validate base64 image
166
- if not image_data.startswith('data:image/'):
167
- return jsonify({'success': False, 'error': 'Invalid image format'})
168
-
169
- # Limit size to ~1MB (base64 encoded size)
170
- if len(image_data) > 1_400_000:
171
- return jsonify({'success': False, 'error': 'Image too large (max 1MB)'})
172
-
173
- session['user_image'] = image_data
174
- return jsonify({'success': True, 'image': image_data})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  @menu_blueprint.route('/delete_avatar', methods=['POST'])
177
  def delete_avatar():
178
- if 'user_image' in session:
179
- session.pop('user_image', None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  return jsonify({'success': True})
181
- return jsonify({'success': False, 'error': 'No image to delete'})
 
 
 
182
 
183
  @menu_blueprint.route('/api/addons', methods=['GET'])
184
  def get_addons():
@@ -216,7 +294,7 @@ def get_addons():
216
  return jsonify({"success": True, "addons": formatted_addons})
217
 
218
  except Exception as e:
219
- print(f"Error fetching addons: {str(e)}")
220
  return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
221
 
222
  @menu_blueprint.route('/cart/add', methods=['POST'])
@@ -305,5 +383,5 @@ def add_to_cart():
305
  except ValueError as e:
306
  return jsonify({"success": False, "error": f"Invalid data format: {str(e)}"}), 400
307
  except Exception as e:
308
- print(f"Error adding item to cart: {str(e)}")
309
  return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500
 
1
  from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
2
  import os
3
+ import base64
4
+ import logging
5
  from salesforce import get_salesforce_connection
6
 
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.DEBUG)
9
+ logger = logging.getLogger(__name__)
10
+
11
  menu_blueprint = Blueprint('menu', __name__)
12
 
13
  # Initialize Salesforce connection
 
23
  if not os.path.exists(PLACEHOLDER_PATH):
24
  with open(PLACEHOLDER_PATH, 'wb') as f:
25
  f.close()
26
+ logger.info(f"Created placeholder video at {PLACEHOLDER_PATH}")
27
 
28
  def get_valid_video_path(item_name, video_url=None):
29
  """Get valid video path for item with placeholder fallback."""
 
37
  if not os.path.exists(PLACEHOLDER_PATH):
38
  with open(PLACEHOLDER_PATH, 'wb') as f:
39
  f.close()
40
+ logger.info(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
41
  return f"/static/{PLACEHOLDER_VIDEO}"
42
 
43
  @menu_blueprint.route("/menu", methods=["GET", "POST"])
 
61
  user_image = session.get('user_image') # Add avatar image from session
62
 
63
  # Fetch user referral and reward points
64
+ user_query = f"SELECT Id, Referral__c, Reward_Points__c, Avatar__c FROM Customer_Login__c WHERE Email__c = '{user_email}'"
65
  user_result = sf.query(user_query)
66
  if not user_result.get('records'):
67
  return redirect(url_for('login'))
68
 
69
+ user_record = user_result['records'][0]
70
+ user_id = user_record['Id']
71
+ referral_code = user_record.get('Referral__c', 'N/A')
72
+ reward_points = user_record.get('Reward_Points__c', 0)
73
+
74
+ # If no session image, check Salesforce for stored avatar
75
+ if not user_image and user_record.get('Avatar__c'):
76
+ session['user_image'] = user_record['Avatar__c']
77
+ user_image = session['user_image']
78
 
79
  # Get cart item count
80
  cart_query = f"SELECT COUNT() FROM Cart_Item__c WHERE Customer_Email__c = '{user_email}'"
 
165
  user_name=user_name,
166
  first_letter=first_letter,
167
  cart_item_count=cart_item_count,
168
+ user_image=user_image,
169
+ user_id=user_id # Pass user_id for avatar updates
170
  )
171
 
172
  @menu_blueprint.route('/upload_avatar', methods=['POST'])
173
  def upload_avatar():
174
+ try:
175
+ data = request.get_json()
176
+ if not data or 'image' not in data:
177
+ logger.error("No image data provided in request")
178
+ return jsonify({'success': False, 'error': 'No image data provided'}), 400
179
+
180
+ image_data = data['image']
181
+ logger.debug(f"Received image data with length: {len(image_data)}")
182
+
183
+ # Validate base64 image
184
+ if not image_data.startswith('data:image/'):
185
+ logger.error("Invalid image format: does not start with 'data:image/'")
186
+ return jsonify({'success': False, 'error': 'Invalid image format'}), 400
187
+
188
+ # Check size limit (~1.5MB for base64, roughly 1MB actual image)
189
+ if len(image_data) > 2_000_000:
190
+ logger.error(f"Image too large: {len(image_data)} characters (max 2,000,000)")
191
+ return jsonify({'success': False, 'error': 'Image too large (max ~1.5MB)'}), 400
192
+
193
+ # Validate base64 decoding
194
+ try:
195
+ # Extract the base64 part (after the comma)
196
+ base64_string = image_data.split(',')[1]
197
+ base64.b64decode(base64_string)
198
+ except Exception as e:
199
+ logger.error(f"Invalid base64 data: {str(e)}")
200
+ return jsonify({'success': False, 'error': 'Invalid base64 data'}), 400
201
+
202
+ # Store in session
203
+ session['user_image'] = image_data
204
+ logger.info("Image stored in session successfully")
205
+
206
+ # Store in Salesforce (optional, for persistence)
207
+ user_email = session.get('user_email')
208
+ if user_email:
209
+ try:
210
+ user_query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{user_email}'"
211
+ user_result = sf.query(user_query)
212
+ if user_result.get('records'):
213
+ user_id = user_result['records'][0]['Id']
214
+ sf.Customer_Login__c.update(user_id, {'Avatar__c': image_data})
215
+ logger.info(f"Image stored in Salesforce for user {user_email}")
216
+ else:
217
+ logger.warning(f"User not found in Salesforce: {user_email}")
218
+ except Exception as e:
219
+ logger.error(f"Failed to store image in Salesforce: {str(e)}")
220
+ # Continue even if Salesforce fails, as session storage is the primary method
221
+
222
+ return jsonify({'success': True, 'image': image_data})
223
+
224
+ except Exception as e:
225
+ logger.error(f"Error in upload_avatar: {str(e)}", exc_info=True)
226
+ return jsonify({'success': False, 'error': f'Server error: {str(e)}'}), 500
227
 
228
  @menu_blueprint.route('/delete_avatar', methods=['POST'])
229
  def delete_avatar():
230
+ try:
231
+ user_email = session.get('user_email')
232
+ if not user_email:
233
+ logger.error("No user email in session")
234
+ return jsonify({'success': False, 'error': 'User not authenticated'}), 401
235
+
236
+ # Remove from session
237
+ if 'user_image' in session:
238
+ session.pop('user_image', None)
239
+ logger.info("Image removed from session")
240
+
241
+ # Remove from Salesforce
242
+ try:
243
+ user_query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{user_email}'"
244
+ user_result = sf.query(user_query)
245
+ if user_result.get('records'):
246
+ user_id = user_result['records'][0]['Id']
247
+ sf.Customer_Login__c.update(user_id, {'Avatar__c': None})
248
+ logger.info(f"Image removed from Salesforce for user {user_email}")
249
+ else:
250
+ logger.warning(f"User not found in Salesforce: {user_email}")
251
+ except Exception as e:
252
+ logger.error(f"Failed to remove image from Salesforce: {str(e)}")
253
+ # Continue even if Salesforce fails, as session removal is the primary method
254
+
255
  return jsonify({'success': True})
256
+
257
+ except Exception as e:
258
+ logger.error(f"Error in delete_avatar: {str(e)}", exc_info=True)
259
+ return jsonify({'success': False, 'error': f'Server error: {str(e)}'}), 500
260
 
261
  @menu_blueprint.route('/api/addons', methods=['GET'])
262
  def get_addons():
 
294
  return jsonify({"success": True, "addons": formatted_addons})
295
 
296
  except Exception as e:
297
+ logger.error(f"Error fetching addons: {str(e)}")
298
  return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500
299
 
300
  @menu_blueprint.route('/cart/add', methods=['POST'])
 
383
  except ValueError as e:
384
  return jsonify({"success": False, "error": f"Invalid data format: {str(e)}"}), 400
385
  except Exception as e:
386
+ logger.error(f"Error adding item to cart: {str(e)}")
387
  return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500