File size: 18,852 Bytes
49fdcbd
5e02fef
49fdcbd
feb9c12
49fdcbd
19a5f27
49fdcbd
 
 
 
 
 
 
 
 
322e0f0
19a5f27
 
 
 
 
 
49fdcbd
 
19a5f27
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
49fdcbd
 
19a5f27
 
 
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
49fdcbd
 
19a5f27
 
 
49fdcbd
19a5f27
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49fdcbd
 
 
 
 
 
 
 
 
 
 
54351d9
49fdcbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54351d9
49fdcbd
 
f844bb0
19a5f27
 
 
 
49fdcbd
19a5f27
 
49fdcbd
19a5f27
49fdcbd
 
 
 
 
19a5f27
49fdcbd
19a5f27
49fdcbd
 
 
 
 
 
 
19a5f27
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
49fdcbd
19a5f27
 
49fdcbd
19a5f27
49fdcbd
19a5f27
 
 
 
49fdcbd
19a5f27
49fdcbd
19a5f27
 
49fdcbd
19a5f27
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49fdcbd
 
 
19a5f27
 
 
 
 
97368a2
49fdcbd
 
19a5f27
 
49fdcbd
19a5f27
 
97368a2
19a5f27
 
97368a2
19a5f27
 
 
 
 
 
97368a2
6546c7f
19a5f27
822593e
49fdcbd
 
 
97368a2
19a5f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
322e0f0
19a5f27
 
49fdcbd
 
19a5f27
 
49fdcbd
 
19a5f27
 
 
49fdcbd
19a5f27
 
 
49fdcbd
19a5f27
 
 
49fdcbd
19a5f27
49fdcbd
19a5f27
 
49fdcbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54351d9
49fdcbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a5f27
49fdcbd
 
 
19a5f27
49fdcbd
 
 
 
19a5f27
49fdcbd
19a5f27
49fdcbd
 
 
 
 
 
 
 
 
 
 
19a5f27
49fdcbd
 
 
19a5f27
 
49fdcbd
19a5f27
49fdcbd
 
 
19a5f27
 
 
 
 
49fdcbd
19a5f27
 
 
 
 
 
 
49fdcbd
19a5f27
 
49fdcbd
19a5f27
 
 
49fdcbd
 
 
19a5f27
 
 
49fdcbd
19a5f27
49fdcbd
19a5f27
 
 
49fdcbd
19a5f27
 
 
49fdcbd
19a5f27
 
 
 
49fdcbd
19a5f27
 
49fdcbd
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
from salesforce import get_salesforce_connection
import re

sf = get_salesforce_connection()
cart_blueprint = Blueprint('cart', __name__)

# Utility function to sanitize SOQL inputs
def sanitize_input(value):
    """Remove potentially dangerous characters for SOQL injection."""
    if value:
        # Remove quotes, semicolons, and other dangerous characters
        value = re.sub(r'[;\'"\\]', '', value)
    return value

