File size: 20,838 Bytes
a7abf85
d3245ed
36d2eb6
b12f5e4
9bf1d7d
b12f5e4
1c327a4
 
 
a4ab8a7
f553154
 
85b9dbe
444fe60
a7abf85
01b8424
a7abf85
01b8424
 
 
a7abf85
01b8424
a7abf85
 
1c327a4
098997e
1c327a4
 
 
a69087c
d3245ed
 
 
8dec0d6
13d210d
 
 
98089df
 
 
 
 
 
 
 
3ad292c
a7abf85
 
c096c2c
 
 
4ad81b7
c096c2c
 
 
 
4ad81b7
 
c096c2c
 
 
1c327a4
c096c2c
7136825
4ad81b7
c096c2c
444fe60
5e4ad36
 
 
 
 
 
425a7d1
 
 
 
 
 
509b124
 
425a7d1
 
 
 
b531c61
 
 
 
 
 
 
 
 
 
 
f358ba9
b531c61
 
 
 
 
 
 
 
 
 
53027ce
b531c61
daf672f
 
 
 
 
 
 
ca21363
127463e
daf672f
 
f358ba9
daf672f
 
b531c61
daf672f
425a7d1
f358ba9
b531c61
f358ba9
 
 
 
 
 
 
 
 
 
 
 
d7eda21
 
 
 
f358ba9
 
d7eda21
b531c61
f358ba9
d7eda21
 
 
 
 
f358ba9
d7eda21
 
 
 
 
 
 
 
f358ba9
 
b531c61
425a7d1
 
6bbfc57
1c327a4
 
6479332
 
 
f8008d1
1c327a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8008d1
6479332
 
1c327a4
6479332
 
 
f8008d1
6479332
1c327a4
f8008d1
6479332
 
f8008d1
1c327a4
 
f8008d1
 
1c327a4
 
6479332
1c327a4
6479332
 
 
1c327a4
 
 
6479332
 
 
 
 
1c327a4
 
 
 
 
6479332
 
1c327a4
9de76b8
6307340
 
1c327a4
 
98312f8
5c3223b
 
 
6bbfc57
5c3223b
6bbfc57
 
5c3223b
6bbfc57
5c3223b
 
6bbfc57
5c3223b
6bbfc57
 
 
1c327a4
 
5c3223b
d316910
1c327a4
 
 
 
dc5e8d2
 
1c327a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9de76b8
1c327a4
 
 
 
 
 
 
 
 
9de76b8
dc5e8d2
5c3223b
6bbfc57
 
 
 
1c327a4
 
820dc7a
80bae4f
 
 
 
 
 
 
 
 
 
 
 
 
 
9bf1d7d
 
 
f62a0a9
 
80f989c
 
 
0270ecb
 
 
 
 
80f989c
 
 
9de76b8
a7abf85
 
 
 
 
7bec215
a7abf85
d792a6f
 
 
a7abf85
8d8058b
5e4ad36
7bec215
 
b97f93a
 
7bec215
 
 
b97f93a
 
d792a6f
 
b35dc9c
d792a6f
 
 
 
 
5e4ad36
d792a6f
5e4ad36
2b574f3
5e4ad36
8d8058b
5e4ad36
 
8d8058b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35dc9c
8d8058b
 
 
5e4ad36
bb11e62
a7abf85
 
 
 
98089df
5e4ad36
d792a6f
a7abf85
8d8058b
a7abf85
d792a6f
a7abf85
 
5e4ad36
a7abf85
444fe60
1c327a4
 
 
494fc19
 
 
 
 
 
a60e6aa
494fc19
9fec724
494fc19
 
 
 
 
 
b95cfbd
9fec724
 
 
 
 
b95cfbd
9fec724
494fc19
9fec724
494fc19
 
9fec724
494fc19
 
 
 
 
 
 
9fec724
494fc19
 
 
9fec724
494fc19
 
 
 
9fec724
a60e6aa
1c327a4
a60e6aa
494fc19
 
 
a60e6aa
494fc19
 
 
098997e
494fc19
1c327a4
8a35f9b
 
b01288a
ee41888
006cdd2
 
