Set query sales order (#11772)

* set_query for sales order based on production_item

* codacy fix

* check in packed item to fetch sales order

* Update production_order.py
diff --git a/erpnext/manufacturing/doctype/production_order/production_order.js b/erpnext/manufacturing/doctype/production_order/production_order.js
index 226ebfc..48fb7e7 100644
--- a/erpnext/manufacturing/doctype/production_order/production_order.js
+++ b/erpnext/manufacturing/doctype/production_order/production_order.js
@@ -167,6 +167,8 @@
 				},
 				callback: function(r) {
 					if(r.message) {
+						frm.set_value('sales_order', "");
+						frm.trigger('set_sales_order');
 						erpnext.in_production_item_onchange = true;
 						$.each(["description", "stock_uom", "project", "bom_no"], function(i, field) {
 							frm.set_value(field, r.message[field]);
@@ -213,6 +215,24 @@
 	before_submit: function(frm) {
 		frm.toggle_reqd(["fg_warehouse", "wip_warehouse"], true);
 		frm.fields_dict.required_items.grid.toggle_reqd("source_warehouse", true);
+	},
+
+	set_sales_order: function(frm) {
+		if(frm.doc.production_item) {
+			frappe.call({
+				method: "erpnext.manufacturing.doctype.production_order.production_order.query_sales_order",
+				args: { production_item: frm.doc.production_item },
+				callback: function(r) {
+					frm.set_query("sales_order", function() {
+						return {
+							filters: [
+								["Sales Order","name", "in", r.message]
+							]
+						}
+					});
+				}
+			});
+		}
 	}
 });
 
diff --git a/erpnext/manufacturing/doctype/production_order/production_order.py b/erpnext/manufacturing/doctype/production_order/production_order.py
index 1e98f39..bf9d3b6 100644
--- a/erpnext/manufacturing/doctype/production_order/production_order.py
+++ b/erpnext/manufacturing/doctype/production_order/production_order.py
@@ -636,3 +636,15 @@
 	pro_order.notify_update()
 
 	return pro_order.status
+
+@frappe.whitelist()
+def query_sales_order(production_item):
+	out = frappe.db.sql_list("""
+		select distinct so.name from `tabSales Order` so, `tabSales Order Item` so_item
+		where so_item.parent=so.name and so_item.item_code=%s and so.docstatus=1
+	union
+		select distinct so.name from `tabSales Order` so, `tabPacked Item` pi_item
+		where pi_item.parent=so.name and pi_item.item_code=%s and so.docstatus=1
+	""", (production_item, production_item))
+	
+	return out