File size: 12,894 Bytes
211d39c
4a9aef9
a7e3033
621242c
a7e3033
621242c
 
ebdfd29
621242c
ebdfd29
a7e3033
621242c
6283128
 
621242c
ebdfd29
6283128
a7e3033
ebdfd29
621242c
6283128
ebdfd29
 
 
 
a7e3033
6283128
a7e3033
6283128
 
a7e3033
6283128
 
a7e3033
6283128
a7e3033
ebdfd29
a7e3033
ebdfd29
a7e3033
ebdfd29
 
6283128
621242c
6283128
 
 
211d39c
6283128
621242c
6283128
 
a7e3033
 
211d39c
 
 
6283128
 
 
 
621242c
ebdfd29
 
 
a7e3033
ebdfd29
a7e3033
 
ebdfd29
 
 
 
 
 
a7e3033
ebdfd29
a7e3033
ebdfd29
a7e3033
ebdfd29
a7e3033
 
 
ebdfd29
 
a7e3033
 
ebdfd29
a7e3033
ebdfd29
a7e3033
 
 
 
 
 
ebdfd29
a7e3033
 
ebdfd29
 
 
a7e3033
ebdfd29
 
a7e3033
ebdfd29
a7e3033
 
 
ebdfd29
a7e3033
 
ebdfd29
 
 
29a2fcc
a7e3033
 
ebdfd29
 
 
 
 
a7e3033
 
 
 
 
29a2fcc
ebdfd29
a7e3033
ebdfd29
 
 
 
 
 
a7e3033
ebdfd29
a7e3033
ebdfd29
 
 
 
 
 
 
 
 
 
 
a7e3033
 
 
 
 
 
 
 
 
 
 
ebdfd29
 
 
 
6283128
 
 
 
 
 
 
 
 
 
 
 
0140872
 
a7e3033
 
ebdfd29
6283128
ebdfd29
 
0140872
ebdfd29
a7e3033
ebdfd29
 
 
a7e3033
211d39c
ebdfd29
 
 
 
 
 
 
a7e3033
 
 
 
 
ebdfd29
a7e3033
 
ebdfd29
 
 
 
 
 
6283128
ebdfd29
0140872
ebdfd29
 
0140872
 
 
 
ebdfd29
 
a7e3033
 
6283128
 
a7e3033
 
 
6283128
 
a7e3033
 
 
 
 
6283128
ebdfd29
a7e3033
ebdfd29
 
 
74528d3
ebdfd29
 
a7e3033
 
ebdfd29
 
a7e3033
 
 
 
 
ebdfd29
 
a7e3033
ebdfd29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7e3033
ebdfd29
 
211d39c
0140872
a7e3033
 
 
 
ebdfd29
a7e3033
211d39c
6283128
211d39c
6283128
 
211d39c
a7e3033
6283128
 
 
 
 
211d39c
74528d3
ebdfd29
 
a7e3033
 
 
211d39c
ebdfd29
a7e3033
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
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
from salesforce import get_salesforce_connection
import os

menu_blueprint = Blueprint('menu', _name_)

# Initialize Salesforce connection
sf = get_salesforce_connection()

# Constants for video handling
STATIC_DIR = os.path.join(os.path.dirname(_file_), 'static')
PLACEHOLDER_VIDEO = 'placeholder.mp4'
PLACEHOLDER_PATH = os.path.join(STATIC_DIR, PLACEHOLDER_VIDEO)
SECTION_ORDER = ["Best Sellers", "Starters", "Biryanis", "Curries", "Breads", "Customized dish", "Apetizer", "Desserts", "Soft Drinks"]

# Create placeholder video at startup if it doesn't exist
if not os.path.exists(PLACEHOLDER_PATH):
    open(PLACEHOLDER_PATH, 'wb').close()
    print(f"Created placeholder video at {PLACEHOLDER_PATH}")

def get_valid_video_path(item_name, video_url=None):
    """
    Get valid video path for item with placeholder fallback
    Priority: 1. Video1__c from Salesforce 2. placeholder.mp4
    """
    # First try: Video1__c from Salesforce if provided
    if video_url:
        # If it's a complete URL (http/https)
        if video_url.startswith(('http://', 'https://')):
            return video_url
        # If it's a relative path (/videos/xxx.mp4)
        elif video_url.startswith('/'):
            return video_url
        # If it's a Salesforce File ID (starts with '069')
        elif video_url.startswith('069'):
            return f"https://yourdomain.my.salesforce.com/sfc/servlet.shepherd/version/download/{video_url}"
    
    # Final fallback: placeholder.mp4
    if not os.path.exists(PLACEHOLDER_PATH):
        open(PLACEHOLDER_PATH, 'wb').close()
        print(f"Created missing placeholder video at {PLACEHOLDER_PATH}")
    
    return f"/static/{PLACEHOLDER_VIDEO}"

