File size: 11,159 Bytes
a7abf85
d3245ed
36d2eb6
b12f5e4
9bf1d7d
5324aa9
 
8369d3e
 
386c140
d8f342f
6218638
174e074
6218638
 
6d3b7e8
d38824d
6218638
 
 
 
 
 
a7abf85
6218638
01b8424
 
a7abf85
6218638
a7abf85
 
4c2d5e8
d831144
 
 
a69087c
d3245ed
 
13d210d
6218638
145b38f
6218638
 
 
d8f342f
174e074
d8f342f
6218638
3ad292c
a7abf85
 
c096c2c
 
 
4ad81b7
c096c2c
 
 
4ad81b7
 
c096c2c
 
 
1fd9c90
7136825
040f053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2731d4a
040f053
 
 
 
 
 
 
 
 
 
cac425f
7180263
b5a097d
23cff82
6790316
 
 
c8fa1a3
6790316
23cff82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d17cd9b
 
 
 
5233fbf
23cff82
 
 
d17cd9b
23cff82
91cf47e
5233fbf
d17cd9b
23cff82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c60dbe
23cff82
 
 
 
 
 
60f97d7
23cff82
 
 
 
 
cf18aa4
c8fa1a3
9f2c95d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5233fbf
 
23cff82
 
 
 
 
 
 
 
5233fbf
 
 
9f2c95d
6a82ae2
23cff82
6a82ae2
1fb4cf5
c8fa1a3
7180263
f62a0a9
 
80f989c
 
 
0270ecb
 
 
 
 
80f989c
 
 
9de76b8
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
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
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from menu import menu_blueprint  # Make sure this import is correct
from cart import cart_blueprint  # Same for other blueprints
from order import order_blueprint  # Same for user blueprint
from orderhistory import orderhistory_blueprint
from user_details import user_details_blueprint
from customdish import customdish_blueprint
from datetime import datetime
from datetime import datetime
from flask import Flask, redirect, url_for

import pytz  # Library to handle timezone conversions
import os
import smtplib
import random
import string

app = Flask(__name__)


# Add debug logs in Salesforce connection setup
sf = get_salesforce_connection()


# Set the secret key to handle sessions securely
app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q")  # 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
app.session_interface = SecureCookieSessionInterface()

app.register_blueprint(cart_blueprint, url_prefix='/cart') 
app.register_blueprint(user_details_blueprint, url_prefix='/user')
app.register_blueprint(menu_blueprint)
app.register_blueprint(order_blueprint)
app.register_blueprint(orderhistory_blueprint, url_prefix='/orderhistory')
app.register_blueprint(customdish_blueprint, url_prefix='/customdish')



@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")
@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")


@app.route('/combined_summary')
def combined_summary():
    email = session.get('user_email')
    if not email:
        return "User not logged in", 400

    try:
        # ====== FETCH REWARDS ======
        reward_query = f"SELECT Id, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{email}'"
        reward_data = sf.query(reward_query)
        if not reward_data.get("records"):
            return "Reward info not found", 400

        user_points = reward_data["records"][0].get("Reward_Points__c", 0)

        # Determine tier
        tiers = {
            "Bronze": 100,
            "Silver": 200,
            "Gold": 300,
            "Platinum": 500
        }
        current_tier, next_tier = "Bronze", "Silver"
        start_point, end_point = 0, 100
        if user_points >= 100 and user_points < 200:
            current_tier, next_tier = "Silver", "Gold"
            start_point, end_point = 100, 200
        elif user_points >= 200 and user_points < 300:
            current_tier, next_tier = "Gold", "Platinum"
            start_point, end_point = 200, 300
        elif user_points >= 300:
            current_tier, next_tier = "Platinum", "N/A"
            start_point, end_point = 300, 500

        progress_percentage = ((user_points - start_point) / (end_point - start_point)) * 100 if end_point != start_point else 100
        points_needed_for_next_tier = max(0, end_point - user_points)

        # ====== FETCH ORDER SUMMARY ======
        order_query = f"""
            SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c, 
                   Order_Status__c, Discount__c, Total_Bill__c
            FROM Order__c
            WHERE Customer_Email__c = '{email}'
            ORDER BY CreatedDate DESC
            LIMIT 1
        """
        order_result = sf.query(order_query)
        if not order_result.get("records"):
            return "No order found", 400

        order = order_result["records"][0]
        order_details = order.get("Order_Details__c", "")
        order_items = []

        for line in order_details.split('\n'):
            item_parts = line.split('|')
            if len(item_parts) >= 5:
                item_name_raw = item_parts[0].strip()
                item_name = ' '.join(item_name_raw.split(' ')[:-1]).strip()

                menu_query = f"""
                    SELECT Name, Price__c, Image1__c,
                        Ingredient_1__r.Ingredient_Name__c, Ingredient_1__r.Ingredient_Image__c, 
                        Ingredient_1__r.Health_Benefits__c, Ingredient_1__r.Fun_Facts__c,
                        Ingredient_2__r.Ingredient_Name__c, Ingredient_2__r.Ingredient_Image__c, 
                        Ingredient_2__r.Health_Benefits__c, Ingredient_2__r.Fun_Facts__c
                    FROM Menu_Item__c
                    WHERE Name = '{item_name}'
                """
                menu_result = sf.query(menu_query)
                ingredients = []

                if menu_result.get("records"):
                    menu_item = menu_result["records"][0]
                    if menu_item.get('Ingredient_1__r') is not None:
                        ingredients.append({
                            "name": menu_item['Ingredient_1__r']['Ingredient_Name__c'],
                            "image": menu_item['Ingredient_1__r']['Ingredient_Image__c'],
                            "health_benefits": menu_item['Ingredient_1__r']['Health_Benefits__c'] or "",
                            "fun_facts": menu_item['Ingredient_1__r']['Fun_Facts__c'] or ""
                        })
                    if menu_item.get('Ingredient_2__r') is not None:
                        ingredients.append({
                            "name": menu_item['Ingredient_2__r']['Ingredient_Name__c'],
                            "image": menu_item['Ingredient_2__r']['Ingredient_Image__c'],
                            "health_benefits": menu_item['Ingredient_2__r']['Health_Benefits__c'] or "",
                            "fun_facts": menu_item['Ingredient_2__r']['Fun_Facts__c'] or ""
                        })

                    # Only add the "Show Ingredients" section if ingredients are present
                    if ingredients:
                        order_items.append({
                            "name": item_name,
                            "price": menu_item.get("Price__c"),
                            "image_url": menu_item.get("Image1__c"),
                            "ingredients": ingredients
                        })
                    else:
                        order_items.append({
                            "name": item_name,
                            "price": menu_item.get("Price__c"),
                            "image_url": menu_item.get("Image1__c"),
                            "ingredients": None
                        })

        return render_template(
            'combined_summary.html',
            user_points=round(user_points),
            current_tier=current_tier,
            next_tier=next_tier,
            start_point=start_point,
            end_point=end_point,
            progress_percentage=round(progress_percentage),
            points_needed_for_next_tier=round(points_needed_for_next_tier),
            order_items=order_items
        )


    except Exception as e:
        return f"Error: {str(e)}", 500




@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)

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