Merge branch 'stable' into live
diff --git a/accounts/doctype/account/account.js b/accounts/doctype/account/account.js
index 071bf57..51cacda 100644
--- a/accounts/doctype/account/account.js
+++ b/accounts/doctype/account/account.js
@@ -72,16 +72,6 @@
   else alert("Please select master type");
 }
 
-/*
-// Get customer/supplier address
-// -----------------------------------------
-cur_frm.cscript.master_name = function(doc,cdt,cdn){
-  if(doc.master_name){
-    get_server_fields('get_address','','',doc,cdt,cdn);
-  }
-}
-*/
-
 // parent account get query
 // -----------------------------------------
 cur_frm.fields_dict['parent_account'].get_query = function(doc){
diff --git a/accounts/doctype/account/account.py b/accounts/doctype/account/account.py
index 52c66a9..6c8003a 100644
--- a/accounts/doctype/account/account.py
+++ b/accounts/doctype/account/account.py
@@ -31,7 +31,7 @@
 	def get_address(self):		
 		add=sql("Select address from `tab%s` where name='%s'"%(self.doc.master_type,self.doc.master_name))
 		ret={'address':add[0][0]}
-		return cstr(ret)
+		return ret
 
 
 	# check whether master name entered for supplier/customer
diff --git a/accounts/doctype/cost_center/cost_center.py b/accounts/doctype/cost_center/cost_center.py
index 060225d..521712b 100644
--- a/accounts/doctype/cost_center/cost_center.py
+++ b/accounts/doctype/cost_center/cost_center.py
@@ -31,7 +31,7 @@
     ret = {
       'company_abbr'  : abbr
     }
-    return cstr(ret)
+    return ret
 
   def validate(self): 
     # Cost Center name must be unique
diff --git a/accounts/doctype/form_16a/form_16a.py b/accounts/doctype/form_16a/form_16a.py
index 292c52a..018b834 100644
--- a/accounts/doctype/form_16a/form_16a.py
+++ b/accounts/doctype/form_16a/form_16a.py
@@ -39,7 +39,7 @@
 				'company_address': cstr(comp_det[0][0]),
 				'registration_details': cstr(comp_det[0][1])
 			}	 
-		return cstr(ret)		
+		return ret
     
 	# Get party details
 	#------------------
@@ -56,7 +56,7 @@
 			'party_address': cstr(address_display)
 		}
           	
-		return cstr(ret)
+		return ret
 	
 	# Get TDS Return acknowledgement
 	#-------------------------------
diff --git a/accounts/doctype/journal_voucher/journal_voucher.py b/accounts/doctype/journal_voucher/journal_voucher.py
index 4f5e67a..5942ca1 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.py
+++ b/accounts/doctype/journal_voucher/journal_voucher.py
@@ -38,9 +38,9 @@
     args = eval(args)
     o_s = sql("select outstanding_amount from `tab%s` where name = '%s'" % (args['doctype'],args['docname']))
     if args['doctype'] == 'Payable Voucher':
-      return cstr({'debit': o_s and flt(o_s[0][0]) or 0})
+      return {'debit': o_s and flt(o_s[0][0]) or 0}
     if args['doctype'] == 'Receivable Voucher':
-      return cstr({'credit': o_s and flt(o_s[0][0]) or 0})
+      return {'credit': o_s and flt(o_s[0][0]) or 0}
 
   #--------------------------------------------------------------------------------------------------------
   # Create remarks
diff --git a/accounts/doctype/ledger_balance_export/ledger_balance_export.py b/accounts/doctype/ledger_balance_export/ledger_balance_export.py
index d6cfc7b..e9a9505 100755
--- a/accounts/doctype/ledger_balance_export/ledger_balance_export.py
+++ b/accounts/doctype/ledger_balance_export/ledger_balance_export.py
@@ -36,7 +36,7 @@
 		# result initiatlization
 		header = 'Ledger Balances Between ' + getdate(self.doc.from_date).strftime('%d-%m-%Y') + ' and ' + getdate(self.doc.to_date).strftime('%d-%m-%Y')
 		res = [[header], ['Account', 'Posting Date', 'Voucher Type', 'Voucher No', 'Debit', 'Credit', 'Remarks']]
-		glc = get_obj('GL Control')	
+		glc = get_obj('GL Control')
 
 		for d in getlist(self.doclist, 'ledger_details'):
 			# Fetch acc details
@@ -59,5 +59,5 @@
 			res.append(['', '', '', 'Total Debit/Credit', debit, credit])
 			res.append(['', '', '', 'Opening Balance', opening])
 			res.append(['', '', '', 'Closing Balance', closing])
-			
+
 		return res
diff --git a/accounts/doctype/loan/loan.js b/accounts/doctype/loan/loan.js
index 1851a84..5a45362 100644
--- a/accounts/doctype/loan/loan.js
+++ b/accounts/doctype/loan/loan.js
@@ -19,9 +19,9 @@
 	},
 	hide_show_buttons: function(doc) {
 		if(doc.docstatus==0) {
-			hide_field('Installment Reciept'); show_field('Generate');
+			hide_field('Installment Reciept'); unhide_field('Generate');
 		} else if (doc.docstatus==1) {
-			show_field('Installment Reciept');hide_field('Generate');
+			unhide_field('Installment Reciept');hide_field('Generate');
 		}
 	},
 	clear_installments: function(doc) {
diff --git a/accounts/doctype/payable_voucher/payable_voucher.py b/accounts/doctype/payable_voucher/payable_voucher.py
index 0e930e3..d7f628f 100644
--- a/accounts/doctype/payable_voucher/payable_voucher.py
+++ b/accounts/doctype/payable_voucher/payable_voucher.py
@@ -48,14 +48,14 @@
 				ret['due_date'] = add_days(cstr(self.doc.posting_date), acc_head and cint(acc_head[0][1]) or 0)
 		elif not acc_head:
 			msgprint("%s does not have an Account Head in %s. You must first create it from the Supplier Master" % (self.doc.supplier, self.doc.company))
-		return cstr(ret)
+		return ret
 		
 	def get_cust(self):
 		ret = {}
 		if self.doc.credit_to:			
 			ret['supplier'] = get_value('Account',self.doc.credit_to,'master_name')
 			
-		return cstr(ret)	
+		return ret
 
 
 	# Get Default Cost Center and Expense Head from Item Master
@@ -70,7 +70,7 @@
 			if not args['cost_center'] or args['cost_center'] == 'undefined':
 				cost_center = sql("select cost_center from `tabItem` where name = '%s'" % args['item_code'])
 				ret['cost_center'] = cost_center and cost_center[0][0] or ''
-		return cstr(ret)
+		return ret
 		 
 	
 	# Get Items based on PO or PR
@@ -115,7 +115,7 @@
 			'cost_center' : item_det and item_det[0]['cost_center'] or '',
 			'item_tax_rate'			: str(t)
 		}
-		return cstr(ret)
+		return ret
 		
 	# Advance Allocation
 	# -------------------
@@ -139,7 +139,7 @@
 	def get_rate1(self,acc):
 		rate = sql("select tax_rate from `tabAccount` where name='%s'"%(acc))
 		ret={'add_tax_rate' :rate and flt(rate[0][0]) or 0 }
-		return cstr(ret)
+		return ret
 	
 
 # *************************** Server Utility Functions *****************************
@@ -345,7 +345,7 @@
 	# get tds rate
 	# -------------
 	def get_tds_rate(self):
-		return str({'rate' : flt(get_value('Account', self.doc.tax_code, 'tax_rate'))})
+		return {'rate' : flt(get_value('Account', self.doc.tax_code, 'tax_rate'))}
 
 	# set aging date
 	#-------------------
diff --git a/accounts/doctype/receivable_voucher/receivable_voucher.py b/accounts/doctype/receivable_voucher/receivable_voucher.py
index cb62a65..0aaebbb 100644
--- a/accounts/doctype/receivable_voucher/receivable_voucher.py
+++ b/accounts/doctype/receivable_voucher/receivable_voucher.py
@@ -90,7 +90,7 @@
 	def get_debit_to(self):
 		acc_head = self.get_customer_account()
 		if acc_head:
-			return cstr({ 'debit_to' : acc_head })
+			return { 'debit_to' : acc_head }
 
 
 	# Set Due Date = Posting Date + Credit Days
@@ -162,7 +162,7 @@
 			if ret['warehouse']:
 				actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse']))		
 				ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0
-		return str(ret)
+		return ret
  
 
 	# Get tax rate if account type is tax
@@ -515,7 +515,7 @@
 		ret = {
 			 'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
 		}
-		return cstr(ret)
+		return ret
 
 	# Make GL Entries
 	# -------------------------
diff --git a/accounts/doctype/tds_payment/tds_payment.py b/accounts/doctype/tds_payment/tds_payment.py
index c91a269..5079d04 100644
--- a/accounts/doctype/tds_payment/tds_payment.py
+++ b/accounts/doctype/tds_payment/tds_payment.py
@@ -34,7 +34,7 @@
     else:
       ret = { 'registration_details': cstr(comp_det[0][0])}
    
-    return cstr(ret)
+    return ret
 
   # Get default bank and tds account
   #------------------------------------
diff --git a/buying/doctype/indent/indent.py b/buying/doctype/indent/indent.py
index 450ea64..882098f 100644
--- a/buying/doctype/indent/indent.py
+++ b/buying/doctype/indent/indent.py
@@ -90,12 +90,12 @@
 	# get item details
 	# ---------------------------------
 	def get_item_details(self, arg =''):
-		return cstr( get_obj(dt='Purchase Common').get_item_details(self,arg) )
+		return get_obj(dt='Purchase Common').get_item_details(self,arg)
 
 	# Get UOM Details
 	# ---------------------------------
 	def get_uom_details(self, arg = ''):
-		return cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
+		return get_obj(dt='Purchase Common').get_uom_details(arg)
 
 	# GET TERMS & CONDITIONS
 	#-----------------------------
diff --git a/buying/doctype/purchase_common/purchase_common.py b/buying/doctype/purchase_common/purchase_common.py
index fe8c8e6..29658cb 100644
--- a/buying/doctype/purchase_common/purchase_common.py
+++ b/buying/doctype/purchase_common/purchase_common.py
@@ -84,7 +84,7 @@
 			# ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
 			contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where supplier = '%s' and is_supplier = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
 			ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
-			return cstr(ret)
+			return ret
 		else:
 			msgprint("Supplier : %s does not exists" % (name))
 			raise Exception
@@ -142,14 +142,14 @@
 			ret['purchase_rate'] = item and flt(item[0]['last_purchase_rate']) or 0
 			ret['import_rate'] = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(obj.doc.fields.has_key('conversion_rate') and flt(obj.doc.conversion_rate) or 1)
 		
-		return cstr(ret)
+		return ret
 
 	# Get Available Qty at Warehouse
 	def get_bin_details( self, arg = ''):
 		arg = eval(arg)
 		bin = sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (arg['item_code'], arg['warehouse']), as_dict=1)
 		ret = { 'projected_qty' : bin and flt(bin[0]['projected_qty']) or 0 }
-		return str(ret)
+		return ret
 
 	# Get UOM Details
 	def get_uom_details(self, arg = ''):
@@ -163,7 +163,7 @@
 				'purchase_rate'		 : (lpr and flt(lpr[0]['last_purchase_rate']) * flt(uom[0]['conversion_factor'])) or 0
 			}
 		
-		return str(ret)
+		return ret
 
 	# get last purchase rate
 	def get_last_purchase_rate( self, obj):
@@ -522,7 +522,7 @@
 				'rate'	:	rate and (rate[0]['account_type'] == 'Tax' and not arg['charge_type'] == 'Actual') and flt(rate[0]['tax_rate']) or 0
 		}
 		#msgprint(ret)
-		return cstr(ret)
+		return ret
 
 
 				
diff --git a/buying/doctype/purchase_order/purchase_order.py b/buying/doctype/purchase_order/purchase_order.py
index 7d9e1da..1a5d2d7 100644
--- a/buying/doctype/purchase_order/purchase_order.py
+++ b/buying/doctype/purchase_order/purchase_order.py
@@ -38,23 +38,17 @@
     get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date')
 
 
-  # Client Trigger Functions
-  #----------------------------------------------------------------------------------------------------
-  # Get Supplier Details 
-  #def get_supplier_details(self, name = ''):
-    #return cstr(get_obj(dt='Purchase Common').get_supplier_details(name))
-
   # Get Item Details
   def get_item_details(self, arg =''):
-    return cstr(get_obj(dt='Purchase Common').get_item_details(self,arg))
+    return get_obj(dt='Purchase Common').get_item_details(self,arg)
 
   # Get UOM Details
   def get_uom_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
+    return get_obj(dt='Purchase Common').get_uom_details(arg)
 
   # get available qty at warehouse
   def get_bin_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_bin_details(arg))
+    return get_obj(dt='Purchase Common').get_bin_details(arg)
 
   # Pull Indent
   def get_indent_details(self):
diff --git a/buying/doctype/supplier_quotation/supplier_quotation.py b/buying/doctype/supplier_quotation/supplier_quotation.py
index 0c659bc..ac59430 100755
--- a/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -18,7 +18,7 @@
       'supplier_name'   : cd and cd[0][4] or '',
       'supplier_address': cd and cd[0][5] or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_rfq_details(self):
     self.doc.clear_table(self.doclist, 'supplier_quotation_details')
@@ -28,12 +28,12 @@
   def update_approval_status(self):
     if not self.doc.approval_status or self.doc.approval_status == 'Not Approved':
       set(self.doc, 'approval_status','Approved')
-      return cstr(self.doc.approval_status)
+      return self.doc.approval_status
     elif self.doc.approval_status == 'Approved':
       pc_obj = get_obj('Purchase Common')
       pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Order', docname = self.doc.name, detail_doctype = 'PO Detail')
       set(self.doc, 'approval_status', 'Not Approved')
-      return cstr(self.doc.approval_status)
+      return self.doc.approval_status
   
   def validate_item_list(self):
     if not getlist(self.doclist, 'supplier_quotation_details'):
@@ -101,4 +101,4 @@
   # Get Supplier Details
   # --------------------
   def get_supplier_details(self, name = ''):
-    return cstr(get_obj('Purchase Common').get_supplier_details(name))
\ No newline at end of file
+    return get_obj('Purchase Common').get_supplier_details(name)
\ No newline at end of file
diff --git a/hr/doctype/appraisal/appraisal.py b/hr/doctype/appraisal/appraisal.py
index 1731559..e13f9f3 100644
--- a/hr/doctype/appraisal/appraisal.py
+++ b/hr/doctype/appraisal/appraisal.py
@@ -26,7 +26,7 @@
     emp_nm = sql("select employee_name from `tabEmployee` where name=%s", self.doc.employee)
     emp_nm= emp_nm and emp_nm[0][0] or ''
     self.doc.employee_name = emp_nm
-    return cstr(emp_nm)
+    return emp_nm
   
   def fetch_kra(self):
     if not self.doc.kra_template:
@@ -88,7 +88,7 @@
       if d.score:
         total = total + flt(d.score_earned)
     ret={'total_score':flt(total)}
-    return cstr(ret)
+    return ret
   
   def declare_completed(self):
     ret={}
diff --git a/hr/doctype/attendance/attendance.py b/hr/doctype/attendance/attendance.py
index d64a8e3..3c687ef 100644
--- a/hr/doctype/attendance/attendance.py
+++ b/hr/doctype/attendance/attendance.py
@@ -34,7 +34,7 @@
     set(self.doc, 'employee_name', emp_nm and emp_nm[0][0] or '')
 
     ret = { 'employee_name' : emp_nm and emp_nm[0][0] or ''}
-    return str(ret)
+    return ret
   
   #validation for duplicate record
   def validate_duplicate_record(self):   
diff --git a/hr/doctype/employee/employee.py b/hr/doctype/employee/employee.py
index 54142db..01ff32d 100644
--- a/hr/doctype/employee/employee.py
+++ b/hr/doctype/employee/employee.py
@@ -41,7 +41,7 @@
     if self.doc.date_of_birth:
       dt = getdate(self.doc.date_of_birth) + datetime.timedelta(21915)
       ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
-    return str(ret)
+    return ret
 
   # check if salary structure exists
   #========================================================================================================
diff --git a/hr/doctype/leave_allocation/leave_allocation.py b/hr/doctype/leave_allocation/leave_allocation.py
index e11a335..46f7809 100755
--- a/hr/doctype/leave_allocation/leave_allocation.py
+++ b/hr/doctype/leave_allocation/leave_allocation.py
@@ -66,7 +66,7 @@
       'carry_forwarded_leaves'  :  prev_bal,
       'total_leaves_allocated'   :  flt(prev_bal) + flt(self.doc.new_leaves_allocated)
     }
-    return str(ret)
+    return ret
 
 
 # ********************************************** validate *****************************************************
diff --git a/hr/doctype/leave_application/leave_application.js b/hr/doctype/leave_application/leave_application.js
index 9fc1e42..1eda69f 100755
--- a/hr/doctype/leave_application/leave_application.js
+++ b/hr/doctype/leave_application/leave_application.js
@@ -56,9 +56,6 @@
     msgprint("To Date should be same as From Date for Half Day leave");
     set_multiple(dt,dn,{to_date:doc.from_date});    
   }
-  if(cint(doc.half_day) == 1){
-    
-  }
   calculate_total_days(doc, dt, dn);
 }
 
diff --git a/hr/doctype/leave_application/leave_application.py b/hr/doctype/leave_application/leave_application.py
index 5f69c63..01bf7fe 100755
--- a/hr/doctype/leave_application/leave_application.py
+++ b/hr/doctype/leave_application/leave_application.py
@@ -33,7 +33,7 @@
     leave_app = sql("select total_leave_days from `tabLeave Application` where employee = '%s' and leave_type = '%s' and fiscal_year = '%s' and docstatus = 1" % (self.doc.employee, self.doc.leave_type, self.doc.fiscal_year))
     leave_app = leave_app and flt(leave_app[0][0]) or 0
     ret = {'leave_balance':leave_all - leave_app}
-    return str(ret)
+    return ret
 
 
 # ************************************************ utilities *************************************************
@@ -55,7 +55,7 @@
     tot_days = date_diff(self.doc.to_date, self.doc.from_date) + 1
     holidays = self.get_holidays()
     ret = {'total_leave_days':flt(tot_days)-flt(holidays)}
-    return str(ret)
+    return ret
 
 
 # ************************************************ validate *************************************************
diff --git a/hr/doctype/salary_structure/salary_structure.py b/hr/doctype/salary_structure/salary_structure.py
index fd295ea..36a1855 100644
--- a/hr/doctype/salary_structure/salary_structure.py
+++ b/hr/doctype/salary_structure/salary_structure.py
@@ -42,7 +42,7 @@
         'grade'          : cstr(det[0][4]),
         'backup_employee': cstr(self.doc.employee)
       }
-    return cstr(ret)
+    return ret
     
 
   # Set Salary structure field values
@@ -53,7 +53,7 @@
             'bank_ac_no'  : basic_info and basic_info[0][1] or '',
             'esic_no'     : basic_info and basic_info[0][2] or '',
             'pf_no'       : basic_info and basic_info[0][3] or ''}
-    return cstr(ret)
+    return ret
    
   # Make earning and deduction table    
   #---------------------------------------------------------
diff --git a/patches/patch.py b/patches/patch.py
index 22f0101..1568469 100644
--- a/patches/patch.py
+++ b/patches/patch.py
@@ -1,7 +1,7 @@
 # REMEMBER to update this
 # ========================
 
-last_patch = 338
+last_patch = 339
 
 #-------------------------------------------
 
@@ -1345,7 +1345,7 @@
 		sql("update `tabDocField` set permlevel=1, hidden = 1 where parent = 'Bulk Rename Tool' and fieldname = 'file_list'")
 	elif patch_no == 333:
 		sql("update `tabDocPerm` set `create`  =1 where role = 'Accounts Manager' and parent = 'Lease Agreement'")
-		
+
 		p = get_obj('Patch Util')
 		p.add_permission('DocType Mapper', 'System Manager', 0, read = 1, write=1, create=1)
 		p.add_permission('Role', 'System Manager', 0, read = 1, write=1, create=1)
@@ -1358,7 +1358,7 @@
 	elif patch_no == 336:
 		reload_doc('server_tools','page','billing')
 	elif patch_no == 337:
-		item_list = webnotes.conn.sql("""SELECT name, description_html 
+		item_list = webnotes.conn.sql("""SELECT name, description_html
 									FROM tabItem""")
 		if item_list:
 			for item, html in item_list:
@@ -1366,7 +1366,7 @@
 					ac_id = webnotes.conn.sql("""SELECT value FROM `tabSingles` WHERE doctype='Control Panel' AND field='account_id'""")
 					sp_acx = html.split("acx=")
 					l_acx = len(sp_acx)
-					if l_acx > 1: 
+					if l_acx > 1:
 						for i in range(l_acx-1):
 							sp_quot = sp_acx[i+1].split('"')
 							if len(sp_quot) > 1: sp_quot[0] = str(ac_id[0][0])
@@ -1374,6 +1374,36 @@
 					html = "acx=".join(sp_acx)
 					webnotes.conn.sql("""UPDATE tabItem SET description_html=%s WHERE name=%s""", (html, item))
 	elif patch_no == 338:
+		# Patch for billing status based on amount
+		# reload so and dn
+		reload_doc('selling','doctype','sales_order')
+		reload_doc('stock','doctype','delivery_note')
+
+		# delete billed_qty field
+		sql("delete from `tabDocField` where fieldname = 'billed_qty' and parent in ('Sales Order Detail', 'Delivery Note Detail')")
+
+		# update billed amt in item table in so and dn
+		sql("""	update `tabSales Order Detail` so
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `so_detail`= so.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		sql(""" update `tabDelivery Note Detail` dn
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `dn_detail`= dn.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		# calculate % billed based on item table
+		sql("""	update `tabSales Order` so
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabSales Order Detail` where parent = so.name), modified = now()""")
+
+		sql("""	update `tabDelivery Note` dn
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabDelivery Note Detail` where parent = dn.name), modified = now()""")
+
+		# update billing status based on % billed
+		sql("""update `tabSales Order` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+		sql("""update `tabDelivery Note` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+
 		# update name of questions page
 		sql("update tabPage set name='questions' where name='Questions'")
-		sql("update tabPage set name='question-view' where name='Question View'")	
+		sql("update tabPage set name='question-view' where name='Question View'")
+	elif patch_no == 339:
+		reload_doc('production','doctype','bill_of_materials')
diff --git a/production/doctype/bill_of_materials/bill_of_materials.js b/production/doctype/bill_of_materials/bill_of_materials.js
index ede959f..d458d27 100644
--- a/production/doctype/bill_of_materials/bill_of_materials.js
+++ b/production/doctype/bill_of_materials/bill_of_materials.js
@@ -1,20 +1,22 @@
-$import(Production Tips Common)
+//$import(Production Tips Common)
 
 // ONLOAD
 cur_frm.cscript.onload = function(doc,cdt,cdn){
 
-   
+
 }
 
 // On REFRESH
 cur_frm.cscript.refresh = function(doc,cdt,cdn){
 
-   
+
 
   // Hide - Un Hide Buttons
   if (!doc.is_default && doc.__islocal!=1) unhide_field('Set as Default BOM');
   else hide_field('Set as Default BOM');
-  
+  if (doc.is_default && doc.__islocal!=1) unhide_field('Unset as Default BOM');
+  else hide_field('Unset as Default BOM');
+
   if(doc.__islocal!=1){
     set_field_permlevel('item',1);
   }
@@ -76,9 +78,20 @@
   if (check) {
     $c('runserverobj', args={'method':'set_as_default_bom', 'docs': compress_doclist([doc])}, function(r,rt) {
     refresh_field('is_default');
-    hide_field('Set as Default BOM');
+    hide_field('Set as Default BOM');unhide_field('Unset as Default BOM');
     refresh_field('Set as Default BOM');
-    });	
+    });
+  }
+}
+
+cur_frm.cscript['Unset as Default BOM'] = function(doc,cdt,cdn) {
+  var check = confirm("Do you Really want to Unset BOM " + doc.name + " as default for Item " + doc.item);
+  if (check) {
+    $c('runserverobj', args={'method':'unset_as_default_bom', 'docs': compress_doclist([doc])}, function(r,rt) {
+    refresh_field('is_default');
+    hide_field('Unset as Default BOM');unhide_field('Set as Default BOM');
+    refresh_field('Unset as Default BOM');
+    });
   }
 }
 
@@ -88,16 +101,23 @@
   if (check) {
     $c('runserverobj', args={'method':'activate_inactivate_bom', 'arg': 'Activate', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
       cur_frm.refresh();
-    });	
+    });
   }
 }
 
+cur_frm.cscript['Test Flat BOM'] = function(doc,cdt,cdn) {
+
+    $c('runserverobj', args={'method':'get_current_flat_bom_items', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+      cur_frm.refresh();
+    });
+}
+
 cur_frm.cscript['Inactivate BOM'] = function(doc,cdt,cdn) {
   var check = confirm("DO YOU REALLY WANT TO INACTIVATE BOM : " + doc.name);
 
   if (check) {
     $c('runserverobj', args={'method':'activate_inactivate_bom', 'arg': 'Inactivate', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
       cur_frm.refresh();
-    });	
+    });
   }
 }
\ No newline at end of file
diff --git a/production/doctype/bill_of_materials/bill_of_materials.py b/production/doctype/bill_of_materials/bill_of_materials.py
index f8f8e30..d287d2f 100644
--- a/production/doctype/bill_of_materials/bill_of_materials.py
+++ b/production/doctype/bill_of_materials/bill_of_materials.py
@@ -13,7 +13,7 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-	
+
 # -----------------------------------------------------------------------------------------
 
 
@@ -21,14 +21,14 @@
   def __init__(self, doc, doclist=[]):
     self.doc = doc
     self.doclist = doclist
-    
+
   def autoname(self):
     last_name = sql("select max(name) from `tabBill Of Materials` where name like 'BOM/%s/%%'" % self.doc.item)
     if last_name:
       idx = cint(cstr(last_name[0][0]).split('/')[-1]) + 1
     else:
       idx = 1
-    self.doc.name = 'BOM/' + self.doc.item + ('/%.3i' % idx) 
+    self.doc.name = 'BOM/' + self.doc.item + ('/%.3i' % idx)
 
   #----------- Client Trigger function ----------
   def get_item_detail(self, item_code):
@@ -36,7 +36,7 @@
     ret={
       'description'   : item and item[0]['description'] or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_workstation_details(self,workstation):
     ws = sql("select hour_rate, capacity from `tabWorkstation` where name = %s",workstation , as_dict = 1)
@@ -44,7 +44,7 @@
       'hour_rate'            : ws and flt(ws[0]['hour_rate']) or '',
       'workstation_capacity' : ws and flt(ws[0]['capacity']) or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_bom_material_detail(self, arg):
     arg = eval(arg)
@@ -53,15 +53,15 @@
       raise Exception
     if arg['item_code']:
       item = sql("select is_asset_item, is_purchase_item, docstatus, is_sub_contracted_item, description, stock_uom, default_bom from `tabItem` where item_code = %s", (arg['item_code']), as_dict = 1)
-      
+
       # Check for Asset Item
       if item and item[0]['is_asset_item'] == 'Yes':
         msgprint("Sorry!!! Item " + arg['item_code'] + " is an Asset of the company. Entered in BOM := " + cstr(self.doc.name))
         raise Exception
-        
+
       if item and item[0]['docstatus'] == 2:
         msgprint("Item %s does not exist in system" % cstr(args['item_code']))
- 
+
       ret_item = {
                  'description' : item and item[0]['description'] or '',
                  'stock_uom'   : item and item[0]['stock_uom'] or '',
@@ -78,15 +78,15 @@
     if arg['bom_no'] or not ret_item['bom_no'] =='':
       if arg['bom_no']:
         bom = sql("select name, dir_mat_as_per_mar,dir_mat_as_per_lpr,dir_mat_as_per_sr, operating_cost, quantity from `tabBill Of Materials` where is_active = 'Yes' and name = %s", (arg['bom_no']), as_dict=1)
-      else:      
-        # get recent direct material cost, operating_cost, cost from Default BOM of Item 
+      else:
+        # get recent direct material cost, operating_cost, cost from Default BOM of Item
         bom = sql("select name, dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, operating_cost, quantity from `tabBill Of Materials` where is_active = 'Yes' and name = %s", (ret_item['bom_no']), as_dict=1)
-      
-      # get recent direct material cost, operating_cost, cost from Entered BOM of Item 
+
+      # get recent direct material cost, operating_cost, cost from Entered BOM of Item
       ret_item['bom_no'] = bom and bom[0]['name'] or ''
 
       if bom and bom[0]['name']:
-        ret_bom = { 
+        ret_bom = {
         'dir_mat_as_per_mar' : flt(bom[0]['dir_mat_as_per_mar']) / flt(bom[0]['quantity']) or 0.00,
         'dir_mat_as_per_lpr' : flt(bom[0]['dir_mat_as_per_lpr']) / flt(bom[0]['quantity']) or 0.00,
         'dir_mat_as_per_sr'  : flt(bom[0]['dir_mat_as_per_sr']) / flt(bom[0]['quantity']) or 0.00,
@@ -106,15 +106,15 @@
             'standard_rate'      : 0
             }
           ret_item.update(ret_bom_rates)
-    return cstr(ret_item)
-  
+    return ret_item
+
   def set_as_default_bom(self):
     # set Is Default as 1
     set(self.doc,'is_default', flt(1))
 
     # get previous default bom from Item Master
     prev_def_bom = sql("select default_bom from `tabItem` where name = %s", self.doc.item,as_dict = 1)
-    
+
     if prev_def_bom[0]['default_bom'] and prev_def_bom[0]['default_bom'] != self.doc.name:
       # update Is Default as 0 in Previous Default BOM
       msgprint(cstr(prev_def_bom[0]['default_bom']) + "is no longer Default BOM for item" + cstr(self.doc.item))
@@ -124,12 +124,20 @@
     sql("update `tabItem` set default_bom = '%s' where name = '%s'" % (self.doc.name,self.doc.item))
     msgprint(cstr(self.doc.name) + "has been set as Default BOM for Item "+cstr(self.doc.item))
 
+  def unset_as_default_bom(self):
+    # set Is Default as 1
+    set(self.doc,'is_default', flt(0))
+
+    # update current BOM as default bom in Item Master
+    sql("update `tabItem` set default_bom = null where name = '%s'" % (self.doc.item))
+    msgprint(cstr(self.doc.name) + "has been unset as Default BOM for Item "+cstr(self.doc.item))
+
   def check_active_parent_boms(self):
     act_pbom = sql("select distinct t1.parent from `tabBOM Material` t1, `tabBill Of Materials` t2 where t1.bom_no ='%s' and t2.name = t1.parent and t2.is_active = 'Yes' and t2.docstatus = 1 and t1.docstatus =1 " % self.doc.name )
     if act_pbom and act_pbom[0][0]:
       msgprint("Sorry cannot Inactivate as BOM %s is child of one or many other active parent BOMs" % self.doc.name)
       raise Exception
-      
+
   def activate_inactivate_bom(self, action):
     if cstr(action) == 'Activate':
       self.validate()
@@ -141,11 +149,11 @@
   #------ On Validation Of Document ----------
   def validate_main_item(self):
     item = sql("select is_manufactured_item, is_sub_contracted_item from `tabItem` where name = %s and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life >  now())", self.doc.item, as_dict = 1)
-    
+
     if not item:
       msgprint("Item %s do not exists in the system. Entered in BOM := %s" % (cstr(self.doc.item), cstr(self.doc.name)))
       raise Exception
-      
+
     elif not item[0]['is_manufactured_item'] == 'Yes' and not item[0]['is_sub_contracted_item'] == 'Yes':
       msgprint("Sorry cannot make Bill Of Materials for Item %s. As it is not a manufactured / sub-contracted item. Entered in BOM := %s " % (cstr(self.doc.item), cstr(self.doc.name)))
       raise Exception
@@ -156,7 +164,7 @@
     if not o.operation_no:
       msgprint("Please Enter Operation No at Row " + cstr(o.idx)+" in BOM := " +cstr(self.doc.name))
       raise Exception
-      
+
     if not o.workstation:
       msgprint("Please Enter Workstation for Operation No. " + cstr(o.operation_no) + " in BOM NO. " + self.doc.name)
       raise Exception
@@ -172,7 +180,7 @@
 
       # add operation in op list
     self.op.append(cstr(o.operation_no))
- 
+
   # Validate materials
   #-------------------------------------------------
 
@@ -196,7 +204,7 @@
     if not item:
       msgprint("Item %s is not present in Item Master." % m.item_code)
       raise Exception
-      
+
     if item[0]['is_manufactured_item'] == 'Yes' or item[0]['is_sub_contracted_item'] == 'Yes':
       bom = sql("select name, is_active, docstatus from `tabBill Of Materials` where item = %s", m.item_code, as_dict =1)
       if bom and bom[0]['name']:
@@ -209,17 +217,17 @@
             if cstr(m.bom_no) == cstr(b['name']):
               if b['is_active'] != 'Yes':
                 msgprint("BOM %s NOT ACTIVE BOM. Entered in BOM := %s at row no := %s" % (cstr(m.bom_no), cstr(self.doc.name), m.idx))
-                raise Exception  
-              
+                raise Exception
+
               #if flt(b['docstatus']) != 1:
               #  msgprint("BOM %s is NOT SUBMITTED."% cstr(m.bom_no))
               #  raise Exception
-              
+
               match = 1
           if not match:
             msgprint("Item %s does not belongs to Bill Of Material %s or Bill Of Material %s is NOT ACTIVE BOM. Entered in BOM := %s at row no := %s" % (cstr(m.item_code),cstr(m.bom_no), cstr(m.bom_no), self.doc.name, m.idx))
             raise Exception
-    
+
     if not item[0]['is_manufactured_item'] == 'Yes' and not item[0]['is_sub_contracted_item']== 'Yes':
       if m.bom_no:
         msgprint("As in Item Master of Item %s Is Manufactured Item / Is Sub-Contracted Item  is not 'Yes' hence there should be no BOM.In BOm := %s at row no := %s" % (m.item_code, cstr(self.doc.name), m.idx))
@@ -235,22 +243,23 @@
 
   # Calculate Cost
   #-----------------------------------------------
-    
+
   def calculate_cost(self, validate = 0):
     self.op, op_cost, dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, count_mat = [], 0.0, 0.0,0.0,0.0, 0
     # --------  Calculate Cost Of BOM  -------------
     # --- calculate operating cost from BOM Operations ----
     for o in getlist(self.doclist, 'bom_operations'):
-      # --- Validation for enteries in BOM Operations ---- 
+      # --- Validation for enteries in BOM Operations ----
       if validate:
         self.validate_operations(o)
-        
+
       o.operating_cost = flt(flt(o.time_in_mins)/60) * flt(o.hour_rate)
       if validate != 1:
         o.save()
+        msgprint('Operation saved')
 
       op_cost = flt(op_cost) + flt(o.operating_cost)
-    
+
     # --- calculate operating cost and direct material cost from BOM Material ---
     for m in getlist(self.doclist, 'bom_materials'):
       # --- Validation for enteries in BOM Material --- '''
@@ -259,12 +268,12 @@
         self.validate_materials(m)
 
       if m.bom_no:
-        # add operating cost of child boms 
+        # add operating cost of child boms
         op_cost += flt(m.operating_cost)
-        
+
         # update dir_mat, op_cost, value from child bom
         self.update_childs_dir_op_value(m, child_bom_cost = 1)
-        
+
         # check for is_sub_contracted_item
         item = sql("select is_sub_contracted_item from `tabItem` where name = '%s'" % m.item_code, as_dict =1)
         if item and item[0]['is_sub_contracted_item'] == 'Yes':
@@ -275,13 +284,13 @@
           # calculate Direct Material
           dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr = self.calculate_dir_mat(m, dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, has_bom = 1, is_sub_cont =1)
         else:
-          # update mar,lpr,sr as 0 
+          # update mar,lpr,sr as 0
           self.update_mar_lpr_sr( m, mar = 0, lpr = 0, sr = 0)
           # calculate amount
           self.calculate_amount( m, has_bom = 1, is_sub_cont = 0)
           # calculate Direct Material
           dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr = self.calculate_dir_mat(m, dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, has_bom = 1, is_sub_cont =0)
-   
+
       else :
         # update dir_mat,op_cost, value as 0
         self.update_childs_dir_op_value(m, child_bom_cost = 0)
@@ -291,7 +300,7 @@
         self.calculate_amount(m, has_bom = 0, is_sub_cont = 0)
         # calculate Direct Material
         dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr = self.calculate_dir_mat(m, dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, has_bom =0, is_sub_cont =0)
-        
+
       # update qty_consumed_per_unit
       m.qty_consumed_per_unit = flt(m.qty) / flt(self.doc.quantity)
       m.save()
@@ -314,12 +323,12 @@
   def update_childs_dir_op_value(self, m, child_bom_cost = 0):
     #msgprint("IN UPDATE CHILDS DIR OP VALUE")
     if child_bom_cost:
-      # get recent direct material cost, operating cost, cost from child bom 
+      # get recent direct material cost, operating cost, cost from child bom
       child_bom_cost = sql("select dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr, operating_cost, cost_as_per_mar, cost_as_per_lpr, cost_as_per_sr, quantity from `tabBill Of Materials` where  name = %s", m.bom_no, as_dict = 1)
-    
+
     # operating_cost
     m.operating_cost = child_bom_cost and flt(child_bom_cost[0]['operating_cost']) / flt(child_bom_cost[0]['quantity']) or 0.00
-    
+
     val_dir_dict = {'value_as_per_mar': 'cost_as_per_mar', 'dir_mat_as_per_mar': 'dir_mat_as_per_mar',
                     'value_as_per_lpr': 'cost_as_per_lpr', 'dir_mat_as_per_lpr': 'dir_mat_as_per_lpr',
                     'value_as_per_sr' : 'cost_as_per_sr' , 'dir_mat_as_per_sr' : 'dir_mat_as_per_sr'  }
@@ -353,7 +362,7 @@
       dir_mat_as_per_mar += flt(m.amount_as_per_mar)
       dir_mat_as_per_lpr += flt(m.amount_as_per_lpr)
       dir_mat_as_per_sr  += flt(m.amount_as_per_sr)
-    #msgprint(cstr(m.item_code))  
+    #msgprint(cstr(m.item_code))
     #msgprint("dir_mat_as_per_mar < ==> " + cstr(dir_mat_as_per_mar) + "***" + "dir_mat_as_per_lpr < ==> " + cstr(dir_mat_as_per_lpr) + "***" + "dir_mat_as_per_sr < ==> " + cstr(dir_mat_as_per_sr) + "***")
     return dir_mat_as_per_mar, dir_mat_as_per_lpr, dir_mat_as_per_sr
 
@@ -367,9 +376,9 @@
       while withdraw:
         if not fcfs_bal:
           break # nothing in store
-           
+
         batch = fcfs_bal[0]
-          
+
         if batch[0] < withdraw:
           # not enough in current batch, clear batch
           withdraw -= batch[0]
@@ -424,8 +433,8 @@
       #ma_rate = sql("select ifnull(sum(ma_rate), 0)/ ifnull(count(*),1) from `tabBin` where item_code = '%s' and ifnull(ma_rate, 0) > 0" % cstr(item_code))
       #ma_rate = flt(ma_rate and ma_rate[0][0]) or 0
       ma_rate = self.get_valuation_rate(item_code, qty)
-      
-    # get recent last purchase rate 
+
+    # get recent last purchase rate
     lpr_rate = lpr and flt(sql("select last_purchase_rate from `tabItem` where name = '%s'" % item_code)[0][0]) or 0.00
     # get recent standard rate
     sr_rate = sr and flt(sql("select standard_rate from `tabItem` where name = '%s'" % item_code)[0][0]) or 0.00
@@ -440,13 +449,14 @@
         raise Exception
       else:
         check_list.append(cstr(d.item_code))
-  
-  #----- Document on Save function------  
+
+  #----- Document on Save function------
   def validate(self):
+    #msgprint(len(getlist(self.doclist, 'bom_materials')))
     self.validate_main_item()
     self.validate_duplicate_items()
     self.calculate_cost(validate = 1)
-   
+
   def check_recursion(self):
     check_list = [['parent', 'bom_no', 'parent'], ['bom_no', 'parent', 'child']]
     for d in check_list:
@@ -466,10 +476,10 @@
       msgprint("Cannot change Item once the Bill Of Material is created.")
       raise Exception
     self.check_recursion()
-    
+
 
 # ********************************************** Submit *************************************************************
-  
+
   # Add Flat BOM Details
   # -----------------------
   def add_to_flat_bom_detail(self, is_submit = 0):
@@ -486,9 +496,11 @@
 
   #Get Child Flat BOM Items
   #----------------------------------------
-  def get_child_flat_bom_items(self, item, d):   
+  def get_child_flat_bom_items(self, item, d):
+
     child_flat_bom_items=[]
     if item and (item[0]['is_sub_contracted_item'] == 'Yes' or item[0]['is_pro_applicable'] == 'Yes'):
+
       child_flat_bom_items = sql("select item_code, description, qty_consumed_per_unit, stock_uom, moving_avg_rate, last_purchase_rate, standard_rate, '%s' as parent_bom, bom_mat_no, 'No' as is_pro_applicable from `tabFlat BOM Detail` where parent = '%s' and is_pro_applicable = 'No' and docstatus = 1" % ( d.bom_no, cstr(d.bom_no)))
       self.cur_flat_bom_items.append([d.item_code, d.description, flt(d.qty), d.stock_uom, flt(d.moving_avg_rate), flt(d.amount_as_per_mar), flt(d.last_purchase_rate), flt(d.amount_as_per_lpr), flt(d.standard_rate), flt(d.amount_as_per_sr), flt(d.qty_consumed_per_unit), (item[0]['is_sub_contracted_item'] == 'Yes') and d.parent or d.bom_no, d.name, (item[0]['is_sub_contracted_item'] == 'Yes') and 'No' or 'Yes'])
 
@@ -500,20 +512,22 @@
       raise Exception
     else:
       return child_flat_bom_items
-  
-  
+
+
   # Get Current Flat BOM Items
   # -----------------------------
   def get_current_flat_bom_items(self):
+
     self.cur_flat_bom_items = []
-    
+
     cfb_lbl = {'item_code': 0, 'description': 1, 'qty_consumed_per_unit': 2, 'stock_uom': 3, 'moving_avg_rate': 4, 'last_purchase_rate': 5, 'standard_rate': 6, 'parent_bom': 7, 'bom_mat_no': 8, 'is_pro_applicable': 9}
-    
-    for d in getlist(self.doclist, 'bom_materials'):  
+
+    for d in getlist(self.doclist, 'bom_materials'):
+
       if d.bom_no:
         item = sql("select is_sub_contracted_item, is_pro_applicable from `tabItem` where name = '%s'" % d.item_code, as_dict = 1)
         child_flat_bom_items = self.get_child_flat_bom_items(item,d)
-        
+
         for c in child_flat_bom_items:
           self.cur_flat_bom_items.append([c[cfb_lbl['item_code']], c[cfb_lbl['description']], flt(d.qty) * flt(c[cfb_lbl['qty_consumed_per_unit']]), c[cfb_lbl['stock_uom']], flt(c[cfb_lbl['moving_avg_rate']]), flt(d.qty) * flt(c[cfb_lbl['qty_consumed_per_unit']]) * flt(c[cfb_lbl['moving_avg_rate']]) ,flt(c[cfb_lbl['last_purchase_rate']]), flt(d.qty) * flt(c[cfb_lbl['qty_consumed_per_unit']]) * flt(c[cfb_lbl['last_purchase_rate']]), flt(c[cfb_lbl['standard_rate']]), flt(d.qty) * flt(c[cfb_lbl['qty_consumed_per_unit']]) * flt(c[cfb_lbl['standard_rate']]), flt(d.qty_consumed_per_unit) * flt(c[cfb_lbl['qty_consumed_per_unit']]), c[cfb_lbl['parent_bom']], c[cfb_lbl['bom_mat_no']], c[cfb_lbl['is_pro_applicable']]])
       else:
@@ -521,10 +535,10 @@
         self.cur_flat_bom_items.append([d.item_code, d.description, flt(d.qty), d.stock_uom, flt(d.moving_avg_rate), flt(d.amount_as_per_mar), flt(d.last_purchase_rate), flt(d.amount_as_per_lpr), flt(d.standard_rate), flt(d.amount_as_per_sr), flt(d.qty_consumed_per_unit), d.parent, d.name, 'No' ])
 
   # Update Flat BOM Engine
-  # ------------------------  
+  # ------------------------
   def update_flat_bom_engine(self, is_submit = 0):
     # following will be correct data
-    # get correct / updated flat bom data    
+    # get correct / updated flat bom data
     self.get_current_flat_bom_items()
     # insert to curr flat bom data
     self.add_to_flat_bom_detail(is_submit)
@@ -533,9 +547,9 @@
   # On Submit
   # -----------
   def on_submit(self):
-    self.update_flat_bom_engine()
+    self.update_flat_bom_engine(1)
 
-        
+
   def get_parent_bom_list(self, bom_no):
     p_bom = sql("select parent from `tabBOM Material` where bom_no = '%s'" % bom_no)
     return p_bom and [i[0] for i in p_bom] or []
diff --git a/production/doctype/bill_of_materials/bill_of_materials.txt b/production/doctype/bill_of_materials/bill_of_materials.txt
index 37d8b69..2590817 100644
--- a/production/doctype/bill_of_materials/bill_of_materials.txt
+++ b/production/doctype/bill_of_materials/bill_of_materials.txt
@@ -34,7 +34,7 @@
 		'section_style': 'Tabbed',
 		'server_code_error': ' ',
 		'show_in_menu': 0,
-		'subject': '%(item_code)s',
+		'subject': '%(item)s',
 		'version': 170
 	},
 
diff --git a/production/doctype/bom_control/bom_control.py b/production/doctype/bom_control/bom_control.py
index 02b61e3..6b0987b 100644
--- a/production/doctype/bom_control/bom_control.py
+++ b/production/doctype/bom_control/bom_control.py
@@ -1,7 +1,7 @@
 # Please edit this list and import only required elements
 import webnotes
 
-from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
+from webnotes.utils import cint, flt
 from webnotes.model import db_exists
 from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
 from webnotes.model.doclist import getlist, copy_doclist
@@ -13,7 +13,7 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-	
+
 # -----------------------------------------------------------------------------------------
 
 
@@ -32,7 +32,7 @@
     return '~~~'.join([r for r in item_group])
 
   def get_item_code(self,item_group):
-    # here Bill Of Materials docstatus = 1 and is_active ='yes' condition is not given because some bom is under construction 
+    # here Bill Of Materials docstatus = 1 and is_active ='yes' condition is not given because some bom is under construction
     # that is it is still in saved mode and they want see till where they have reach.
     ret = sql("select distinct t1.name from `tabItem` t1, `tabBill Of Materials` t2 where t2.item = t1.name and t1.item_group = '%s' " % (item_group))
     return '~~~'.join([r[0] for r in ret])
@@ -44,18 +44,20 @@
   def get_operations(self,bom_no):
     # reply = [ 'Operation',operation_no, opn_description,BOM NO     , workstation, hour_rate,  time_in_minutes,  Total Direct Material, Total Operating Cost, Cost]
     # reply = [ 0           ,  1         ,    2          ,3          , 4          ,  5        ,  6             ,         7            ,   8                 ,9                     , 10                  , 11  ]
-    
     ret = sql("select operation_no,opn_description,workstation,hour_rate,time_in_mins from `tabBOM Operation` where parent = %s", bom_no, as_dict = 1)
     cost = sql("select dir_mat_as_per_mar , operating_cost , cost_as_per_mar from `tabBill Of Materials` where name = %s", bom_no, as_dict = 1)
+
     # Validate the BOM ENTRIES
     #check = get_obj('Bill Of Materials', bom_no, with_children =1).validate()
     reply = []
-    for r in ret:
-      reply.append(['operation',cint(r['operation_no']), r['opn_description'] or '','%s'% bom_no,r['workstation'],flt(r['hour_rate']),flt(r['time_in_mins']),0,0,0])
-    reply[0][7]= flt(cost[0]['dir_mat_as_per_mar'])
-    reply[0][8]=flt(cost[0]['operating_cost']) 
-    reply[0][9]=flt(cost[0]['cost_as_per_mar'])
-    #msgprint(bom_no)
+
+    if ret:
+      for r in ret:
+        reply.append(['operation',cint(r['operation_no']), r['opn_description'] or '','%s'% bom_no,r['workstation'],flt(r['hour_rate']),flt(r['time_in_mins']),0,0,0])
+
+      reply[0][7]= flt(cost[0]['dir_mat_as_per_mar'])
+      reply[0][8]=flt(cost[0]['operating_cost'])
+      reply[0][9]=flt(cost[0]['cost_as_per_mar'])
     return reply
 
   def get_item_bom(self,data):
@@ -64,7 +66,7 @@
     data = eval(data)
     reply = []
     ret = sql("select item_code,description,bom_no,qty,scrap,stock_uom,value_as_per_mar,moving_avg_rate from `tabBOM Material` where parent = '%s' and operation_no = '%s'" % (data['bom_no'],data['op_no']), as_dict =1 )
-    
+
     for r in ret:
       item = sql("select is_manufactured_item, is_sub_contracted_item from `tabItem` where name = '%s'" % r['item_code'], as_dict=1)
       if not item[0]['is_manufactured_item'] == 'Yes' and not item[0]['is_sub_contracted_item'] =='Yes':
@@ -78,9 +80,8 @@
     return reply
 
 
-
-  #------------- Wrapper Code --------------  
-  # BOM TREE   
+  #------------- Wrapper Code --------------
+  # BOM TREE
   def calculate_cost( self, bom_no):
     main_bom_list = get_obj(dt = 'Production Control').traverse_bom_tree( bom_no = bom_no, qty = 1, calculate_cost = 1)
     main_bom_list.reverse()
@@ -89,13 +90,13 @@
       bom_obj.calculate_cost(validate = 0)
       bom_obj.doc.save()
     return 'calculated'
-      
+
 
   def get_bom_tree_list(self,args):
     arg = eval(args)
     i =[]
     for a in sql("select t1.name from `tabBill Of Materials` t1, `tabItem` t2 where t2.item_group like '%s' and t1.item like '%s'"%(arg['item_group'] +'%',arg['item_code'] + '%')):
       if a[0] not in i:
-        i.append(a[0]) 
+        i.append(a[0])
     return i
 #    return [s[0] for s in sql("select t1.name from `tabBill Of Materials` t1, `tabItem` t2 where t2.item_group like '%s'  and t1.item like '%s' " %(arg['item_group']+'%',arg['item_code'+'%'])]
\ No newline at end of file
diff --git a/production/doctype/production_order/production_order.py b/production/doctype/production_order/production_order.py
index ce8f082..570c802 100644
--- a/production/doctype/production_order/production_order.py
+++ b/production/doctype/production_order/production_order.py
@@ -34,7 +34,7 @@
             'stock_uom'   : item and item[0]['stock_uom'] or '',
             'default_bom' : item and item[0]['default_bom'] or ''
     }
-    return cstr(ret)
+    return ret
     
   def validate(self):
     if not self.doc.production_item :
diff --git a/production/doctype/production_planning_tool/production_planning_tool.py b/production/doctype/production_planning_tool/production_planning_tool.py
index c548173..d0ae05b 100644
--- a/production/doctype/production_planning_tool/production_planning_tool.py
+++ b/production/doctype/production_planning_tool/production_planning_tool.py
@@ -32,7 +32,7 @@
              'stock_uom'   : item and item[0]['stock_uom'],
              'bom_no'      : item and item[0]['default_bom']
       }
-      return cstr(ret)
+      return ret
     else:
       msgprint("Item %s does not exist in system." %(args['item_code']))
       raise Exception
diff --git a/production/doctype/workstation/workstation.py b/production/doctype/workstation/workstation.py
index aaa4908..45851de 100644
--- a/production/doctype/workstation/workstation.py
+++ b/production/doctype/workstation/workstation.py
@@ -25,7 +25,7 @@
   def update_bom_operation(self):
       bom_list = sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
       for bom_no in bom_list:
-        sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no, self.doc.name))
+        sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
   
   def on_update(self):
     set(self.doc, 'overhead', flt(self.doc.hour_rate_electricity) + flt(self.doc.hour_rate_consumable) + flt(self.doc.hour_rate_rent))
diff --git a/projects/doctype/project/project.py b/projects/doctype/project/project.py
index e68771c..9930bf4 100644
--- a/projects/doctype/project/project.py
+++ b/projects/doctype/project/project.py
@@ -38,7 +38,7 @@
       ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
       ret['contact_no'] = contact_det and contact_det[0]['contact_no'] or ''
       ret['email_id'] = contact_det and contact_det[0]['email_id'] or ''    
-      return cstr(ret)
+      return ret
     else:
       msgprint("Customer : %s does not exist in system." % (self.doc.customer))
       raise Exception  
@@ -52,7 +52,7 @@
         'contact_no' : contact and contact[0]['contact_no'] or '',
         'email_id' : contact and contact[0]['email_id'] or ''
       }
-      return str(ret)
+      return ret
     else:
       msgprint("Contact Person : %s does not exist in the system." % (self.doc,contact_person))
       raise Exception
@@ -65,7 +65,7 @@
     #if pft > 0:
     per_pft = (flt(pft) / flt(self.doc.project_value)) * 100
     ret = {'gross_margin_value': pft, 'per_gross_margin': per_pft}
-    return cstr(ret)
+    return ret
     
   # validate
   #================================================
diff --git a/projects/doctype/ticket/ticket.py b/projects/doctype/ticket/ticket.py
index 8d716cc..0f18b21 100644
--- a/projects/doctype/ticket/ticket.py
+++ b/projects/doctype/ticket/ticket.py
@@ -22,18 +22,18 @@
     cust = sql("select customer, customer_name from `tabProject` where name = %s", self.doc.project)
     if cust:
       ret = {'customer': cust and cust[0][0] or '', 'customer_name': cust and cust[0][1] or ''}
-      return cstr(ret)
+      return ret
   
   def get_customer_details(self):
     cust = sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
     if cust:
       ret = {'customer_name': cust and cust[0][0] or ''}
-      return cstr(ret)
+      return ret
   
   def get_allocated_to_name(self):
     as_em = sql("select first_name, last_name from `tabProfile` where name=%s",self.doc.allocated_to)
     ret = { 'allocated_to_name' : as_em and (as_em[0][0] + ' ' + as_em[0][1]) or ''}
-    return cstr(ret)
+    return ret
 
   # validate
   #--------------------------------------------   
diff --git a/projects/doctype/timesheet/timesheet.py b/projects/doctype/timesheet/timesheet.py
index ba921f4..f07975c 100644
--- a/projects/doctype/timesheet/timesheet.py
+++ b/projects/doctype/timesheet/timesheet.py
@@ -32,7 +32,7 @@
     tsk = sql("select name, project, customer, customer_name from `tabTicket` where subject = %s", task_sub)
     if tsk:
       ret = {'task_id': tsk and tsk[0][0] or '', 'project_name': tsk and tsk[0][1] or '', 'customer_name': tsk and tsk[0][3] or ''}
-      return cstr(ret)
+      return ret
   
   def validate(self):
     if getdate(self.doc.timesheet_date) > getdate(nowdate()):
diff --git a/selling/doctype/enquiry/enquiry.py b/selling/doctype/enquiry/enquiry.py
index 61bc4ec..1259702 100644
--- a/selling/doctype/enquiry/enquiry.py
+++ b/selling/doctype/enquiry/enquiry.py
@@ -50,7 +50,7 @@
       ret['contact_no']     = contact_det and contact_det[0]['contact_no'] or ''
       ret['email_id']       = contact_det and contact_det[0]['email_id'] or ''
     
-      return cstr(ret)
+      return ret
     else:
       msgprint("Customer : %s does not exist in system." % (name))
       raise Exception
@@ -64,7 +64,7 @@
       'contact_no' : contact and contact[0]['contact_no'] or '',
       'email_id' : contact and contact[0]['email_id'] or ''
     }
-    return str(ret)   
+    return ret
     
   # ====================================================================================================================
   def on_update(self):
@@ -184,7 +184,7 @@
     else:
       set(self.doc, 'status', 'Enquiry Lost')
       set(self.doc, 'order_lost_reason', arg)
-      return cstr('true')
+      return 'true'
     
   # ====================================================================================================================  
   def update_follow_up(self):
diff --git a/selling/doctype/installation_note/installation_note.py b/selling/doctype/installation_note/installation_note.py
index ce21363..e0af7ec 100644
--- a/selling/doctype/installation_note/installation_note.py
+++ b/selling/doctype/installation_note/installation_note.py
@@ -29,20 +29,7 @@
   # ---------
   def autoname(self):
     self.doc.name = make_autoname(self.doc.naming_series+'.#####')
-  
-  #fetch customer details
-  #=================================
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name, t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = '%s' and t1.name=t2.customer and t2.is_primary_contact = 'Yes'"%self.doc.customer, as_dict=1)
-    
-  #  ret = {
-  #    'customer_name':  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-
-  #  return str(ret)
+ 
   
   #fetch delivery note details
   #====================================
diff --git a/selling/doctype/lead/lead.py b/selling/doctype/lead/lead.py
index 1bf8c8d..14d14e1 100644
--- a/selling/doctype/lead/lead.py
+++ b/selling/doctype/lead/lead.py
@@ -51,7 +51,7 @@
       'description': it and it[0][3] or '',
       'uom' : it and it[0][4] or ''
       }
-      return cstr(ret)
+      return ret
   
   def validate(self):
     import string
diff --git a/selling/doctype/quotation/quotation.py b/selling/doctype/quotation/quotation.py
index aed868e..1175540 100644
--- a/selling/doctype/quotation/quotation.py
+++ b/selling/doctype/quotation/quotation.py
@@ -45,17 +45,12 @@
 
     self.get_adj_percent()
 
-    return cstr(self.doc.quotation_to)
-    
-  # Get Customer Details
-  # --------------------
-  #def get_customer_details(self):
-  #  return cstr(get_obj('Sales Common').get_customer_details(self))
+    return self.doc.quotation_to
 
   # Get contact person details based on customer selected
   # ------------------------------------------------------
   def get_contact_details(self):
-    return cstr(get_obj('Sales Common').get_contact_details(self,0))
+    return get_obj('Sales Common').get_contact_details(self,0)
   
   # Clear Quotation Details
   # -----------------------
@@ -111,7 +106,7 @@
       'contact_mobile' : details and details[0]['mobile_no'] or '-',
       'contact_email' : details and details[0]['email_id'] or '-'      
     }
-    return cstr(ret)
+    return ret
 
      
 # GET TERMS AND CONDITIONS
@@ -295,7 +290,7 @@
       set(self.doc, 'status', 'Order Lost')
       set(self.doc, 'order_lost_reason', arg)
       self.update_enquiry('order lost')
-      return cstr('true')
+      return 'true'
   
   #check if value entered in item table
   #--------------------------------------
diff --git a/selling/doctype/sales_common/sales_common.py b/selling/doctype/sales_common/sales_common.py
index 7a1af22..acdca50 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -118,21 +118,21 @@
 		t = {}
 		for x in tax: t[x[0]] = flt(x[1])
 		ret = {
-			'description'								 : item and item[0]['description_html'] or item[0]['description'],
-			'item_group'									: item and item[0]['item_group'] or '',
-			'item_name'									 : item and item[0]['item_name'] or '',
-			'brand'											 : item and item[0]['brand'] or '',
-			'stock_uom'									 : item and item[0]['stock_uom'] or '',
-			'reserved_warehouse'					: item and item[0]['default_warehouse'] or '',
-			'warehouse'									 : item and item[0]['default_warehouse'] or '',
-			'income_account'							: item and item[0]['default_income_account'] or '',
-			'cost_center'								 : item and item[0]['default_sales_cost_center'] or '',
-			'qty'												 : 1.00,	 # this is done coz if item once fetched is fetched again thn its qty shld be reset to 1
-			'adj_rate'										: 0,
-			'amount'											: 0,
-			'export_amount'							 : 0,
-			'item_tax_rate'							 : str(t),
-			'batch_no'										: ''
+			'description'			: item and item[0]['description_html'] or item[0]['description'],
+			'item_group'			: item and item[0]['item_group'] or '',
+			'item_name'				: item and item[0]['item_name'] or '',
+			'brand'					: item and item[0]['brand'] or '',
+			'stock_uom'				: item and item[0]['stock_uom'] or '',
+			'reserved_warehouse'	: item and item[0]['default_warehouse'] or '',
+			'warehouse'				: item and item[0]['default_warehouse'] or '',
+			'income_account'		: item and item[0]['default_income_account'] or '',
+			'cost_center'			: item and item[0]['default_sales_cost_center'] or '',
+			'qty'					: 1.00,	 # this is done coz if item once fetched is fetched again thn its qty shld be reset to 1
+			'adj_rate'				: 0,
+			'amount'				: 0,
+			'export_amount'			: 0,
+			'item_tax_rate'			: str(t),
+			'batch_no'				: ''
 		}
 		if(obj.doc.price_list_name and item):	#this is done to fetch the changed BASIC RATE and REF RATE based on PRICE LIST
 			ref_rate =	self.get_ref_rate(item_code, obj.doc.price_list_name, obj.doc.currency)
@@ -143,7 +143,8 @@
 			
 		if obj.doc.doctype == 'Receivable Voucher':
 			return ret
-		return str(ret)
+			
+		return ret
 	
 	# ***************** Get Ref rate as entered in Item Master ********************
 	def get_ref_rate(self, item_code, price_list_name, currency):
@@ -161,7 +162,6 @@
 			d.base_ref_rate = flt(ref_rate) * flt(obj.doc.conversion_rate)
 			d.export_rate = flt(ref_rate)
 
-
 	# Load Default Taxes
 	# ====================
 	def load_default_taxes(self, obj):
@@ -203,7 +203,7 @@
 		ret = {
 			'item_tax_rate'		:	tax and str(t) or ''
 		}
-		return str(ret)
+		return ret
 
 	# Get Serial No Details
 	# ==========================================================================
@@ -220,7 +220,7 @@
 			'description'			: item and item[0]['description'] or '',
 			'item_tax_rate'		: str(t)
 		}
-		return str(ret)
+		return ret
 		
 	# Get Commission rate
 	# =======================================================================
@@ -233,7 +233,7 @@
 				'commission_rate'		 :	comm_rate and flt(comm_rate[0]['commission_rate']) or 0,
 				'total_commission'		:	flt(total_comm)
 			}
-			return str(ret)
+			return ret
 		else:
 			msgprint("Business Associate : %s does not exist in the system." % (sales_partner))
 			raise Exception
@@ -287,7 +287,7 @@
 			ret = {
 				'rate'	:	rate and flt(rate[0]['tax_rate']) or 0
 			}
-		return cstr(ret)
+		return ret
 		
 
 	# Make Packing List from Sales BOM
@@ -324,7 +324,7 @@
 			
 			if self.has_sales_bom(d.item_code):
 				for i in self.get_sales_bom_items(d.item_code):
-					il.append([warehouse, i[0], flt(flt(i[1])* qty), reserved_qty, i[2], d.batch_no, d.serial_no])
+					il.append([warehouse, i[0], flt(flt(i[1])* qty), flt(flt(i[1])*reserved_qty), i[2], d.batch_no, d.serial_no])
 			else:
 				il.append([warehouse, d.item_code, qty, reserved_qty, d.stock_uom, d.batch_no, d.serial_no])
 		return il
@@ -498,7 +498,7 @@
 			- Validate over delivery
 			
 		From Receivable Voucher 
-			- Update Billed Qty
+			- Update Billed Amt
 			- Update Percent
 			- Validate over billing
 			
@@ -526,23 +526,33 @@
 			self.validate_qty({
 				'source_dt'		:'Delivery Note Detail',
 				'compare_field'	:'delivered_qty',
+				'compare_ref_field'	:'qty',
 				'target_dt'		:'Sales Order Detail',
 				'join_field'	:'prevdoc_detail_docname'
 			})
 		elif self.obj.doc.doctype=='Receivable Voucher':
 			self.validate_qty({
 				'source_dt'		:'RV Detail',
-				'compare_field'	:'billed_qty',
+				'compare_field'	:'billed_amt',
+				'compare_ref_field'	:'amount',
 				'target_dt'		:'Sales Order Detail',
 				'join_field'	:'so_detail'
 			})
+			self.validate_qty({
+				'source_dt'		:'RV Detail',
+				'compare_field'	:'billed_amt',
+				'compare_ref_field'	:'amount',
+				'target_dt'		:'Delivery Note Detail',
+				'join_field'	:'dn_detail'
+			}, no_tolerance =1)
 		elif self.obj.doc.doctype=='Installation Note':
 			self.validate_qty({
 				'source_dt'		:'Installation Item Details',
 				'compare_field'	:'installed_qty',
+				'compare_ref_field'	:'qty',
 				'target_dt'		:'Delivery Note Detail',
 				'join_field'	:'dn_detail'
-			}, no_tolerance =1);
+			}, no_tolerance =1)
 
 	
 	def get_tolerance_for(self, item_code):
@@ -569,22 +579,22 @@
 		
 		# check if overflow is within tolerance
 		tolerance = self.get_tolerance_for(item['item_code'])
-		overflow_percent = ((item[args['compare_field']] - item['qty']) / item['qty'] * 100)
+		overflow_percent = ((item[args['compare_field']] - item[args['compare_ref_field']]) / item[args['compare_ref_field']] * 100)
 	
 		if overflow_percent - tolerance > 0.0001:
-			item['max_allowed'] = flt(item['qty'] * (100+tolerance)/100)
+			item['max_allowed'] = flt(item[args['compare_ref_field']] * (100+tolerance)/100)
 			item['reduce_by'] = item[args['compare_field']] - item['max_allowed']
 		
 			msgprint("""
-				Row #%(idx)s: Max qty allowed for <b>Item %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>. 
+				Row #%(idx)s: Max %(compare_ref_field)s allowed for <b>Item %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>. 
 				
 				If you want to increase your overflow tolerance, please increase tolerance %% in Global Defaults or Item master. 
 				
-				Or, you must reduce the qty by %(reduce_by)s""" % item, raise_exception=1)
+				Or, you must reduce the %(compare_ref_field)s by %(reduce_by)s""" % item, raise_exception=1)
 
 	def validate_qty(self, args, no_tolerance=None):
 		"""
-			Updates qty at row level
+			Validates qty at row level
 		"""
 		# get unique transactions to update
 		for d in self.obj.doclist:
@@ -593,22 +603,23 @@
 
 				# get all qty where qty > compare_field
 				item = sql("""
-					select item_code, qty, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s` 
-					where qty < `%(compare_field)s` and name="%(name)s" and docstatus=1
+					select item_code, `%(compare_ref_field)s`, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s` 
+					where `%(compare_ref_field)s` < `%(compare_field)s` and name="%(name)s" and docstatus=1
 					""" % args, as_dict=1)
 				
 				if item:
 					item = item[0]
 					item['idx'] = d.idx
-					
+					item['compare_ref_field'] = args['compare_ref_field']
 					if no_tolerance:
-						item['reduce_by'] = item[args['compare_field']] - item['qty']
+						item['reduce_by'] = item[args['compare_field']] - item[args['compare_ref_field']]
 						msgprint("""
-							Row #%(idx)s: Max qty allowed for <b>Item %(item_code)s</b> against 
-							<b>%(parenttype)s %(parent)s</b> is <b>%(qty)s</b>. 
+							Row #%(idx)s: Max %(compare_ref_field)s allowed for <b>Item %(item_code)s</b> against 
+							<b>%(parenttype)s %(parent)s</b> is <b>""" % item 
+							+ cstr(item[args['compare_ref_field']]) + """</b>. 
 							
-							You must reduce the qty by %(reduce_by)s""" % item, raise_exception=1)
-						
+							You must reduce the %(compare_ref_field)s by %(reduce_by)s""" % item, raise_exception=1)
+					
 					else:
 						self.check_overflow_with_tolerance(item, args)
 						
@@ -623,6 +634,7 @@
 				'target_dt'				:'Sales Order Detail',
 				'target_parent_dt'		:'Sales Order',
 				'target_parent_field'	:'per_delivered',
+				'target_ref_field'		:'qty',
 				'source_dt'				:'Delivery Note Detail',
 				'source_field'			:'qty',
 				'join_field'			:'prevdoc_detail_docname',
@@ -633,12 +645,13 @@
 			
 		elif self.obj.doc.doctype=='Receivable Voucher':
 			self.update_qty({
-				'target_field'			:'billed_qty',
+				'target_field'			:'billed_amt',
 				'target_dt'				:'Sales Order Detail',
 				'target_parent_dt'		:'Sales Order',
 				'target_parent_field'	:'per_billed',
+				'target_ref_field'		:'amount',
 				'source_dt'				:'RV Detail',
-				'source_field'			:'qty',
+				'source_field'			:'amount',
 				'join_field'			:'so_detail',
 				'percent_join_field'	:'sales_order',
 				'status_field'			:'billing_status',
@@ -646,12 +659,13 @@
 			})
 
 			self.update_qty({
-				'target_field'			:'billed_qty',
+				'target_field'			:'billed_amt',
 				'target_dt'				:'Delivery Note Detail',
 				'target_parent_dt'		:'Delivery Note',
 				'target_parent_field'	:'per_billed',
+				'target_ref_field'		:'amount',
 				'source_dt'				:'RV Detail',
-				'source_field'			:'qty',
+				'source_field'			:'amount',
 				'join_field'			:'dn_detail',
 				'percent_join_field'	:'delivery_note',
 				'status_field'			:'billing_status',
@@ -664,6 +678,7 @@
 				'target_dt'				:'Delivery Note Detail',
 				'target_parent_dt'		:'Delivery Note',
 				'target_parent_field'	:'per_installed',
+				'target_ref_field'		:'qty',
 				'source_dt'				:'Installed Item Details',
 				'source_field'			:'qty',
 				'join_field'			:'prevdoc_detail_docname',
@@ -694,7 +709,7 @@
 						update 
 							`tab%(target_dt)s` 
 						set 
-							%(target_field)s = (select sum(qty) from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s" and (docstatus=1 %(cond)s))
+							%(target_field)s = (select sum(%(source_field)s) from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s" and (docstatus=1 %(cond)s))
 						where
 							name="%(detail_id)s"            
 					""" % args)			
