File size: 11,295 Bytes
a7abf85
 
 
08a6f6e
7621a66
f3ea496
444fe60
a7abf85
 
 
 
 
098997e
09862d2
 
098997e
3ad292c
a7abf85
 
b9ae446
444fe60
a7abf85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444fe60
a7abf85
 
 
 
 
098997e
 
a7abf85
 
 
098997e
a7abf85
 
 
098997e
a7abf85
 
 
 
 
098997e
a7abf85
 
098997e
a7abf85
 
 
 
098997e
a7abf85
098997e
a7abf85
098997e
a7abf85
 
 
 
 
098997e
a7abf85
 
 
 
 
 
098997e
a7abf85
 
098997e
a7abf85
 
 
c053032
a7abf85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444fe60
a7abf85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444fe60
a7abf85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d370d9
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
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
import random
from salesforce import get_salesforce_connection
import os
from flask import Flask, session
from flask_session import Session

# Initialize Flask app and Salesforce connection
app = Flask(__name__)
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"
Session(app)


@app.route("/")
def home():
    return render_template("index.html")

@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")
        password = request.form.get("password")
        try:
            sf.Customer_Login__c.create({
                "Name": name,
                "Phone_Number__c": phone,
                "Email__c": email,
                "Password__c": password
            })
            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}")  # Correctly indented print statement

        try:
            query = f"SELECT Id, Name, Email__c FROM Customer_Login__c WHERE Email__c='{email}' AND Password__c='{password}'"
            result = sf.query(query)

            if result["records"]:
                session['user_id'] = result["records"][0]['Id']
                session['user_email'] = email
                print(f"Session variables: {session}")  # Moved print statement before return
                return redirect(url_for("menu"))
            else:
                return render_template("login.html", error="Invalid credentials!")
        except Exception as e:
            return render_template("login.html", error=f"Error: {str(e)}")

    return render_template("login.html")


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

    if not user_id:
        print(f"Session data: {session}")  # Moved print statement before return
        return redirect(url_for('login'))

    try:
        query = "SELECT Name, Price__c, Image1__c, Category__c, Description__c FROM Menu_Item__c"
        result = sf.query(query)
        food_items = result['records'] if 'records' in result else []
        categories = {item['Category__c'] for item in food_items if 'Category__c' in item}

        if selected_category != "All":
            food_items = [item for item in food_items if item.get("Category__c") == selected_category]
    except Exception as e:
        food_items = []
        categories = []
        print(f"Error fetching data: {e}")

    return render_template("menu.html", food_items=food_items, categories=categories, selected_category=selected_category)


@app.route("/cart", methods=["GET"])
def cart():
    email = session.get('user_email') # Get logged-in user's email
    if not email:
        return redirect(url_for("login")) # Redirect to login if not logged in
    try:
        result = sf.query(f"""
            SELECT Name, Price__c, Quantity__c, Add_Ons__c, Image1__c
            FROM Cart_Item__c
            WHERE Customer_Email__c = '{email}'
        """)
        cart_items = result.get("records", [])
        subtotal = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
    except Exception as e:
        print(f"Error fetching cart items: {e}")
        cart_items = []
        subtotal = 0
        
    return render_template("cart.html", cart_items=cart_items, subtotal=subtotal)



@app.route('/cart/add', methods=['POST'])
def add_to_cart():
    data = request.json
    item_name = data.get('itemName').strip()
    item_price = data.get('itemPrice')
    item_image = data.get('itemImage')
    addons = data.get('addons', [])
    customer_email = session.get('user_email')  # Get logged-in user's email from session

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

    try:
         # Check if the item already exists in the cart for this custpmer
         query= f""" SELECT Id, Quantity__c FROM Cart_Item__c
            WHERE Customer_Email__c = '{customer_email}' AND Name = '{item_name}'
        """
         result = sf.query(query)
         if result['totalSize'] > 0:
            # Update quantity if the item exists
            cart_item = result['records'][0]
            sf.Cart_Item__c.update(cart_item['Id'], {
                "Quantity__c": cart_item['Quantity__c'] + 1
            })
         else:
             # Add a new item if it doesn't exist
             sf.Cart_Item__c.create({
                 "Name": item_name,
            "Price__c": item_price,
            "Quantity__c": 1,
            "Add_Ons__c": ";".join(addons) if addons else None,
            "Image1__c": item_image,
            "Customer_Email__c": customer_email,  # Associate with the logged-in user
                 
             })
             return jsonify({"success": True, "message": "Item added/updated successfully."})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

