| from flask import Blueprint, render_template, request, session, jsonify |
| from salesforce import get_salesforce_connection |
| sf = get_salesforce_connection() |
|
|
| cart_blueprint = Blueprint('cart', __name__) |
| @cart_blueprint.route("/cart", methods=["GET"]) |
| def cart(): |
| email = session.get('user_email') |
| if not email: |
| return redirect(url_for("login")) |
|
|
| try: |
| |
| result = sf.query(f""" |
| SELECT Name, Price__c, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Image1__c, Instructions__c, Category__c, Section__c |
| FROM Cart_Item__c |
| WHERE Customer_Email__c = '{email}' |
| """) |
| cart_items = result.get("records", []) |
|
|
| subtotal = sum(item['Price__c'] for item in cart_items) |
|
|
| |
| customer_result = sf.query(f""" |
| SELECT Reward_Points__c |
| FROM Customer_Login__c |
| WHERE Email__c = '{email}' |
| """) |
| reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0 |
|
|
| |
| coupon_result = sf.query(f""" |
| SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}' |
| """) |
| if coupon_result["records"]: |
| raw_coupons = coupon_result["records"][0].get("Coupon_Code__c", "") |
| coupons = raw_coupons.split("\n") if raw_coupons else [] |
| else: |
| coupons = [] |
|
|
| |
| suggestions = [] |
|
|
| |
| if cart_items: |
| |
| first_item = cart_items[0] |
| item_category = first_item.get('Category__c', 'All') |
| item_section = first_item.get('Section__c', 'Biryanis') |
|
|
| |
| complementary_sections = { |
| 'Breads': ['Curries', 'Biryanis', 'Starters'], |
| 'Biryanis': ['Curries', 'Starters', 'Desserts'], |
| 'Curries': ['Biryanis', 'Breads', 'Starters'], |
| 'Starters': ['Biryanis', 'Curries', 'Desserts'], |
| 'Desserts': ['Biryanis', 'Curries', 'Soft Drinks'], |
| 'Soft Drinks': ['Starters', 'Biryanis', 'Curries'] |
| } |
|
|
| |
| suggested_sections = complementary_sections.get(item_section, []) |
|
|
| |
| try: |
| for suggested_section in suggested_sections: |
| if item_category == "All": |
| query = f""" |
| SELECT Name, Price__c, Image1__c |
| FROM Menu_Item__c |
| WHERE Section__c = '{suggested_section}' |
| AND (Veg_NonVeg__c = 'Veg' OR Veg_NonVeg__c = 'Non veg') |
| LIMIT 4 |
| """ |
| else: |
| query = f""" |
| SELECT Name, Price__c, Image1__c |
| FROM Menu_Item__c |
| WHERE Section__c = '{suggested_section}' |
| AND Veg_NonVeg__c = '{item_category}' |
| LIMIT 4 |
| """ |
| suggestion_result = sf.query(query) |
| suggestions.extend(suggestion_result.get("records", [])) |
|
|
| |
| if len(suggestions) > 4: |
| suggestions = suggestions[:4] |
|
|
| except Exception as e: |
| print(f"Error fetching suggestions: {e}") |
|
|
| return render_template( |
| "cart.html", |
| cart_items=cart_items, |
| subtotal=subtotal, |
| reward_points=reward_points, |
| customer_email=email, |
| coupons=coupons, |
| suggestions=suggestions |
| ) |
|
|
| except Exception as e: |
| print(f"Error fetching cart items: {e}") |
| return render_template("cart.html", cart_items=[], subtotal=0, reward_points=0, coupons=[], suggestions=[]) |
|
|
| @cart_blueprint.route("/add_suggestion_to_cart", methods=["POST"]) |
| def add_suggestion_to_cart(): |
| try: |
| |
| data = request.get_json() |
| item_name = data.get('item_name').strip() |
| item_price = data.get('item_price') |
| item_image = data.get('item_image') |
| item_id = data.get('item_id') |
| customer_email = data.get('customer_email') |
| addons = data.get('addons', []) |
| instructions = data.get('instructions', "") |
|
|
| |
| addons_price = 0 |
| addons_string = "None" |
|
|
| |
| query = f""" |
| SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c, Instructions__c |
| FROM Cart_Item__c |
| WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}' |
| """ |
| result = sf.query(query) |
| cart_items = result.get("records", []) |
|
|
| |
| if cart_items: |
| cart_item_id = cart_items[0]['Id'] |
| existing_quantity = cart_items[0]['Quantity__c'] |
| existing_addons = cart_items[0].get('Add_Ons__c', "None") |
| existing_addons_price = cart_items[0].get('Add_Ons_Price__c', 0) |
| existing_instructions = cart_items[0].get('Instructions__c', "") |
|
|
| |
| combined_addons = existing_addons if existing_addons != "None" else "" |
| if addons: |
| combined_addons = f"{combined_addons}; {addons}".strip("; ") |
|
|
| combined_instructions = existing_instructions |
| if instructions: |
| combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ") |
|
|
| combined_addons_list = combined_addons.split("; ") |
| combined_addons_price = sum( |
| float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon |
| ) |
|
|
| |
| sf.Cart_Item__c.update(cart_item_id, { |
| "Quantity__c": existing_quantity + 1, |
| "Add_Ons__c": combined_addons, |
| "Add_Ons_Price__c": combined_addons_price, |
| "Instructions__c": combined_instructions, |
| "Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price |
| }) |
| else: |
| |
| total_price = float(item_price) + addons_price |
|
|
| |
| sf.Cart_Item__c.create({ |
| "Name": item_name, |
| "Price__c": total_price, |
| "Base_Price__c": item_price, |
| "Quantity__c": 1, |
| "Add_Ons_Price__c": addons_price, |
| "Add_Ons__c": addons_string, |
| "Image1__c": item_image, |
| "Customer_Email__c": customer_email, |
| "Instructions__c": instructions |
| }) |
|
|
| return jsonify({"success": True, "message": "Item added to cart successfully."}) |
|
|
| except Exception as e: |
| print(f"Error adding item to cart: {str(e)}") |
| return jsonify({"success": False, "error": str(e)}) |
| @cart_blueprint.route('/remove/<item_name>', methods=['POST']) |
| def remove_cart_item(item_name): |
| try: |
| customer_email = session.get('user_email') |
| if not customer_email: |
| return jsonify({'success': False, 'message': 'User email not found. Please log in again.'}), 400 |
| |
| query = f""" |
| SELECT Id FROM Cart_Item__c |
| WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}' |
| """ |
| result = sf.query(query) |
| |
| if result['totalSize'] == 0: |
| return jsonify({'success': False, 'message': 'Item not found in cart.'}), 400 |
| |
| |
| cart_item_id = result['records'][0]['Id'] |
| sf.Cart_Item__c.delete(cart_item_id) |
| return jsonify({'success': True, 'message': f"'{item_name}' removed successfully!"}), 200 |
| except Exception as e: |
| print(f"Error: {str(e)}") |
| return jsonify({'success': False, 'message': f"An error occurred: {str(e)}"}), 500 |
|
|
| @cart_blueprint.route("/update_quantity", methods=["POST"]) |
| def update_quantity(): |
| print("Handling update_quantity request...") |
| data = request.json |
| email = data.get('email') |
| item_name = data.get('item_name') |
|
|
| try: |
| |
| quantity = int(data.get('quantity')) |
| except (ValueError, TypeError): |
| return jsonify({"success": False, "error": "Invalid quantity provided."}), 400 |
|
|
| |
| if not email or not item_name or quantity is None: |
| return jsonify({"success": False, "error": "Email, item name, and quantity are required."}), 400 |
|
|
| try: |
| |
| cart_items = sf.query( |
| f"SELECT Id, Quantity__c, Price__c, Base_Price__c, Add_Ons_Price__c FROM Cart_Item__c " |
| f"WHERE Customer_Email__c = '{email}' AND Name = '{item_name}'" |
| )['records'] |
|
|
| if not cart_items: |
| return jsonify({"success": False, "error": "Cart item not found."}), 404 |
|
|
| |
| cart_item_id = cart_items[0]['Id'] |
| base_price = cart_items[0]['Base_Price__c'] |
| addons_price = cart_items[0].get('Add_Ons_Price__c', 0) |
|
|
| |
| new_item_price = (base_price * quantity) + addons_price |
|
|
| |
| sf.Cart_Item__c.update(cart_item_id, { |
| "Quantity__c": quantity, |
| "Price__c": new_item_price, |
| }) |
|
|
| |
| cart_items = sf.query(f""" |
| SELECT Price__c, Add_Ons_Price__c |
| FROM Cart_Item__c |
| WHERE Customer_Email__c = '{email}' |
| """)['records'] |
| new_subtotal = sum(item['Price__c'] for item in cart_items) |
|
|
| |
| return jsonify({"success": True, "new_item_price": new_item_price, "subtotal": new_subtotal}) |
|
|
| except Exception as e: |
| print(f"Error updating quantity: {str(e)}") |
| return jsonify({"success": False, "error": str(e)}), 500 |
|
|
|
|
| @cart_blueprint.route("/checkout", methods=["POST"]) |
| def checkout(): |
| email = session.get('user_email') |
| user_id = session.get('user_name') |
| table_number = session.get('table_number') |
|
|
| print(f"Session Email: {email}, User ID: {user_id}, Table Number: {table_number}") |
|
|
| if not email or not user_id: |
| print("User not logged in") |
| return jsonify({"success": False, "message": "User not logged in"}) |
|
|
| try: |
| |
| data = request.json |
| selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None |
| |
| print(f"Selected Coupon: {selected_coupon}") |
|
|
| |
| result = sf.query(f""" |
| SELECT Id, Name, Price__c, Add_Ons_Price__c, Quantity__c, Add_Ons__c, Instructions__c, Image1__c |
| FROM Cart_Item__c |
| WHERE Customer_Email__c = '{email}' |
| """) |
| |
| |
| cart_items = result.get("records", []) |
| print(f"Cart Items Retrieved: {cart_items}") |
|
|
| if not cart_items: |
| print("Cart is empty") |
| return jsonify({"success": False, "message": "Cart is empty"}) |
|
|
| total_price = sum(item['Price__c'] for item in cart_items) |
| print(f"Total Price: {total_price}") |
|
|
| discount = 0 |
|
|
| |
| coupon_query = sf.query(f""" |
| SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}' |
| """) |
| print(f"Coupon Query Results: {coupon_query}") |
|
|
| has_coupons = bool(coupon_query["records"]) |
| print(f"Has Coupons: {has_coupons}") |
|
|
| if selected_coupon: |
| |
| discount = total_price * 0.10 |
| print(f"Discount Applied: {discount}") |
| |
| referral_coupon_id = coupon_query["records"][0]["Id"] |
| print(f"Referral Coupon ID: {referral_coupon_id}") |
|
|
| existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n") |
| print(f"Existing Coupons Before Removal: {existing_coupons}") |
|
|
| |
| updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon] |
| updated_coupons_str = "\n".join(updated_coupons).strip() |
|
|
| print(f"Updated Coupons After Removal: {updated_coupons}") |
|
|
| |
| if not updated_coupons: |
| updated_coupons_str = None |
| print("No Coupons Remaining. Setting to None") |
|
|
| |
| print(f"Updating Referral Coupon: {updated_coupons_str}") |
| sf.Referral_Coupon__c.update(referral_coupon_id, { |
| "Coupon_Code__c": updated_coupons_str |
| }) |
| else: |
| |
| reward_points_to_add = total_price * 0.10 |
| print(f"Reward Points to Add: {reward_points_to_add}") |
|
|
| |
| customer_record = sf.query(f""" |
| SELECT Id, Reward_Points__c FROM Customer_Login__c |
| WHERE Email__c = '{email}' |
| """) |
| print(f"Customer Reward Points Query: {customer_record}") |
| |
| customer = customer_record.get("records", [])[0] if customer_record else None |
| if customer: |
| current_reward_points = customer.get("Reward_Points__c") or 0 |
| print(f"Current Reward Points: {current_reward_points}") |
| new_reward_points = current_reward_points + reward_points_to_add |
| print(f"New Reward Points: {new_reward_points}") |
|
|
| |
| sf.Customer_Login__c.update(customer["Id"], { |
| "Reward_Points__c": new_reward_points |
| }) |
|
|
| |
| total_bill = total_price - discount |
| print(f"Total Bill After Discount: {total_bill}") |
|
|
| |
| order_details = "\n".join( |
| f"{item['Name']} x{item['Quantity__c']} | Add-Ons: {item.get('Add_Ons__c', 'None')} | " |
| f"Instructions: {item.get('Instructions__c', 'None')} | " |
| f"Price: ${item['Price__c']} | Image: {item['Image1__c']}" |
| for item in cart_items |
| ) |
| print(f"Order Details: {order_details}") |
|
|
| |
| customer_query = sf.query(f""" |
| SELECT Id FROM Customer_Login__c |
| WHERE Email__c = '{email}' |
| """) |
| |
| customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None |
| print(f"Customer ID: {customer_id}") |
|
|
| if not customer_id: |
| print("Customer record not found") |
| return jsonify({"success": False, "message": "Customer record not found in Salesforce"}) |
| table_number = table_number if table_number != 'null' else None |
| |
| order_data = { |
| "Customer_Name__c": user_id, |
| "Customer_Email__c": email, |
| "Total_Amount__c": total_price, |
| "Discount__c": discount, |
| "Total_Bill__c": total_bill, |
| "Order_Status__c": "Pending", |
| "Customer2__c": customer_id, |
| "Order_Details__c": order_details, |
| "Table_Number__c": table_number |
| } |
| print(f"Order Data: {order_data}") |
|
|
| |
| order_response = sf.Order__c.create(order_data) |
| print(f"Order Response: {order_response}") |
|
|
| |
| if order_response: |
| |
| for item in cart_items: |
| print(f"Deleting Cart Item: {item['Id']}") |
| sf.Cart_Item__c.delete(item["Id"]) |
|
|
| return jsonify({"success": True, "message": "Order placed successfully!", "discount": discount, "totalBill": total_bill}) |
|
|
| except Exception as e: |
| print(f"Error during checkout: {str(e)}") |
| return jsonify({"success": False, "error": str(e)}) |
|
|
|
|
|
|