@@ -710,10 +725,10 @@
 						`tab%(target_parent_dt)s` 
 					set 
 						%(target_parent_field)s = 
-							(select sum(if(qty > ifnull(%(target_field)s, 0), %(target_field)s, qty))/sum(qty)*100 from `tab%(target_dt)s` where parent="%(name)s"), 
+							(select sum(if(%(target_ref_field)s > ifnull(%(target_field)s, 0), %(target_field)s, %(target_ref_field)s))/sum(%(target_ref_field)s)*100 from `tab%(target_dt)s` where parent="%(name)s"), 
 						modified = now()
-						where
-							name="%(name)s"
+					where
+						name="%(name)s"
 					""" % args)
 
 				# update field
diff --git a/selling/doctype/sales_order/sales_order.py b/selling/doctype/sales_order/sales_order.py
index 9dee82e..ca5af7a 100644
--- a/selling/doctype/sales_order/sales_order.py
+++ b/selling/doctype/sales_order/sales_order.py
@@ -102,8 +102,7 @@
 			 'projected_qty' : tot_avail_qty and flt(tot_avail_qty[0]['projected_qty']) or 0,
 			 'actual_qty' : tot_avail_qty and flt(tot_avail_qty[0]['actual_qty']) or 0
 		}
-		return cstr(ret)
-	
+		return ret
 	
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
@@ -136,7 +135,7 @@
 		nm = nm and nm[0][0] or ''
 		
 		if not nm:
-			return cstr('No')
+			return 'No'
 
 #check if maintenance visit already generated
 #============================================
@@ -145,7 +144,7 @@
 		nm = nm and nm[0][0] or ''
 		
 		if not nm:
-			return cstr('No')
+			return 'No'
 
 # VALIDATE
 # =====================================================================================
diff --git a/selling/doctype/sales_order/sales_order.txt b/selling/doctype/sales_order/sales_order.txt
index 69773dd..98833d1 100644
--- a/selling/doctype/sales_order/sales_order.txt
+++ b/selling/doctype/sales_order/sales_order.txt
@@ -5,15 +5,14 @@
 	{
 		'creation': '2010-08-08 17:09:21',
 		'docstatus': 0,
-		'modified': '2011-06-27 16:05:56',
+		'modified': '2011-08-09 17:06:09',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309170956',
-		'client_script': "cur_frm.add_fetch('customer','sales_person','sales_person');",
+		'_last_update': '1311621379',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'document_type': 'Transaction',
@@ -28,7 +27,7 @@
 		'show_in_menu': 0,
 		'subject': 'From %(customer_name)s on %(transaction_date)s worth %(currency)s %(grand_total_export)s | %(per_delivered)s% delivered | %(per_billed)s% billed',
 		'tag_fields': 'delivery_status,billing_status',
-		'version': 593
+		'version': 597
 	},
 
 	# These values are common for all DocField
@@ -58,28 +57,23 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 1,
-		'permlevel': 1,
-		'role': 'Sales Manager',
-		'submit': 0,
-		'write': 0
+		'permlevel': 0,
+		'role': 'Production Manager'
 	},
 
 	# DocPerm
 	{
-		'amend': 1,
-		'cancel': 1,
-		'create': 1,
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 2,
-		'permlevel': 0,
+		'permlevel': 1,
 		'role': 'Sales Manager',
-		'submit': 1,
-		'write': 1
+		'submit': 0,
+		'write': 0
 	},
 
 	# DocPerm
@@ -90,6 +84,19 @@
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
+		'role': 'Sales Manager',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocPerm
+	{
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'idx': 4,
+		'permlevel': 0,
 		'role': 'Sales User',
 		'submit': 1,
 		'write': 1
@@ -101,7 +108,7 @@
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
-		'idx': 4,
+		'idx': 5,
 		'permlevel': 1,
 		'role': 'Sales User',
 		'submit': 0,
@@ -111,7 +118,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 5,
+		'idx': 6,
 		'match': 'customer_name',
 		'permlevel': 0,
 		'role': 'Customer'
@@ -120,7 +127,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 6,
+		'idx': 7,
 		'permlevel': 2,
 		'role': 'Accounts User',
 		'write': 1
@@ -132,7 +139,7 @@
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 7,
+		'idx': 8,
 		'permlevel': 0,
 		'role': 'Maintenance Manager',
 		'submit': 1,
@@ -142,7 +149,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 8,
+		'idx': 9,
 		'permlevel': 1,
 		'role': 'Maintenance Manager'
 	},
@@ -153,7 +160,7 @@
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 9,
+		'idx': 10,
 		'permlevel': 0,
 		'role': 'Maintenance User',
 		'submit': 1,
@@ -163,7 +170,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 10,
+		'idx': 11,
 		'permlevel': 1,
 		'role': 'Maintenance User'
 	},
@@ -204,7 +211,7 @@
 		'no_copy': 1,
 		'oldfieldname': 'naming_series',
 		'oldfieldtype': 'Select',
-		'options': 'SO\nSO/10-11/',
+		'options': 'PI/2011/\nSO\nSO/10-11/\nSO1112',
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1
@@ -504,7 +511,7 @@
 		'fieldtype': 'Currency',
 		'idx': 23,
 		'in_filter': 1,
-		'label': '% Qty Billed',
+		'label': '% Amount Billed',
 		'no_copy': 1,
 		'oldfieldname': 'per_billed',
 		'oldfieldtype': 'Currency',
@@ -607,12 +614,22 @@
 
 	# DocField
 	{
+		'doctype': 'DocField',
+		'fieldname': 'vehicle_detail',
+		'fieldtype': 'Small Text',
+		'idx': 30,
+		'label': 'Vehicle Detail',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldname': 'quotation_date',
 		'fieldtype': 'Date',
 		'hidden': 1,
-		'idx': 30,
+		'idx': 31,
 		'label': 'Quotation Date',
 		'no_copy': 0,
 		'oldfieldname': 'quotation_date',
@@ -627,7 +644,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 31,
+		'idx': 32,
 		'label': 'Pull Quotation Details',
 		'oldfieldtype': 'Button',
 		'options': 'pull_quotation_details',
@@ -642,7 +659,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'price_list_name',
 		'fieldtype': 'Select',
-		'idx': 32,
+		'idx': 33,
 		'label': 'Price List',
 		'oldfieldname': 'price_list_name',
 		'oldfieldtype': 'Select',
@@ -658,7 +675,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 33,
+		'idx': 34,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -670,7 +687,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'currency',
 		'fieldtype': 'Select',
-		'idx': 34,
+		'idx': 35,
 		'label': 'Currency',
 		'oldfieldname': 'currency',
 		'oldfieldtype': 'Select',
@@ -689,7 +706,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'conversion_rate',
 		'fieldtype': 'Currency',
-		'idx': 35,
+		'idx': 36,
 		'label': 'Conversion Rate',
 		'oldfieldname': 'conversion_rate',
 		'oldfieldtype': 'Currency',
@@ -704,7 +721,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 36,
+		'idx': 37,
 		'permlevel': 0
 	},
 
@@ -715,7 +732,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_order_details',
 		'fieldtype': 'Table',
-		'idx': 37,
+		'idx': 38,
 		'label': 'Sales Order Details',
 		'oldfieldname': 'sales_order_details',
 		'oldfieldtype': 'Table',
@@ -729,7 +746,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 38,
+		'idx': 39,
 		'label': 'Clear Table',
 		'oldfieldtype': 'Button',
 		'options': 'clear_sales_order_details',
@@ -741,7 +758,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 39,
+		'idx': 40,
 		'label': 'Re-Calculate Values',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -755,7 +772,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'net_total',
 		'fieldtype': 'Currency',
-		'idx': 40,
+		'idx': 41,
 		'label': 'Net Total*',
 		'oldfieldname': 'net_total',
 		'oldfieldtype': 'Currency',
@@ -770,7 +787,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 41,
+		'idx': 42,
 		'label': 'Note1',
 		'oldfieldtype': 'HTML',
 		'options': '<b>NOTE :</b> * In Base Currency',
@@ -783,7 +800,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 42,
+		'idx': 43,
 		'label': 'Taxes',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -795,7 +812,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'charge',
 		'fieldtype': 'Link',
-		'idx': 43,
+		'idx': 44,
 		'label': 'Select Charges Master',
 		'oldfieldname': 'charge',
 		'oldfieldtype': 'Link',
@@ -808,7 +825,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 44,
+		'idx': 45,
 		'label': 'Get Charges',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -820,7 +837,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'other_charges',
 		'fieldtype': 'Table',
-		'idx': 45,
+		'idx': 46,
 		'label': 'Other Charges',
 		'oldfieldname': 'other_charges',
 		'oldfieldtype': 'Table',
@@ -832,7 +849,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 46,
+		'idx': 47,
 		'label': 'Calculate Charges',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -845,7 +862,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'other_charges_total',
 		'fieldtype': 'Currency',
-		'idx': 47,
+		'idx': 48,
 		'label': 'Charges Total*',
 		'oldfieldname': 'other_charges_total',
 		'oldfieldtype': 'Currency',
@@ -859,7 +876,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'grand_total',
 		'fieldtype': 'Currency',
-		'idx': 48,
+		'idx': 49,
 		'label': 'Grand Total*',
 		'oldfieldname': 'grand_total',
 		'oldfieldtype': 'Currency',
@@ -873,7 +890,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 49,
+		'idx': 50,
 		'label': 'OT Notes',
 		'oldfieldtype': 'HTML',
 		'options': '<b>NOTE :</b> * In Base Currency',
@@ -885,7 +902,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 50,
+		'idx': 51,
 		'label': 'Other Charges Calculation',
 		'oldfieldtype': 'HTML',
 		'permlevel': 0,
@@ -897,7 +914,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 51,
+		'idx': 52,
 		'label': 'Totals',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -909,7 +926,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'rounded_total',
 		'fieldtype': 'Currency',
-		'idx': 52,
+		'idx': 53,
 		'label': 'Rounded Total',
 		'oldfieldname': 'rounded_total',
 		'oldfieldtype': 'Currency',
@@ -925,7 +942,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'in_words',
 		'fieldtype': 'Data',
-		'idx': 53,
+		'idx': 54,
 		'label': 'In Words',
 		'oldfieldname': 'in_words',
 		'oldfieldtype': 'Data',
@@ -938,7 +955,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 54,
+		'idx': 55,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -950,7 +967,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'grand_total_export',
 		'fieldtype': 'Currency',
-		'idx': 55,
+		'idx': 56,
 		'label': 'Grand Total (Export)',
 		'oldfieldname': 'grand_total_export',
 		'oldfieldtype': 'Currency',
@@ -965,7 +982,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'rounded_total_export',
 		'fieldtype': 'Currency',
-		'idx': 56,
+		'idx': 57,
 		'label': 'Rounded Total (Export)',
 		'oldfieldname': 'rounded_total_export',
 		'oldfieldtype': 'Currency',
@@ -981,7 +998,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'in_words_export',
 		'fieldtype': 'Data',
-		'idx': 57,
+		'idx': 58,
 		'label': 'In Words (Export)',
 		'oldfieldname': 'in_words_export',
 		'oldfieldtype': 'Data',
@@ -995,7 +1012,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 58,
+		'idx': 59,
 		'label': 'Terms',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1007,7 +1024,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'tc_name',
 		'fieldtype': 'Link',
-		'idx': 59,
+		'idx': 60,
 		'label': 'Select Terms',
 		'oldfieldname': 'tc_name',
 		'oldfieldtype': 'Link',
@@ -1021,7 +1038,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 60,
+		'idx': 61,
 		'label': 'Get Terms',
 		'oldfieldtype': 'Button',
 		'options': 'get_tc_details',
@@ -1033,7 +1050,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 61,
+		'idx': 62,
 		'label': 'Terms HTML',
 		'oldfieldtype': 'HTML',
 		'options': 'You can add Terms and Notes that will be printed in the Transaction',
@@ -1046,7 +1063,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'terms',
 		'fieldtype': 'Text Editor',
-		'idx': 62,
+		'idx': 63,
 		'label': 'Term Details',
 		'oldfieldname': 'terms',
 		'oldfieldtype': 'Text Editor',
@@ -1060,7 +1077,7 @@
 		'description': 'Filling in additional information about the Sales Order will help you analyze your data better.',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 63,
+		'idx': 64,
 		'label': 'More Info',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1071,7 +1088,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 64,
+		'idx': 65,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -1084,7 +1101,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'letter_head',
 		'fieldtype': 'Select',
-		'idx': 65,
+		'idx': 66,
 		'label': 'Letter Head',
 		'oldfieldname': 'letter_head',
 		'oldfieldtype': 'Select',
@@ -1100,7 +1117,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'company',
 		'fieldtype': 'Link',
-		'idx': 66,
+		'idx': 67,
 		'in_filter': 1,
 		'label': 'Company',
 		'oldfieldname': 'company',
@@ -1119,7 +1136,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'fiscal_year',
 		'fieldtype': 'Select',
-		'idx': 67,
+		'idx': 68,
 		'in_filter': 1,
 		'label': 'Fiscal Year',
 		'oldfieldname': 'fiscal_year',
@@ -1139,7 +1156,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'select_print_heading',
 		'fieldtype': 'Link',
-		'idx': 68,
+		'idx': 69,
 		'label': 'Select Print Heading',
 		'no_copy': 1,
 		'oldfieldname': 'select_print_heading',
@@ -1154,7 +1171,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 69,
+		'idx': 70,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -1167,7 +1184,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'source',
 		'fieldtype': 'Select',
-		'idx': 70,
+		'idx': 71,
 		'label': 'Source',
 		'oldfieldname': 'source',
 		'oldfieldtype': 'Select',
@@ -1183,7 +1200,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'campaign',
 		'fieldtype': 'Link',
-		'idx': 71,
+		'idx': 72,
 		'label': 'Campaign',
 		'oldfieldname': 'campaign',
 		'oldfieldtype': 'Link',
@@ -1198,7 +1215,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'note',
 		'fieldtype': 'Text',
-		'idx': 72,
+		'idx': 73,
 		'label': 'Note',
 		'oldfieldname': 'note',
 		'oldfieldtype': 'Text',
@@ -1213,7 +1230,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'cancel_reason',
 		'fieldtype': 'Data',
-		'idx': 73,
+		'idx': 74,
 		'label': 'Cancel Reason',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1229,7 +1246,7 @@
 		'fieldname': 'delivery_status',
 		'fieldtype': 'Select',
 		'hidden': 1,
-		'idx': 74,
+		'idx': 75,
 		'label': 'Delivery Status',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1244,7 +1261,7 @@
 		'fieldname': 'billing_status',
 		'fieldtype': 'Select',
 		'hidden': 1,
-		'idx': 75,
+		'idx': 76,
 		'label': 'Billing Status',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1260,7 +1277,7 @@
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
 		'hidden': 0,
-		'idx': 76,
+		'idx': 77,
 		'label': 'Packing List',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1273,7 +1290,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'packing_details',
 		'fieldtype': 'Table',
-		'idx': 77,
+		'idx': 78,
 		'label': 'Packing Details',
 		'oldfieldname': 'packing_details',
 		'oldfieldtype': 'Table',
@@ -1286,7 +1303,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 78,
+		'idx': 79,
 		'label': 'Sales Team',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1300,7 +1317,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_partner',
 		'fieldtype': 'Link',
-		'idx': 79,
+		'idx': 80,
 		'in_filter': 1,
 		'label': 'Sales Partner',
 		'oldfieldname': 'sales_partner',
@@ -1318,7 +1335,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'commission_rate',
 		'fieldtype': 'Currency',
-		'idx': 80,
+		'idx': 81,
 		'label': 'Commission Rate',
 		'oldfieldname': 'commission_rate',
 		'oldfieldtype': 'Currency',
@@ -1333,7 +1350,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'total_commission',
 		'fieldtype': 'Currency',
-		'idx': 81,
+		'idx': 82,
 		'label': 'Total Commission',
 		'oldfieldname': 'total_commission',
 		'oldfieldtype': 'Currency',
@@ -1347,7 +1364,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_team',
 		'fieldtype': 'Table',
-		'idx': 82,
+		'idx': 83,
 		'label': 'Sales Team1',
 		'oldfieldname': 'sales_team',
 		'oldfieldtype': 'Table',
@@ -1361,7 +1378,7 @@
 		'allow_on_submit': 1,
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 83,
+		'idx': 84,
 		'label': 'Repair Sales Order',
 		'oldfieldtype': 'Button',
 		'options': 'repair_sales_order',
diff --git a/setup/doctype/email_settings/email_settings.py b/setup/doctype/email_settings/email_settings.py
index 37de7bc..ef0a763 100644
--- a/setup/doctype/email_settings/email_settings.py
+++ b/setup/doctype/email_settings/email_settings.py
@@ -13,7 +13,7 @@
 		for r in res:
 			ret[cstr(r[0])]=r[1] and cstr(r[1]) or ''
 				
-		return str(ret)
+		return ret
 
 	def set_cp_value(self, key):
 		"""
diff --git a/setup/doctype/workflow_rule/workflow_rule.py b/setup/doctype/workflow_rule/workflow_rule.py
index 3a8cc82..792cbf0 100644
--- a/setup/doctype/workflow_rule/workflow_rule.py
+++ b/setup/doctype/workflow_rule/workflow_rule.py
@@ -281,4 +281,4 @@
         elif cond_hold =='Yes':
           all_cond_hold ='Yes'
    
-    return all_cond_hold
\ No newline at end of file
+    return all_cond_hold
diff --git a/stock/doctype/delivery_note/delivery_note.py b/stock/doctype/delivery_note/delivery_note.py
index 74e6f8a..3534dad 100644
--- a/stock/doctype/delivery_note/delivery_note.py
+++ b/stock/doctype/delivery_note/delivery_note.py
@@ -40,15 +40,10 @@
   def validate_fiscal_year(self):
     get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
 
-  # ******************* Get Customer Details ***********************
-  #def get_customer_details(self):
-  #  sales_com_obj = get_obj('Sales Common')
-  #  sales_com_obj.get_customer_details(self)
-  #  sales_com_obj.get_shipping_details(self)
 
   # ****** Get contact person details based on customer selected ****
   def get_contact_details(self):
-    return cstr(get_obj('Sales Common').get_contact_details(self,0))
+    return get_obj('Sales Common').get_contact_details(self,0)
 
   # *********** Get Commission rate of Sales Partner ****************
   def get_comm_rate(self, sales_partner):
@@ -122,7 +117,7 @@
     ret = {
        'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
     }
-    return cstr(ret)
+    return ret
 
     
 # OTHER CHARGES TRIGGER FUNCTIONS
diff --git a/stock/doctype/delivery_note/delivery_note.txt b/stock/doctype/delivery_note/delivery_note.txt
index 97280e9..b77a6a5 100644
--- a/stock/doctype/delivery_note/delivery_note.txt
+++ b/stock/doctype/delivery_note/delivery_note.txt
@@ -3,16 +3,16 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2010-08-08 17:08:57',
+		'creation': '2011-04-18 15:58:20',
 		'docstatus': 0,
-		'modified': '2011-06-27 16:42:01',
+		'modified': '2011-08-09 17:10:45',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309173122',
+		'_last_update': '1311621379',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'document_type': 'Transaction',
@@ -27,7 +27,7 @@
 		'show_in_menu': 0,
 		'subject': 'To %(customer_name)s on %(transaction_date)s | %(per_billed)s% billed',
 		'tag_fields': 'billing_status',
-		'version': 444
+		'version': 446
 	},
 
 	# These values are common for all DocField
@@ -70,15 +70,15 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 2,
-		'permlevel': 1,
-		'role': 'Material User',
-		'submit': 0,
-		'write': 0
+		'permlevel': 0,
+		'role': 'Sales User',
+		'submit': 1,
+		'write': 1
 	},
 
 	# DocPerm
