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) <noreply@anthropic.com>
This commit is contained in:
Mihir Kandoi
2026-06-20 19:41:57 +05:30
parent a65aa27225
commit c76c0d85ba

View File

@@ -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: