Merge pull request #1107 from akhileshdarjee/master

[fix] [minor] fiscal year validation ignored for test cases
diff --git a/accounts/doctype/mis_control/mis_control.py b/accounts/doctype/mis_control/mis_control.py
index 3637d44..3a0483f 100644
--- a/accounts/doctype/mis_control/mis_control.py
+++ b/accounts/doctype/mis_control/mis_control.py
@@ -3,16 +3,9 @@
 
 from __future__ import unicode_literals
 import webnotes
-
-from webnotes.utils import cint, cstr, flt, get_first_day, get_last_day, has_common
-from webnotes.model import db_exists
-from webnotes.model.bean import copy_doclist
-from webnotes import session, msgprint
-
+from webnotes.utils import flt, get_first_day, get_last_day, has_common
 import webnotes.defaults
-
-
-from accounts.utils import get_balance_on, get_fiscal_year
+from accounts.utils import get_balance_on
 
 class DocType:
 	def __init__(self, doc, doclist):
@@ -30,15 +23,12 @@
 		self.flag = 0
 		
 	# Get defaults on load of MIS, MIS - Comparison Report and Financial statements
-	# ----------------------------------------------------
 	def get_comp(self):
 		ret = {}
 		type = []
-		comp = []
-		# ------ get period -----------
+
 		ret['period'] = ['Annual','Half Yearly','Quarterly','Monthly']
 		
-		# ---- get companies ---------
 		from accounts.page.accounts_browser.accounts_browser import get_companies
 		ret['company'] = get_companies()
 
@@ -58,7 +48,7 @@
 		for i in range(0,fiscal_start_month-1): mon.append(month_list[i])
 		ret['month'] = mon
 
-		# ------------------------ get MIS Type on basis of roles of session user ------------------------------------------
+		# get MIS Type on basis of roles of session user
 		self.roles = webnotes.user.get_roles()
 		if has_common(self.roles, ['Sales Manager']):
 			type.append('Sales')
@@ -66,101 +56,7 @@
 			type.append('Purchase')
 		ret['type'] = type
 		return ret
-		
-	# Gets Transactions type and Group By options based on module
-	#------------------------------------------------------------------
-	def get_trans_group(self,module):
-		ret = {}
-		st,group = [],[]
-		if module == 'Sales':
-			st = ['Quotation','Sales Order','Delivery Note','Sales Invoice']
-			group = ['Item','Item Group','Customer','Customer Group','Cost Center']
-		elif module == 'Purchase':
-			st = ['Purchase Order','Purchase Receipt','Purchase Invoice']
-			group = ['Item','Item Group','Supplier','Supplier Type']
-		
-		ret['stmt_type'] = st
-		ret['group_by'] = group
-		
-		return ret
 