@menu_blueprint.route("/menu", methods=["GET", "POST"])
def menu():
    selected_category = request.args.get("category", "All")
    user_email = session.get('user_email')

    if not user_email:
        user_email = request.args.get("email")
        user_name = request.args.get("name")

        if user_email:
            session['user_email'] = user_email
            session['user_name'] = user_name
        else:
            return redirect(url_for("login"))
    else:
        user_name = session.get('user_name')

    first_letter = user_name[0].upper() if user_name else "A"

    try:
        # Fetch user referral and reward points
        user_query = f"SELECT Referral_c, Reward_Pointsc FROM Customer_Loginc WHERE Email_c = '{user_email}'"
        user_result = sf.query(user_query)

        if not user_result['records']:
            return redirect(url_for('login'))

        referral_code = user_result['records'][0].get('Referral__c', 'N/A')
        reward_points = user_result['records'][0].get('Reward_Points__c', 0)

        # Get cart item count
        cart_query = f"SELECT COUNT() FROM Cart_Item_c WHERE Customer_Email_c = '{user_email}'"
        cart_count_result = sf.query(cart_query)
        cart_item_count = cart_count_result['totalSize']

        # Query to fetch Menu_Item_c records including Video1c, Ingredientsinfoc, NutritionalInfoc, Allergens_c
        menu_query = """
            SELECT Name, Price_c, Descriptionc, Image1c, Image2_c, 
                   Veg_NonVeg_c, Sectionc, Total_Orderedc, Video1_c, 
                   Ingredientsinfo_c, NutritionalInfoc, Allergens_c
            FROM Menu_Item__c
        """
        result = sf.query(menu_query)
        food_items = result['records'] if 'records' in result else []

        # Process items and add video paths, ingredients, nutritional info, and allergens
        for item in food_items:
            item['Ingredientsinfo_c'] = item.get('Ingredientsinfo_c', 'Not Available')
            item['NutritionalInfo_c'] = item.get('NutritionalInfo_c', 'Not Available')
            item['Allergens_c'] = item.get('Allergens_c', 'Not Available')
            item['Video1_c'] = get_valid_video_path(item['Name'], item.get('Video1_c'))

        # Query to fetch Custom_Dish__c records
        custom_dish_query = """
            SELECT Name, Price_c, Descriptionc, Image1c, Image2_c, 
                   Veg_NonVeg_c, Sectionc, Total_Ordered_c
            FROM Custom_Dish__c
            WHERE CreatedDate >= LAST_N_DAYS:7
        """
        custom_dish_result = sf.query(custom_dish_query)
        custom_dishes = custom_dish_result.get('records', [])

        # Process custom dishes and add video paths
        for item in custom_dishes:
            item['Ingredientsinfo__c'] = 'Custom Dish Ingredients'
            item['NutritionalInfo__c'] = 'Custom Dish Nutritional Info'
            item['Allergens__c'] = 'Custom Dish Allergens'
            item['Video1__c'] = get_valid_video_path(item['Name'])

        # Merge both Menu_Item_c and Custom_Dish_c records
        all_items = food_items + custom_dishes
        ordered_menu = {section: [] for section in SECTION_ORDER}

        # Process best sellers
        best_sellers = sorted(all_items, key=lambda x: x.get("Total_Ordered__c", 0), reverse=True)
        
        if selected_category == "Veg":
            best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Veg", "both"]]
        elif selected_category == "Non veg":
            best_sellers = [item for item in best_sellers if item.get("Veg_NonVeg__c") in ["Non veg", "both"]]

        best_sellers = best_sellers[:4]
        if best_sellers:
            ordered_menu["Best Sellers"] = best_sellers

        # Organize other sections
        added_item_names = set()
        for item in all_items:
            section = item.get("Section__c", "Others")
            if section not in ordered_menu:
                ordered_menu[section] = []

            if item['Name'] in added_item_names:
                continue

            if selected_category == "Veg" and item.get("Veg_NonVeg__c") not in ["Veg", "both"]:
                continue
            if selected_category == "Non veg" and item.get("Veg_NonVeg__c") not in ["Non veg", "both"]:
                continue

            ordered_menu[section].append(item)
            added_item_names.add(item['Name'])

        ordered_menu = {section: items for section, items in ordered_menu.items() if items}
        categories = ["All", "Veg", "Non veg"]

    except Exception as e:
        print(f"Error fetching menu data: {str(e)}")
        ordered_menu = {section: [] for section in SECTION_ORDER}
        best_sellers = ["Chicken Biryani", "Paneer Butter Masala", "Veg Manchurian", "Prawn Fry"]
        ordered_menu["Best Sellers"] = [{
            "Name": name,
            "Price__c": "12.99",
            "Description__c": f"Popular {name}",
            "Image1__c": "/static/placeholder.jpg",
            "Video1__c": get_valid_video_path(name),
            "Total_Ordered__c": 100,
            "Veg_NonVeg__c": "Veg" if "Paneer" in name or "Veg" in name else "Non veg"
        } for name in best_sellers]
        
        categories = ["All", "Veg", "Non veg"]
        referral_code = 'N/A'
        reward_points = 0
        cart_item_count = 0

    return render_template(
        "menu.html",
        ordered_menu=ordered_menu,
        categories=categories,
        selected_category=selected_category,
        referral_code=referral_code,
        reward_points=reward_points,
        user_name=user_name,
        first_letter=first_letter,
        cart_item_count=cart_item_count
    )
