From c76c0d85bae2ca7b3a433e67efd9921b75e24640 Mon Sep 17 00:00:00 2001 From: Mihir Kandoi Date: Sat, 20 Jun 2026 19:41:57 +0530 Subject: [PATCH] refactor(stock): convert PR get_invoiced_qty_map to qb aggregate Replace the raw `select pr_detail, qty from Purchase Invoice Item` (summed in Python) with a frappe.qb GROUP BY Sum(qty) per pr_detail, matching the sibling get_returned_qty_map. Same result on MariaDB; valid under Postgres. Covered by the existing make_purchase_invoice tests. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../stock/doctype/purchase_receipt/mapper.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/erpnext/stock/doctype/purchase_receipt/mapper.py b/erpnext/stock/doctype/purchase_receipt/mapper.py index 9ea7371554a..273afcec7a9 100644 --- a/erpnext/stock/doctype/purchase_receipt/mapper.py +++ b/erpnext/stock/doctype/purchase_receipt/mapper.py @@ -21,18 +21,15 @@ from erpnext.stock.serial_batch_bundle import ( def get_invoiced_qty_map(purchase_receipt: str) -> dict: """returns a map: {pr_detail: invoiced_qty}""" - invoiced_qty_map = {} + pi_item = frappe.qb.DocType("Purchase Invoice Item") + query = ( + frappe.qb.from_(pi_item) + .select(pi_item.pr_detail, Sum(pi_item.qty).as_("qty")) + .where((pi_item.purchase_receipt == purchase_receipt) & (pi_item.docstatus == 1)) + .groupby(pi_item.pr_detail) + ).run(as_list=1) - for pr_detail, qty in frappe.db.sql( - """select pr_detail, qty from `tabPurchase Invoice Item` - where purchase_receipt=%s and docstatus=1""", - purchase_receipt, - ): - if not invoiced_qty_map.get(pr_detail): - invoiced_qty_map[pr_detail] = 0 - invoiced_qty_map[pr_detail] += qty - - return invoiced_qty_map + return frappe._dict(query) if query else frappe._dict() def get_returned_qty_map(purchase_receipt: str) -> dict: