[minor] [fix] opportunity form, queries, stock uom replace utility
diff --git a/controllers/js/contact_address_common.js b/controllers/js/contact_address_common.js
index de1ab34..0b8ef08 100644
--- a/controllers/js/contact_address_common.js
+++ b/controllers/js/contact_address_common.js
@@ -2,11 +2,11 @@
 	cur_frm.add_fetch('customer', 'customer_name', 'customer_name');
 	cur_frm.add_fetch('supplier', 'supplier_name', 'supplier_name');
 
-	cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
-	cur_frm.fields_dict.supplier.get_query = erpnext.utils.supplier_query;
+	cur_frm.fields_dict.customer.get_query = erpnext.queries.customer;
+	cur_frm.fields_dict.supplier.get_query = erpnext.queries.supplier;
 	
 	if(cur_frm.fields_dict.lead) {
-		cur_frm.fields_dict.lead.get_query = erpnext.utils.lead_query;
+		cur_frm.fields_dict.lead.get_query = erpnext.queries.lead;
 		cur_frm.add_fetch('lead', 'lead_name', 'lead_name');
 	}
 	
diff --git a/controllers/queries.py b/controllers/queries.py
index 321e15c..8a99077 100644
--- a/controllers/queries.py
+++ b/controllers/queries.py
@@ -145,20 +145,6 @@
 		'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 'start': start, 
 		'page_len': page_len})
 
-def item_std(doctype, txt, searchfield, start, page_len, filters):
-	return webnotes.conn.sql("""select tabItem.name, 
-		if(length(tabItem.item_name) > 40, 
-			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name, 
-		if(length(tabItem.description) > 40, 
-			concat(substr(tabItem.description, 1, 40), "..."), description) as decription 
-		FROM tabItem 
-		WHERE tabItem.docstatus!=2 
-			and tabItem.%(key)s LIKE "%(txt)s" 
-			%(mcond)s 
-		limit %(start)s, %(page_len)s """ % {'key': searchfield, 'txt': "%%%s%%" % txt, 
-		'mcond':get_match_cond(doctype, searchfield), 'start': start, 
-		'page_len': page_len})
-
 def account_query(doctype, txt, searchfield, start, page_len, filters):
 	conditions = []
 	if not filters:
