Merge branch 'responsive' of github.com:webnotes/erpnext into responsive
diff --git a/hr/doctype/salary_slip/salary_slip.py b/hr/doctype/salary_slip/salary_slip.py
index 2b1d80c..09bd602 100644
--- a/hr/doctype/salary_slip/salary_slip.py
+++ b/hr/doctype/salary_slip/salary_slip.py
@@ -33,16 +33,12 @@
 		self.doc = doc
 		self.doclist = doclist
 		
-		
 	def autoname(self):
 		self.doc.name = make_autoname('Sal Slip/' +self.doc.employee + '/.#####') 
 
-
 	def get_emp_and_leave_details(self):
 		if self.doc.employee:
 			self.get_leave_details()
-
-			# check sal structure
 			struct = self.check_sal_struct()
 			if struct:
 				self.pull_sal_struct(struct)
@@ -91,16 +87,18 @@
 			where name = %s", self.doc.employee, as_dict=1)[0]
 			
 		if emp['relieving_date']:
-			if getdate(emp['relieving_date']) > m['month_start_date'] and getdate(emp['relieving_date']) < m['month_end_date']:
-				payment_days = getdate(emp['relieving_date']).day
+			if getdate(emp['relieving_date']) > m['month_start_date'] and \
+				getdate(emp['relieving_date']) < m['month_end_date']:
+					payment_days = getdate(emp['relieving_date']).day
 			elif getdate(emp['relieving_date']) < m['month_start_date']:
 				webnotes.msgprint(_("Relieving Date of employee is ") + cstr(emp['relieving_date']
 					+ _(". Please set status of the employee as 'Left'")), raise_exception=1)
 				
 			
 		if emp['date_of_joining']:
-			if getdate(emp['date_of_joining']) > m['month_start_date'] and getdate(emp['date_of_joining']) < m['month_end_date']:
-				payment_days = payment_days - getdate(emp['date_of_joining']).day + 1
+			if getdate(emp['date_of_joining']) > m['month_start_date'] and \
+				getdate(emp['date_of_joining']) < m['month_end_date']:
+					payment_days = payment_days - getdate(emp['date_of_joining']).day + 1
 			elif getdate(emp['date_of_joining']) > m['month_end_date']:
 				payment_days = 0
 
@@ -110,9 +108,16 @@
 
 
 	def calculate_lwp(self, m):
-		holidays = sql("select t1.holiday_date from `tabHoliday` t1, tabEmployee t2 where t1.parent = t2.holiday_list and t2.name = '%s' and t1.holiday_date between '%s' and '%s'" % (self.doc.employee, m['month_start_date'], m['month_end_date']))
+		holidays = sql("""select t1.holiday_date 
+			from `tabHoliday` t1, tabEmployee t2 
+			where t1.parent = t2.holiday_list and t2.name = %s 
+			and t1.holiday_date between %s and %s""", 
+			(self.doc.employee, m['month_start_date'], m['month_end_date']))
 		if not holidays:
-			holidays = sql("select t1.holiday_date from `tabHoliday` t1, `tabHoliday List` t2 where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1 and t2.fiscal_year = '%s'" % self.doc.fiscal_year)
+			holidays = sql("""select t1.holiday_date 
+				from `tabHoliday` t1, `tabHoliday List` t2 
+				where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1 
+				and t2.fiscal_year = %s""", self.doc.fiscal_year)
 		holidays = [cstr(i[0]) for i in holidays]
 		lwp = 0
 		for d in range(m['month_days']):
@@ -124,20 +129,22 @@
 					where t2.name = t1.leave_type 
 					and ifnull(t2.is_lwp, 0) = 1 
 					and t1.docstatus = 1 
-					and t1.employee = '%s' 
-					and '%s' between from_date and to_date
-				"""%(self.doc.employee, dt))
+					and t1.employee = %s
+					and %s between from_date and to_date
+				""", (self.doc.employee, dt))
 				if leave:
 					lwp = cint(leave[0][1]) and lwp + 0.5 or lwp + 1
 		return lwp
-					
 
 	def check_existing(self):
-		ret_exist = sql("select name from `tabSalary Slip` where month = '%s' and fiscal_year = '%s' and docstatus != 2 and employee = '%s' and name !='%s'" % (self.doc.month,self.doc.fiscal_year,self.doc.employee,self.doc.name))
+		ret_exist = sql("""select name from `tabSalary Slip` 
+			where month = %s and fiscal_year = %s and docstatus != 2 
+			and employee = %s and name != %s""", 
+			(self.doc.month, self.doc.fiscal_year, self.doc.employee, self.doc.name))
 		if ret_exist:
-			msgprint("Salary Slip of employee '%s' already created for this month" % self.doc.employee)
 			self.doc.employee = ''
-			raise Exception
+			msgprint("Salary Slip of employee '%s' already created for this month" 
+				% self.doc.employee, raise_exception=1)
 
 
 	def validate(self):
@@ -146,41 +153,32 @@
 		company_currency = get_company_currency(self.doc.company)
 		self.doc.total_in_words = money_in_words(self.doc.rounded_total, company_currency)
 
-
 	def calculate_earning_total(self):
-		"""
-			Calculates total earnings considering lwp
-		"""
 		self.doc.gross_pay = flt(self.doc.arrear_amount) + flt(self.doc.leave_encashment_amount)
 		for d in getlist(self.doclist, 'earning_details'):
 			if cint(d.e_depends_on_lwp) == 1:
-				d.e_modified_amount = round(flt(d.e_amount)*flt(self.doc.payment_days)/cint(self.doc.total_days_in_month), 2)
+				d.e_modified_amount = round(flt(d.e_amount) * flt(self.doc.payment_days)
+					/ cint(self.doc.total_days_in_month), 2)
 			elif not self.doc.payment_days:
 				d.e_modified_amount = 0
 			self.doc.gross_pay += flt(d.e_modified_amount)
 	
 	def calculate_ded_total(self):
-		"""
-			Calculates total deduction considering lwp
-		"""
 		self.doc.total_deduction = 0
 		for d in getlist(self.doclist, 'deduction_details'):
 			if cint(d.d_depends_on_lwp) == 1:
-				d.d_modified_amount = round(flt(d.d_amount)*flt(self.doc.payment_days)/cint(self.doc.total_days_in_month), 2)
+				d.d_modified_amount = round(flt(d.d_amount) * flt(self.doc.payment_days) 
+					/ cint(self.doc.total_days_in_month), 2)
 			elif not self.doc.payment_days:
 				d.d_modified_amount = 0
 			
 			self.doc.total_deduction += flt(d.d_modified_amount)
 				
 	def calculate_net_pay(self):
-		"""
-			Calculate net payment
-		"""
 		self.calculate_earning_total()
 		self.calculate_ded_total()
 		self.doc.net_pay = flt(self.doc.gross_pay) - flt(self.doc.total_deduction)
-		self.doc.rounded_total = round(self.doc.net_pay)
-		
+		self.doc.rounded_total = round(self.doc.net_pay)		
 
 	def on_submit(self):
 		if(self.doc.email_check == 1):			
@@ -189,12 +187,13 @@
 
 	def send_mail_funct(self):	 
 		from webnotes.utils.email_lib import sendmail
-		emailid_ret=sql("select company_email from `tabEmployee` where name = '%s'"%self.doc.employee)
-		if emailid_ret:
-			receiver = cstr(emailid_ret[0][0]) 
+		receiver = webnotes.conn.get_value("Employee", self.doc.employee, "company_email")
+		if receiver:
 			subj = 'Salary Slip - ' + cstr(self.doc.month) +'/'+cstr(self.doc.fiscal_year)
-			earn_ret=sql("select e_type,e_modified_amount from `tabSalary Slip Earning` where parent = '%s'"%self.doc.name)
-			ded_ret=sql("select d_type,d_modified_amount from `tabSalary Slip Deduction` where parent = '%s'"%self.doc.name)
+			earn_ret=sql("""select e_type, e_modified_amount from `tabSalary Slip Earning` 
+				where parent = %s""", self.doc.name)
+			ded_ret=sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction` 
+				where parent = %s""", self.doc.name)
 		 
 			earn_table = ''
 			ded_table = ''
@@ -203,9 +202,10 @@
 				
 				for e in earn_ret:
 					if not e[1]:
-						earn_table +='<tr><td>%s</td><td align="right">0.00</td></tr>'%(cstr(e[0]))
+						earn_table += '<tr><td>%s</td><td align="right">0.00</td></tr>' % cstr(e[0])
 					else:
-						earn_table +='<tr><td>%s</td><td align="right">%s</td></tr>'%(cstr(e[0]),cstr(e[1]))
+						earn_table += '<tr><td>%s</td><td align="right">%s</td></tr>' \
+							% (cstr(e[0]), cstr(e[1]))
 				earn_table += '</table>'
 			
 			if ded_ret:
@@ -214,15 +214,14 @@
 				
 				for d in ded_ret:
 					if not d[1]:
-						ded_table +='<tr><td">%s</td><td align="right">0.00</td></tr>'%(cstr(d[0]))
+						ded_table +='<tr><td">%s</td><td align="right">0.00</td></tr>' % cstr(d[0])
 					else:
-						ded_table +='<tr><td>%s</td><td align="right">%s</td></tr>'%(cstr(d[0]),cstr(d[1]))
+						ded_table +='<tr><td>%s</td><td align="right">%s</td></tr>' \
+							% (cstr(d[0]), cstr(d[1]))
 				ded_table += '</table>'
 			
-			letter_head = sql("select value from `tabSingles` where field = 'letter_head' and doctype = 'Control Panel'")
-			
-			if not letter_head:
-				letter_head = ''
+			letter_head = webnotes.conn.get_value("Letter Head", {"is_default": 1, "disabled": 0}, 
+				"content")
 			
 			msg = '''<div> %s <br>
 			<table cellspacing= "5" cellpadding="5"  width = "100%%">
@@ -258,8 +257,10 @@
 			</table>
 			<table border="1px solid #CCC" width="100%%" cellpadding="0px" cellspacing="0px">
 				<tr>
-					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center"><b>Earnings</b></td>
-					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center"><b>Deductions</b></td>
+					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center">
+						<b>Earnings</b></td>
+					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center">
+						<b>Deductions</b></td>
 				</tr>
 				<tr>
 					<td colspan = 2 width = "50%%" valign= "top">%s</td>
@@ -268,17 +269,28 @@
 			</table>
 			<table cellspacing= "5" cellpadding="5" width = '100%%'>
 				<tr>
-					<td width = '25%%'><b>Gross Pay :</b> </td><td width = '25%%' align='right'>%s</td>
-					<td width = '25%%'><b>Total Deduction :</b></td><td width = '25%%' align='right'> %s</td>
+					<td width = '25%%'><b>Gross Pay :</b> </td>
+					<td width = '25%%' align='right'>%s</td>
+					<td width = '25%%'><b>Total Deduction :</b></td>
+					<td width = '25%%' align='right'> %s</td>
 				</tr>
 				<tr>
-					<tdwidth='25%%'><b>Net Pay : </b></td><td width = '25%%' align='right'><b>%s</b></td>
+					<tdwidth='25%%'><b>Net Pay : </b></td>
+					<td width = '25%%' align='right'><b>%s</b></td>
 					<td colspan = '2' width = '50%%'></td>
 				</tr>
 				<tr>
-					<td width='25%%'><b>Net Pay(in words) : </td><td colspan = '3' width = '50%%'>%s</b></td>
+					<td width='25%%'><b>Net Pay(in words) : </td>
+					<td colspan = '3' width = '50%%'>%s</b></td>
 				</tr>
-			</table></div>'''%(cstr(letter_head[0][0]),cstr(self.doc.employee), cstr(self.doc.employee_name), cstr(self.doc.month), cstr(self.doc.fiscal_year), cstr(self.doc.department), cstr(self.doc.branch), cstr(self.doc.designation), cstr(self.doc.grade), cstr(self.doc.bank_account_no), cstr(self.doc.bank_name), cstr(self.doc.arrear_amount), cstr(self.doc.payment_days), earn_table, ded_table, cstr(flt(self.doc.gross_pay)), cstr(flt(self.doc.total_deduction)), cstr(flt(self.doc.net_pay)), cstr(self.doc.total_in_words))
+			</table></div>''' % (cstr(letter_head), cstr(self.doc.employee), 
+				cstr(self.doc.employee_name), cstr(self.doc.month), cstr(self.doc.fiscal_year), 
+				cstr(self.doc.department), cstr(self.doc.branch), cstr(self.doc.designation), 
+				cstr(self.doc.grade), cstr(self.doc.bank_account_no), cstr(self.doc.bank_name), 
+				cstr(self.doc.arrear_amount), cstr(self.doc.payment_days), earn_table, ded_table, 
+				cstr(flt(self.doc.gross_pay)), cstr(flt(self.doc.total_deduction)), 
+				cstr(flt(self.doc.net_pay)), cstr(self.doc.total_in_words))
+
 			sendmail([receiver], subject=subj, msg = msg)
 		else:
 			msgprint("Company Email ID not found, hence mail not sent")
diff --git a/stock/doctype/stock_entry/stock_entry.js b/stock/doctype/stock_entry/stock_entry.js
index 3fc03cb..123c9fb 100644
--- a/stock/doctype/stock_entry/stock_entry.js
+++ b/stock/doctype/stock_entry/stock_entry.js
@@ -313,23 +313,14 @@
 cur_frm.fields_dict['mtn_details'].grid.get_field('batch_no').get_query = function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];		
 	if(d.item_code) {
-		if (d.s_warehouse) {
-			return{
-				query: "stock.doctype.stock_entry.stock_entry.get_batch_no",
-				filters:{
-					'item_code': d.item_code,
-					's_warehouse': d.s_warehouse,
-					'posting_date': doc.posting_date
-				}
-			}			
-		} else {
-			return{
-				filters:[
-					['Batch', 'item', '=', d.item_code],
-					['Batch', 'expiry_date', '>=', doc.posting_date]
-				]
+		return{
+			query: "stock.doctype.stock_entry.stock_entry.get_batch_no",
+			filters:{
+				'item_code': d.item_code,
+				's_warehouse': d.s_warehouse,
+				'posting_date': doc.posting_date
 			}
-		}		
+		}			
 	} else {
 		msgprint("Please enter Item Code to get batch no");
 	}
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index 4e2d484..47c0a75 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -18,7 +18,7 @@
 import webnotes
 import webnotes.defaults
 
-from webnotes.utils import cstr, cint, flt, comma_or
+from webnotes.utils import cstr, cint, flt, comma_or, nowdate
 from webnotes.model.doc import Document, addchild
 from webnotes.model.bean import getlist
 from webnotes.model.code import get_obj
@@ -719,7 +719,6 @@
 	return result and result[0] or {}
 	
 def query_sales_return_doc(doctype, txt, searchfield, start, page_len, filters):
-	from controllers.queries import get_match_cond
 	conditions = ""
 	if doctype == "Sales Invoice":
 		conditions = "and update_stock=1"
@@ -735,7 +734,6 @@
 		as_list=True)
 	
 def query_purchase_return_doc(doctype, txt, searchfield, start, page_len, filters):
-	from controllers.queries import get_match_cond
 	return webnotes.conn.sql("""select name, supplier, supplier_name
 		from `tab%s` where docstatus = 1
 			and (`%s` like %%(txt)s 
@@ -770,24 +768,50 @@
 	return result[start:start+page_len]
 
 def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
-	from controllers.queries import get_match_cond
-
-	return webnotes.conn.sql("""select batch_no from `tabStock Ledger Entry` sle 
+	if not filters.get("posting_date"):
+		filters["posting_date"] = nowdate()
+		
+	batch_nos = None
+	args = {
+		'item_code': filters['item_code'], 
+		's_warehouse': filters['s_warehouse'], 
+		'posting_date': filters['posting_date'], 
+		'txt': "%%%s%%" % txt, 
+		'mcond':get_match_cond(doctype, searchfield), 
+		"start": start, 
+		"page_len": page_len
+	}
+	
+	if filters.get("s_warehouse"):
+		batch_nos = webnotes.conn.sql("""select batch_no 
+			from `tabStock Ledger Entry` sle 
 			where item_code = '%(item_code)s' 
 				and warehouse = '%(s_warehouse)s'
 				and ifnull(is_cancelled, 'No') = 'No' 
 				and batch_no like '%(txt)s' 
 				and exists(select * from `tabBatch` 
-						where name = sle.batch_no 
-							and expiry_date >= %(posting_date)s 
-							and docstatus != 2) 
+					where name = sle.batch_no 
+					and (ifnull(expiry_date, '2099-12-31') >= %(posting_date)s 
+						or expiry_date = '')
+					and docstatus != 2) 
 			%(mcond)s
 			group by batch_no having sum(actual_qty) > 0 
 			order by batch_no desc 
-			limit %(start)s, %(page_len)s """ % {'item_code': filters['item_code'], 
-			's_warehouse': filters['s_warehouse'], 'posting_date': filters['posting_date'], 
-			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 
-			"start": start, "page_len": page_len})
+			limit %(start)s, %(page_len)s """ 
+			% args)
+	
+	if batch_nos:
+		return batch_nos
+	else:
+		return webnotes.conn.sql("""select name from `tabBatch` 
+			where item = '%(item_code)s'
+			and docstatus < 2
+			and (ifnull(expiry_date, '2099-12-31') >= %(posting_date)s 
+				or expiry_date = '' or expiry_date = "0000-00-00")
+			%(mcond)s
+			order by name desc 
+			limit %(start)s, %(page_len)s
+		""" % args)
 
 def get_stock_items_for_return(ref_doclist, parentfields):
 	"""return item codes filtered from doclist, which are stock items"""