-	# Get Days based on month (for MIS Comparison Report)
-	# --------------------------------------------------------
-	def get_days(self,month):
-		days = []
-		ret = {}
-		if month == 'Jan' or month == 'Mar' or month == 'May' or month == 'Jul' or month == 'Aug' or month == 'Oct' or month == 'Dec':
-			for i in range(1,32):
-				days.append(i)
-		elif month == 'Apr' or month == 'Jun' or month == 'Sep' or month == 'Nov':
-			for i in range(1,31):
-				days.append(i)
-		elif month == 'Feb':
-			for i in range(1,29):
-				days.append(i)
-		ret['days'] = days
-		return ret
-	
-	# Get from date and to date based on fiscal year (for in summary - comparison report)
-	# -----------------------------------------------------------------------------------------------------
-	def dates(self,fiscal_year,from_date,to_date):
-		import datetime
-		ret = ''
-		start_date = cstr(webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name = %s",fiscal_year)[0][0])
-		st_mon = cint(from_date.split('-')[1])
-		ed_mon = cint(to_date.split('-')[1])
-		st_day = cint(from_date.split('-')[2])
-		ed_day = cint(to_date.split('-')[2])
-		fiscal_start_month = cint(start_date.split('-')[1])
-		next_fiscal_year = cint(start_date.split('-')[0]) + 1
-		current_year = ''
-		next_year = ''
-		
-		#CASE - 1 : Jan - Mar (Valid)
-		if st_mon < fiscal_start_month and ed_mon < fiscal_start_month:
-			current_year = cint(start_date.split('-')[0]) + 1
-			next_year	= cint(start_date.split('-')[0]) + 1
-		
-		# Case - 2 : Apr - Dec (Valid)
-		elif st_mon >= fiscal_start_month and ed_mon <= 12 and ed_mon >= fiscal_start_month:
-			current_year = cint(start_date.split('-')[0])
-			next_year	= cint(start_date.split('-')[0])
-
-		# Case 3 : Jan - May (Invalid)
-		elif st_mon < fiscal_start_month and ed_mon >= fiscal_start_month:
-			current_year = cint(start_date.split('-')[0]) + 1
-			next_year	= cint(start_date.split('-')[0]) + 2
-	
-		# check whether from date is within fiscal year
-		if datetime.date(current_year, st_mon, st_day) >= datetime.date(cint(start_date.split('-')[0]), cint(start_date.split('-')[1]), cint(start_date.split('-')[2])) and datetime.date(cint(current_year), cint(st_mon), cint(st_day)) < datetime.date((cint(start_date.split('-')[0])+1), cint(start_date.split('-')[1]), cint(start_date.split('-')[2])):
-			begin_date = cstr(current_year)+"-"+cstr(st_mon)+"-"+cstr(st_day)
-		else:
-			msgprint("Please enter appropriate from date.")
-			raise Exception
-		# check whether to date is within fiscal year
-		if datetime.date(next_year, ed_mon, ed_day) >= datetime.date(cint(start_date.split('-')[0]), cint(start_date.split('-')[1]), cint(start_date.split('-')[2])) and datetime.date(cint(next_year), cint(ed_mon), cint(ed_day)) < datetime.date(cint(start_date.split('-')[0])+1, cint(start_date.split('-')[1]), cint(start_date.split('-')[2])):
-			end_date = cstr(next_year)+"-"+cstr(ed_mon)+"-"+cstr(ed_day)
-		else:
-			msgprint("Please enter appropriate to date.")
-			raise Exception
-		ret = begin_date+'~~~'+end_date
-		return ret
-
-	# Get MIS Totals
-	# ---------------
-	def get_totals(self, args):
-		args = eval(args)
-		#msgprint(args)
-		totals = webnotes.conn.sql("SELECT %s FROM %s WHERE %s %s %s %s" %(cstr(args['query_val']), cstr(args['tables']), cstr(args['company']), cstr(args['cond']), cstr(args['add_cond']), cstr(args['fil_cond'])), as_dict = 1)[0]
-		#msgprint(totals)
-		tot_keys = totals.keys()
-		# return in flt because JSON doesn't accept Decimal
-		for d in tot_keys:
-			totals[d] = flt(totals[d])
-		return totals
-
-	# Get Statement
-	# -------------
 	
 	def get_statement(self, arg): 
 		self.return_data = []		
@@ -176,13 +72,9 @@
 		if arg['statement'] == 'Balance Sheet': pl = 'No'
 		if arg['statement'] == 'Profit & Loss': pl = 'Yes'
 		self.get_children('',0,pl,arg['company'], arg['year'])
-				
-		#self.balance_pl_statement(acct, arg['statement'])
-		#msgprint(self.return_data)
-		return self.return_data
 		
-	# Get Children
-	# ------------
+		return self.return_data
+
 	def get_children(self, parent_account, level, pl, company, fy):
 		cl = webnotes.conn.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
 		level0_diff = [0 for p in self.period_list]
@@ -208,7 +100,6 @@
 					self.get_children(c[1], level+1, pl, company, fy)
 					
 				# make totals - for top level
-				# ---------------------------
 				if level==0:
 					# add rows for profit / loss in B/S
 					if pl=='No':
@@ -230,13 +121,8 @@
 								level0_diff[i] = flt(totals[i]) + level0_diff[i]
 						else:
 							self.return_data.append([4, 'Total '+c[0]] + totals)
-	
-	# Define Periods
-	# --------------
-	
-	def define_periods(self, year, period):
-		
-		# get year start date		
+
+	def define_periods(self, year, period):	
 		ysd = webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
 		ysd = ysd and ysd[0][0] or ''
 
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.txt b/accounts/doctype/purchase_invoice/purchase_invoice.txt
index f98c14a..af0eb8e 100755
--- a/accounts/doctype/purchase_invoice/purchase_invoice.txt
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-21 16:16:39", 
   "docstatus": 0, 
-  "modified": "2013-11-05 23:09:38", 
+  "modified": "2013-11-22 17:15:27", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -297,7 +297,7 @@
   "oldfieldname": "net_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -396,7 +396,7 @@
   "oldfieldname": "grand_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -406,7 +406,7 @@
   "label": "In Words", 
   "oldfieldname": "in_words_import", 
   "oldfieldtype": "Data", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
diff --git a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
index e1a0d14..84521ed 100644
--- a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
+++ b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
@@ -14,6 +14,19 @@
    cur_frm.set_footnote(wn.markdown(cur_frm.meta.description));
 }
 
+// For customizing print
+cur_frm.pformat.net_total_import = function(doc) {
+	return '';
+}
+
+cur_frm.pformat.grand_total_import = function(doc) {
+	return '';
+}
+
+cur_frm.pformat.in_words_import = function(doc) {
+	return '';
+}
+
 cur_frm.pformat.purchase_tax_details= function(doc){
  
   //function to make row of table
@@ -42,9 +55,9 @@
 		<tr><td style="width: 60%"></td><td>';
   
   // main table
-  out +='<table class="noborder" style="width:100%">'
-  if(!print_hide('net_total')) {
-	out += make_row('Net Total', convert_rate(doc.net_total), 1);
+  out +='<table class="noborder" style="width:100%">';
+  if(!print_hide('net_total_import')) {
+	out += make_row('Net Total', doc.net_total_import, 1);
   }
   
   // add rows
diff --git a/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.py b/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.py
index 574a66a..3529aee 100644
--- a/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.py
+++ b/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.py
@@ -74,4 +74,4 @@
 	for t in webnotes.conn.sql("""select name, posting_date from `tabSales Invoice`"""):
 		si_posting_date_map[t[0]] = t[1]
 		
-	return si_posting_date_map
\ No newline at end of file
+	return si_posting_date_map
diff --git a/accounts/report/payment_made_with_ageing/payment_made_with_ageing.py b/accounts/report/payment_made_with_ageing/payment_made_with_ageing.py
index 6d0ca8a..a70ce1b 100644
--- a/accounts/report/payment_made_with_ageing/payment_made_with_ageing.py
+++ b/accounts/report/payment_made_with_ageing/payment_made_with_ageing.py
@@ -73,4 +73,4 @@
 	for t in webnotes.conn.sql("""select name, posting_date from `tabPurchase Invoice`"""):
 		pi_posting_date_map[t[0]] = t[1]
 		
-	return pi_posting_date_map
\ No newline at end of file
+	return pi_posting_date_map
diff --git a/accounts/utils.py b/accounts/utils.py
index 7f8f0e6..caad793 100644
--- a/accounts/utils.py
+++ b/accounts/utils.py
@@ -344,4 +344,28 @@
 		from `tabGL Entry`
 		where account='%(account)s' and cost_center='%(cost_center)s' 
 		and fiscal_year='%(fiscal_year)s' and company='%(company)s' %(condition)s
-	""" % (args))[0][0]
\ No newline at end of file
+	""" % (args))[0][0]
+	
+def rename_account_for(dt, olddn, newdn, merge):
+	old_account = get_account_for(dt, olddn)
+	if old_account:
+		new_account = None
+		if not merge:
+			if old_account == olddn:
+				new_account = webnotes.rename_doc("Account", olddn, newdn)
+		else:
+			existing_new_account = get_account_for(dt, newdn)
+			new_account = webnotes.rename_doc("Account", old_account, 
+				existing_new_account or newdn, merge=True if existing_new_account else False)
+
+		if new_account:
+			webnotes.conn.set_value("Account", new_account, "master_name", newdn)
+			
+def get_account_for(account_for_doctype, account_for):
+	if account_for_doctype in ["Customer", "Supplier"]:
+		account_for_field = "master_type"
+	elif account_for_doctype == "Warehouse":
+		account_for_field = "account_type"
+		
+	return webnotes.conn.get_value("Account", {account_for_field: account_for_doctype, 
+		"master_name": account_for})
diff --git a/buying/doctype/purchase_order/purchase_order.txt b/buying/doctype/purchase_order/purchase_order.txt
index 6a97eed..3f3937c 100644
--- a/buying/doctype/purchase_order/purchase_order.txt
+++ b/buying/doctype/purchase_order/purchase_order.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-21 16:16:39", 
   "docstatus": 0, 
-  "modified": "2013-11-05 23:09:58", 
+  "modified": "2013-11-22 17:20:58", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -263,7 +263,7 @@
   "oldfieldname": "net_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -376,7 +376,7 @@
   "oldfieldname": "grand_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1, 
   "report_hide": 0
  }, 
@@ -387,7 +387,7 @@
   "label": "In Words", 
   "oldfieldname": "in_words_import", 
   "oldfieldtype": "Data", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
diff --git a/buying/doctype/supplier/supplier.py b/buying/doctype/supplier/supplier.py
index f60d4dd..b2873c5 100644
--- a/buying/doctype/supplier/supplier.py
+++ b/buying/doctype/supplier/supplier.py
@@ -148,21 +148,13 @@
 		self.delete_supplier_contact()
 		self.delete_supplier_account()
 		
-	def after_rename(self, old, new, merge=False):
-		#update supplier_name if not naming series
+	def before_rename(self, olddn, newdn, merge=False):
+		from accounts.utils import rename_account_for
+		rename_account_for("Supplier", olddn, newdn, merge)
+		
+	def after_rename(self, olddn, newdn, merge=False):
 		if webnotes.defaults.get_global_default('supp_master_name') == 'Supplier Name':
-			webnotes.conn.set(self.doc, "supplier_name", new)
-				
-		for account in webnotes.conn.sql("""select name, account_name from 
-			tabAccount where master_name=%s and master_type='Supplier'""", old, as_dict=1):
-			if account.account_name != new:
-				merge_account = True if merge and webnotes.conn.get_value("Account", 
-					{"master_name": new, "master_type": "Supplier"}) else False
-				webnotes.rename_doc("Account", account.name, new, merge=merge_account)
-
-		#update master_name in doctype account
-		webnotes.conn.sql("""update `tabAccount` set master_name = %s, 
-			master_type = 'Supplier' where master_name = %s""" , (new, old))
+			webnotes.conn.set(self.doc, "supplier_name", newdn)
 
 @webnotes.whitelist()
 def get_dashboard_info(supplier):
diff --git a/buying/doctype/supplier_quotation/supplier_quotation.txt b/buying/doctype/supplier_quotation/supplier_quotation.txt
index fcef822..cf62a9f 100644
--- a/buying/doctype/supplier_quotation/supplier_quotation.txt
+++ b/buying/doctype/supplier_quotation/supplier_quotation.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-21 16:16:45", 
   "docstatus": 0, 
-  "modified": "2013-11-03 14:14:12", 
+  "modified": "2013-11-22 17:16:16", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -262,7 +262,7 @@
   "oldfieldname": "net_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -366,7 +366,7 @@
   "oldfieldname": "grand_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1, 
   "report_hide": 0
  }, 
@@ -377,7 +377,7 @@
   "label": "In Words", 
   "oldfieldname": "in_words_import", 
   "oldfieldtype": "Data", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
diff --git a/patches/1311/p06_fix_report_columns.py b/patches/1311/p06_fix_report_columns.py
index 3516b38..4132f17 100644
--- a/patches/1311/p06_fix_report_columns.py
+++ b/patches/1311/p06_fix_report_columns.py
@@ -3,7 +3,6 @@
 
 from __future__ import unicode_literals
 import webnotes
-from webnotes.utils import cstr
 import json
 
 def execute():
@@ -24,12 +23,12 @@
 	for value, key in columns:
 		new_columns = []
 		column_doctype = key.split(':')[-1]
-		for child_doctype in doctypes_child_tables_map.get(column_doctype):
-			for field, field_doctype in json.loads(value):
-				if field_doctype == child_doctype:
-					new_columns.append([field, field_doctype])
+		for field, field_doctype in json.loads(value):
+			if field_doctype in doctypes_child_tables_map.get(column_doctype):
+				new_columns.append([field, field_doctype])
 
 		if new_columns:
-			defkey = "_list_settings:" + column_doctype
 			webnotes.conn.sql("""update `tabDefaultValue` set defvalue=%s 
-				where defkey=%s""" % ('%s', '%s'), (json.dumps(new_columns), defkey))
\ No newline at end of file
+				where defkey=%s""" % ('%s', '%s'), (json.dumps(new_columns), key))
+		else:
+			webnotes.conn.sql("""delete from `tabDefaultValue` where defkey=%s""", key)
\ No newline at end of file
diff --git a/patches/october_2013/p09_update_naming_series_settings.py b/patches/october_2013/p09_update_naming_series_settings.py
index 18f44dc..36632b4 100644
--- a/patches/october_2013/p09_update_naming_series_settings.py
+++ b/patches/october_2013/p09_update_naming_series_settings.py
@@ -5,6 +5,14 @@
 import webnotes
 
 def execute():
+	selling_price_list =  webnotes.conn.get_value("Selling Settings", None, "selling_price_list")
+	if selling_price_list and not webnotes.conn.exists("Price List", selling_price_list):
+		webnotes.conn.set_value("Selling Settings", None, "selling_price_list", None)
+		
+	buying_price_list =  webnotes.conn.get_value("Buying Settings", None, "buying_price_list")
+	if buying_price_list and not webnotes.conn.exists("Price List", buying_price_list):
+		webnotes.conn.set_value("Buying Settings", None, "buying_price_list", None)
+	
 	# reset property setters for series
 	for name in ("Stock Settings", "Selling Settings", "Buying Settings", "HR Settings"):
 		webnotes.bean(name, name).save()
\ No newline at end of file
diff --git a/selling/doctype/customer/customer.py b/selling/doctype/customer/customer.py
index 7e4a73a..d00926f 100644
--- a/selling/doctype/customer/customer.py
+++ b/selling/doctype/customer/customer.py
@@ -143,21 +143,13 @@
 		if self.doc.lead_name:
 			webnotes.conn.sql("update `tabLead` set status='Interested' where name=%s",self.doc.lead_name)
 			
-	def after_rename(self, old, new, merge=False):
-		#update customer_name if not naming series
+	def before_rename(self, olddn, newdn, merge=False):
+		from accounts.utils import rename_account_for
+		rename_account_for("Customer", olddn, newdn, merge)
+			
+	def after_rename(self, olddn, newdn, merge=False):
 		if webnotes.defaults.get_global_default('cust_master_name') == 'Customer Name':
-			webnotes.conn.set(self.doc, "customer_name", new)
-		
-		for account in webnotes.conn.sql("""select name, account_name from 
-			tabAccount where master_name=%s and master_type='Customer'""", old, as_dict=1):
-			if account.account_name != new:
-				merge_account = True if merge and webnotes.conn.get_value("Account", 
-					{"master_name": new, "master_type": "Customer"}) else False
-				webnotes.rename_doc("Account", account.name, new, merge=merge_account)
-
-		#update master_name in account record
-		webnotes.conn.sql("""update `tabAccount` set master_name = %s, 
-			master_type = 'Customer' where master_name = %s""", (new, old))
+			webnotes.conn.set(self.doc, "customer_name", newdn)
 
 @webnotes.whitelist()
 def get_dashboard_info(customer):
diff --git a/selling/doctype/lead/lead.txt b/selling/doctype/lead/lead.txt
index 01a3aca..6e6b61a 100644
--- a/selling/doctype/lead/lead.txt
+++ b/selling/doctype/lead/lead.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-04-10 11:45:37", 
   "docstatus": 0, 
-  "modified": "2013-11-25 11:37:00", 
+  "modified": "2013-11-25 11:38:00", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
diff --git a/stock/doctype/material_request/material_request.txt b/stock/doctype/material_request/material_request.txt
index 1330c45..c71d7d1 100644
--- a/stock/doctype/material_request/material_request.txt
+++ b/stock/doctype/material_request/material_request.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-03-07 14:48:38", 
   "docstatus": 0, 
-  "modified": "2013-11-03 15:29:49", 
+  "modified": "2013-11-03 15:30:49", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.txt b/stock/doctype/purchase_receipt/purchase_receipt.txt
index 6035b71..95e254e 100755
--- a/stock/doctype/purchase_receipt/purchase_receipt.txt
+++ b/stock/doctype/purchase_receipt/purchase_receipt.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-21 16:16:39", 
   "docstatus": 0, 
-  "modified": "2013-11-03 14:20:21", 
+  "modified": "2013-11-22 17:15:47", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -291,7 +291,7 @@
   "oldfieldname": "net_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -398,7 +398,7 @@
   "oldfieldname": "grand_total_import", 
   "oldfieldtype": "Currency", 
   "options": "currency", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
@@ -408,7 +408,7 @@
   "label": "In Words", 
   "oldfieldname": "in_words_import", 
   "oldfieldtype": "Data", 
-  "print_hide": 1, 
+  "print_hide": 0, 
   "read_only": 1
  }, 
  {
diff --git a/stock/doctype/serial_no/serial_no.py b/stock/doctype/serial_no/serial_no.py
index c7a10ed..a248cd0 100644
--- a/stock/doctype/serial_no/serial_no.py
+++ b/stock/doctype/serial_no/serial_no.py
@@ -73,23 +73,16 @@
 		self.doc.item_name = item.item_name
 		self.doc.brand = item.brand
 		self.doc.warranty_period = item.warranty_period
-				
-	def set_status(self):
-		last_sle = webnotes.conn.sql("""select * from `tabStock Ledger Entry` 
-			where (serial_no like %s or serial_no like %s or serial_no=%s) 
-			and item_code=%s and ifnull(is_cancelled, 'No')='No' 
-			order by name desc limit 1""", 
-			("%%%s%%" % (self.doc.name+"\n"), "%%%s%%" % ("\n"+self.doc.name), self.doc.name, 
-				self.doc.item_code), as_dict=1)
 		
+	def set_status(self, last_sle):
 		if last_sle:
-			if last_sle[0].voucher_type == "Stock Entry":
-				document_type = webnotes.conn.get_value("Stock Entry", last_sle[0].voucher_no, 
+			if last_sle.voucher_type == "Stock Entry":
+				document_type = webnotes.conn.get_value("Stock Entry", last_sle.voucher_no, 
 					"purpose")
 			else:
-				document_type = last_sle[0].voucher_type
+				document_type = last_sle.voucher_type
 
-			if last_sle[0].actual_qty > 0:
+			if last_sle.actual_qty > 0:
 				if document_type == "Sales Return":
 					self.doc.status = "Sales Returned"
 				else:
@@ -97,59 +90,73 @@
 			else:
 				if document_type == "Purchase Return":
 					self.doc.status = "Purchase Returned"
-				elif last_sle[0].voucher_type in ("Delivery Note", "Sales Invoice"):
+				elif last_sle.voucher_type in ("Delivery Note", "Sales Invoice"):
 					self.doc.status = "Delivered"
 				else:
 					self.doc.status = "Not Available"
 		
-	def set_purchase_details(self):
-		purchase_sle = webnotes.conn.sql("""select * from `tabStock Ledger Entry` 
-			where (serial_no like %s or serial_no like %s or serial_no=%s) 
-			and item_code=%s and actual_qty > 0 
-			and ifnull(is_cancelled, 'No')='No' order by name asc limit 1""", 
-			("%%%s%%" % (self.doc.name+"\n"), "%%%s%%" % ("\n"+self.doc.name), self.doc.name, 
-				 self.doc.item_code), as_dict=1)
-
+	def set_purchase_details(self, purchase_sle):
 		if purchase_sle:
-			self.doc.purchase_document_type = purchase_sle[0].voucher_type
-			self.doc.purchase_document_no = purchase_sle[0].voucher_no
-			self.doc.purchase_date = purchase_sle[0].posting_date
-			self.doc.purchase_time = purchase_sle[0].posting_time
-			self.doc.purchase_rate = purchase_sle[0].incoming_rate
-			if purchase_sle[0].voucher_type == "Purchase Receipt":
+			self.doc.purchase_document_type = purchase_sle.voucher_type
+			self.doc.purchase_document_no = purchase_sle.voucher_no
+			self.doc.purchase_date = purchase_sle.posting_date
+			self.doc.purchase_time = purchase_sle.posting_time
+			self.doc.purchase_rate = purchase_sle.incoming_rate
+			if purchase_sle.voucher_type == "Purchase Receipt":
 				self.doc.supplier, self.doc.supplier_name = \
-					webnotes.conn.get_value("Purchase Receipt", purchase_sle[0].voucher_no, 
+					webnotes.conn.get_value("Purchase Receipt", purchase_sle.voucher_no, 
 						["supplier", "supplier_name"])
 		else:
 			for fieldname in ("purchase_document_type", "purchase_document_no", 
 				"purchase_date", "purchase_time", "purchase_rate", "supplier", "supplier_name"):
 					self.doc.fields[fieldname] = None
 				
-	def set_sales_details(self):
-		delivery_sle = webnotes.conn.sql("""select * from `tabStock Ledger Entry` 
-			where (serial_no like %s or serial_no like %s or serial_no=%s)
-			and item_code=%s and actual_qty<0 
-			and voucher_type in ('Delivery Note', 'Sales Invoice')
-			and ifnull(is_cancelled, 'No')='No' order by name desc limit 1""", 
-			("%%%s%%" % (self.doc.name+"\n"), "%%%s%%" % ("\n"+self.doc.name), self.doc.name, 
-				 self.doc.item_code), as_dict=1)
+	def set_sales_details(self, delivery_sle):
 		if delivery_sle:
-			self.doc.delivery_document_type = delivery_sle[0].voucher_type
-			self.doc.delivery_document_no = delivery_sle[0].voucher_no
-			self.doc.delivery_date = delivery_sle[0].posting_date
-			self.doc.delivery_time = delivery_sle[0].posting_time
+			self.doc.delivery_document_type = delivery_sle.voucher_type
+			self.doc.delivery_document_no = delivery_sle.voucher_no
+			self.doc.delivery_date = delivery_sle.posting_date
+			self.doc.delivery_time = delivery_sle.posting_time
 			self.doc.customer, self.doc.customer_name = \
-				webnotes.conn.get_value(delivery_sle[0].voucher_type, delivery_sle[0].voucher_no, 
+				webnotes.conn.get_value(delivery_sle.voucher_type, delivery_sle.voucher_no, 
 					["customer", "customer_name"])
 			if self.doc.warranty_period:
-				self.doc.warranty_expiry_date	= add_days(cstr(delivery_sle[0].posting_date), 
+				self.doc.warranty_expiry_date	= add_days(cstr(delivery_sle.posting_date), 
 					cint(self.doc.warranty_period))
 		else:
 			for fieldname in ("delivery_document_type", "delivery_document_no", 
 				"delivery_date", "delivery_time", "customer", "customer_name", 
 				"warranty_expiry_date"):
-					self.doc.fields[fieldname] = None		
+					self.doc.fields[fieldname] = None
+							
+	def get_last_sle(self):
+		entries = {}
+		sle_dict = self.get_stock_ledger_entries()
+		if sle_dict.get("incoming", []):
+			entries["purchase_sle"] = sle_dict["incoming"][0]
 		
+		if len(sle_dict.get("incoming", [])) - len(sle_dict.get("outgoing", [])) > 0:
+			entries["last_sle"] = sle_dict["incoming"][0]
+		else:
+			entries["last_sle"] = sle_dict["outgoing"][0]
+			entries["delivery_sle"] = sle_dict["outgoing"][0]
+				
+		return entries
+		
+	def get_stock_ledger_entries(self):
+		sle_dict = {}
+		for sle in webnotes.conn.sql("""select * from `tabStock Ledger Entry` 
+			where serial_no like %s and item_code=%s and ifnull(is_cancelled, 'No')='No' 
+			order by posting_date desc, posting_time desc, name desc""", 
+			("%%%s%%" % self.doc.name, self.doc.item_code), as_dict=1):
+				if self.doc.name in get_serial_nos(sle.serial_no):
+					if sle.actual_qty > 0:
+						sle_dict.setdefault("incoming", []).append(sle)
+					else:
+						sle_dict.setdefault("outgoing", []).append(sle)
+					
+		return sle_dict
+					
 	def on_trash(self):
 		if self.doc.status == 'Delivered':
 			webnotes.throw(_("Delivered Serial No ") + self.doc.name + _(" can not be deleted"))
@@ -176,15 +183,10 @@
 	
 	def on_stock_ledger_entry(self):
 		if self.via_stock_ledger and not self.doc.fields.get("__islocal"):
-			self.set_status()
-			self.set_purchase_details()
-			self.set_sales_details()
-
-	def on_stock_ledger_entry(self):
-		if self.via_stock_ledger and not self.doc.fields.get("__islocal"):
-			self.set_status()
-			self.set_purchase_details()
-			self.set_sales_details()
+			last_sle = self.get_last_sle()
+			self.set_status(last_sle.get("last_sle"))
+			self.set_purchase_details(last_sle.get("purchase_sle"))
+			self.set_sales_details(last_sle.get("delivery_sle"))
 			
 	def on_communication(self):
 		return
@@ -235,12 +237,12 @@
 					# transfer out
 					webnotes.throw(_("Serial No must exist to transfer out.") + \
 						": " + serial_no, SerialNoNotExistsError)
-		elif not item_det.serial_no_series:
+		elif sle.actual_qty < 0 or not item_det.serial_no_series:
 			webnotes.throw(_("Serial Number Required for Serialized Item" + ": " 
 				+ sle.item_code), SerialNoRequiredError)
 				
 def update_serial_nos(sle, item_det):
-	if not sle.serial_no and sle.actual_qty > 0 and item_det.serial_no_series:
+	if sle.is_cancelled == "No" and not sle.serial_no and sle.actual_qty > 0 and item_det.serial_no_series:
 		from webnotes.model.doc import make_autoname
 		serial_nos = []
 		for i in xrange(cint(sle.actual_qty)):
diff --git a/stock/doctype/warehouse/warehouse.py b/stock/doctype/warehouse/warehouse.py
index 4869d39..3559960 100644
--- a/stock/doctype/warehouse/warehouse.py
+++ b/stock/doctype/warehouse/warehouse.py
@@ -73,7 +73,8 @@
 		if warehouse_account:
 			webnotes.delete_doc("Account", warehouse_account)
 				
-		if sql("""select name from `tabStock Ledger Entry` where warehouse = %s""", self.doc.name):
+		if webnotes.conn.sql("""select name from `tabStock Ledger Entry` 
+				where warehouse = %s""", self.doc.name):
 			msgprint("""Warehouse can not be deleted as stock ledger entry 
 				exists for this warehouse.""", raise_exception=1)
 			
@@ -88,7 +89,8 @@
 				
 			webnotes.conn.sql("delete from `tabBin` where warehouse=%s", olddn)
 			
-		self.rename_account(olddn, new_warehouse, merge)
+		from accounts.utils import rename_account_for
+		rename_account_for("Warehouse", olddn, new_warehouse, merge)
 
 		return new_warehouse
 
@@ -109,21 +111,4 @@
 			
 		webnotes.conn.set_default("allow_negative_stock", 
 			webnotes.conn.get_value("Stock Settings", None, "allow_negative_stock"))
-		webnotes.conn.auto_commit_on_many_writes = 0
-			
-	def rename_account(self, olddn, newdn, merge):
-		old_account = webnotes.conn.get_value("Account", 
-			{"account_type": "Warehouse", "master_name": olddn})
-		if old_account:
-			new_account = None
-			if not merge:
-				if old_account == olddn:
-					new_account = webnotes.rename_doc("Account", olddn, newdn)
-			else:
-				existing_new_account = webnotes.conn.get_value("Account", 
-					{"account_type": "Warehouse", "master_name": newdn})
-				new_account = webnotes.rename_doc("Account", old_account, 
-					existing_new_account or newdn, merge=True if existing_new_account else False)
-
-			if new_account:
-				webnotes.conn.set_value("Account", new_account, "master_name", newdn)
\ No newline at end of file
+		webnotes.conn.auto_commit_on_many_writes = 0
\ No newline at end of file