perf: avoid per-row Warehouse doc fetches in auto reorder job

get_item_warehouse_projected_qty() called frappe.get_doc("Warehouse", ...)
inside the per-bin loop to walk up the warehouse hierarchy, re-fetching the
same parent warehouses over and over on sites with nested warehouses. Preload
the warehouse-to-parent mapping with a single query and walk it in-memory
instead, cutting the DB round-trips from O(bins * hierarchy depth) to one
query.

(cherry picked from commit 6beb3d2509)
This commit is contained in:
pandiyan
2026-07-10 11:41:43 +05:30
parent 8bfba5fcf3
commit c10b86d538

View File

@@ -186,6 +186,10 @@ def get_item_warehouse_projected_qty(items_to_consider):
item_warehouse_projected_qty = {}
items_to_consider = list(items_to_consider.keys())
warehouse_parent_map = frappe._dict(
frappe.get_all("Warehouse", fields=["name", "parent_warehouse"], as_list=True)
)
for item_code, warehouse, projected_qty in frappe.db.sql(
"""select item_code, warehouse, projected_qty
from tabBin where item_code in ({})
@@ -200,16 +204,14 @@ def get_item_warehouse_projected_qty(items_to_consider):
if warehouse not in item_warehouse_projected_qty.get(item_code):
item_warehouse_projected_qty[item_code][warehouse] = flt(projected_qty)
warehouse_doc = frappe.get_doc("Warehouse", warehouse)
parent_warehouse = warehouse_parent_map.get(warehouse)
while warehouse_doc.parent_warehouse:
if not item_warehouse_projected_qty.get(item_code, {}).get(warehouse_doc.parent_warehouse):
item_warehouse_projected_qty.setdefault(item_code, {})[warehouse_doc.parent_warehouse] = flt(
projected_qty
)
while parent_warehouse:
if not item_warehouse_projected_qty.get(item_code, {}).get(parent_warehouse):
item_warehouse_projected_qty.setdefault(item_code, {})[parent_warehouse] = flt(projected_qty)
else:
item_warehouse_projected_qty[item_code][warehouse_doc.parent_warehouse] += flt(projected_qty)
warehouse_doc = frappe.get_doc("Warehouse", warehouse_doc.parent_warehouse)
item_warehouse_projected_qty[item_code][parent_warehouse] += flt(projected_qty)
parent_warehouse = warehouse_parent_map.get(parent_warehouse)
return item_warehouse_projected_qty