@menu_blueprint.route('/api/addons', methods=['GET'])
def get_addons():
    item_name = request.args.get('item_name')  
    item_section = request.args.get('item_section')  

    if not item_name or not item_section:
        return jsonify({"success": False, "error": "Item name and section are required."}), 400

    try:
        query = f"""
            SELECT Name, Customization_Type_c, Optionsc, Max_Selectionsc, Extra_Chargec, Extra_Charge_Amount_c
            FROM Customization_Options__c
            WHERE Section__c = '{item_section}'
        """
        result = sf.query(query)
        addons = result.get('records', [])

        if not addons:
            return jsonify({"success": False, "error": "No customization options found for the given section."}), 404

        formatted_addons = []
        for addon in addons:
            options = addon.get("Options__c", "")
            if options:
                options = options.split(", ")
            else:
                options = []

            formatted_addons.append({
                "name": addon["Name"],
                "type": addon["Customization_Type__c"],
                "options": options,
                "max_selections": addon.get("Max_Selections__c", 1),
                "extra_charge": addon.get("Extra_Charge__c", False),
                "extra_charge_amount": addon.get("Extra_Charge_Amount__c", 0)
            })

        return jsonify({"success": True, "addons": formatted_addons})

    except Exception as e:
        print(f"Error fetching addons: {str(e)}")
        return jsonify({"success": False, "error": "An error occurred while fetching customization options."}), 500

@menu_blueprint.route('/cart/add', methods=['POST'])
def add_to_cart():
    try:
        data = request.json
        item_name = data.get('itemName', '').strip()
        item_price = data.get('itemPrice')
        item_image = data.get('itemImage')
        addons = data.get('addons', [])
        instructions = data.get('instructions', '')
        category = data.get('category')
        section = data.get('section')
        quantity = data.get('quantity', 1)
        customer_email = session.get('user_email')

        if not item_name or not item_price:
            return jsonify({"success": False, "error": "Item name and price are required."}), 400

        if not customer_email:
            return jsonify({"success": False, "error": "User email is required."}), 400

        query = f"""
            SELECT Id, Quantity_c, Add_Onsc, Add_Ons_Pricec, 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", [])

        addons_price = sum(addon['price'] for addon in addons)
        new_addons = "; ".join([f"{addon['name']} (${addon['price']})" for addon in addons])

        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 new_addons:
                combined_addons = f"{combined_addons}; {new_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 + quantity,
                "Add_Ons__c": combined_addons,
                "Add_Ons_Price__c": combined_addons_price,
                "Instructions__c": combined_instructions,
                "Price__c": (existing_quantity + quantity) * item_price + combined_addons_price,
                "Category__c": category,
                "Section__c": section
            })
        else:
            addons_string = "None"
            if addons:
                addons_string = new_addons

            total_price = item_price * quantity + addons_price

            sf.Cart_Item__c.create({
                "Name": item_name,
                "Price__c": total_price,
                "Base_Price__c": item_price,
                "Quantity__c": quantity,
                "Add_Ons_Price__c": addons_price,
                "Add_Ons__c": addons_string,
                "Image1__c": item_image,
                "Customer_Email__c": customer_email,
                "Instructions__c": instructions,
                "Category__c": category,
                "Section__c": section
            })

        return jsonify({"success": True, "message": "Item added to cart successfully."})

    except KeyError as e:
        return jsonify({"success": False, "error": f"Missing required field: {str(e)}"}), 400

    except Exception as e:
        print(f"Error adding item to cart: {str(e)}")
        return jsonify({"success": False, "error": "An error occurred while adding the item to the cart."}), 500