@@ -89,22 +89,22 @@
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
-		'role': 'Material Manager',
+		'role': 'Material Master Manager',
 		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 4,
-		'permlevel': 1,
+		'permlevel': 0,
 		'role': 'Material Manager',
-		'submit': 0,
-		'write': 0
+		'submit': 1,
+		'write': 1
 	},
 
 	# DocPerm
@@ -115,60 +115,25 @@
 		'doctype': 'DocPerm',
 		'idx': 5,
 		'permlevel': 0,
-		'role': 'Sales User',
+		'role': 'Sales Manager',
 		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 6,
 		'permlevel': 1,
-		'role': 'Sales User',
-		'submit': 0,
-		'write': 0
+		'role': 'All'
 	},
 
 	# DocPerm
 	{
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 7,
-		'permlevel': 0,
-		'role': 'Accounts User',
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 8,
-		'permlevel': 1,
-		'role': 'Accounts User'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 9,
-		'match': 'customer_name',
-		'permlevel': 0,
-		'role': 'Customer'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 10,
 		'permlevel': 2,
-		'role': 'All',
-		'write': 1
+		'role': 'All'
 	},
 
 	# DocField
@@ -332,7 +297,7 @@
 		'permlevel': 0,
 		'print_hide': 0,
 		'reqd': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '100px'
 	},
 
@@ -352,7 +317,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '150px'
 	},
 
@@ -366,13 +331,13 @@
 		'fieldtype': 'Currency',
 		'idx': 15,
 		'in_filter': 1,
-		'label': '% Qty Billed',
+		'label': '% Amount Billed',
 		'no_copy': 1,
 		'oldfieldname': 'per_billed',
 		'oldfieldtype': 'Currency',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -391,7 +356,7 @@
 		'oldfieldtype': 'Currency',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -439,7 +404,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -453,7 +418,7 @@
 		'options': 'Customer Group',
 		'permlevel': 0,
 		'print_hide': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -1014,7 +979,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '150px'
 	},
 
@@ -1032,7 +997,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '150px'
 	},
 
diff --git a/stock/doctype/item/item.py b/stock/doctype/item/item.py
index 7f0d3c2..b506541 100644
--- a/stock/doctype/item/item.py
+++ b/stock/doctype/item/item.py
@@ -27,7 +27,7 @@
 		ret = {
 			'tax_rate'	:	rate and flt(rate[0][0]) or 0
 		}
-		return str(ret)
+		return ret
 
 	def on_update(self):
 		bin = sql("select stock_uom from `tabBin` where item_code = '%s' " % self.doc.item_code)
@@ -169,7 +169,7 @@
 			'description'	:	file and file[0]['description'] or ''
 			
 		}
-		return str(ret)
+		return ret
 		
 	def check_if_sle_exists(self):
 		"""
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.py b/stock/doctype/purchase_receipt/purchase_receipt.py
index 0eda680..bb2b456 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -13,7 +13,7 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-	
+
 # -----------------------------------------------------------------------------------------
 
 from utilities.transaction_base import TransactionBase
@@ -38,23 +38,20 @@
 
   def get_default_schedule_date(self):
     get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
-    
+
 #-----------------Validation For Fiscal Year------------------------
   def validate_fiscal_year(self):
     get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')
-    
-  # Get Supplier Details 
-  #def get_supplier_details(self, name = ''):
-  #  return cstr(get_obj(dt='Purchase Common').get_supplier_details(name))
-  
+
+
   # Get Item Details
   def get_item_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_item_details(self,arg))
-  
+    return get_obj(dt='Purchase Common').get_item_details(self,arg)
+
   # Get UOM Details
   def get_uom_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
-  
+    return get_obj(dt='Purchase Common').get_uom_details(arg)
+
   # GET TERMS & CONDITIONS
   # =====================================================================================
   def get_tc_details(self):
@@ -62,16 +59,16 @@
 
   # get available qty at warehouse
   def get_bin_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_bin_details(arg))
+    return get_obj(dt='Purchase Common').get_bin_details(arg)
 
   # Pull Purchase Order
   def get_po_details(self):
     self.validate_prev_docname()
     get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
-  
+
   # validate if PO has been pulled twice
   def validate_prev_docname(self):
-    for d in getlist(self.doclist, 'purchase_receipt_details'): 
+    for d in getlist(self.doclist, 'purchase_receipt_details'):
       if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
         msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
         raise Exception
@@ -82,15 +79,15 @@
   # validate accepted and rejected qty
   def validate_accepted_rejected_qty(self):
     for d in getlist(self.doclist, "purchase_receipt_details"):
-      
-      # If Reject Qty than Rejected warehouse is mandatory    
+
+      # If Reject Qty than Rejected warehouse is mandatory
       if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
         msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
         raise Exception
 
-      # Check Received Qty = Accepted Qty + Rejected Qty 
+      # Check Received Qty = Accepted Qty + Rejected Qty
       if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
-        
+
         msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
         raise Exception
 
@@ -102,8 +99,8 @@
       if flt(self.doc.net_total) and flt(d.qty):
         #d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
         d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
-  
-  # Check for Stopped status 
+
+  # Check for Stopped status
   def check_for_stopped_status(self, pc_obj):
     check_list =[]
     for d in getlist(self.doclist, 'purchase_receipt_details'):
@@ -120,8 +117,8 @@
          if not d.prevdoc_docname:
            msgprint("Purchse Order No. required against item %s"%d.item_code)
            raise Exception
-    
-   
+
+
   # validate
   def validate(self):
     self.po_required()
@@ -140,20 +137,20 @@
     self.check_for_stopped_status(pc_obj)
 
     # get total in words
-    dcc = TransactionBase().get_company_currency(self.doc.company)    
+    dcc = TransactionBase().get_company_currency(self.doc.company)
     self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
     self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
     # update valuation rate
     self.update_valuation_rate()
 
-  
+
   # On Update
-  # ----------------------------------------------------------------------------------------------------    
+  # ----------------------------------------------------------------------------------------------------
   def on_update(self):
     if self.doc.rejected_warehouse:
       for d in getlist(self.doclist,'purchase_receipt_details'):
         d.rejected_warehouse = self.doc.rejected_warehouse
-    
+
     self.update_rw_material_detail()
     get_obj('Stock Ledger').scrub_serial_nos(self)
 
@@ -169,23 +166,23 @@
       # Check if is_stock_item == 'Yes'
       if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
         ord_qty = 0
-        pr_qty = flt(d.qty) * flt(d.conversion_factor) 
-        
-        # Check If Prevdoc Doctype is Purchase Order  
+        pr_qty = flt(d.qty) * flt(d.conversion_factor)
+
+        # Check If Prevdoc Doctype is Purchase Order
         if cstr(d.prevdoc_doctype) == 'Purchase Order':
-          # get qty and pending_qty of prevdoc 
+          # get qty and pending_qty of prevdoc
           curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name)
           max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
-          
+
           if flt(qty) + flt(pr_qty) > flt(max_qty):
             curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor)
           else:
             curr_qty = flt(pr_qty)
-          
+
           ord_qty = -flt(curr_qty)
           # update order qty in bin
           bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date)
-        
+
         # UPDATE actual qty to warehouse by pr_qty
         self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit)
         # UPDATE actual to rejected warehouse by rejected qty
@@ -208,8 +205,8 @@
       'posting_time'        : self.doc.posting_time,
       'voucher_type'        : 'Purchase Receipt',
       'voucher_no'          : self.doc.name,
-      'voucher_detail_no'   : d.name, 
-      'actual_qty'          : qty, 
+      'voucher_detail_no'   : d.name,
+      'actual_qty'          : qty,
       'stock_uom'           : d.stock_uom,
       'incoming_rate'       : in_value,
       'company'             : self.doc.company,
@@ -223,11 +220,11 @@
   def validate_inspection(self):
     for d in getlist(self.doclist, 'purchase_receipt_details'):     #Enter inspection date for all items that require inspection
       ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1)
-      ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'        
+      ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'
       if ins_reqd == 'Yes' and not d.qa_no:
         msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report")
 
-  # Check for Stopped status 
+  # Check for Stopped status
   def check_for_stopped_status(self, pc_obj):
     check_list =[]
     for d in getlist(self.doclist, 'purchase_receipt_details'):
@@ -236,7 +233,7 @@
         pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
 
 
-  # on submit        
+  # on submit
   def on_submit(self):
     # Check for Approving Authority
     get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
@@ -244,19 +241,19 @@
     # Set status as Submitted
     set(self.doc,'status', 'Submitted')
     pc_obj = get_obj('Purchase Common')
-      
+
     # Update Previous Doc i.e. update pending_qty and Status accordingly
     pc_obj.update_prevdoc_detail(self, is_submit = 1)
-        
+
     # Update Serial Record
     get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1)
 
-    # Update Stock 
+    # Update Stock
     self.update_stock(is_submit = 1)
-    
-    # Update last purchase rate 
+
+    # Update last purchase rate
     pc_obj.update_last_purchase_rate(self, 1)
-  
+
     # on submit notification
     get_obj('Notification Control').notify_contact('Purchase Receipt', self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
 
@@ -274,11 +271,11 @@
 
   def on_cancel(self):
     pc_obj = get_obj('Purchase Common')
-    
+
     self.check_for_stopped_status(pc_obj)
     # 1.Check if Payable Voucher has been submitted against current Purchase Order
     # pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
-    
+
     submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name)
     if submitted:
       msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
@@ -286,27 +283,27 @@
 
     # 2.Set Status as Cancelled
     set(self.doc,'status','Cancelled')
-    
-    # 3. Cancel Serial No   
+
+    # 3. Cancel Serial No
     get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1)
 
-    # 4.Update Bin  
+    # 4.Update Bin
     self.update_stock(is_submit = 0)
-    
-    # 5.Update Indents Pending Qty and accordingly it's Status 
+
+    # 5.Update Indents Pending Qty and accordingly it's Status
     pc_obj.update_prevdoc_detail(self, is_submit = 0)
 
-    # 6. Update last purchase rate 
+    # 6. Update last purchase rate
     pc_obj.update_last_purchase_rate(self, 0)
 
-        
+
 #----------- code for Sub-contracted Items -------------------
   #--------check for sub-contracted items and accordingly update PR raw material detail table--------
   def update_rw_material_detail(self):
-  
+
     for d in getlist(self.doclist,'purchase_receipt_details'):
       item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
-      
+
       if item_det[0][0] == 'Yes':
         if item_det[0][1] == 'Yes':
           if not self.doc.is_subcontracted:
@@ -315,7 +312,7 @@
           if self.doc.is_subcontracted == 'Yes':
             if not self.doc.supplier_warehouse:
               msgprint("Please Enter Supplier Warehouse for subcontracted Items")
-              raise Exception         
+              raise Exception
             self.add_bom(d)
           else:
             self.doc.clear_table(self.doclist,'pr_raw_material_details',1)
@@ -325,7 +322,7 @@
             msgprint("Please Enter Supplier Warehouse for subcontracted Items")
             raise Exception
           self.add_bom(d)
-        
+
       self.delete_irrelevant_raw_material()
       #---------------calculate amt in  PR Raw Material Detail-------------
       self.calculate_amount(d)
@@ -341,7 +338,7 @@
       #-------------- add child function--------------------
       chgd_rqd_qty = []
       for i in bom_det:
-        
+
         if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
 
           rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist)
@@ -350,7 +347,7 @@
           rm_child.bom_detail_no = i and i[6] or ''
           rm_child.main_item_code = i and i[0] or ''
           rm_child.rm_item_code = i and i[1] or ''
-          rm_child.description = i and i[7] or ''          
+          rm_child.description = i and i[7] or ''
           rm_child.stock_uom = i and i[5] or ''
           rm_child.rate = i and flt(i[3]) or flt(i[4])
           rm_child.conversion_factor = d.conversion_factor
@@ -366,7 +363,7 @@
               chgd_rqd_qty.append(cstr(i[1]))
               pr_rmd.main_item_code = i[0]
               pr_rmd.rm_item_code = i[1]
-              pr_rmd.description = i[7]              
+              pr_rmd.description = i[7]
               pr_rmd.stock_uom = i[5]
               pr_rmd.required_qty = flt(act_qty)
               pr_rmd.consumed_qty = flt(act_qty)
@@ -375,20 +372,20 @@
               pr_rmd.save()
       if chgd_rqd_qty:
         msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0])))
-              
+
 
   # Delete irrelevant raw material from PR Raw material details
-  #--------------------------------------------------------------  
+  #--------------------------------------------------------------
   def delete_irrelevant_raw_material(self):
     for d in getlist(self.doclist,'pr_raw_material_details'):
       if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
         d.parent = 'old_par:'+self.doc.name
         d.save()
-    
+
   def calculate_amount(self, d):
     amt = 0
     for i in getlist(self.doclist,'pr_raw_material_details'):
-      
+
       if(i.reference_name == d.name):
         #if i.consumed_qty == 0:
          # msgprint("consumed qty cannot be 0. Please Enter consumed qty ")
@@ -397,7 +394,7 @@
         amt += i.amount
     d.rm_supp_cost = amt
     d.save()
-    
+
 
   # --------------- Back Flush function called on submit and on cancel from update stock
   def bk_flush_supp_wh(self, is_submit):
@@ -405,7 +402,7 @@
       #--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled
       consumed_qty = - flt(d.consumed_qty)
       self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit)
-      
+
 
   # get current_stock
   # ----------------
@@ -414,13 +411,13 @@
       if self.doc.supplier_warehouse:
         bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1)
         d.current_stock = bin and flt(bin[0]['actual_qty']) or 0
-        
-        
-        
+
+
+
 
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
-  
+
   # *********** Get Tax rate if account type is TAX ********************
   def get_rate(self,arg):
     return get_obj('Purchase Common').get_rate(arg,self)
diff --git a/stock/doctype/sales_bom/sales_bom.py b/stock/doctype/sales_bom/sales_bom.py
index 3bd6fa5..ce4567e 100644
--- a/stock/doctype/sales_bom/sales_bom.py
+++ b/stock/doctype/sales_bom/sales_bom.py
@@ -38,7 +38,7 @@
   def get_item_details(self, name):
     det = sql("select description, stock_uom from `tabItem` where name = '%s' " % cstr(name))
     rate = sql("select ref_rate from `tabRef Rate Detail` where price_list_name = %s and parent = %s and ref_currency = %s", (self.doc.price_list, name, self.doc.currency))
-    return cstr({'description' : det and det[0][0] or '', 'uom': det and det[0][1] or '', 'rate': rate and flt(rate[0][0]) or 0.00})
+    return {'description' : det and det[0][0] or '', 'uom': det and det[0][1] or '', 'rate': rate and flt(rate[0][0]) or 0.00}
 
 
   def get_main_item(self):
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index b380995..47f0394 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -54,7 +54,7 @@
 			'conversion_factor'		: 1,
      		'batch_no'          	: ''
 		}
-		return str(ret)
+		return ret
 
 
 	# Get UOM Details
@@ -70,7 +70,7 @@
 				'conversion_factor'		: flt(uom[0]['conversion_factor']),
 				'transfer_qty'			: flt(arg['qty']) * flt(uom[0]['conversion_factor']),
 			}
-		return str(ret)
+		return ret
 
 		
 	# get stock and incoming rate on posting date
@@ -396,7 +396,7 @@
 			'customer_name'		: res and res[0][1] or '',
 			'customer_address' : res and res[0][2] or ''}
 
-		return str(ret)
+		return ret
 
 
 	def get_cust_addr(self):
@@ -405,7 +405,7 @@
 			'customer_name'		: res and res[0][0] or '',
 			'customer_address' : res and res[0][1] or ''}
 
-		return str(ret)
+		return ret
 
 
 		
@@ -415,7 +415,7 @@
 			'supplier' : res and res[0][0] or '',
 			'supplier_name' :res and res[0][1] or '',
 			'supplier_address' : res and res[0][2] or ''}
-		return str(ret)
+		return ret
 		
 
 	def get_supp_addr(self):
@@ -423,4 +423,4 @@
 		ret = {
 			'supplier_name' : res and res[0][0] or '',
 			'supplier_address' : res and res[0][1] or ''}
-		return str(ret)
+		return ret
diff --git a/stock/doctype/stock_ledger/stock_ledger.py b/stock/doctype/stock_ledger/stock_ledger.py
index e67afa6..5188e08 100644
--- a/stock/doctype/stock_ledger/stock_ledger.py
+++ b/stock/doctype/stock_ledger/stock_ledger.py
@@ -13,7 +13,7 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-	
+
 # -----------------------------------------------------------------------------------------
 
 def get_sr_no_list(sr_nos, qty = 0):
@@ -55,15 +55,17 @@
 				serial_nos = self.get_sr_no_list(d.serial_no)
 				for s in serial_nos:
 					s = s.strip()
-					sr_war =	sql("select warehouse from `tabSerial No` where name = '%s'" % (s))
+					sr_war = sql("select warehouse,name from `tabSerial No` where name = '%s'" % (s))
 					if not sr_war:
+						msgprint("Serial No %s does not exists",s, raise_exception = 1)
+					elif not sr_war[0][0]:
 						msgprint("Please set a warehouse in the Serial No <b>%s</b>" % s, raise_exception = 1)
-					if sr_war[0][0] != d.warehouse:
+					elif sr_war[0][0] != d.warehouse:
 						msgprint("Serial No : %s for Item : %s doesn't exists in Warehouse : %s" % (s, d.item_code, d.warehouse), raise_exception = 1)
-					
+
 
 	# ------------------------------------
-	# check whether serial no is required	
+	# check whether serial no is required
 	# ------------------------------------
 	def validate_serial_no(self, obj, fname):
 		for d in getlist(obj.doclist, fname):
@@ -76,9 +78,9 @@
 					msgprint("If serial no required, please select 'Yes' in 'Has Serial No' in Item :" + d.item_code + ', otherwise please remove serial no', raise_exception=1)
 			elif ar_required == 'Yes' and not d.serial_no:
 				msgprint("Serial no is mandatory for item: "+ d.item_code, raise_exception = 1)
-			
 
-	
+
+
 	# -------------------
 	# get serial no list
 	# -------------------
@@ -90,27 +92,27 @@
 	# ---------------------
 	def set_pur_serial_no_values(self, obj, serial_no, d, s, new_rec):
 		item_details = sql("select item_group, warranty_period from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now()) " %(d.item_code), as_dict=1)
-		s.purchase_document_type =	 obj.doc.doctype
-		s.purchase_document_no	 =	 obj.doc.name
-		s.purchase_date					=	 obj.doc.posting_date
-		s.purchase_time					=	 obj.doc.posting_time
-		s.purchase_rate					=	 d.purchase_rate or d.incoming_rate
-		s.item_code						=	 d.item_code
-		s.brand							=	 d.brand
-		s.description					=	 d.description
-		s.item_group					=	 item_details and item_details[0]['item_group'] or ''
-		s.warranty_period				=	 item_details and item_details[0]['warranty_period'] or 0
-		s.supplier						=	 obj.doc.supplier
-		s.supplier_name					=	 obj.doc.supplier_name
-		s.supplier_address			 	=	 obj.doc.supplier_address
-		s.warehouse						=	 d.warehouse or d.t_warehouse
-		s.docstatus						=	 0
-		s.status						=	 'In Store'
-		s.modified						=	 nowdate()
-		s.modified_by					=	 session['user']
-		s.serial_no						=	 serial_no
-		s.fiscal_year					=	 obj.doc.fiscal_year
-		s.company						=	 obj.doc.company
+		s.purchase_document_type=	 obj.doc.doctype
+		s.purchase_document_no	=	 obj.doc.name
+		s.purchase_date		=	 obj.doc.posting_date
+		s.purchase_time		=	 obj.doc.posting_time
+		s.purchase_rate		=	 d.purchase_rate or d.incoming_rate
+		s.item_code		=	 d.item_code
+		s.brand			=	 d.brand
+		s.description		=	 d.description
+		s.item_group		=	 item_details and item_details[0]['item_group'] or ''
+		s.warranty_period	=	 item_details and item_details[0]['warranty_period'] or 0
+		s.supplier		=	 obj.doc.supplier
+		s.supplier_name		=	 obj.doc.supplier_name
+		s.supplier_address	=	 obj.doc.supplier_address
+		s.warehouse		=	 d.warehouse or d.t_warehouse
+		s.docstatus		=	 0
+		s.status		=	 'In Store'
+		s.modified		=	 nowdate()
+		s.modified_by		=	 session['user']
+		s.serial_no		=	 serial_no
+		s.fiscal_year		=	 obj.doc.fiscal_year
+		s.company		=	 obj.doc.company
 		s.save(new_rec)
 
 
@@ -227,7 +229,7 @@
 		sle = Document(doctype = 'Stock Ledger Entry')
 		for k in args.keys():
 			# adds warehouse_type
-			if k == 'warehouse': 
+			if k == 'warehouse':
 				sle.fields['warehouse_type'] = get_value('Warehouse' , args[k], 'warehouse_type')
 			sle.fields[k] = args[k]
 		sle_obj = get_obj(doc=sle)
@@ -235,7 +237,7 @@
 		sle_obj.validate()
 		sle.save(new = 1)
 		return sle.name
-		
+
 	def repost(self):
 		"""
 		Repost everything!
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 e603d1f..f8ac737 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
@@ -22,7 +22,7 @@
     self.doc, self.doclist = d,dl
 
   def get_stock_uom(self, item_code):
