BiryaniHubsubbu12341 / orderhistory.py
Subbu1304's picture
Update orderhistory.py
dc40b5d verified
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