diff --git a/public/js/queries.js b/public/js/queries.js
index a7e137e..8c3dd01 100644
--- a/public/js/queries.js
+++ b/public/js/queries.js
@@ -15,154 +15,51 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 // searches for enabled profiles
-wn.provide("erpnext.utils");
-erpnext.utils.profile_query = function() {
-	return "select name, concat_ws(' ', first_name, middle_name, last_name) \
-		from `tabProfile` where ifnull(enabled, 0)=1 and docstatus < 2 and \
-		name not in ('Administrator', 'Guest') and (%(key)s like \"%s\" or \
-		concat_ws(' ', first_name, middle_name, last_name) like \"%%%s\") \
-		order by \
-		case when name like \"%s%%\" then 0 else 1 end, \
-		case when concat_ws(' ', first_name, middle_name, last_name) like \"%s%%\" \
-			then 0 else 1 end, \
-		name asc limit 50";
-};
-
-// searches for active employees
-erpnext.utils.employee_query = function() {
-	return "select name, employee_name from `tabEmployee` \
-		where status = 'Active' and docstatus < 2 and \
-		(%(key)s like \"%s\" or employee_name like \"%%%s\") \
-		order by \
-		case when name like \"%s%%\" then 0 else 1 end, \
-		case when employee_name like \"%s%%\" then 0 else 1 end, \
-		name limit 50";
-};
-
-// searches for leads which are not converted
-erpnext.utils.lead_query = function() {
-	return "select name, lead_name, company_name from `tabLead` \
-		where docstatus < 2 and ifnull(status, '') != 'Converted' and \
-		(%(key)s like \"%s\" or lead_name like \"%%%s\" or company_name like \"%%%s\") \
-		order by \
-		case when name like \"%s%%\" then 0 else 1 end, \
-		case when lead_name like \"%s%%\" then 0 else 1 end, \
-		case when company_name like \"%s%%\" then 0 else 1 end, \
-		lead_name asc limit 50";
-};
-
-// searches for customer
-erpnext.utils.customer_query = function() {
-	if(sys_defaults.cust_master_name == "Customer Name") {
-		var fields = ["name", "customer_group", "territory"];
-	} else {
-		var fields = ["name", "customer_name", "customer_group", "territory"];
-	}
-	
-	return "select " + fields.join(", ") + " from `tabCustomer` where docstatus < 2 and \
-		(%(key)s like \"%s\" or customer_name like \"%%%s\") \
-		order by \
-		case when name like \"%s%%\" then 0 else 1 end, \
-		case when customer_name like \"%s%%\" then 0 else 1 end, \
-		name, customer_name limit 50";
-};
-
-// searches for supplier
-erpnext.utils.supplier_query = function() {
-	if(sys_defaults.supp_master_name == "Supplier Name") {
-		var fields = ["name", "supplier_type"];
-	} else {
-		var fields = ["name", "supplier_name", "supplier_type"];
-	}
-	
-	return "select " + fields.join(", ") + " from `tabSupplier` where docstatus < 2 and \
-		(%(key)s like \"%s\" or supplier_name like \"%%%s\") \
-		order by \
-		case when name like \"%s%%\" then 0 else 1 end, \
-		case when supplier_name like \"%s%%\" then 0 else 1 end, \
-		name, supplier_name limit 50";
-};
-
 wn.provide("erpnext.queries");
