fix: Make material request against SO only for pending qty (#18216)

diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 6c0b02d..e9b310e 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -492,13 +492,27 @@
 
 	frappe.local.message_log = []
 
+def get_requested_item_qty(sales_order):
+	return frappe._dict(frappe.db.sql("""
+		select sales_order_item, sum(stock_qty)
+		from `tabMaterial Request Item`
+		where docstatus = 1
+			and sales_order = %s
+		group by sales_order_item
+	""", sales_order))
+
 @frappe.whitelist()
 def make_material_request(source_name, target_doc=None):
+	requested_item_qty = get_requested_item_qty(source_name)
+
 	def postprocess(source, doc):
 		doc.material_request_type = "Purchase"
 
 	def update_item(source, target, source_parent):
 		target.project = source_parent.project
+		target.qty = source.stock_qty - requested_item_qty.get(source.name, 0)
+		target.conversion_factor = 1
+		target.stock_qty = source.stock_qty - requested_item_qty.get(source.name, 0)
 
 	doc = get_mapped_doc("Sales Order", source_name, {
 		"Sales Order": {
@@ -523,7 +537,7 @@
 				"stock_uom": "uom",
 				"stock_qty": "qty"
 			},
-			"condition": lambda doc: not frappe.db.exists('Product Bundle', doc.item_code),
+			"condition": lambda doc: not frappe.db.exists('Product Bundle', doc.item_code) and doc.stock_qty > requested_item_qty.get(doc.name, 0),
 			"postprocess": update_item
 		}
 	}, target_doc, postprocess)