a7abf85
fcdec6b
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_session import Session  # Import the Session class
from flask.sessions import SecureCookieSessionInterface  # Import the class
from salesforce import get_salesforce_connection
from datetime import timedelta
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from Menu_page import menu_page  # Make sure this import is correct
#from cart import cart_blueprint  # Same for other blueprints
#rom order import order_blueprint  # Same for user blueprint


# Initialize Flask app and Salesforce connection
print("Starting app...")
app = Flask(__name__)
print("Flask app initialized.")

# Add debug logs in Salesforce connection setup
sf = get_salesforce_connection()
print("Salesforce connection established.")

# Set the secret key to handle sessions securely
app.secret_key = os.getenv("SECRET_KEY", "xEr0cwgsiatzrzaeFewYrVA1O")  # Replace with a secure key

app.config["SESSION_TYPE"] = "filesystem"  # Storing sessions in filesystem
app.config["SESSION_COOKIE_SECURE"] = True  # Enabling secure cookies (ensure your app is served over HTTPS)
app.config["SESSION_COOKIE_SAMESITE"] = "None"  # Cross-site cookies allowed

# Initialize the session
Session(app)  # Correctly initialize the Session object
print("Session interface configured.")

# Ensure secure session handling for environments like Hugging Face
app.session_interface = SecureCookieSessionInterface()
print("Session interface configured.")
import random
import string

def generate_referral_code(length=8):
    # Generates a random referral code with uppercase, lowercase letters, and digits
    characters = string.ascii_letters + string.digits  # A-Z, a-z, 0-9
    referral_code = ''.join(random.choice(characters) for _ in range(length))
    return referral_code

@app.route("/")
def home():
    # Fetch user details from URL parameters
    user_email = request.args.get("email")
    user_name = request.args.get("name")
    table_number = request.args.get("table")  # Capture table number

    if user_email and user_name:
        session["user_email"] = user_email
        session["user_name"] = user_name
        session["table_number"] = table_number  # Store table number in session
        print(f"User logged in: {user_email} - {user_name} - Table: {table_number}")

        # Ensure session is saved before redirecting
        session.modified = True
        return redirect(url_for("menu.menu"))  # Redirect to menu directly

    return render_template("index.html")



from datetime import datetime

def generate_coupon_code(length=10):
    """Generates a random alphanumeric coupon code"""
    characters = string.ascii_uppercase + string.digits  # A-Z, 0-9
    return ''.join(random.choice(characters) for _ in range(length))
@app.route("/generate_custom_dish", methods=["POST"])
def generate_custom_dish():
    try:
        data = request.form
        dish_name = data.get("name")
        description = data.get("description")
        item_image_url = "https://huggingface.co/spaces/nagasurendra/BiryaniHubflask30/resolve/main/static/customized.jpg"
        item_image_url2 = "https://huggingface.co/spaces/nagasurendra/BiryaniHubflask30/resolve/main/static/customized1.jpg"

        if not dish_name or not description:
            return jsonify({"success": False, "error": "Both fields are required"}), 400

        # Generate a random price for the custom dish
        price = random.randint(10, 30)  # Example logic for price setting

        # Determine Veg/Non-Veg
        veg_keywords = ["paneer", "vegetable", "mushroom", "cheese"]
        non_veg_keywords = ["chicken", "mutton", "fish", "egg"]
        
        category = "Veg" if any(word in description.lower() for word in veg_keywords) else \
                   "Non veg" if any(word in description.lower() for word in non_veg_keywords) else \
                   "both"

        # Query to check if the dish already exists in Salesforce (Custom_Dish__c object)
        existing_dish_query = f"SELECT Id, Name, Price__c, Image1__c, Image2__c, Description__c, Veg_NonVeg__c FROM Custom_Dish__c WHERE Name = '{dish_name}'"
        existing_dish_result = sf.query(existing_dish_query)

        if existing_dish_result['totalSize'] > 0:
            # If the dish exists, use the existing details
            existing_dish = existing_dish_result['records'][0]
            price = existing_dish['Price__c']
            item_image_url = existing_dish['Image1__c']
            item_image_url2 = existing_dish['Image2__c']
            category = existing_dish['Veg_NonVeg__c']
        else:
            # If the dish does not exist, create a new custom dish
            custom_dish = {
                'Name': dish_name,
                'Price__c': price,
                'Image1__c': item_image_url,
                'Image2__c': item_image_url2,
                'Description__c': description,
                'Veg_NonVeg__c': category,
                'Section__c': 'Customized dish',
                'Total_Ordered__c': 0
            }

            # Insert the custom dish into Salesforce (Custom_Dish__c object)
            result = sf.Custom_Dish__c.create(custom_dish)

            if not result.get('success'):
                return jsonify({"success": False, "error": "Failed to create custom dish in Salesforce"}), 500

        # After ensuring the dish exists, check if it's already in the Cart_Item__c
        email = session.get('user_email')  # Assuming you have the user's email in session
        
        # Query to check if the custom dish already exists in the cart for the logged-in user
        cart_item_query = f"SELECT Id, Quantity__c, Price__c, Base_Price__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name = '{dish_name}'"
        cart_item_result = sf.query(cart_item_query)

        if cart_item_result['totalSize'] > 0:
            # If the custom dish is already in the cart, update the quantity and price
            cart_item = cart_item_result['records'][0]
            new_quantity = cart_item['Quantity__c'] + 1  # Increase quantity by 1
            new_price = price * new_quantity  # Update price based on new quantity
            
            # Update the cart item in Salesforce
            updated_cart_item = {
                'Quantity__c': new_quantity,
                'Price__c': new_price
            }
            
            cart_item_update = sf.Cart_Item__c.update(cart_item['Id'], updated_cart_item)

        else:
            # If the custom dish is not in the cart, create a new cart item
            cart_item = {
                'Name': dish_name,
                'Price__c': price,
                'Base_Price__c': price,
                'Image1__c': item_image_url,
                'Quantity__c': 1,  # Default quantity is 1
                'Add_Ons__c': '',  # Set Add_ons__c to empty
                'Add_Ons_Price__c': 0,  # Set Add_ons_Price__c to 0
                'Customer_Email__c': email  # Associate the custom dish with the logged-in user
            }

            # Insert the custom dish as a Cart_Item__c record in Salesforce
            cart_result = sf.Cart_Item__c.create(cart_item)

        # Redirect to the cart page after successfully adding or updating the cart item
        return redirect(url_for("cart"))

    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/customer_details", methods=["GET"])
def customer_details():
    email = session.get('user_email')  # Get logged-in user's email
    if not email:
        return redirect(url_for("login"))

    try:
        # Fetch customer details from Salesforce based on the email
        customer_record = sf.query(f"""
            SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
            FROM Customer_Login__c
            WHERE Email__c = '{email}'
            LIMIT 1
        """)

        if not customer_record.get("records"):
            flash("Customer not found", "danger")
            return redirect(url_for("login"))

        customer = customer_record["records"][0]

        # Prepare the data to return to the frontend
        customer_data = {
            "name": customer.get("Name", ""),
            "email": customer.get("Email__c", ""),
            "phone": customer.get("Phone_Number__c", ""),
            "referral_code": customer.get("Referral__c", ""),
            "reward_points": customer.get("Reward_Points__c", 0)
        }

        return render_template("customer_details.html", customer=customer_data)

    except Exception as e:
        flash(f"Error fetching customer details: {str(e)}", "danger")
        return redirect(url_for("login"))

@app.route("/update_profile", methods=["POST"])
def update_profile():
    email = session.get('user_email')  # Get logged-in user's email
    if not email:
        return jsonify({'status': 'error', 'message': 'User not logged in'})

    try:
        # Fetch user details from Salesforce
        result = sf.query(f"""
            SELECT Id, Name, Email__c, Phone_Number__c, Referral__c, Reward_Points__c
            FROM Customer_Login__c
            WHERE Email__c = '{email}'
        """)

        if not result['records']:
            return jsonify({'status': 'error', 'message': 'User not found'})

        user = result['records'][0]
        user_id = user.get("Id")

        # Get updated profile data from the form
        new_name = request.form.get('customerName')
        new_email = request.form.get('email')
        new_phone = request.form.get('phone')
        new_referral_code = request.form.get('referralCode')
        new_reward_points = request.form.get('rewardPoints')

        # Prepare data for Salesforce update
        update_data = {
            'Name': new_name,
            'Email__c': new_email,
            'Phone_Number__c': new_phone,
            'Referral__c': new_referral_code,
            'Reward_Points__c': new_reward_points
        }

        # Update Salesforce record
        sf.Customer_Login__c.update(user_id, update_data)

        return jsonify({
            'status': 'success',
            'message': 'Profile updated successfully!',
            'data': update_data
        })

    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})



from datetime import datetime
import pytz  # Library to handle timezone conversions

@app.route("/order-history", methods=["GET"])
def order_history():
    email = session.get('user_email')  # Get logged-in user's email
    if not email:
        return redirect(url_for("login"))

    try:
        # Fetch past orders for the user
        result = sf.query(f"""
            SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, 
                   Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c, CreatedDate
            FROM Order__c
            WHERE Customer_Email__c = '{email}'
            ORDER BY CreatedDate DESC
        """)

        print(f"Salesforce query result: {result}")  # Debugging line

        orders = result.get("records", [])  # Fetch all orders

        if not orders:
            print("No orders found for this email.")  # Debugging line

        # Format the order details for better readability
        for order in orders:
            order_details = order.get("Order_Details__c", "")
            items = order_details.split("\n")  # Assuming each item is separated by a new line
            formatted_items = []

            # Loop through the items and format them as "item name * quantity"
            for item in items:
                item_details = item.split(" | ")
                if len(item_details) > 1:
                    name = item_details[0].strip()
                    quantity = item_details[1].strip()
                    formatted_items.append(f"{name} * {quantity}")

            # Join the formatted items into a single string
            order['formatted_items'] = ", ".join(formatted_items)

            # Get the order date and time from CreatedDate
            created_date = order.get("CreatedDate", "")
            if created_date:
                # Convert CreatedDate to datetime object in UTC
                utc_datetime = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.000+0000')
                utc_datetime = utc_datetime.replace(tzinfo=pytz.UTC)
            
                # Convert UTC datetime to the desired timezone (e.g., IST)
                local_timezone = pytz.timezone('Asia/Kolkata')  # Replace with your timezone
                local_datetime = utc_datetime.astimezone(local_timezone)

                # Format the date and time in the desired format
                order['formatted_date'] = local_datetime.strftime('%B %d, %I:%M %p')

            order_status = order.get("Order_Status__c", "N/A")  # Default to "N/A" if no status
            order['order_status'] = order_status


        return render_template("order_history.html", orders=orders)

    except Exception as e:
        print(f"Error fetching order history: {str(e)}")
        return render_template("order_history.html", orders=[], error=str(e))


app.permanent_session_lifetime = timedelta(minutes=5)
@app.before_request
def check_session_timeout():
    if "last_activity" in session:
        last_activity_time = session["last_activity"]
        now = datetime.now().timestamp()
        
        # Check if inactivity time has exceeded 5 minutes (300 seconds)
        if now - last_activity_time > 300:
            session.clear()  # Clear session
            return redirect(url_for("logout"))
    
    # Update last activity timestamp on every request
    session["last_activity"] = datetime.now().timestamp()

@app.route("/dashboard")
def dashboard():
    return render_template("dashboard.html") 
@app.route("/logout")
def logout():
    # Retrieve table number before clearing session
    table_number = session.get('table_number', '')

    # Clear session variables
    session.pop('name', None)
    session.pop('email', None)
    session.pop('rewardPoints', None)
    session.pop('coupon', None)

    # Pass table number to redirect page
    return render_template("redirect_page.html", table_number=table_number)

@app.route("/signup", methods=["GET", "POST"])
def signup():
    if request.method == "POST":
        name = request.form.get("name")
        phone = request.form.get("phone")
        email = request.form.get("email").strip()  # Trim spaces
        password = request.form.get("password")
        referral_code = request.form.get("referral")  # Fetch referral code from the form
        generated_referral_code = generate_referral_code()

        try:
            ref = 0  # Default reward points for new user

            # **Fix: Fetch all emails and compare in Python (Case-Insensitive)**
            email_query = "SELECT Id, Email__c FROM Customer_Login__c"
            email_result = sf.query(email_query)

            # Convert all stored emails to lowercase and compare with user input
            existing_emails = {record["Email__c"].lower() for record in email_result["records"]}
            if email.lower() in existing_emails:
                return render_template("signup.html", error="Email already in use! Please use a different email.")

            # Check if a referral code is entered
            if referral_code:
                referral_query = f"SELECT Id, Email__c, Name FROM Customer_Login__c WHERE Referral__c = '{referral_code}'"
                referral_result = sf.query(referral_query)

                if not referral_result['records']:
                    return render_template("signup.html", error="Invalid referral code!")

                # Get referrer's details
                referrer = referral_result['records'][0]
                referrer_email = referrer.get('Email__c')
                referrer_name = referrer.get('Name')

                # Generate a new unique coupon code
                new_coupon_code = generate_coupon_code()

                # Check if referrer already has a record in Referral_Coupon__c
                existing_coupon_query = f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{referrer_email}'"
                existing_coupon_result = sf.query(existing_coupon_query)

                if existing_coupon_result['records']:
                    referral_record = existing_coupon_result['records'][0]
                    referral_id = referral_record['Id']
                    existing_coupons = referral_record.get('Coupon_Code__c', '')

                    updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()

                    # Update the existing record with the new coupon
                    sf.Referral_Coupon__c.update(referral_id, {
                        "Coupon_Code__c": updated_coupons
                    })
                else:
                    # If no record exists, create a new one
                    sf.Referral_Coupon__c.create({
                        "Name": referrer_name,
                        "Referral_Email__c": referrer_email,
                        "Coupon_Code__c": new_coupon_code
                    })

            # **Fix: Ensure Salesforce enforces unique email constraint**
            sf.Customer_Login__c.create({
                "Name": name,
                "Phone_Number__c": phone,
                "Email__c": email,
                "Password__c": password,
                "Reward_Points__c": ref,  # No points added, only coupon is created
                "Referral__c": generated_referral_code
            })

            return redirect(url_for("login"))

        except Exception as e:
            return render_template("signup.html", error=f"Error: {str(e)}")

    return render_template("signup.html")




@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        email = request.form.get("email")
        password = request.form.get("password")
        print(f"Login attempt with email: {email}")  # Debug log

        try:
            # Fetch user details from Salesforce
            query = f"SELECT Id, Name, Email__c, Reward_Points__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
            result = sf.query(query)

            if result["records"]:
                user = result["records"][0]
                session['user_id'] = user['Id']

                # ✅ Always store or update session email
                if 'user_email' not in session or session['user_email'] != email:
                    session['user_email'] = email
                    session['user_name'] = user.get("Name", "")
                    print(f"✅ Session email updated: {session['user_email']}")

                reward_points = user.get("Reward_Points__c") or 0

                # Coupon generation logic (if reward points >= 500)
                if reward_points >= 500:
                    new_coupon_code = generate_coupon_code()
                    coupon_query = sf.query(f"SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}'")

                    if coupon_query["records"]:
                        coupon_record = coupon_query["records"][0]
                        referral_coupon_id = coupon_record["Id"]
                        existing_coupons = coupon_record.get("Coupon_Code__c", "")

                        updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip()
                        sf.Referral_Coupon__c.update(referral_coupon_id, {"Coupon_Code__c": updated_coupons})
                    else:
                        sf.Referral_Coupon__c.create({
                            "Referral_Email__c": email,
                            "Name": user.get("Name", ""),
                            "Coupon_Code__c": new_coupon_code
                        })

                    new_reward_points = reward_points - 500
                    sf.Customer_Login__c.update(user['Id'], {"Reward_Points__c": new_reward_points})

                return redirect(url_for("menu.menu"))

            else:
                print("Invalid credentials!")
                return render_template("login.html", error="Invalid credentials!")

        except Exception as e:
            print(f"Error during login: {str(e)}")
            return render_template("login.html", error=f"Error: {str(e)}")

    return render_template("login.html")
# Register Blueprints for each functionality
app.register_blueprint(menu_page)
#app.register_blueprint(cart_blueprint, url_prefix='/cart')  # Register the cart blueprint with URL prefix

#app.register_blueprint(order_blueprint)


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=7860)