-
-erpnext.queries.get_conditions = function(doctype, opts) {
-	conditions = [];
-	if (opts) {
-		$.each(opts, function(key, val) {
-			var lhs = "`tab" + doctype + "`.`" + key + "`";
-			
-			if(key.indexOf(doctype)!=-1) {
-				// with function
-				lhs = key;
-			}
-			
-			if (esc_quotes(val).charAt(0) != "!")
-				conditions.push(lhs + "='"+esc_quotes(val)+"'");
-			else
-				conditions.push(lhs + "!='"+esc_quotes(val).substr(1)+"'");
-		});
-	}
-	return conditions;
-}
-
-erpnext.queries.account = function(opts) {
-	if(!opts) 
-		opts = {};
-	if(!opts.group_or_ledger) 
-		opts.group_or_ledger = "Ledger";
+$.extend(erpnext.queries, {
+	profile: function() {
+		return { query: "controllers.queries.profile_query" };
+	},
+	
+	lead: function() {
+		return { query: "controllers.queries.lead_query" };
+	},
+	
+	customer: function() {
+		return { query: "controllers.queries.customer_query" };
+	},
+	
+	supplier: function() {
+		return { query: "controllers.queries.supplier_query" };
+	},
+	
+	account: function() {
+		return { query: "controllers.queries.account_query" };
+	},
+	
+	item: function() {
+		return { query: "controllers.queries.item_query" };
+	},
+	
+	bom: function() {
+		return { query: "controllers.queries.bom" };
+	},
+	
+	task: function() {
+		return { query: "projects.utils.query_task" };
+	},
+	
+	customer_filter: function(doc) {
+		if(!doc.customer) {
+			wn.throw(wn._("Please specify a") + " " + 
+				wn._(wn.meta.get_label(doc.doctype, "customer", doc.name)));
+		}
 		
-	var conditions = erpnext.queries.get_conditions("Account", opts);
+		return { filters: { customer: doc.customer } };
+	},
 	
-	return 'SELECT tabAccount.name, tabAccount.parent_account, tabAccount.debit_or_credit \
-		FROM tabAccount \
-		WHERE tabAccount.docstatus!=2 \
-		AND tabAccount.%(key)s LIKE "%s" ' + (conditions 
-			? (" AND " + conditions.join(" AND "))
-			: "")
-		+ " LIMIT 50"
-}
-
-erpnext.queries.item = function(opts) {
-	var conditions = erpnext.queries.get_conditions("Item", opts);
+	not_a_group_filter: function() {
+		return { filters: { is_group: "No" } };
+	},
 	
-	return 'SELECT tabItem.name, \
-		if(length(tabItem.item_name) > 40, \
-			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name, \
-		if(length(tabItem.description) > 40, \
-			concat(substr(tabItem.description, 1, 40), "..."), description) as decription \
-		FROM tabItem \
-		WHERE tabItem.docstatus!=2 \
-		AND (ifnull(`tabItem`.`end_of_life`,"") in ("", "0000-00-00") \
-			OR `tabItem`.`end_of_life` > NOW()) \
-		AND (tabItem.%(key)s LIKE \"%s\" OR tabItem.item_name LIKE \"%%%s\")' + 
-			(conditions ? (" AND " + conditions.join(" AND ")) : "") + " LIMIT 50"
-}
-
-erpnext.queries.item_std = function() {
-	return 'SELECT tabItem.name, \
-		if(length(tabItem.item_name) > 40, \
-			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name, \
-		if(length(tabItem.description) > 40, \
-			concat(substr(tabItem.description, 1, 40), "..."), description) as decription \
-		FROM tabItem \
-		WHERE tabItem.docstatus!=2 \
-		AND tabItem.%(key)s LIKE "%s" LIMIT 50';
-}
-
-erpnext.queries.bom = function(opts) {
-	var conditions = erpnext.queries.get_conditions("BOM", opts);
-	
-	return 'SELECT tabBOM.name, tabBOM.item \
-		FROM tabBOM \
-		WHERE tabBOM.docstatus=1 \
-		AND tabBOM.is_active=1 \
-		AND tabBOM.%(key)s LIKE "%s" ' + (conditions.length 
-			? (" AND " + conditions.join(" AND "))
-			: "")
-		+ " LIMIT 50"
-
-}
-
-erpnext.queries.task = function() {
-	return { query: "projects.utils.query_task" };
-};
\ No newline at end of file
+});
\ No newline at end of file
diff --git a/selling/doctype/opportunity/opportunity.js b/selling/doctype/opportunity/opportunity.js
index b87fee1..606f9a7 100644
--- a/selling/doctype/opportunity/opportunity.js
+++ b/selling/doctype/opportunity/opportunity.js
@@ -19,6 +19,70 @@
 wn.provide("erpnext.selling");
 // TODO commonify this code
 erpnext.selling.Opportunity = wn.ui.form.Controller.extend({
+	onload: function() {
+		if(!this.frm.doc.enquiry_from && this.frm.doc.customer)
+			this.frm.doc.enquiry_from = "Customer";
+		if(!this.frm.doc.enquiry_from && this.frm.doc.lead)
+			this.frm.doc.enquiry_from = "Lead";
+
+		if(!this.frm.doc.enquiry_from) 
+			hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
+		if(!this.frm.doc.status) 
+			set_multiple(cdt,cdn,{status:'Draft'});
+		if(!this.frm.doc.date) 
+			this.frm.doc.transaction_date = date.obj_to_str(new Date());
+		if(!this.frm.doc.company && sys_defaults.company) 
+			set_multiple(cdt,cdn,{company:sys_defaults.company});
+		if(!this.frm.doc.fiscal_year && sys_defaults.fiscal_year) 
+			set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});		
+	
+		if(this.frm.doc.enquiry_from) {
+			if(this.frm.doc.enquiry_from == 'Customer') {
+				hide_field('lead');
+			}
+			else if (this.frm.doc.enquiry_from == 'Lead') {
+				hide_field(['customer', 'customer_address', 'contact_person', 'customer_group']);
+			}
+		} 
+
+		if(!this.frm.doc.__islocal) {
+			cur_frm.communication_view = new wn.views.CommunicationList({
+				list: wn.model.get("Communication", {"opportunity": this.frm.doc.name}),
+				parent: cur_frm.fields_dict.communication_html.wrapper,
+				doc: this.frm.doc,
+				recipients: this.frm.doc.contact_email
+			});
+		}
+		
+		if(this.frm.doc.customer && !this.frm.doc.customer_name) cur_frm.cscript.customer(doc);
+		
+		this.setup_queries();
+	},
+	
+	setup_queries: function() {
+		var me = this;
+		
+		if(this.frm.fields_dict.contact_by.df.options.match(/^Profile/)) {
+			this.frm.set_query("contact_by", erpnext.queries.profile);
+		}
+		
+		this.frm.set_query("item_code", "enquiry_details", function() {
+			var key = (me.frm.doc.enquiry_type === "Maintenance" ? "is_service_item" : "is_sales_item");
+			return {
+				query: "controllers.queries.item_query",
+				filters: { key: "Yes" }
+			};
+		});
+		
+		$.each([["lead", "lead"],
+			["customer", "customer"],
+			["customer_address", "customer_filter"], 
+			["contact_person", "customer_filter"],
+			["territory", "not_a_group_filter"]], function(i, opts) {
+				me.frm.set_query(opts[0], erpnext.queries[opts[1]]);
+			});
+	},
+	
 	customer: function() {
 		var me = this;
 		if(this.frm.doc.customer) {
@@ -70,52 +134,6 @@
 	
 }
 
-// ONLOAD
-// ===============================================================
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-
-	if(!doc.enquiry_from && doc.customer)
-		doc.enquiry_from = "Customer";
-	if(!doc.enquiry_from && doc.lead)
-		doc.enquiry_from = "Lead";
-
-	if(!doc.enquiry_from) 
-		hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
-	if(!doc.status) 
-		set_multiple(cdt,cdn,{status:'Draft'});
-	if(!doc.date) 
-		doc.transaction_date = date.obj_to_str(new Date());
-	if(!doc.company && sys_defaults.company) 
-		set_multiple(cdt,cdn,{company:sys_defaults.company});
-	if(!doc.fiscal_year && sys_defaults.fiscal_year) 
-		set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});		
-	
-	if(doc.enquiry_from) {
-		if(doc.enquiry_from == 'Customer') {
-			hide_field('lead');
-		}
-		else if (doc.enquiry_from == 'Lead') {
-			hide_field(['customer', 'customer_address', 'contact_person', 'customer_group']);
-		}
-	} 
-
-	if(!doc.__islocal) {
-		cur_frm.communication_view = new wn.views.CommunicationList({
-			list: wn.model.get("Communication", {"opportunity": doc.name}),
-			parent: cur_frm.fields_dict.communication_html.wrapper,
-			doc: doc,
-			recipients: doc.contact_email
-		});
-	}
-	
-	if(cur_frm.fields_dict.contact_by.df.options.match(/^Profile/)) {
-		cur_frm.fields_dict.contact_by.get_query = function(doc,cdt,cdn) {
-				return { query:"controllers.queries.profile_query" } }
-	}
-	
-	if(doc.customer && !doc.customer_name) cur_frm.cscript.customer(doc);
-}
-
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
 	if(doc.enquiry_from == 'Lead' && doc.lead) {
 	 	cur_frm.cscript.lead(doc,cdt,cdn);
@@ -153,26 +171,6 @@
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return {
-		filters:{'customer':doc.customer}
-	}
-}
-
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	if (!doc.customer) msgprint("Please select customer first");
-	else {
-		filters:{'customer':doc.customer}
-	}
-}
-
-// lead
-cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
-	return {
-		query: "selling.doctype.opportunity.opportunity.get_lead"
-	}
-}
-
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
 	cur_frm.toggle_display("contact_info", doc.customer || doc.lead);
 	
@@ -185,19 +183,7 @@
 		'contact_email', 'territory']);	
 }
 
-cur_frm.fields_dict['enquiry_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
-	if (doc.enquiry_type == 'Maintenance') {
-		return {
-			query:"controllers.queries.item_query",
-			filters:{ 'is_service_item': 'Yes' }
-		}
-	} else {
-		return {
-			query:"controllers.queries.item_query",
-			filters:{ 'is_sales_item': 'Yes' }
-		}		
-	}
-}
+
 
 cur_frm.cscript['Declare Opportunity Lost'] = function(){
 	var dialog = new wn.ui.Dialog({
@@ -229,16 +215,4 @@
 	});
 	dialog.show();
 	
-}
-
-//get query select Territory
-cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return{
-		filters:{'is_group': 'No'}
-	}	
-	
-cur_frm.fields_dict.lead.get_query = function(doc,cdt,cdn) {
-				return { query:"controllers.queries.lead_query" } }
-
-cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
-				return { query:"controllers.queries.customer_query" } }
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/selling/doctype/opportunity/opportunity.py b/selling/doctype/opportunity/opportunity.py
index d4a97b6..f31d533 100644
--- a/selling/doctype/opportunity/opportunity.py
+++ b/selling/doctype/opportunity/opportunity.py
@@ -197,14 +197,4 @@
 		}
 	}, target_doclist)
 		