@app.route("/cart/add_item", methods=["POST"])
def add_item_to_cart():
    data = request.json  # Extract JSON data from the request
    email = data.get('email')  # Customer email
    item_name = data.get('item_name')  # Item name
    quantity = data.get('quantity', 0)  # Quantity to add (default is 1) // default value is 1

    try:
        # Check if the item already exists in the cart for this customer
        cart_items = sf.query(
            f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Item_Name__c = '{item_name}'"
        )['records']

        if cart_items:
            # If the item already exists, update its quantity
            cart_item = cart_items[0]
            new_quantity = cart_item['Quantity__c'] + quantity
            sf.Cart_Item__c.update(cart_item['Id'], {"Quantity__c": new_quantity})
            return jsonify({"success": True, "message": "Item quantity updated successfully."})
        else:
            # If the item does not exist, add it to the cart
            sf.Cart_Item__c.create({
                "Customer_Email__c": email,
                "Item_Name__c": item_name,
                "Quantity__c": quantity
            })

        return jsonify({"success": True, "message": "Item added/updated successfully."})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500


@app.route('/cart/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
        query = f"""
            SELECT Id FROM Cart_Item__c 
            WHERE Customer_Email__c = '{customer_email}' AND Name = '{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

@app.route('/api/addons', methods=['GET'])
def get_addons():
    item_name = request.args.get('item_name')
    if not item_name:
        return jsonify({"success": False, "error": "Item name is required."})

    try:
        query = f"SELECT Name, Price__c FROM Add_Ons__c WHERE Menu_Item__r.Name = '{item_name}'"
        addons = sf.query(query)['records']
        return jsonify({"success": True, "addons": addons})
    except Exception as e:
        print(f"Error fetching add-ons: {e}")
        return jsonify({"success": False, "error": "Unable to fetch add-ons. Please try again later."})

@app.route("/cart/update_quantity", methods=["POST"])
def update_quantity():
    data = request.json  # Extract JSON data from the request
    email = data.get('email')  # Customer email
    item_name = data.get('item_name')  # Item name (Cart Item Name in Salesforce)
    quantity = data.get('quantity')  # New quantity

    # Validate inputs
    if not email or not item_name:
        return jsonify({"success": False, "error": "Email and item name are required."}), 400

    try:
        # Query the cart item using the correct field names
        cart_items = sf.query(
            f"SELECT Id, Quantity__c FROM Cart_Item__c WHERE Customer_Email__c = '{email}' AND Name__c = '{item_name}'"
        )['records']

        if not cart_items:
            return jsonify({"success": False, "error": "Cart item not found."}), 404

        # Get the first matching record ID
        cart_item_id = cart_items[0]['Id']

        # Update the quantity in Salesforce
        sf.Cart_Item__c.update(cart_item_id, {"Quantity__c": quantity})

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

    

@app.route("/checkout", methods=["POST"])
def checkout():
    email = session.get('user_email')
    user_id = session.get('user_id')
    if not email or not user_id:
        return jsonify({"success": False, "message": "User not logged in"})
    try:
        result = sf.query(f"""
            SELECT Id, Name, Price__c, Quantity__c, Add_Ons__c
            FROM Cart_Item__c
            WHERE Customer_Email__c = '{email}'
        """)
        cart_items = result["records"]
        if not cart_items:
            return jsonify({"success": False, "message": "Cart is empty"})
        total_price = sum(item['Quantity__c'] * item['Price__c'] for item in cart_items)
        order_data = {
            "Customer_Name__c": user_id,
            "Customer_Email__c": email,
            "Total_Amount__c": total_price,
            "Order_Status__c": "Pending",
            "Order_Items__c": "\n".join(
                [f"{item['Name']} (Qty: {item['Quantity__c']})" for item in cart_items]
            ),
            "Add_Ons__c": "\n".join(
                [f"{item['Add_Ons__c']}" if item['Add_Ons__c'] else "None" for item in cart_items]
            ),
        }
        sf.Order__c.create(order_data)
        for item in cart_items:
            sf.Cart_Item__c.delete(item["Id"])
        return jsonify({"success": True, "message": "Order placed successfully!"})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

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