File size: 5,219 Bytes
a755aa6
 
25c7209
3ad460d
a755aa6
 
 
 
 
 
 
 
 
 
 
 
3ad460d
 
 
 
 
 
 
 
 
a755aa6
 
 
 
 
 
 
 
 
 
 
3ad460d
 
b66abc8
3ad460d
 
 
 
 
 
 
 
 
 
 
 
 
b66abc8
3ad460d
a755aa6
 
 
b66abc8
a755aa6
 
 
 
 
 
 
 
 
 
 
 
 
3ad460d
b66abc8
3ad460d
 
a755aa6
 
 
 
 
 
 
 
b66abc8
a755aa6
 
 
 
 
 
 
3ad460d
b66abc8
a755aa6
 
 
3ad460d
b66abc8
a755aa6
 
3ad460d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b66abc8
 
a755aa6
b66abc8
3ad460d
 
b66abc8
3ad460d
 
 
 
 
 
 
 
 
 
 
 
 
a755aa6
 
 
 
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
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