-	return [d.fields for d in doclist]
-
-def get_lead(doctype, txt, searchfield, start, page_len, filters):
-	from controllers.queries import get_match_cond
-	return webnotes.conn.sql ("""select `tabLead`.name, `tabLead`.lead_name FROM `tabLead` 
-			where `tabLead`.%(key)s like "%(txt)s" 
-				%(mcond)s	
-			order by `tabLead`.`name` asc 
-			limit %(start)s, %(page_len)s """ % {'key': searchfield, 
-			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield),
-			'start': start, 'page_len': page_len})
\ No newline at end of file
+	return [d.fields for d in doclist]
\ No newline at end of file
diff --git a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
index 94b3bf0..d736ff6 100644
--- a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
+++ b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
@@ -14,15 +14,17 @@
 // You should have received a copy of the GNU General Public License
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-cur_frm.fields_dict['item_code'].get_query = function(doc) {
- 	return {
- 		query: "controllers.queries.item_std"
- 	}	
-}
-
-//==================== Get Items Stock UOM =====================================================
-cur_frm.cscript.item_code = function(doc,cdt,cdn) {
- if (doc.item_code) {
-    get_server_fields('get_stock_uom', doc.item_code, '', doc, cdt, cdn, 1);
-  }
-}
\ No newline at end of file
+$.extend(cur_frm.cscript, {
+	onload: function() {
+		cur_frm.set_query("item_code", erpnext.queries.item);
+	},
+	
+	item_code: function() {
+		if(cur_frm.doc.item_code) {
+			cur_frm.call({
+				method: "get_stock_uom",
+				args: { item_code: cur_frm.doc.item_code }
+			});
+		}
+	}
+});
\ No newline at end of file
diff --git a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
index dbcccc4..f353629 100644
--- a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
+++ b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
@@ -31,9 +31,6 @@
 	def __init__(self, d, dl=[]):
 		self.doc, self.doclist = d,dl
 
-	def get_stock_uom(self, item_code):
-		return {'current_stock_uom': cstr(webnotes.conn.get_value('Item', item_code, 'stock_uom'))}
-	
 	def validate_mandatory(self):
 		if not cstr(self.doc.item_code):
 			msgprint("Please Enter an Item.")
@@ -111,3 +108,8 @@
 		self.update_bin()
 
 		get_obj("Item", self.doc.item_code).on_update()
+
+@webnotes.whitelist()
+def get_stock_uom(item_code):
+	return { 'current_stock_uom': cstr(webnotes.conn.get_value('Item', item_code, 'stock_uom')) }
+