nagasurendra commited on
Commit
c4b6776
·
verified ·
1 Parent(s): 954910a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -35
app.py CHANGED
@@ -55,7 +55,6 @@ app.register_blueprint(order_blueprint)
55
  app.register_blueprint(orderhistory_blueprint, url_prefix='/orderhistory')
56
  app.register_blueprint(customdish_blueprint, url_prefix='/customdish')
57
  app.register_blueprint(combined_summary_blueprint, url_prefix='/combined_summary')
58
-
59
  @app.route('/login', methods=['GET', 'POST'])
60
  def login():
61
  # Your login logic goes here
@@ -73,7 +72,8 @@ def login():
73
  session.modified = True
74
  return redirect(url_for("menu.menu")) # Redirect to menu directly
75
  return render_template('login.html')
76
-
 
77
  @app.route("/")
78
  def home():
79
  # Fetch user details from URL parameters
@@ -218,14 +218,17 @@ def submit_customization_ingredients():
218
  ingredients = data.get('ingredients', [])
219
  instructions = data.get('instructions', '')
220
 
221
- # Get the session email (this should already be set during login)
222
  customer_email = session.get('user_email')
223
-
224
  if not customer_email:
225
  return jsonify({"error": "User email not found in session"}), 400
226
 
227
  try:
228
- if items: # Cart submission
 
 
 
 
 
229
  for item in items:
230
  ingredient_names = ', '.join(i['name'] for i in item.get('ingredients', [])) if item.get('ingredients') else ''
231
  base_price = item.get('price', 0.0)
@@ -233,26 +236,23 @@ def submit_customization_ingredients():
233
  addons_price = 0
234
  total_price = (base_price * quantity) + addons_price
235
 
236
- # Check if item already exists in the cart for the user based on Customer_Email__c and Item Name
237
  soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item['name']}' LIMIT 1"
238
  existing_item = sf.query(soql)
239
 
240
- if existing_item['records']: # If the item exists, update it
241
- item_id = existing_item['records'][0]['Id']
242
- existing_quantity = existing_item['records'][0]['Quantity__c']
243
- existing_addons = existing_item['records'][0]['Add_Ons__c']
244
- existing_instructions = existing_item['records'][0]['Instructions__c']
245
- existing_price = existing_item['records'][0]['Price__c']
 
246
 
247
- # Update quantity, addons, and instructions
248
  new_quantity = existing_quantity + quantity
249
- new_addons = (existing_addons or '') + (', ' + ingredient_names if ingredient_names else '')
250
- new_instructions = (existing_instructions or '') + ('; ' + instructions if instructions else '')
251
-
252
- # Calculate the new total price
253
  updated_price = (base_price * new_quantity) + addons_price
254
 
255
- # Update the existing item in Salesforce
256
  sf.Cart_Item__c.update(item_id, {
257
  'Quantity__c': new_quantity,
258
  'Add_Ons__c': new_addons,
@@ -260,7 +260,8 @@ def submit_customization_ingredients():
260
  'Price__c': updated_price
261
  })
262
  logger.debug(f"Updated {item['name']} in Cart_Item__c")
263
- else: # If the item doesn't exist, create a new one
 
264
  sf.Cart_Item__c.create({
265
  'Name': item['name'],
266
  'Base_Price__c': base_price,
@@ -272,9 +273,22 @@ def submit_customization_ingredients():
272
  'Instructions__c': item.get('instructions', ''),
273
  'Category__c': item.get('veg_nonveg', ''),
274
  'Section__c': item.get('section', ''),
275
- 'Customer_Email__c': customer_email # Store session email
276
  })
277
  logger.debug(f"Created new Cart_Item__c for {item['name']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  return jsonify({"success": True, "message": f"Processed {len(items)} items"})
279
 
280
  elif menu_item: # Single item customization
@@ -284,26 +298,22 @@ def submit_customization_ingredients():
284
  addons_price = 0
285
  total_price = (base_price * quantity) + addons_price
286
 
287
- # Check if the menu item already exists in the cart for the user
288
  soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{menu_item['name']}' LIMIT 1"
289
  existing_item = sf.query(soql)
290
 
291
- if existing_item['records']: # If the item exists, update it
292
- item_id = existing_item['records'][0]['Id']
293
- existing_quantity = existing_item['records'][0]['Quantity__c']
294
- existing_addons = existing_item['records'][0]['Add_Ons__c']
295
- existing_instructions = existing_item['records'][0]['Instructions__c']
296
- existing_price = existing_item['records'][0]['Price__c']
 
297
 
298
- # Update quantity, addons, and instructions
299
  new_quantity = existing_quantity + quantity
300
- new_addons = (existing_addons or '') + (', ' + ingredient_names if ingredient_names else '')
301
- new_instructions = (existing_instructions or '') + ('; ' + instructions if instructions else '')
302
-
303
- # Calculate the new total price
304
  updated_price = (base_price * new_quantity) + addons_price
305
 
306
- # Update the existing item in Salesforce
307
  sf.Cart_Item__c.update(item_id, {
308
  'Quantity__c': new_quantity,
309
  'Add_Ons__c': new_addons,
@@ -311,7 +321,8 @@ def submit_customization_ingredients():
311
  'Price__c': updated_price
312
  })
313
  logger.debug(f"Updated customization for {menu_item['name']} in Cart_Item__c")
314
- else: # If the item doesn't exist, create a new one
 
315
  sf.Cart_Item__c.create({
316
  'Name': menu_item['name'],
317
  'Base_Price__c': base_price,
@@ -323,9 +334,22 @@ def submit_customization_ingredients():
323
  'Instructions__c': instructions,
324
  'Category__c': menu_item.get('veg_nonveg', ''),
325
  'Section__c': menu_item.get('section', ''),
326
- 'Customer_Email__c': customer_email # Store session email
327
  })
328
  logger.debug(f"Created new Cart_Item__c for {menu_item['name']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  return jsonify({"success": True, "message": "Customization submitted"})
330
 
331
  else:
@@ -336,5 +360,96 @@ def submit_customization_ingredients():
336
  return jsonify({"error": f"Failed to submit: {str(e)}"}), 500
337
 
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  if __name__ == "__main__":
340
  app.run(debug=True, host="0.0.0.0", port=7860)
 
55
  app.register_blueprint(orderhistory_blueprint, url_prefix='/orderhistory')
56
  app.register_blueprint(customdish_blueprint, url_prefix='/customdish')
57
  app.register_blueprint(combined_summary_blueprint, url_prefix='/combined_summary')
 
58
  @app.route('/login', methods=['GET', 'POST'])
59
  def login():
60
  # Your login logic goes here
 
72
  session.modified = True
73
  return redirect(url_for("menu.menu")) # Redirect to menu directly
74
  return render_template('login.html')
75
+
76
+
77
  @app.route("/")
78
  def home():
79
  # Fetch user details from URL parameters
 
218
  ingredients = data.get('ingredients', [])
219
  instructions = data.get('instructions', '')
220
 
 
221
  customer_email = session.get('user_email')
 
222
  if not customer_email:
223
  return jsonify({"error": "User email not found in session"}), 400
224
 
225
  try:
226
+ # Fetch customer name from Customer_Login__c using email
227
+ soql_customer = f"SELECT Name, Email__c FROM Customer_Login__c WHERE Email__c = '{customer_email}' LIMIT 1"
228
+ customer_record = sf.query(soql_customer)
229
+ customer_name = customer_record['records'][0]['Name'] if customer_record['records'] else 'Unknown Customer'
230
+
231
+ if items: # Bulk items in cart submission
232
  for item in items:
233
  ingredient_names = ', '.join(i['name'] for i in item.get('ingredients', [])) if item.get('ingredients') else ''
234
  base_price = item.get('price', 0.0)
 
236
  addons_price = 0
237
  total_price = (base_price * quantity) + addons_price
238
 
239
+ # Check if item exists in cart
240
  soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{item['name']}' LIMIT 1"
241
  existing_item = sf.query(soql)
242
 
243
+ if existing_item['records']:
244
+ # Update existing cart item
245
+ record = existing_item['records'][0]
246
+ item_id = record['Id']
247
+ existing_quantity = record['Quantity__c'] or 0
248
+ existing_addons = record.get('Add_Ons__c') or ''
249
+ existing_instructions = record.get('Instructions__c') or ''
250
 
 
251
  new_quantity = existing_quantity + quantity
252
+ new_addons = existing_addons + (', ' + ingredient_names if ingredient_names else '')
253
+ new_instructions = existing_instructions + ('; ' + instructions if instructions else '')
 
 
254
  updated_price = (base_price * new_quantity) + addons_price
255
 
 
256
  sf.Cart_Item__c.update(item_id, {
257
  'Quantity__c': new_quantity,
258
  'Add_Ons__c': new_addons,
 
260
  'Price__c': updated_price
261
  })
262
  logger.debug(f"Updated {item['name']} in Cart_Item__c")
263
+ else:
264
+ # Create new cart item
265
  sf.Cart_Item__c.create({
266
  'Name': item['name'],
267
  'Base_Price__c': base_price,
 
273
  'Instructions__c': item.get('instructions', ''),
274
  'Category__c': item.get('veg_nonveg', ''),
275
  'Section__c': item.get('section', ''),
276
+ 'Customer_Email__c': customer_email
277
  })
278
  logger.debug(f"Created new Cart_Item__c for {item['name']}")
279
+
280
+ # Create corresponding Custom_Dish__c record
281
+ sf.Custom_Dish__c.create({
282
+ 'Name': f"{customer_name} - {item['name']}",
283
+ 'Price__c': total_price,
284
+ 'Description__c': (ingredient_names + '; ' + instructions).strip('; '),
285
+ 'Image1__c': item.get('image_url', ''),
286
+ 'Veg_NonVeg__c': item.get('veg_nonveg', ''),
287
+ 'Total_Ordered__c': 1,
288
+ 'Section__c': 'Customized dish' # Fixed value here
289
+ })
290
+ logger.debug(f"Created Custom_Dish__c for {item['name']}")
291
+
292
  return jsonify({"success": True, "message": f"Processed {len(items)} items"})
293
 
294
  elif menu_item: # Single item customization
 
298
  addons_price = 0
299
  total_price = (base_price * quantity) + addons_price
300
 
 
301
  soql = f"SELECT Id, Quantity__c, Add_Ons__c, Instructions__c, Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{customer_email}' AND Name = '{menu_item['name']}' LIMIT 1"
302
  existing_item = sf.query(soql)
303
 
304
+ if existing_item['records']:
305
+ # Update existing cart item
306
+ record = existing_item['records'][0]
307
+ item_id = record['Id']
308
+ existing_quantity = record['Quantity__c'] or 0
309
+ existing_addons = record.get('Add_Ons__c') or ''
310
+ existing_instructions = record.get('Instructions__c') or ''
311
 
 
312
  new_quantity = existing_quantity + quantity
313
+ new_addons = existing_addons + (', ' + ingredient_names if ingredient_names else '')
314
+ new_instructions = existing_instructions + ('; ' + instructions if instructions else '')
 
 
315
  updated_price = (base_price * new_quantity) + addons_price
316
 
 
317
  sf.Cart_Item__c.update(item_id, {
318
  'Quantity__c': new_quantity,
319
  'Add_Ons__c': new_addons,
 
321
  'Price__c': updated_price
322
  })
323
  logger.debug(f"Updated customization for {menu_item['name']} in Cart_Item__c")
324
+ else:
325
+ # Create new cart item
326
  sf.Cart_Item__c.create({
327
  'Name': menu_item['name'],
328
  'Base_Price__c': base_price,
 
334
  'Instructions__c': instructions,
335
  'Category__c': menu_item.get('veg_nonveg', ''),
336
  'Section__c': menu_item.get('section', ''),
337
+ 'Customer_Email__c': customer_email
338
  })
339
  logger.debug(f"Created new Cart_Item__c for {menu_item['name']}")
340
+
341
+ # Create corresponding Custom_Dish__c record
342
+ sf.Custom_Dish__c.create({
343
+ 'Name': f"{customer_name} - {menu_item['name']}",
344
+ 'Price__c': total_price,
345
+ 'Description__c': (ingredient_names + '; ' + instructions).strip('; '),
346
+ 'Image1__c': menu_item.get('image_url', ''),
347
+ 'Veg_NonVeg__c': menu_item.get('veg_nonveg', ''),
348
+ 'Total_Ordered__c': 1,
349
+ 'Section__c': 'Customized dish' # Fixed value here
350
+ })
351
+ logger.debug(f"Created Custom_Dish__c for {menu_item['name']}")
352
+
353
  return jsonify({"success": True, "message": "Customization submitted"})
354
 
355
  else:
 
360
  return jsonify({"error": f"Failed to submit: {str(e)}"}), 500
361
 
362
 
363
+ from flask import Flask, render_template, request, jsonify
364
+ import os
365
+ import base64
366
+ import requests
367
+ import logging
368
+ from requests.adapters import HTTPAdapter
369
+ from urllib3.util.retry import Retry
370
+
371
+ # Configure logging
372
+ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
373
+
374
+
375
+
376
+ # Configuration
377
+ UPLOAD_FOLDER = 'static/captures'
378
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
379
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
380
+
381
+ # Zapier webhook settings
382
+ ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
383
+
384
+ def send_to_zapier(image_path):
385
+ if not ZAPIER_WEBHOOK_URL:
386
+ logging.error("Zapier webhook URL not set.")
387
+ return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
388
+ try:
389
+ payload = {
390
+ 'image_url': request.url_root + image_path,
391
+ 'filename': os.path.basename(image_path),
392
+ 'content_type': 'image/jpeg'
393
+ }
394
+
395
+ session = requests.Session()
396
+ retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
397
+ session.mount('https://', HTTPAdapter(max_retries=retries))
398
+ logging.debug(f"Sending image URL to Zapier webhook: {ZAPIER_WEBHOOK_URL}")
399
+ response = session.post(ZAPIER_WEBHOOK_URL, json=payload, timeout=10)
400
+ response.raise_for_status()
401
+ logging.debug("Image URL sent to Zapier successfully.")
402
+ return {"status": "success"}
403
+ except requests.exceptions.RequestException as e:
404
+ logging.error(f"Failed to send to Zapier: {str(e)}")
405
+ if e.response is not None:
406
+ logging.error(f"Response details: {e.response.text}")
407
+ return {"error": f"Failed to send to Zapier: {str(e)}"}
408
+
409
+
410
+
411
+ @app.route('/camera')
412
+ def camera():
413
+ return render_template('camera.html')
414
+
415
+ @app.route('/capture', methods=['POST'])
416
+ def capture():
417
+ try:
418
+ data = request.form['image']
419
+ header, encoded = data.split(",", 1)
420
+ binary_data = base64.b64decode(encoded)
421
+
422
+ filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
423
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
424
+ with open(filepath, "wb") as f:
425
+ f.write(binary_data)
426
+
427
+ image_url = f"/{filepath}"
428
+ return jsonify({
429
+ 'status': 'success',
430
+ 'image_url': image_url
431
+ })
432
+ except Exception as e:
433
+ logging.error(f"Error in capture: {str(e)}")
434
+ return jsonify({'status': 'error', 'message': str(e)})
435
+
436
+ @app.route('/upload_zapier', methods=['POST'])
437
+ def upload_zapier():
438
+ try:
439
+ image_url = request.form['image_url']
440
+ if not image_url.startswith('/static/captures/'):
441
+ return jsonify({'status': 'error', 'message': 'Invalid image path.'})
442
+
443
+ result = send_to_zapier(image_url.lstrip('/'))
444
+ if 'error' in result:
445
+ return jsonify({'status': 'error', 'message': result['error']})
446
+ return jsonify({'status': 'success'})
447
+ except Exception as e:
448
+ logging.error(f"Error in upload_zapier: {str(e)}")
449
+ return jsonify({'status': 'error', 'message': str(e)})
450
+
451
+
452
+
453
+
454
  if __name__ == "__main__":
455
  app.run(debug=True, host="0.0.0.0", port=7860)