Update menu.py
Browse files
menu.py
CHANGED
@@ -7,173 +7,181 @@ menu_blueprint = Blueprint('menu', __name__)
|
|
7 |
# Initialize Salesforce connection
|
8 |
sf = get_salesforce_connection()
|
9 |
|
10 |
-
# Constants
|
11 |
STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')
|
12 |
PLACEHOLDER_VIDEO = 'placeholder.mp4'
|
13 |
PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
|
14 |
-
SECTION_ORDER = [
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
# Create placeholder video
|
17 |
if not os.path.exists(PLACEHOLDER_PATH):
|
18 |
open(PLACEHOLDER_PATH, 'wb').close()
|
19 |
-
print(f"Created placeholder video at {PLACEHOLDER_PATH}")
|
20 |
|
21 |
def get_valid_video_path(item_name, video_url=None):
|
22 |
-
"""
|
23 |
-
Get valid video path for item with placeholder fallback
|
24 |
-
Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
|
25 |
-
"""
|
26 |
-
# First try: Video1__c from Salesforce if provided
|
27 |
if video_url:
|
28 |
-
# If it's a complete URL (http/https)
|
29 |
if video_url.startswith(('http://', 'https://')):
|
30 |
return video_url
|
31 |
-
# If it's a relative path (/videos/xxx.mp4)
|
32 |
elif video_url.startswith('/'):
|
33 |
return video_url
|
34 |
-
# If it's a Salesforce File ID (starts with '069')
|
35 |
elif video_url.startswith('069'):
|
36 |
return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
|
37 |
-
|
38 |
-
# Final fallback: placeholder.mp4
|
39 |
-
if not os.path.exists(PLACEHOLDER_PATH):
|
40 |
-
open(PLACEHOLDER_PATH, 'wb').close()
|
41 |
-
print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
|
42 |
-
|
43 |
return f"/static/{PLACEHOLDER_VIDEO}"
|
44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
@menu_blueprint.route("/menu", methods=["GET", "POST"])
|
46 |
def menu():
|
|
|
47 |
selected_category = request.args.get("category", "All")
|
48 |
-
user_email = session.get('user_email')
|
|
|
49 |
|
50 |
if not user_email:
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
session['user_name'] = user_name
|
57 |
-
else:
|
58 |
-
return redirect(url_for("login"))
|
59 |
-
else:
|
60 |
-
user_name = session.get('user_name')
|
61 |
|
62 |
first_letter = user_name[0].upper() if user_name else "A"
|
63 |
|
64 |
try:
|
65 |
-
#
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
return redirect(url_for('login'))
|
71 |
|
72 |
-
referral_code =
|
73 |
-
reward_points =
|
74 |
-
|
75 |
-
# Get cart
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
nutrition_fields = []
|
92 |
-
if 'IngredientsInfo__c' in available_fields:
|
93 |
-
nutrition_fields.append('IngredientsInfo__c')
|
94 |
-
if 'Nutritional_Info__c' in available_fields:
|
95 |
-
nutrition_fields.append('Nutritional_Info__c')
|
96 |
-
if 'Allergens__c' in available_fields:
|
97 |
-
nutrition_fields.append('Allergens__c')
|
98 |
-
|
99 |
-
query_fields = base_fields + nutrition_fields
|
100 |
-
except Exception as e:
|
101 |
-
print(f"Error checking for nutrition fields: {str(e)}")
|
102 |
-
query_fields = base_fields
|
103 |
-
|
104 |
-
# Build and execute the query
|
105 |
-
menu_query = f"SELECT {', '.join(query_fields)} FROM Menu_Item__c"
|
106 |
-
result = sf.query(menu_query)
|
107 |
-
food_items = result['records'] if 'records' in result else []
|
108 |
-
|
109 |
-
# Process items with fallback values
|
110 |
-
for item in food_items:
|
111 |
-
# Ensure required fields have values
|
112 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
|
113 |
item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
|
114 |
|
115 |
-
#
|
116 |
-
item['IngredientsInfo__c'] = item.get('IngredientsInfo__c',
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
#
|
121 |
-
best_sellers = sorted(
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
elif selected_category == "Non veg":
|
127 |
-
best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]
|
128 |
|
129 |
-
|
130 |
ordered_menu = {section: [] for section in SECTION_ORDER}
|
131 |
-
|
132 |
if best_sellers:
|
133 |
ordered_menu["Best Sellers"] = best_sellers
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
for item in food_items:
|
138 |
section = item.get("Section__c", "Others")
|
139 |
-
if
|
140 |
-
ordered_menu
|
141 |
-
|
142 |
-
if item['Name'] in added_item_names:
|
143 |
-
continue
|
144 |
-
|
145 |
-
# Apply category filter to all items
|
146 |
-
if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
|
147 |
-
continue
|
148 |
-
if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
|
149 |
-
continue
|
150 |
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
# Remove empty sections
|
155 |
-
ordered_menu = {section: items for section, items in ordered_menu.items() if items}
|
156 |
-
categories = ["All", "Veg", "Non veg"]
|
157 |
|
158 |
except Exception as e:
|
159 |
-
print(f"Error
|
160 |
-
#
|
161 |
-
ordered_menu = {
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
referral_code = 'N/A'
|
178 |
reward_points = 0
|
179 |
cart_item_count = 0
|
@@ -181,144 +189,109 @@ def menu():
|
|
181 |
return render_template(
|
182 |
"menu.html",
|
183 |
ordered_menu=ordered_menu,
|
184 |
-
categories=
|
185 |
selected_category=selected_category,
|
186 |
referral_code=referral_code,
|
187 |
reward_points=reward_points,
|
188 |
user_name=user_name,
|
189 |
first_letter=first_letter,
|
190 |
-
cart_item_count=cart_item_count
|
|
|
191 |
)
|
192 |
|
193 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
194 |
def get_addons():
|
195 |
-
item_name = request.args.get('item_name')
|
196 |
-
item_section = request.args.get('item_section')
|
197 |
-
|
198 |
-
if not item_name or not item_section:
|
199 |
-
return jsonify({"success": False, "error": "Item name and section are required."}), 400
|
200 |
-
|
201 |
try:
|
202 |
-
|
203 |
-
|
|
|
|
|
|
|
|
|
|
|
204 |
FROM Customization_Options__c
|
205 |
WHERE Section__c = '{item_section}'
|
206 |
-
"""
|
207 |
-
result = sf.query(query)
|
208 |
-
addons = result.get('records', [])
|
209 |
-
|
210 |
-
if not addons:
|
211 |
-
return jsonify({"success": False, "error": "No customization options found for the given section."}), 404
|
212 |
|
213 |
formatted_addons = []
|
214 |
for addon in addons:
|
215 |
-
options = addon.get("Options__c", "")
|
216 |
-
if options:
|
217 |
-
options = options.split(", ")
|
218 |
-
else:
|
219 |
-
options = []
|
220 |
-
|
221 |
formatted_addons.append({
|
222 |
"name": addon["Name"],
|
223 |
"type": addon["Customization_Type__c"],
|
224 |
-
"options":
|
225 |
"max_selections": addon.get("Max_Selections__c", 1),
|
226 |
"extra_charge": addon.get("Extra_Charge__c", False),
|
227 |
-
"extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
|
228 |
})
|
229 |
|
230 |
return jsonify({"success": True, "addons": formatted_addons})
|
231 |
|
232 |
except Exception as e:
|
233 |
print(f"Error fetching addons: {str(e)}")
|
234 |
-
return jsonify({"success": False, "error":
|
235 |
|
236 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
237 |
def add_to_cart():
|
238 |
try:
|
239 |
data = request.json
|
240 |
-
|
241 |
-
|
242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
addons = data.get('addons', [])
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
if not customer_email:
|
254 |
-
return jsonify({"success": False, "error": "User email is required."}), 400
|
255 |
|
256 |
-
|
257 |
-
|
|
|
258 |
FROM Cart_Item__c
|
259 |
-
WHERE
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
if new_addons:
|
276 |
-
combined_addons = f"{combined_addons}; {new_addons}".strip("; ")
|
277 |
-
|
278 |
-
combined_instructions = existing_instructions
|
279 |
-
if instructions:
|
280 |
-
combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")
|
281 |
-
|
282 |
-
combined_addons_list = combined_addons.split("; ")
|
283 |
-
combined_addons_price = sum(
|
284 |
-
float(addon.split("($")[1][:-1]) for addon in combined_addons_list if "($" in addon
|
285 |
-
)
|
286 |
-
|
287 |
-
sf.Cart_Item__c.update(cart_item_id, {
|
288 |
-
"Quantity__c": existing_quantity + quantity,
|
289 |
-
"Add_Ons__c": combined_addons,
|
290 |
-
"Add_Ons_Price__c": combined_addons_price,
|
291 |
-
"Instructions__c": combined_instructions,
|
292 |
-
"Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
|
293 |
-
"Category__c": category,
|
294 |
-
"Section__c": section
|
295 |
})
|
296 |
else:
|
297 |
-
|
298 |
-
|
299 |
-
addons_string = new_addons
|
300 |
-
|
301 |
-
total_price = item_price * quantity + addons_price
|
302 |
-
|
303 |
-
sf.Cart_Item__c.create({
|
304 |
-
"Name": item_name,
|
305 |
-
"Price__c": total_price,
|
306 |
-
"Base_Price__c": item_price,
|
307 |
-
"Quantity__c": quantity,
|
308 |
-
"Add_Ons_Price__c": addons_price,
|
309 |
-
"Add_Ons__c": addons_string,
|
310 |
-
"Image1__c": item_image,
|
311 |
-
"Customer_Email__c": customer_email,
|
312 |
-
"Instructions__c": instructions,
|
313 |
-
"Category__c": category,
|
314 |
-
"Section__c": section
|
315 |
-
})
|
316 |
-
|
317 |
-
return jsonify({"success": True, "message": "Item added to cart successfully."})
|
318 |
|
319 |
-
|
320 |
-
return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400
|
321 |
|
322 |
except Exception as e:
|
323 |
-
print(f"Error adding
|
324 |
-
return jsonify({"success": False, "error":
|
|
|
7 |
# Initialize Salesforce connection
|
8 |
sf = get_salesforce_connection()
|
9 |
|
10 |
+
# Constants
|
11 |
STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')
|
12 |
PLACEHOLDER_VIDEO = 'placeholder.mp4'
|
13 |
PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
|
14 |
+
SECTION_ORDER = [
|
15 |
+
"Best Sellers", "Starters", "Biryanis", "Curries",
|
16 |
+
"Breads", "Customized dish", "Appetizer", "Desserts",
|
17 |
+
"Soft Drinks"
|
18 |
+
]
|
19 |
|
20 |
+
# Create placeholder video if missing
|
21 |
if not os.path.exists(PLACEHOLDER_PATH):
|
22 |
open(PLACEHOLDER_PATH, 'wb').close()
|
|
|
23 |
|
24 |
def get_valid_video_path(item_name, video_url=None):
|
25 |
+
"""Handle video paths with proper fallback logic"""
|
|
|
|
|
|
|
|
|
26 |
if video_url:
|
|
|
27 |
if video_url.startswith(('http://', 'https://')):
|
28 |
return video_url
|
|
|
29 |
elif video_url.startswith('/'):
|
30 |
return video_url
|
|
|
31 |
elif video_url.startswith('069'):
|
32 |
return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
return f"/static/{PLACEHOLDER_VIDEO}"
|
34 |
|
35 |
+
def get_available_fields():
|
36 |
+
"""Check which custom fields exist in Salesforce"""
|
37 |
+
try:
|
38 |
+
desc = sf.Menu_Item__c.describe()
|
39 |
+
existing_fields = {field['name'] for field in desc['fields']}
|
40 |
+
|
41 |
+
return {
|
42 |
+
'base': [
|
43 |
+
'Name', 'Price__c', 'Description__c', 'Image1__c', 'Image2__c',
|
44 |
+
'Veg_NonVeg__c', 'Section__c', 'Total_Ordered__c', 'Video1__c'
|
45 |
+
],
|
46 |
+
'nutrition': [
|
47 |
+
f for f in ['IngredientsInfo__c', 'Nutritional_Info__c', 'Allergens__c']
|
48 |
+
if f in existing_fields
|
49 |
+
]
|
50 |
+
}
|
51 |
+
except Exception as e:
|
52 |
+
print(f"Error checking Salesforce fields: {str(e)}")
|
53 |
+
return {
|
54 |
+
'base': ['Name', 'Price__c', 'Description__c', 'Image1__c', 'Veg_NonVeg__c', 'Section__c'],
|
55 |
+
'nutrition': []
|
56 |
+
}
|
57 |
+
|
58 |
@menu_blueprint.route("/menu", methods=["GET", "POST"])
|
59 |
def menu():
|
60 |
+
# Authentication and session handling
|
61 |
selected_category = request.args.get("category", "All")
|
62 |
+
user_email = session.get('user_email') or request.args.get("email")
|
63 |
+
user_name = session.get('user_name') or request.args.get("name")
|
64 |
|
65 |
if not user_email:
|
66 |
+
return redirect(url_for("login"))
|
67 |
+
|
68 |
+
if not session.get('user_email'):
|
69 |
+
session['user_email'] = user_email
|
70 |
+
session['user_name'] = user_name
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
first_letter = user_name[0].upper() if user_name else "A"
|
73 |
|
74 |
try:
|
75 |
+
# Check available fields in Salesforce
|
76 |
+
available_fields = get_available_fields()
|
77 |
+
all_fields = available_fields['base'] + available_fields['nutrition']
|
78 |
+
|
79 |
+
# Fetch user data
|
80 |
+
user_data = sf.query(f"""
|
81 |
+
SELECT Referral__c, Reward_Points__c
|
82 |
+
FROM Customer_Login__c
|
83 |
+
WHERE Email__c = '{user_email}'
|
84 |
+
""").get('records', [{}])[0]
|
85 |
+
|
86 |
+
if not user_data:
|
87 |
return redirect(url_for('login'))
|
88 |
|
89 |
+
referral_code = user_data.get('Referral__c', 'N/A')
|
90 |
+
reward_points = user_data.get('Reward_Points__c', 0)
|
91 |
+
|
92 |
+
# Get cart count
|
93 |
+
cart_item_count = sf.query(f"""
|
94 |
+
SELECT COUNT()
|
95 |
+
FROM Cart_Item__c
|
96 |
+
WHERE Customer_Email__c = '{user_email}'
|
97 |
+
""")['totalSize']
|
98 |
+
|
99 |
+
# Fetch menu items with available fields
|
100 |
+
menu_items = sf.query(f"""
|
101 |
+
SELECT {', '.join(all_fields)}
|
102 |
+
FROM Menu_Item__c
|
103 |
+
""").get('records', [])
|
104 |
+
|
105 |
+
# Process items with nutrition data
|
106 |
+
for item in menu_items:
|
107 |
+
# Required fields
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
item['Total_Ordered__c'] = item.get('Total_Ordered__c', 0)
|
109 |
item['Video1__c'] = get_valid_video_path(item['Name'], item.get('Video1__c'))
|
110 |
|
111 |
+
# Nutrition fields with clear fallbacks
|
112 |
+
item['IngredientsInfo__c'] = item.get('IngredientsInfo__c',
|
113 |
+
'Ingredients information not available' if 'IngredientsInfo__c' in available_fields['nutrition']
|
114 |
+
else 'Ingredients data not configured')
|
115 |
+
|
116 |
+
item['Nutritional_Info__c'] = item.get('Nutritional_Info__c',
|
117 |
+
'Nutritional information not available' if 'Nutritional_Info__c' in available_fields['nutrition']
|
118 |
+
else 'Nutritional data not configured')
|
119 |
+
|
120 |
+
item['Allergens__c'] = item.get('Allergens__c',
|
121 |
+
'Allergen information not available' if 'Allergens__c' in available_fields['nutrition']
|
122 |
+
else 'Allergen data not configured')
|
123 |
+
|
124 |
+
# Filter by category
|
125 |
+
category_filter = {
|
126 |
+
"Veg": ["Veg", "both"],
|
127 |
+
"Non veg": ["Non veg", "both"],
|
128 |
+
"All": ["Veg", "Non veg", "both"]
|
129 |
+
}.get(selected_category, ["Veg", "Non veg", "both"])
|
130 |
+
|
131 |
+
filtered_items = [
|
132 |
+
item for item in menu_items
|
133 |
+
if item.get("Veg_NonVeg__c") in category_filter
|
134 |
+
]
|
135 |
|
136 |
+
# Get best sellers (top 4 most ordered)
|
137 |
+
best_sellers = sorted(
|
138 |
+
filtered_items,
|
139 |
+
key=lambda x: x.get("Total_Ordered__c", 0),
|
140 |
+
reverse=True
|
141 |
+
)[:4]
|
|
|
|
|
142 |
|
143 |
+
# Organize by sections
|
144 |
ordered_menu = {section: [] for section in SECTION_ORDER}
|
|
|
145 |
if best_sellers:
|
146 |
ordered_menu["Best Sellers"] = best_sellers
|
147 |
|
148 |
+
added_items = set()
|
149 |
+
for item in filtered_items:
|
|
|
150 |
section = item.get("Section__c", "Others")
|
151 |
+
if item['Name'] not in added_items:
|
152 |
+
ordered_menu.setdefault(section, []).append(item)
|
153 |
+
added_items.add(item['Name'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
+
# Clean empty sections
|
156 |
+
ordered_menu = {k: v for k, v in ordered_menu.items() if v}
|
|
|
|
|
|
|
|
|
157 |
|
158 |
except Exception as e:
|
159 |
+
print(f"Error in menu route: {str(e)}")
|
160 |
+
# Comprehensive fallback data
|
161 |
+
ordered_menu = {
|
162 |
+
"Best Sellers": [
|
163 |
+
{
|
164 |
+
"Name": "Chicken Biryani",
|
165 |
+
"Price__c": 14.99,
|
166 |
+
"Description__c": "Fragrant basmati rice with chicken and spices",
|
167 |
+
"Image1__c": "/static/placeholder.jpg",
|
168 |
+
"Veg_NonVeg__c": "Non veg",
|
169 |
+
"IngredientsInfo__c": "Chicken, basmati rice, yogurt, spices",
|
170 |
+
"Nutritional_Info__c": "Calories: 850, Protein: 45g",
|
171 |
+
"Allergens__c": "Dairy (yogurt)"
|
172 |
+
},
|
173 |
+
{
|
174 |
+
"Name": "Paneer Tikka",
|
175 |
+
"Price__c": 12.99,
|
176 |
+
"Description__c": "Grilled cottage cheese with spices",
|
177 |
+
"Image1__c": "/static/placeholder.jpg",
|
178 |
+
"Veg_NonVeg__c": "Veg",
|
179 |
+
"IngredientsInfo__c": "Paneer, bell peppers, spices",
|
180 |
+
"Nutritional_Info__c": "Calories: 420, Protein: 22g",
|
181 |
+
"Allergens__c": "Dairy (paneer)"
|
182 |
+
}
|
183 |
+
]
|
184 |
+
}
|
185 |
referral_code = 'N/A'
|
186 |
reward_points = 0
|
187 |
cart_item_count = 0
|
|
|
189 |
return render_template(
|
190 |
"menu.html",
|
191 |
ordered_menu=ordered_menu,
|
192 |
+
categories=["All", "Veg", "Non veg"],
|
193 |
selected_category=selected_category,
|
194 |
referral_code=referral_code,
|
195 |
reward_points=reward_points,
|
196 |
user_name=user_name,
|
197 |
first_letter=first_letter,
|
198 |
+
cart_item_count=cart_item_count,
|
199 |
+
show_nutrition=bool(available_fields['nutrition'])
|
200 |
)
|
201 |
|
202 |
@menu_blueprint.route('/api/addons', methods=['GET'])
|
203 |
def get_addons():
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
try:
|
205 |
+
item_section = request.args.get('item_section')
|
206 |
+
if not item_section:
|
207 |
+
return jsonify({"success": False, "error": "Section is required"}), 400
|
208 |
+
|
209 |
+
addons = sf.query(f"""
|
210 |
+
SELECT Name, Customization_Type__c, Options__c,
|
211 |
+
Max_Selections__c, Extra_Charge__c, Extra_Charge_Amount__c
|
212 |
FROM Customization_Options__c
|
213 |
WHERE Section__c = '{item_section}'
|
214 |
+
""").get('records', [])
|
|
|
|
|
|
|
|
|
|
|
215 |
|
216 |
formatted_addons = []
|
217 |
for addon in addons:
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
formatted_addons.append({
|
219 |
"name": addon["Name"],
|
220 |
"type": addon["Customization_Type__c"],
|
221 |
+
"options": addon.get("Options__c", "").split(", ") if addon.get("Options__c") else [],
|
222 |
"max_selections": addon.get("Max_Selections__c", 1),
|
223 |
"extra_charge": addon.get("Extra_Charge__c", False),
|
224 |
+
"extra_charge_amount": float(addon.get("Extra_Charge_Amount__c", 0))
|
225 |
})
|
226 |
|
227 |
return jsonify({"success": True, "addons": formatted_addons})
|
228 |
|
229 |
except Exception as e:
|
230 |
print(f"Error fetching addons: {str(e)}")
|
231 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
232 |
|
233 |
@menu_blueprint.route('/cart/add', methods=['POST'])
|
234 |
def add_to_cart():
|
235 |
try:
|
236 |
data = request.json
|
237 |
+
required_fields = ['itemName', 'itemPrice', 'category', 'section']
|
238 |
+
if not all(field in data for field in required_fields):
|
239 |
+
return jsonify({"success": False, "error": "Missing required fields"}), 400
|
240 |
+
|
241 |
+
if not session.get('user_email'):
|
242 |
+
return jsonify({"success": False, "error": "Not authenticated"}), 401
|
243 |
+
|
244 |
+
# Prepare cart item data
|
245 |
+
cart_data = {
|
246 |
+
"Name": data['itemName'].strip(),
|
247 |
+
"Price__c": float(data['itemPrice']),
|
248 |
+
"Base_Price__c": float(data['itemPrice']),
|
249 |
+
"Quantity__c": int(data.get('quantity', 1)),
|
250 |
+
"Customer_Email__c": session['user_email'],
|
251 |
+
"Category__c": data['category'],
|
252 |
+
"Section__c": data['section'],
|
253 |
+
"Image1__c": data.get('itemImage'),
|
254 |
+
"Instructions__c": data.get('instructions', '')[:255]
|
255 |
+
}
|
256 |
+
|
257 |
+
# Handle addons
|
258 |
addons = data.get('addons', [])
|
259 |
+
if addons:
|
260 |
+
addons_price = sum(float(a['price']) for a in addons)
|
261 |
+
addons_str = "; ".join(f"{a['name']} (${a['price']})" for a in addons)
|
262 |
+
cart_data.update({
|
263 |
+
"Add_Ons__c": addons_str,
|
264 |
+
"Add_Ons_Price__c": addons_price,
|
265 |
+
"Price__c": float(data['itemPrice']) * int(data.get('quantity', 1)) + addons_price
|
266 |
+
})
|
|
|
|
|
|
|
267 |
|
268 |
+
# Check if item already in cart
|
269 |
+
existing = sf.query(f"""
|
270 |
+
SELECT Id, Quantity__c, Add_Ons__c, Add_Ons_Price__c
|
271 |
FROM Cart_Item__c
|
272 |
+
WHERE Name = '{cart_data["Name"]}'
|
273 |
+
AND Customer_Email__c = '{session['user_email']}'
|
274 |
+
""").get('records', [])
|
275 |
+
|
276 |
+
if existing:
|
277 |
+
# Update existing item
|
278 |
+
existing = existing[0]
|
279 |
+
new_quantity = existing['Quantity__c'] + cart_data['Quantity__c']
|
280 |
+
new_addons = f"{existing.get('Add_Ons__c', '')}; {cart_data.get('Add_Ons__c', '')}".strip("; ")
|
281 |
+
new_addons_price = existing.get('Add_Ons_Price__c', 0) + cart_data.get('Add_Ons_Price__c', 0)
|
282 |
+
|
283 |
+
sf.Cart_Item__c.update(existing['Id'], {
|
284 |
+
"Quantity__c": new_quantity,
|
285 |
+
"Add_Ons__c": new_addons,
|
286 |
+
"Add_Ons_Price__c": new_addons_price,
|
287 |
+
"Price__c": (cart_data['Base_Price__c'] * new_quantity) + new_addons_price
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
288 |
})
|
289 |
else:
|
290 |
+
# Create new cart item
|
291 |
+
sf.Cart_Item__c.create(cart_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
292 |
|
293 |
+
return jsonify({"success": True, "message": "Added to cart"})
|
|
|
294 |
|
295 |
except Exception as e:
|
296 |
+
print(f"Error adding to cart: {str(e)}")
|
297 |
+
return jsonify({"success": False, "error": str(e)}), 500
|