From 66e82c56b15237b4ff44411f562ef7c7825a8cfa Mon Sep 17 00:00:00 2001 From: Mihir Kandoi Date: Wed, 17 Jun 2026 17:35:55 +0530 Subject: [PATCH] refactor(postgres): port Gross Profit report query to the query builder Co-Authored-By: Claude Opus 4.8 (1M context) --- .../report/gross_profit/gross_profit.py | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py index 71af2b9d211..8785144a8da 100644 --- a/erpnext/accounts/report/gross_profit/gross_profit.py +++ b/erpnext/accounts/report/gross_profit/gross_profit.py @@ -713,20 +713,25 @@ class GrossProfitGenerator: ) def get_returned_invoice_items(self): - returned_invoices = frappe.db.sql( - """ - select - si.name, si_item.item_code, si_item.stock_qty as qty, si_item.base_net_amount as base_amount, si.return_against - from - `tabSales Invoice` si, `tabSales Invoice Item` si_item - where - si.name = si_item.parent - and si.docstatus = 1 - and si.is_return = 1 - and si.posting_date between %(from_date)s and %(to_date)s - """, - {"from_date": self.filters.from_date, "to_date": self.filters.to_date}, - as_dict=1, + si = frappe.qb.DocType("Sales Invoice") + si_item = frappe.qb.DocType("Sales Invoice Item") + returned_invoices = ( + frappe.qb.from_(si) + .inner_join(si_item) + .on(si.name == si_item.parent) + .select( + si.name, + si_item.item_code, + si_item.stock_qty.as_("qty"), + si_item.base_net_amount.as_("base_amount"), + si.return_against, + ) + .where( + (si.docstatus == 1) + & (si.is_return == 1) + & si.posting_date.between(self.filters.from_date, self.filters.to_date) + ) + .run(as_dict=1) ) self.returned_invoices = frappe._dict() @@ -1241,7 +1246,4 @@ class GrossProfitGenerator: ).setdefault(d.parent_item, []).append(d) def load_non_stock_items(self): - self.non_stock_items = frappe.db.sql_list( - """select name from tabItem - where is_stock_item=0""" - ) + self.non_stock_items = frappe.get_all("Item", filters={"is_stock_item": 0}, pluck="name")