Spaces:
Runtime error
Runtime error
| from flask import Blueprint, render_template, request,redirect, session, jsonify # Added jsonify import | |
| from salesforce import get_salesforce_connection | |
| from datetime import datetime | |
| import pytz # Library to handle timezone conversions | |
| orderhistory_blueprint = Blueprint('orderhistory', __name__) | |
| # Initialize Salesforce connection | |
| sf = get_salesforce_connection() | |
| 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)) | |