fixes to my_company, added secrity settings to restrict by ip, timings
diff --git a/accounts/doctype/loan/__init__.py b/accounts/doctype/loan/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/accounts/doctype/loan/__init__.py
+++ /dev/null
diff --git a/accounts/doctype/loan/loan.js b/accounts/doctype/loan/loan.js
deleted file mode 100644
index 5a45362..0000000
--- a/accounts/doctype/loan/loan.js
+++ /dev/null
@@ -1,54 +0,0 @@
-$.extend(cur_frm.cscript, {
-	Generate: function(doc, dt, dn) {
-		cur_frm.cscript.clear_installments(doc);
-		for(var i=0; i< doc.no_of_installments; i++) {
-			d = LocalDB.add_child(doc, 'Loan Installment', 'installments');
-			d.amount = doc.loan_amount / doc.no_of_installments;
-			d.due_date = dateutil.add_months(doc.start_date, i+1);
-		}
-		cur_frm.refresh();
-	},
-/*	submit:function(doc){
-		data=doc.get_values();
-
-		data['']=
-		$c_obj(make_doclist(dt,dn),'loan_post',data,function(){});
-	},*/
-	refresh: function(doc) {
-		cur_frm.cscript.hide_show_buttons(doc);
-	},
-	hide_show_buttons: function(doc) {
-		if(doc.docstatus==0) {
-			hide_field('Installment Reciept'); unhide_field('Generate');
-		} else if (doc.docstatus==1) {
-			unhide_field('Installment Reciept');hide_field('Generate');
-		}
-	},
-	clear_installments: function(doc) {
-		$.each(getchildren('Loan Installment', doc.name, 'installments', 'Loan'),
-			function(i, d) {
-				LocalDB.delete_doc('Loan Installment', d.name);
-			}
-		)
-	},
-	'Installment Reciept': function(doc, dt, dn) {
-		var d = new wn.widgets.Dialog({
-			width: 500,
-			title: 'Add a new payment installment',
-			fields: [
-				{fieldtype:'Data', label:'Cheque Number', fieldname:'cheque_number', reqd:1},
-				{fieldtype:'Date', label:'Cheque Date', fieldname:'cheque_date', reqd:1},
-				{fieldtype:'Link', label:'Bank Account', fieldname:'bank_account', reqd:1, options:'Account'},
-				{fieldtype:'Button', label:'Update',fieldname:'update'}
-			]
-		})
-		d.show();
-		d.fields_dict.update.input.onclick = function() {
-			var data = d.get_values();
-
-			if(data) {
-				$c_obj(make_doclist(dt,dn),'loan_installment_post',data,function(){cur_frm.refresh(); d.hide();});
-			}
-		}
-	}
-})
diff --git a/accounts/doctype/loan/loan.py b/accounts/doctype/loan/loan.py
deleted file mode 100644
index 9f0bcb5..0000000
--- a/accounts/doctype/loan/loan.py
+++ /dev/null
@@ -1,48 +0,0 @@
-import webnotes
-from webnotes.model.doc import make_autoname, Document, addchild
-from webnotes import msgprint
-from webnotes.utils import get_defaults
-import json
-from accounts.utils import post_jv
-sql = webnotes.conn.sql
-
-class DocType:
-	def __init__(self, doc, doclist):
-		self.doc, self.doclist = doc, doclist
-
-	def autoname(self):
-		"""
-			Create Loan Id using naming_series pattern
-		"""
-		self.doc.name = make_autoname(self.doc.naming_series+ '.#####')
-
-	def loan_post(self):
-		data['voucher_type']='Loan Issue'
-		data['naming_series']='JV'
-		data['fiscal_year'] = get_defaults()['fiscal_year'] # To be modified to take care
-		data['company'] = get_defaults()['company']
-		data['debit_account'] = self.doc['receivable_account']
-		data['credit_account'] = self.doc['account']
-		data['amount'] = self.doc.loan_amount
-		jv_name=post_jv(data)
-
-	def loan_installment_post(self, args):
-		"""
-			Posts the loan receipt into Journal Voucher
-		"""
-		next_inst = sql("select amount,name from `tabLoan Installment` where parent=%s and ifnull(cheque_number,'')='' order by due_date limit 1",self.doc.name)
-
-		data = json.loads(args)
-		data['voucher_type']='Loan Receipt'
-		data['naming_series']='JV'
-		data['amount']=next_inst[0][0]
-		data['debit_account']=data.get('bank_account')
-		data['credit_account']=self.doc.account
-		data['fiscal_year']=get_defaults()['fiscal_year']
-		data['company']=get_defaults()['company']
-		jv_name=post_jv(data)
-
-		sql("update `tabLoan Installment` set cheque_number=%s, cheque_date=%s, jv_number=%s where name=%s",(data.get('cheque_number'),data.get('cheque_date'),jv_name,next_inst[0][1]))
-
-		self.doclist = [Document(d.doctype, d.name) for d in self.doclist]
-
diff --git a/accounts/doctype/loan/loan.txt b/accounts/doctype/loan/loan.txt
deleted file mode 100644
index 001e1d3..0000000
--- a/accounts/doctype/loan/loan.txt
+++ /dev/null
@@ -1,172 +0,0 @@
-# DocType, Loan
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2011-07-15 10:35:26',
-		'docstatus': 0,
-		'modified': '2011-07-18 12:12:19',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
-	},
-
-	# These values are common for all DocType
-	{
-		'_last_update': '1310963215',
-		'colour': 'White:FFF',
-		'doctype': 'DocType',
-		'module': 'Accounts',
-		'name': '__common__',
-		'section_style': 'Simple',
-		'show_in_menu': 0,
-		'version': 15
-	},
-
-	# These values are common for all DocField
-	{
-		'doctype': 'DocField',
-		'name': '__common__',
-		'parent': 'Loan',
-		'parentfield': 'fields',
-		'parenttype': 'DocType',
-		'permlevel': 0
-	},
-
-	# These values are common for all DocPerm
-	{
-		'doctype': 'DocPerm',
-		'name': '__common__',
-		'parent': 'Loan',
-		'parentfield': 'permissions',
-		'parenttype': 'DocType',
-		'read': 1,
-		'role': 'Accounts User'
-	},
-
-	# DocType, Loan
-	{
-		'doctype': 'DocType',
-		'name': 'Loan'
-	},
-
-	# DocPerm
-	{
-		'cancel': 1,
-		'create': 1,
-		'doctype': 'DocPerm',
-		'idx': 1,
-		'permlevel': 0,
-		'submit': 1,
-		'write': 1
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 2,
-		'permlevel': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'naming_series',
-		'fieldtype': 'Select',
-		'idx': 1,
-		'label': 'Naming Series',
-		'options': '\nLOAN',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'account',
-		'fieldtype': 'Link',
-		'idx': 2,
-		'label': 'Account',
-		'options': 'Account',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'receivable_account',
-		'fieldtype': 'Link',
-		'idx': 3,
-		'label': 'Receivable Account',
-		'options': 'Account'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'invoice',
-		'fieldtype': 'Link',
-		'idx': 4,
-		'label': 'Invoice',
-		'options': 'Receivable Voucher',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'loan_amount',
-		'fieldtype': 'Currency',
-		'idx': 5,
-		'label': 'Loan Amount',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'start_date',
-		'fieldtype': 'Date',
-		'idx': 6,
-		'label': 'Start Date',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'no_of_installments',
-		'fieldtype': 'Int',
-		'idx': 7,
-		'label': 'No of Installments',
-		'reqd': 1
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'idx': 8,
-		'label': 'Generate',
-		'trigger': 'Client'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'installments',
-		'fieldtype': 'Table',
-		'idx': 9,
-		'label': 'Installments',
-		'options': 'Loan Installment'
-	},
-
-	# DocField
-	{
-		'allow_on_submit': 1,
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'idx': 10,
-		'label': 'Installment Reciept'
-	}
-]
\ No newline at end of file
diff --git a/accounts/doctype/loan/test_loan.py b/accounts/doctype/loan/test_loan.py
deleted file mode 100644
index 4e72559..0000000
--- a/accounts/doctype/loan/test_loan.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import unittest
-import webnotes
-from webnotes.model.code import get_obj
-
-class TestScheduleGeneartion(unittest.TestCase):
-	def setUp(self):
-		webnotes.conn.begin()
-		# create a mock loan
-		self.loan = get_obj('Loan', 'LOAN00001')
-		
-	def test_generation(self):
-		"test the genaration of loan installments"
-		self.loan.generate()
-		self.assertEqual(self.loan.get_installment_total(), self.loan.doc.loan_amount)
-		
-	def tearDown(self):
-		webnotes.conn.rollback()
diff --git a/accounts/doctype/loan_installment/__init__.py b/accounts/doctype/loan_installment/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/accounts/doctype/loan_installment/__init__.py
+++ /dev/null
diff --git a/accounts/doctype/loan_installment/loan_installment.txt b/accounts/doctype/loan_installment/loan_installment.txt
deleted file mode 100644
index f729e34..0000000
--- a/accounts/doctype/loan_installment/loan_installment.txt
+++ /dev/null
@@ -1,111 +0,0 @@
-# DocType, Loan Installment
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2011-07-15 10:36:42',
-		'docstatus': 0,
-		'modified': '2011-07-15 15:48:34',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
-	},
-
-	# These values are common for all DocType
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocType',
-		'istable': 1,
-		'module': 'Accounts',
-		'name': '__common__',
-		'section_style': 'Simple',
-		'show_in_menu': 0,
-		'version': 4
-	},
-
-	# These values are common for all DocField
-	{
-		'doctype': 'DocField',
-		'name': '__common__',
-		'parent': 'Loan Installment',
-		'parentfield': 'fields',
-		'parenttype': 'DocType'
-	},
-
-	# DocType, Loan Installment
-	{
-		'doctype': 'DocType',
-		'name': 'Loan Installment'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'amount',
-		'fieldtype': 'Currency',
-		'idx': 1,
-		'label': 'Amount',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'due_date',
-		'fieldtype': 'Date',
-		'idx': 2,
-		'label': 'Due Date',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'cheque_number',
-		'fieldtype': 'Data',
-		'idx': 3,
-		'label': 'Cheque Number',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'cheque_date',
-		'fieldtype': 'Date',
-		'idx': 4,
-		'label': 'Cheque Date',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'deposit_date',
-		'fieldtype': 'Date',
-		'idx': 5,
-		'label': 'Deposit Date',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'realized_date',
-		'fieldtype': 'Date',
-		'idx': 6,
-		'label': 'Realized Date',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'jv_number',
-		'fieldtype': 'Link',
-		'hidden': 0,
-		'idx': 7,
-		'label': 'JV Number',
-		'options': 'Journal Voucher',
-		'permlevel': 1
-	}
-]
\ No newline at end of file
diff --git a/accounts/search_criteria/budget_variance_report/budget_variance_report.js b/accounts/search_criteria/budget_variance_report/budget_variance_report.js
index ed5adb1..08c9693 100644
--- a/accounts/search_criteria/budget_variance_report/budget_variance_report.js
+++ b/accounts/search_criteria/budget_variance_report/budget_variance_report.js
@@ -1,17 +1,15 @@
 report.customize_filters = function() {
-
-  //this.hide_all_filters();
-  this.mytabs.items['Select Columns'].hide();
-  this.mytabs.items['More Filters'].hide();
-
- 
   this.add_filter({fieldname:'period', label:'Period', fieldtype:'Select', options:'Monthly'+NEWLINE+'Quarterly'+NEWLINE+'Half Yearly'+NEWLINE+'Annual',report_default:'Quarterly',ignore : 1, parent:'Budget Detail'});
+  this.add_filter({fieldname:'company', label:'Company', fieldtype:'Link',  options:'Company', report_default:sys_defaults.company, ignore : 1, parent:'Budget Detail', in_first_page:1});
   this.filter_fields_dict['Budget Detail'+FILTER_SEP +'Fiscal Year'].df.in_first_page = 1;
   this.filter_fields_dict['Budget Detail'+FILTER_SEP +'Period'].df.in_first_page = 1;
 
   this.filter_fields_dict['Budget Detail'+FILTER_SEP +'Fiscal Year'].df['report_default'] = sys_defaults.fiscal_year;
 }
+
 report.aftertableprint = function(t) {
    $yt(t,'*',1,{whiteSpace:'pre'});
 }
+
+this.mytabs.items['More Filters'].hide();
 this.mytabs.items['Select Columns'].hide();
diff --git a/accounts/search_criteria/budget_variance_report/budget_variance_report.py b/accounts/search_criteria/budget_variance_report/budget_variance_report.py
index 182f9e5..9f7c690 100644
--- a/accounts/search_criteria/budget_variance_report/budget_variance_report.py
+++ b/accounts/search_criteria/budget_variance_report/budget_variance_report.py
@@ -131,11 +131,6 @@
     col_idx[str(c) + n ] = len(colnames) - 1
 
 
-
-# make default columns
-#coltypes[col_idx[based_on]] = 'Link'
-#coloptions[col_idx[based_on]]= based_on
-
 # get start date
 start_date = get_value('Fiscal Year', fiscal_year, 'year_start_date')
 if not start_date:
@@ -162,7 +157,7 @@
 
     ch = make_child_lst(based_on,r[0].strip())
    
-    actual = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1, `tabAccount` t2 where t2.is_pl_account = 'Yes' and t1.is_cancelled = 'No' and t1.cost_center in %s and t2.debit_or_credit = 'Debit' and t1.posting_date between '%s' and '%s' and t1.account = t2.name"%(ch, mon_list[count][data['start_date']], mon_list[count][data['end_date']]))
+    actual = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1, `tabAccount` t2 where ifnull(t2.is_pl_account, 'No') = 'Yes' and ifnull(t1.is_cancelled, 'No') = 'No' and t1.cost_center in %s and t2.debit_or_credit = 'Debit' and t1.posting_date between '%s' and '%s' and t1.account = t2.name"%(ch, mon_list[count][data['start_date']], mon_list[count][data['end_date']]))
    
     #----------------------------------------------------------
     actual = flt(actual[0][0])
diff --git a/accounts/search_criteria/budget_variance_report/budget_variance_report.sql b/accounts/search_criteria/budget_variance_report/budget_variance_report.sql
index d53f7e1..575fbfb 100644
--- a/accounts/search_criteria/budget_variance_report/budget_variance_report.sql
+++ b/accounts/search_criteria/budget_variance_report/budget_variance_report.sql
@@ -1 +1,10 @@
-SELECT CONCAT(REPEAT('     ', COUNT(parent.name) - 1), node.name) AS name FROM `tabCost Center` AS node,`tabCost Center` AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.docstatus !=2 GROUP BY node.name ORDER BY node.lft
\ No newline at end of file
+SELECT 
+	CONCAT(REPEAT('     ', COUNT(parent.name) - 1), node.name) AS name 
+FROM 
+	`tabCost Center` AS node,`tabCost Center` AS parent 
+WHERE 
+	node.lft BETWEEN parent.lft AND parent.rgt 
+	AND node.docstatus !=2
+	AND node.company_name like '%(company)s%%'
+GROUP BY node.name 
+ORDER BY node.lft
diff --git a/home/page/my_company/my_company.js b/home/page/my_company/my_company.js
index 0850607..c2a55ea 100644
--- a/home/page/my_company/my_company.js
+++ b/home/page/my_company/my_company.js
@@ -134,24 +134,28 @@
 MemberList.prototype.make_list = function() {
 	var me = this;
 	this.lst_area = $a(this.list_wrapper, 'div');
-	this.lst = new Listing('Profiles',1);
-	this.lst.colwidths = ['100%'];
-	this.lst.opts.cell_style = {padding:'0px'}
-	this.lst.get_query = function() {
-		var c1 = '';
-		if(me.search_inp.value && me.search_inp.value != 'Search') {
-			var c1 = repl(' AND (first_name LIKE "%(txt)s" OR last_name LIKE "%(txt)s" OR name LIKE "%(txt)s")', {txt:'%' + me.search_inp.value + '%'});
+
+	this.lst = new wn.widgets.Listing({
+		parent: this.lst_area,
+		as_dict: 1,
+		get_query: function() {
+			var c1 = '';
+			if(me.search_inp.value && me.search_inp.value != 'Search') {
+				var c1 = repl(' AND (first_name LIKE "%(txt)s" OR last_name LIKE "%(txt)s" OR name LIKE "%(txt)s")', {txt:'%' + me.search_inp.value + '%'});
+			}
+
+			return repl("SELECT name, \
+				ifnull(concat_ws(' ', first_name, last_name),'') as full_name, \
+				gender, file_list, enabled \
+				FROM tabProfile \
+				WHERE docstatus != 2 \
+				AND name not in ('Guest','Administrator') %(cond)s \
+				ORDER BY name asc",{cond:c1});			
+		},
+		render_row: function(parent, data) {
+			me.member_items[data.name] = new MemberItem(parent, data, me);			
 		}
-		
-		this.query = repl("SELECT distinct ifnull(name,''), ifnull(concat_ws(' ', first_name, last_name),''), \
-			ifnull(messanger_status,''), ifnull(gender,''), ifnull(file_list,''), 0, enabled, last_login \
-			from tabProfile where docstatus != 2 AND name not in ('Guest','Administrator') %(cond)s \
-			ORDER BY name asc",{cond:c1});
-	}
-	this.lst.make(this.lst_area);
-	this.lst.show_cell= function(cell, ri, ci, d) {
-		me.member_items[d[ri][0]] = new MemberItem(cell, d[ri], me);
-	}
+	});	
 	this.lst.run();
 }
 
@@ -186,14 +190,14 @@
 	var me = this;
 	this.det = det;
 	this.wrapper = $a(parent, 'div');
-	this.enabled = det[6];
+	this.enabled = det.enabled;
 	
 	this.tab = make_table(this.wrapper, 1,2,'100%', ['20%', '70%'], {padding:'4px', overflow:'hidden'});
 	$y(this.tab, {tableLayout:'fixed', borderCollapse:'collapse'})
 	
 	this.is_online = function() {
 		for(var i=0;i<pscript.online_users.length;i++) {
-			if(det[0]==pscript.online_users[i][0]) return true;
+			if(det.name==pscript.online_users[i][0]) return true;
 		}
 	}
 	
@@ -210,30 +214,30 @@
 	this.set_image = function() {
 		// image
 		this.img = $a($td(this.tab,0,0),'img','',{width:'41px'});
-		set_user_img(this.img, det[0], null, 
-			(det[4] ? det[4].split(NEWLINE)[0].split(',')[1] : ('no_img_' + (det[3]=='Female' ? 'f' : 'm'))));		
+		set_user_img(this.img, det.name, null, 
+			(det.file_list ? det.file_list.split(NEWLINE)[0].split(',')[1] : ('no_img_' + (det.gender=='Female' ? 'f' : 'm'))));		
 	}
 	
 	// set other details like email id, name etc
 	this.set_details = function() {
 		// name
-		this.fullname = det[1] ? det[1] : det[0];
+		this.fullname = det.full_name || det.name;
 		var div = $a($td(this.tab, 0, 1), 'div', '', {fontWeight: 'bold',padding:'2px 0px'});
 		this.name_link = $a(div,'span','link_type');
 		this.name_link.innerHTML = crop(this.fullname, 15);
 		this.name_link.onclick = function() {
-			mlist.show_profile(me.det[0], me);
+			mlist.show_profile(me.det.name, me);
 		}
 
 		// "you" tag
-		if(user==det[0]) {
+		if(user==det.name) {
 			var span = $a(div,'span','',{padding:'2px' ,marginLeft:'3px'});
 			span.innerHTML = '(You)'
 		}
 
 		// email id
 		var div = $a($td(this.tab, 0, 1), 'div', '', {color: '#777', fontSize:'11px'});
-		div.innerHTML = det[0];
+		div.innerHTML = det.name;
 
 		// working img
 		var div = $a($td(this.tab, 0, 1), 'div');
@@ -256,7 +260,7 @@
 	this.set_details();
 	
 	// show initial
-	if(user==det[0]) me.name_link.onclick();
+	if(user==det.name) me.name_link.onclick();
 }
 
 
@@ -305,6 +309,7 @@
 		if(has_common(['Administrator','System Manager'],user_roles)) {
 			var roles_btn = $btn(this.toolbar_area, 'Set Roles', function() { me.show_roles() },{marginRight:'3px'});
 			var delete_btn = $btn(this.toolbar_area, 'Delete User', function() { me.delete_user(); },{marginRight:'3px'});
+			var ip_btn = $btn(this.toolbar_area, 'Securty Settings', function() { me.set_security(); },{marginRight:'3px'});
 		}
 	}
 	
@@ -315,6 +320,74 @@
 		this.role_object.dialog.show();
 	}
 	
+	// show securty settings
+	this.set_security = function() {
+		var d = new wn.widgets.Dialog({
+			title: 'Set User Security',
+			width: 500,
+			fields: [
+				{
+					label:'IP Address', 
+					description: 'Restrict user login by IP address, partial ips (111.111.111), \
+					multiple addresses (separated by commas) allowed', 
+					fieldname:'restrict_ip', 
+					fieldtype:'Data'
+				},
+				
+				{
+					label:'Login After',
+					description: 'User can only login after this hour (0-24)',
+					fieldtype: 'Int',
+					fieldname: 'login_after'
+				},
+
+				{
+					label:'Login Before',
+					description: 'User can only login before this hour (0-24)',
+					fieldtype: 'Int',
+					fieldname: 'login_before'
+				},
+				
+				{
+					label:'New Password',
+					description: 'Update the current user password',
+					fieldtype: 'Data',
+					fieldname: 'new_password'
+				},
+
+				{
+					label:'Update',
+					fieldtype:'Button',
+					fieldname:'update'
+				}
+			]
+		});
+		d.onshow = function() {
+			d.set_values({
+				restrict_ip: me.profile.restrict_ip || '',
+				login_before: me.profile.login_before || '',
+				login_after: me.profile.login_after || '',
+				new_password: ''
+			})
+		}
+		d.fields_dict.update.input.onclick = function() {
+			var btn = this;
+			this.set_working();
+			var args = d.get_values();
+			args.user = me.profile.name;
+			$c_page('home', 'my_company', 'update_security', JSON.stringify(args), function(r,rt) {
+				if(r.exc) {
+					msgprint(r.exc);
+					btn.done_working();
+					return;
+				}
+				$.extend(me.profile, d.get_values());
+				d.hide();
+			});
+		}
+		d.show();
+	}
+	
 	// delete user
 	// create a confirm dialog and call server method
 	this.delete_user = function() {
@@ -534,6 +607,7 @@
 		
 		this.lst = new wn.widgets.Listing({
 			parent: this.lst_area,
+			as_dict: 1,
 			no_result_message: (user==uid 
 				? 'No messages by anyone yet' 
 				: 'No messages yet. To start a conversation post a new message'),
@@ -577,18 +651,18 @@
 	this.wrapper = $a(cell, 'div', 'my-company-comment-wrapper');
 	this.comment = $a(this.wrapper, 'div', 'my-company-comment');
 
-	this.user = $a(this.comment, 'span', 'link_type', {fontWeight:'bold'}, pscript.get_fullname(det[1]));
+	this.user = $a(this.comment, 'span', 'link_type', {fontWeight:'bold'}, pscript.get_fullname(det.owner));
 	this.user.onclick = function() {
-		page_body.pages['My Company'].member_list.show_profile(me.det[1]);
+		page_body.pages['My Company'].member_list.show_profile(me.det.owner);
 	}
 
-	var st = (!det[4] ? {fontWeight: 'bold'} : null);
-	this.msg = $a(this.comment, 'span', 'social', st, ': ' + det[0]);
+	var st = (!det.docstatus ? {fontWeight: 'bold'} : null);
+	this.msg = $a(this.comment, 'span', 'social', st, ': ' + det.creation);
 
-	if(det[1]==user) {
+	if(det.full_name==user) {
 		$y(this.wrapper, {backgroundColor: '#D9D9F3'});
 	}
-	this.timestamp = $a(this.wrapper, 'div', 'my-company-timestamp', '', comment_when(det[3]));
+	this.timestamp = $a(this.wrapper, 'div', 'my-company-timestamp', '', comment_when(det.creation));
 }
 
 
diff --git a/home/page/my_company/my_company.py b/home/page/my_company/my_company.py
index 560ea6e..5d5ed80 100644
--- a/home/page/my_company/my_company.py
+++ b/home/page/my_company/my_company.py
@@ -129,3 +129,19 @@
 	WHERE comment_doctype = 'My Company'
 	AND comment_docname = %s
 	""", webnotes.user.name)
+
+def update_security(args=''):
+	import json
+	args = json.loads(args)
+	webnotes.conn.set_value('Profile', args['user'], 'restrict_ip', args.get('restrict_ip'))
+	webnotes.conn.set_value('Profile', args['user'], 'login_after', args.get('login_after'))
+	webnotes.conn.set_value('Profile', args['user'], 'login_before', args.get('login_before'))
+
+	if 'new_password' in args:
+		if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+			import server_tools.gateway_utils
+			webnotes.msgprint(server_tools.gateway_utils.change_password('', args['new_password'])['message'])
+		else:
+			webnotes.conn.sql("update tabProfile set password=password(%s) where name=%s", (args['new_password'], args['user']))
+
+	webnotes.msgprint('Settings Updated')
\ No newline at end of file
diff --git a/home/page/profile_settings/profile_settings.py b/home/page/profile_settings/profile_settings.py
index f9124b6..56f7f15 100644
--- a/home/page/profile_settings/profile_settings.py
+++ b/home/page/profile_settings/profile_settings.py
@@ -17,7 +17,7 @@
 			webnotes.msgprint('Old password is not correct', raise_exception=1)
 			
 		from webnotes.utils import nowdate
-		webnotes.conn.sql("update tabProfile set password=password(%s), password_last_updated=%s where name=%s",(arg['new_password'], nowdate(), webnotes.session['user']))
+		webnotes.conn.sql("update tabProfile set password=password(%s) where name=%s",(arg['new_password'], nowdate(), webnotes.session['user']))
 		webnotes.msgprint('Password Updated');
 
 def get_user_details(arg=None):
diff --git a/hr/Module Def/HR/HR.txt b/hr/Module Def/HR/HR.txt
index 5ad5e54..212d689 100644
--- a/hr/Module Def/HR/HR.txt
+++ b/hr/Module Def/HR/HR.txt
@@ -1,603 +1,318 @@
+# Module Def, HR
 [
+
+	# These values are common in all dictionaries
 	{
-		'_last_update': None,
-		'creation': '2011-06-30 15:51:33',
-		'disabled': 'No',
+		'creation': '2011-07-01 17:41:43',
 		'docstatus': 0,
-		'doctype': u'Module Def',
-		'doctype_list': None,
-		'file_list': None,
-		'idx': None,
-		'is_hidden': 'No',
-		'last_updated_date': None,
-		'modified': '2011-06-30 15:51:33',
+		'modified': '2011-08-25 13:54:43',
 		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Module Def Role
+	{
+		'doctype': 'Module Def Role',
+		'name': '__common__',
+		'parent': 'HR',
+		'parentfield': 'roles',
+		'parenttype': 'Module Def'
+	},
+
+	# These values are common for all Module Def Item
+	{
+		'doctype': 'Module Def Item',
+		'name': '__common__',
+		'parent': 'HR',
+		'parentfield': 'items',
+		'parenttype': 'Module Def'
+	},
+
+	# These values are common for all Module Def
+	{
+		'disabled': 'No',
+		'doctype': u'Module Def',
+		'is_hidden': 'No',
 		'module_desc': 'Human Resource Management - Employee Database, Salaries etc.',
 		'module_icon': 'HR.gif',
 		'module_label': 'HR',
 		'module_name': 'HR',
-		'module_page': None,
 		'module_seq': 9,
-		'name': 'HR',
-		'owner': 'Administrator',
-		'parent': None,
-		'parentfield': None,
-		'parenttype': None,
-		'trash_reason': None,
-		'widget_code': None
+		'name': '__common__'
 	},
+
+	# Module Def, HR
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
+		'doctype': u'Module Def',
+		'name': 'HR'
+	},
+
+	# Module Def Item
+	{
 		'description': 'Your Employee Database',
 		'display_name': 'Employee',
 		'doc_name': 'Employee',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'employee_name\nemployment_type\nstatus\nbranch\ndesignation\ndepartment\ngrade\nreports_to',
-		'hide': None,
-		'icon': None,
-		'idx': 1,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01335',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 1
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Employees Daily Attendance Tracking Form',
 		'display_name': 'Attendance',
 		'doc_name': 'Attendance',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'employee\nemployee_name\nstatus\natt_date\nfiscal_year\ncompany',
-		'hide': None,
-		'icon': None,
-		'idx': 2,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01336',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 2
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Upload Attendance data',
 		'display_name': 'Attendance Control Panel',
 		'doc_name': 'Attendance Control Panel',
 		'doc_type': 'Single DocType',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 3,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01337',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 3
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Leave allocation for selected employees at a time',
 		'display_name': 'Leave Control Panel',
 		'doc_name': 'Leave Control Panel',
 		'doc_type': 'Single DocType',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 4,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01338',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 4
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Allocate leave for fiscal year',
 		'display_name': 'Leave Allocation',
 		'doc_name': 'Leave Allocation',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'employee\nleave_type\nfiscal_year\ntotal_leaves_allocated\nposting_date',
-		'hide': None,
-		'icon': None,
-		'idx': 5,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01339',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 5
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Apply Leave',
 		'display_name': 'Leave Application',
 		'doc_name': 'Leave Application',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'employee\nleave_type\nfiscal_year\nfrom_date\nto_date\ntotal_leave_days',
-		'hide': None,
-		'icon': None,
-		'idx': 6,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01340',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 6
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Submit Employees Expenses',
 		'display_name': 'Expense Voucher',
 		'doc_name': 'Expense Voucher',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'status\nemployee\nemployee_name\nposting_date\ntotal_claimed_amount\ntotal_sanctioned_amount\nexp_approver',
-		'hide': None,
-		'icon': None,
-		'idx': 7,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01341',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 7
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Assign Responsibilities to employee and evaluate',
 		'display_name': 'Appraisal',
 		'doc_name': 'Appraisal',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'status\nemployee\nemployee_name\nstart_date\nend_date\ntotal_score\nkra_approver',
-		'hide': None,
-		'icon': None,
-		'idx': 8,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01342',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 8
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Generate Salary Structure heads for an employee',
 		'display_name': 'Salary Structure',
 		'doc_name': 'Salary Structure',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'employee\nis_active\nfiscal_year\nfrom_date\nctc\ntotal_earning\ntotal_deduction\ntotal',
-		'hide': None,
-		'icon': None,
-		'idx': 9,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01343',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 9
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Generate Salary Slip for an employee',
 		'display_name': 'Salary Slip',
 		'doc_name': 'Salary Slip',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'month\nyear\nemployee\nemployee_name\npayment_days\narrear_amount\nencashment_amount\ngross_pay\ntotal_deduction\nnet_pay',
-		'hide': None,
-		'icon': None,
-		'idx': 10,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01344',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 10
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': 'Generate Salary Slip for all employee at a time',
-		'display_name': 'Salary Slip Control Panel',
-		'doc_name': 'Salary Slip Control Panel',
+		'description': 'Generate Salary Slip for multiple employee at a time based on selected criteria',
+		'display_name': 'Salary Manager',
+		'doc_name': 'Salary Manager',
 		'doc_type': 'Single DocType',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 11,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01345',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 11
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
 		'description': 'Job Applications received for various positions',
 		'display_name': 'Job Application',
 		'doc_name': 'Job Application',
 		'doc_type': 'Forms',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
 		'fields': 'applicant_name\nemail\nposition',
-		'hide': None,
-		'icon': None,
-		'idx': 12,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01346',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 12
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': None,
 		'display_name': 'Employee Information',
 		'doc_name': 'Employee',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 13,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01347',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 13
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': None,
 		'display_name': "Employee's Birthday",
 		'doc_name': 'Employee',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 14,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01348',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 14
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': None,
 		'display_name': 'New or left employees for a month',
 		'doc_name': 'Employee',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 15,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01349',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 15
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': None,
 		'display_name': 'Monthly Attendance Details',
 		'doc_name': 'Attendance',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 16,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01350',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 16
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:33',
-		'description': None,
 		'display_name': 'Leave Application Details',
 		'doc_name': 'Leave Application',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 17,
-		'modified': '2011-06-30 15:51:33',
-		'modified_by': 'Administrator',
-		'name': 'MDI01351',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 17
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Leave Allocation Details',
 		'doc_name': 'Leave Allocation',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 18,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01352',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 18
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Employee Leave Balance Report',
 		'doc_name': 'Employee',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 19,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01353',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 19
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Salary Structure Details',
 		'doc_name': 'Salary Structure',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 20,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01354',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 20
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Salary Register',
 		'doc_name': 'Salary Slip',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 21,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01355',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 21
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Salary Slips',
 		'doc_name': 'Salary Slip',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 22,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01356',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 22
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Pending Appraisals',
 		'doc_name': 'Appraisal',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 23,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01357',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 23
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Employee Appraisals',
 		'doc_name': 'Appraisal',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 24,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01358',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 24
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Pending Expense Vouchers',
 		'doc_name': 'Expense Voucher',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 25,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01359',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 25
 	},
+
+	# Module Def Item
 	{
-		'click_function': None,
-		'creation': '2011-06-30 15:51:34',
-		'description': None,
 		'display_name': 'Expense Vouchers',
 		'doc_name': 'Expense Voucher',
 		'doc_type': 'Reports',
-		'docstatus': 0,
 		'doctype': 'Module Def Item',
-		'fields': None,
-		'hide': None,
-		'icon': None,
-		'idx': 26,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDI01360',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'items',
-		'parenttype': 'Module Def'
+		'idx': 26
 	},
+
+	# Module Def Role
 	{
-		'creation': '2011-06-30 15:51:34',
-		'docstatus': 0,
 		'doctype': 'Module Def Role',
 		'idx': 1,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDR00340',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'roles',
-		'parenttype': 'Module Def',
 		'role': 'HR Manager'
 	},
+
+	# Module Def Role
 	{
-		'creation': '2011-06-30 15:51:34',
-		'docstatus': 0,
 		'doctype': 'Module Def Role',
 		'idx': 2,
-		'modified': '2011-06-30 15:51:34',
-		'modified_by': 'Administrator',
-		'name': 'MDR00341',
-		'owner': 'Administrator',
-		'parent': 'HR',
-		'parentfield': 'roles',
-		'parenttype': 'Module Def',
 		'role': 'HR User'
 	}
 ]
\ No newline at end of file
diff --git a/hr/doctype/employee/employee.txt b/hr/doctype/employee/employee.txt
index 49a494b..98caa2c 100644
--- a/hr/doctype/employee/employee.txt
+++ b/hr/doctype/employee/employee.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2011-02-17 11:16:08',
+		'creation': '2010-08-08 17:08:59',
 		'docstatus': 0,
-		'modified': '2011-06-27 14:39:04',
+		'modified': '2011-08-11 17:27:12',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -26,7 +26,7 @@
 		'show_in_menu': 0,
 		'subject': '%(employee_name)s',
 		'tag_fields': 'status',
-		'version': 443
+		'version': 444
 	},
 
 	# These values are common for all DocField
@@ -40,12 +40,14 @@
 
 	# These values are common for all DocPerm
 	{
+		'amend': 0,
 		'doctype': 'DocPerm',
 		'name': '__common__',
 		'parent': 'Employee',
 		'parentfield': 'permissions',
 		'parenttype': 'DocType',
-		'read': 1
+		'read': 1,
+		'submit': 0
 	},
 
 	# DocType, Employee
@@ -56,21 +58,24 @@
 
 	# DocPerm
 	{
-		'cancel': 1,
-		'create': 1,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 1,
 		'permlevel': 0,
-		'role': 'System Manager',
-		'write': 1
+		'role': 'Employee',
+		'write': 0
 	},
 
 	# DocPerm
 	{
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 2,
 		'permlevel': 1,
-		'role': 'All'
+		'role': 'All',
+		'write': 0
 	},
 
 	# DocPerm
@@ -95,22 +100,6 @@
 		'write': 1
 	},
 
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 5,
-		'permlevel': 1,
-		'role': 'HR User'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 6,
-		'permlevel': 1,
-		'role': 'HR Manager'
-	},
-
 	# DocField
 	{
 		'doctype': 'DocField',
@@ -141,7 +130,7 @@
 		'no_copy': 1,
 		'oldfieldname': 'naming_series',
 		'oldfieldtype': 'Select',
-		'options': 'WN-EMP\nEMP/',
+		'options': 'EMP/',
 		'permlevel': 0,
 		'reqd': 0
 	},
@@ -173,8 +162,7 @@
 		'oldfieldname': 'employee_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
-		'reqd': 1,
-		'search_index': 1
+		'reqd': 1
 	},
 
 	# DocField
@@ -276,7 +264,7 @@
 		'options': '\nActive\nLeft',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -409,8 +397,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Department',
 		'permlevel': 0,
-		'reqd': 1,
-		'search_index': 1
+		'reqd': 1
 	},
 
 	# DocField
@@ -477,18 +464,8 @@
 	# DocField
 	{
 		'doctype': 'DocField',
-		'fieldname': 'is_sales_person',
-		'fieldtype': 'Check',
-		'idx': 27,
-		'label': 'Is Sales Person',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 28,
+		'idx': 27,
 		'label': 'Salary Information',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -501,11 +478,11 @@
 		'doctype': 'DocField',
 		'fieldname': 'salary_mode',
 		'fieldtype': 'Select',
-		'idx': 29,
+		'idx': 28,
 		'label': 'Salary Mode',
 		'oldfieldname': 'salary_mode',
 		'oldfieldtype': 'Select',
-		'options': '\nBank\nCash \nCheque',
+		'options': '\nBank\nCash\nCheque',
 		'permlevel': 0,
 		'trigger': 'Client'
 	},
@@ -518,7 +495,7 @@
 		'fieldname': 'bank_name',
 		'fieldtype': 'Data',
 		'hidden': 0,
-		'idx': 30,
+		'idx': 29,
 		'in_filter': 1,
 		'label': 'Bank Name',
 		'oldfieldname': 'bank_name',
@@ -535,7 +512,7 @@
 		'fieldname': 'bank_ac_no',
 		'fieldtype': 'Data',
 		'hidden': 0,
-		'idx': 31,
+		'idx': 30,
 		'label': 'Bank A/C No.',
 		'oldfieldname': 'bank_ac_no',
 		'oldfieldtype': 'Data',
@@ -547,7 +524,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'esic_card_no',
 		'fieldtype': 'Data',
-		'idx': 32,
+		'idx': 31,
 		'label': 'ESIC CARD No',
 		'oldfieldname': 'esic_card_no',
 		'oldfieldtype': 'Data',
@@ -559,7 +536,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'pf_number',
 		'fieldtype': 'Data',
-		'idx': 33,
+		'idx': 32,
 		'label': 'PF Number',
 		'oldfieldname': 'pf_number',
 		'oldfieldtype': 'Data',
@@ -571,7 +548,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'gratuity_lic_id',
 		'fieldtype': 'Data',
-		'idx': 34,
+		'idx': 33,
 		'label': 'Gratuity LIC ID',
 		'oldfieldname': 'gratuity_lic_id',
 		'oldfieldtype': 'Data',
@@ -582,7 +559,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 35,
+		'idx': 34,
 		'label': 'Contact Details',
 		'permlevel': 0
 	},
@@ -591,7 +568,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 36,
+		'idx': 35,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -601,7 +578,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'cell_number',
 		'fieldtype': 'Data',
-		'idx': 37,
+		'idx': 36,
 		'label': 'Cell Number',
 		'permlevel': 0
 	},
@@ -611,7 +588,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'personal_email',
 		'fieldtype': 'Data',
-		'idx': 38,
+		'idx': 37,
 		'label': 'Personal Email',
 		'permlevel': 0
 	},
@@ -621,7 +598,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'notice_number_of_days',
 		'fieldtype': 'Int',
-		'idx': 39,
+		'idx': 38,
 		'label': 'Notice - Number of Days',
 		'oldfieldname': 'notice_number_of_days',
 		'oldfieldtype': 'Int',
@@ -632,7 +609,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 40,
+		'idx': 39,
 		'label': 'Emergency Contact Details',
 		'options': '<b>Emergency Contact Details</b>',
 		'permlevel': 0
@@ -643,7 +620,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'person_to_be_contacted',
 		'fieldtype': 'Data',
-		'idx': 41,
+		'idx': 40,
 		'label': 'Person To Be Contacted',
 		'permlevel': 0
 	},
@@ -653,7 +630,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'relation',
 		'fieldtype': 'Data',
-		'idx': 42,
+		'idx': 41,
 		'label': 'Relation',
 		'permlevel': 0
 	},
@@ -663,7 +640,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'emergency_phone_number',
 		'fieldtype': 'Data',
-		'idx': 43,
+		'idx': 42,
 		'label': 'Emergency Phone Number',
 		'permlevel': 0
 	},
@@ -672,7 +649,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 44,
+		'idx': 43,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -682,7 +659,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'permanent_accommodation_type',
 		'fieldtype': 'Select',
-		'idx': 45,
+		'idx': 44,
 		'label': 'Permanent Accommodation Type',
 		'options': '\nRented\nOwned',
 		'permlevel': 0
@@ -693,7 +670,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'permanent_address',
 		'fieldtype': 'Small Text',
-		'idx': 46,
+		'idx': 45,
 		'label': 'Permanent Address',
 		'permlevel': 0
 	},
@@ -703,7 +680,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'current_accommodation_type',
 		'fieldtype': 'Select',
-		'idx': 47,
+		'idx': 46,
 		'label': 'Current Accommodation Type',
 		'options': '\nRented\nOwned',
 		'permlevel': 0
@@ -714,7 +691,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'current_address',
 		'fieldtype': 'Small Text',
-		'idx': 48,
+		'idx': 47,
 		'label': 'Current Address',
 		'permlevel': 0
 	},
@@ -723,7 +700,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 49,
+		'idx': 48,
 		'label': 'Personal Details',
 		'permlevel': 0
 	},
@@ -732,7 +709,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 50,
+		'idx': 49,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -742,7 +719,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'pan_number',
 		'fieldtype': 'Data',
-		'idx': 51,
+		'idx': 50,
 		'label': 'PAN Number',
 		'permlevel': 0
 	},
@@ -752,7 +729,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'passport_number',
 		'fieldtype': 'Data',
-		'idx': 52,
+		'idx': 51,
 		'label': 'Passport Number',
 		'permlevel': 0
 	},
@@ -763,7 +740,7 @@
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
 		'hidden': 1,
-		'idx': 53,
+		'idx': 52,
 		'label': 'Employee Profile',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -775,7 +752,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'date_of_issue',
 		'fieldtype': 'Date',
-		'idx': 54,
+		'idx': 53,
 		'label': 'Date of Issue',
 		'permlevel': 0
 	},
@@ -785,7 +762,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'valid_upto',
 		'fieldtype': 'Date',
-		'idx': 55,
+		'idx': 54,
 		'label': 'Valid Upto',
 		'permlevel': 0
 	},
@@ -796,7 +773,7 @@
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
 		'hidden': 1,
-		'idx': 56,
+		'idx': 55,
 		'label': 'Salary Structure',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -808,7 +785,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'place_of_issue',
 		'fieldtype': 'Data',
-		'idx': 57,
+		'idx': 56,
 		'label': 'Place of Issue',
 		'permlevel': 0
 	},
@@ -818,7 +795,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'marital_status',
 		'fieldtype': 'Select',
-		'idx': 58,
+		'idx': 57,
 		'label': 'Marital Status',
 		'options': '\nSingle\nMarried\nDivorced\nWidowed',
 		'permlevel': 0
@@ -829,7 +806,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'blood_group',
 		'fieldtype': 'Select',
-		'idx': 59,
+		'idx': 58,
 		'label': 'Blood Group',
 		'options': '\nA+\nA-\nB+\nB-\nAB+\nAB-\nO+\nO-',
 		'permlevel': 0
@@ -839,7 +816,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 60,
+		'idx': 59,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -851,7 +828,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'family_background',
 		'fieldtype': 'Small Text',
-		'idx': 61,
+		'idx': 60,
 		'label': 'Family Background',
 		'permlevel': 0
 	},
@@ -863,7 +840,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'health_details',
 		'fieldtype': 'Small Text',
-		'idx': 62,
+		'idx': 61,
 		'label': 'Health Details',
 		'permlevel': 0
 	},
@@ -872,7 +849,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 63,
+		'idx': 62,
 		'label': 'Educational Qualification',
 		'permlevel': 0
 	},
@@ -882,7 +859,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'educational_qualification_details',
 		'fieldtype': 'Table',
-		'idx': 64,
+		'idx': 63,
 		'label': 'Educational Qualification Details',
 		'options': 'Educational Qualifications Detail',
 		'permlevel': 0
@@ -892,7 +869,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 65,
+		'idx': 64,
 		'label': 'Career History',
 		'permlevel': 0
 	},
@@ -901,7 +878,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 66,
+		'idx': 65,
 		'label': 'Previous Work Experience',
 		'options': 'Simple',
 		'permlevel': 0
@@ -912,7 +889,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'previous_experience_details',
 		'fieldtype': 'Table',
-		'idx': 67,
+		'idx': 66,
 		'label': 'Previous Experience Details',
 		'options': 'Previous Experience Detail',
 		'permlevel': 0
@@ -922,7 +899,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 68,
+		'idx': 67,
 		'label': 'History In Company',
 		'options': 'Simple',
 		'permlevel': 0
@@ -933,7 +910,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'experience_in_company_details',
 		'fieldtype': 'Table',
-		'idx': 69,
+		'idx': 68,
 		'label': 'Experience In Company Details',
 		'options': 'Experience In Company Detail',
 		'permlevel': 0
@@ -943,7 +920,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 70,
+		'idx': 69,
 		'label': 'Exit',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -953,7 +930,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 71,
+		'idx': 70,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -963,7 +940,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'resignation_letter_date',
 		'fieldtype': 'Date',
-		'idx': 72,
+		'idx': 71,
 		'label': 'Resignation Letter Date',
 		'oldfieldname': 'resignation_letter_date',
 		'oldfieldtype': 'Date',
@@ -975,7 +952,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'relieving_date',
 		'fieldtype': 'Date',
-		'idx': 73,
+		'idx': 72,
 		'in_filter': 1,
 		'label': 'Relieving Date',
 		'oldfieldname': 'relieving_date',
@@ -988,7 +965,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'reason_for_leaving',
 		'fieldtype': 'Data',
-		'idx': 74,
+		'idx': 73,
 		'label': 'Reason for Leaving',
 		'oldfieldname': 'reason_for_leaving',
 		'oldfieldtype': 'Data',
@@ -1000,7 +977,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'leave_encashed',
 		'fieldtype': 'Select',
-		'idx': 75,
+		'idx': 74,
 		'label': 'Leave Encashed?',
 		'oldfieldname': 'leave_encashed',
 		'oldfieldtype': 'Select',
@@ -1013,7 +990,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'encashment_date',
 		'fieldtype': 'Date',
-		'idx': 76,
+		'idx': 75,
 		'label': 'Encashment Date',
 		'oldfieldname': 'encashment_date',
 		'oldfieldtype': 'Date',
@@ -1024,7 +1001,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 77,
+		'idx': 76,
 		'label': 'Exit Interview Details',
 		'oldfieldname': 'col_brk6',
 		'oldfieldtype': 'Column Break',
@@ -1037,7 +1014,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'held_on',
 		'fieldtype': 'Date',
-		'idx': 78,
+		'idx': 77,
 		'label': 'Held On',
 		'oldfieldname': 'held_on',
 		'oldfieldtype': 'Date',
@@ -1049,7 +1026,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'reason_for_resignation',
 		'fieldtype': 'Select',
-		'idx': 79,
+		'idx': 78,
 		'label': 'Reason for Resignation',
 		'oldfieldname': 'reason_for_resignation',
 		'oldfieldtype': 'Select',
@@ -1062,7 +1039,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'new_workplace',
 		'fieldtype': 'Data',
-		'idx': 80,
+		'idx': 79,
 		'label': 'New Workplace',
 		'oldfieldname': 'new_workplace',
 		'oldfieldtype': 'Data',
@@ -1074,7 +1051,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'feedback',
 		'fieldtype': 'Small Text',
-		'idx': 81,
+		'idx': 80,
 		'label': 'Feedback',
 		'oldfieldname': 'feedback',
 		'oldfieldtype': 'Text',
@@ -1087,7 +1064,7 @@
 		'fieldname': 'file_list',
 		'fieldtype': 'Text',
 		'hidden': 1,
-		'idx': 82,
+		'idx': 81,
 		'label': 'File List',
 		'permlevel': 0,
 		'print_hide': 1
@@ -1098,7 +1075,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'trash_reason',
 		'fieldtype': 'Small Text',
-		'idx': 83,
+		'idx': 82,
 		'label': 'Trash Reason',
 		'oldfieldname': 'trash_reason',
 		'oldfieldtype': 'Small Text',
diff --git a/hr/doctype/salary_manager/__init__.py b/hr/doctype/salary_manager/__init__.py
new file mode 100644
index 0000000..cb6c600
--- /dev/null
+++ b/hr/doctype/salary_manager/__init__.py
@@ -0,0 +1,4 @@
+from webnotes import ValidationError
+
+class SalarySlipExistsError(ValidationError): pass
+
diff --git a/hr/doctype/salary_manager/salary_manager.js b/hr/doctype/salary_manager/salary_manager.js
new file mode 100644
index 0000000..cf470be
--- /dev/null
+++ b/hr/doctype/salary_manager/salary_manager.js
@@ -0,0 +1,67 @@
+var display_activity_log = function(msg) {
+	if(!pscript.ss_html)
+		pscript.ss_html = $a(cur_frm.fields_dict['Activity Log'].wrapper,'div','',{border:'1px solid #CCC', backgroundColor:'#CCC'});
+	pscript.ss_html.innerHTML = '<div style="color:#EEE; background-color:#555;"><b><i>Activity Log:</i><br></b></div>';
+	pscript.ss_html.innerHTML += '<div style="color:#666; padding: 5px">'+ msg + '</div>';
+}
+
+//Create salary slip
+//-----------------------
+cur_frm.cscript['Create Salary Slip'] = function(doc, cdt, cdn) {
+	var callback = function(r, rt){
+		if (r.message)
+			display_activity_log(r.message);
+	}
+	$c('runserverobj', args={'method':'create_sal_slip','docs':compress_doclist(make_doclist (cdt, cdn))},callback);
+}
+
+
+
+//Submit salary slip
+//-----------------------
+cur_frm.cscript['Submit Salary Slip'] = function(doc, cdt, cdn) {
+	var check = confirm("Do you really want to Submit all Salary Slip for month : " + doc.month+" and fiscal year : "+doc.fiscal_year);
+	if(check){
+		var callback = function(r, rt){
+			if (r.message)
+				display_activity_log(r.message);
+		}
+		$c('runserverobj', args={'method':'submit_salary_slip','docs':compress_doclist(make_doclist (cdt, cdn))},callback);
+	}
+}
+
+// Make Bank Voucher
+//-----------------------
+cur_frm.cscript['Make Bank Voucher'] = function(doc,cdt,cdn){
+  if(doc.month && doc.fiscal_year){
+  	cur_frm.cscript.make_jv(doc, cdt, cdn);
+  }
+}
+
+
+// Make JV
+//-----------------------
+cur_frm.cscript.make_jv = function(doc, dt, dn) {
+	var call_back = function(r,rt){
+		var jv = LocalDB.create('Journal Voucher');
+		jv = locals['Journal Voucher'][jv];
+		jv.voucher_type = 'Bank Voucher';
+		jv.user_remark = 'Payment of salary for the month: ' + doc.month + 'and fiscal year: ' + doc.fiscal_year;
+		jv.fiscal_year = doc.fiscal_year;
+		jv.company = doc.company;
+		jv.posting_date = dateutil.obj_to_str(new Date());
+
+		// credit to bank
+		var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
+		d1.account = r.message['default_bank_account'];
+		d1.credit = r.message['amount']
+
+		// debit to salary account
+		var d2 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
+		d2.account = r.message['default_salary_account'];
+		d2.debit = r.message['amount']
+
+		loaddoc('Journal Voucher', jv.name);
+	}
+	$c_obj(make_doclist(dt,dn),'get_acc_details','',call_back);
+}
diff --git a/hr/doctype/salary_manager/salary_manager.py b/hr/doctype/salary_manager/salary_manager.py
new file mode 100644
index 0000000..ec8fba2
--- /dev/null
+++ b/hr/doctype/salary_manager/salary_manager.py
@@ -0,0 +1,164 @@
+# 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.model import db_exists
+from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
+from webnotes.model.doclist import getlist, copy_doclist
+from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
+from webnotes import session, form, is_testing, msgprint, errprint
+
+set = webnotes.conn.set
+sql = webnotes.conn.sql
+get_value = webnotes.conn.get_value
+in_transaction = webnotes.conn.in_transaction
+convert_to_lists = webnotes.conn.convert_to_lists
+	
+# -----------------------------------------------------------------------------------------
+
+
+class DocType:
+	def __init__(self, doc, doclist):
+		self.doc = doc
+		self.doclist = doclist
+		
+		
+	def get_emp_list(self):
+		"""
+			Returns list of active employees based on selected criteria 
+			and for which salary structure exists		
+		"""
+		
+		cond = self.get_filter_condition()
+		
+		emp_list = sql("""
+			select t1.name
+			from `tabEmployee` t1, `tabSalary Structure` t2 
+			where t1.docstatus!=2 and t2.docstatus != 2 
+			and ifnull(t1.status, 'Left') = 'Active' and ifnull(t2.is_active, 'No') = 'Yes' 
+			and t1.name = t2.employee
+		%s """% cond)
+
+		return emp_list
+		
+		
+	def get_filter_condition(self):
+		self.check_mandatory()
+		
+		cond = ''
+		for f in ['company', 'branch', 'department', 'designation', 'grade', 'employment_type']:
+			if self.doc.fields.get(f):
+				cond += " and t1." + f + " = '" + self.doc.fields.get(f) + "'"
+				
+		return cond
+		
+		
+	def check_mandatory(self):
+		for f in ['company', 'month', 'fiscal_year']:
+			if not self.doc.fields[f]:
+				msgprint("Please select %s to proceed" % f, raise_exception=1)
+		
+		
+	def create_sal_slip(self):
+		"""
+			Creates salary slip for selected employees if already not created
+		
+		"""
+		
+		emp_list = self.get_emp_list()
+		log = ""
+		if emp_list:
+			log = "<table><tr><td>Following Salary Slip has been created: </td></tr><tr><td><u>SAL SLIP ID</u></td><td><u>EMPLOYEE NAME</u></td></tr>"
+		else:
+			log = "<table><tr><td>No employee found for the above selected criteria</td></tr>"
+			
+		for emp in emp_list:
+			if not sql("""select name from `tabSalary Slip` 
+					where docstatus!= 2 and employee = %s and month = %s and fiscal_year = %s and company = %s
+					""", (emp[0], self.doc.month, self.doc.fiscal_year, self.doc.company)):
+				ss = Document('Salary Slip')
+				ss.fiscal_year = self.doc.fiscal_year
+				ss.employee = emp[0]
+				ss.month = self.doc.month
+				ss.email_check = self.doc.send_email
+				ss.company = self.doc.company
+				ss.save(1)
+			
+				ss_obj = get_obj('Salary Slip', ss.name, with_children=1)
+				ss_obj.get_emp_and_leave_details()
+				ss_obj.calculate_net_pay()
+				ss_obj.validate()
+				ss_obj.doc.save()
+			
+				for d in getlist(ss_obj.doclist, 'earning_details'):
+					d.save()
+				for d in getlist(ss_obj.doclist, 'deduction_details'):
+					d.save()
+					
+				log += '<tr><td>' + ss.name + '</td><td>' + ss_obj.doc.employee_name + '</td></tr>'
+		log += '</table>'
+		return log	
+				
+	def get_sal_slip_list(self):
+		"""
+			Returns list of salary slips based on selected criteria
+			which are not submitted
+		"""
+		cond = self.get_filter_condition()
+		ss_list = sql("""
+			select t1.name from `tabSalary Slip` t1 
+			where t1.docstatus = 0 and month = '%s' and fiscal_year = '%s' %s
+		""" % (self.doc.month, self.doc.fiscal_year, cond))
+		return ss_list
+			
+				
+	def submit_salary_slip(self):
+		"""
+			Submit all salary slips based on selected criteria
+		"""
+		ss_list = self.get_sal_slip_list()
+		log = ""
+		if ss_list:
+			log = "<table><tr><td>Following Salary Slip has been submitted: </td></tr><tr><td><u>SAL SLIP ID</u></td><td><u>EMPLOYEE NAME</u></td></tr>"
+		else:
+			log = "<table><tr><td>No salary slip found to submit for the above selected criteria</td></tr>"
+			
+		for ss in ss_list:
+			ss_obj = get_obj("Salary Slip",ss[0],with_children=1)
+			set(ss_obj.doc, 'docstatus', 1)
+			ss_obj.on_submit()
+			
+			log += '<tr><td>' + ss[0] + '</td><td>' + ss_obj.doc.employee_name + '</td></tr>'
+		log += '</table>'	
+		return log	
+			
+			
+	def get_total_salary(self):
+		"""
+			Get total salary amount from submitted salary slip based on selected criteria
+		"""
+		cond = self.get_filter_condition()
+		tot = sql("""
+			select sum(rounded_total) from `tabSalary Slip` t1 
+			where t1.docstatus = 1 and month = '%s' and fiscal_year = '%s' %s
+		""" % (self.doc.month, self.doc.fiscal_year, cond))
+		
+		return flt(tot[0][0])
+		
+		
+	def get_acc_details(self):
+		"""
+			get default bank account,default salary acount from company
+		"""
+		amt = self.get_total_salary()
+		com = sql("select default_bank_account from `tabCompany` where name = '%s'" % self.doc.company)
+		
+		if not com[0][0] or not com[0][1]:
+			msgprint("You can set Default Bank Account in Company master.")
+
+		ret = {
+			'def_bank_acc' : com and com[0][0] or '',
+			'def_sal_acc' : com and com[0][1] or '',
+			'amount' : amt
+		}
+		return ret
diff --git a/hr/doctype/salary_manager/salary_manager.txt b/hr/doctype/salary_manager/salary_manager.txt
new file mode 100644
index 0000000..66a7282
--- /dev/null
+++ b/hr/doctype/salary_manager/salary_manager.txt
@@ -0,0 +1,287 @@
+# DocType, Salary Manager
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-08-11 16:40:04',
+		'docstatus': 0,
+		'modified': '2011-08-25 12:02:57',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all DocType
+	{
+		'_last_update': '1314179318',
+		'allow_copy': 1,
+		'allow_email': 1,
+		'allow_print': 1,
+		'colour': 'White:FFF',
+		'doctype': 'DocType',
+		'document_type': 'Other',
+		'issingle': 1,
+		'module': 'HR',
+		'name': '__common__',
+		'section_style': 'Simple',
+		'show_in_menu': 1,
+		'version': 29
+	},
+
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'name': '__common__',
+		'parent': 'Salary Manager',
+		'parentfield': 'fields',
+		'parenttype': 'DocType',
+		'permlevel': 0
+	},
+
+	# These values are common for all DocPerm
+	{
+		'create': 1,
+		'doctype': 'DocPerm',
+		'name': '__common__',
+		'parent': 'Salary Manager',
+		'parentfield': 'permissions',
+		'parenttype': 'DocType',
+		'permlevel': 0,
+		'read': 1,
+		'write': 1
+	},
+
+	# DocType, Salary Manager
+	{
+		'doctype': 'DocType',
+		'name': 'Salary Manager'
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm',
+		'idx': 1,
+		'role': 'System Manager'
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm',
+		'idx': 2,
+		'role': 'HR User'
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm',
+		'idx': 3,
+		'role': 'HR Manager'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldtype': 'HTML',
+		'idx': 1,
+		'label': 'Document Description',
+		'options': '<div class="field_description">You can generate multiple salary slips based on the selected criteria, submit and mail those to the employee directly from here</div>'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 2
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 3,
+		'width': '50%'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'company',
+		'fieldtype': 'Select',
+		'idx': 4,
+		'label': 'Company',
+		'options': 'link:Company',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'branch',
+		'fieldtype': 'Link',
+		'idx': 5,
+		'label': 'Branch',
+		'options': 'Branch'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'department',
+		'fieldtype': 'Link',
+		'idx': 6,
+		'label': 'Department',
+		'options': 'Department'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'designation',
+		'fieldtype': 'Link',
+		'idx': 7,
+		'label': 'Designation',
+		'options': 'Designation'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 8,
+		'width': '50%'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'grade',
+		'fieldtype': 'Select',
+		'idx': 9,
+		'label': 'Grade',
+		'options': 'link:Grade'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'employment_type',
+		'fieldtype': 'Select',
+		'idx': 10,
+		'label': 'Employment Type',
+		'options': 'link:Employment Type'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldname': 'fiscal_year',
+		'fieldtype': 'Select',
+		'idx': 11,
+		'label': 'Fiscal Year',
+		'options': 'link:Fiscal Year',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldname': 'month',
+		'fieldtype': 'Select',
+		'idx': 12,
+		'label': 'Month',
+		'options': '\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Check if you want to send salary slip in mail to each employee while submitting salary slip',
+		'doctype': 'DocField',
+		'fieldname': 'send_email',
+		'fieldtype': 'Check',
+		'idx': 13,
+		'label': 'Send Email'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 14
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 15,
+		'width': '50%'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Creates salary slip for above mentioned criteria.',
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 16,
+		'label': 'Create Salary Slip',
+		'trigger': 'Client'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 17,
+		'width': '25%'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Submit all salary slips for the above selected criteria',
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 18,
+		'label': 'Submit Salary Slip',
+		'trigger': 'Client'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 19,
+		'width': '25%'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Create Bank Voucher for the total salary paid for the above selected criteria',
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 20,
+		'label': 'Make Bank Voucher',
+		'trigger': 'Client'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 21
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'HTML',
+		'idx': 22,
+		'label': 'Activity Log'
+	}
+]
\ No newline at end of file
diff --git a/hr/doctype/salary_manager/test_salary_manager.py b/hr/doctype/salary_manager/test_salary_manager.py
new file mode 100644
index 0000000..1a0b48a
--- /dev/null
+++ b/hr/doctype/salary_manager/test_salary_manager.py
@@ -0,0 +1,197 @@
+import unittest
+import webnotes
+
+from webnotes.model.doc import Document
+from webnotes.model.code import get_obj
+sql = webnotes.conn.sql
+
+class TestSalarySlip(unittest.TestCase):
+	def setUp(self):
+		webnotes.conn.begin()
+		for rec in [des1, dep1, branch1, grade1, comp1, emp1, emp2]:
+			rec.save(1)
+					
+		ss1[0].employee = emp1.name
+		for s in ss1: s.save(1)
+		for s in ss1[1:]:
+			sql("update `tabEarning Detail` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
+			sql("update `tabDeduction Detail` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
+			
+		
+		ss2[0].employee = emp2.name
+		for s in ss2: s.save(1)		
+		for s in ss2[1:]:
+			sql("update `tabEarning Detail` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
+			sql("update `tabDeduction Detail` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
+			
+		sman.save()
+		self.sm = get_obj('Salary Manager')	
+		leave.save(1)
+		self.sm.create_sal_slip()
+		
+	def test_creation(self):
+		ssid = sql("""
+			select name, department 
+			from `tabSalary Slip` 
+			where month = '08' and fiscal_year='2011-2012'""")
+
+		self.assertTrue(len(ssid)==1)
+		self.assertTrue(ssid[0][1] == 'dep1')
+		
+		
+	def test_lwp_calc(self):
+		ss = sql("""
+			select payment_days
+			from `tabSalary Slip` 
+			where month = '08' and fiscal_year='2011-2012' and employee = '%s'
+		""" % emp1.name)
+		
+		self.assertTrue(ss[0][0]==27)
+		
+	def test_net_pay(self):
+		ss = webnotes.conn.sql("""
+			select rounded_total 
+			from `tabSalary Slip` 
+			where month = '08'
+			and fiscal_year='2011-2012' and employee = '%s'""" % emp1.name)
+		self.assertTrue(ss[0][0]==67)
+
+	def test_submit(self):
+		self.sm.submit_sal_slip()
+		ss = webnotes.conn.sql("""
+			select docstatus 
+			from `tabSalary Slip` 
+			where month = '08'
+			and fiscal_year='2011-2012' and employee = '%s'""" % emp1.name)
+		self.assertTrue(ss[0][0]==1)
+		
+	def tearDown(self):
+		webnotes.conn.rollback()
+		
+#--------------------------------------------
+# test data
+#--------------------------------------------
+des1 = Document(fielddata={
+	'name':'des1',
+	'doctype':'Designation',
+	'designation_name':'des1'
+})
+
+dep1 = Document(fielddata={
+	'name':'dep1',
+	'doctype':'Department',
+	'department_name' : 'dep1'
+})
+
+branch1 = Document(fielddata={
+	'name':'branch1',
+	'doctype':'Branch',
+	'branch' : 'branch1'
+})
+
+comp1 = Document(fielddata={
+	'name':'comp1',
+	'doctype':'Company',
+	'abbr':'c1',
+	'company_name' : 'comp1'
+})
+
+grade1 = Document(fielddata={
+	'name':'grade1',
+	'doctype':'Grade',
+	'grade_name' : 'grade1'	
+})
+	
+emp1 = Document(fielddata={
+	'doctype':'Employee',
+	'employee_number':'emp1',
+	'department':'dep1',
+	'designation':'des1',
+	'branch' : 'branch1',
+	'company':'comp1',
+	'grade':'grade1',
+	'naming_series':'EMP/',
+	'status':'Active',
+	'docstatus':0
+})
+
+emp2 = Document(fielddata={
+	'doctype':'Employee',
+	'employee_number':'emp2',
+	'department':'dep1',
+	'designation':'des2',
+	'branch' : 'branch1',
+	'company':'comp1',
+	'naming_series':'EMP/',
+	'grade':'grade1',
+	'status':'Active',
+
+})
+
+ss1 = [
+	Document(fielddata={
+		'doctype':'Salary Structure',
+		'docstatus':0,
+		'employee':'emp1',
+		'is_active':'Yes',
+		'department': 'dep1',
+		'designation' : 'des1'
+	}),
+	Document(fielddata={
+		'parenttype':'Salary Structure',
+		'parentfield':'earning_details',
+		'doctype':'Earning Detail',
+		'e_type' : 'Basic',
+		'depend_on_lwp':1,
+		'modified_value':100
+	}),
+	Document(fielddata={
+		'parenttype':'Salary Structure',
+		'parentfield':'earning_details',
+		'doctype':'Deduction Detail',
+		'd_type':'TDS',
+		'd_modified_amt':20
+	})
+]
+
+ss2 = [
+	Document(fielddata={
+		'doctype':'Salary Structure',
+		'is_active':'Yes',
+		'docstatus':0,
+	}),
+	Document(fielddata={
+		'parenttype':'Salary Structure',
+		'parentfield':'deduction_details',
+		'doctype':'Earning Detail',
+		'e_type' : 'Basic',
+		'modified_value':100
+	}),
+	Document(fielddata={
+		'parenttype':'Salary Structure',
+		'parentfield':'deduction_details',
+		'doctype':'Deduction Detail',
+		'd_type':'TDS',
+		'd_modified_amt':20
+	})
+]
+
+sman = Document(fielddata={
+		'name':'Salary Manager',
+		'doctype':'Salary Manager',
+		'company': 'comp1',
+		'department':'dep1',
+		'designation':'des1',
+		'month': '08',
+		'fiscal_year':'2011-2012'
+	})
+	
+leave = Document(fielddata = {
+		'doctype':'Leave Application',
+		'employee':'emp1',
+		'from_date':'2011-08-12',
+		'to_date':'2011-08-15',
+		'total_leave_days':'4',
+		'leave_type':'Leave Without Pay',
+		'docstatus':1
+	})
diff --git a/hr/doctype/salary_slip/salary_slip.js b/hr/doctype/salary_slip/salary_slip.js
index 8f953e6..c6ae27b 100644
--- a/hr/doctype/salary_slip/salary_slip.js
+++ b/hr/doctype/salary_slip/salary_slip.js
@@ -3,25 +3,25 @@
 // On load
 // -------------------------------------------------------------------
 cur_frm.cscript.onload = function(doc,dt,dn){
-  if((cint(doc.__islocal) == 1) && !doc.amended_from){
-    var today=new Date();
-    month = (today.getMonth()+01).toString();
-    if(month.length>1) doc.month = month;
-    else doc.month = '0'+month;
+	if((cint(doc.__islocal) == 1) && !doc.amended_from){
+		var today=new Date();
+		month = (today.getMonth()+01).toString();
+		if(month.length>1) doc.month = month;
+		else doc.month = '0'+month;
 		doc.fiscal_year = sys_defaults['fiscal_year'];
-    refresh_many(['month', 'fiscal_year']);
-    cur_frm.cscript.fiscal_year(doc, dt, dn);
-  }
+		refresh_many(['month', 'fiscal_year']);
+		cur_frm.cscript.fiscal_year(doc, dt, dn);
+	}
 }
 
 // Get leave details
 //---------------------------------------------------------------------
 cur_frm.cscript.fiscal_year = function(doc,dt,dn){
-    $c_obj(make_doclist(doc.doctype,doc.name), 'get_emp_and_leave_details','',function(r, rt) {
-      var doc = locals[dt][dn];
-      cur_frm.refresh();
-      calculate_all(doc, dt, dn);
-    });
+		$c_obj(make_doclist(doc.doctype,doc.name), 'get_emp_and_leave_details','',function(r, rt) {
+			var doc = locals[dt][dn];
+			cur_frm.refresh();
+			calculate_all(doc, dt, dn);
+		});
 }
 
 cur_frm.cscript.month = cur_frm.cscript.employee = cur_frm.cscript.fiscal_year;
@@ -29,24 +29,24 @@
 // Calculate total if lwp exists
 // ------------------------------------------------------------------------
 cur_frm.cscript.leave_without_pay = function(doc,dt,dn){
-  doc.payment_days = flt(doc.total_days_in_month) - flt(doc.leave_without_pay);
-  refresh_field('payment_days');
-  calculate_all(doc, dt, dn);
+	doc.payment_days = flt(doc.total_days_in_month) - flt(doc.leave_without_pay);
+	refresh_field('payment_days');
+	calculate_all(doc, dt, dn);
 }
 
 // Calculate all
 // ------------------------------------------------------------------------
 var calculate_all = function(doc, dt, dn) {
-  calculate_earning_total(doc, dt, dn);
-  calculate_ded_total(doc, dt, dn);
-  calculate_net_pay(doc, dt, dn);
+	calculate_earning_total(doc, dt, dn);
+	calculate_ded_total(doc, dt, dn);
+	calculate_net_pay(doc, dt, dn);
 }
 
 // Trigger on earning modified amount and depends on lwp
 // ------------------------------------------------------------------------
 cur_frm.cscript.e_modified_amount = function(doc,dt,dn){
-  calculate_earning_total(doc, dt, dn);
-  calculate_net_pay(doc, dt, dn);
+	calculate_earning_total(doc, dt, dn);
+	calculate_net_pay(doc, dt, dn);
 }
 
 cur_frm.cscript.e_depends_on_lwp = cur_frm.cscript.e_modified_amount;
@@ -54,8 +54,8 @@
 // Trigger on earning modified amount and depends on lwp
 // ------------------------------------------------------------------------
 cur_frm.cscript.d_modified_amount = function(doc,dt,dn){
-  calculate_ded_total(doc, dt, dn);
-  calculate_net_pay(doc, dt, dn);
+	calculate_ded_total(doc, dt, dn);
+	calculate_net_pay(doc, dt, dn);
 }
 
 cur_frm.cscript.d_depends_on_lwp = cur_frm.cscript.d_modified_amount;
@@ -63,50 +63,50 @@
 // Calculate earning total
 // ------------------------------------------------------------------------
 var calculate_earning_total = function(doc, dt, dn) {
-  var tbl = getchildren('SS Earning Detail', doc.name, 'earning_details', doc.doctype);
+	var tbl = getchildren('SS Earning Detail', doc.name, 'earning_details', doc.doctype);
 
-  var total_earn = 0;
-  for(var i = 0; i < tbl.length; i++){
-    if(cint(tbl[i].e_depends_on_lwp) == 1) {
-      tbl[i].e_modified_amount = flt(tbl[i].e_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month));      
-      refresh_field('e_modified_amount', tbl[i].name, 'earning_details');
-    }
-    total_earn += flt(tbl[i].e_modified_amount);
-  }
-  doc.gross_pay = total_earn + flt(doc.arrear_amount) + flt(doc.leave_encashment_amount);
-  refresh_many(['e_modified_amount', 'gross_pay']);
+	var total_earn = 0;
+	for(var i = 0; i < tbl.length; i++){
+		if(cint(tbl[i].e_depends_on_lwp) == 1) {
+			tbl[i].e_modified_amount = Math.round(tbl[i].e_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100;			
+			refresh_field('e_modified_amount', tbl[i].name, 'earning_details');
+		}
+		total_earn += flt(tbl[i].e_modified_amount);
+	}
+	doc.gross_pay = total_earn + flt(doc.arrear_amount) + flt(doc.leave_encashment_amount);
+	refresh_many(['e_modified_amount', 'gross_pay']);
 }
 
 // Calculate deduction total
 // ------------------------------------------------------------------------
 var calculate_ded_total = function(doc, dt, dn) {
-  var tbl = getchildren('SS Deduction Detail', doc.name, 'deduction_details', doc.doctype);
+	var tbl = getchildren('SS Deduction Detail', doc.name, 'deduction_details', doc.doctype);
 
-  var total_ded = 0;
-  for(var i = 0; i < tbl.length; i++){
-    if(cint(tbl[i].d_depends_on_lwp) == 1) {
-      tbl[i].d_modified_amount = flt(tbl[i].d_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month));
+	var total_ded = 0;
+	for(var i = 0; i < tbl.length; i++){
+		if(cint(tbl[i].d_depends_on_lwp) == 1) {
+			tbl[i].d_modified_amount = Math.round(tbl[i].d_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100;
 			refresh_field('d_modified_amount', tbl[i].name, 'deduction_details');
-    }
-    total_ded += flt(tbl[i].d_modified_amount);
-  }
-  doc.total_deduction = total_ded;
-  refresh_field('total_deduction');  
+		}
+		total_ded += flt(tbl[i].d_modified_amount);
+	}
+	doc.total_deduction = total_ded;
+	refresh_field('total_deduction');	
 }
 
 // Calculate net payable amount
 // ------------------------------------------------------------------------
 var calculate_net_pay = function(doc, dt, dn) {
-  doc.net_pay = flt(doc.gross_pay) - flt(doc.total_deduction);
+	doc.net_pay = flt(doc.gross_pay) - flt(doc.total_deduction);
 	doc.rounded_total = Math.round(doc.net_pay);
-  refresh_many(['net_pay', 'rounded_total']);
+	refresh_many(['net_pay', 'rounded_total']);
 }
 
 // trigger on arrear
 // ------------------------------------------------------------------------
 cur_frm.cscript.arrear_amount = function(doc,dt,dn){
-  calculate_earning_total(doc, dt, dn);
-  calculate_net_pay(doc, dt, dn);
+	calculate_earning_total(doc, dt, dn);
+	calculate_net_pay(doc, dt, dn);
 }
 
 // trigger on encashed amount
@@ -116,5 +116,5 @@
 // validate
 // ------------------------------------------------------------------------
 cur_frm.cscript.validate = function(doc, dt, dn) {
-  calculate_all(doc, dt, dn);
+	calculate_all(doc, dt, dn);
 }
diff --git a/hr/doctype/salary_slip/salary_slip.py b/hr/doctype/salary_slip/salary_slip.py
index af55956..0cdc898 100644
--- a/hr/doctype/salary_slip/salary_slip.py
+++ b/hr/doctype/salary_slip/salary_slip.py
@@ -68,7 +68,7 @@
 	# Get leave details
 	#=======================================================
 	def get_leave_details(self):
-		m = self.get_month_details()		
+		m = self.get_month_details()
 		lwp = self.calculate_lwp(m)
 		self.doc.total_days_in_month = m[3]
 		self.doc.leave_without_pay = lwp
@@ -129,12 +129,45 @@
 		self.check_existing()
 		dcc = TransactionBase().get_company_currency(self.doc.company)
 		self.doc.total_in_words	= get_obj('Sales Common').get_total_in_words(dcc, self.doc.rounded_total)
+
+
+	def calculate_earning_total(self):
+		"""
+			Calculates total earnings considering lwp
+		"""
+		self.doc.gross_pay = flt(self.doc.arrear_amount) + flt(self.doc.leave_encashment_amount)
+		for d in getlist(self.doclist, 'earning_details'):
+			if cint(d.e_depends_on_lwp) == 1:
+				d.e_modified_amount = round(flt(d.e_amount)*flt(self.doc.payment_days)/cint(self.doc.total_days_in_month), 2)
+			self.doc.gross_pay += d.e_modified_amount
+	
+	def calculate_ded_total(self):
+		"""
+			Calculates total deduction considering lwp
+		"""
+		self.doc.total_deduction = 0
+		for d in getlist(self.doclist, 'deduction_details'):
+			if cint(d.d_depends_on_lwp) == 1:
+				d.d_modified_amount = round(flt(d.d_amount)*flt(self.doc.payment_days)/cint(self.doc.total_days_in_month), 2)
+			self.doc.total_deduction += d.d_modified_amount
+				
+	def calculate_net_pay(self):
+		"""
+			Calculate net payment
+		"""
+		self.calculate_earning_total()
+		self.calculate_ded_total()
+		self.doc.net_pay = flt(self.doc.gross_pay) - flt(self.doc.total_deduction)
+		self.doc.rounded_total = round(self.doc.net_pay)
 		
 	# ON SUBMIT
 	#=======================================================
 	def on_submit(self):
 		if(self.doc.email_check == 1):			
 			self.send_mail_funct()
+			
+	
+
 
 	# Send mail
 	#=======================================================
@@ -148,8 +181,7 @@
 		 
 			earn_table = ''
 			ded_table = ''
-			if earn_ret:
-			
+			if earn_ret:			
 				earn_table += "<table cellspacing= '5' cellpadding='5' >"
 				
 				for e in earn_ret:
diff --git a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.js b/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.js
deleted file mode 100644
index 5fd80cb..0000000
--- a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.js
+++ /dev/null
@@ -1,71 +0,0 @@
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-  alert("Salary Slip Control Panel is currently under re-development. It will take around a week time.");
-  hide_field(['Process Payroll', 'Submit Salary Slip', 'Make Bank Voucher']);
-}
-
-cur_frm.cscript['Process Payroll'] = function(doc,cdt,cdn){
-  $c('runserverobj', args={'method':'process_payroll','docs':compress_doclist (make_doclist (doc.doctype,doc.name))},function(r,rt){
-    
-      if(!pscript.ss_html)
-        pscript.ss_html = $a(cur_frm.fields_dict['Salary Slip HTML'].wrapper,'span','',{border:'1px solid #CCC', backgroundColor:'#DDD'});
-      pscript.ss_html.innerHTML = '';
-      pscript.ss_html.innerHTML = r.message;
-      
-    
-    });
-
-}
-
-cur_frm.cscript['Submit Salary Slip'] = function(doc,cdt,cdn){
-  if(doc.month && doc.fiscal_year && doc.year){
-    var check = confirm("DO you really want to Submit all Salary Slip for month : " + doc.month+" and year : "+doc.year);
-    if(check){
-      $c('runserverobj', args={'method':'submit_sal_slip','docs':compress_doclist (make_doclist (doc.doctype,doc.name))},function(r,rt){
-      
-        if(!pscript.ss_html)
-          pscript.ss_html = $a(cur_frm.fields_dict['Salary Slip HTML'].wrapper,'span','',{border:'1px solid #CCC', backgroundColor:'#DDD'});
-        pscript.ss_html.innerHTML = '';
-        pscript.ss_html.innerHTML = r.message;
-        
-      
-      });
-    }
-  }
-  else
-    alert("Please select month, fiscal year and year");
-}
-
-// Make JV
-// --------
-cur_frm.cscript.make_jv = function(doc, dt, dn) {
-  var call_back = function(r,rt){
-    var jv = LocalDB.create('Journal Voucher');
-    jv = locals['Journal Voucher'][jv];
-    jv.voucher_type = 'Bank Voucher';
-    jv.remark = 'Salary - Bank Voucher';
-    jv.fiscal_year = doc.fiscal_year;
-    jv.company = doc.company;
-    
-    // credit to bank
-    var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
-    d1.account = r.message['default_bank_account'];
-
-    // debit to salary account
-    var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
-    d1.account = r.message['default_salary_account'];
-    if(!r.message['default_salary_account'] && !r.message['default_bank_account']) alert("To debit salary amount in salary head and credit amount from bank, you need to specify default salary account and default bank account in Global Defaults.\nGo to Setup, click on Company. Select a company.\nSelect Default Salary Account, Default Bank Account from Accounting tab.");
-    else if(!r.message['default_salary_account']) alert("To debit salary amount you need to specify default salary account in Global Defaults.\nGo to Setup, click on Company. Select a company.\nSelect Default Salary Account from Accounting tab.");
-    else if(!r.message['default_bank_account']) alert("To credit salary amount you need to specify default bank account in Global Defaults.\nGo to Setup, click on Company. Select a company.\nSelect Default Bank Account from Accounting tab.");
-    loaddoc('Journal Voucher', jv.name);
-  }
-  $c_obj(make_doclist(dt,dn),'get_acct_dtl','',call_back);
-
-}
-
-
-
-// Make Journal Voucher
-// --------------------
-cur_frm.cscript['Make Bank Voucher'] = function(doc, dt, dn) {
-  cur_frm.cscript.make_jv(doc,dt,dn);
-}
diff --git a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.py b/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.py
deleted file mode 100644
index 3a4fadf..0000000
--- a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.py
+++ /dev/null
@@ -1,137 +0,0 @@
-# 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.model import db_exists
-from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
-from webnotes.model.doclist import getlist, copy_doclist
-from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
-from webnotes import session, form, is_testing, msgprint, errprint
-
-set = webnotes.conn.set
-sql = webnotes.conn.sql
-get_value = webnotes.conn.get_value
-in_transaction = webnotes.conn.in_transaction
-convert_to_lists = webnotes.conn.convert_to_lists
-	
-# -----------------------------------------------------------------------------------------
-
-
-class DocType:
-  def __init__(self, doc, doclist):
-    self.doc = doc
-    self.doclist = doclist   
-  
-  # Get Employees
-  # ********************************************************************** 
-  def get_employee(self):    
-    e1 = self.emp_fr_memp()  #get employee list from employee where employee is active
-    e2 = self.emp_fr_salstr(e1)  #get employee list from salary structure whose salary structure is created and is active 
-    e3 = self.emp_fr_salslip(e2)  #get employee list from salary slip whose salary slip not yet created for this month and year
-    return e3
-
-  # ********************************************************************** 
-  def emp_fr_memp(self):
-    lst1 = [[self.doc.employee_type,"employment_type"],[self.doc.branch,"branch"],[self.doc.designation,"designation"],[self.doc.department, "department"],[self.doc.grade,"grade"]]
-    
-    condition = ""
-    #flag = 0
-    for l in lst1:
-      
-      if(l[0]):
-        #if flag == 0:
-        #  condition += l[1] + "= '" + l[0] +"'"
-        #else:
-        condition += " and " + l[1]+ "= '" +l[0] +"'"
-        #flag = 1
-
-    emp_query = "select name from `tabEmployee` where status = 'Active'"
-    #if flag == 1:
-    emp_query += condition
-            
-    e = sql(emp_query)
-    return e
-
-  # ********************************************************************** 
-  def emp_fr_salstr(self,e1):
-    lst = []
-    for r in e1:
-      lst.append(r[0])
-    
-    
-    e_lst = "%s"%lst
-    e_lst=e_lst.replace("[","(")
-    e_lst=e_lst.replace("]",")")
-    cond = ''
-
-    if e1:
-      cond = " and employee in %s"%e_lst
-    
-    el=sql("select employee from `tabSalary Structure` where is_active = 'Yes'"+cond)
-
-    return el
-
-  # ********************************************************************** 
-  def emp_fr_salslip(self,e2):
-    e3 = []
-    for i in e2:
-      ret = sql("select name from `tabSalary Slip` where month = '%s' and year = '%s' and employee = '%s' and docstatus !=2 "%(self.doc.month,self.doc.year,i[0]))
-
-      if not ret:
-        e3.append(i[0])
-    return e3
-    
-  # ********************************************************************** 
-  def process_payroll(self):
-    sal_slip_str = ''
-    if self.doc.month and self.doc.fiscal_year and self.doc.year:
-      e = self.get_employee()
-      if e:
-        self.doc.emp_lst=e
-        sal_slip_str += 'Sucessfully created following salary slips:'
-      for i in e:
-      	ss = Document('Salary Slip')
-        ss.fiscal_year = self.doc.fiscal_year
-        ss.employee = i
-        ss.month = self.doc.month
-        ss.year= self.doc.year
-        ss.arrear_amount = self.doc.arrear_amount    
-        ss.email_check = self.doc.email_check
-        ss.save(1)
-        salary_obj=get_obj("Salary Slip",ss.name,with_children=1)   
-        salary_obj.process_payroll_all()
-        sal_slip_str += "<br/>"+ss.name 
-        
-    else:
-    
-      msgprint("For Process Payroll Fiscal Year, Month, Year fields are mandatory.")
-    if not sal_slip_str: 
-     
-      sal_slip_str = "No record found."
-    return cstr(sal_slip_str)
-
-  # ********************************************************************** 
-  def submit_sal_slip(self):
-  
-    sal_slip_str = ''
-    r = sql("select name from `tabSalary Slip` where month='%s' and year = '%s' and fiscal_year = '%s' and docstatus = 0"%(self.doc.month,self.doc.year,self.doc.fiscal_year))
-
-  
-    ret = sql("update `tabSalary Slip` set docstatus = 1 where month='%s' and year = '%s' and fiscal_year = '%s' and docstatus = 0"%(self.doc.month,self.doc.year,self.doc.fiscal_year))
-    if r:
-      sal_slip_str += 'Sucessfully updated following salary slips:'
-    for i in r:
-      
-      salary_obj=get_obj("Salary Slip",i[0],with_children=1)   
-      salary_obj.on_submit()
-      sal_slip_str += "<br/>"+cstr(i[0]) 
-    if not sal_slip_str: 
-     
-      sal_slip_str = "No record found."
-    return cstr(sal_slip_str)
-  
-  # ********************************************************************** 
-  #get default bank account,default salary acount from company.
-  def get_acct_dtl(self):
-    res = sql("select default_bank_account,default_salary_acount from `tabCompany` where name = '%s'"%get_defaults()['company'], as_dict=1)
-    return res[0]
diff --git a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.txt b/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.txt
deleted file mode 100644
index b83e0c7..0000000
--- a/hr/doctype/salary_slip_control_panel/salary_slip_control_panel.txt
+++ /dev/null
@@ -1,286 +0,0 @@
-# DocType, Salary Slip Control Panel
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2010-08-08 17:09:20',
-		'docstatus': 0,
-		'modified': '2010-12-29 18:02:38',
-		'modified_by': 'umair@iwebnotes.com',
-		'owner': 'Administrator'
-	},
-
-	# These values are common for all DocType
-	{
-		'_last_update': '1294312182',
-		'allow_copy': 1,
-		'allow_email': 1,
-		'allow_print': 1,
-		'colour': 'White:FFF',
-		'doctype': 'DocType',
-		'hide_heading': 0,
-		'hide_toolbar': 0,
-		'in_create': 0,
-		'issingle': 1,
-		'module': 'HR',
-		'name': '__common__',
-		'read_only': 1,
-		'section_style': 'Simple',
-		'server_code_error': ' ',
-		'show_in_menu': 0,
-		'use_template': 0,
-		'version': 113
-	},
-
-	# These values are common for all DocField
-	{
-		'doctype': 'DocField',
-		'name': '__common__',
-		'parent': 'Salary Slip Control Panel',
-		'parentfield': 'fields',
-		'parenttype': 'DocType',
-		'permlevel': 0
-	},
-
-	# These values are common for all DocPerm
-	{
-		'create': 1,
-		'doctype': 'DocPerm',
-		'name': '__common__',
-		'parent': 'Salary Slip Control Panel',
-		'parentfield': 'permissions',
-		'parenttype': 'DocType',
-		'permlevel': 0,
-		'read': 1,
-		'write': 1
-	},
-
-	# DocType, Salary Slip Control Panel
-	{
-		'doctype': 'DocType',
-		'name': 'Salary Slip Control Panel'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 1,
-		'role': 'System Manager'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 2,
-		'role': 'HR User'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 3,
-		'role': 'HR Manager'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'Section Break',
-		'idx': 1,
-		'label': 'Salary Slip Control Panel'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'employee_type',
-		'fieldtype': 'Select',
-		'idx': 2,
-		'label': 'Employment Type',
-		'oldfieldname': 'employee_type',
-		'oldfieldtype': 'Select',
-		'options': 'link:Employment Type'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'grade',
-		'fieldtype': 'Select',
-		'idx': 3,
-		'label': 'Grade',
-		'oldfieldname': 'grade',
-		'oldfieldtype': 'Select',
-		'options': 'link:Grade'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'branch',
-		'fieldtype': 'Select',
-		'idx': 4,
-		'label': 'Branch',
-		'oldfieldname': 'branch',
-		'oldfieldtype': 'Select',
-		'options': 'link:Branch'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'department',
-		'fieldtype': 'Select',
-		'idx': 5,
-		'label': 'Department',
-		'oldfieldname': 'department',
-		'oldfieldtype': 'Select',
-		'options': 'link:Department'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'designation',
-		'fieldtype': 'Select',
-		'idx': 6,
-		'label': 'Designation',
-		'oldfieldname': 'designation',
-		'oldfieldtype': 'Select',
-		'options': 'link:Designation'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldtype': 'Column Break',
-		'idx': 7,
-		'oldfieldtype': 'Column Break'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'fiscal_year',
-		'fieldtype': 'Select',
-		'idx': 8,
-		'in_filter': 1,
-		'label': 'Fiscal Year',
-		'oldfieldname': 'fiscal_year',
-		'oldfieldtype': 'Select',
-		'options': 'link:Fiscal Year'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'month',
-		'fieldtype': 'Select',
-		'idx': 9,
-		'label': 'Month',
-		'oldfieldname': 'month',
-		'oldfieldtype': 'Select',
-		'options': '\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'year',
-		'fieldtype': 'Select',
-		'idx': 10,
-		'label': 'Year',
-		'oldfieldname': 'year',
-		'oldfieldtype': 'Select',
-		'options': '\n2009\n2010\n2011\n2012'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'week_off',
-		'fieldtype': 'Currency',
-		'idx': 11,
-		'label': 'Week Off',
-		'oldfieldname': 'week_off',
-		'oldfieldtype': 'Currency'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'arrear_amount',
-		'fieldtype': 'Currency',
-		'idx': 12,
-		'label': 'Arrear Amount',
-		'oldfieldname': 'arrear_amount',
-		'oldfieldtype': 'Currency'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldname': 'email_check',
-		'fieldtype': 'Check',
-		'idx': 13,
-		'label': 'Email',
-		'oldfieldname': 'email_check',
-		'oldfieldtype': 'Check'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'Section Break',
-		'idx': 14,
-		'oldfieldtype': 'Section Break'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'idx': 15,
-		'label': 'Process Payroll',
-		'oldfieldtype': 'Button',
-		'trigger': 'Client'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'HTML',
-		'idx': 16,
-		'label': 'Salary Slip HTML'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'Column Break',
-		'idx': 17
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'idx': 18,
-		'label': 'Submit Salary Slip',
-		'oldfieldtype': 'Button',
-		'trigger': 'Client'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'idx': 19,
-		'label': 'Make Bank Voucher',
-		'trigger': 'Client'
-	}
-]
\ No newline at end of file
diff --git a/hr/doctype/salary_structure/salary_structure.txt b/hr/doctype/salary_structure/salary_structure.txt
index 3dcb8f9..d9a9acd 100644
--- a/hr/doctype/salary_structure/salary_structure.txt
+++ b/hr/doctype/salary_structure/salary_structure.txt
@@ -5,14 +5,14 @@
 	{
 		'creation': '2010-12-14 16:50:05',
 		'docstatus': 0,
-		'modified': '2011-06-27 14:39:11',
+		'modified': '2011-08-11 16:56:38',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1308808105',
+		'_last_update': '1311621379',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'module': 'HR',
@@ -21,7 +21,7 @@
 		'server_code_error': ' ',
 		'show_in_menu': 0,
 		'subject': 'For %(employee_name)s',
-		'version': 586
+		'version': 587
 	},
 
 	# These values are common for all DocField
@@ -39,7 +39,8 @@
 		'name': '__common__',
 		'parent': 'Salary Structure',
 		'parentfield': 'permissions',
-		'parenttype': 'DocType'
+		'parenttype': 'DocType',
+		'read': 1
 	},
 
 	# DocType, Salary Structure
@@ -54,9 +55,9 @@
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
-		'match': 'owner',
+		'idx': 1,
 		'permlevel': 0,
-		'read': 1,
+		'role': 'Employee',
 		'submit': 0,
 		'write': 0
 	},
@@ -67,96 +68,39 @@
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
-		'match': 'owner',
-		'permlevel': 0,
-		'read': 1,
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
-		'doctype': 'DocPerm',
-		'match': 'owner',
-		'permlevel': 0,
-		'read': 1,
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
-		'doctype': 'DocPerm',
-		'match': 'owner',
-		'permlevel': 0,
-		'read': 1,
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'permlevel': 0,
-		'role': 'Sales User'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
 		'idx': 2,
 		'permlevel': 1,
-		'read': 1,
 		'role': 'All',
+		'submit': 0,
 		'write': 0
 	},
 
 	# DocPerm
 	{
-		'create': 1,
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
-		'read': 1,
 		'role': 'HR User',
-		'write': 1
+		'submit': 0,
+		'write': 0
 	},
 
 	# DocPerm
 	{
+		'amend': 1,
+		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 4,
 		'permlevel': 0,
-		'read': 1,
 		'role': 'HR Manager',
+		'submit': 1,
 		'write': 1
 	},
 
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 5,
-		'permlevel': 1,
-		'read': 1,
-		'role': 'HR Manager'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 6,
-		'permlevel': 1,
-		'read': 1,
-		'role': 'HR User'
-	},
-
 	# DocField
 	{
 		'doctype': 'DocField',
diff --git a/patches/old_patches/patch_1.py b/patches/old_patches/patch_1.py
new file mode 100644
index 0000000..9173ca5
--- /dev/null
+++ b/patches/old_patches/patch_1.py
@@ -0,0 +1,1180 @@
+"""
+	Old patches for reference
+"""
+
+if patch_no==33:
+	pass
+elif patch_no==34:
+	webnotes.conn.sql("update `tabDocField` set options = 'Letter Head', print_hide = 1 where fieldname = 'letter_head' and fieldtype = 'Link'")
+elif patch_no==35:
+	webnotes.conn.sql("update tabDocType set module = 'Event Updates' where name = 'Feed Control'")
+elif patch_no==36:
+	# remove delivery note foreign key in Serial Number
+	from webnotes.model.db_schema import DbTable
+	t = DbTable('Serial No')
+	fk_list  = t.get_foreign_keys()
+	for f in fk_list:
+		if f[0]=='delivery_note_no':
+			webnotes.conn.commit()
+			webnotes.conn.sql("alter table `tabSerial No` drop foreign key `%s`" % f[1])
+			webnotes.conn.begin()
+			webnotes.conn.sql("update tabDocField set fieldtype='Data' where fieldname='delivery_note_no' and parent='Serial No' limit 1")
+elif patch_no==37:
+	import os
+	mod_path = webnotes.defs.modules_path
+	path_list = []
+	for m in os.listdir(mod_path):
+		for t in ['doctype', 'page', 'search_criteria']:
+			dt_path = os.path.join(mod_path, m, t)
+			if os.path.exists(dt_path):
+				for dt in os.listdir(dt_path):
+					if '.' not in dt and os.path.exists(os.path.join(dt_path, dt, dt+ '.txt')):
+						path_list.append(os.path.join(dt_path, dt, dt+ '.txt'))
+
+	for d in path_list:
+		doclist = eval(open(d,'r').read())
+		webnotes.conn.sql("update `tab%s` set module = '%s' where name = '%s'" % (doclist[0]['doctype'], doclist[0]['module'], doclist[0]['name']))
+
+elif patch_no==38:
+	import webnotes
+	webnotes.conn.set_global("system_message", "System Updates: Hello! You would have noticed some changes on the Home Page. As a part of our commitment to make the system more friendly and social, we have re-designed the feed so that now you will only see feed that is relevant to you (either you have created something or you have been mentioned in the document).<br><br>On the individual listings, you can add tags and also color them!<br><br>You will also get time-to-time updates from our side here. Do keep sending your feedback at support@erpnext.com.")
+	webnotes.conn.set_global("system_message_id", "1")
+
+elif patch_no == 39:
+	pass
+
+elif patch_no == 40:
+	import_from_files(record_list=[['material_management','doctype','item']])
+
+elif patch_no == 42:
+	acc = sql("select name, lft, rgt from tabAccount where account_name in ('Incomes', 'Expenses')")
+	for d in acc:
+		sql("update tabAccount set is_pl_account = 'Yes' where lft >= '%s' and rgt <= '%s'" % (d[1], d[2]))
+elif patch_no == 43:
+	import webnotes.model
+	webnotes.model.delete_doc('Page', 'Module Manager')
+
+# cleanup of Service, Customer Support, Utilities Modules
+# -------------------------------------------------------
+elif patch_no == 44:
+	from webnotes.model import delete_doc
+
+	for dt in sql("select name from tabDocType where module in ('Customer Support')"):
+		delete_doc('DocType', dt[0])
+
+	for dt in sql("select name from `tabSearch Criteria` where module in ('Customer Support')"):
+		delete_doc('Search Criteria', dt[0])
+
+	for dt in sql("select name from tabPage where module in ('Customer Support')"):
+		delete_doc('Page', dt[0])
+
+	# move a couple
+	webnotes.conn.sql("update `tab%s` set module=%s where name=%s" % ('DocType', '%s', '%s'), ('Application Internal', 'Patch Util'))
+	webnotes.conn.sql("update `tab%s` set module=%s where name=%s" % ('DocType', '%s', '%s'), ('Application Internal', 'DocType Property Setter'))
+
+	# remove utilities
+	webnotes.conn.sql('delete from `tabModule Def` where name in ("Customer Support", "Utilities")')
+
+elif patch_no == 45:
+	webnotes.conn.sql('delete from tabDocField where options="Ticket Response Detail"')
+
+elif patch_no == 46:
+	import webnotes
+	webnotes.conn.set_global("system_message", "<b>SYSTEM DOWNTIME:</b> Hello! As part of our commitment to keep improving the service, we are planning a scheduled maintenance on our servers for 4 hrs on 16-Jan-2011(Sunday), from 10AM to 2PM. Do keep sending your feedback at support@erpnext.com.")
+	webnotes.conn.set_global("system_message_id", "2")
+
+elif patch_no == 47:
+	import webnotes
+	webnotes.conn.set_global("system_message", "")
+	webnotes.conn.set_global("system_message_id", "3")
+
+elif patch_no == 48:
+	webnotes.conn.sql("update tabDocField set options = 'Print Heading' where fieldname = 'select_print_heading'")
+
+elif patch_no == 49:
+	webnotes.conn.sql("update tabDocType set autoname = '' where name = 'Search Criteria'")
+elif patch_no == 50:
+	sql("update tabDocField set in_filter = 1 where fieldname in ('cost_center', 'income_account', 'Item Group') and parent = 'RV Detail'")
+elif patch_no == 51:
+	sql("update tabDocField set options = 'link:Print Heading' where fieldtype = 'Select' and fieldname = 'select_print_heading' and parent = 'POS Setting'")
+elif patch_no == 52:
+	sql("update tabDocField set print_hide = 1 where fieldname = 'letter_head'")
+elif patch_no == 53:
+	sql("update tabDocType set search_fields = 'lead_name,lead_owner,status,contact_by,contact_date' where name = 'Lead'")
+elif patch_no == 54:
+	sql("delete from tabDocField where parent = 'Supplier' and label = 'Supplier Contacts' and fieldtype = 'Section Break'")
+elif patch_no == 55:
+	sql("commit")
+	try:
+		sql("alter table tabFeed add column `_user_tags` varchar(180)")
+	except Exception, e:
+		if e.args[0]!=1060:
+			raise e
+elif patch_no == 56:
+	sql("delete from `tabModule Def Item` where parent = 'CRM' and doc_type = 'Reports' and doc_name = 'Delivery Note' and display_name = 'Territory, Item Group wise GP'")
+elif patch_no == 57:
+	import_from_files(record_list=[['selling','doctype','sales_order_detail']])
+
+elif patch_no == 58:
+	# module def patches
+	sql("update `tabModule Def` set module_page = NULL where name not in ('Event Updates', 'Setup', 'My Company')")
+	sql("delete from `tabModule Def Item` where doc_type in ('Separator', 'Setup Forms', 'More Reports')")
+	sql("delete from `tabModule Def Item` where doc_name = 'Project Activity'")
+	sql("update `tabModule Def` set module_label = 'People', disabled='No', is_hidden='No' where name = 'My Company'")
+
+	# insert new module items
+	from webnotes.model.doc import make_autoname
+	if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Ticket'"):
+		sql("""insert into `tabModule Def Item`
+			(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
+			(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Ticket', 'Task', 1)""", make_autoname('MDI.#####'))
+
+	if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Timesheet'"):
+		sql("""insert into `tabModule Def Item`
+			(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
+			(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Timesheet', 'Timesheet', 2)""", make_autoname('MDI.#####'))
+
+	if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Projects'"):
+		sql("""insert into `tabModule Def Item`
+			(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
+			(%s, 'Projects', 'Module Def', 'items', 0, 'Pages', 'Projects', 'Gantt Chart', 1)""", make_autoname('MDI.#####'))
+
+elif patch_no == 59:
+	webnotes.conn.set_value('Control Panel',None,'mail_footer','')
+	webnotes.conn.set_global('global_mail_footer','<div style="margin-top:8px; padding: 8px; font-size: 11px; text-align:right; border-top: 1px solid #AAA">Sent via <a href="https://www.erpnext.com">ERPNext</a></div>')
+elif patch_no == 60:
+	sql("delete from `tabModule Def Item` where display_name = 'Point of Sales'")
+elif patch_no == 61:
+	sql("delete from `tabTDS Category Account` where company not in (select name from tabCompany)")
+elif patch_no == 62:
+	# Import Supplier Quotation
+	import_from_files(record_list=[['srm','doctype','supplier_quotation']])
+
+	# Adding Status Filter
+	sql("update tabDocType set search_fields = concat('status,',search_fields) where name IN ('Delivery Note','Leave Transaction')")
+	# Import Other Charges
+
+	import_from_files(record_list=[['setup','doctype','other_charges']])
+elif patch_no == 63:
+	sql("update `tabDocField` set permlevel = 1 where fieldname in ('return_date', 'return_details') and parent = 'Sales and Purchase Return Wizard'")
+	import_from_files(record_list = [['accounts', 'doctype', 'rv_detail'], ['material_management', 'doctype', 'sales_and_purchase_return_wizard'], ['material_management', 'doctype', 'stock_entry']])
+
+elif patch_no == 64:
+	sql("update tabDocField set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where options in ('RFQ','Supplier Quotation')")
+	sql("update tabDocType set `read_only` = 1, in_create = 1 where name in ('RFQ','Supplier Quotation')")
+	sql("update tabDocField set `report_hide` = 0 where fieldname in ('email_id','phone_1','fax_1') and parent = 'Customer'")
+elif patch_no == 65:
+	# Monthly Trend Analyzer <-> Trend Analyzer
+	sql("update `tabSearch Criteria` set criteria_name = 'Trend Analyzer' where criteria_name = 'Monthly Trend Analyzer' and name = 'SRCH/00159'")
+	sql("update `tabModule Def Item` set display_name = 'Trend Analyzer' where parent = 'Analysis' and display_name = 'Monthly Trend Analyzer'")
+elif patch_no == 66:
+	import webnotes
+	webnotes.conn.set_global("system_message", """<h3>UI Updates</h3>Based on user feedback, we have made a couple of changes in the UI:<ul><li>Sidebar menus are now collapsable</li><li>Forms are now scrollable (we removed the confusing tabs)</li><li>Feed is a lot more descriptive</li></ul>Do send us your feedback!""")
+	webnotes.conn.set_global("system_message_id", "4")
+
+	sql("update `tabModule Def Item` set doc_type = 'Setup Forms' where doc_name in ('TDS Payment', 'TDS Return Acknowledgement', 'Form 16A', 'Period Closing Voucher', 'IT Checklist')")
+	from webnotes.session_cache import clear_cache
+	clear_cache(webnotes.session['user'])
+elif patch_no == 67:
+	sql("update `tabDocField` set in_filter = 1 where fieldname = 'brand' and parent = 'RV Detail'")
+	sql("delete from `tabModule Def Item` where (display_name = 'Sales Invoice' and parent = 'CRM') or (display_name = 'Purchase Invoice' and parent = 'SRM')")
+elif patch_no == 68:
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list=[['hr','doctype','employee'],['roles','Role','Employee']])
+elif patch_no == 69:
+	# delete flds from employee master
+	p = get_obj('Patch Util')
+	emp_del_flds = ['month_of_birth']
+	for f in emp_del_flds:
+		p.delete_field('Employee', f)
+
+	sql("Update tabDocField set `default` = 'Active' where fieldname = 'status' and parent = 'Employee'")
+
+	# map parent flds
+	fld_map = ['cell_number', 'personal_email', 'person_to_be_contacted', 'relation', 'emergency_phone_number', 'pan_number', 'passport_number', 'date_of_issue', 'valid_upto', 'place_of_issue', 'marital_status', 'blood_group', 'permanent_accommodation_type']
+
+	emp_prof = sql("select t1.name, t1.employee, t1.permanent_address_line_1, t1.permanent_address_line_2, t1.city1, t1.state1, t1.country1, t1.pin_code1, t1.phn_no1, t1.present_address_line_1, t1.present_address_line_2, t1.city2, t1.state2, t1.country2, t1.pin_code2, t1.phn_no2, t1.fathers_name, t1.fathers_occupation, t1.mothers_name, t1.mothers_occupation, t1.spouses_name, t1.spouses_occupation, t1.height_cms, t1.weight_kgs, t1.allergies, t1.other_medical_concerns, t1.physical_handicap from `tabEmployee Profile` t1, `tabEmployee` t2 where t1.employee = t2.name")
+	for e in emp_prof:
+		prof_obj = get_obj('Employee Profile', e[0])
+		emp_obj = get_obj('Employee', e[1])
+		for d in fld_map:
+			emp_obj.doc.fields[d] = prof_obj.doc.fields[d]
+		emp_obj.doc.current_accommodation_type = prof_obj.doc.present_accommodation_type
+
+		# address
+		per_addr = cstr(e[2]) + '\n' + cstr(e[3]) + '\n' + cstr(e[4]) + '\n' + cstr(e[5]) + ', ' + cstr(e[6]) + '\n' + 'PIN - ' + cstr(e[7]) + '\n' + 'Ph. No' + cstr(e[8])
+		cur_addr = cstr(e[9]) + '\n' + cstr(e[10]) + '\n' + cstr(e[11]) + '\n' + cstr(e[12]) + ', ' + cstr(e[13]) + '\n' + 'PIN - ' + cstr(e[14]) + '\n' + 'Ph. No' + cstr(e[15])
+		emp_obj.doc.permanent_address = per_addr
+		emp_obj.doc.current_address = cur_addr
+		#family
+		fam = "Father's Name: " + cstr(e[16]) + '\n' + "Father's Occupation: " + cstr(e[17]) + '\n' + "Mother's Name: " + cstr(e[18]) + '\n' + "Mother's Occupation: " + cstr(e[19]) + '\n' + "Spouse's Name: " + cstr(e[20]) + '\n' + "Spouse's Occupation: " + cstr(e[21])
+		emp_obj.doc.family_background = fam
+		# health
+		health = 'Height(cms): ' + cstr(e[22]) + '\n' + 'Weight(kgs): ' + cstr(e[23]) + '\n' + 'Allergies: ' +cstr( e[24]) + '\n' + 'Other Medical Concern: ' + cstr(e[25]) + '\n' + 'Physically Handicapped(if any): ' + cstr(e[26])
+		emp_obj.doc.health_details = health
+		emp_obj.doc.save()
+
+
+	# map tables
+	tbl_list = ['Experience In Company Detail', 'Previous Experience Detail', 'Educational Qualifications Detail']
+	for t in tbl_list:
+		sql("update `tab%s` t1, `tabEmployee Profile` t2 set t1.parent = t2.employee, t1.parenttype = 'Employee' where t1.parent = t2.name" % t)
+
+
+	# overwrite idx?????????
+
+
+	# delete emp profile
+	webnotes.model.delete_doc('DocType', 'Employee Profile')
+	for e in emp_prof:
+		webnotes.model.delete_doc('Employee Profile', e[0])
+
+elif patch_no == 70:
+	# update search criteria module -> System
+	sql("update tabDocType set module='System' where name='Search Criteria'")
+
+	# Cleanups to Contact
+	sql("update tabDocField set fieldtype='Data' where options='Designation' and parent='Contact'")
+	sql("update tabDocField set fieldtype='Data' where options='Department' and parent='Contact'")
+	sql("update tabDocField set depends_on='eval:(cint(doc.is_customer) || cint(doc.is_supplier) || cint(doc.is_sales_partner))' where fieldname='is_primary_contact' and parent='Contact'")
+
+	# import Contact, Employee
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list=[['utilities','doctype','contact']])
+
+
+	# remove last_contact_date from Lead
+	sql("delete from tabDocField where fieldname='last_contact_date' and parent='Lead'")
+
+elif patch_no == 71:
+	# Make Stock Qty and Conversion Factor field editable. Also no need to mention Conversion factor in table can do it directly
+	sql("update `tabDocField` set `permlevel` = 0, `width` = '100px', `trigger` = 'Client' where parent IN ('PO Detail','Purchase Receipt Detail') and fieldname in ('stock_qty','conversion_factor')")
+	sql("update `tabDocField` set `width` = '100px' where parent IN ('PO Detail','Purchase Receipt Detail') and fieldname = 'stock_uom'")
+
+elif patch_no == 72:
+	# Core Patch
+	# ----------
+
+	from webnotes.modules.import_module import import_from_files
+
+	# import module def
+	import_from_files(record_list = [['core', 'Module Def', 'Core']])
+elif patch_no == 73:
+	# set module in DocTypes
+	sql("update tabDocType set module='Core' where name in ('DocType', 'DocField', 'DocPerm', 'Role', 'UserRole', 'Profile', 'Print Format', 'DocFormat', 'Control Panel', 'Event', 'Event Role', 'Event User', 'DefaultValue', 'Default Home Page', 'File', 'File Group', 'File Data', 'Letter Head', 'Module Def', 'Module Def Item', 'Module Def Role', 'Page', 'Page Role', 'Search Criteria', 'DocType Label', 'DocType Mapper', 'Field Mapper Detail', 'Table Mapper Detail')")
+
+	# set module in Page
+	sql("update tabPage set module='Core' where name='Login Page'")
+
+	# move file browser to Tools
+	sql("update tabPage set module='Tools' where name='File Browser'")
+	sql("update tabDocType set module='Tools' where name='File Browser Control'")
+	sql("update tabDocType set module='Application Internal' where name='Profile Control'")
+elif patch_no == 74:
+	p = get_obj('Patch Util')
+	# permission
+	p.delete_permission('Employee', 'Administrator', 0)
+	p.delete_permission('Employee', 'Administrator', 1)
+	p.add_permission('Employee', 'Employee', 0, read = 1, match = 'owner')
+	p.add_permission('Employee', 'Employee', 1, read = 1, match = 'owner')
+	sql("delete from `tabDocField` where parent = 'Employee' and label = 'Payroll Rule'")
+elif patch_no == 75:
+	#sal structure patch
+	# import
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr','doctype','earning_detail'],['hr','doctype','deduction_detail']])
+elif patch_no == 76:
+	# property
+	p = get_obj('Patch Util')
+	p.set_field_property('Salary Structure', 'is_active', 'default', 'Yes')
+	p.set_field_property('Salary Structure', 'ctc', 'reqd', '1')
+	p.set_field_property('Earning Detail', 'modified_value', 'width', '')
+	p.set_field_property('Earning Detail', 'modified_value', 'trigger', 'Client')
+	p.set_field_property('Deduction Detail', 'd_modified_amt', 'width', '')
+	p.set_field_property('Earning Detail', 'd_modified_amt', 'trigger', 'Client')
+	sql("Update tabDocField set `description` = 'You can create more earning and deduction type from Setup --> HR' where label = 'Earning & Deduction' and parent = 'Salary Structure' and fieldtype = 'Section Break'")
+
+	# delete
+	sql("update `tabSalary Structure` set net_pay = total")
+	sql("delete from tabDocField where label in ('LWP Help', 'Calculate Total', 'Total') and parent = 'Salary Structure'")
+	sql("delete from tabDocPerm where parent in ('Earning Detail', 'Deduction Detail')")
+
+
+	# permission
+	p.delete_permission('Salary Structure', 'Administrator', 0)
+	p.delete_permission('Salary Structure', 'Administrator', 1)
+	p.add_permission('Salary Structure', 'Employee', 0, read = 1, match = 'owner')
+	p.add_permission('Salary Structure', 'Employee', 1, read = 1, match = 'owner')
+elif patch_no == 77:
+	# sal slip patch
+	# import
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list=[['hr','doctype','salary_slip'], ['hr','doctype','ss_earning_detail'],['hr','doctype','ss_deduction_detail'], ['mapper', 'DocType Mapper', 'Salary Structure-Salary Slip']])
+elif patch_no == 78:
+	p = get_obj('Patch Util')
+	# delete
+	sql("update `tabSalary Slip` set leave_encashment_amount = encashment_amount")
+	p.delete_field('Salary Slip', 'encashment_amount')
+	p.delete_field('Salary Slip', 'year')
+	p.delete_field('Salary Slip', 'flag')
+	sql("delete from tabDocField where label = 'Process Payroll' and parent = 'Salary Slip'")
+
+	# field property
+	p.set_field_property('Salary Slip', 'bank_name', 'permlevel', '1')
+	p.set_field_property('Salary Slip', 'leave_without_pay', 'permlevel', '0')
+	p.set_field_property('Salary Slip', 'leave_without_pay', 'trigger', 'Client')
+	p.set_field_property('SS Earning Detail', 'e_type', 'permlevel', '0')
+	p.set_field_property('SS Earning Detail', 'e_type', 'fieldtype', 'Link')
+	p.set_field_property('SS Earning Detail', 'e_type', 'options', 'Earning Type')
+	p.set_field_property('SS Deduction Detail', 'd_type', 'permlevel', '0')
+	p.set_field_property('SS Deduction Detail', 'd_type', 'fieldtype', 'Link')
+	p.set_field_property('SS Deduction Detail', 'd_type', 'options', 'Deduction Type')
+	sql("update `tabSS Earning Detail` set e_modified_amount = e_amount")
+	sql("update `tabSS Deduction Detail` set d_modified_amount = d_amount")
+
+	# permission
+	p.delete_permission('Salary Slip', 'Administrator', 0)
+	p.delete_permission('Salary Slip', 'Administrator', 1)
+	p.add_permission('Salary Slip', 'Employee', 0, read = 1, match = 'owner')
+	p.add_permission('Salary Slip', 'Employee', 1, read = 1, match = 'owner')
+elif patch_no == 79:
+	# Import Modules
+	import_from_files(record_list=[['hr','doctype','leave_application'],['hr','doctype','leave_allocation'],['hr','doctype','leave_control_panel'],['hr','doctype','holiday_list'],['hr','doctype','holiday_list_detail'],['hr','Module Def','HR']])
+elif patch_no == 80:
+	# Holiday List
+	sql("update `tabHoliday List Detail` set description = holiday_name")
+	sql("delete from tabDocField where parent = 'Holiday List Detail' and fieldname = 'holiday_name'")
+	sql("update tabDocField set fieldtype = 'Select', options = 'link:Fiscal Year' where parent = 'Holiday List' and fieldname = 'fiscal_year'")
+	sql("delete from tabDocPerm where role in ('Administrator','HR User') and parent = 'Holiday List'")
+
+	# Leave Control Panel
+	# --------------------
+	sql("delete from `tabDocField` where parent = 'Leave Control Panel' and label in ('Leave Control Panel','Allocation Details') and fieldtype = 'Section Break'")
+	sql("delete from tabDocField where parent = 'Leave Control Panel' and fieldname in ('col_brk3','allocation_type','col_brk2','from_date','to_date','leave_transaction_type','posting_date')")
+	sql("update tabDocField set fieldtype = 'Select', options = 'link:Fiscal Year' where parent = 'Leave Control Panel' and fieldname = 'fiscal_year'")
+	sql("update tabDocField set fieldtype = 'Select', options = 'link:Leave Type' where parent = 'Leave Control Panel' and fieldname = 'leave_type'")
+	sql("update tabDocField set reqd = 1 where parent = 'Leave Control Panel' and fieldname = 'no_of_days'")
+
+	# Leave Application
+	# ------------------
+	for d in sql("select * from `tabLeave Transaction` where leave_transaction_type = 'Deduction' and ifnull(deduction_type, '') = 'Leave'", as_dict = 1):
+		lp = Document('Leave Application')
+		lp.employee = d['employee']
+		lp.leave_type = d['leave_type']
+		lp.posting_date = d['date']
+		lp.fiscal_year = d['fiscal_year']
+		lp.leave_balance = d['pre_balance']
+		lp.half_day = d['half_day']
+		lp.from_date = d['from_date']
+		lp.to_date = d['to_date']
+		lp.total_leave_days = d['total_leave']
+		lp.description = d['reason']
+		lp.docstatus = cint(d['docstatus'])
+		lp.save(1)
+
+	# Leave Allocation
+	# -----------------
+	for d in sql("select * from `tabLeave Transaction` where leave_transaction_type = 'Allocation'", as_dict = 1):
+		la = Document('Leave Allocation')
+		la.employee = d['employee']
+		la.leave_type = d['leave_type']
+		la.posting_date = d['date']
+		la.fiscal_year = d['fiscal_year']
+		la.new_leaves_allocated = d['total_leave']
+		la.total_leaves_allocated = d['total_leave']
+		la.description = d['reason']
+		la.docstatus = cint(d['docstatus'])
+		la.save(1)
+
+	# Payroll Module Def
+	# -------------------
+	sql("delete from `tabModule Def Item` where doc_name = 'Leave Transaction' and display_name = 'Leave Transaction' and parent = 'Payroll' and doc_type = 'Forms'")
+
+elif patch_no == 81:
+	# Import Modules
+	import_from_files(record_list=[['hr','Module Def','HR']])
+elif patch_no == 82:
+	sql("update tabDocType set search_fields = 'employee,leave_type,total_leaves_allocated,fiscal_year' where name = 'Leave Allocation'")
+	sql("update tabDocType set search_fields = 'employee,leave_type,from_date,to_date,total_leave_days,fiscal_year' where name = 'Leave Application'")
+elif patch_no == 83:
+	# delete leave transaction
+	webnotes.conn.sql("set foreign_key_checks=0")
+	sql("delete from `tabLeave Transaction`")
+	import webnotes.model
+	webnotes.model.delete_doc('DocType','Badge Settings Detail')
+	webnotes.model.delete_doc('DocType','Leave Transaction')
+	webnotes.conn.sql("set foreign_key_checks=1")
+elif patch_no == 84:
+	p = get_obj('Patch Util')
+	p.set_field_property('SS Earning Detail', 'e_amount', 'permlevel', '1')
+	p.set_field_property('SS Deduction Detail', 'd_amount', 'permlevel', '1')
+elif patch_no == 85:
+	# permission
+	p = get_obj('Patch Util')
+	p.add_permission('Leave Application', 'Employee', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
+	p.add_permission('Leave Application', 'Employee', 1, read = 1, match = 'owner')
+	p.add_permission('Leave Allocation', 'HR User', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
+	p.add_permission('Leave Allocation', 'HR User', 1, read = 1)
+	sql("update tabDocPerm set `match` = '' where parent = 'Leave Application' and role = 'HR User'")
+elif patch_no == 86:
+	# Import Modules
+	import_from_files(record_list=[['hr','doctype','leave_type']])
+elif patch_no == 87:
+	sql("update `tabLeave Type` set is_lwp = 1 where name = 'Leave Without Pay'")
+elif patch_no == 88:
+	# Import Modules
+	import_from_files(record_list=[['hr','doctype','leave_allocation']])
+
+elif patch_no == 89:
+	sql("delete from `tabModule Def Item` where doc_type = 'Setup Forms' and doc_name in ('Payroll Rule', 'IT Checklist', 'Employee Profile') and parent = 'Payroll'")
+	sql("update `tabDocField` set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where parent = 'Leave Type' and fieldname = 'is_encash'")
+elif patch_no == 90:
+	sql("update `tabLeave Allocation` set docstatus = 1")
+elif patch_no == 91:
+	import webnotes
+	webnotes.conn.set_global("system_message", """<h3>System Updates</h3>Based on user feedback, we have cleaned up HR module (Partly):<ul><li>Employee and Employee Profile are merged into a single document</li><li>Salary Structure and Salary Slip are now more user friendly</li><li>Leave Transaction document is now divided into 2 documents Leave Application and Leave Allocation</li></ul>We will work on Reports, Attendance and other documents of Payroll module next week<br><br> Do send us your feedback!""")
+	webnotes.conn.set_global("system_message_id", "5")
+elif patch_no == 92:
+	sql("update tabDocField set label = 'Get Charges' where parent IN ('Sales Order','Delivery Note','Receivable Voucher') and label = 'Get Other Charges' and fieldtype = 'Button'")
+	# Automated Other Charges Calculation basis
+	sql("update tabDocField set options = '', `trigger` = 'Client' where parent IN ('Quotation','Sales Order','Delivery Note','Receivable Voucher') and label = 'Get Charges' and fieldtype = 'Button'")
+elif patch_no == 93:
+	sql("update `tabTable Mapper Detail` set validation_logic = 'qty > ifnull(billed_qty,0) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail'")
+	sql("update `tabField Mapper Detail` set from_field = 'customer' where to_field = 'customer' and parent = 'Sales Order-Receivable Voucher'")
+elif patch_no == 94:
+	import_from_files(record_list=[['selling','doctype','sms_center']])
+elif patch_no == 95:
+	import_from_files(record_list=[['mapper','DocType Mapper','Sales Order-Receivable Voucher'], ['mapper','DocType Mapper','Delivery Note-Receivable Voucher']])
+elif patch_no == 96:
+	sql("delete from `tabModule Def Item` where doc_type = 'Reports' and display_name = 'Cenvat Credit - Input or Capital Goods' and parent = 'Accounts'")
+elif patch_no == 97:
+	sql("update tabFeed set doc_label = 'Feed', doc_name = name where ifnull(doc_name,'') = '' and ifnull(doc_label,'') = ''")
+elif patch_no == 98:
+	import_from_files(record_list=[['accounts','doctype','payable_voucher']])
+elif patch_no == 99:
+	import_from_files(record_list=[['accounts','doctype','account']])
+elif patch_no == 100:
+	p = get_obj('Patch Util')
+	p.set_field_property('Account', 'level', 'hidden', '1')
+	p.set_field_property('Account', 'level', 'print_hide', '1')
+	p.set_field_property('Account', 'account_type', 'search_index', '0')
+	p.set_field_property('TDS Detail', 'tds_category', 'width', '150px')
+	p.set_field_property('TDS Detail', 'special_tds_rate_applicable', 'width', '150px')
+	p.set_field_property('TDS Detail', 'special_tds_rate', 'width', '150px')
+	p.set_field_property('TDS Detail', 'special_tds_limit', 'width', '150px')
+elif patch_no == 101:
+	# Leave Application Details and Leave Allocation Details
+	sql("update tabDocField set search_index = 1, in_filter = 1 where fieldname in ('employee','leave_type','fiscal_year') and parent in ('Leave Application','Leave Allocation')")
+	get_obj('DocType','Leave Application').doc.save()
+	get_obj('DocType','Leave Allocation').doc.save()
+elif patch_no == 102:
+	# make item description field editable in production order
+	sql("update tabDocField set permlevel = 0 where fieldname = 'description' and parent = 'Production Order'")
+elif patch_no == 103:
+	sql("update tabDocField set fieldname = '' where fieldtype = 'HTML'")
+elif patch_no == 104:
+	import_from_files(record_list=[['hr','search_criteria','stdsrch_00001'],['hr','search_criteria','stdsrch_00002'],['hr','search_criteria','stdsrch_00003'],['hr','Module Def','HR'],['hr','doctype','leave_application'],['hr','doctype','leave_allocation']])
+
+elif patch_no == 105:
+	# Employee Leave Balance
+	sql("delete from `tabModule Def Item` where parent = 'Payroll' and doc_type = 'Reports' and display_name IN ('Employeewise Leave Transaction Details','Employeewise Balance Leave Report')")
+	# Update Search Fields
+	sql("update tabDocType set search_fields = 'employee,employee_name,leave_type,from_date,to_date,total_leave_days,fiscal_year' where name = 'Leave Application'")
+	sql("update tabDocType set search_fields = 'employee,employee_name,leave_type,total_leaves_allocated,fiscal_year' where name = 'Leave Allocation'")
+elif patch_no == 106:
+	for d in sql("select name,employee,employee_name from `tabLeave Allocation`"):
+		if not cstr(d[2]):
+			sql("update `tabLeave Allocation` set employee_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Employee',cstr(d[1]),'employee_name'), cstr(d[0])))
+	for d in sql("select name,employee,employee_name from `tabLeave Application`"):
+		if not cstr(d[2]):
+			sql("update `tabLeave Application` set employee_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Employee',cstr(d[1]),'employee_name'), cstr(d[0])))
+elif patch_no == 107:
+	sql("delete from `tabDocField` where fieldname = 'fiscal_year' and parent = 'Employee'")
+elif patch_no == 108:
+	import_from_files(record_list=[['hr','search_criteria','srch_std_00013']])
+elif patch_no == 109:
+	import_from_files(record_list=[['hr','search_criteria','srch_std_00015']])
+elif patch_no == 110:
+	import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr', 'doctype', 'salary_slip']])
+elif patch_no == 111:
+	sql("update tabDocType set search_fields = 'transfer_date, from_warehouse, to_warehouse, purpose, remarks' where name = 'Stock Entry'")
+elif patch_no == 112:
+	sql("delete from tabDocField where label = 'Get Other Charges' and fieldtype = 'Button' and parent = 'Receivable Voucher'")
+elif patch_no == 113:
+	sql("update tabDocField set reqd = 1 where parent = 'Customer' and fieldname = 'phone_1'")
+elif patch_no == 114:
+	for d in sql("select name, master_name, credit_days, credit_limit from tabAccount where master_type = 'Customer'"):
+		if cstr(d[1]):
+			days, limit = cint(d[2]), flt(d[3])
+			cust_det = sql("select credit_days, credit_limit from tabCustomer where name = '%s'" % (cstr(d[1])))
+			if not days: days = cust_det and cint(cust_det[0][0]) or 0
+			if not limit: limit = cust_det and flt(cust_det[0][1]) or 0
+			sql("COMMIT")
+			sql("START TRANSACTION")
+			sql("update tabAccount set credit_days = '%s', credit_limit = '%s' where name = '%s'" % (days, limit, cstr(d[0])))
+			sql("COMMIT")
+
+elif patch_no == 115:
+	# patch for timesheet cleanup
+	from webnotes.model import delete_doc
+	delete_doc('DocType', 'Timesheet Detail')
+
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list = [['Projects', 'DocType', 'Timesheet'], ['Projects', 'DocType', 'Timesheet Detail'], ['Projects', 'DocType', 'Activity Type']])
+
+elif patch_no == 116:
+	# again!
+	from webnotes.model import delete_doc
+	delete_doc('DocType', 'Timesheet Detail')
+
+	from webnotes.modules.import_module import import_from_files
+	import_from_files(record_list = [['Projects', 'DocType', 'Timesheet Detail']])
+elif patch_no == 117:
+	op = '\n' + 'Walk In'
+	sql("update `tabDocField` set `options` = concat(options, %s) where parent = 'Enquiry' and fieldname = 'source' and options not like '%%Walk%%'", op)
+elif patch_no == 118:
+	from webnotes.utils import get_defaults
+	ss = sql("select name, net_pay from `tabSalary Slip`")
+	for d in ss:
+		if d[1]:
+			w = get_obj('Sales Common').get_total_in_words(get_defaults()['currency'], d[1])
+			sql("update `tabSalary Slip` set net_pay_in_words = '%s' where name = '%s'" % (w, d[0]))
+elif patch_no == 119:
+	sql("update tabDocType set in_create = 1 where name = 'Profile'")
+elif patch_no == 120:
+	sql("update tabDocField set permlevel = 0 where parent = 'Sales and Purchase Return Wizard' and fieldname = 'return_date'")
+elif patch_no == 121:
+	import_from_files(record_list = [['CRM', 'DocType', 'Return Detail'], ['Material Management', 'DocType', 'Sales and Purchase Return Wizard']])
+elif patch_no == 122:
+	sql("delete from tabDocField where (fieldname = 'serial_no' or label = 'Warrany Status') and parent = 'Sales Order'")
+elif patch_no == 123:
+	import_from_files(record_list = [['CRM', 'Module Def', 'CRM'], ['CRM', 'Search Criteria', 'STDSRCH/00004']])
+elif patch_no == 124:
+	import webnotes
+	webnotes.conn.set_global("system_message", """<h3>Updates(New)</h3>We have added a new report in the Selling Module.<br><br><b>Sales Personwise Transaction Summary: </b>In this report you can see sales person's contribution in a particular order, delivery or invoice. You can select voucher type in "Based On" filter.<br><br> Do send us your feedback!""")
+	webnotes.conn.set_global("system_message_id", "5")
+elif patch_no == 125:
+	import_from_files(record_list = [['Material Management', 'DocType', 'Delivery Note']])
+elif patch_no == 126:
+	sql("delete from tabDocField where parent = 'Delivery Note' and label in ('Make Sales Invoice', 'Make Installation Note', 'Intro Note')")
+elif patch_no == 127:
+	sql("delete from tabDocPerm where role = 'All' and parent = 'Expense Voucher' and (permlevel = 0 or permlevel = 2)")
+	p = get_obj('Patch Util')
+	p.add_permission('Expense Voucher', 'Employee', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
+	p.add_permission('Expense Voucher', 'HR Manager', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1)
+	p.add_permission('Expense Voucher', 'HR User', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1)
+elif patch_no == 128:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['selling','doctype','sales_order'], ['selling','doctype','sales_order_detail'],  ['stock','doctype','delivery_note'], ['stock','doctype','delivery_note_detail']])
+elif patch_no == 129:
+	sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail' and to_table = 'RV Detail'")
+	sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Delivery Note-Receivable Voucher' and from_table = 'Delivery Note Detail' and to_table = 'RV Detail'")
+elif patch_no == 130:
+	# update from rv
+	from webnotes.model.code import get_obj
+	from webnotes.utils import cstr
+	for d in sql("select name, docstatus from `tabReceivable Voucher` where ifnull(docstatus,0) != 0"):
+		sql("COMMIT")
+		sql("START TRANSACTION")
+		try:
+			obj = get_obj('Receivable Voucher', cstr(d[0]), with_children = 1)
+			is_submit = 1
+			if cint(d[1]) == 2: is_submit = 0
+			get_obj('Sales Common').update_prevdoc_detail(is_submit, obj)
+		except:
+			pass
+		sql("COMMIT")
+
+	# update from dn
+	from webnotes.model.code import get_obj
+	for d in sql("select name, docstatus from `tabDelivery Note` where ifnull(docstatus,0) != 0"):
+		sql("COMMIT")
+		sql("START TRANSACTION")
+		try:
+			obj = get_obj('Delivery Note', cstr(d[0]), with_children = 1)
+			is_submit = 1
+			if cint(d[1]) == 2: is_submit = 0
+			get_obj('Sales Common').update_prevdoc_detail(is_submit, obj)
+		except:
+			pass
+		sql("COMMIT")
+elif patch_no == 131:
+	sql("update `tabDocType` set allow_trash = 1 where name = 'Purchase Other Charges'")
+	sql("update tabDocPerm set `cancel` = 1 where parent = 'Purchase Other Charges' and permlevel = 0 and `read` = 1 and `write` = 1")
+elif patch_no == 132:
+	sql("update tabDocField set no_copy = 0 where parent = 'Receivable Voucher' and fieldname = 'customer'")
+elif patch_no == 133:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['accounts','doctype','receivable_voucher']])
+elif patch_no == 134:
+	sql("update tabDocField set no_copy = 1 where parent = 'Receivable Voucher' and fieldname = 'posting_time'")
+elif patch_no == 135:
+	sql("update tabDocField set `default` = 'Today' where parent = 'Receivable Voucher' and fieldname = 'due_date'")
+elif patch_no == 136:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['accounts','doctype','rv_detail']])
+elif patch_no == 137:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['setup','doctype','price_list']])
+elif patch_no == 138:
+	sql("update `tabDocType` set allow_attach = 1 where name = 'Price List'")
+elif patch_no == 139:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['mapper','DocType Mapper','Sales Order-Receivable Voucher'], ['mapper','DocType Mapper','Delivery Note-Receivable Voucher']])
+elif patch_no == 140:
+	from webnotes.modules import import_module
+	import_module.import_from_files(record_list=[['accounts','doctype','rv_detail']])
+elif patch_no == 141:
+	sql("delete from tabDocField where (fieldname = 'letter_head' or label = 'Letter Head') and parent = 'Company'")
+elif patch_no == 142:
+	# fixes to letter head and personalize
+	from webnotes.model import delete_doc
+
+	delete_doc('DocType', 'Batch Settings')
+	delete_doc('DocType', 'Batch Settings Detail')
+	delete_doc('DocType', 'Social Badge')
+	delete_doc('Page', 'Personalize Page')
+	delete_doc('DocType', 'Personalize Page Control')
+
+	import_from_files(record_list=[['core','doctype','letter_head'], ['setup','doctype','personalize']])
+elif patch_no == 144:
+	webnotes.conn.sql("update tabDocField set fieldtype='Code' where parent='Letter Head' and fieldname='content'")
+elif patch_no == 145:
+	sql("update `tabDocField` set permlevel=1 where fieldname = 'group_or_ledger' and parent = 'Account'")
+elif patch_no == 146:
+	import_from_files(record_list=[['accounts','doctype','account']])
+elif patch_no == 147:
+	import_from_files(record_list=[['mapper', 'DocType Mapper', 'Purchase Order-Payable Voucher'], ['mapper', 'DocType Mapper', 'Purchase Receipt-Payable Voucher'], ['mapper', 'DocType Mapper', 'Purchase Order-Purchase Receipt']])
+elif patch_no == 148:
+	sql("delete from `tabDocField` where (fieldname = 'account_balances' or label = 'Balances') and parent = 'Account'")
+	sql("update tabDocType set istable = 0, section_style = 'Simple', search_fields = 'account, period, fiscal_year, balance' where name = 'Account Balance'")
+	sql("update tabDocField set permlevel = 0 where parent = 'Account Balance'")
+	p = get_obj('Patch Util')
+	p.add_permission('Account Balance', 'Accounts User', 0, read = 1)
+	p.add_permission('Account Balance', 'Accounts Manager', 0, read = 1)
+	import_from_files(record_list=[['accounts','doctype','account_balance']])
+elif patch_no == 149:
+	sql("update `tabAccount Balance` set account = parent")
+elif patch_no == 150:
+	sql("update tabDocField set in_filter = 1, search_index = 1 where parent = 'Account Balance' and fieldname in ('account', 'period', 'fiscal_year', 'start_date', 'end_date')")
+	ac_bal = Document("DocType", "Account Balance")
+	ac_bal.save()
+elif patch_no == 151:
+	sql("delete from tabDocField where label = 'Add / Manage Contacts' and fieldtype = 'Button' and parent = 'Customer'")
+	sql("delete from `tabField Mapper Detail` where parent = 'Sales Order-Delivery Note' and from_field = 'note' and to_field = 'note'")
+elif patch_no == 152:
+	import_from_files(record_list=[['selling','doctype','sales_order'], ['stock','doctype','delivery_note'], ['selling','doctype','customer'], ['selling','doctype','shipping_address'], ['mapper', 'DocType Mapper', 'Sales Order-Delivery Note']])
+elif patch_no == 153:
+	sql("delete from `tabDocField` where fieldname = 'sales_person' and parent = 'Customer'")
+elif patch_no == 154:
+	import_from_files(record_list=[['stock','doctype','serial_no'], ['support','doctype','customer_issue']])
+elif patch_no == 155:
+	for d in sql("select name, item_code from `tabSerial No`"):
+		sql("COMMIT")
+		sql("START TRANSACTION")
+		sql("update `tabSerial No` set item_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Item',cstr(d[1]),'item_name'), cstr(d[0])))
+		sql("COMMIT")
+elif patch_no == 156:
+	sql("update tabDocField set fieldtype = 'Code' where fieldname = 'html' and parent = 'Print Format'")
+elif patch_no == 157:
+	import_from_files(record_list=[['accounts', 'doctype', 'journal_voucher'], ['accounts', 'Print Format', 'Payment Receipt Voucher'], ['accounts', 'Print Format', 'Cheque Printing Format']])
+elif patch_no == 158:
+	from webnotes.model.doc import addchild
+	sql("delete from tabDocField where parent = 'Customer Issue' and fieldname = 'customer_group'")
+elif patch_no == 159:
+	sql("update tabAccount set account_type = 'Chargeable' where account_name in ('Advertising and Publicity', 'Freight & Forwarding Charges', 'Miscellaneous Expenses', 'Sales Promotion Expenses')")
+elif patch_no == 160:
+	sql("update `tabDocType` set search_fields = 'posting_date, due_date, debit_to, fiscal_year, grand_total, outstanding_amount' where name = 'Receivable Voucher'")
+	sql("update `tabDocType` set search_fields = 'posting_date, credit_to, fiscal_year, bill_no, grand_total, outstanding_amount' where name = 'Payable Voucher'")
+elif patch_no == 161:
+	sql("update tabDocType set autoname = 'field:batch_id' where name = 'Batch'")
+	sql("update tabDocField set no_copy = 1 where parent = 'Batch' and fieldname = 'batch_id'")
+elif patch_no == 162:
+	import_from_files(record_list=[['selling', 'search_criteria', 'sales_order_pending_items1']])
+elif patch_no == 163:
+	sql("delete from `tabModule Def Item` where display_name = 'Sales Orderwise Pending Packing Item Summary' and parent = 'CRM'")
+	import_from_files(record_list=[['selling', 'search_criteria', 'sales_orderwise_pending_qty_to_deliver'], ['selling', 'search_criteria', 'sales_orderwise_pending_amount_to_bill'], ['selling', 'search_criteria', 'delivered_items_to_be_install']])
+elif patch_no == 164:
+	import_from_files(record_list=[['buying', 'search_criteria', 'pending_po_items_to_receive'], ['buying', 'search_criteria', 'pending_po_items_to_bill']])
+elif patch_no == 165:
+	pass
+elif patch_no == 166:
+	import_from_files(record_list=[['buying', 'doctype', 'purchase_order']])
+elif patch_no == 167:
+	if webnotes.conn.get_value('Control Panel', None, 'account_id') not in ['ax0000956', 'ax0001338']:
+		sql("delete from tabDocField where parent = 'Purchase Order' and fieldname in ('test_certificate_required', 'estimated_cost', 'transport', 'vendor_reference', 'transportation_required', 'mode_of_dispatch', 'octroi')")
+elif patch_no == 168:
+	sql("update tabDocField set fieldtype = 'Data', options = 'Suggest' where fieldname = 'bank_name' and parent = 'Employee'")
+elif patch_no == 169:
+	import_from_files(record_list=[['accounts', 'doctype', 'pv_detail'], ['accounts', 'doctype', 'rv_detail']])
+elif patch_no == 170:
+	import_from_files(record_list=[['mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher']])
+elif patch_no == 171:
+	import_from_files(record_list=[['buying', 'doctype', 'supplier']])
+elif patch_no == 172:
+	import webnotes
+	webnotes.conn.set_global("system_message", """<b>Welcome to the new financial year 2011-2012 !!! </b><br><br> So obvious question in your mind is how to start Entries in the New Fiscal Year in ERPNext? What are the changes you have to make in the system? <br>We have made some guidelines regarding the basic steps you should follow. Please click on link <a href='http://erpnext.blogspot.com/2011/03/how-to-start-entries-in-new-fiscal-year.html'>How to start Entries in the New Fiscal Year in ERPNext?</a>""")
+	webnotes.conn.set_global("system_message_id", "6")
+elif patch_no == 173:
+	sql("delete from tabDocField where label = 'Get Other Charges' and parent = 'Delivery Note'")
+	sql("update tabDocField set reqd = 0 where fieldname = 'posting_time' and parent = 'Serial No'")
+elif patch_no == 174:
+	c = sql("select count(name) from `tabField Mapper Detail` where parent = 'Delivery Note-Receivable Voucher' and from_field = 'description' and to_field = 'description' and match_id = 2")
+	if c and cint(c[0][0]) > 1:
+		sql("update `tabField Mapper Detail` set match_id = 1 where parent = 'Delivery Note-Receivable Voucher' and from_field = 'description' and to_field = 'description' limit 1")
+elif patch_no == 175:
+	import webnotes
+	webnotes.conn.set_global("system_message", """If your financial year starts on 1st April then you have make some changes in the system to start entry in the new year.<br>We have made some guidelines regarding the basic steps you should follow. Please click on link <a href='http://erpnext.blogspot.com/2011/03/how-to-start-entries-in-new-fiscal-year.html'>How to start Entries in the New Fiscal Year in ERPNext?</a>""")
+	webnotes.conn.set_global("system_message_id", "6")
+elif patch_no == 176:
+	sql("update tabDocPerm set role='Guest', `write`=0, `create`=0 where role='Administrator' and parent='Notification Control' limit 1")
+elif patch_no == 177:
+	sql("delete from `tabDocField` where label = 'Next Steps' and parent = 'Purchase Order'")
+	sql("update tabDocField set options = 'Material Issue\nMaterial Receipt\nMaterial Transfer\nSales Return\nPurchase Return\nSubcontracting\nProduction Order' where parent = 'Stock Entry' and fieldname = 'purpose'")
+elif patch_no == 178:
+	import_from_files(record_list = [['hr', 'doctype', 'salary_slip']])
+elif patch_no == 179:
+	from webnotes.utils import get_defaults
+	sl = sql("select name, net_pay from `tabSalary Slip`")
+	for d in sl:
+		in_words = get_obj('Sales Common').get_total_in_words(get_defaults()['currency'], round(flt(d[1])))
+		sql("update `tabSalary Slip` set rounded_total = '%s', total_in_words = '%s' where name = '%s'" % (round(flt(d[1])), in_words, d[0]))
+elif patch_no == 180:
+	sql("delete from tabDocField where parent = 'Salary Slip' and fieldname = 'net_pay_in_words'")
+elif patch_no == 181:
+	import_from_files(record_list = [['accounts', 'doctype', 'journal_voucher']])
+elif patch_no == 182:
+	sql("update tabDocField set options = CONCAT(options, '\nWrite Off Voucher') where fieldname = 'voucher_type' and parent = 'Journal Voucher'")
+elif patch_no == 183:
+	sql("delete from tabDocField where label = 'SMS' and fieldtype = 'Section Break' and parent in  ('Enquiry', 'Lead', 'Sales Order', 'Delivery Note')")
+elif patch_no == 184:
+	from webnotes.model import delete_doc
+	delete_doc('DocType', 'Feed')
+	delete_doc('DocType', 'Feed List')
+	delete_doc('DocType', 'Feed Control')
+
+	# add trigger
+	from webnotes.model.triggers import add_trigger
+	add_trigger('*','*','*','event_updates.update_feed')
+
+	webnotes.conn.commit()
+
+	try:
+		sql("drop table tabFeed")
+		sql("drop table `tabFeed List`")
+	except: pass
+
+	# import
+	from webnotes.modules.module_manager import reload_doc
+	reload_doc('event_updates','doctype','feed')
+elif patch_no==185:
+	sql("delete from tabDocTrigger where method = 'webnotes.widgets.follow.on_docsave'")
+elif patch_no==186:
+	from webnotes.modules.module_manager import reload_doc
+	reload_doc('event_updates','doctype','feed')
+elif patch_no == 187:
+	sql("update tabDocType set autoname = '' where name = 'QA Inspection Report'")
+elif patch_no == 188:
+	import_from_files(record_list = [['buying', 'doctype', 'qa_inspection_report']])
+elif patch_no == 189:
+	sql("update `tabDocField` set allow_on_submit = 1 where fieldname in ('entries', 'other_charges') and parent = 'Receivable Voucher'")
+elif patch_no == 190:
+	sql("update tabDocField set permlevel=0 where fieldname = 'fiscal_year' and parent = 'Stock Entry'")
+elif patch_no == 191:
+	import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
+elif patch_no == 192:
+	sql("delete from `tabModule Def Item` where parent = 'Material Management' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
+	import_from_files(record_list = [['buying', 'Module Def', 'SRM']])
+elif patch_no == 193:
+	sql("update tabDocField set fieldtype='Button', `trigger`='Client' where parent='Letter Head' and fieldname='set_from_image'")
+elif patch_no == 194:
+	sql("delete from `tabModule Def Item` where parent = 'SRM' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
+	import_from_files(record_list = [['stock', 'Module Def', 'Material Management']])
+elif patch_no == 195:
+	from webnotes.modules.module_manager import reload_doc
+	reload_doc('setup','doctype','manage_account')
+elif patch_no == 196:
+	sql("update `tabModule Def` set module_page = null where name = 'Material Management'")
+elif patch_no == 197:
+	sql("update `tabDocField` set permlevel = 0, in_filter = 1 where fieldname = 'warranty_amc_status' and parent = 'Customer Issue'")
+	import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
+elif patch_no == 198:
+	sql("delete from `tabDocField` where (label in ('SMS', 'Send SMS') or fieldname in ('message', 'customer_mobile_no')) and parent in ('Quoattion', 'Sales Order', 'Delivery Note', 'Receivable Voucher')")
+	sql("delete from `tabDocField` where label in ('SMS', 'Send SMS') and parent = 'Purchase Order'")
+	sql("delete from `tabDocField` where (label in ('Send SMS', 'SMS Html') or fieldname in ('sms_message', 'lead_sms_detail', 'enquiry_sms_detail')) and parent in ('Lead', 'Enquiry')")
+	from webnotes.model import delete_doc
+	delete_doc('DocType', 'Lead SMS Detail')
+	delete_doc('DocType', 'Enquiry SMS Detail')
+elif patch_no == 199:
+	sql("update tabDocField set reqd = 0 where parent = 'Attendance' and fieldname = 'shifts'")
+elif patch_no == 200:
+	reload_doc('event_updates','page','profile_settings')
+elif patch_no == 201:
+	reload_doc('setup','doctype','price_list')
+elif patch_no == 202:
+	name1 = sql("select name from tabDocField where parent='Price List' and label='Clear Prices' limit 1,1")
+	name2 = sql("select name from tabDocField where parent='Price List' and label='Update Prices' limit 1,1")
+	if name1:
+		sql("delete from tabDocField where name=%s limit 1", name1[0][0])
+	if name2:
+		sql("delete from tabDocField where name=%s limit 1", name2[0][0])
+elif patch_no == 203:
+	sql("delete from tabDocField where parent = 'Company' and fieldname = 'default_salary_account' limit 1")
+elif patch_no == 204:
+	sql("delete from tabDocField where parent = 'Company' and fieldname = 'default_salary_acount' limit 1")
+elif patch_no == 205:
+	sql("update `tabDocField` set `default` = '' where fieldname = 'naming_series' and parent = 'Installation Note'")
+elif patch_no == 206:
+	reload_doc('selling','doctype','installation_note')
+elif patch_no == 207:
+	import_from_files(record_list = [['setup', 'doctype', 'company']])
+elif patch_no == 208:
+	sql("delete from `tabDocField` where (label in ('SMS', 'Send SMS') or fieldname in ('message', 'customer_mobile_no')) and parent ='Quotation'")
+	default_currency = get_obj('Manage Account').doc.default_currency
+	sql("update tabCompany set default_currency = '%s'" % default_currency)
+elif patch_no == 209:
+	import_from_files(record_list = [['setup', 'doctype', 'company']])
+elif patch_no == 210:
+	sql("delete FROM `tabDocField` WHERE parent = 'Lead' AND label in ('CC:','Attachment Html','Create New File','Attachment')")
+elif patch_no == 212:
+	# reload company because of disturbed UI
+	import_from_files(record_list = [['setup', 'doctype', 'company']])
+elif patch_no == 213:
+	reload_doc('selling','doctype','lead')
+	reload_doc('setup','doctype','company')
+elif patch_no == 214:
+	reload_doc('selling','doctype','sales_order')
+elif patch_no == 215:
+	# patch for item and image in description
+	sql("update tabDocField set width = '300px' where fieldname='description'")
+	reload_doc('stock', 'doctype', 'item')
+	sql("delete from __DocTypeCache")
+elif patch_no == 216:
+	import_from_files(record_list = [['stock', 'doctype', 'serial_no'], ['stock', 'doctype', 'stock_ledger_entry']])
+elif patch_no == 217:
+	sql("update tabDocField set options = '\nIn Store\nDelivered\nNot in Use' where fieldname = 'status' and parent = 'Serial No'")
+	sql("update tabDocField set no_copy = 1 where fieldname = 'serial_no' and parent = 'Delivery Note Detail'")
+	sql("update tabDocField set no_copy = 1 where fieldname = 'serial_no' and parent = 'Stock Entry Detail'")
+elif patch_no == 218:
+	for d in sql("select name from `tabSerial No`"):
+		sql("Commit")
+		sql("Start Transaction")
+		s = Document('Serial No', d[0])
+		if s.pr_no:
+			s.purchase_document_type = 'Purchase Receipt'
+			s.purchase_document_no = s.pr_no
+		if s.delivery_note_no:
+			s.delivery_document_type = 'Delivery Note'
+			s.delivery_document_no = s.delivery_note_no
+		if s.notes:
+			s.delivery_note_no = s.notes
+		s.company = webnotes.utils.get_defaults()['company']
+		s.fiscal_year = webnotes.utils.get_defaults()['fiscal_year']
+		s.save()
+elif patch_no == 219:
+	sql("delete from tabDocField where fieldname in ('pr_no', 'make', 'label', 'delivery_note_no', 'notes') and parent = 'Serial No'")
+elif patch_no == 220:
+	sql("update tabDocField set label = 'Incoming Rate' where fieldname = 'purchase_rate' and parent = 'Serial No'")
+	sql("update tabDocField set label = 'Incoming Time' where fieldname = 'purchase_time' and parent = 'Serial No'")
+elif patch_no == 221:
+	sql("update tabDocField set reqd = 1 where fieldname in ('purchase_rate', 'warehouse') and parent = 'Serial No'")
+elif patch_no == 222:
+	sql("update tabDocField set options = '\nDelivery Note\nReceivable Voucher\nStock Entry' where fieldname = 'delivery_document_type' and parent = 'Serial No'")
+elif patch_no == 223:
+	sql("update tabDocField set hidden = 0 where fieldname in ('pay_to_recd_from', 'total_amount', 'total_amount_in_words') and parent = 'Journal Voucher'")
+	sql("update tabDocField set permlevel = 0 where fieldname = 'pay_to_recd_from' and parent = 'Journal Voucher'")
+elif patch_no == 224:
+	import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail'], ['accounts', 'Print Format', 'Payment Receipt Voucher']])
+elif patch_no == 225:
+	import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
+elif patch_no == 226:
+	import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
+elif patch_no == 227:
+	reload_doc('stock', 'doctype', 'item')
+	if webnotes.conn.get_value('Control Panel', None, 'account_id') != 'axjanak2011':
+		sql("delete from tabDocField where parent = 'Item' and fieldname='alternate_description' limit 1")
+elif patch_no == 228:
+	# knowledge base patch
+	reload_doc('knowledge_base', 'doctype', 'question')
+	reload_doc('knowledge_base', 'doctype', 'answer')
+	reload_doc('knowledge_base', 'page', 'questions')
+	reload_doc('knowledge_base', 'Module Def', 'Knowledge Base')
+	sql("update `tabModule Def` set disabled='No' where name='Knowledge Base'")
+elif patch_no == 229:
+	reload_doc('knowledge_base', 'page', 'question_view')
+elif patch_no == 230:
+	reload_doc('buying', 'doctype', 'indent')
+	reload_doc('buying', 'doctype', 'indent_detail')
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
+elif patch_no == 231:
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
+elif patch_no == 232:
+	sql("update `tabDocField` set options = 'Sales Order' where fieldname = 'sales_order_no' and parent = 'Indent'")
+elif patch_no == 233:
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Receivable Voucher')
+	reload_doc('Mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher')
+elif patch_no == 234:
+	sql("update `tabTable Mapper Detail` set validation_logic = 'docstatus=1' where parent = 'Sales Order-Indent' and from_table = 'Sales Order Detail'")
+elif patch_no == 235:
+	for sc in sql("""select name from `tabSearch Criteria` where ifnull(name,'')
+		like 'srch%' or ifnull(name,'') like '%stdsrch'"""):
+		try:
+			get_obj('Search Criteria', sc[0]).rename()
+		except AttributeError, e:
+			pass
+	reload_doc('core', 'doctype', 'system_console')
+elif patch_no == 236:
+	# warehouse not mandatory for delivered serial nos
+	sql("update tabDocField set reqd=0 where parent='Serial No' and fieldname='warehouse'")
+elif patch_no == 237:
+	sql("update tabDocField set depends_on = 'eval:doc.is_pos==1' where fieldname = 'cash_bank_account' and parent = 'Receivable Voucher'")
+elif patch_no == 238:
+	reload_doc('accounts', 'doctype', 'receivable_voucher')
+	reload_doc('accounts', 'GL Mapper', 'POS with write off')
+elif patch_no == 239:
+	reload_doc('core', 'doctype', 'docfield')
+	reload_doc('core', 'doctype', 'doctype')
+	from patches.old_patches.feed_patch import set_subjects_and_tagfields
+
+	set_subjects_and_tagfields()
+elif patch_no == 240:
+	# again for sales order (status)
+	from patches.old_patches.feed_patch import set_subjects_and_tagfields
+	set_subjects_and_tagfields()
+elif patch_no == 241:
+	sql("update `tabDocField` set fieldtype = 'Text', options = '', in_filter = '' where fieldname = 'serial_no' and parent = 'Stock Ledger Entry'")
+elif patch_no == 242:
+	if webnotes.conn.get_value('Control Panel', None, 'account_id') not in ['axjanak2011']:
+		sql("commit")
+		try:
+			sql("alter table `tabStock Ledger Entry` drop index serial_no")
+		except:
+			pass
+
+		sql("alter table `tabStock Ledger Entry` change serial_no serial_no text")
+elif patch_no == 243:
+	# moving custom script and custom fields to framework
+	webnotes.conn.set_value('DocType', 'Custom Script', 'module', 'Core')
+	webnotes.conn.set_value('DocType', 'Custom Field', 'module', 'Core')
+	reload_doc('setup', 'doctype', 'company')
+elif patch_no == 244:
+	reload_doc('stock', 'search_criteria', 'shortage_to_indent')
+elif patch_no == 245:
+	from patches.old_patches.doctype_permission_patch import set_doctype_permissions
+	set_doctype_permissions()
+
+	from patches.old_patches.feed_patch import set_subjects_and_tagfields
+	set_subjects_and_tagfields()
+elif patch_no == 246:
+	webnotes.conn.set_value('DocType','Stock Entry','tag_fields','purpose')
+	webnotes.conn.set_value('DocType','Stock Entry','subject','%(remarks)s')
+elif patch_no == 247:
+	webnotes.conn.set_value('DocType','Stock Entry','subject','%(remarks)s')
+elif patch_no == 248:
+	reload_doc('setup', 'doctype', 'manage_account')
+elif patch_no == 249:
+	sql("update `tabDocPerm` t1, `tabDocType` t2 set t1.role = 'System Manager' where t1.role = 'Administrator' and t1.parent = t2.name and t2.module != 'Core'")
+elif patch_no == 250:
+	from patches.old_patches.feed_patch  import support_patch
+	support_patch()
+elif patch_no == 251:
+	from webnotes.model import db_schema
+	db_schema.remove_all_foreign_keys()
+	from patches.old_patches.customer_address import run_patch
+	run_patch()
+elif patch_no == 252:
+	reload_doc('support','doctype','support_ticket')
+	reload_doc('support','doctype','support_ticket_response')
+elif patch_no == 253:
+	reload_doc('accounts','doctype','ledger_balance_export')
+	reload_doc('accounts','doctype','ledger_detail')
+	reload_doc('accounts', 'Module Def', 'Accounts')
+
+	from webnotes.model.db_schema import updatedb
+	updatedb('Ledger Balance Export')
+	updatedb('Ledger Detail')
+elif patch_no == 254:
+	reload_doc('setup', 'doctype', 'sms_settings')
+	reload_doc('setup', 'doctype', 'static_parameter_detail')
+
+	from webnotes.model.db_schema import updatedb
+	updatedb('SMS Settings')
+	updatedb('Static Parameter Detail')
+elif patch_no == 255:
+	from patches.old_patches.customer_address import run_old_data_sync_patch
+	run_old_data_sync_patch()
+elif patch_no == 256:
+	sql("update `tabLetter Head` set content = replace(content, 'http://46.4.50.84/v170-test/', '')")
+	sql("update `tabSingles` set value = replace(value, 'http://46.4.50.84/v170-test/', '') where field in ('letter_head', 'client_name') and doctype = 'Control Panel'")
+	sql("update `tabItem` set description_html = replace(description_html, 'http://46.4.50.84/v170-test/', '')")
+elif patch_no == 257:
+	from patches.old_patches.customer_address import run_old_data_sync_patch
+	run_old_data_sync_patch()
+elif patch_no == 258:
+	sql("update tabDocField set `default`=NULL where fieldname = 'naming_series'")
+elif patch_no == 259:
+	sql("update `tabQuotation Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
+	sql("update `tabSales Order Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
+	sql("update `tabRV Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
+	sql("update `tabDelivery Note Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
+elif patch_no == 260:
+	sql("update `tabLetter Head` set content = replace(content, 'http://46.4.50.84/v170/', '')")
+	sql("update `tabSingles` set value = replace(value, 'http://46.4.50.84/v170/', '') where field in ('letter_head', 'client_name') and doctype = 'Control Panel'")
+	sql("update `tabItem` set description_html = replace(description_html, 'http://46.4.50.84/v170/', '')")
+	sql("update `tabQuotation Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
+	sql("update `tabSales Order Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
+	sql("update `tabRV Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
+	sql("update `tabDelivery Note Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
+elif patch_no == 261:
+	sql("update `tabPrint Format` set html = replace(html, 'customer_address', 'address_display')")
+elif patch_no == 262:
+	from patches.old_patches.customer_address import sync_lead_phone
+	sync_lead_phone()
+elif patch_no == 263:
+	ol = ['','Open','To Reply','Waiting for Customer','Hold','Closed']
+	sql("update tabDocField set options=%s where parent=%s and fieldname=%s", ('\n'.join(ol), 'Support Ticket', 'status'))
+elif patch_no == 264:
+	sql("delete from tabDocField where parent = 'Customer Issue' and (fieldname = 'issue_in' or fieldname = 'issue_category')")
+	sql("update tabDocField set options=NULL where parent='Support Ticket' and label = 'Send'")
+elif patch_no == 266:
+	reload_doc('setup','doctype','support_email_settings')
+elif patch_no == 267:
+	sql("update `tabPrint Format` set html = replace(html, 'supplier_address', 'address_display')")
+elif patch_no == 268:
+	sql("update `tabDocPerm` set permlevel = 0 where permlevel is null")
+elif patch_no == 269:
+	p = get_obj('Patch Util')
+	p.add_permission('GL Entry', 'Accounts User', 0, read = 1)
+elif patch_no == 270:
+	pages = ['Accounts Setup', 'Accounts', 'Accounting Reports','GeneralLedger','How do I - Accounts','Making Opening Entries',\
+	'Analysis','How do I - CRM','How do I - Inventory','Inventory Setup', 'Stock','HR','HR & Payroll Setup',\
+	'Payroll Setup','Production Setup','Production','Buying','SRM Setup','Contact Page','Forum','Messages','Test Toolbar',\
+	'Trend Analyzer']
+	from webnotes.model import delete_doc
+	sql("delete from `tabPage Visit`")
+	for p in pages:
+		try: delete_doc('Page', p)
+		except: pass
+elif patch_no == 271:
+	# tags patch
+	reload_doc('selling','doctype','sales_order')
+	reload_doc('stock','doctype','delivery_note')
+	sql("delete from tabDocField where fieldname='per_amt_billed' and parent in ('Sales Order', 'Delivery Note')")
+
+	sql("""update `tabSales Order` set delivery_status = if(ifnull(per_delivered,0) < 0.001, 'Not Delivered',
+			if(per_delivered >= 99.99, 'Fully Delivered', 'Partly Delivered'))""")
+	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'))""")
+elif patch_no == 272:
+	from webnotes.model import delete_doc
+	try:
+		delete_doc('Search Criteria', '_SRCH00003')
+	except:
+		pass
+	reload_doc('accounts', 'search_criteria', 'purchase_register')
+elif patch_no == 276:
+	from webnotes.model import delete_doc
+	sn = sql("select name from `tabSearch Criteria` where criteria_name = 'Sales Personwise Transaction Summary'")
+	for d in sn:
+		delete_doc('Search Criteria', d[0])
+	reload_doc('selling', 'search_criteria', 'sales_personwise_transaction_summary')
+elif patch_no == 277:
+	webnotes.model.delete_doc('DocType','HomePage Settings')
+	webnotes.model.delete_doc('DocType','Badge Settings')
+	sql("update tabDocType set module='Home' where module in ('Event Updates', 'My Company')")
+	sql("update tabPage set module='Home' where module in ('Event Updates', 'My Company')")
+	sql("update `tabSearch Criteria` set module='Home' where module in ('Event Updates', 'My Company')")
+
+
+	delete_pages = ('Chat User Gallery', 'Badge Info', 'Home', 'Website Setup', 'Test Page', 'Setup Masters', 'Service', 'Selling', 'Sales Reports', 'Organize','My Cart', 'My Activity', 'Manage Users', 'Maintenance', 'Getting Started', 'Gantt Test', 'Custom Reports - Stock', 'Custom Reports - Selling', 'Custom Reports - Production', 'Custom Reports - Payroll', 'Custom Reports - Maintenance', 'Custom Reports - Buying', 'Custom Reports - Accounts', 'CRM Setup', 'CRM Reports')
+	for p in delete_pages:
+	  webnotes.model.delete_doc('Page',p)
+elif patch_no == 278:
+	sql("update tabDocTrigger set method = 'home.update_feed' where method = 'event_updates.update_feed'")
+elif patch_no == 279:
+	dt = ['GL Entry', 'Stock Ledger Entry']
+	for t in dt:
+		rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tab%s` where modified >= '2011-06-15 01:00:00' group by voucher_no" % t)
+		for d in rec:
+			sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
+
+	other_dt = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note']
+	for dt in other_dt:
+		rec = sql("select name, status from `tab%s` where modified >= '2011-06-15 01:00:00'" % dt)
+		for r in rec:
+			sql("update `tab%s` set docstatus = %s where name = '%s'" % (dt, (r[1] in ['Submitted', 'Closed'] and 1 or r[1]=='Cancelled' and 2 or 0), r[0]))
+elif patch_no == 280:
+	reload_doc('accounts', 'doctype', 'form_16a')
+elif patch_no == 281:
+	dt_list = ['Delivery Note', 'Purchase Receipt']
+	for dt in dt_list:
+		sql("update `tab%s` set status = 'Submitted' where docstatus = 1 and modified >='2011-06-15 01:00:00'" % dt)
+		sql("update `tab%s` set status = 'Cancelled' where docstatus = 2 and modified >='2011-06-15 01:00:00'" % dt)
+elif patch_no == 282:
+	dt_list = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note', 'Receivable Voucher', 'Payable Voucher', 'Delivery Note', 'Purchase Receipt', 'Journal Voucher', 'Stock Entry']
+	for d in dt_list:
+		tbl = sql("select options from `tabDocField` where fieldtype = 'Table' and parent = '%s'" % d)
+		for t in tbl:
+			sql("update `tab%s` t1, `tab%s` t2 set t1.docstatus = t2.docstatus where t1.parent = t2.name" % (t[0], d))
+elif patch_no == 283:
+	rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tabGL Entry` where modified >= '2011-06-15 01:00:00' order by name ASC")
+	for d in rec:
+		sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
+elif patch_no == 284:
+	reload_doc('support', 'doctype', 'support_ticket')
+	sql("update `tabDocField` set in_filter = 1 where fieldname in ('raised_by', 'subject') and parent = 'Support Ticket'")
+elif patch_no == 286:
+	reload_doc('accounts', 'search_criteria', 'itemwise_sales_register')
+	reload_doc('accounts', 'search_criteria', 'itemwise_purchase_register')
+elif patch_no == 287:
+	sql("update `tabDocField` set no_copy = 1 where fieldname in ('per_received', 'per_billed', 'per_delivered') and parent in ('Purchase Order', 'Purchase Receipt', 'Sales Order', 'Delivery Note')")
+elif patch_no == 288:
+	reload_doc('accounts', 'doctype', 'payable_voucher')
+elif patch_no == 289:
+	sql("update `tabDocType` set subject = 'From %(supplier_name)s worth %(grand_total)s due on %(due_date)s | %(outstanding_amount)s outstanding' where name = 'Payable Voucher'")
+	sql("update `tabDocType` set search_fields = 'status,transaction_date,customer,lead,order_type' where name = 'Quotation'")
+elif patch_no == 290:
+	count = sql("""SELECT * FROM  `tabModule Def`
+		   WHERE `module_name` LIKE 'Home'""")
+	if not count:
+		md = Document('Module Def')
+		md.module_name = 'Home'
+		md.module_label = 'Home'
+		md.save(1)
+elif patch_no == 291:
+	reload_doc('utilities','doctype','rename_tool')
+elif patch_no == 292:
+	reload_doc('accounts', 'search_criteria', 'trial_balance')
+elif patch_no == 293:
+	sql("delete from tabDocField where parent='Account' and fieldname='address'")
+	reload_doc('accounts', 'doctype', 'account')
+elif patch_no == 294:
+	# new account profile fix
+	ul = sql("select name from tabProfile where ifnull(name,'') not in ('Administrator', 'Guest', '')")
+	# if one user and one user has no roles
+	if len(ul)==1 and not sql("select parent from tabUserRole where role='System Manager' and parent=%s", ul[0][0]):
+		get_obj('Setup Control').add_roles(Document('Profile', ul[0][0]))
+elif patch_no == 295:
+	sql("update `tabDocField` set options = 'Delivered\nNot Delivered\nPartly Delivered\nClosed\nNot Applicable' where parent = 'Sales Order' and fieldname = 'delivery_status'")
+	sql("update `tabDocField` set options = 'Billed\nNot Billed\nPartly Billed\nClosed' where parent = 'Sales Order' and fieldname = 'billing_status'")
+elif patch_no == 296:
+	sql("delete from tabDocField where parent='Support Ticket' and fieldname='contact_no'")
+	reload_doc('support', 'doctype', 'support_ticket')
+elif patch_no == 297:
+	reload_doc('hr', 'doctype', 'employee')
+	reload_doc('hr', 'doctype', 'attendance')
+	reload_doc('hr', 'doctype', 'expense_voucher')
+	reload_doc('hr', 'doctype', 'appraisal')
+	reload_doc('hr', 'doctype', 'salary_structure')
+	reload_doc('hr', 'doctype', 'salary_slip')
+elif patch_no == 298:
+	sql("update `tabDocField` set options = 'link:Company' where parent = 'Attendance' and fieldname = 'company'")
+	sql("update `tabDocField` set options = 'link:Company' where parent = 'Expense Voucher' and fieldname = 'company'")
+	sql("update `tabDocField` set options = 'link:Company' where parent = 'Appraisal' and fieldname = 'company'")
+elif patch_no == 299:
+	sql("update `tabDocPerm` set `match` = NULL where parent = 'Employee' and role = 'Employee'")
+elif patch_no == 300:
+	sql("""DELETE FROM `tabSearch Criteria` WHERE name IN
+		   ('sales_register1', 'sales_register2', 'purchase_register1')""")
\ No newline at end of file
diff --git a/patches/patch.py b/patches/patch.py
index 9a2bb83..7f0cf69 100644
--- a/patches/patch.py
+++ b/patches/patch.py
@@ -1,8 +1,7 @@
 # REMEMBER to update this
 # ========================
 
-last_patch = 343
-
+last_patch = 344
 #-------------------------------------------
 
 def execute(patch_no):
@@ -13,1183 +12,8 @@
 	sql = webnotes.conn.sql
 	from webnotes.utils import cint, cstr, flt
 	from webnotes.model.doc import Document
-
-	if patch_no==33:
-		pass
-	elif patch_no==34:
-		webnotes.conn.sql("update `tabDocField` set options = 'Letter Head', print_hide = 1 where fieldname = 'letter_head' and fieldtype = 'Link'")
-	elif patch_no==35:
-		webnotes.conn.sql("update tabDocType set module = 'Event Updates' where name = 'Feed Control'")
-	elif patch_no==36:
-		# remove delivery note foreign key in Serial Number
-		from webnotes.model.db_schema import DbTable
-		t = DbTable('Serial No')
-		fk_list  = t.get_foreign_keys()
-		for f in fk_list:
-			if f[0]=='delivery_note_no':
-				webnotes.conn.commit()
-				webnotes.conn.sql("alter table `tabSerial No` drop foreign key `%s`" % f[1])
-				webnotes.conn.begin()
-				webnotes.conn.sql("update tabDocField set fieldtype='Data' where fieldname='delivery_note_no' and parent='Serial No' limit 1")
-	elif patch_no==37:
-		import os
-		mod_path = webnotes.defs.modules_path
-		path_list = []
-		for m in os.listdir(mod_path):
-			for t in ['doctype', 'page', 'search_criteria']:
-				dt_path = os.path.join(mod_path, m, t)
-				if os.path.exists(dt_path):
-					for dt in os.listdir(dt_path):
-						if '.' not in dt and os.path.exists(os.path.join(dt_path, dt, dt+ '.txt')):
-							path_list.append(os.path.join(dt_path, dt, dt+ '.txt'))
-
-		for d in path_list:
-			doclist = eval(open(d,'r').read())
-			webnotes.conn.sql("update `tab%s` set module = '%s' where name = '%s'" % (doclist[0]['doctype'], doclist[0]['module'], doclist[0]['name']))
-
-	elif patch_no==38:
-		import webnotes
-		webnotes.conn.set_global("system_message", "System Updates: Hello! You would have noticed some changes on the Home Page. As a part of our commitment to make the system more friendly and social, we have re-designed the feed so that now you will only see feed that is relevant to you (either you have created something or you have been mentioned in the document).<br><br>On the individual listings, you can add tags and also color them!<br><br>You will also get time-to-time updates from our side here. Do keep sending your feedback at support@erpnext.com.")
-		webnotes.conn.set_global("system_message_id", "1")
-
-	elif patch_no == 39:
-		pass
-
-	elif patch_no == 40:
-		import_from_files(record_list=[['material_management','doctype','item']])
-
-	elif patch_no == 42:
-		acc = sql("select name, lft, rgt from tabAccount where account_name in ('Incomes', 'Expenses')")
-		for d in acc:
-			sql("update tabAccount set is_pl_account = 'Yes' where lft >= '%s' and rgt <= '%s'" % (d[1], d[2]))
-	elif patch_no == 43:
-		import webnotes.model
-		webnotes.model.delete_doc('Page', 'Module Manager')
-
-	# cleanup of Service, Customer Support, Utilities Modules
-	# -------------------------------------------------------
-	elif patch_no == 44:
-		from webnotes.model import delete_doc
-
-		for dt in sql("select name from tabDocType where module in ('Customer Support')"):
-			delete_doc('DocType', dt[0])
-
-		for dt in sql("select name from `tabSearch Criteria` where module in ('Customer Support')"):
-			delete_doc('Search Criteria', dt[0])
-
-		for dt in sql("select name from tabPage where module in ('Customer Support')"):
-			delete_doc('Page', dt[0])
-
-		# move a couple
-		webnotes.conn.sql("update `tab%s` set module=%s where name=%s" % ('DocType', '%s', '%s'), ('Application Internal', 'Patch Util'))
-		webnotes.conn.sql("update `tab%s` set module=%s where name=%s" % ('DocType', '%s', '%s'), ('Application Internal', 'DocType Property Setter'))
-
-		# remove utilities
-		webnotes.conn.sql('delete from `tabModule Def` where name in ("Customer Support", "Utilities")')
-
-	elif patch_no == 45:
-		webnotes.conn.sql('delete from tabDocField where options="Ticket Response Detail"')
-
-	elif patch_no == 46:
-		import webnotes
-		webnotes.conn.set_global("system_message", "<b>SYSTEM DOWNTIME:</b> Hello! As part of our commitment to keep improving the service, we are planning a scheduled maintenance on our servers for 4 hrs on 16-Jan-2011(Sunday), from 10AM to 2PM. Do keep sending your feedback at support@erpnext.com.")
-		webnotes.conn.set_global("system_message_id", "2")
-
-	elif patch_no == 47:
-		import webnotes
-		webnotes.conn.set_global("system_message", "")
-		webnotes.conn.set_global("system_message_id", "3")
-
-	elif patch_no == 48:
-		webnotes.conn.sql("update tabDocField set options = 'Print Heading' where fieldname = 'select_print_heading'")
-
-	elif patch_no == 49:
-		webnotes.conn.sql("update tabDocType set autoname = '' where name = 'Search Criteria'")
-	elif patch_no == 50:
-		sql("update tabDocField set in_filter = 1 where fieldname in ('cost_center', 'income_account', 'Item Group') and parent = 'RV Detail'")
-	elif patch_no == 51:
-		sql("update tabDocField set options = 'link:Print Heading' where fieldtype = 'Select' and fieldname = 'select_print_heading' and parent = 'POS Setting'")
-	elif patch_no == 52:
-		sql("update tabDocField set print_hide = 1 where fieldname = 'letter_head'")
-	elif patch_no == 53:
-		sql("update tabDocType set search_fields = 'lead_name,lead_owner,status,contact_by,contact_date' where name = 'Lead'")
-	elif patch_no == 54:
-		sql("delete from tabDocField where parent = 'Supplier' and label = 'Supplier Contacts' and fieldtype = 'Section Break'")
-	elif patch_no == 55:
-		sql("commit")
-		try:
-			sql("alter table tabFeed add column `_user_tags` varchar(180)")
-		except Exception, e:
-			if e.args[0]!=1060:
-				raise e
-	elif patch_no == 56:
-		sql("delete from `tabModule Def Item` where parent = 'CRM' and doc_type = 'Reports' and doc_name = 'Delivery Note' and display_name = 'Territory, Item Group wise GP'")
-	elif patch_no == 57:
-		import_from_files(record_list=[['selling','doctype','sales_order_detail']])
-
-	elif patch_no == 58:
-		# module def patches
-		sql("update `tabModule Def` set module_page = NULL where name not in ('Event Updates', 'Setup', 'My Company')")
-		sql("delete from `tabModule Def Item` where doc_type in ('Separator', 'Setup Forms', 'More Reports')")
-		sql("delete from `tabModule Def Item` where doc_name = 'Project Activity'")
-		sql("update `tabModule Def` set module_label = 'People', disabled='No', is_hidden='No' where name = 'My Company'")
-
-		# insert new module items
-		from webnotes.model.doc import make_autoname
-		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Ticket'"):
-			sql("""insert into `tabModule Def Item`
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
-				(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Ticket', 'Task', 1)""", make_autoname('MDI.#####'))
-
-		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Timesheet'"):
-			sql("""insert into `tabModule Def Item`
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
-				(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Timesheet', 'Timesheet', 2)""", make_autoname('MDI.#####'))
-
-		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Projects'"):
-			sql("""insert into `tabModule Def Item`
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
-				(%s, 'Projects', 'Module Def', 'items', 0, 'Pages', 'Projects', 'Gantt Chart', 1)""", make_autoname('MDI.#####'))
-
-	elif patch_no == 59:
-		webnotes.conn.set_value('Control Panel',None,'mail_footer','')
-		webnotes.conn.set_global('global_mail_footer','<div style="margin-top:8px; padding: 8px; font-size: 11px; text-align:right; border-top: 1px solid #AAA">Sent via <a href="https://www.erpnext.com">ERPNext</a></div>')
-	elif patch_no == 60:
-		sql("delete from `tabModule Def Item` where display_name = 'Point of Sales'")
-	elif patch_no == 61:
-		sql("delete from `tabTDS Category Account` where company not in (select name from tabCompany)")
-	elif patch_no == 62:
-		# Import Supplier Quotation
-		import_from_files(record_list=[['srm','doctype','supplier_quotation']])
-
-		# Adding Status Filter
-		sql("update tabDocType set search_fields = concat('status,',search_fields) where name IN ('Delivery Note','Leave Transaction')")
-		# Import Other Charges
-
-		import_from_files(record_list=[['setup','doctype','other_charges']])
-	elif patch_no == 63:
-		sql("update `tabDocField` set permlevel = 1 where fieldname in ('return_date', 'return_details') and parent = 'Sales and Purchase Return Wizard'")
-		import_from_files(record_list = [['accounts', 'doctype', 'rv_detail'], ['material_management', 'doctype', 'sales_and_purchase_return_wizard'], ['material_management', 'doctype', 'stock_entry']])
-
-	elif patch_no == 64:
-		sql("update tabDocField set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where options in ('RFQ','Supplier Quotation')")
-		sql("update tabDocType set `read_only` = 1, in_create = 1 where name in ('RFQ','Supplier Quotation')")
-		sql("update tabDocField set `report_hide` = 0 where fieldname in ('email_id','phone_1','fax_1') and parent = 'Customer'")
-	elif patch_no == 65:
-		# Monthly Trend Analyzer <-> Trend Analyzer
-		sql("update `tabSearch Criteria` set criteria_name = 'Trend Analyzer' where criteria_name = 'Monthly Trend Analyzer' and name = 'SRCH/00159'")
-		sql("update `tabModule Def Item` set display_name = 'Trend Analyzer' where parent = 'Analysis' and display_name = 'Monthly Trend Analyzer'")
-	elif patch_no == 66:
-		import webnotes
-		webnotes.conn.set_global("system_message", """<h3>UI Updates</h3>Based on user feedback, we have made a couple of changes in the UI:<ul><li>Sidebar menus are now collapsable</li><li>Forms are now scrollable (we removed the confusing tabs)</li><li>Feed is a lot more descriptive</li></ul>Do send us your feedback!""")
-		webnotes.conn.set_global("system_message_id", "4")
-
-		sql("update `tabModule Def Item` set doc_type = 'Setup Forms' where doc_name in ('TDS Payment', 'TDS Return Acknowledgement', 'Form 16A', 'Period Closing Voucher', 'IT Checklist')")
-		from webnotes.session_cache import clear_cache
-		clear_cache(webnotes.session['user'])
-	elif patch_no == 67:
-		sql("update `tabDocField` set in_filter = 1 where fieldname = 'brand' and parent = 'RV Detail'")
-		sql("delete from `tabModule Def Item` where (display_name = 'Sales Invoice' and parent = 'CRM') or (display_name = 'Purchase Invoice' and parent = 'SRM')")
-	elif patch_no == 68:
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['hr','doctype','employee'],['roles','Role','Employee']])
-	elif patch_no == 69:
-		# delete flds from employee master
-		p = get_obj('Patch Util')
-		emp_del_flds = ['month_of_birth']
-		for f in emp_del_flds:
-			p.delete_field('Employee', f)
-
-		sql("Update tabDocField set `default` = 'Active' where fieldname = 'status' and parent = 'Employee'")
-
-		# map parent flds
-		fld_map = ['cell_number', 'personal_email', 'person_to_be_contacted', 'relation', 'emergency_phone_number', 'pan_number', 'passport_number', 'date_of_issue', 'valid_upto', 'place_of_issue', 'marital_status', 'blood_group', 'permanent_accommodation_type']
-
-		emp_prof = sql("select t1.name, t1.employee, t1.permanent_address_line_1, t1.permanent_address_line_2, t1.city1, t1.state1, t1.country1, t1.pin_code1, t1.phn_no1, t1.present_address_line_1, t1.present_address_line_2, t1.city2, t1.state2, t1.country2, t1.pin_code2, t1.phn_no2, t1.fathers_name, t1.fathers_occupation, t1.mothers_name, t1.mothers_occupation, t1.spouses_name, t1.spouses_occupation, t1.height_cms, t1.weight_kgs, t1.allergies, t1.other_medical_concerns, t1.physical_handicap from `tabEmployee Profile` t1, `tabEmployee` t2 where t1.employee = t2.name")
-		for e in emp_prof:
-			prof_obj = get_obj('Employee Profile', e[0])
-			emp_obj = get_obj('Employee', e[1])
-			for d in fld_map:
-				emp_obj.doc.fields[d] = prof_obj.doc.fields[d]
-			emp_obj.doc.current_accommodation_type = prof_obj.doc.present_accommodation_type
-
-			# address
-			per_addr = cstr(e[2]) + '\n' + cstr(e[3]) + '\n' + cstr(e[4]) + '\n' + cstr(e[5]) + ', ' + cstr(e[6]) + '\n' + 'PIN - ' + cstr(e[7]) + '\n' + 'Ph. No' + cstr(e[8])
-			cur_addr = cstr(e[9]) + '\n' + cstr(e[10]) + '\n' + cstr(e[11]) + '\n' + cstr(e[12]) + ', ' + cstr(e[13]) + '\n' + 'PIN - ' + cstr(e[14]) + '\n' + 'Ph. No' + cstr(e[15])
-			emp_obj.doc.permanent_address = per_addr
-			emp_obj.doc.current_address = cur_addr
-			#family
-			fam = "Father's Name: " + cstr(e[16]) + '\n' + "Father's Occupation: " + cstr(e[17]) + '\n' + "Mother's Name: " + cstr(e[18]) + '\n' + "Mother's Occupation: " + cstr(e[19]) + '\n' + "Spouse's Name: " + cstr(e[20]) + '\n' + "Spouse's Occupation: " + cstr(e[21])
-			emp_obj.doc.family_background = fam
-			# health
-			health = 'Height(cms): ' + cstr(e[22]) + '\n' + 'Weight(kgs): ' + cstr(e[23]) + '\n' + 'Allergies: ' +cstr( e[24]) + '\n' + 'Other Medical Concern: ' + cstr(e[25]) + '\n' + 'Physically Handicapped(if any): ' + cstr(e[26])
-			emp_obj.doc.health_details = health
-			emp_obj.doc.save()
-
-
-		# map tables
-		tbl_list = ['Experience In Company Detail', 'Previous Experience Detail', 'Educational Qualifications Detail']
-		for t in tbl_list:
-			sql("update `tab%s` t1, `tabEmployee Profile` t2 set t1.parent = t2.employee, t1.parenttype = 'Employee' where t1.parent = t2.name" % t)
-
-
-		# overwrite idx?????????
-
-
-		# delete emp profile
-		webnotes.model.delete_doc('DocType', 'Employee Profile')
-		for e in emp_prof:
-			webnotes.model.delete_doc('Employee Profile', e[0])
-
-	elif patch_no == 70:
-		# update search criteria module -> System
-		sql("update tabDocType set module='System' where name='Search Criteria'")
-
-		# Cleanups to Contact
-		sql("update tabDocField set fieldtype='Data' where options='Designation' and parent='Contact'")
-		sql("update tabDocField set fieldtype='Data' where options='Department' and parent='Contact'")
-		sql("update tabDocField set depends_on='eval:(cint(doc.is_customer) || cint(doc.is_supplier) || cint(doc.is_sales_partner))' where fieldname='is_primary_contact' and parent='Contact'")
-
-		# import Contact, Employee
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['utilities','doctype','contact']])
-
-
-		# remove last_contact_date from Lead
-		sql("delete from tabDocField where fieldname='last_contact_date' and parent='Lead'")
-
-	elif patch_no == 71:
-		# Make Stock Qty and Conversion Factor field editable. Also no need to mention Conversion factor in table can do it directly
-		sql("update `tabDocField` set `permlevel` = 0, `width` = '100px', `trigger` = 'Client' where parent IN ('PO Detail','Purchase Receipt Detail') and fieldname in ('stock_qty','conversion_factor')")
-		sql("update `tabDocField` set `width` = '100px' where parent IN ('PO Detail','Purchase Receipt Detail') and fieldname = 'stock_uom'")
-
-	elif patch_no == 72:
-		# Core Patch
-		# ----------
-
-		from webnotes.modules.import_module import import_from_files
-
-		# import module def
-		import_from_files(record_list = [['core', 'Module Def', 'Core']])
-	elif patch_no == 73:
-		# set module in DocTypes
-		sql("update tabDocType set module='Core' where name in ('DocType', 'DocField', 'DocPerm', 'Role', 'UserRole', 'Profile', 'Print Format', 'DocFormat', 'Control Panel', 'Event', 'Event Role', 'Event User', 'DefaultValue', 'Default Home Page', 'File', 'File Group', 'File Data', 'Letter Head', 'Module Def', 'Module Def Item', 'Module Def Role', 'Page', 'Page Role', 'Search Criteria', 'DocType Label', 'DocType Mapper', 'Field Mapper Detail', 'Table Mapper Detail')")
-
-		# set module in Page
-		sql("update tabPage set module='Core' where name='Login Page'")
-
-		# move file browser to Tools
-		sql("update tabPage set module='Tools' where name='File Browser'")
-		sql("update tabDocType set module='Tools' where name='File Browser Control'")
-		sql("update tabDocType set module='Application Internal' where name='Profile Control'")
-	elif patch_no == 74:
-		p = get_obj('Patch Util')
-		# permission
-		p.delete_permission('Employee', 'Administrator', 0)
-		p.delete_permission('Employee', 'Administrator', 1)
-		p.add_permission('Employee', 'Employee', 0, read = 1, match = 'owner')
-		p.add_permission('Employee', 'Employee', 1, read = 1, match = 'owner')
-		sql("delete from `tabDocField` where parent = 'Employee' and label = 'Payroll Rule'")
-	elif patch_no == 75:
-		#sal structure patch
-		# import
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr','doctype','earning_detail'],['hr','doctype','deduction_detail']])
-	elif patch_no == 76:
-		# property
-		p = get_obj('Patch Util')
-		p.set_field_property('Salary Structure', 'is_active', 'default', 'Yes')
-		p.set_field_property('Salary Structure', 'ctc', 'reqd', '1')
-		p.set_field_property('Earning Detail', 'modified_value', 'width', '')
-		p.set_field_property('Earning Detail', 'modified_value', 'trigger', 'Client')
-		p.set_field_property('Deduction Detail', 'd_modified_amt', 'width', '')
-		p.set_field_property('Earning Detail', 'd_modified_amt', 'trigger', 'Client')
-		sql("Update tabDocField set `description` = 'You can create more earning and deduction type from Setup --> HR' where label = 'Earning & Deduction' and parent = 'Salary Structure' and fieldtype = 'Section Break'")
-
-		# delete
-		sql("update `tabSalary Structure` set net_pay = total")
-		sql("delete from tabDocField where label in ('LWP Help', 'Calculate Total', 'Total') and parent = 'Salary Structure'")
-		sql("delete from tabDocPerm where parent in ('Earning Detail', 'Deduction Detail')")
-
-
-		# permission
-		p.delete_permission('Salary Structure', 'Administrator', 0)
-		p.delete_permission('Salary Structure', 'Administrator', 1)
-		p.add_permission('Salary Structure', 'Employee', 0, read = 1, match = 'owner')
-		p.add_permission('Salary Structure', 'Employee', 1, read = 1, match = 'owner')
-	elif patch_no == 77:
-		# sal slip patch
-		# import
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['hr','doctype','salary_slip'], ['hr','doctype','ss_earning_detail'],['hr','doctype','ss_deduction_detail'], ['mapper', 'DocType Mapper', 'Salary Structure-Salary Slip']])
-	elif patch_no == 78:
-		p = get_obj('Patch Util')
-		# delete
-		sql("update `tabSalary Slip` set leave_encashment_amount = encashment_amount")
-		p.delete_field('Salary Slip', 'encashment_amount')
-		p.delete_field('Salary Slip', 'year')
-		p.delete_field('Salary Slip', 'flag')
-		sql("delete from tabDocField where label = 'Process Payroll' and parent = 'Salary Slip'")
-
-		# field property
-		p.set_field_property('Salary Slip', 'bank_name', 'permlevel', '1')
-		p.set_field_property('Salary Slip', 'leave_without_pay', 'permlevel', '0')
-		p.set_field_property('Salary Slip', 'leave_without_pay', 'trigger', 'Client')
-		p.set_field_property('SS Earning Detail', 'e_type', 'permlevel', '0')
-		p.set_field_property('SS Earning Detail', 'e_type', 'fieldtype', 'Link')
-		p.set_field_property('SS Earning Detail', 'e_type', 'options', 'Earning Type')
-		p.set_field_property('SS Deduction Detail', 'd_type', 'permlevel', '0')
-		p.set_field_property('SS Deduction Detail', 'd_type', 'fieldtype', 'Link')
-		p.set_field_property('SS Deduction Detail', 'd_type', 'options', 'Deduction Type')
-		sql("update `tabSS Earning Detail` set e_modified_amount = e_amount")
-		sql("update `tabSS Deduction Detail` set d_modified_amount = d_amount")
-
-		# permission
-		p.delete_permission('Salary Slip', 'Administrator', 0)
-		p.delete_permission('Salary Slip', 'Administrator', 1)
-		p.add_permission('Salary Slip', 'Employee', 0, read = 1, match = 'owner')
-		p.add_permission('Salary Slip', 'Employee', 1, read = 1, match = 'owner')
-	elif patch_no == 79:
-		# Import Modules
-		import_from_files(record_list=[['hr','doctype','leave_application'],['hr','doctype','leave_allocation'],['hr','doctype','leave_control_panel'],['hr','doctype','holiday_list'],['hr','doctype','holiday_list_detail'],['hr','Module Def','HR']])
-	elif patch_no == 80:
-		# Holiday List
-		sql("update `tabHoliday List Detail` set description = holiday_name")
-		sql("delete from tabDocField where parent = 'Holiday List Detail' and fieldname = 'holiday_name'")
-		sql("update tabDocField set fieldtype = 'Select', options = 'link:Fiscal Year' where parent = 'Holiday List' and fieldname = 'fiscal_year'")
-		sql("delete from tabDocPerm where role in ('Administrator','HR User') and parent = 'Holiday List'")
-
-		# Leave Control Panel
-		# --------------------
-		sql("delete from `tabDocField` where parent = 'Leave Control Panel' and label in ('Leave Control Panel','Allocation Details') and fieldtype = 'Section Break'")
-		sql("delete from tabDocField where parent = 'Leave Control Panel' and fieldname in ('col_brk3','allocation_type','col_brk2','from_date','to_date','leave_transaction_type','posting_date')")
-		sql("update tabDocField set fieldtype = 'Select', options = 'link:Fiscal Year' where parent = 'Leave Control Panel' and fieldname = 'fiscal_year'")
-		sql("update tabDocField set fieldtype = 'Select', options = 'link:Leave Type' where parent = 'Leave Control Panel' and fieldname = 'leave_type'")
-		sql("update tabDocField set reqd = 1 where parent = 'Leave Control Panel' and fieldname = 'no_of_days'")
-
-		# Leave Application
-		# ------------------
-		for d in sql("select * from `tabLeave Transaction` where leave_transaction_type = 'Deduction' and ifnull(deduction_type, '') = 'Leave'", as_dict = 1):
-			lp = Document('Leave Application')
-			lp.employee = d['employee']
-			lp.leave_type = d['leave_type']
-			lp.posting_date = d['date']
-			lp.fiscal_year = d['fiscal_year']
-			lp.leave_balance = d['pre_balance']
-			lp.half_day = d['half_day']
-			lp.from_date = d['from_date']
-			lp.to_date = d['to_date']
-			lp.total_leave_days = d['total_leave']
-			lp.description = d['reason']
-			lp.docstatus = cint(d['docstatus'])
-			lp.save(1)
-
-		# Leave Allocation
-		# -----------------
-		for d in sql("select * from `tabLeave Transaction` where leave_transaction_type = 'Allocation'", as_dict = 1):
-			la = Document('Leave Allocation')
-			la.employee = d['employee']
-			la.leave_type = d['leave_type']
-			la.posting_date = d['date']
-			la.fiscal_year = d['fiscal_year']
-			la.new_leaves_allocated = d['total_leave']
-			la.total_leaves_allocated = d['total_leave']
-			la.description = d['reason']
-			la.docstatus = cint(d['docstatus'])
-			la.save(1)
-
-		# Payroll Module Def
-		# -------------------
-		sql("delete from `tabModule Def Item` where doc_name = 'Leave Transaction' and display_name = 'Leave Transaction' and parent = 'Payroll' and doc_type = 'Forms'")
-
-	elif patch_no == 81:
-		# Import Modules
-		import_from_files(record_list=[['hr','Module Def','HR']])
-	elif patch_no == 82:
-		sql("update tabDocType set search_fields = 'employee,leave_type,total_leaves_allocated,fiscal_year' where name = 'Leave Allocation'")
-		sql("update tabDocType set search_fields = 'employee,leave_type,from_date,to_date,total_leave_days,fiscal_year' where name = 'Leave Application'")
-	elif patch_no == 83:
-		# delete leave transaction
-		webnotes.conn.sql("set foreign_key_checks=0")
-		sql("delete from `tabLeave Transaction`")
-		import webnotes.model
-		webnotes.model.delete_doc('DocType','Badge Settings Detail')
-		webnotes.model.delete_doc('DocType','Leave Transaction')
-		webnotes.conn.sql("set foreign_key_checks=1")
-	elif patch_no == 84:
-		p = get_obj('Patch Util')
-		p.set_field_property('SS Earning Detail', 'e_amount', 'permlevel', '1')
-		p.set_field_property('SS Deduction Detail', 'd_amount', 'permlevel', '1')
-	elif patch_no == 85:
-		# permission
-		p = get_obj('Patch Util')
-		p.add_permission('Leave Application', 'Employee', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
-		p.add_permission('Leave Application', 'Employee', 1, read = 1, match = 'owner')
-		p.add_permission('Leave Allocation', 'HR User', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
-		p.add_permission('Leave Allocation', 'HR User', 1, read = 1)
-		sql("update tabDocPerm set `match` = '' where parent = 'Leave Application' and role = 'HR User'")
-	elif patch_no == 86:
-		# Import Modules
-		import_from_files(record_list=[['hr','doctype','leave_type']])
-	elif patch_no == 87:
-		sql("update `tabLeave Type` set is_lwp = 1 where name = 'Leave Without Pay'")
-	elif patch_no == 88:
-		# Import Modules
-		import_from_files(record_list=[['hr','doctype','leave_allocation']])
-
-	elif patch_no == 89:
-		sql("delete from `tabModule Def Item` where doc_type = 'Setup Forms' and doc_name in ('Payroll Rule', 'IT Checklist', 'Employee Profile') and parent = 'Payroll'")
-		sql("update `tabDocField` set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where parent = 'Leave Type' and fieldname = 'is_encash'")
-	elif patch_no == 90:
-		sql("update `tabLeave Allocation` set docstatus = 1")
-	elif patch_no == 91:
-		import webnotes
-		webnotes.conn.set_global("system_message", """<h3>System Updates</h3>Based on user feedback, we have cleaned up HR module (Partly):<ul><li>Employee and Employee Profile are merged into a single document</li><li>Salary Structure and Salary Slip are now more user friendly</li><li>Leave Transaction document is now divided into 2 documents Leave Application and Leave Allocation</li></ul>We will work on Reports, Attendance and other documents of Payroll module next week<br><br> Do send us your feedback!""")
-		webnotes.conn.set_global("system_message_id", "5")
-	elif patch_no == 92:
-		sql("update tabDocField set label = 'Get Charges' where parent IN ('Sales Order','Delivery Note','Receivable Voucher') and label = 'Get Other Charges' and fieldtype = 'Button'")
-		# Automated Other Charges Calculation basis
-		sql("update tabDocField set options = '', `trigger` = 'Client' where parent IN ('Quotation','Sales Order','Delivery Note','Receivable Voucher') and label = 'Get Charges' and fieldtype = 'Button'")
-	elif patch_no == 93:
-		sql("update `tabTable Mapper Detail` set validation_logic = 'qty > ifnull(billed_qty,0) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail'")
-		sql("update `tabField Mapper Detail` set from_field = 'customer' where to_field = 'customer' and parent = 'Sales Order-Receivable Voucher'")
-	elif patch_no == 94:
-		import_from_files(record_list=[['selling','doctype','sms_center']])
-	elif patch_no == 95:
-		import_from_files(record_list=[['mapper','DocType Mapper','Sales Order-Receivable Voucher'], ['mapper','DocType Mapper','Delivery Note-Receivable Voucher']])
-	elif patch_no == 96:
-		sql("delete from `tabModule Def Item` where doc_type = 'Reports' and display_name = 'Cenvat Credit - Input or Capital Goods' and parent = 'Accounts'")
-	elif patch_no == 97:
-		sql("update tabFeed set doc_label = 'Feed', doc_name = name where ifnull(doc_name,'') = '' and ifnull(doc_label,'') = ''")
-	elif patch_no == 98:
-		import_from_files(record_list=[['accounts','doctype','payable_voucher']])
-	elif patch_no == 99:
-		import_from_files(record_list=[['accounts','doctype','account']])
-	elif patch_no == 100:
-		p = get_obj('Patch Util')
-		p.set_field_property('Account', 'level', 'hidden', '1')
-		p.set_field_property('Account', 'level', 'print_hide', '1')
-		p.set_field_property('Account', 'account_type', 'search_index', '0')
-		p.set_field_property('TDS Detail', 'tds_category', 'width', '150px')
-		p.set_field_property('TDS Detail', 'special_tds_rate_applicable', 'width', '150px')
-		p.set_field_property('TDS Detail', 'special_tds_rate', 'width', '150px')
-		p.set_field_property('TDS Detail', 'special_tds_limit', 'width', '150px')
-	elif patch_no == 101:
-		# Leave Application Details and Leave Allocation Details
-		sql("update tabDocField set search_index = 1, in_filter = 1 where fieldname in ('employee','leave_type','fiscal_year') and parent in ('Leave Application','Leave Allocation')")
-		get_obj('DocType','Leave Application').doc.save()
-		get_obj('DocType','Leave Allocation').doc.save()
-	elif patch_no == 102:
-		# make item description field editable in production order
-		sql("update tabDocField set permlevel = 0 where fieldname = 'description' and parent = 'Production Order'")
-	elif patch_no == 103:
-		sql("update tabDocField set fieldname = '' where fieldtype = 'HTML'")
-	elif patch_no == 104:
-		import_from_files(record_list=[['hr','search_criteria','stdsrch_00001'],['hr','search_criteria','stdsrch_00002'],['hr','search_criteria','stdsrch_00003'],['hr','Module Def','HR'],['hr','doctype','leave_application'],['hr','doctype','leave_allocation']])
-
-	elif patch_no == 105:
-		# Employee Leave Balance
-		sql("delete from `tabModule Def Item` where parent = 'Payroll' and doc_type = 'Reports' and display_name IN ('Employeewise Leave Transaction Details','Employeewise Balance Leave Report')")
-		# Update Search Fields
-		sql("update tabDocType set search_fields = 'employee,employee_name,leave_type,from_date,to_date,total_leave_days,fiscal_year' where name = 'Leave Application'")
-		sql("update tabDocType set search_fields = 'employee,employee_name,leave_type,total_leaves_allocated,fiscal_year' where name = 'Leave Allocation'")
-	elif patch_no == 106:
-		for d in sql("select name,employee,employee_name from `tabLeave Allocation`"):
-			if not cstr(d[2]):
-				sql("update `tabLeave Allocation` set employee_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Employee',cstr(d[1]),'employee_name'), cstr(d[0])))
-		for d in sql("select name,employee,employee_name from `tabLeave Application`"):
-			if not cstr(d[2]):
-				sql("update `tabLeave Application` set employee_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Employee',cstr(d[1]),'employee_name'), cstr(d[0])))
-	elif patch_no == 107:
-		sql("delete from `tabDocField` where fieldname = 'fiscal_year' and parent = 'Employee'")
-	elif patch_no == 108:
-		import_from_files(record_list=[['hr','search_criteria','srch_std_00013']])
-	elif patch_no == 109:
-		import_from_files(record_list=[['hr','search_criteria','srch_std_00015']])
-	elif patch_no == 110:
-		import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr', 'doctype', 'salary_slip']])
-	elif patch_no == 111:
-		sql("update tabDocType set search_fields = 'transfer_date, from_warehouse, to_warehouse, purpose, remarks' where name = 'Stock Entry'")
-	elif patch_no == 112:
-		sql("delete from tabDocField where label = 'Get Other Charges' and fieldtype = 'Button' and parent = 'Receivable Voucher'")
-	elif patch_no == 113:
-		sql("update tabDocField set reqd = 1 where parent = 'Customer' and fieldname = 'phone_1'")
-	elif patch_no == 114:
-		for d in sql("select name, master_name, credit_days, credit_limit from tabAccount where master_type = 'Customer'"):
-			if cstr(d[1]):
-				days, limit = cint(d[2]), flt(d[3])
-				cust_det = sql("select credit_days, credit_limit from tabCustomer where name = '%s'" % (cstr(d[1])))
-				if not days: days = cust_det and cint(cust_det[0][0]) or 0
-				if not limit: limit = cust_det and flt(cust_det[0][1]) or 0
-				sql("COMMIT")
-				sql("START TRANSACTION")
-				sql("update tabAccount set credit_days = '%s', credit_limit = '%s' where name = '%s'" % (days, limit, cstr(d[0])))
-				sql("COMMIT")
-
-	elif patch_no == 115:
-		# patch for timesheet cleanup
-		from webnotes.model import delete_doc
-		delete_doc('DocType', 'Timesheet Detail')
-
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list = [['Projects', 'DocType', 'Timesheet'], ['Projects', 'DocType', 'Timesheet Detail'], ['Projects', 'DocType', 'Activity Type']])
-
-	elif patch_no == 116:
-		# again!
-		from webnotes.model import delete_doc
-		delete_doc('DocType', 'Timesheet Detail')
-
-		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list = [['Projects', 'DocType', 'Timesheet Detail']])
-	elif patch_no == 117:
-		op = '\n' + 'Walk In'
-		sql("update `tabDocField` set `options` = concat(options, %s) where parent = 'Enquiry' and fieldname = 'source' and options not like '%%Walk%%'", op)
-	elif patch_no == 118:
-		from webnotes.utils import get_defaults
-		ss = sql("select name, net_pay from `tabSalary Slip`")
-		for d in ss:
-			if d[1]:
-				w = get_obj('Sales Common').get_total_in_words(get_defaults()['currency'], d[1])
-				sql("update `tabSalary Slip` set net_pay_in_words = '%s' where name = '%s'" % (w, d[0]))
-	elif patch_no == 119:
-		sql("update tabDocType set in_create = 1 where name = 'Profile'")
-	elif patch_no == 120:
-		sql("update tabDocField set permlevel = 0 where parent = 'Sales and Purchase Return Wizard' and fieldname = 'return_date'")
-	elif patch_no == 121:
-		import_from_files(record_list = [['CRM', 'DocType', 'Return Detail'], ['Material Management', 'DocType', 'Sales and Purchase Return Wizard']])
-	elif patch_no == 122:
-		sql("delete from tabDocField where (fieldname = 'serial_no' or label = 'Warrany Status') and parent = 'Sales Order'")
-	elif patch_no == 123:
-		import_from_files(record_list = [['CRM', 'Module Def', 'CRM'], ['CRM', 'Search Criteria', 'STDSRCH/00004']])
-	elif patch_no == 124:
-		import webnotes
-		webnotes.conn.set_global("system_message", """<h3>Updates(New)</h3>We have added a new report in the Selling Module.<br><br><b>Sales Personwise Transaction Summary: </b>In this report you can see sales person's contribution in a particular order, delivery or invoice. You can select voucher type in "Based On" filter.<br><br> Do send us your feedback!""")
-		webnotes.conn.set_global("system_message_id", "5")
-	elif patch_no == 125:
-		import_from_files(record_list = [['Material Management', 'DocType', 'Delivery Note']])
-	elif patch_no == 126:
-		sql("delete from tabDocField where parent = 'Delivery Note' and label in ('Make Sales Invoice', 'Make Installation Note', 'Intro Note')")
-	elif patch_no == 127:
-		sql("delete from tabDocPerm where role = 'All' and parent = 'Expense Voucher' and (permlevel = 0 or permlevel = 2)")
-		p = get_obj('Patch Util')
-		p.add_permission('Expense Voucher', 'Employee', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1, match = 'owner')
-		p.add_permission('Expense Voucher', 'HR Manager', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1)
-		p.add_permission('Expense Voucher', 'HR User', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1)
-	elif patch_no == 128:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['selling','doctype','sales_order'], ['selling','doctype','sales_order_detail'],  ['stock','doctype','delivery_note'], ['stock','doctype','delivery_note_detail']])
-	elif patch_no == 129:
-		sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail' and to_table = 'RV Detail'")
-		sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Delivery Note-Receivable Voucher' and from_table = 'Delivery Note Detail' and to_table = 'RV Detail'")
-	elif patch_no == 130:
-		# update from rv
-		from webnotes.model.code import get_obj
-		from webnotes.utils import cstr
-		for d in sql("select name, docstatus from `tabReceivable Voucher` where ifnull(docstatus,0) != 0"):
-			sql("COMMIT")
-			sql("START TRANSACTION")
-			try:
-				obj = get_obj('Receivable Voucher', cstr(d[0]), with_children = 1)
-				is_submit = 1
-				if cint(d[1]) == 2: is_submit = 0
-				get_obj('Sales Common').update_prevdoc_detail(is_submit, obj)
-			except:
-				pass
-			sql("COMMIT")
-
-		# update from dn
-		from webnotes.model.code import get_obj
-		for d in sql("select name, docstatus from `tabDelivery Note` where ifnull(docstatus,0) != 0"):
-			sql("COMMIT")
-			sql("START TRANSACTION")
-			try:
-				obj = get_obj('Delivery Note', cstr(d[0]), with_children = 1)
-				is_submit = 1
-				if cint(d[1]) == 2: is_submit = 0
-				get_obj('Sales Common').update_prevdoc_detail(is_submit, obj)
-			except:
-				pass
-			sql("COMMIT")
-	elif patch_no == 131:
-		sql("update `tabDocType` set allow_trash = 1 where name = 'Purchase Other Charges'")
-		sql("update tabDocPerm set `cancel` = 1 where parent = 'Purchase Other Charges' and permlevel = 0 and `read` = 1 and `write` = 1")
-	elif patch_no == 132:
-		sql("update tabDocField set no_copy = 0 where parent = 'Receivable Voucher' and fieldname = 'customer'")
-	elif patch_no == 133:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['accounts','doctype','receivable_voucher']])
-	elif patch_no == 134:
-		sql("update tabDocField set no_copy = 1 where parent = 'Receivable Voucher' and fieldname = 'posting_time'")
-	elif patch_no == 135:
-		sql("update tabDocField set `default` = 'Today' where parent = 'Receivable Voucher' and fieldname = 'due_date'")
-	elif patch_no == 136:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['accounts','doctype','rv_detail']])
-	elif patch_no == 137:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['setup','doctype','price_list']])
-	elif patch_no == 138:
-		sql("update `tabDocType` set allow_attach = 1 where name = 'Price List'")
-	elif patch_no == 139:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['mapper','DocType Mapper','Sales Order-Receivable Voucher'], ['mapper','DocType Mapper','Delivery Note-Receivable Voucher']])
-	elif patch_no == 140:
-		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['accounts','doctype','rv_detail']])
-	elif patch_no == 141:
-		sql("delete from tabDocField where (fieldname = 'letter_head' or label = 'Letter Head') and parent = 'Company'")
-	elif patch_no == 142:
-		# fixes to letter head and personalize
-		from webnotes.model import delete_doc
-
-		delete_doc('DocType', 'Batch Settings')
-		delete_doc('DocType', 'Batch Settings Detail')
-		delete_doc('DocType', 'Social Badge')
-		delete_doc('Page', 'Personalize Page')
-		delete_doc('DocType', 'Personalize Page Control')
-
-		import_from_files(record_list=[['core','doctype','letter_head'], ['setup','doctype','personalize']])
-	elif patch_no == 144:
-		webnotes.conn.sql("update tabDocField set fieldtype='Code' where parent='Letter Head' and fieldname='content'")
-	elif patch_no == 145:
-		sql("update `tabDocField` set permlevel=1 where fieldname = 'group_or_ledger' and parent = 'Account'")
-	elif patch_no == 146:
-		import_from_files(record_list=[['accounts','doctype','account']])
-	elif patch_no == 147:
-		import_from_files(record_list=[['mapper', 'DocType Mapper', 'Purchase Order-Payable Voucher'], ['mapper', 'DocType Mapper', 'Purchase Receipt-Payable Voucher'], ['mapper', 'DocType Mapper', 'Purchase Order-Purchase Receipt']])
-	elif patch_no == 148:
-		sql("delete from `tabDocField` where (fieldname = 'account_balances' or label = 'Balances') and parent = 'Account'")
-		sql("update tabDocType set istable = 0, section_style = 'Simple', search_fields = 'account, period, fiscal_year, balance' where name = 'Account Balance'")
-		sql("update tabDocField set permlevel = 0 where parent = 'Account Balance'")
-		p = get_obj('Patch Util')
-		p.add_permission('Account Balance', 'Accounts User', 0, read = 1)
-		p.add_permission('Account Balance', 'Accounts Manager', 0, read = 1)
-		import_from_files(record_list=[['accounts','doctype','account_balance']])
-	elif patch_no == 149:
-		sql("update `tabAccount Balance` set account = parent")
-	elif patch_no == 150:
-		sql("update tabDocField set in_filter = 1, search_index = 1 where parent = 'Account Balance' and fieldname in ('account', 'period', 'fiscal_year', 'start_date', 'end_date')")
-		ac_bal = Document("DocType", "Account Balance")
-		ac_bal.save()
-	elif patch_no == 151:
-		sql("delete from tabDocField where label = 'Add / Manage Contacts' and fieldtype = 'Button' and parent = 'Customer'")
-		sql("delete from `tabField Mapper Detail` where parent = 'Sales Order-Delivery Note' and from_field = 'note' and to_field = 'note'")
-	elif patch_no == 152:
-		import_from_files(record_list=[['selling','doctype','sales_order'], ['stock','doctype','delivery_note'], ['selling','doctype','customer'], ['selling','doctype','shipping_address'], ['mapper', 'DocType Mapper', 'Sales Order-Delivery Note']])
-	elif patch_no == 153:
-		sql("delete from `tabDocField` where fieldname = 'sales_person' and parent = 'Customer'")
-	elif patch_no == 154:
-		import_from_files(record_list=[['stock','doctype','serial_no'], ['support','doctype','customer_issue']])
-	elif patch_no == 155:
-		for d in sql("select name, item_code from `tabSerial No`"):
-			sql("COMMIT")
-			sql("START TRANSACTION")
-			sql("update `tabSerial No` set item_name = '%s' where name = '%s'" % (webnotes.conn.get_value('Item',cstr(d[1]),'item_name'), cstr(d[0])))
-			sql("COMMIT")
-	elif patch_no == 156:
-		sql("update tabDocField set fieldtype = 'Code' where fieldname = 'html' and parent = 'Print Format'")
-	elif patch_no == 157:
-		import_from_files(record_list=[['accounts', 'doctype', 'journal_voucher'], ['accounts', 'Print Format', 'Payment Receipt Voucher'], ['accounts', 'Print Format', 'Cheque Printing Format']])
-	elif patch_no == 158:
-		from webnotes.model.doc import addchild
-		sql("delete from tabDocField where parent = 'Customer Issue' and fieldname = 'customer_group'")
-	elif patch_no == 159:
-		sql("update tabAccount set account_type = 'Chargeable' where account_name in ('Advertising and Publicity', 'Freight & Forwarding Charges', 'Miscellaneous Expenses', 'Sales Promotion Expenses')")
-	elif patch_no == 160:
-		sql("update `tabDocType` set search_fields = 'posting_date, due_date, debit_to, fiscal_year, grand_total, outstanding_amount' where name = 'Receivable Voucher'")
-		sql("update `tabDocType` set search_fields = 'posting_date, credit_to, fiscal_year, bill_no, grand_total, outstanding_amount' where name = 'Payable Voucher'")
-	elif patch_no == 161:
-		sql("update tabDocType set autoname = 'field:batch_id' where name = 'Batch'")
-		sql("update tabDocField set no_copy = 1 where parent = 'Batch' and fieldname = 'batch_id'")
-	elif patch_no == 162:
-		import_from_files(record_list=[['selling', 'search_criteria', 'sales_order_pending_items1']])
-	elif patch_no == 163:
-		sql("delete from `tabModule Def Item` where display_name = 'Sales Orderwise Pending Packing Item Summary' and parent = 'CRM'")
-		import_from_files(record_list=[['selling', 'search_criteria', 'sales_orderwise_pending_qty_to_deliver'], ['selling', 'search_criteria', 'sales_orderwise_pending_amount_to_bill'], ['selling', 'search_criteria', 'delivered_items_to_be_install']])
-	elif patch_no == 164:
-		import_from_files(record_list=[['buying', 'search_criteria', 'pending_po_items_to_receive'], ['buying', 'search_criteria', 'pending_po_items_to_bill']])
-	elif patch_no == 165:
-		pass
-	elif patch_no == 166:
-		import_from_files(record_list=[['buying', 'doctype', 'purchase_order']])
-	elif patch_no == 167:
-		if webnotes.conn.get_value('Control Panel', None, 'account_id') not in ['ax0000956', 'ax0001338']:
-			sql("delete from tabDocField where parent = 'Purchase Order' and fieldname in ('test_certificate_required', 'estimated_cost', 'transport', 'vendor_reference', 'transportation_required', 'mode_of_dispatch', 'octroi')")
-	elif patch_no == 168:
-		sql("update tabDocField set fieldtype = 'Data', options = 'Suggest' where fieldname = 'bank_name' and parent = 'Employee'")
-	elif patch_no == 169:
-		import_from_files(record_list=[['accounts', 'doctype', 'pv_detail'], ['accounts', 'doctype', 'rv_detail']])
-	elif patch_no == 170:
-		import_from_files(record_list=[['mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher']])
-	elif patch_no == 171:
-		import_from_files(record_list=[['buying', 'doctype', 'supplier']])
-	elif patch_no == 172:
-		import webnotes
-		webnotes.conn.set_global("system_message", """<b>Welcome to the new financial year 2011-2012 !!! </b><br><br> So obvious question in your mind is how to start Entries in the New Fiscal Year in ERPNext? What are the changes you have to make in the system? <br>We have made some guidelines regarding the basic steps you should follow. Please click on link <a href='http://erpnext.blogspot.com/2011/03/how-to-start-entries-in-new-fiscal-year.html'>How to start Entries in the New Fiscal Year in ERPNext?</a>""")
-		webnotes.conn.set_global("system_message_id", "6")
-	elif patch_no == 173:
-		sql("delete from tabDocField where label = 'Get Other Charges' and parent = 'Delivery Note'")
-		sql("update tabDocField set reqd = 0 where fieldname = 'posting_time' and parent = 'Serial No'")
-	elif patch_no == 174:
-		c = sql("select count(name) from `tabField Mapper Detail` where parent = 'Delivery Note-Receivable Voucher' and from_field = 'description' and to_field = 'description' and match_id = 2")
-		if c and cint(c[0][0]) > 1:
-			sql("update `tabField Mapper Detail` set match_id = 1 where parent = 'Delivery Note-Receivable Voucher' and from_field = 'description' and to_field = 'description' limit 1")
-	elif patch_no == 175:
-		import webnotes
-		webnotes.conn.set_global("system_message", """If your financial year starts on 1st April then you have make some changes in the system to start entry in the new year.<br>We have made some guidelines regarding the basic steps you should follow. Please click on link <a href='http://erpnext.blogspot.com/2011/03/how-to-start-entries-in-new-fiscal-year.html'>How to start Entries in the New Fiscal Year in ERPNext?</a>""")
-		webnotes.conn.set_global("system_message_id", "6")
-	elif patch_no == 176:
-		sql("update tabDocPerm set role='Guest', `write`=0, `create`=0 where role='Administrator' and parent='Notification Control' limit 1")
-	elif patch_no == 177:
-		sql("delete from `tabDocField` where label = 'Next Steps' and parent = 'Purchase Order'")
-		sql("update tabDocField set options = 'Material Issue\nMaterial Receipt\nMaterial Transfer\nSales Return\nPurchase Return\nSubcontracting\nProduction Order' where parent = 'Stock Entry' and fieldname = 'purpose'")
-	elif patch_no == 178:
-		import_from_files(record_list = [['hr', 'doctype', 'salary_slip']])
-	elif patch_no == 179:
-		from webnotes.utils import get_defaults
-		sl = sql("select name, net_pay from `tabSalary Slip`")
-		for d in sl:
-			in_words = get_obj('Sales Common').get_total_in_words(get_defaults()['currency'], round(flt(d[1])))
-			sql("update `tabSalary Slip` set rounded_total = '%s', total_in_words = '%s' where name = '%s'" % (round(flt(d[1])), in_words, d[0]))
-	elif patch_no == 180:
-		sql("delete from tabDocField where parent = 'Salary Slip' and fieldname = 'net_pay_in_words'")
-	elif patch_no == 181:
-		import_from_files(record_list = [['accounts', 'doctype', 'journal_voucher']])
-	elif patch_no == 182:
-		sql("update tabDocField set options = CONCAT(options, '\nWrite Off Voucher') where fieldname = 'voucher_type' and parent = 'Journal Voucher'")
-	elif patch_no == 183:
-		sql("delete from tabDocField where label = 'SMS' and fieldtype = 'Section Break' and parent in  ('Enquiry', 'Lead', 'Sales Order', 'Delivery Note')")
-	elif patch_no == 184:
-		from webnotes.model import delete_doc
-		delete_doc('DocType', 'Feed')
-		delete_doc('DocType', 'Feed List')
-		delete_doc('DocType', 'Feed Control')
-
-		# add trigger
-		from webnotes.model.triggers import add_trigger
-		add_trigger('*','*','*','event_updates.update_feed')
-
-		webnotes.conn.commit()
-
-		try:
-			sql("drop table tabFeed")
-			sql("drop table `tabFeed List`")
-		except: pass
-
-		# import
-		from webnotes.modules.module_manager import reload_doc
-		reload_doc('event_updates','doctype','feed')
-	elif patch_no==185:
-		sql("delete from tabDocTrigger where method = 'webnotes.widgets.follow.on_docsave'")
-	elif patch_no==186:
-		from webnotes.modules.module_manager import reload_doc
-		reload_doc('event_updates','doctype','feed')
-	elif patch_no == 187:
-		sql("update tabDocType set autoname = '' where name = 'QA Inspection Report'")
-	elif patch_no == 188:
-		import_from_files(record_list = [['buying', 'doctype', 'qa_inspection_report']])
-	elif patch_no == 189:
-		sql("update `tabDocField` set allow_on_submit = 1 where fieldname in ('entries', 'other_charges') and parent = 'Receivable Voucher'")
-	elif patch_no == 190:
-		sql("update tabDocField set permlevel=0 where fieldname = 'fiscal_year' and parent = 'Stock Entry'")
-	elif patch_no == 191:
-		import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
-	elif patch_no == 192:
-		sql("delete from `tabModule Def Item` where parent = 'Material Management' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
-		import_from_files(record_list = [['buying', 'Module Def', 'SRM']])
-	elif patch_no == 193:
-		sql("update tabDocField set fieldtype='Button', `trigger`='Client' where parent='Letter Head' and fieldname='set_from_image'")
-	elif patch_no == 194:
-		sql("delete from `tabModule Def Item` where parent = 'SRM' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
-		import_from_files(record_list = [['stock', 'Module Def', 'Material Management']])
-	elif patch_no == 195:
-		from webnotes.modules.module_manager import reload_doc
-		reload_doc('setup','doctype','manage_account')
-	elif patch_no == 196:
-		sql("update `tabModule Def` set module_page = null where name = 'Material Management'")
-	elif patch_no == 197:
-		sql("update `tabDocField` set permlevel = 0, in_filter = 1 where fieldname = 'warranty_amc_status' and parent = 'Customer Issue'")
-		import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
-	elif patch_no == 198:
-		sql("delete from `tabDocField` where (label in ('SMS', 'Send SMS') or fieldname in ('message', 'customer_mobile_no')) and parent in ('Quoattion', 'Sales Order', 'Delivery Note', 'Receivable Voucher')")
-		sql("delete from `tabDocField` where label in ('SMS', 'Send SMS') and parent = 'Purchase Order'")
-		sql("delete from `tabDocField` where (label in ('Send SMS', 'SMS Html') or fieldname in ('sms_message', 'lead_sms_detail', 'enquiry_sms_detail')) and parent in ('Lead', 'Enquiry')")
-		from webnotes.model import delete_doc
-		delete_doc('DocType', 'Lead SMS Detail')
-		delete_doc('DocType', 'Enquiry SMS Detail')
-	elif patch_no == 199:
-		sql("update tabDocField set reqd = 0 where parent = 'Attendance' and fieldname = 'shifts'")
-	elif patch_no == 200:
-		reload_doc('event_updates','page','profile_settings')
-	elif patch_no == 201:
-		reload_doc('setup','doctype','price_list')
-	elif patch_no == 202:
-		name1 = sql("select name from tabDocField where parent='Price List' and label='Clear Prices' limit 1,1")
-		name2 = sql("select name from tabDocField where parent='Price List' and label='Update Prices' limit 1,1")
-		if name1:
-			sql("delete from tabDocField where name=%s limit 1", name1[0][0])
-		if name2:
-			sql("delete from tabDocField where name=%s limit 1", name2[0][0])
-	elif patch_no == 203:
-		sql("delete from tabDocField where parent = 'Company' and fieldname = 'default_salary_account' limit 1")
-	elif patch_no == 204:
-		sql("delete from tabDocField where parent = 'Company' and fieldname = 'default_salary_acount' limit 1")
-	elif patch_no == 205:
-		sql("update `tabDocField` set `default` = '' where fieldname = 'naming_series' and parent = 'Installation Note'")
-	elif patch_no == 206:
-		reload_doc('selling','doctype','installation_note')
-	elif patch_no == 207:
-		import_from_files(record_list = [['setup', 'doctype', 'company']])
-	elif patch_no == 208:
-		sql("delete from `tabDocField` where (label in ('SMS', 'Send SMS') or fieldname in ('message', 'customer_mobile_no')) and parent ='Quotation'")
-		default_currency = get_obj('Manage Account').doc.default_currency
-		sql("update tabCompany set default_currency = '%s'" % default_currency)
-	elif patch_no == 209:
-		import_from_files(record_list = [['setup', 'doctype', 'company']])
-	elif patch_no == 210:
-		sql("delete FROM `tabDocField` WHERE parent = 'Lead' AND label in ('CC:','Attachment Html','Create New File','Attachment')")
-	elif patch_no == 212:
-		# reload company because of disturbed UI
-		import_from_files(record_list = [['setup', 'doctype', 'company']])
-	elif patch_no == 213:
-		reload_doc('selling','doctype','lead')
-		reload_doc('setup','doctype','company')
-	elif patch_no == 214:
-		reload_doc('selling','doctype','sales_order')
-	elif patch_no == 215:
-		# patch for item and image in description
-		sql("update tabDocField set width = '300px' where fieldname='description'")
-		reload_doc('stock', 'doctype', 'item')
-		sql("delete from __DocTypeCache")
-	elif patch_no == 216:
-		import_from_files(record_list = [['stock', 'doctype', 'serial_no'], ['stock', 'doctype', 'stock_ledger_entry']])
-	elif patch_no == 217:
-		sql("update tabDocField set options = '\nIn Store\nDelivered\nNot in Use' where fieldname = 'status' and parent = 'Serial No'")
-		sql("update tabDocField set no_copy = 1 where fieldname = 'serial_no' and parent = 'Delivery Note Detail'")
-		sql("update tabDocField set no_copy = 1 where fieldname = 'serial_no' and parent = 'Stock Entry Detail'")
-	elif patch_no == 218:
-		for d in sql("select name from `tabSerial No`"):
-			sql("Commit")
-			sql("Start Transaction")
-			s = Document('Serial No', d[0])
-			if s.pr_no:
-				s.purchase_document_type = 'Purchase Receipt'
-				s.purchase_document_no = s.pr_no
-			if s.delivery_note_no:
-				s.delivery_document_type = 'Delivery Note'
-				s.delivery_document_no = s.delivery_note_no
-			if s.notes:
-				s.delivery_note_no = s.notes
-			s.company = webnotes.utils.get_defaults()['company']
-			s.fiscal_year = webnotes.utils.get_defaults()['fiscal_year']
-			s.save()
-	elif patch_no == 219:
-		sql("delete from tabDocField where fieldname in ('pr_no', 'make', 'label', 'delivery_note_no', 'notes') and parent = 'Serial No'")
-	elif patch_no == 220:
-		sql("update tabDocField set label = 'Incoming Rate' where fieldname = 'purchase_rate' and parent = 'Serial No'")
-		sql("update tabDocField set label = 'Incoming Time' where fieldname = 'purchase_time' and parent = 'Serial No'")
-	elif patch_no == 221:
-		sql("update tabDocField set reqd = 1 where fieldname in ('purchase_rate', 'warehouse') and parent = 'Serial No'")
-	elif patch_no == 222:
-		sql("update tabDocField set options = '\nDelivery Note\nReceivable Voucher\nStock Entry' where fieldname = 'delivery_document_type' and parent = 'Serial No'")
-	elif patch_no == 223:
-		sql("update tabDocField set hidden = 0 where fieldname in ('pay_to_recd_from', 'total_amount', 'total_amount_in_words') and parent = 'Journal Voucher'")
-		sql("update tabDocField set permlevel = 0 where fieldname = 'pay_to_recd_from' and parent = 'Journal Voucher'")
-	elif patch_no == 224:
-		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail'], ['accounts', 'Print Format', 'Payment Receipt Voucher']])
-	elif patch_no == 225:
-		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
-	elif patch_no == 226:
-		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
-	elif patch_no == 227:
-		reload_doc('stock', 'doctype', 'item')
-		if webnotes.conn.get_value('Control Panel', None, 'account_id') != 'axjanak2011':
-			sql("delete from tabDocField where parent = 'Item' and fieldname='alternate_description' limit 1")
-	elif patch_no == 228:
-		# knowledge base patch
-		reload_doc('knowledge_base', 'doctype', 'question')
-		reload_doc('knowledge_base', 'doctype', 'answer')
-		reload_doc('knowledge_base', 'page', 'questions')
-		reload_doc('knowledge_base', 'Module Def', 'Knowledge Base')
-		sql("update `tabModule Def` set disabled='No' where name='Knowledge Base'")
-	elif patch_no == 229:
-		reload_doc('knowledge_base', 'page', 'question_view')
-	elif patch_no == 230:
-		reload_doc('buying', 'doctype', 'indent')
-		reload_doc('buying', 'doctype', 'indent_detail')
-		reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
-	elif patch_no == 231:
-		reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
-	elif patch_no == 232:
-		sql("update `tabDocField` set options = 'Sales Order' where fieldname = 'sales_order_no' and parent = 'Indent'")
-	elif patch_no == 233:
-		reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Receivable Voucher')
-		reload_doc('Mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher')
-	elif patch_no == 234:
-		sql("update `tabTable Mapper Detail` set validation_logic = 'docstatus=1' where parent = 'Sales Order-Indent' and from_table = 'Sales Order Detail'")
-	elif patch_no == 235:
-		for sc in sql("""select name from `tabSearch Criteria` where ifnull(name,'')
-			like 'srch%' or ifnull(name,'') like '%stdsrch'"""):
-			try:
-				get_obj('Search Criteria', sc[0]).rename()
-			except AttributeError, e:
-				pass
-		reload_doc('core', 'doctype', 'system_console')
-	elif patch_no == 236:
-		# warehouse not mandatory for delivered serial nos
-		sql("update tabDocField set reqd=0 where parent='Serial No' and fieldname='warehouse'")
-	elif patch_no == 237:
-		sql("update tabDocField set depends_on = 'eval:doc.is_pos==1' where fieldname = 'cash_bank_account' and parent = 'Receivable Voucher'")
-	elif patch_no == 238:
-		reload_doc('accounts', 'doctype', 'receivable_voucher')
-		reload_doc('accounts', 'GL Mapper', 'POS with write off')
-	elif patch_no == 239:
-		reload_doc('core', 'doctype', 'docfield')
-		reload_doc('core', 'doctype', 'doctype')
-		from patches.old_patches.feed_patch import set_subjects_and_tagfields
-
-		set_subjects_and_tagfields()
-	elif patch_no == 240:
-		# again for sales order (status)
-		from patches.old_patches.feed_patch import set_subjects_and_tagfields
-		set_subjects_and_tagfields()
-	elif patch_no == 241:
-		sql("update `tabDocField` set fieldtype = 'Text', options = '', in_filter = '' where fieldname = 'serial_no' and parent = 'Stock Ledger Entry'")
-	elif patch_no == 242:
-		if webnotes.conn.get_value('Control Panel', None, 'account_id') not in ['axjanak2011']:
-			sql("commit")
-			try:
-				sql("alter table `tabStock Ledger Entry` drop index serial_no")
-			except:
-				pass
-
-			sql("alter table `tabStock Ledger Entry` change serial_no serial_no text")
-	elif patch_no == 243:
-		# moving custom script and custom fields to framework
-		webnotes.conn.set_value('DocType', 'Custom Script', 'module', 'Core')
-		webnotes.conn.set_value('DocType', 'Custom Field', 'module', 'Core')
-		reload_doc('setup', 'doctype', 'company')
-	elif patch_no == 244:
-		reload_doc('stock', 'search_criteria', 'shortage_to_indent')
-	elif patch_no == 245:
-		from patches.old_patches.doctype_permission_patch import set_doctype_permissions
-		set_doctype_permissions()
-
-		from patches.old_patches.feed_patch import set_subjects_and_tagfields
-		set_subjects_and_tagfields()
-	elif patch_no == 246:
-		webnotes.conn.set_value('DocType','Stock Entry','tag_fields','purpose')
-		webnotes.conn.set_value('DocType','Stock Entry','subject','%(remarks)s')
-	elif patch_no == 247:
-		webnotes.conn.set_value('DocType','Stock Entry','subject','%(remarks)s')
-	elif patch_no == 248:
-		reload_doc('setup', 'doctype', 'manage_account')
-	elif patch_no == 249:
-		sql("update `tabDocPerm` t1, `tabDocType` t2 set t1.role = 'System Manager' where t1.role = 'Administrator' and t1.parent = t2.name and t2.module != 'Core'")
-	elif patch_no == 250:
-		from patches.old_patches.feed_patch  import support_patch
-		support_patch()
-	elif patch_no == 251:
-		from webnotes.model import db_schema
-		db_schema.remove_all_foreign_keys()
-		from patches.old_patches.customer_address import run_patch
-		run_patch()
-	elif patch_no == 252:
-		reload_doc('support','doctype','support_ticket')
-		reload_doc('support','doctype','support_ticket_response')
-	elif patch_no == 253:
-		reload_doc('accounts','doctype','ledger_balance_export')
-		reload_doc('accounts','doctype','ledger_detail')
-		reload_doc('accounts', 'Module Def', 'Accounts')
-
-		from webnotes.model.db_schema import updatedb
-		updatedb('Ledger Balance Export')
-		updatedb('Ledger Detail')
-	elif patch_no == 254:
-		reload_doc('setup', 'doctype', 'sms_settings')
-		reload_doc('setup', 'doctype', 'static_parameter_detail')
-
-		from webnotes.model.db_schema import updatedb
-		updatedb('SMS Settings')
-		updatedb('Static Parameter Detail')
-	elif patch_no == 255:
-		from patches.old_patches.customer_address import run_old_data_sync_patch
-		run_old_data_sync_patch()
-	elif patch_no == 256:
-		sql("update `tabLetter Head` set content = replace(content, 'http://46.4.50.84/v170-test/', '')")
-		sql("update `tabSingles` set value = replace(value, 'http://46.4.50.84/v170-test/', '') where field in ('letter_head', 'client_name') and doctype = 'Control Panel'")
-		sql("update `tabItem` set description_html = replace(description_html, 'http://46.4.50.84/v170-test/', '')")
-	elif patch_no == 257:
-		from patches.old_patches.customer_address import run_old_data_sync_patch
-		run_old_data_sync_patch()
-	elif patch_no == 258:
-		sql("update tabDocField set `default`=NULL where fieldname = 'naming_series'")
-	elif patch_no == 259:
-		sql("update `tabQuotation Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
-		sql("update `tabSales Order Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
-		sql("update `tabRV Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
-		sql("update `tabDelivery Note Detail` set description = replace(description, 'http://46.4.50.84/v170-test/', '')")
-	elif patch_no == 260:
-		sql("update `tabLetter Head` set content = replace(content, 'http://46.4.50.84/v170/', '')")
-		sql("update `tabSingles` set value = replace(value, 'http://46.4.50.84/v170/', '') where field in ('letter_head', 'client_name') and doctype = 'Control Panel'")
-		sql("update `tabItem` set description_html = replace(description_html, 'http://46.4.50.84/v170/', '')")
-		sql("update `tabQuotation Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
-		sql("update `tabSales Order Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
-		sql("update `tabRV Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
-		sql("update `tabDelivery Note Detail` set description = replace(description, 'http://46.4.50.84/v170/', '')")
-	elif patch_no == 261:
-		sql("update `tabPrint Format` set html = replace(html, 'customer_address', 'address_display')")
-	elif patch_no == 262:
-		from patches.old_patches.customer_address import sync_lead_phone
-		sync_lead_phone()
-	elif patch_no == 263:
-		ol = ['','Open','To Reply','Waiting for Customer','Hold','Closed']
-		sql("update tabDocField set options=%s where parent=%s and fieldname=%s", ('\n'.join(ol), 'Support Ticket', 'status'))
-	elif patch_no == 264:
-		sql("delete from tabDocField where parent = 'Customer Issue' and (fieldname = 'issue_in' or fieldname = 'issue_category')")
-		sql("update tabDocField set options=NULL where parent='Support Ticket' and label = 'Send'")
-	elif patch_no == 266:
-		reload_doc('setup','doctype','support_email_settings')
-	elif patch_no == 267:
-		sql("update `tabPrint Format` set html = replace(html, 'supplier_address', 'address_display')")
-	elif patch_no == 268:
-		sql("update `tabDocPerm` set permlevel = 0 where permlevel is null")
-	elif patch_no == 269:
-		p = get_obj('Patch Util')
-		p.add_permission('GL Entry', 'Accounts User', 0, read = 1)
-	elif patch_no == 270:
-		pages = ['Accounts Setup', 'Accounts', 'Accounting Reports','GeneralLedger','How do I - Accounts','Making Opening Entries',\
-		'Analysis','How do I - CRM','How do I - Inventory','Inventory Setup', 'Stock','HR','HR & Payroll Setup',\
-		'Payroll Setup','Production Setup','Production','Buying','SRM Setup','Contact Page','Forum','Messages','Test Toolbar',\
-		'Trend Analyzer']
-		from webnotes.model import delete_doc
-		sql("delete from `tabPage Visit`")
-		for p in pages:
-			try: delete_doc('Page', p)
-			except: pass
-	elif patch_no == 271:
-		# tags patch
-		reload_doc('selling','doctype','sales_order')
-		reload_doc('stock','doctype','delivery_note')
-		sql("delete from tabDocField where fieldname='per_amt_billed' and parent in ('Sales Order', 'Delivery Note')")
-
-		sql("""update `tabSales Order` set delivery_status = if(ifnull(per_delivered,0) < 0.001, 'Not Delivered',
-				if(per_delivered >= 99.99, 'Fully Delivered', 'Partly Delivered'))""")
-		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'))""")
-	elif patch_no == 272:
-		from webnotes.model import delete_doc
-		try:
-			delete_doc('Search Criteria', '_SRCH00003')
-		except:
-			pass
-		reload_doc('accounts', 'search_criteria', 'purchase_register')
-	elif patch_no == 276:
-		from webnotes.model import delete_doc
-		sn = sql("select name from `tabSearch Criteria` where criteria_name = 'Sales Personwise Transaction Summary'")
-		for d in sn:
-			delete_doc('Search Criteria', d[0])
-		reload_doc('selling', 'search_criteria', 'sales_personwise_transaction_summary')
-	elif patch_no == 277:
-		webnotes.model.delete_doc('DocType','HomePage Settings')
-		webnotes.model.delete_doc('DocType','Badge Settings')
-		sql("update tabDocType set module='Home' where module in ('Event Updates', 'My Company')")
-		sql("update tabPage set module='Home' where module in ('Event Updates', 'My Company')")
-		sql("update `tabSearch Criteria` set module='Home' where module in ('Event Updates', 'My Company')")
-
-
-		delete_pages = ('Chat User Gallery', 'Badge Info', 'Home', 'Website Setup', 'Test Page', 'Setup Masters', 'Service', 'Selling', 'Sales Reports', 'Organize','My Cart', 'My Activity', 'Manage Users', 'Maintenance', 'Getting Started', 'Gantt Test', 'Custom Reports - Stock', 'Custom Reports - Selling', 'Custom Reports - Production', 'Custom Reports - Payroll', 'Custom Reports - Maintenance', 'Custom Reports - Buying', 'Custom Reports - Accounts', 'CRM Setup', 'CRM Reports')
-		for p in delete_pages:
-		  webnotes.model.delete_doc('Page',p)
-	elif patch_no == 278:
-		sql("update tabDocTrigger set method = 'home.update_feed' where method = 'event_updates.update_feed'")
-	elif patch_no == 279:
-		dt = ['GL Entry', 'Stock Ledger Entry']
-		for t in dt:
-			rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tab%s` where modified >= '2011-06-15 01:00:00' group by voucher_no" % t)
-			for d in rec:
-				sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
+	from webnotes.model import delete_doc
 
-		other_dt = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note']
-		for dt in other_dt:
-			rec = sql("select name, status from `tab%s` where modified >= '2011-06-15 01:00:00'" % dt)
-			for r in rec:
-				sql("update `tab%s` set docstatus = %s where name = '%s'" % (dt, (r[1] in ['Submitted', 'Closed'] and 1 or r[1]=='Cancelled' and 2 or 0), r[0]))
-	elif patch_no == 280:
-		reload_doc('accounts', 'doctype', 'form_16a')
-	elif patch_no == 281:
-		dt_list = ['Delivery Note', 'Purchase Receipt']
-		for dt in dt_list:
-			sql("update `tab%s` set status = 'Submitted' where docstatus = 1 and modified >='2011-06-15 01:00:00'" % dt)
-			sql("update `tab%s` set status = 'Cancelled' where docstatus = 2 and modified >='2011-06-15 01:00:00'" % dt)
-	elif patch_no == 282:
-		dt_list = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note', 'Receivable Voucher', 'Payable Voucher', 'Delivery Note', 'Purchase Receipt', 'Journal Voucher', 'Stock Entry']
-		for d in dt_list:
-			tbl = sql("select options from `tabDocField` where fieldtype = 'Table' and parent = '%s'" % d)
-			for t in tbl:
-				sql("update `tab%s` t1, `tab%s` t2 set t1.docstatus = t2.docstatus where t1.parent = t2.name" % (t[0], d))
-	elif patch_no == 283:
-		rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tabGL Entry` where modified >= '2011-06-15 01:00:00' order by name ASC")
-		for d in rec:
-			sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
-	elif patch_no == 284:
-		reload_doc('support', 'doctype', 'support_ticket')
-		sql("update `tabDocField` set in_filter = 1 where fieldname in ('raised_by', 'subject') and parent = 'Support Ticket'")
-	elif patch_no == 286:
-		reload_doc('accounts', 'search_criteria', 'itemwise_sales_register')
-		reload_doc('accounts', 'search_criteria', 'itemwise_purchase_register')
-	elif patch_no == 287:
-		sql("update `tabDocField` set no_copy = 1 where fieldname in ('per_received', 'per_billed', 'per_delivered') and parent in ('Purchase Order', 'Purchase Receipt', 'Sales Order', 'Delivery Note')")
-	elif patch_no == 288:
-		reload_doc('accounts', 'doctype', 'payable_voucher')
-	elif patch_no == 289:
-		sql("update `tabDocType` set subject = 'From %(supplier_name)s worth %(grand_total)s due on %(due_date)s | %(outstanding_amount)s outstanding' where name = 'Payable Voucher'")
-		sql("update `tabDocType` set search_fields = 'status,transaction_date,customer,lead,order_type' where name = 'Quotation'")
-	elif patch_no == 290:
-		count = sql("""SELECT * FROM  `tabModule Def`
-			   WHERE `module_name` LIKE 'Home'""")
-		if not count:
-			md = Document('Module Def')
-			md.module_name = 'Home'
-			md.module_label = 'Home'
-			md.save(1)
-	elif patch_no == 291:
-		reload_doc('utilities','doctype','rename_tool')
-	elif patch_no == 292:
-		reload_doc('accounts', 'search_criteria', 'trial_balance')
-	elif patch_no == 293:
-		sql("delete from tabDocField where parent='Account' and fieldname='address'")
-		reload_doc('accounts', 'doctype', 'account')
-	elif patch_no == 294:
-		# new account profile fix
-		ul = sql("select name from tabProfile where ifnull(name,'') not in ('Administrator', 'Guest', '')")
-		# if one user and one user has no roles
-		if len(ul)==1 and not sql("select parent from tabUserRole where role='System Manager' and parent=%s", ul[0][0]):
-			get_obj('Setup Control').add_roles(Document('Profile', ul[0][0]))
-	elif patch_no == 295:
-		sql("update `tabDocField` set options = 'Delivered\nNot Delivered\nPartly Delivered\nClosed\nNot Applicable' where parent = 'Sales Order' and fieldname = 'delivery_status'")
-		sql("update `tabDocField` set options = 'Billed\nNot Billed\nPartly Billed\nClosed' where parent = 'Sales Order' and fieldname = 'billing_status'")
-	elif patch_no == 296:
-		sql("delete from tabDocField where parent='Support Ticket' and fieldname='contact_no'")
-		reload_doc('support', 'doctype', 'support_ticket')
-	elif patch_no == 297:
-		reload_doc('hr', 'doctype', 'employee')
-		reload_doc('hr', 'doctype', 'attendance')
-		reload_doc('hr', 'doctype', 'expense_voucher')
-		reload_doc('hr', 'doctype', 'appraisal')
-		reload_doc('hr', 'doctype', 'salary_structure')
-		reload_doc('hr', 'doctype', 'salary_slip')
-	elif patch_no == 298:
-		sql("update `tabDocField` set options = 'link:Company' where parent = 'Attendance' and fieldname = 'company'")
-		sql("update `tabDocField` set options = 'link:Company' where parent = 'Expense Voucher' and fieldname = 'company'")
-		sql("update `tabDocField` set options = 'link:Company' where parent = 'Appraisal' and fieldname = 'company'")
-	elif patch_no == 299:
-		sql("update `tabDocPerm` set `match` = NULL where parent = 'Employee' and role = 'Employee'")
-	elif patch_no == 300:
-		sql("""DELETE FROM `tabSearch Criteria` WHERE name IN
-			   ('sales_register1', 'sales_register2', 'purchase_register1')""")
 	elif patch_no == 301:
 		from patches.delivery_billing_status_patch import run_patch
 		run_patch()
@@ -1312,7 +136,6 @@
 				webnotes.conn.get_value('Support Email Settings',None,field_map[key]))
 
 		# delete support email settings
-		from webnotes.model import delete_doc
 		delete_doc('DocType', 'Support Email Settings')
 
 		reload_doc('support','doctype','support_ticket')
@@ -1424,4 +247,14 @@
 	elif patch_no == 342:
 		sql("update `tabDocField` set permlevel = 0 where parent = 'Stock Entry Detail' and fieldname in ('s_warehouse', 't_warehouse', 'fg_item')")
 	elif patch_no == 343:
+		reload_doc('stock','doctype','item_customer_detail')
+	elif patch_no == 344:
 		sql("delete from `tabDocFormat` where ifnull(format, '') = '' and parent = 'Delivery Note'")
+	elif patch_no == 345:
+		sql("delete from `tabModule Def Item` where display_name = 'Salary Slip Control Panel' and parent = 'HR'")
+		reload_doc('hr','Module Def','HR')
+	elif patch_no == 346:
+		delete_doc('DocType', 'Profile')
+		reload_doc('core', 'doctype', 'profile')
+		
+		
\ No newline at end of file
diff --git a/selling/doctype/quotation/quotation.js b/selling/doctype/quotation/quotation.js
index f21df25..b3dcde6 100644
--- a/selling/doctype/quotation/quotation.js
+++ b/selling/doctype/quotation/quotation.js
@@ -11,7 +11,7 @@
 
 // ONLOAD
 // ===================================================================================
-cur_frm.cscript.onload = function(doc, cdt, cdn) {  
+cur_frm.cscript.onload = function(doc, cdt, cdn) {
   if(!doc.quotation_to) hide_field(['customer','customer_address','contact_person','customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
   if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
   if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
@@ -21,7 +21,7 @@
   //if(!doc.price_list_name && sys_defaults.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
   if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
   if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
-  
+
   if(doc.quotation_to) {
     if(doc.quotation_to == 'Customer') {
       hide_field(['lead', 'lead_name']);
@@ -34,7 +34,7 @@
 
 cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
   // load default charges
-  if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length) 
+  if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
     cur_frm.cscript.load_taxes(doc, cdt, cdn);
 }
 
@@ -46,9 +46,9 @@
     hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
     doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
   }
-  else if(doc.quotation_to == 'Customer'){    
+  else if(doc.quotation_to == 'Customer'){
     unhide_field(['customer']);
-    hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);    
+    hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);
     doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
   }
   //refresh_many(['lead','customer']);
@@ -56,7 +56,7 @@
 
 
 
-//================ hide - unhide fields on basis of quotation to either lead or customer =============================== 
+//================ hide - unhide fields on basis of quotation to either lead or customer ===============================
 cur_frm.cscript.quotation_to = function(doc,cdt,cdn){
   cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
   //doc.customer_address = doc.territory = doc.contact_no = doc.email_id = "";
@@ -77,7 +77,7 @@
     cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
     cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
   }
-  
+
   if (!doc.docstatus) hide_field(['Update Follow up']);
   else unhide_field(['Update Follow up']);
   //cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
@@ -111,7 +111,7 @@
   var callback = function(r,rt) {
       var doc = locals[cur_frm.doctype][cur_frm.docname];
       cur_frm.refresh();
-  }   
+  }
 
   if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
   if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
@@ -123,12 +123,12 @@
 
 cur_frm.fields_dict.customer_address.on_new = function(dn) {
   locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;  
+  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
   locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;  
+  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
@@ -146,7 +146,7 @@
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
   if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
-  if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);  
+  if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);
 }
 
 
@@ -166,7 +166,7 @@
 cur_frm.cscript['Make Sales Order'] = function() {
   var doc = cur_frm.doc;
 
-  if (doc.docstatus == 1) { 
+  if (doc.docstatus == 1) {
     var n = createLocal("Sales Order");
     $c('dt_map', args={
       'docs':compress_doclist([locals["Sales Order"][n]]),
@@ -186,17 +186,17 @@
   var callback = function(r,rt){
     if(r.message){
       doc.quotation_to = r.message;
-      
+
 		  if(doc.quotation_to == 'Lead') {
-  			  unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']);			  
+  			  unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']);
 		  }
 		  else if(doc.quotation_to == 'Customer') {
 			  unhide_field(['customer','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
 		  }
 		  refresh_many(['quotation_details','quotation_to','customer','customer_address','contact_person','lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','order_type']);
     }
-  }   
-  
+  }
+
   $c_obj(make_doclist(doc.doctype, doc.name),'pull_enq_details','',callback);
 
 }
@@ -217,7 +217,7 @@
 //-------------------------
 cur_frm.cscript['Declare Order Lost'] = function(){
   var qtn_lost_dialog;
-  
+
   set_qtn_lost_dialog = function(doc,cdt,cdn){
     qtn_lost_dialog = new Dialog(400,400,'Add Quotation Lost Reason');
     qtn_lost_dialog.make_body([
@@ -226,26 +226,26 @@
       ['HTML', 'Response', '<div class = "comment" id="update_quotation_dialog_response"></div>'],
       ['HTML', 'Add Reason', '<div></div>']
     ]);
-    
+
     var add_reason_btn1 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
     add_reason_btn1.innerHTML = 'Add';
     add_reason_btn1.onclick = function(){ qtn_lost_dialog.add(); }
-    
+
     var add_reason_btn2 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
     add_reason_btn2.innerHTML = 'Cancel';
     $y(add_reason_btn2,{marginLeft:'4px'});
     add_reason_btn2.onclick = function(){ qtn_lost_dialog.hide();}
-    
+
     qtn_lost_dialog.onshow = function() {
       qtn_lost_dialog.widgets['Quotation Lost Reason'].value = '';
       $i('update_quotation_dialog_response').innerHTML = '';
     }
-    
+
     qtn_lost_dialog.add = function() {
       // sending...
       $i('update_quotation_dialog_response').innerHTML = 'Processing...';
       var arg =  strip(qtn_lost_dialog.widgets['Quotation Lost Reason'].value);
-      var call_back = function(r,rt) { 
+      var call_back = function(r,rt) {
         if(r.message == 'true'){
           $i('update_quotation_dialog_response').innerHTML = 'Done';
           qtn_lost_dialog.hide();
@@ -254,11 +254,11 @@
       if(arg) $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_order_lost',arg,call_back);
       else msgprint("Please add Quotation lost reason");
     }
-  }  
-  
+  }
+
   if(!qtn_lost_dialog){
     set_qtn_lost_dialog(doc,cdt,cdn);
-  }  
+  }
   qtn_lost_dialog.show();
 }
 
@@ -284,23 +284,23 @@
 
 //===================== Quotation to validation - either customer or lead mandatory ====================
 cur_frm.cscript.quot_to_validate = function(doc,cdt,cdn){
-  
+
   if(doc.quotation_to == 'Lead'){
-  
+
     if(!doc.lead){
-      alert("Lead is mandatory.");  
-      validated = false; 
+      alert("Lead is mandatory.");
+      validated = false;
     }
   }
   else if(doc.quotation_to == 'Customer'){
-   
+
     if(!doc.customer){
       alert("Customer is mandatory.");
       validated = false;
     }
-    
+
   }
- 
+
 }
 
 //===================validation function =================================
@@ -308,3 +308,35 @@
 cur_frm.cscript.validate = function(doc,cdt,cdn){
   cur_frm.cscript.quot_to_validate(doc,cdt,cdn);
 }
+
+//================ Last Quoted Price and Last Sold Price suggestion ======================
+cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query= function(doc, cdt, cdn) {
+  var d = locals[cdt][cdn];
+  if(doc.customer)
+    return repl("SELECT i.name,i.item_code,concat('Last quoted at - ',cast(quote_rate as char)) as quote_rate,concat('Last sold at - ',cast(sales_rate as char)) as sales_rate FROM\
+		(\
+			select item_code,name from tabItem where tabItem.%(key)s like '%s'\
+		)i\
+		left join\
+		(\
+			select q.item_code,q.quote_rate from\
+			(\
+				select q.transaction_date,qd.item_code,basic_rate as quote_rate from `tabQuotation Detail` qd, `tabQuotation` q where q.name=qd.parent and q.docstatus=1 and customer='%(cust)s'\
+			)q,\
+			(\
+				select qd.item_code,max(transaction_date) as transaction_date from `tabQuotation Detail` qd, `tabQuotation` q where q.name=qd.parent and q.docstatus=1 and customer='%(cust)s' group by qd.item_code\
+			)m where q.item_code=m.item_code and q.transaction_date=m.transaction_date\
+		)q on i.item_code=q.item_code\
+		left join\
+		(\
+			select r.item_code,r.sales_rate from\
+			(\
+				select r.voucher_date,rd.item_code,basic_rate as sales_rate from `tabRV Detail` rd, `tabReceivable Voucher` r where r.name=rd.parent and r.docstatus=1 and customer='%(cust)s'\
+			)r,\
+			(\
+				select rd.item_code,max(voucher_date) as voucher_date from `tabRV Detail` rd, `tabReceivable Voucher` r where r.name=rd.parent and r.docstatus=1 and customer='%(cust)s' group by rd.item_code\
+			)m where r.item_code=m.item_code and r.voucher_date=m.voucher_date\
+		)s on i.item_code=s.item_code ORDER BY item_code LIMIT 50",{cust:doc.customer});
+  else
+    return "SELECT name, item_code FROM tabItem WHERE `tabItem`.%(key)s LIKE '%s' ORDER BY tabItem.item_code DESC LIMIT 50";
+}
\ No newline at end of file
diff --git a/startup/startup.js b/startup/startup.js
index 1280e0f..4e2bc1d 100644
--- a/startup/startup.js
+++ b/startup/startup.js
@@ -48,10 +48,9 @@
 		if(r.message){
 			login_file = 'http://' + r.message;
 		}
-		else {
-			
+		else if(pscript.is_erpnext_saas) {
 			login_file = 'http://www.erpnext.com';
-			}
+		}
 		// setup toolbar
 		pscript.startup_setup_toolbar();
 	}
diff --git a/stock/Print Format/Delivery Note Packing List Wise/Delivery Note Packing List Wise.txt b/stock/Print Format/Delivery Note Packing List Wise/Delivery Note Packing List Wise.txt
new file mode 100644
index 0000000..97f57a9
--- /dev/null
+++ b/stock/Print Format/Delivery Note Packing List Wise/Delivery Note Packing List Wise.txt
@@ -0,0 +1,27 @@
+# Print Format, Delivery Note Packing List Wise
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-08-18 16:29:14',
+		'docstatus': 0,
+		'modified': '2011-08-23 13:24:12',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Print Format
+	{
+		'doctype': 'Print Format',
+		'html': "<html>\n<head>\n\n<script>\nfunction replaceAll(s,s1,s2){ return s.split(s1).join(s2);}\n\nfunction get_letter_head(){\n  var cp = locals['Control Panel']['Control Panel'];\n    if(cp.letter_head != 'None') {return cp.letter_head; }\n      else{ return ''};\n  }\n</script>\n<style>\n.cust_tbl { border-collapse:collapse; }\n.cust_tbl td { border:1px solid #848484; }\n</style>\n</head>\n\n<body>\n<script>\nreplaceAll(doc.print_packing_slip,'[HEADER GOES HERE]',get_letter_head());\n</script>\n</body>\n</html>",
+		'module': 'Stock',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Print Format, Delivery Note Packing List Wise
+	{
+		'doctype': 'Print Format',
+		'name': 'Delivery Note Packing List Wise'
+	}
+]
\ No newline at end of file
diff --git a/stock/doctype/bin/bin.py b/stock/doctype/bin/bin.py
index 1a1eb70..fc51d76 100644
--- a/stock/doctype/bin/bin.py
+++ b/stock/doctype/bin/bin.py
@@ -37,9 +37,13 @@
 		self.doc.projected_qty = flt(self.doc.actual_qty) + flt(self.doc.ordered_qty) + flt(self.doc.indented_qty) + flt(self.doc.planned_qty) - flt(self.doc.reserved_qty)
 
 		self.doc.save()
-
+			
+		
 		# update valuation for post dated entry
 		if actual_qty:
+			# check actual qty with total number of serial no
+			self.check_qty_with_serial_no()
+			
 			prev_sle = self.get_prev_sle(dt, posting_time, sle_id)
 			cqty = flt(prev_sle.get('bin_aqat', 0))
 			# Block if actual qty becomes negative
@@ -48,6 +52,18 @@
 
 			self.update_item_valuation(sle_id, dt, posting_time, serial_no, prev_sle)
 
+	def check_qty_with_serial_no(self):
+		"""
+			check actual qty with total number of serial no in store
+			Temporary validation added on: 18-07-2011
+		"""
+		if sql("select name from `tabItem` where ifnull(has_serial_no, 'No') = 'Yes' and name = '%s'" % self.doc.item_code):
+			sr_count = sql("select count(name) from `tabSerial No` where item_code = '%s' and warehouse = '%s' and status  ='In Store' and docstatus != 2" % (self.doc.item_code, self.doc.warehouse))[0][0]
+			if sr_count != self.doc.actual_qty:
+				msg = "Actual Qty(%s) in Bin is mismatched with total number(%s) of serial no in store for item: '%s' and warehouse: '%s'" % (self.doc.actual_qty, sr_count, self.doc.item_code, self.doc.warehouse)
+				msgprint(msg, raise_exception=1)
+				sendmail(['developer@iwebnotes.com'], sender='automail@webnotestech.com', subject='Serial No Count vs Bin Actual Qty', parts=[['text/plain', msg]])			
+
 	# --------------------------------
 	# get first stock ledger entry
 	# --------------------------------
diff --git a/stock/doctype/delivery_note/delivery_note.py b/stock/doctype/delivery_note/delivery_note.py
index 3534dad..e5acd16 100644
--- a/stock/doctype/delivery_note/delivery_note.py
+++ b/stock/doctype/delivery_note/delivery_note.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
@@ -24,7 +24,7 @@
     self.doclist = doclist
     self.tname = 'Delivery Note Detail'
     self.fname = 'delivery_note_details'
-    
+
     # Notification objects
     self.notify_obj = get_obj('Notification Control')
 
@@ -33,7 +33,7 @@
   def autoname(self):
     self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
-    
+
 # DOCTYPE TRIGGERS FUNCTIONS
 # ==============================================================================
 #************Fiscal Year Validation*****************************
@@ -48,21 +48,21 @@
   # *********** Get Commission rate of Sales Partner ****************
   def get_comm_rate(self, sales_partner):
     return get_obj('Sales Common').get_comm_rate(sales_partner, self)
-  
+
   # *************** Pull Sales Order Details ************************
   def pull_sales_order_details(self):
     self.validate_prev_docname()
     self.doc.clear_table(self.doclist,'other_charges')
-        
-    if self.doc.sales_order_no:        
+
+    if self.doc.sales_order_no:
       get_obj('DocType Mapper', 'Sales Order-Delivery Note').dt_map('Sales Order', 'Delivery Note', self.doc.sales_order_no, self.doc, self.doclist, "[['Sales Order', 'Delivery Note'],['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]")
     else:
-      msgprint("Please select Sales Order No. whose details need to be pulled")    
+      msgprint("Please select Sales Order No. whose details need to be pulled")
 
     return cstr(self.doc.sales_order_no)
 
-    
-  
+
+
   #-------------------set item details -uom and item group----------------
   def set_item_details(self):
     for d in getlist(self.doclist,'delivery_note_details'):
@@ -70,14 +70,14 @@
       if not d.stock_uom:    d.stock_uom = res and cstr(res[0][0]) or ''
       if not d.item_group:   d.item_group = res and cstr(res[0][1]) or ''
       d.save()
-      
+
   # ::::: Validates that Sales Order is not pulled twice :::::::
   def validate_prev_docname(self):
-    for d in getlist(self.doclist, 'delivery_note_details'): 
+    for d in getlist(self.doclist, 'delivery_note_details'):
       if self.doc.sales_order_no == d.prevdoc_docname:
         msgprint(cstr(self.doc.sales_order_no) + " sales order details have already been pulled. ")
         raise Exception, "Validation Error. "
-  
+
   #Set Actual Qty based on item code and warehouse
   #------------------------------------------------------
   def set_actual_qty(self):
@@ -91,14 +91,14 @@
   # -------------------------------------
   def get_tc_details(self):
     return get_obj('Sales Common').get_tc_details(self)
-  
+
   #pull project customer
   #-------------------------
   def pull_project_customer(self):
     res = sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name)
     if res:
       get_obj('DocType Mapper', 'Project-Delivery Note').dt_map('Project', 'Delivery Note', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Delivery Note']]")
-        
+
 # DELIVERY NOTE DETAILS TRIGGER FUNCTIONS
 # ================================================================================
 
@@ -119,10 +119,10 @@
     }
     return ret
 
-    
+
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
-  
+
   # *********** Get Tax rate if account type is TAX ********************
   def get_rate(self,arg):
     return get_obj('Sales Common').get_rate(arg)
@@ -137,7 +137,7 @@
   def get_other_charges(self):
     return get_obj('Sales Common').get_other_charges(self)
 
-    
+
   #check in manage account if sales order required or not.
   # ====================================================================================
   def so_required(self):
@@ -147,9 +147,9 @@
          if not d.prevdoc_docname:
            msgprint("Sales Order No. required against item %s"%d.item_code)
            raise Exception
-       
 
-    
+
+
 # VALIDATE
 # ====================================================================================
   def validate(self):
@@ -167,13 +167,16 @@
     sales_com_obj.make_packing_list(self,'delivery_note_details')
     get_obj('Stock Ledger').validate_serial_no(self, 'packing_details')
     sales_com_obj.validate_max_discount(self, 'delivery_note_details')             #verify whether rate is not greater than max discount
-    sales_com_obj.get_allocated_sum(self)  # this is to verify that the allocated % of sales persons is 100%    
+    sales_com_obj.get_allocated_sum(self)  # this is to verify that the allocated % of sales persons is 100%
     sales_com_obj.check_conversion_rate(self)
     # ::::::: Get total in Words ::::::::
     dcc = TransactionBase().get_company_currency(self.doc.company)
     self.doc.in_words = sales_com_obj.get_total_in_words(dcc, self.doc.rounded_total)
     self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export)
-    
+
+    # ::::::: Set Net Weight of each Packing
+    self.update_pack_nett_weight()
+    self.print_packing_slip()
     # ::::::: Set actual qty for each item in selected warehouse :::::::
     self.update_current_stock()
     # :::::: set DN status :::::::
@@ -181,8 +184,7 @@
     self.doc.status = 'Draft'
     if not self.doc.billing_status: self.doc.billing_status = 'Not Billed'
     if not self.doc.installation_status: self.doc.installation_status = 'Not Installed'
-    
- 
+
   # ************** Validate Mandatory *************************
   def validate_mandatory(self):
     # :::::::::: Amendment Date ::::::::::::::
@@ -198,20 +200,20 @@
       if not res:
         msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in project - %s."%(self.doc.customer,self.doc.project_name,self.doc.project_name))
         raise Exception
-            
+
   # Validate values with reference document
   #----------------------------------------
   def validate_reference_value(self):
     get_obj('DocType Mapper', 'Sales Order-Delivery Note', with_children = 1).validate_reference_value(self, self.doc.name)
-  
-	  
+
+
   # ******* Validate Previous Document Details ************
   def validate_prevdoc_details(self):
     for d in getlist(self.doclist,'delivery_note_details'):
-           
+
       prevdoc = d.prevdoc_doctype
       prevdoc_docname = d.prevdoc_docname
-      
+
       if prevdoc_docname and prevdoc:
         # ::::::::::: Validates Transaction Date of DN and previous doc (i.e. SO , PO, PR) *********
         trans_date = sql("select transaction_date from `tab%s` where name = '%s'" %(prevdoc,prevdoc_docname))[0][0]
@@ -259,7 +261,7 @@
       ch = sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
       if d.prevdoc_doctype and d.prevdoc_detail_docname and ch and ch[0][0]=='Yes':
         self.validate_items_with_prevdoc(d)
-      
+
       # validates whether item is not entered twice
       e = [d.item_code, d.description, d.warehouse, d.prevdoc_docname or '', d.batch_no or '']
       f = [d.item_code, d.description, d.prevdoc_docname or '']
@@ -297,8 +299,8 @@
     for d in getlist(self.doclist, 'packing_details'):
       bin = sql("select actual_qty, projected_qty from `tabBin` where item_code =  %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
       d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
-      d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0  
-      
+      d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
+
 
 # ON SUBMIT
 # =================================================================================================
@@ -322,7 +324,7 @@
     # on submit notification
     self.notify_obj.notify_contact('Delivery Note',self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
 
-   
+
   # *********** Checks whether actual quantity is present in warehouse *************
   def check_qty_in_stock(self):
     for d in getlist(self.doclist, 'packing_details'):
@@ -334,7 +336,7 @@
 
 
 # ON CANCEL
-# =================================================================================================  
+# =================================================================================================
   def on_cancel(self):
     sales_com_obj = get_obj(dt = 'Sales Common')
     sales_com_obj.check_stop_sales_order(self)
@@ -345,14 +347,14 @@
     # :::::: set DN status :::::::
     set(self.doc, 'status', 'Cancelled')
 
-  
+
   # ******************** Check Next DocStatus **************************
   def check_next_docstatus(self):
     submit_rv = sql("select t1.name from `tabReceivable Voucher` t1,`tabRV Detail` t2 where t1.name = t2.parent and t2.delivery_note = '%s' and t1.docstatus = 1" % (self.doc.name))
     if submit_rv:
       msgprint("Sales Invoice : " + cstr(submit_rv[0][0]) + " has already been submitted !")
       raise Exception , "Validation Error."
-    
+
     submit_in = sql("select t1.name from `tabInstallation Note` t1, `tabInstalled Item Details` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
     if submit_in:
       msgprint("Installation Note : "+cstr(submit_in[0][0]) +" has already been submitted !")
@@ -369,11 +371,11 @@
         if not d[0]:
           msgprint("Message: Please enter Warehouse for item %s as it is stock item."% d[1])
           raise Exception
-        # if prevdoc_doctype = "Sales Order" 
+        # if prevdoc_doctype = "Sales Order"
         if d[3] < 0 :
           # Reduce Reserved Qty from warehouse
           bin = get_obj('Warehouse', d[0]).update_bin(0, flt(update_stock) * flt(d[3]), 0, 0, 0, d[1], self.doc.transaction_date)
-          
+
         # Reduce actual qty from warehouse
         self.make_sl_entry(d, d[0], - flt(d[2]) , 0, update_stock)
     get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
@@ -383,7 +385,7 @@
   def get_item_list(self, is_stopped):
    return get_obj('Sales Common').get_item_list(self, is_stopped)
 
-	
+
   # ********************** Make Stock Entry ************************************
   def make_sl_entry(self, d, wh, qty, in_value, update_stock):
     self.values.append({
@@ -394,8 +396,8 @@
       'posting_time'        : self.doc.posting_time,
       'voucher_type'        : 'Delivery Note',
       'voucher_no'          : self.doc.name,
-      'voucher_detail_no'   : '', 
-      'actual_qty'          : qty, 
+      'voucher_detail_no'   : '',
+      'actual_qty'          : qty,
       'stock_uom'           : d[4],
       'incoming_rate'       : in_value,
       'company'             : self.doc.company,
@@ -403,9 +405,9 @@
       'is_cancelled'        : (update_stock==1) and 'No' or 'Yes',
       'batch_no'            : d[5],
       'serial_no'           : d[6]
-    })    
+    })
 
-  
+
   # SEND SMS
   # ============================================================================================
   def send_sms(self):
@@ -436,3 +438,44 @@
   # ===========================================
   def repair_delivery_note(self):
     get_obj('Sales Common', 'Sales Common').repair_curr_doctype_details(self)
+
+  # Packing Slip Related
+  # ==========================================
+  def update_pack_nett_weight(self):
+      for d in getlist(self.doclist, 'delivery_note_details'):
+        if d.item_name:
+          item_wt = sql("select nett_weight from `tabItem` where item_name = '%s'" % (d.item_name))
+          d.pack_nett_wt = item_wt and flt(item_wt[0][0])*flt(d.qty) or 0
+
+  # ==========================================
+  def print_packing_slip(self):
+    prev_pack='0'
+    sno=0
+    html=''
+    tot_nett_wt,tot_gross_wt=0,0
+    for d in getlist(self.doclist, 'delivery_note_details'):
+      sno=sno+1
+      if sno!=1:#Footer goes here
+        html+='</table><table width="100%"><tr><td>CASE NO</td><td>'+cstr(d.pack_no)+'</td><td>NETT WT</td><td>'+cstr(tot_nett_wt)+'</td><td>CHECKED BY</td><td></td></tr><tr><td>SIZE</td><td></td><td>GROSS WT</td><td>'+cstr(tot_gross_wt)+'</td><td>PACKED BY</td><td></td></tr></table>'
+      if prev_pack!=d.pack_no: #Prepare Header Here
+        #Header code goes here
+        html+='<div align="center">[HEADER GOES HERE]</div><div><center><h2>Packing Slip</h2></center></div> <table width="100%"><tr><td>Order No.</td><td>'+cstr(self.doc.sales_order_no)+'</td><td>Shipping Marks</td><td>'+cstr(d.pack_no)+'</td></tr></table>'
+        html+='<table class="cust_tbl" style="page-break-after:always" width="100%"><tr><td>S.NO.</td><td>QUANTITY</td><td>CS.NO.</td><td>DESCRIPTION</td><td>WEIGHT</td><tr>'
+        sno=0
+        tot_nett_wt,to_gross_wt=flt(d.pack_nett_wt),flt(d.pack_gross_wt)
+      #Body code goes here
+      html+='<tr><td>'+cstr(sno+1)+'</td><td>'+cstr(d.qty)+'</td><td></td><td>'+d.item_code+'</td><td>'+cstr(d.pack_nett_wt)+'</td></tr>'
+      prev_pack=d.pack_no
+      tot_nett_wt+=flt(d.pack_nett_wt)
+      tot_gross_wt+=flt(d.pack_gross_wt)
+    html+='</html>'
+    self.doc.print_packing_slip=html
+
+
+
+
+
+
+
+
+
diff --git a/stock/doctype/delivery_note/delivery_note.txt b/stock/doctype/delivery_note/delivery_note.txt
index b77a6a5..1ab19e0 100644
--- a/stock/doctype/delivery_note/delivery_note.txt
+++ b/stock/doctype/delivery_note/delivery_note.txt
@@ -5,14 +5,23 @@
 	{
 		'creation': '2011-04-18 15:58:20',
 		'docstatus': 0,
-		'modified': '2011-08-09 17:10:45',
+		'modified': '2011-08-23 15:26:57',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'name': '__common__',
+		'parent': 'Delivery Note',
+		'parentfield': 'fields',
+		'parenttype': 'DocType'
+	},
+
 	# These values are common for all DocType
 	{
-		'_last_update': '1311621379',
+		'_last_update': '1313665263',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'document_type': 'Transaction',
@@ -27,15 +36,16 @@
 		'show_in_menu': 0,
 		'subject': 'To %(customer_name)s on %(transaction_date)s | %(per_billed)s% billed',
 		'tag_fields': 'billing_status',
-		'version': 446
+		'version': 449
 	},
 
-	# These values are common for all DocField
+	# These values are common for all DocFormat
 	{
-		'doctype': 'DocField',
+		'doctype': 'DocFormat',
+		'format': 'Delivery Note Packing List Wise',
 		'name': '__common__',
 		'parent': 'Delivery Note',
-		'parentfield': 'fields',
+		'parentfield': 'formats',
 		'parenttype': 'DocType'
 	},
 
@@ -109,21 +119,8 @@
 
 	# DocPerm
 	{
-		'amend': 1,
-		'cancel': 1,
-		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 5,
-		'permlevel': 0,
-		'role': 'Sales Manager',
-		'submit': 1,
-		'write': 1
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 6,
 		'permlevel': 1,
 		'role': 'All'
 	},
@@ -131,11 +128,23 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 7,
+		'idx': 6,
 		'permlevel': 2,
 		'role': 'All'
 	},
 
+	# DocFormat
+	{
+		'doctype': 'DocFormat',
+		'idx': 1
+	},
+
+	# DocFormat
+	{
+		'doctype': 'DocFormat',
+		'idx': 2
+	},
+
 	# DocField
 	{
 		'colour': 'White:FFF',
@@ -1471,5 +1480,18 @@
 		'options': 'repair_delivery_note',
 		'permlevel': 0,
 		'print_hide': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'print_packing_slip',
+		'fieldtype': 'Text',
+		'hidden': 1,
+		'idx': 95,
+		'in_filter': 0,
+		'label': 'Print Packing Slip',
+		'permlevel': 0,
+		'print_hide': 0
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/delivery_note_detail/delivery_note_detail.txt b/stock/doctype/delivery_note_detail/delivery_note_detail.txt
index 78aea32..a8fea20 100644
--- a/stock/doctype/delivery_note_detail/delivery_note_detail.txt
+++ b/stock/doctype/delivery_note_detail/delivery_note_detail.txt
@@ -5,7 +5,7 @@
 	{
 		'creation': '2010-08-08 17:08:58',
 		'docstatus': 0,
-		'modified': '2011-03-01 10:35:06',
+		'modified': '2011-08-22 12:11:51',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -21,7 +21,7 @@
 		'section_style': 'Tray',
 		'server_code_error': ' ',
 		'show_in_menu': 0,
-		'version': 35
+		'version': 38
 	},
 
 	# These values are common for all DocField
@@ -104,25 +104,11 @@
 
 	# DocField
 	{
-		'doctype': 'DocField',
-		'fieldname': 'no_of_packs',
-		'fieldtype': 'Int',
-		'idx': 5,
-		'label': 'No of Packs',
-		'oldfieldname': 'no_of_packs',
-		'oldfieldtype': 'Int',
-		'permlevel': 0,
-		'print_hide': 1,
-		'width': '100px'
-	},
-
-	# DocField
-	{
 		'default': '0.00',
 		'doctype': 'DocField',
 		'fieldname': 'qty',
 		'fieldtype': 'Currency',
-		'idx': 6,
+		'idx': 5,
 		'label': 'Quantity',
 		'oldfieldname': 'qty',
 		'oldfieldtype': 'Currency',
@@ -138,7 +124,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'ref_rate',
 		'fieldtype': 'Currency',
-		'idx': 7,
+		'idx': 6,
 		'label': 'Ref Rate',
 		'no_copy': 0,
 		'oldfieldname': 'ref_rate',
@@ -156,7 +142,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'adj_rate',
 		'fieldtype': 'Float',
-		'idx': 8,
+		'idx': 7,
 		'label': 'Discount (%)',
 		'oldfieldname': 'adj_rate',
 		'oldfieldtype': 'Float',
@@ -171,7 +157,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'export_rate',
 		'fieldtype': 'Currency',
-		'idx': 9,
+		'idx': 8,
 		'label': 'Rate',
 		'oldfieldname': 'export_rate',
 		'oldfieldtype': 'Currency',
@@ -187,7 +173,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'export_amount',
 		'fieldtype': 'Currency',
-		'idx': 10,
+		'idx': 9,
 		'label': 'Amount',
 		'oldfieldname': 'export_amount',
 		'oldfieldtype': 'Currency',
@@ -202,7 +188,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'base_ref_rate',
 		'fieldtype': 'Currency',
-		'idx': 11,
+		'idx': 10,
 		'label': 'Ref Rate*',
 		'oldfieldname': 'base_ref_rate',
 		'oldfieldtype': 'Currency',
@@ -217,7 +203,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'basic_rate',
 		'fieldtype': 'Currency',
-		'idx': 12,
+		'idx': 11,
 		'label': 'Rate*',
 		'oldfieldname': 'basic_rate',
 		'oldfieldtype': 'Currency',
@@ -233,7 +219,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'amount',
 		'fieldtype': 'Currency',
-		'idx': 13,
+		'idx': 12,
 		'label': 'Amount*',
 		'oldfieldname': 'amount',
 		'oldfieldtype': 'Currency',
@@ -248,7 +234,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'warehouse',
 		'fieldtype': 'Link',
-		'idx': 14,
+		'idx': 13,
 		'label': 'Warehouse',
 		'oldfieldname': 'warehouse',
 		'oldfieldtype': 'Link',
@@ -264,7 +250,8 @@
 		'doctype': 'DocField',
 		'fieldname': 'serial_no',
 		'fieldtype': 'Text',
-		'idx': 15,
+		'idx': 14,
+		'in_filter': 1,
 		'label': 'Serial No',
 		'no_copy': 1,
 		'oldfieldname': 'serial_no',
@@ -279,14 +266,13 @@
 		'doctype': 'DocField',
 		'fieldname': 'batch_no',
 		'fieldtype': 'Link',
-		'idx': 16,
+		'idx': 15,
 		'label': 'Batch No',
 		'oldfieldname': 'batch_no',
 		'oldfieldtype': 'Link',
 		'options': 'Batch',
 		'permlevel': 0,
-		'print_hide': 1,
-		'search_index': 0
+		'print_hide': 1
 	},
 
 	# DocField
@@ -294,14 +280,13 @@
 		'doctype': 'DocField',
 		'fieldname': 'item_group',
 		'fieldtype': 'Link',
-		'idx': 17,
+		'idx': 16,
 		'label': 'Item Group',
 		'oldfieldname': 'item_group',
 		'oldfieldtype': 'Link',
 		'options': 'Item Group',
 		'permlevel': 1,
-		'print_hide': 1,
-		'search_index': 0
+		'print_hide': 1
 	},
 
 	# DocField
@@ -309,23 +294,77 @@
 		'doctype': 'DocField',
 		'fieldname': 'brand',
 		'fieldtype': 'Link',
-		'idx': 18,
+		'idx': 17,
 		'label': 'Brand Name',
 		'oldfieldname': 'brand',
 		'oldfieldtype': 'Link',
 		'options': 'Brand',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 0,
 		'width': '150px'
 	},
 
 	# DocField
 	{
 		'doctype': 'DocField',
+		'fieldname': 'pack_no',
+		'fieldtype': 'Data',
+		'idx': 18,
+		'label': 'Pack No',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'pack_gross_wt',
+		'fieldtype': 'Float',
+		'idx': 19,
+		'label': 'Pack Gross Wt',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'weight_uom',
+		'fieldtype': 'Link',
+		'idx': 20,
+		'label': 'Weight UOM',
+		'options': 'UOM',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'pack_nett_wt',
+		'fieldtype': 'Float',
+		'idx': 21,
+		'label': 'Pack Nett Wt',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'no_of_packs',
+		'fieldtype': 'Int',
+		'idx': 22,
+		'label': 'No of Packs',
+		'oldfieldname': 'no_of_packs',
+		'oldfieldtype': 'Int',
+		'permlevel': 0,
+		'print_hide': 1,
+		'width': '100px'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
 		'fieldname': 'pack_unit',
 		'fieldtype': 'Data',
-		'idx': 19,
+		'idx': 23,
 		'label': 'Pack Unit',
 		'oldfieldname': 'pack_unit',
 		'oldfieldtype': 'Data',
@@ -339,7 +378,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'installed_qty',
 		'fieldtype': 'Currency',
-		'idx': 20,
+		'idx': 24,
 		'label': 'Installed Qty',
 		'no_copy': 1,
 		'oldfieldname': 'installed_qty',
@@ -354,7 +393,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'actual_qty',
 		'fieldtype': 'Currency',
-		'idx': 21,
+		'idx': 25,
 		'label': 'Available Qty at Warehouse',
 		'no_copy': 1,
 		'oldfieldname': 'actual_qty',
@@ -366,27 +405,10 @@
 
 	# DocField
 	{
-		'colour': 'White:FFF',
-		'default': '0.00',
-		'doctype': 'DocField',
-		'fieldname': 'billed_qty',
-		'fieldtype': 'Currency',
-		'idx': 22,
-		'label': 'Billed Qty',
-		'no_copy': 1,
-		'oldfieldname': 'billed_qty',
-		'oldfieldtype': 'Currency',
-		'permlevel': 1,
-		'print_hide': 1,
-		'width': '100px'
-	},
-
-	# DocField
-	{
 		'doctype': 'DocField',
 		'fieldname': 'billed_amt',
 		'fieldtype': 'Currency',
-		'idx': 23,
+		'idx': 26,
 		'label': 'Billed Amt',
 		'no_copy': 1,
 		'permlevel': 1,
@@ -401,7 +423,7 @@
 		'fieldname': 'prevdoc_docname',
 		'fieldtype': 'Data',
 		'hidden': 0,
-		'idx': 24,
+		'idx': 27,
 		'in_filter': 1,
 		'label': 'Against Document No',
 		'no_copy': 1,
@@ -419,14 +441,14 @@
 		'fieldname': 'prevdoc_doctype',
 		'fieldtype': 'Data',
 		'hidden': 1,
-		'idx': 25,
+		'idx': 28,
 		'in_filter': 1,
 		'label': 'Document Type',
 		'oldfieldname': 'prevdoc_doctype',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '150px'
 	},
 
@@ -436,7 +458,7 @@
 		'fieldname': 'prevdoc_date',
 		'fieldtype': 'Date',
 		'hidden': 1,
-		'idx': 26,
+		'idx': 29,
 		'in_filter': 1,
 		'label': 'Against Document Date',
 		'oldfieldname': 'prevdoc_date',
@@ -451,14 +473,14 @@
 		'fieldname': 'prevdoc_detail_docname',
 		'fieldtype': 'Data',
 		'hidden': 1,
-		'idx': 27,
+		'idx': 30,
 		'in_filter': 1,
 		'label': 'Against Document Detail No',
 		'oldfieldname': 'prevdoc_detail_docname',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -468,7 +490,7 @@
 		'fieldname': 'item_tax_rate',
 		'fieldtype': 'Small Text',
 		'hidden': 1,
-		'idx': 28,
+		'idx': 31,
 		'label': 'Item Tax Rate',
 		'oldfieldname': 'item_tax_rate',
 		'oldfieldtype': 'Small Text',
@@ -482,7 +504,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'page_break',
 		'fieldtype': 'Check',
-		'idx': 29,
+		'idx': 32,
 		'label': 'Page Break',
 		'oldfieldname': 'page_break',
 		'oldfieldtype': 'Check',
diff --git a/stock/doctype/item/item.js b/stock/doctype/item/item.js
index 3c02629..6dd7377 100644
--- a/stock/doctype/item/item.js
+++ b/stock/doctype/item/item.js
@@ -1,17 +1,17 @@
 cur_frm.cscript.refresh = function(doc) {
 	// make sensitive fields(has_serial_no, is_stock_item, valuation_method)
 	// read only if any stock ledger entry exists
-	
+
 	if ((!doc.__islocal) && (doc.is_stock_item == 'Yes')) {
 		var callback = function(r, rt) {
 			if (r.message == 'exists') permlevel = 1;
 			else permlevel = 0;
-				
+
 			set_field_permlevel('has_serial_no', permlevel);
 			set_field_permlevel('is_stock_item', permlevel);
 			set_field_permlevel('valuation_method', permlevel);
 		}
-		$c_obj(make_doclist(doc.doctype, doc.name),'check_if_sle_exists','',callback); 
+		$c_obj(make_doclist(doc.doctype, doc.name),'check_if_sle_exists','',callback);
 	}
 }
 
@@ -24,25 +24,25 @@
 
 // Expense Account
 // ---------------------------------
-cur_frm.fields_dict['purchase_account'].get_query = function(doc){ 
+cur_frm.fields_dict['purchase_account'].get_query = function(doc){
   return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Debit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.`is_pl_account` = "Yes" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
 }
 
-// Income Account 
+// Income Account
 // --------------------------------
 cur_frm.fields_dict['default_income_account'].get_query = function(doc) {
   return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Credit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`is_pl_account` = "Yes" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.`account_type` ="Income Account" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
 }
 
 
-// Purchase Cost Center 
+// Purchase Cost Center
 // -----------------------------
 cur_frm.fields_dict['cost_center'].get_query = function(doc) {
   return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50'
 }
 
 
-// Sales Cost Center 
+// Sales Cost Center
 // -----------------------------
 cur_frm.fields_dict['default_sales_cost_center'].get_query = function(doc) {
   return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50'
@@ -66,7 +66,7 @@
 
 cur_frm.cscript.IGHelp = function(doc,dt,dn){
   var call_back = function(){
-    var sb_obj = new SalesBrowser();        
+    var sb_obj = new SalesBrowser();
     sb_obj.set_val('Item Group');
 
   }
@@ -79,21 +79,34 @@
 // in the "alternate_description" field
 cur_frm.cscript['Add Image'] = function(doc, dt, dn) {
 	if(!doc.file_list) {
-		msgprint('Please attach a file first!'); 
+		msgprint('Please attach a file first!');
 	}
-	
+
 	var f = doc.file_list.split('\n')[0];
 	var fname = f.split(',')[0];
 	var fid = f.split(',')[1];
 	if(!in_list(['jpg','jpeg','gif','png'], fname.split('.')[1].toLowerCase())) {
 		msgprint('File must be of extension jpg, jpeg, gif or png'); return;
 	}
-	
+
 	doc.description_html = repl('<table style="width: 100%; table-layout: fixed;">'+
 	'<tr><td style="width:110px"><img src="%(imgurl)s" width="100px"></td>'+
 	'<td>%(desc)s</td></tr>'+
 	'</table>', {imgurl: wn.urllib.get_file_url(fid), desc:doc.description});
-	
+
 	refresh_field('description_html');
 }
+//===================== Quotation to validation - either customer or lead mandatory ====================
+cur_frm.cscript.weight_to_validate = function(doc,cdt,cdn){
 
+  if((doc.nett_weight || doc.gross_weight) && !doc.weight_uom)
+  {
+    alert('Weight is mentioned,\nPlease mention "Weight UOM" too');
+    validated=0;
+  }
+}
+//===================validation function =================================
+
+cur_frm.cscript.validate = function(doc,cdt,cdn){
+  cur_frm.cscript.weight_to_validate(doc,cdt,cdn);
+}
diff --git a/stock/doctype/item/item.py b/stock/doctype/item/item.py
index b506541..28f1d12 100644
--- a/stock/doctype/item/item.py
+++ b/stock/doctype/item/item.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,7 +21,7 @@
 	def __init__(self, doc, doclist=[]):
 		self.doc = doc
 		self.doclist = doclist
-		
+
 	def get_tax_rate(self, tax_type):
 		rate = sql("select tax_rate from tabAccount where name = %s", tax_type)
 		ret = {
@@ -39,14 +39,14 @@
 			if not self.doc.stock_uom:
 				msgprint("Please enter Stock UOM first.")
 				raise Exception
-			
+
 			if cstr(d.uom) in check_list:
 				msgprint("UOM %s has been entered more than once in Conversion Factor Details." % cstr(d.uom))
 				raise Exception
-			
+
 			if not cstr(d.uom) in check_list:
 				check_list.append(cstr(d.uom))
-							
+
 			if cstr(d.uom) == cstr(self.doc.stock_uom):
 				if flt(d.conversion_factor) != 1:
 					msgprint("Conversion Fator of UOM : %s should be equal to 1. As UOM : %s is Stock UOM of Item: %s." % ( cstr(d.uom), cstr(d.uom), cstr(self.doc.name)))
@@ -56,14 +56,14 @@
 			elif cstr(d.uom) != cstr(self.doc.stock_uom) and flt(d.conversion_factor) == 1:
 				msgprint("Conversion Factor of UOM : %s should not be equal to 1. As UOM : %s is not Stock UOM of Item: %s." % ( cstr(d.uom), cstr(d.uom), cstr(self.doc.name)))
 				raise Exception
-		
+
 		if not cstr(self.doc.stock_uom) in check_list :
 			child = addchild( self.doc, 'uom_conversion_details', 'UOM Conversion Detail', 1, self.doclist)
 			child.uom = self.doc.stock_uom
 			child.conversion_factor = 1
 			child.save()
 
-	
+
 	# Check whether Ref Rate is not entered twice for same Price List and Currency
 	def check_ref_rate_detail(self):
 		check_list=[]
@@ -73,7 +73,13 @@
 				raise Exception
 			else:
 				check_list.append([cstr(d.price_list_name),cstr(d.ref_currency)])
-				
+
+	# Append all the customer codes and insert into "customer_code" field of item table
+	def fill_customer_code(self):
+		cust_code=[]
+		for d in getlist(self.doclist,'item_customer_details'):
+			cust_code.append(d.ref_code)
+		self.doc.customer_code=','.join(cust_code)
 
 	# Check whether Tax Rate is not entered twice for same Tax Type
 	def check_item_tax(self):
@@ -89,7 +95,7 @@
 					msgprint("Rate is entered twice for Tax : '%s'." % (d.tax_type))
 					raise Exception
 				else:
-					check_list.append(d.tax_type)				
+					check_list.append(d.tax_type)
 
 	def check_for_active_boms(self, check):
 		if check in ['Is Active', 'Is Purchase Item']:
@@ -102,7 +108,7 @@
 			if bom and bom[0][0]:
 				msgprint("%s should be 'Yes'. As Item %s is present in one or many Active BOMs." % (cstr(check), cstr(self.doc.name)))
 				raise Exception
-		
+
 	def validate(self):
 		fl = {'is_manufactured_item'	:'Is Manufactured Item',
 					'is_sub_contracted_item':'Is Sub Contracted Item',
@@ -112,18 +118,19 @@
 			if cstr(self.doc.fields[d]) != 'Yes':
 				self.check_for_active_boms(check = fl[d])
 		self.check_ref_rate_detail()
+		self.fill_customer_code()
 		self.check_item_tax()
 		if not self.doc.min_order_qty:
 			self.doc.min_order_qty = 0
 		self.check_non_asset_warehouse()
-		
+
 		if self.doc.is_pro_applicable == 'Yes' and self.doc.is_manufactured_item != 'Yes':
 			msgprint("If making Production Order is allowed then, it should also allow to make Bill of Materials. Refer Manufacturing section.")
 			raise Exception
-			
+
 		if self.doc.is_pro_applicable == 'Yes' and self.doc.is_stock_item == 'No':
 			msgprint("As Production Order can be made for this Item, then Is Stock Item Should be 'Yes' as we maintain it's stock. Refer Manufacturing and Inventory section.", raise_exception=1)
-			
+
 		if self.doc.is_stock_item == "Yes" and not self.doc.default_warehouse:
 			msgprint("As we maintain stock of this item, its better to maintain default warehouse. To add default warehouse please go to 'Inventory' section. It will be fetched automatically while making Sales Order, Delivery Note, etc.. ", 1)
 
@@ -146,7 +153,7 @@
 			if flt(total_qty) < flt(self.doc.minimum_inventory_level):
 				msgprint("Your minimum inventory level is reached")
 				send_to = []
-				send = sql("select t1.email from `tabProfile` t1,`tabUserRole` t2 where t2.role IN ('Material Master Manager','Purchase Manager') and t2.parent = t1.name") 
+				send = sql("select t1.email from `tabProfile` t1,`tabUserRole` t2 where t2.role IN ('Material Master Manager','Purchase Manager') and t2.parent = t1.name")
 				for d in send:
 					send_to.append(d[0])
 				msg = '''
@@ -167,10 +174,10 @@
 		ret = {
 			'file_group'	:	file and file[0]['file_group'] or '',
 			'description'	:	file and file[0]['description'] or ''
-			
+
 		}
 		return ret
-		
+
 	def check_if_sle_exists(self):
 		"""
 			checks if any stock ledger entry exists for this item
@@ -178,7 +185,7 @@
 
 		sle = sql("select name from `tabStock Ledger Entry` where item_code = %s and ifnull(is_cancelled, 'No') = 'No'", self.doc.name)
 		return sle and 'exists' or 'not exists'
-		
+
 	def on_rename(self,newdn,olddn):
-		sql("update tabItem set item_code = %s where name = %s", (newdn, olddn))	
-		
+		sql("update tabItem set item_code = %s where name = %s", (newdn, olddn))
+
diff --git a/stock/doctype/item/item.txt b/stock/doctype/item/item.txt
index ec42ff4..0d20f7b 100644
--- a/stock/doctype/item/item.txt
+++ b/stock/doctype/item/item.txt
@@ -5,14 +5,14 @@
 	{
 		'creation': '2010-08-08 17:09:05',
 		'docstatus': 0,
-		'modified': '2011-05-30 15:22:32',
+		'modified': '2011-08-18 13:03:31',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309508838',
+		'_last_update': '1313651083',
 		'allow_attach': 1,
 		'allow_trash': 1,
 		'autoname': 'field:item_code',
@@ -22,13 +22,13 @@
 		'max_attachments': 1,
 		'module': 'Stock',
 		'name': '__common__',
-		'search_fields': 'item_name,description,item_group',
+		'search_fields': 'item_name,description,item_group,customer_code',
 		'section_style': 'Tray',
 		'server_code_error': ' ',
 		'show_in_menu': 0,
 		'subject': '%(item_name)s',
 		'tag_fields': 'item_group',
-		'version': 153
+		'version': 161
 	},
 
 	# These values are common for all DocField
@@ -42,14 +42,12 @@
 
 	# These values are common for all DocPerm
 	{
-		'amend': 0,
 		'doctype': 'DocPerm',
 		'name': '__common__',
 		'parent': 'Item',
 		'parentfield': 'permissions',
 		'parenttype': 'DocType',
-		'read': 1,
-		'submit': 0
+		'read': 1
 	},
 
 	# DocType, Item
@@ -60,44 +58,53 @@
 
 	# DocPerm
 	{
-		'cancel': 0,
-		'create': 0,
-		'doctype': 'DocPerm',
-		'permlevel': 0,
-		'role': 'Material User',
-		'write': 0
-	},
-
-	# DocPerm
-	{
+		'amend': 0,
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 1,
 		'permlevel': 1,
 		'role': 'Material Manager',
+		'submit': 0,
 		'write': 0
 	},
 
 	# DocPerm
 	{
+		'amend': 0,
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 2,
 		'permlevel': 0,
 		'role': 'Material Manager',
+		'submit': 0,
 		'write': 0
 	},
 
 	# DocPerm
 	{
+		'amend': 0,
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 1,
 		'role': 'Material User',
+		'submit': 0,
+		'write': 0
+	},
+
+	# DocPerm
+	{
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
+		'doctype': 'DocPerm',
+		'idx': 4,
+		'permlevel': 0,
+		'role': 'Material User',
+		'submit': 0,
 		'write': 0
 	},
 
@@ -114,7 +121,6 @@
 
 	# DocPerm
 	{
-		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 6,
@@ -136,13 +142,10 @@
 
 	# DocPerm
 	{
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 8,
 		'permlevel': 1,
-		'role': 'System Manager',
-		'write': 0
+		'role': 'System Manager'
 	},
 
 	# DocField
@@ -197,7 +200,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -241,8 +244,7 @@
 		'options': 'Brand',
 		'permlevel': 0,
 		'print_hide': 1,
-		'reqd': 0,
-		'search_index': 0
+		'reqd': 0
 	},
 
 	# DocField
@@ -285,7 +287,7 @@
 		'description': 'Generates HTML to include image (1st attachment) in the description',
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 12,
+		'idx': 11,
 		'label': 'Add Image',
 		'permlevel': 0
 	},
@@ -294,7 +296,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 13,
+		'idx': 12,
 		'label': 'Inventory',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -307,14 +309,13 @@
 		'doctype': 'DocField',
 		'fieldname': 'stock_uom',
 		'fieldtype': 'Link',
-		'idx': 14,
+		'idx': 13,
 		'label': 'Default UoM',
 		'oldfieldname': 'stock_uom',
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
 		'permlevel': 0,
-		'reqd': 1,
-		'search_index': 0
+		'reqd': 1
 	},
 
 	# DocField
@@ -325,7 +326,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_stock_item',
 		'fieldtype': 'Select',
-		'idx': 15,
+		'idx': 14,
 		'label': 'Is Stock Item',
 		'oldfieldname': 'is_stock_item',
 		'oldfieldtype': 'Select',
@@ -339,7 +340,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'valuation_method',
 		'fieldtype': 'Select',
-		'idx': 16,
+		'idx': 15,
 		'label': 'Valuation Method',
 		'oldfieldname': 'valuation_method',
 		'oldfieldtype': 'Select',
@@ -352,13 +353,12 @@
 		'doctype': 'DocField',
 		'fieldname': 'default_warehouse',
 		'fieldtype': 'Link',
-		'idx': 17,
+		'idx': 16,
 		'label': 'Default Warehouse',
 		'oldfieldname': 'default_warehouse',
 		'oldfieldtype': 'Link',
 		'options': 'Warehouse',
-		'permlevel': 0,
-		'search_index': 0
+		'permlevel': 0
 	},
 
 	# DocField
@@ -368,7 +368,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'tolerance',
 		'fieldtype': 'Currency',
-		'idx': 18,
+		'idx': 17,
 		'label': 'Allowance Percent',
 		'oldfieldname': 'tolerance',
 		'oldfieldtype': 'Currency',
@@ -380,7 +380,7 @@
 		'doctype': 'DocField',
 		'fieldname': 're_order_level',
 		'fieldtype': 'Currency',
-		'idx': 19,
+		'idx': 18,
 		'label': 'Re-Order Level',
 		'oldfieldname': 're_order_level',
 		'oldfieldtype': 'Currency',
@@ -395,7 +395,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'minimum_inventory_level',
 		'fieldtype': 'Currency',
-		'idx': 20,
+		'idx': 19,
 		'label': 'Minimum Inventory Level',
 		'oldfieldname': 'minimum_inventory_level',
 		'oldfieldtype': 'Currency',
@@ -412,7 +412,7 @@
 		'fieldname': 'min_order_qty',
 		'fieldtype': 'Currency',
 		'hidden': 0,
-		'idx': 21,
+		'idx': 20,
 		'label': 'Minimum Order Qty',
 		'oldfieldname': 'min_order_qty',
 		'oldfieldtype': 'Currency',
@@ -423,7 +423,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 22,
+		'idx': 21,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'width': '50%'
@@ -437,7 +437,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_asset_item',
 		'fieldtype': 'Select',
-		'idx': 23,
+		'idx': 22,
 		'label': 'Is Asset Item',
 		'oldfieldname': 'is_asset_item',
 		'oldfieldtype': 'Select',
@@ -453,7 +453,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'has_batch_no',
 		'fieldtype': 'Select',
-		'idx': 24,
+		'idx': 23,
 		'label': 'Has Batch No',
 		'oldfieldname': 'has_batch_no',
 		'oldfieldtype': 'Select',
@@ -470,7 +470,8 @@
 		'doctype': 'DocField',
 		'fieldname': 'has_serial_no',
 		'fieldtype': 'Select',
-		'idx': 25,
+		'idx': 24,
+		'in_filter': 1,
 		'label': 'Has Serial No',
 		'oldfieldname': 'has_serial_no',
 		'oldfieldtype': 'Select',
@@ -484,7 +485,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'warranty_period',
 		'fieldtype': 'Data',
-		'idx': 26,
+		'idx': 25,
 		'label': 'Warranty Period (in days)',
 		'oldfieldname': 'warranty_period',
 		'oldfieldtype': 'Data',
@@ -496,7 +497,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'end_of_life',
 		'fieldtype': 'Date',
-		'idx': 27,
+		'idx': 26,
 		'label': 'End of Life',
 		'oldfieldname': 'end_of_life',
 		'oldfieldtype': 'Date',
@@ -505,10 +506,41 @@
 
 	# DocField
 	{
+		'doctype': 'DocField',
+		'fieldname': 'nett_weight',
+		'fieldtype': 'Float',
+		'idx': 27,
+		'label': 'Nett Weight',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'gross_weight',
+		'fieldtype': 'Float',
+		'idx': 28,
+		'label': 'Gross Weight',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'weight_uom',
+		'fieldtype': 'Link',
+		'idx': 29,
+		'label': 'Weight UOM',
+		'options': 'UOM',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 28,
+		'idx': 30,
 		'label': 'Purchase Details',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -522,7 +554,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_purchase_item',
 		'fieldtype': 'Select',
-		'idx': 29,
+		'idx': 31,
 		'label': 'Is Purchase Item',
 		'oldfieldname': 'is_purchase_item',
 		'oldfieldtype': 'Select',
@@ -538,7 +570,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'lead_time_days',
 		'fieldtype': 'Int',
-		'idx': 30,
+		'idx': 32,
 		'label': 'Lead Time Days',
 		'no_copy': 1,
 		'oldfieldname': 'lead_time_days',
@@ -553,13 +585,12 @@
 		'doctype': 'DocField',
 		'fieldname': 'purchase_account',
 		'fieldtype': 'Link',
-		'idx': 31,
+		'idx': 33,
 		'label': 'Default Expense Account',
 		'oldfieldname': 'purchase_account',
 		'oldfieldtype': 'Link',
 		'options': 'Account',
 		'permlevel': 0,
-		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -570,13 +601,12 @@
 		'doctype': 'DocField',
 		'fieldname': 'cost_center',
 		'fieldtype': 'Link',
-		'idx': 32,
+		'idx': 34,
 		'label': 'Default Cost Center',
 		'oldfieldname': 'cost_center',
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
-		'permlevel': 0,
-		'search_index': 0
+		'permlevel': 0
 	},
 
 	# DocField
@@ -586,7 +616,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'buying_cost',
 		'fieldtype': 'Currency',
-		'idx': 33,
+		'idx': 35,
 		'label': 'Buying Cost',
 		'no_copy': 1,
 		'oldfieldname': 'buying_cost',
@@ -600,7 +630,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'last_purchase_rate',
 		'fieldtype': 'Currency',
-		'idx': 34,
+		'idx': 36,
 		'label': 'Last Purchase Rate',
 		'no_copy': 1,
 		'oldfieldname': 'last_purchase_rate',
@@ -613,7 +643,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'standard_rate',
 		'fieldtype': 'Currency',
-		'idx': 35,
+		'idx': 37,
 		'label': 'Standard Rate',
 		'oldfieldname': 'standard_rate',
 		'oldfieldtype': 'Currency',
@@ -624,7 +654,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 36,
+		'idx': 38,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'width': '50%'
@@ -635,7 +665,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'uom_conversion_details',
 		'fieldtype': 'Table',
-		'idx': 37,
+		'idx': 39,
 		'label': 'UOM Conversion Details',
 		'oldfieldname': 'uom_conversion_details',
 		'oldfieldtype': 'Table',
@@ -647,7 +677,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 38,
+		'idx': 40,
 		'label': 'Sales Details',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -661,7 +691,8 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_sales_item',
 		'fieldtype': 'Select',
-		'idx': 39,
+		'idx': 41,
+		'in_filter': 1,
 		'label': 'Is Sales Item',
 		'oldfieldname': 'is_sales_item',
 		'oldfieldtype': 'Select',
@@ -678,7 +709,8 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_service_item',
 		'fieldtype': 'Select',
-		'idx': 40,
+		'idx': 42,
+		'in_filter': 1,
 		'label': 'Is Service Item',
 		'oldfieldname': 'is_service_item',
 		'oldfieldtype': 'Select',
@@ -695,7 +727,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_sample_item',
 		'fieldtype': 'Select',
-		'idx': 41,
+		'idx': 43,
 		'label': 'Allow Samples',
 		'oldfieldname': 'is_sample_item',
 		'oldfieldtype': 'Select',
@@ -709,7 +741,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'max_discount',
 		'fieldtype': 'Currency',
-		'idx': 42,
+		'idx': 44,
 		'label': 'Max Discount (%)',
 		'oldfieldname': 'max_discount',
 		'oldfieldtype': 'Currency',
@@ -721,11 +753,10 @@
 		'doctype': 'DocField',
 		'fieldname': 'default_income_account',
 		'fieldtype': 'Link',
-		'idx': 43,
+		'idx': 45,
 		'label': 'Default Income Account',
 		'options': 'Account',
-		'permlevel': 0,
-		'search_index': 0
+		'permlevel': 0
 	},
 
 	# DocField
@@ -733,11 +764,10 @@
 		'doctype': 'DocField',
 		'fieldname': 'default_sales_cost_center',
 		'fieldtype': 'Link',
-		'idx': 44,
+		'idx': 46,
 		'label': 'Cost Center',
 		'options': 'Cost Center',
-		'permlevel': 0,
-		'search_index': 0
+		'permlevel': 0
 	},
 
 	# DocField
@@ -746,7 +776,7 @@
 		'fieldname': 'sales_rate',
 		'fieldtype': 'Currency',
 		'hidden': 1,
-		'idx': 45,
+		'idx': 47,
 		'label': 'Sales Rate',
 		'oldfieldname': 'sales_rate',
 		'oldfieldtype': 'Currency',
@@ -757,7 +787,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 46,
+		'idx': 48,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'width': '50%'
@@ -770,7 +800,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'ref_rate_details',
 		'fieldtype': 'Table',
-		'idx': 47,
+		'idx': 49,
 		'label': 'Ref Rate Details',
 		'oldfieldname': 'ref_rate_details',
 		'oldfieldtype': 'Table',
@@ -780,9 +810,21 @@
 
 	# DocField
 	{
+		'description': 'For the convenience of customers, these codes can be used in print formats like Invoices and Delivery Notes',
+		'doctype': 'DocField',
+		'fieldname': 'item_customer_details',
+		'fieldtype': 'Table',
+		'idx': 50,
+		'label': 'Customer Codes',
+		'options': 'Item Customer Detail',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 48,
+		'idx': 51,
 		'label': 'Item Tax',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -793,7 +835,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'item_tax',
 		'fieldtype': 'Table',
-		'idx': 49,
+		'idx': 52,
 		'label': 'Item Tax1',
 		'oldfieldname': 'item_tax',
 		'oldfieldtype': 'Table',
@@ -805,7 +847,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 50,
+		'idx': 53,
 		'label': 'Inspection Criteria',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -817,7 +859,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'inspection_required',
 		'fieldtype': 'Select',
-		'idx': 51,
+		'idx': 54,
 		'label': 'Inspection Required',
 		'no_copy': 0,
 		'oldfieldname': 'inspection_required',
@@ -832,7 +874,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'item_specification_details',
 		'fieldtype': 'Table',
-		'idx': 52,
+		'idx': 55,
 		'label': 'Item Specification Detail',
 		'oldfieldname': 'item_specification_details',
 		'oldfieldtype': 'Table',
@@ -844,7 +886,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 53,
+		'idx': 56,
 		'label': 'Manufacturing',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -858,7 +900,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_manufactured_item',
 		'fieldtype': 'Select',
-		'idx': 54,
+		'idx': 57,
 		'label': 'Allow Bill of Materials',
 		'oldfieldname': 'is_manufactured_item',
 		'oldfieldtype': 'Select',
@@ -873,14 +915,13 @@
 		'doctype': 'DocField',
 		'fieldname': 'default_bom',
 		'fieldtype': 'Link',
-		'idx': 55,
+		'idx': 58,
 		'label': 'Default BOM',
 		'no_copy': 1,
 		'oldfieldname': 'default_bom',
 		'oldfieldtype': 'Link',
 		'options': 'Bill Of Materials',
-		'permlevel': 1,
-		'search_index': 0
+		'permlevel': 1
 	},
 
 	# DocField
@@ -891,7 +932,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_pro_applicable',
 		'fieldtype': 'Select',
-		'idx': 56,
+		'idx': 59,
 		'label': 'Allow Production Order',
 		'oldfieldname': 'is_pro_applicable',
 		'oldfieldtype': 'Select',
@@ -908,7 +949,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_sub_contracted_item',
 		'fieldtype': 'Select',
-		'idx': 57,
+		'idx': 60,
 		'label': 'Is Sub Contracted Item',
 		'oldfieldname': 'is_sub_contracted_item',
 		'oldfieldtype': 'Select',
@@ -923,9 +964,23 @@
 		'fieldname': 'file_list',
 		'fieldtype': 'Text',
 		'hidden': 1,
-		'idx': 59,
+		'idx': 61,
 		'label': 'File List',
 		'permlevel': 0,
 		'print_hide': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'customer_code',
+		'fieldtype': 'Data',
+		'hidden': 1,
+		'idx': 62,
+		'in_filter': 1,
+		'label': 'Customer Code',
+		'no_copy': 1,
+		'permlevel': 0,
+		'print_hide': 1
 	}
 ]
\ No newline at end of file
diff --git a/hr/doctype/salary_slip_control_panel/__init__.py b/stock/doctype/item_customer_detail/__init__.py
similarity index 100%
rename from hr/doctype/salary_slip_control_panel/__init__.py
rename to stock/doctype/item_customer_detail/__init__.py
diff --git a/stock/doctype/item_customer_detail/item_customer_detail.txt b/stock/doctype/item_customer_detail/item_customer_detail.txt
new file mode 100644
index 0000000..f53f18e
--- /dev/null
+++ b/stock/doctype/item_customer_detail/item_customer_detail.txt
@@ -0,0 +1,73 @@
+# DocType, Item Customer Detail
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-08-18 11:38:43',
+		'docstatus': 0,
+		'modified': '2011-08-18 11:54:36',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all DocType
+	{
+		'autoname': 'ITEMCUST/.#####',
+		'colour': 'White:FFF',
+		'description': 'For the convenience of customers, these codes can be used in print formats like Invoices and Delivery Notes',
+		'doctype': 'DocType',
+		'in_create': 1,
+		'istable': 1,
+		'module': 'Stock',
+		'name': '__common__',
+		'read_only': 0,
+		'section_style': 'Tray',
+		'server_code_error': ' ',
+		'show_in_menu': 0,
+		'version': 7
+	},
+
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'in_filter': 1,
+		'name': '__common__',
+		'parent': 'Item Customer Detail',
+		'parentfield': 'fields',
+		'parenttype': 'DocType',
+		'permlevel': 0,
+		'reqd': 1,
+		'search_index': 1
+	},
+
+	# DocType, Item Customer Detail
+	{
+		'doctype': 'DocType',
+		'name': 'Item Customer Detail'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'customer_name',
+		'fieldtype': 'Link',
+		'idx': 1,
+		'label': 'Customer Name',
+		'oldfieldname': 'price_list_name',
+		'oldfieldtype': 'Select',
+		'options': 'Customer',
+		'width': '180px'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'ref_code',
+		'fieldtype': 'Data',
+		'idx': 2,
+		'label': 'Ref Code',
+		'oldfieldname': 'ref_rate',
+		'oldfieldtype': 'Currency',
+		'width': '120px'
+	}
+]
\ No newline at end of file
diff --git a/stock/doctype/serial_no/serial_no.js b/stock/doctype/serial_no/serial_no.js
index 32620dd..a41113c 100644
--- a/stock/doctype/serial_no/serial_no.js
+++ b/stock/doctype/serial_no/serial_no.js
@@ -7,15 +7,16 @@
 
 // ************************************** refresh ***************************************************
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-  if(!doc.__islocal && doc.warehouse) set_field_permlevel('warehouse', 1);
-  if(!doc.__islocal && doc.item_code) set_field_permlevel('item_code', 1);
-  if(doc.__islocal) set_field_permlevel('status', 0);
+  if(!doc.__islocal) {
+    flds = ['item_code', 'warehouse', 'purchase_document_type', 'purchase_document_no', 'purchase_date', 'purchase_time', 'purchase_rate', 'supplier']
+    for(i=0;i<flds.length;i++) 
+      set_field_permlevel(flds[i], 1);
+  }
 }
 
 
 // ************************************** triggers **************************************************
 
-// -------------
 // item details
 // -------------
 cur_frm.add_fetch('item_code', 'item_name', 'item_name')
@@ -24,23 +25,12 @@
 cur_frm.add_fetch('item_code', 'description', 'description')
 cur_frm.add_fetch('item_code', 'warranty_period', 'warranty_period')
 
-
-// ---------
 // customer
 // ---------
 cur_frm.add_fetch('customer', 'customer_name', 'customer_name')
 cur_frm.add_fetch('customer', 'address', 'delivery_address')
 cur_frm.add_fetch('customer', 'territory', 'territory')
 
-
-// ---------
-// supplier
-// ---------
-//cur_frm.add_fetch('supplier', 'supplier_name', 'supplier_name')
-//cur_frm.add_fetch('customer', 'address', 'supplier_address')
-
-
-// ----------
 // territory
 // ----------
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
@@ -48,10 +38,8 @@
 }
 
 // Supplier
+//-------------
 cur_frm.cscript.supplier = function(doc,dt,dn) {
   if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
   if(doc.supplier) unhide_field(['supplier_name','address_display']);
 }
-
-
-
diff --git a/stock/doctype/serial_no/serial_no.py b/stock/doctype/serial_no/serial_no.py
index 9c99357..cf7fd50 100644
--- a/stock/doctype/serial_no/serial_no.py
+++ b/stock/doctype/serial_no/serial_no.py
@@ -16,39 +16,19 @@
 		self.doc = doc
 		self.doclist = doclist
 
-
-# ********************************* validate warranty / amc status ***************************************
-
-	# --------------------
-	# validate amc status
-	# --------------------
 	def validate_amc_status(self):
-		if self.doc.amc_expiry_date and getdate(self.doc.amc_expiry_date) >= datetime.date.today() and self.doc.maintenance_status == 'Out of AMC':
-			msgprint("AMC expiry date and maintenance status mismatch. Please verify")
-			raise Exception
-		elif (not self.doc.amc_expiry_date or getdate(self.doc.amc_expiry_date) < datetime.date.today()) and self.doc.maintenance_status == 'Under AMC':
-			msgprint("AMC expiry date and maintenance status mismatch. Please verify")
-			raise Exception
+		"""
+			validate amc status
+		"""
+		if (self.doc.maintenance_status == 'Out of AMC' and self.doc.amc_expiry_date and getdate(self.doc.amc_expiry_date) >= datetime.date.today()) or (self.doc.maintenance_status == 'Under AMC' and (not self.doc.amc_expiry_date or getdate(self.doc.amc_expiry_date) < datetime.date.today())):
+			msgprint("AMC expiry date and maintenance status mismatch. Please verify", raise_exception=1)
 
-
-	# -------------------------
-	# validate warranty status
-	# -------------------------
 	def validate_warranty_status(self):
-		if self.doc.warranty_expiry_date and getdate(self.doc.warranty_expiry_date) >= datetime.date.today() and self.doc.maintenance_status == 'Out of Warranty':
-			msgprint("Warranty expiry date and maintenance status mismatch. Please verify")
-			raise Exception
-		elif (not self.doc.warranty_expiry_date or getdate(self.doc.warranty_expiry_date) < datetime.date.today()) and self.doc.maintenance_status == 'Under Warranty':
-			msgprint("Warranty expiry date and maintenance status mismatch. Please verify")
-			raise Exception
-
-
-	# -------------------------------
-	# validate warranty / amc status
-	# -------------------------------
-	def validate_warranty_amc_status(self):
-		self.validate_warranty_status()
-		self.validate_amc_status()
+		"""
+			validate warranty status	
+		"""
+		if (self.doc.maintenance_status == 'Out of Warranty' and self.doc.warranty_expiry_date and getdate(self.doc.warranty_expiry_date) >= datetime.date.today()) or (self.doc.maintenance_status == 'Under Warranty' and (not self.doc.warranty_expiry_date or getdate(self.doc.warranty_expiry_date) < datetime.date.today())):
+			msgprint("Warranty expiry date and maintenance status mismatch. Please verify", raise_exception=1)
 
 
 	def validate_warehouse(self):
@@ -56,6 +36,9 @@
 			msgprint("Warehouse is mandatory if this Serial No is <b>In Store</b>", raise_exception=1)
 
 	def validate_item(self):
+		"""
+			Validate whether serial no is required for this item
+		"""
 		item = sql("select name, has_serial_no from tabItem where name = '%s'" % self.doc.item_code)
 		if not item:
 			msgprint("Item is not exists in the system", raise_exception=1)
@@ -67,7 +50,8 @@
 	# validate
 	# ---------
 	def validate(self):
-		self.validate_warranty_amc_status()
+		self.validate_warranty_status()
+		self.validate_amc_status()
 		self.validate_warehouse()
 		self.validate_item()
 
@@ -102,7 +86,7 @@
 	# on update
 	# ----------
 	def on_update(self):
-		if self.doc.warehouse and not sql("select name from `tabStock Ledger Entry` where serial_no = '%s'" % (self.doc.name)) and self.doc.status == 'In Store':
+		if self.doc.localname and self.doc.warehouse and self.doc.status == 'In Store' and not sql("select name from `tabStock Ledger Entry` where serial_no = '%s' and ifnull(is_cancelled, 'No') = 'No'" % (self.doc.name)):
 			self.make_stock_ledger_entry(update_stock = 1)
 
 
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index 47f0394..024bd1f 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -355,6 +355,9 @@
 	# ----------------------------------
 	def update_serial_no(self, is_submit):
 		sl_obj = get_obj('Stock Ledger')
+		if is_submit:
+			sl_obj.validate_serial_no_warehouse(self, 'mtn_details')
+		
 		for d in getlist(self.doclist, 'mtn_details'):
 			if d.serial_no:
 				serial_nos = sl_obj.get_sr_no_list(d.serial_no)
@@ -363,7 +366,7 @@
 					if d.s_warehouse:
 						sl_obj.update_serial_delivery_details(self, d, serial_no, is_submit)
 					if d.t_warehouse:
-						sl_obj.update_serial_purchase_details(self, d, serial_no, is_submit, (self.doc.purpose in ['Material Transfer', 'Sales Return']) and 1 or 0)
+						sl_obj.update_serial_purchase_details(self, d, serial_no, is_submit, self.doc.purpose)
 					
 					if self.doc.purpose == 'Purchase Return':
 						delete_doc("Serial No", serial_no)
diff --git a/stock/doctype/stock_ledger/stock_ledger.py b/stock/doctype/stock_ledger/stock_ledger.py
index 5188e08..dca9754 100644
--- a/stock/doctype/stock_ledger/stock_ledger.py
+++ b/stock/doctype/stock_ledger/stock_ledger.py
@@ -57,11 +57,11 @@
 					s = s.strip()
 					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)
+						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)
-					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)
+						msgprint("Warehouse not mentioned in the Serial No <b>%s</b>" % s, raise_exception = 1)
+					elif (d.warehouse and sr_war[0][0] != d.warehouse) or (d.s_warehouse and sr_war[0][0] != d.s_warehouse):
+						msgprint("Serial No : %s for Item : %s doesn't exists in Warehouse : %s" % (s, d.item_code, d.warehouse or d.s_warehouse), raise_exception = 1)
 
 
 	# ------------------------------------
@@ -119,10 +119,10 @@
 	# ----------------------------------
 	# update serial no purchase details
 	# ----------------------------------
-	def update_serial_purchase_details(self, obj, d, serial_no, is_submit, is_transfer = 0):
+	def update_serial_purchase_details(self, obj, d, serial_no, is_submit, purpose = ''):
 		exists = sql("select name, status, docstatus from `tabSerial No` where name = '%s'" % (serial_no))
 		if is_submit:
-			if exists and exists[0][2] != 2 and not is_transfer:
+			if exists and exists[0][2] != 2 and purpose not in ['Material Transfer', 'Sales Return']:
 				msgprint("Serial No: %s already %s" % (serial_no, exists and exists[0][1]), raise_exception = 1)
 			elif exists:
 				s = Document('Serial No', exists and exists[0][0])
@@ -133,8 +133,10 @@
 		else:
 			if exists and exists[0][1] == 'Delivered' and exists[0][2] != 2:
 				msgprint("Serial No: %s is already delivered, you can not cancel the document." % serial_no, raise_exception=1)
+			elif purpose in ['Material Transfer', 'Sales Return']:
+				sql("update `tabSerial No` set status = '%s', purchase_document_type = '', purchase_document_no = '', warehouse = '%s' where name = '%s'" % (purpose == 'Material Transfer' and 'In Store' or 'Delivered', d.s_warehouse, serial_no))				
 			else:
-				sql("update `tabSerial No` set docstatus = '%s', status = '%s', purchase_document_type = '', purchase_document_no = '', purchase_date = '', purchase_rate = '', supplier = null, supplier_name = '', supplier_address = '', warehouse = null where name = '%s'" % (not is_transfer and 2 or 0, is_transfer and 'In Store' or 'Not in Use', serial_no))
+				sql("update `tabSerial No` set docstatus = 2, status = 'Not in Use', purchase_document_type = '', purchase_document_no = '', purchase_date = '', purchase_rate = '', supplier = null, supplier_name = '', supplier_address = '', warehouse = '' where name = '%s'" % serial_no)
 
 
 	# -------------------------------
@@ -233,6 +235,7 @@
 				sle.fields['warehouse_type'] = get_value('Warehouse' , args[k], 'warehouse_type')
 			sle.fields[k] = args[k]
 		sle_obj = get_obj(doc=sle)
+		
 		# validate
 		sle_obj.validate()
 		sle.save(new = 1)
diff --git a/support/doctype/support_ticket/__init__.py b/support/doctype/support_ticket/__init__.py
index 9379280..23c4059 100644
--- a/support/doctype/support_ticket/__init__.py
+++ b/support/doctype/support_ticket/__init__.py
@@ -61,15 +61,15 @@
 		d.status = 'Open'
 		try:
 			d.save(1)
+			# update feed
+			update_feed(d)
+
+			# send auto reply
+			self.send_auto_reply(d)
+
 		except:
 			d.description = 'Unable to extract message'
 			d.save(1)
-
-		# update feed
-		update_feed(d)
-		
-		# send auto reply
-		self.send_auto_reply(d)
 		
 	def send_auto_reply(self, d):
 		"""