diff --git a/performancewest_erpnext/performancewest_erpnext/www/orders.py b/performancewest_erpnext/performancewest_erpnext/www/orders.py index 3d4faaf..29989a4 100644 --- a/performancewest_erpnext/performancewest_erpnext/www/orders.py +++ b/performancewest_erpnext/performancewest_erpnext/www/orders.py @@ -66,39 +66,63 @@ def get_context(context): raise frappe.Redirect context.no_cache = 1 - context.show_sidebar = True + context.show_sidebar = False context.title = "My Orders" # Find the Customer linked to this portal user + user_email = frappe.session.user customer_name = frappe.db.get_value( - "Customer", {"portal_user_name": frappe.session.user}, "name" + "Customer", {"email_id": user_email}, "name" ) if not customer_name: - # Try matching by email_id - customer_name = frappe.db.get_value( - "Customer", {"email_id": frappe.session.user}, "name" + # Try matching via Contact linked to Customer + contact_name = frappe.db.get_value("Contact", {"email_id": user_email}, "name") + if contact_name: + link = frappe.db.get_value( + "Dynamic Link", + {"parent": contact_name, "link_doctype": "Customer"}, + "link_name", + ) + if link: + customer_name = link + + context.customer_name = customer_name or "" + context.user_email = user_email + + # Fetch Sales Orders — by Customer link first, then by contact email + so_fields = [ + "name", "custom_external_order_id", "custom_order_type", + "workflow_state", "transaction_date", "grand_total", + "custom_mailbox_address", "custom_payment_gateway", + "status", + ] + + if customer_name: + raw_orders = frappe.get_all( + "Sales Order", + filters={"customer": customer_name, "docstatus": ["!=", 2]}, + fields=so_fields, + order_by="transaction_date desc", + limit=50, ) + else: + raw_orders = [] - if not customer_name: - context.orders = [] - context.message = "No customer account found. Please contact support." - return - - context.customer_name = customer_name - - # Fetch all Sales Orders for this customer (CRTC + Formation) - raw_orders = frappe.get_all( + # Also fetch orders by contact email (catches orders where Customer + # record wasn't linked, e.g. compliance orders placed via PW checkout) + email_orders = frappe.get_all( "Sales Order", - filters={"customer": customer_name, "docstatus": ["!=", 2]}, - fields=[ - "name", "custom_external_order_id", "custom_order_type", - "workflow_state", "transaction_date", "grand_total", - "custom_mailbox_address", "custom_payment_gateway", - "status", - ], + filters={"custom_contact_email": user_email, "docstatus": ["!=", 2]}, + fields=so_fields, order_by="transaction_date desc", limit=50, ) + # Merge without duplicates + seen = {so["name"] for so in raw_orders} + for so in email_orders: + if so["name"] not in seen: + raw_orders.append(so) + seen.add(so["name"]) orders = [] for so in raw_orders: