File size: 4,997 Bytes
dc40b5d
9ba62d8
 
 
dc40b5d
 
e0af4bc
9ba62d8
 
 
 
 
 
 
 
e0af4bc
 
9ba62d8
e0af4bc
 
9ba62d8
e0af4bc
9ba62d8
 
e0af4bc
9ba62d8
 
e0af4bc
 
9ba62d8
e0af4bc
9ba62d8
e0af4bc
9ba62d8
 
e0af4bc
9ba62d8
 
 
 
 
e0af4bc
9ba62d8
 
 
 
 
 
 
e0af4bc
9ba62d8
 
e0af4bc
9ba62d8
 
 
 
 
 
 
 
 
 
 
 
 
e0af4bc
9ba62d8
 
 
 
 
 
 
 
dc40b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Blueprint, render_template, request, redirect, session, jsonify, send_file, url_for
from salesforce import get_salesforce_connection
from datetime import datetime
import pytz  # Library to handle timezone conversions
from weasyprint import HTML
from io import BytesIO

orderhistory_blueprint = Blueprint('orderhistory', __name__)

# Initialize Salesforce connection
sf = get_salesforce_connection()


@orderhistory_blueprint.route("/order-history", methods=["GET"])
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
        """)

        print(f"Salesforce query result: {result}")  # Debugging line

        orders = result.get("records", [])  # Fetch all orders

        if not orders:
            print("No orders found for this email.")  # Debugging line

        # Format the order details for better readability
        for order in orders:
            order_details = order.get("Order_Details__c", "")
            items = order_details.split("\n")  # Assuming each item is separated by a new line
            formatted_items = []

            # Loop through the items and format them as "item name * quantity"
            for item in items:
                item_details = item.split(" | ")
                if len(item_details) > 1:
                    name = item_details[0].strip()
                    quantity = item_details[1].strip()
                    formatted_items.append(f"{name} * {quantity}")

            # Join the formatted items into a single string
            order['formatted_items'] = ", ".join(formatted_items)

            # Get the order date and time from CreatedDate
            created_date = order.get("CreatedDate", "")
            if created_date:
                # Convert CreatedDate to datetime object in UTC
                utc_datetime = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.000+0000')
                utc_datetime = utc_datetime.replace(tzinfo=pytz.UTC)
            
                # Convert UTC datetime to the desired timezone (e.g., IST)
                local_timezone = pytz.timezone('Asia/Kolkata')  # Replace with your timezone
                local_datetime = utc_datetime.astimezone(local_timezone)

                # Format the date and time in the desired format
                order['formatted_date'] = local_datetime.strftime('%B %d, %I:%M %p')

            order_status = order.get("Order_Status__c", "N/A")  # Default to "N/A" if no status
            order['order_status'] = order_status

        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))


@orderhistory_blueprint.route("/generate_invoice/<order_id>", methods=["GET"])
def generate_invoice(order_id):
    email = session.get('user_email')  # Get logged-in user's email
    if not email:
        return jsonify({"success": False, "message": "User not logged in"}), 400

    try:
        # Fetch order details from Salesforce
        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 Id = '{order_id}'
        """)
        order = result.get("records", [])[0] if result.get("records") else None

        if not order:
            return jsonify({"success": False, "message": "Order not found"}), 404

        # Format order details for better readability
        order_details = order.get("Order_Details__c", "")
        items = order_details.split("\n")
        formatted_items = []

        for item in items:
            item_details = item.split(" | ")
            if len(item_details) > 1:
                name = item_details[0].strip()
                quantity = item_details[1].strip()
                formatted_items.append(f"{name} * {quantity}")

        # Render HTML invoice template
        rendered_html = render_template('invoice.html', order=order, formatted_items=formatted_items)

        # Convert HTML to PDF using WeasyPrint
        pdf = HTML(string=rendered_html).write_pdf()

        # Send the PDF as a downloadable file
        return send_file(BytesIO(pdf), as_attachment=True, download_name=f"invoice_{order_id}.pdf", mimetype="application/pdf")

    except Exception as e:
        print(f"Error generating invoice: {str(e)}")
        return jsonify({"success": False, "message": str(e)}), 500