lokesh143 / combined_summary.py
lokeshloki143's picture
Update combined_summary.py
b66abc8 verified
from flask import Blueprint, render_template, session, redirect, url_for
from salesforce import get_salesforce_connection
from datetime import datetime
from num2words import num2words
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
def number_to_words(number):
"""Convert a number to words for invoice amount in words."""
integer_part = int(number)
decimal_part = int((number - integer_part) * 100)
words = num2words(integer_part, lang='en_IN').replace(',', '').title() + " Rupees"
if decimal_part > 0:
words += " And " + num2words(decimal_part, lang='en_IN').replace(',', '').title() + " Paisa Only"
return words
@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 CUSTOMER DETAILS ======
customer_query = f"""
SELECT Id, Name, Email__c, Phone_Number__c
FROM Customer_Login__c
WHERE Email__c = '{safe_email}'
LIMIT 1
"""
customer_result = sf.query_all(customer_query)
if not customer_result.get("records"):
print(f"No customer found for email: {email}")
return "Customer not found", 404
customer = customer_result["records"][0]
customer_data = {
"name": customer.get("Name", "SATHVIK GANTA"),
"email": customer.get("Email__c", "sathvik@example.com"),
"phone": customer.get("Phone_Number__c", "9876543210")
}
# ====== FETCH ORDER SUMMARY ======
order_query = f"""
SELECT Id, Customer_Name__c, Customer_Email__c, Order_Details__c, CreatedDate
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 = []
# Calculate total
total_amount = 0
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
FROM Menu_Item__c
WHERE Name = '{safe_item_name}'
"""
menu_result = sf.query_all(menu_query)
if menu_result.get("records"):
menu_item = menu_result["records"][0]
price = menu_item.get("Price__c", 0)
total_amount += price
order_items.append({
"name": item_name,
"price": price,
"image_url": menu_item.get("Image1__c", '')
})
# Fetch restaurant details
restaurant_query = f"""
SELECT Legal_Name__c, Name, Address__c, GSTIN__c, FSSAI__c
FROM Restaurant__c
WHERE Name = 'Pista House'
LIMIT 1
"""
restaurant_result = sf.query_all(restaurant_query)
restaurant = restaurant_result["records"][0] if restaurant_result.get("records") else {
"legal_name": "DOUBLE TREE BY KVP HOSPITALITY LLP",
"name": "Pista House",
"address": "52 To 57, 69 & 70, 5-5-162 & 5-5-163, 5-5-164 & 5-5-165, Plot 1, Vanasthali Hills, Saheb Nagar, LB Nagar Circle 4, Vanasthalipuram, Hyderabad",
"gstin": "36AATFD1209K1Z9",
"fssai": "13622012000022"
}
# Convert total amount to words
total_amount_in_words = number_to_words(total_amount)
# Prepare template data
order_data = {
"id": order.get("Id", "247JD92F00043965"),
"created_date": order.get("CreatedDate", "2024-12-12").split("T")[0]
}
template_data = {
"order_id": order_data["id"],
"order_items": order_items,
"customer": customer_data,
"restaurant": restaurant,
"order": order_data,
"total_amount": total_amount,
"total_amount_in_words": total_amount_in_words
}
return render_template("combined_summary.html", **template_data)
except Exception as e:
print(f"Error in combined_summary: {str(e)}")
return f"Error: {str(e)}", 500