-    return cstr({'current_stock_uom': cstr(get_value('Item', item_code, 'stock_uom'))})
+    return {'current_stock_uom': cstr(get_value('Item', item_code, 'stock_uom'))}
   
   def validate_mandatory(self):
     if not cstr(self.doc.item_code):
diff --git a/support/doctype/customer_issue/customer_issue.py b/support/doctype/customer_issue/customer_issue.py
index db63cc2..12a8ebd 100644
--- a/support/doctype/customer_issue/customer_issue.py
+++ b/support/doctype/customer_issue/customer_issue.py
@@ -27,37 +27,6 @@
   def autoname(self):
     #self.doc.name = make_autoname('CI/' + self.doc.fiscal_year + '/.######')
     self.doc.name = make_autoname(self.doc.naming_series + '.######')
-
-  #def get_customer_details(self):
-  #  details = sql("select address, territory, customer_group, customer_name from `tabCustomer` where name = '%s' and docstatus != 2" %(self.doc.customer), as_dict = 1)
-  #  if details:
-  #    ret = {
-  #      'customer_address'  :  details and details[0]['address'] or '',
-  #      'customer_name'  :  details and details[0]['customer_name'] or '',
-  #      'territory'       :  details and details[0]['territory'] or '',
-  #      'customer_group'    :  details and details[0]['customer_group'] or ''
-  #    }
-  #    # ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
-  #    contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where customer_name = '%s' and is_customer = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(self.doc.customer), as_dict = 1)
-  #    ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
-  #    ret['contact_no']     = contact_det and contact_det[0]['contact_no'] or ''
-  #    ret['email_id']       = contact_det and contact_det[0]['email_id'] or ''
-  #  
-  #    return cstr(ret)
-  #  else:
-  #    msgprint("Customer : %s does not exist in system." % (name))
-  #    raise Exception
-
-  # Get customer's contact person details
-  # ==============================================================
-  #def get_contact_details(self):
-  #  contact = sql("select contact_no, email_id from `tabContact` where contact_name = '%s' and customer_name = '%s' and docstatus != 2" %(self.doc.contact_person, self.doc.customer), as_dict = 1)
-  #  ret = {
-  #    'contact_no'       :    contact and contact[0]['contact_no'] or '',
-  #    'email_id'         :    contact and contact[0]['email_id'] or ''
-  #  }
-  #  return str(ret)
-    
     
 #check if maintenance schedule already generated
 #============================================
@@ -66,7 +35,7 @@
     nm = nm and nm[0][0] or ''
     
     if not nm:
-      return cstr('No')    
+      return 'No'
   
   def on_submit(self):
     if session['user'] != 'Guest':
diff --git a/support/doctype/maintenance_schedule/maintenance_schedule.py b/support/doctype/maintenance_schedule/maintenance_schedule.py
index 0d6ef80..d5c90b5 100644
--- a/support/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/support/doctype/maintenance_schedule/maintenance_schedule.py
@@ -38,21 +38,8 @@
       'item_name': item and item[0]['item_name'] or '',
       'description' : item and item[0]['description'] or ''
     }
-    return str(ret)
-  
-  #pull customer details
-  #-------------------------
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name,t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = %s and t1.name=t2.customer and t2.is_primary_contact = 'Yes'", self.doc.customer, as_dict=1)
-  #  
-  #  ret = {
-  #    'customer_name':  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-  #  return str(ret)
-  
+    return ret
+    
   # generate maintenance schedule
   #-------------------------------------
   def generate_schedule(self):
@@ -132,7 +119,7 @@
       count = period/365
     
     ret = {'no_of_visits':count}
-    return str(ret)
+    return ret
   
   def validate_maintenance_detail(self):
     if not getlist(self.doclist, 'item_maintenance_detail'):
diff --git a/support/doctype/maintenance_visit/maintenance_visit.py b/support/doctype/maintenance_visit/maintenance_visit.py
index 203793c..e4efe1c 100644
--- a/support/doctype/maintenance_visit/maintenance_visit.py
+++ b/support/doctype/maintenance_visit/maintenance_visit.py
@@ -31,20 +31,7 @@
       'item_name' : item and item[0]['item_name'] or '',
       'description' : item and item[0]['description'] or ''
     }
-    return str(ret)
-  
-  #get customer details
-  #-----------------------
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name,t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = %s and t1.name=t2.customer and t2.is_primary_contact = 'Yes'", self.doc.customer, as_dict=1)
-  #  
-  #  ret = {
-  #    'customer_name' :  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-  #  return str(ret)
+    return ret
   
   # fetch details of resp Sales order or customer issue
   #-----------------------------------------------------------
diff --git a/utilities/doctype/file_browser_control/file_browser_control.py b/utilities/doctype/file_browser_control/file_browser_control.py
index 8008ae9..d5ad0cc 100644
--- a/utilities/doctype/file_browser_control/file_browser_control.py
+++ b/utilities/doctype/file_browser_control/file_browser_control.py
@@ -69,7 +69,7 @@
             'name'  :   f_obj.doc.name,
             'label' :   f_obj.doc.file_name
         }
-        return cstr(ret)
+        return ret
     
     # Update changes done to selected file group.
     def update_grp(self,arg):
@@ -160,7 +160,7 @@
                     'file_name' :   f.file_name
                 }
                     
-                return cstr(ret)
+                return ret
             else:
                 return 'No file found.'
         else:
@@ -195,4 +195,4 @@
     def get_privileges(self,arg):
         arg = eval(arg)
         privilege = convert_to_lists(sql("select ifnull(can_edit,''), ifnull(can_view,''),owner from `tab%s` where name='%s'" % (arg['dt'],arg['dn'])))
-        return privilege
\ No newline at end of file
+        return privilege
diff --git a/utilities/transaction_base.py b/utilities/transaction_base.py
index 332e201..3678298 100644
--- a/utilities/transaction_base.py
+++ b/utilities/transaction_base.py
@@ -53,7 +53,7 @@
 			'contact_email' : contact_email,
 			'contact_mobile' : contact_mobile
 		}
-		return cstr(ret)	
+		return ret	
 			
 	# Get Address Text
 	# -----------------------
@@ -125,7 +125,7 @@
 			'shipping_address_name' : details and details[0]['name'] or '',
 			'shipping_address' : address_display
 		}
-		return cstr(ret)
+		return ret
 		
 	# Get Lead Details
 	# -----------------------
@@ -144,7 +144,7 @@
 			'contact_mobile' : extract('mobile_no'),
 			'contact_email' : extract('email_id')
 		}
-		return cstr(ret)
+		return ret
 		
 		
 	# Get Supplier Default Primary Address - first load
@@ -162,7 +162,7 @@
 			'contact_mobile' : contact_mobile						
 		}
 		ret.update(self.get_supplier_details(args['supplier']))
-		return cstr(ret)
+		return ret
 		
 	# Get Supplier Address
 	# -----------------------
@@ -178,7 +178,7 @@
 			'contact_email' : contact_email,
 			'contact_mobile' : contact_mobile
 		}
-		return cstr(ret)	
+		return ret
 	
 	# Get Supplier Details
 	# -----------------------