fix: Update Received Qty in Material Request as per Stock UOM (#21054)

* fix: Update Received Qty in Material Request as per Stock UOM

* fix: Process each PR only once

* fix: minor suggested changes

Co-authored-by: Nabin Hait <nabinhait@gmail.com>
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 8aec8bd..bd50ff4 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -660,3 +660,4 @@
 erpnext.patches.v12_0.create_irs_1099_field_united_states
 erpnext.patches.v12_0.move_bank_account_swift_number_to_bank
 erpnext.patches.v12_0.rename_bank_reconciliation_fields # 2020-01-22
+erpnext.patches.v12_0.set_received_qty_in_material_request_as_per_stock_uom
\ No newline at end of file
diff --git a/erpnext/patches/v12_0/set_received_qty_in_material_request_as_per_stock_uom.py b/erpnext/patches/v12_0/set_received_qty_in_material_request_as_per_stock_uom.py
new file mode 100644
index 0000000..88c3e2e
--- /dev/null
+++ b/erpnext/patches/v12_0/set_received_qty_in_material_request_as_per_stock_uom.py
@@ -0,0 +1,30 @@
+from __future__ import unicode_literals
+import frappe
+
+def execute():
+	purchase_receipts = frappe.db.sql("""
+		SELECT
+			 parent from `tabPurchase Receipt Item`
+		WHERE
+			material_request is not null
+			AND docstatus=1
+		""",as_dict=1)
+
+	purchase_receipts = set([d.parent for d in purchase_receipts])
+
+	for pr in purchase_receipts:
+		doc = frappe.get_doc("Purchase Receipt", pr)
+		doc.status_updater = [
+			{
+			'source_dt': 'Purchase Receipt Item',
+			'target_dt': 'Material Request Item',
+			'join_field': 'material_request_item',
+			'target_field': 'received_qty',
+			'target_parent_dt': 'Material Request',
+			'target_parent_field': 'per_received',
+			'target_ref_field': 'stock_qty',
+			'source_field': 'stock_qty',
+			'percent_join_field': 'material_request'
+			}
+		]
+		doc.update_qty()
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 3b43690..c2b3892 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -50,8 +50,8 @@
 			'target_field': 'received_qty',
 			'target_parent_dt': 'Material Request',
 			'target_parent_field': 'per_received',
-			'target_ref_field': 'qty',
-			'source_field': 'qty',
+			'target_ref_field': 'stock_qty',
+			'source_field': 'stock_qty',
 			'percent_join_field': 'material_request'
 		}]
 		if cint(self.is_return):
@@ -357,7 +357,7 @@
 		if warehouse_with_no_account:
 			frappe.msgprint(_("No accounting entries for the following warehouses") + ": \n" +
 				"\n".join(warehouse_with_no_account))
-		
+
 		return process_gl_map(gl_entries)
 
 	def get_asset_gl_entry(self, gl_entries):
@@ -628,7 +628,7 @@
 
 	if not landed_cost_vouchers:
 		return
-	
+
 	item_account_wise_cost = {}
 
 	for lcv in landed_cost_vouchers: