Subbu1304 commited on
Commit
9ba62d8
·
verified ·
1 Parent(s): 89e2c45

Update orderhistory.py

Browse files
Files changed (1) hide show
  1. orderhistory.py +58 -32
orderhistory.py CHANGED
@@ -1,48 +1,74 @@
1
- from flask import send_file
2
- from weasyprint import HTML
3
- from io import BytesIO
 
4
 
5
- @orderhistory_blueprint.route("/generate_invoice/<order_id>", methods=["GET"])
6
- def generate_invoice(order_id):
 
 
 
 
 
 
7
  email = session.get('user_email') # Get logged-in user's email
8
  if not email:
9
- return jsonify({"success": False, "message": "User not logged in"}), 400
10
 
11
  try:
12
- # Fetch order details from Salesforce
13
  result = sf.query(f"""
14
- SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c, Order_Details__c,
15
- Order_Status__c, Discount__c, Total_Bill__c, CreatedDate
16
  FROM Order__c
17
- WHERE Id = '{order_id}'
 
18
  """)
19
- order = result.get("records", [])[0] if result.get("records") else None
20
 
21
- if not order:
22
- return jsonify({"success": False, "message": "Order not found"}), 404
23
 
24
- # Format order details for better readability
25
- order_details = order.get("Order_Details__c", "")
26
- items = order_details.split("\n")
27
- formatted_items = []
28
 
29
- for item in items:
30
- item_details = item.split(" | ")
31
- if len(item_details) > 1:
32
- name = item_details[0].strip()
33
- quantity = item_details[1].strip()
34
- formatted_items.append(f"{name} * {quantity}")
35
 
36
- # Render HTML invoice template
37
- rendered_html = render_template('invoice.html', order=order, formatted_items=formatted_items)
 
 
 
38
 
39
- # Convert HTML to PDF using WeasyPrint
40
- pdf = HTML(string=rendered_html).write_pdf()
 
 
 
 
 
41
 
42
- # Send the PDF as a downloadable file
43
- return send_file(BytesIO(pdf), as_attachment=True, download_name=f"invoice_{order_id}.pdf", mimetype="application/pdf")
44
 
45
- except Exception as e:
46
- print(f"Error generating invoice: {str(e)}")
47
- return jsonify({"success": False, "message": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
48
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template, request,redirect, session, jsonify # Added jsonify import
2
+ from salesforce import get_salesforce_connection
3
+ from datetime import datetime
4
+ import pytz # Library to handle timezone conversions
5
 
6
+ orderhistory_blueprint = Blueprint('orderhistory', __name__)
7
+
8
+ # Initialize Salesforce connection
9
+ sf = get_salesforce_connection()
10
+
11
+
12
+ @orderhistory_blueprint.route("/order-history", methods=["GET"])
13
+ def order_history():
14
  email = session.get('user_email') # Get logged-in user's email
15
  if not email:
16
+ return redirect(url_for("login"))
17
 
18
  try:
19
+ # Fetch past orders for the user
20
  result = sf.query(f"""
21
+ SELECT Id, Customer_Name__c, Customer_Email__c, Total_Amount__c,
22
+ Order_Details__c, Order_Status__c, Discount__c, Total_Bill__c, CreatedDate
23
  FROM Order__c
24
+ WHERE Customer_Email__c = '{email}'
25
+ ORDER BY CreatedDate DESC
26
  """)
 
27
 
28
+ print(f"Salesforce query result: {result}") # Debugging line
 
29
 
30
+ orders = result.get("records", []) # Fetch all orders
 
 
 
31
 
32
+ if not orders:
33
+ print("No orders found for this email.") # Debugging line
 
 
 
 
34
 
35
+ # Format the order details for better readability
36
+ for order in orders:
37
+ order_details = order.get("Order_Details__c", "")
38
+ items = order_details.split("\n") # Assuming each item is separated by a new line
39
+ formatted_items = []
40
 
41
+ # Loop through the items and format them as "item name * quantity"
42
+ for item in items:
43
+ item_details = item.split(" | ")
44
+ if len(item_details) > 1:
45
+ name = item_details[0].strip()
46
+ quantity = item_details[1].strip()
47
+ formatted_items.append(f"{name} * {quantity}")
48
 
49
+ # Join the formatted items into a single string
50
+ order['formatted_items'] = ", ".join(formatted_items)
51
 
52
+ # Get the order date and time from CreatedDate
53
+ created_date = order.get("CreatedDate", "")
54
+ if created_date:
55
+ # Convert CreatedDate to datetime object in UTC
56
+ utc_datetime = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.000+0000')
57
+ utc_datetime = utc_datetime.replace(tzinfo=pytz.UTC)
58
+
59
+ # Convert UTC datetime to the desired timezone (e.g., IST)
60
+ local_timezone = pytz.timezone('Asia/Kolkata') # Replace with your timezone
61
+ local_datetime = utc_datetime.astimezone(local_timezone)
62
+
63
+ # Format the date and time in the desired format
64
+ order['formatted_date'] = local_datetime.strftime('%B %d, %I:%M %p')
65
 
66
+ order_status = order.get("Order_Status__c", "N/A") # Default to "N/A" if no status
67
+ order['order_status'] = order_status
68
+
69
+
70
+ return render_template("order_history.html", orders=orders)
71
+
72
+ except Exception as e:
73
+ print(f"Error fetching order history: {str(e)}")
74
+ return render_template("order_history.html", orders=[], error=str(e))