BiryaniHubflaskhema2001 / combined_summary.py
lokesh341's picture
Create combined_summary.py
a755aa6 verified
from flask import Blueprint, render_template, session, redirect, url_for
from salesforce import get_salesforce_connection
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for
import os
import re
from salesforce import get_salesforce_connection
combined_summary_blueprint = Blueprint('combined_summary', __name__)
# Initialize Salesforce connection
sf = get_salesforce_connection()
def escape_soql(value):
"""Escape single quotes in SOQL query values to prevent injection."""
if value:
return value.replace("'", "\\'")
return value
@combined_summary_blueprint.route('/combined_summary')
def combined_summary():
email = session.get('user_email')
if not email:
print("No user email in session, redirecting to login")
return redirect(url_for('login'))
try:
# Sanitize email for SOQL query
safe_email = escape_soql(email)
# ====== FETCH REWARDS ======
reward_query = f"SELECT Id, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{safe_email}'"
reward_data = sf.query_all(reward_query)
if not reward_data.get("records"):
print(f"No reward info found for email: {email}")
return "Reward info not found", 404
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 = '{safe_email}'
ORDER BY CreatedDate DESC
LIMIT 1
"""
order_result = sf.query_all(order_query)
if not order_result.get("records"):
print(f"No order found for email: {email}")
return "No order found", 404
order = order_result["records"][0]
order_details = order.get("Order_Details__c", "")
order_items = []
sector_names = set() # Use a set to ensure sector names are unique
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()
safe_item_name = escape_soql(item_name)
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,
Sector__c
FROM Menu_Item__c
WHERE Name = '{safe_item_name}'
"""
menu_result = sf.query_all(menu_query)
ingredients = []
if menu_result.get("records"):
menu_item = menu_result["records"][0]
# Process Ingredient 1 if it exists
if menu_item.get('Ingredient_1__r') is not None:
ingredients.append({
"name": menu_item['Ingredient_1__r'].get('Ingredient_Name__c', ''),
"image": menu_item['Ingredient_1__r'].get('Ingredient_Image__c', ''),
"health_benefits": menu_item['Ingredient_1__r'].get('Health_Benefits__c', ''),
"fun_facts": menu_item['Ingredient_1__r'].get('Fun_Facts__c', '')
})
# Process Ingredient 2 if it exists
if menu_item.get('Ingredient_2__r') is not None:
ingredients.append({
"name": menu_item['Ingredient_2__r'].get('Ingredient_Name__c', ''),
"image": menu_item['Ingredient_2__r'].get('Ingredient_Image__c', ''),
"health_benefits": menu_item['Ingredient_2__r'].get('Health_Benefits__c', ''),
"fun_facts": menu_item['Ingredient_2__r'].get('Fun_Facts__c', '')
})
# Process the Sector__c field from Menu_Item__c
if menu_item.get('Sector__c'):
sector_names.update(menu_item['Sector__c'].split(',')) # Add sectors to the set
# Only add the item if ingredients are present
order_items.append({
"name": item_name,
"price": menu_item.get("Price__c", 0),
"image_url": menu_item.get("Image1__c", ''),
"ingredients": ingredients
})
# Fetch the sector details from the Sector_Detail__c object
sector_details = {}
for sector_name in sector_names:
safe_sector_name = escape_soql(sector_name.strip())
sector_query = f"""
SELECT Name, Image_URL__c, Description__c
FROM Sector_Detail__c
WHERE Name = '{safe_sector_name}'
"""
sector_result = sf.query_all(sector_query)
if sector_result.get("records"):
sector_record = sector_result["records"][0]
sector_details[sector_name] = {
"image_url": sector_record.get('Image_URL__c', ''),
"description": sector_record.get('Description__c', '')
}
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,
sector_details=sector_details
)
except Exception as e:
print(f"Error in combined_summary: {str(e)}")
return f"Error: {str(e)}", 500