@cart_blueprint.route("/cart", methods=["GET"])
def cart():
    email = session.get('user_email')
    if not email:
        return redirect(url_for("login"))

    try:
        # Sanitize email input
        sanitized_email = sanitize_input(email)
        # Fetch cart items with Category and Section
        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 = '{sanitized_email}'
        """)
        cart_items = result.get("records", [])

        subtotal = sum(item['Price__c'] for item in cart_items)

        # Fetch reward points
        customer_result = sf.query(f"""
            SELECT Reward_Points__c 
            FROM Customer_Login__c
            WHERE Email__c = '{sanitized_email}'
        """)
        reward_points = customer_result['records'][0].get('Reward_Points__c', 0) if customer_result['records'] else 0

        # Fetch coupons for the user
        coupon_result = sf.query(f"""
            SELECT Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{sanitized_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 = []

        # Initialize suggestions as an empty list
        suggestions = []

        # If there are items in the cart, fetch suggestions
        if cart_items:
            # Get the category and section of the first item in the cart
            first_item = cart_items[0]
            item_category = first_item.get('Category__c', 'All')
            item_section = first_item.get('Section__c', 'Biryanis')

            # Define section-to-complementary section mapping
            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']
            }

            # Get the complementary sections
            suggested_sections = complementary_sections.get(item_section, [])

            # Fetch suggestions from the complementary sections
            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 = '{sanitize_input(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 = '{sanitize_input(suggested_section)}' 
                            AND Veg_NonVeg__c = '{sanitize_input(item_category)}'
                            LIMIT 4
                        """
                    suggestion_result = sf.query(query)
                    suggestions.extend(suggestion_result.get("records", []))

                # Limit to 4 suggestions
                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("/fetch_menu_items", methods=["GET"])
def fetch_menu_items():
    try:
        # Get query parameters for filtering (optional)
        category = request.args.get('category', 'All')
        section = request.args.get('section', '')

        # Sanitize inputs
        category = sanitize_input(category)
        section = sanitize_input(section)

        # Build SOQL query (removed Active__c condition)
        query = """
            SELECT Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
            FROM Menu_Item__c
        """
        if category != 'All':
            query += f" AND Veg_NonVeg__c = '{category}'"
        if section:
            query += f" AND Section__c = '{section}'"
        query += " LIMIT 20"

        result = sf.query(query)
        menu_items = result.get("records", [])

        return jsonify({"success": True, "menu_items": menu_items})

    except Exception as e:
        print(f"Error fetching menu items: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500

@cart_blueprint.route("/add_suggestion_to_cart", methods=["POST"])
def add_suggestion_to_cart():
    try:
        # Get data from the request
        data = request.get_json()
        item_name = sanitize_input(data.get('item_name').strip())
        item_price = data.get('item_price')
        item_image = data.get('item_image')
        customer_email = sanitize_input(data.get('customer_email'))
        addons = data.get('addons', [])
        instructions = sanitize_input(data.get('instructions', ""))

        # Validate inputs
        if not all([item_name, item_price, customer_email]):
            return jsonify({"success": False, "error": "Missing required fields"}), 400

        # Process add-ons
        addons_price = 0
        addons_string = ", ".join(addons) if addons else "None"

        if addons:
            # Assuming addons are in format "Name ($Price)"
            addons_price = sum(
                float(addon.split("($")[1][:-1]) for addon in addons if "($" in addon
            )

        # Check if item exists in cart
        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:
            # Update existing item
            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', "")

            # Combine add-ons
            combined_addons = existing_addons if existing_addons != "None" else ""
            if addons:
                combined_addons = f"{combined_addons}, {addons_string}".strip(", ")

            # Combine instructions
            combined_instructions = existing_instructions
            if instructions:
                combined_instructions = f"{combined_instructions} | {instructions}".strip(" | ")

            combined_addons_price = existing_addons_price + addons_price

            # Update cart item
            sf.Cart_Item__c.update(cart_item_id, {
                "Quantity__c": existing_quantity + 1,
                "Add_Ons__c": combined_addons if combined_addons else "None",
                "Add_Ons_Price__c": combined_addons_price,
                "Instructions__c": combined_instructions,
                "Price__c": (existing_quantity + 1) * float(item_price) + combined_addons_price
            })
        else:
            # Create new cart item
            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)}), 500

@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
        
        sanitized_email = sanitize_input(customer_email)
        sanitized_item_name = sanitize_input(item_name)
        query = f"""
            SELECT Id FROM Cart_Item__c 
            WHERE Customer_Email__c = '{sanitized_email}' AND Name = '{sanitized_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 = sanitize_input(data.get('email'))
    item_name = sanitize_input(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')
    if not email:
        return jsonify({"success": False, "message": "User not logged in"}), 401

    try:
        sanitized_email = sanitize_input(email)
        # Fetch selected coupon
        data = request.json
        selected_coupon = data.get("selectedCoupon", "").strip() if data.get("selectedCoupon") else None

        # Fetch cart items
        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 = '{sanitized_email}'
        """)
        cart_items = result.get("records", [])
        if not cart_items:
            return jsonify({"success": False, "message": "Cart is empty"}), 400

        subtotal = sum(item['Price__c'] for item in cart_items)
        discount = 0

        # Apply coupon if selected
        if selected_coupon:
            discount = subtotal * 0.10  # 10% discount

        total = subtotal - discount

        # Prepare cart items for response
        bill_items = [
            {
                "name": item['Name'],
                "quantity": item['Quantity__c'],
                "price": item['Price__c'],
                "addons": item.get('Add_Ons__c', 'None'),
                "instructions": item.get('Instructions__c', 'None'),
                "image": item['Image1__c']
            } for item in cart_items
        ]

        # Fetch menu items for "Anything else you want?" (removed Active__c condition)
        menu_query = """
            SELECT Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
            FROM Menu_Item__c
            LIMIT 20
        """
        menu_result = sf.query(menu_query)
        menu_items = menu_result.get("records", [])

        return jsonify({
            "success": True,
            "cart": {
                "items": bill_items,
                "subtotal": subtotal,
                "discount": discount,
                "total": total,
                "selected_coupon": selected_coupon
            },
            "menu_items": menu_items
        })

    except Exception as e:
        print(f"Error during checkout: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500

@cart_blueprint.route("/submit_order", methods=["POST"])
def submit_order():
    email = session.get('user_email')
    user_id = session.get('user_name')
    table_number = session.get('table_number')

    if not email or not user_id:
        return jsonify({"success": False, "message": "User not logged in"}), 401

    try:
        sanitized_email = sanitize_input(email)
        data = request.json
        cart = data.get("cart")
        if not cart:
            return jsonify({"success": False, "message": "Cart data is required"}), 400

        # Fetch cart items to validate
        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 = '{sanitized_email}'
        """)
        cart_items = result.get("records", [])
        if not cart_items:
            return jsonify({"success": False, "message": "Cart is empty"}), 400

        subtotal = cart.get("subtotal")
        discount = cart.get("discount", 0)
        total = cart.get("total")
        selected_coupon = cart.get("selected_coupon")

        # Handle coupon redemption
        if selected_coupon:
            coupon_query = sf.query(f"""
                SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{sanitized_email}'
            """)
            if coupon_query["records"]:
                referral_coupon_id = coupon_query["records"][0]["Id"]
                existing_coupons = coupon_query["records"][0]["Coupon_Code__c"].split("\n")
                updated_coupons = [coupon for coupon in existing_coupons if coupon.strip() != selected_coupon]
                updated_coupons_str = "\n".join(updated_coupons).strip() or None
                sf.Referral_Coupon__c.update(referral_coupon_id, {
                    "Coupon_Code__c": updated_coupons_str
                })

        # Add reward points if no coupon
        if not selected_coupon:
            reward_points_to_add = subtotal * 0.10
            customer_record = sf.query(f"""
                SELECT Id, Reward_Points__c FROM Customer_Login__c
                WHERE Email__c = '{sanitized_email}'
            """)
            if customer_record["records"]:
                customer = customer_record["records"][0]
                current_reward_points = customer.get("Reward_Points__c", 0)
                new_reward_points = current_reward_points + reward_points_to_add
                sf.Customer_Login__c.update(customer["Id"], {
                    "Reward_Points__c": new_reward_points
                })

        # Prepare order details
        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
        )

        # Fetch Customer ID
        customer_query = sf.query(f"""
            SELECT Id FROM Customer_Login__c
            WHERE Email__c = '{sanitized_email}'
        """)
        customer_id = customer_query["records"][0]["Id"] if customer_query["records"] else None
        if not customer_id:
            return jsonify({"success": False, "message": "Customer record not found"}), 404

        table_number = table_number if table_number != 'null' else None
        order_data = {
            "Customer_Name__c": user_id,
            "Customer_Email__c": email,
            "Total_Amount__c": subtotal,
            "Discount__c": discount,
            "Total_Bill__c": total,
            "Order_Status__c": "Pending",
            "Customer2__c": customer_id,
            "Order_Details__c": order_details,
            "Table_Number__c": table_number
        }
        order_response = sf.Order__c.create(order_data)

        # Delete cart items
        if order_response:
            for item in cart_items:
                sf.Cart_Item__c.delete(item["Id"])

        return jsonify({"success": True, "message": "Order placed successfully!"})

    except Exception as e:
        print(f"Error during order submission: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500