Spaces:
Sleeping
Sleeping
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 | |
import os | |
from simple_salesforce import Salesforce | |
import salesforce_api as sf | |
# 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", "sSSjyhInIsUohKpG8sHzty2q") # Replace with a secure key | |
try: | |
sf = Salesforce( | |
username="diggavalli98@gmail.com", | |
password="Sati@1020", | |
security_token="sSSjyhInIsUohKpG8sHzty2q" | |
) | |
print("✅ Successfully connected to Salesforce!") | |
except Exception as e: | |
print(f"❌ Salesforce connection failed: {e}") | |
exit(1) # Stop execution if connection fails | |
# ✅ Debugging session data | |
def print_session(): | |
print(f"Session Data: {session}") | |
# Configure the session type | |
app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage | |
#app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name | |
app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS | |
app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies | |
# 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 | |
def home(): | |
# Fetch user details from URL parameters | |
user_email = request.args.get("email") | |
user_name = request.args.get("name") | |
if user_email and user_name: | |
session["user_email"] = user_email | |
session["user_name"] = user_name | |
print(f"User logged in via Hugging Face: {user_email} - {user_name}") | |
# Ensure session is saved before redirecting | |
session.modified = True | |
return redirect(url_for("menu")) # Redirect to menu directly | |
return render_template("login.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)) | |
import re | |
import re | |
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 | |
""") | |
orders = result.get("records", []) # Fetch all orders | |
# Strip image URLs from order details and split remaining data by new lines | |
for order in orders: | |
order_details = order.get("Order_Details__c", "") | |
# Remove image URLs using regex | |
cleaned_details = re.sub(r'http[s]?://\S+', '', order_details) | |
# Now split the cleaned details by lines and join them with <br> to create line breaks | |
cleaned_details = cleaned_details.replace("\n", "<br>") | |
# Update the order details with the cleaned and formatted details | |
order['Order_Details__c'] = cleaned_details | |
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)) | |
def logout(): | |
session.clear() # Clear the session | |
session.modified = True # Explicitly mark session as modified | |
# Optionally, delete the session cookie explicitly | |
response = redirect("https://biryanihub-dev-ed.develop.my.salesforce-sites.com/PublicLogin") | |
response.delete_cookie('session') # Adjust this depending on the session cookie name | |
return response # Redirect to Salesforce login page | |
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") | |
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, including Name and Reward_Points__c | |
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'] | |
session['user_email'] = email | |
print(f"Session variables set: user_id={session['user_id']}, user_email={session['user_email']}") | |
user_name = user.get("Name", "") # Get the user's name | |
reward_points = user.get("Reward_Points__c") or 0 # Ensures reward_points is always an integer | |
if reward_points >= 500: | |
print(f"User {email} has {reward_points} reward points. Generating coupon...") | |
# Generate a new coupon code | |
new_coupon_code = generate_coupon_code() | |
# Check if user already has a record in Referral_Coupon__c | |
coupon_query = sf.query(f""" | |
SELECT Id, Coupon_Code__c FROM Referral_Coupon__c WHERE Referral_Email__c = '{email}' | |
""") | |
if coupon_query["records"]: | |
# If record exists, append the new coupon | |
coupon_record = coupon_query["records"][0] | |
referral_coupon_id = coupon_record["Id"] | |
existing_coupons = coupon_record.get("Coupon_Code__c", "") | |
# Append the new coupon on the next line | |
updated_coupons = f"{existing_coupons}\n{new_coupon_code}".strip() | |
# Update the Referral_Coupon__c record | |
sf.Referral_Coupon__c.update(referral_coupon_id, { | |
"Coupon_Code__c": updated_coupons | |
}) | |
print(f"Updated existing coupon record for {email}. New Coupon: {new_coupon_code}") | |
else: | |
# If no record exists, create a new one with Referral_Name__c | |
sf.Referral_Coupon__c.create({ | |
"Referral_Email__c": email, | |
"Name": user_name, # Store user's name in Referral_Coupon__c | |
"Coupon_Code__c": new_coupon_code | |
}) | |
print(f"Created new coupon record for {email} with name {user_name}. Coupon: {new_coupon_code}") | |
# Subtract 500 reward points from user's account | |
new_reward_points = reward_points - 500 | |
sf.Customer_Login__c.update(user['Id'], { | |
"Reward_Points__c": new_reward_points | |
}) | |
print(f"Coupon {new_coupon_code} generated and 500 points deducted. New balance: {new_reward_points}") | |
return redirect(url_for("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") | |