Subbu1304's picture
Update order.py
0cc0be5 verified
raw
history blame
3.35 kB
from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for, send_file
from salesforce import get_salesforce_connection
from io import BytesIO
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
order_blueprint = Blueprint('order', __name__)
# Initialize Salesforce connection
sf = get_salesforce_connection()
@order_blueprint.route("/order", methods=["GET"])
def order_summary():
email = session.get('user_email') # Fetch logged-in user's email
if not email:
return redirect(url_for("login"))
try:
# Fetch the most recent order 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
FROM Order__c
WHERE Customer_Email__c = '{email}'
ORDER BY CreatedDate DESC
LIMIT 1
""")
order = result.get("records", [])[0] if result.get("records") else None
if not order:
return render_template("order.html", order=None)
return render_template("order.html", order=order)
except Exception as e:
print(f"Error fetching order details: {str(e)}")
return render_template("order.html", order=None, error=str(e))
# New route to generate the invoice
@order_blueprint.route("/generate_invoice/<order_id>", methods=["GET"])
def generate_invoice(order_id):
email = session.get('user_email') # Fetch 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
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
# Create PDF invoice
buffer = BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
c.drawString(100, 750, f"Invoice for Order ID: {order_id}")
c.drawString(100, 730, f"Customer Name: {order['Customer_Name__c']}")
c.drawString(100, 710, f"Customer Email: {order['Customer_Email__c']}")
c.drawString(100, 690, f"Total Amount: ${order['Total_Amount__c']}")
c.drawString(100, 670, f"Discount: ${order['Discount__c']}")
c.drawString(100, 650, f"Total Bill: ${order['Total_Bill__c']}")
# Add order details (split by new lines)
order_details = order.get("Order_Details__c", "").split("\n")
y_position = 630
for line in order_details:
c.drawString(100, y_position, line)
y_position -= 20
# Finalize the PDF
c.showPage()
c.save()
# Send the PDF as a downloadable file
buffer.seek(0)
return send_file(buffer, 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